// Package tools serves the archive's read queries as MCP tools over the // streamable HTTP transport, at /mcp. It does no auth: the deployment // puts each view behind its own mcp-sidecar, so the view comes only from // the address a request reaches. package tools import ( "context" "encoding/json" "errors" "fmt" "log/slog" "net/http" "reflect" "time" "github.com/google/jsonschema-go/jsonschema" "github.com/modelcontextprotocol/go-sdk/mcp" "tangled.org/guid.foo/midden/archive" ) const instructions = `midden is the archive of a person's agent sessions: every Claude Code transcript from their machines and from agent Jobs. Use it to find what was said and done in an earlier session. To find what was said about a subject, call search with a few words of it, and since and until for the time, such as since "2026-10-09" for a week before the 16th. Each match names its session and has a From cursor. To read the conversation around a match, call read_session with the match's SessionID, and its From as after. To find a session by its time, host, or repository, call list_sessions. Every tool returns one page. When Next is not empty, call the same tool again with the same arguments and Next as after for the next page. Times are RFC 3339 in UTC, such as "2026-10-16T01:18:33Z".` const timeHelp = `RFC 3339, such as "2026-10-16T01:18:33Z", or a date, such as "2026-10-16", for midnight UTC at its start` // SessionsInput is the input of list_sessions. type SessionsInput struct { Since string `json:"since,omitempty" jsonschema:"list sessions with an entry at or after this time: RFC 3339, such as 2026-10-16T01:18:33Z, or a date, such as 2026-10-16, for midnight UTC at its start"` Until string `json:"until,omitempty" jsonschema:"list sessions with an entry before this time: RFC 3339, such as 2026-10-16T01:18:33Z, or a date, such as 2026-10-16, for midnight UTC at its start"` Host string `json:"host,omitempty" jsonschema:"list sessions with an entry from this host, such as laptop or agent-0"` Username string `json:"username,omitempty" jsonschema:"list sessions with an entry from this user, the Authentik user that shipped it"` Harness string `json:"harness,omitempty" jsonschema:"list sessions with an entry from this harness, such as claude-code"` Limit int `json:"limit,omitempty" jsonschema:"the most sessions to return: 50 when left out, and at most 500"` After string `json:"after,omitempty" jsonschema:"the Next of the page before this one, with the other arguments the same; leave it out for the first page"` } // ConversationInput is the input of read_session. type ConversationInput struct { Session string `json:"session" jsonschema:"the session's ID, as a Session's ID or a Match's SessionID"` Limit int `json:"limit,omitempty" jsonschema:"the most entries to return: 100 when left out, and at most 1000"` After string `json:"after,omitempty" jsonschema:"the Next of the page before this one, or a search Match's From to start at that match's entry; leave it out to start at the session's first entry"` } // SearchInput is the input of search. type SearchInput struct { Query string `json:"query" jsonschema:"the words to find: every word must match, \"a phrase\" matches the words in order, the word or between two words matches either one, and -word leaves out entries with that word; words match after English stemming, so deploys finds deployed"` Since string `json:"since,omitempty" jsonschema:"find entries at or after this time: RFC 3339, such as 2026-10-16T01:18:33Z, or a date, such as 2026-10-16, for midnight UTC at its start"` Until string `json:"until,omitempty" jsonschema:"find entries before this time: RFC 3339, such as 2026-10-16T01:18:33Z, or a date, such as 2026-10-16, for midnight UTC at its start"` Host string `json:"host,omitempty" jsonschema:"find entries from this host, such as laptop or agent-0"` Username string `json:"username,omitempty" jsonschema:"find entries from this user, the Authentik user that shipped it"` Harness string `json:"harness,omitempty" jsonschema:"find entries from this harness, such as claude-code"` Limit int `json:"limit,omitempty" jsonschema:"the most matches to return: 20 when left out, and at most 200"` After string `json:"after,omitempty" jsonschema:"the Next of the page before this one, with the other arguments the same; leave it out for the first page"` } var listSessions = &mcp.Tool{ Name: "list_sessions", Title: "List sessions", Description: `Lists the archive's sessions, newest first by their last entry, one page at a time. Each filter left out selects every session, and a filter on time keeps a session whole: its First, Last, and Entries count all its entries. Each Session has its ID, the times of its First and Last entries, the Username, Host, and Harness of its first entry, the Cwd and GitBranch it worked in, the FirstPrompt that a person wrote, and its number of Entries. Read one with read_session and its ID. When Next is not empty, call again with Next as after for the next page.`, Annotations: readOnly("List sessions"), } var readSession = &mcp.Tool{ Name: "read_session", Title: "Read a session", Description: `Reads one session's conversation in order, one page of entries at a time. Each Entry has its Time, its Type, such as user, assistant, summary, or system, Sidechain for a subagent's entry, Meta for an entry that the harness added, and its Parts. A Part's Kind is prompt for the user's text, text for the assistant's text, tool_use for a tool call with its Tool and Input, tool_result for a tool's result with the ToolUseID of its call, other for thinking, images, and the like, or unread for what midden could not parse. A tool result's Text is a short form of at most 10 lines and 2000 bytes, and Truncated, Bytes, and Lines say how long the whole is. A session that the archive does not have reads as no entries. When Next is not empty, call again with Next as after for the next page.`, Annotations: readOnly("Read a session"), } var search = &mcp.Tool{ Name: "search", Title: "Search transcripts", Description: `Finds the parts of transcript entries whose text matches the query: the user's prompts, the assistant's text, tool calls by the string values of their input, and tool results. Matches come newest first, one page at a time. Each Match has the SessionID it came from, its Time, the Kind of the part that matched, the Tool for a tool call, and a Snippet with each matched word between ** and **. To read the conversation from a match on, call read_session with session set to its SessionID and after set to its From. When Next is not empty, call again with Next as after for the next page.`, Annotations: readOnly("Search transcripts"), } func readOnly(title string) *mcp.ToolAnnotations { closed := false return &mcp.ToolAnnotations{Title: title, ReadOnlyHint: true, OpenWorldHint: &closed} } // New returns the handler of the archive's MCP tools in the view, at // /mcp. func New(a *archive.Archive, view archive.View, version string, m *Metrics, log *slog.Logger) http.Handler { server := mcp.NewServer(&mcp.Implementation{Name: "midden", Version: version}, &mcp.ServerOptions{Instructions: instructions, Logger: log}) mcp.AddTool(server, withOutput[archive.SessionPage](listSessions), observed(m, listSessions, view, func(ctx context.Context, _ *mcp.CallToolRequest, in SessionsInput) (*mcp.CallToolResult, archive.SessionPage, error) { filter := archive.SessionFilter{Host: in.Host, Username: in.Username, Harness: in.Harness, Limit: in.Limit, After: in.After} if err := times(in.Since, in.Until, &filter.Since, &filter.Until); err != nil { return nil, archive.SessionPage{}, err } page, err := a.Sessions(ctx, view, filter) if page.Sessions == nil { page.Sessions = []archive.Session{} } return nil, page, explain(err) })) mcp.AddTool(server, withOutput[archive.ConversationPage](readSession), observed(m, readSession, view, func(ctx context.Context, _ *mcp.CallToolRequest, in ConversationInput) (*mcp.CallToolResult, archive.ConversationPage, error) { page, err := a.Conversation(ctx, view, in.Session, archive.ConversationFilter{Limit: in.Limit, After: in.After}) if page.Entries == nil { page.Entries = []archive.Entry{} } return nil, page, explain(err) })) mcp.AddTool(server, withOutput[archive.SearchPage](search), observed(m, search, view, func(ctx context.Context, _ *mcp.CallToolRequest, in SearchInput) (*mcp.CallToolResult, archive.SearchPage, error) { filter := archive.SearchFilter{Query: in.Query, Host: in.Host, Username: in.Username, Harness: in.Harness, Limit: in.Limit, After: in.After} if err := times(in.Since, in.Until, &filter.Since, &filter.Until); err != nil { return nil, archive.SearchPage{}, err } page, err := a.Search(ctx, view, filter) if page.Matches == nil { page.Matches = []archive.Match{} } return nil, page, explain(err) })) // Each request stands alone, so a restart of midden loses no session // that the sidecar holds. handler := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return server }, &mcp.StreamableHTTPOptions{Stateless: true, Logger: log}) mux := http.NewServeMux() mux.Handle("/mcp", handler) return mux } // withOutput sets the tool's output schema from the archive's page type. // A tool call's Input is any JSON, where the inferred schema would make // json.RawMessage a list of bytes. func withOutput[Out any](t *mcp.Tool) *mcp.Tool { schema, err := jsonschema.For[Out](&jsonschema.ForOptions{ TypeSchemas: map[reflect.Type]*jsonschema.Schema{ reflect.TypeFor[json.RawMessage](): {}, }, }) if err != nil { panic(err) } copied := *t copied.OutputSchema = schema return &copied } // times reads since and until into the filter's times. func times(since, until string, s, u *time.Time) error { var err error if *s, err = parseTime("since", since); err != nil { return err } *u, err = parseTime("until", until) return err } func parseTime(name, value string) (time.Time, error) { if value == "" { return time.Time{}, nil } if t, err := time.Parse(time.RFC3339, value); err == nil { return t, nil } if t, err := time.Parse(time.DateOnly, value); err == nil { return t, nil } return time.Time{}, &badTime{name: name, value: value} } // badTime is a since or until that does not parse. It is a type, so a // call's outcome tells it apart from midden's own errors. type badTime struct{ name, value string } func (e *badTime) Error() string { return fmt.Sprintf("%s is %q, and it must be %s", e.name, e.value, timeHelp) } // explain says what a caller can do about the archive's errors. func explain(err error) error { switch { case errors.Is(err, archive.ErrBadCursor): return fmt.Errorf("%w: pass after only as the Next of a page, or a Match's From for read_session, with the same other arguments", err) case errors.Is(err, archive.ErrEmptyQuery): return fmt.Errorf("%w: give at least one word that is not a stop word such as \"the\"", err) } return err }