_meouwu on X: a memory added by hand in several lines showed as one line with its breaks gone; it should keep its format and, folded, show the first line and an ellipsis. Cause: the store never lost the breaks. A memory file's body is m.Text as written (encode/apply trim only the ends). They were lost where it was shown: the Library row clamped the name to two lines with white-space normal, the digest given to agents went through oneLine (strings.Fields), and so did memory_search / memory_list in the memory MCP. Now: - Library: a folded row and a suggestion show firstLine(text) (first line, " …" when more follow); an open row shows the whole text pre-wrap. The editor already kept "\n". - Digest and memory MCP: memory.Indented keeps each line, the lines after the first indented two spaces so the memory stays one list item. - Dream and distill listings stay one line on purpose: the model's reply is read line by line, and a user's memory is Fixed, never rewritten by them. Written in docs/subsystems/memory.md. Memories saved before: their files already hold the breaks, so after updating they show, edit and reach agents in their own lines. Nothing to redo, no migration. Run at 3fabaf8f2 (on origin/mainb332ef7ef, the pushed head), f6452d777 (on1622484a8) and ee84e288a (on54117164c), on the WSL VM magpie-desktop: mote and mica were over their cores with other sessions' suites for ~2h. - go vet -tags gtk3 ./... ok; gofmt -l clean. - go test -tags gtk3 -count=1 -timeout 45m ./... at ee84e288a: 101 ok, 2 FAIL, both red at origin/main2416beed6on the same VM: internal/gui TestClipboardReadBack (#7074, #7073), internal/usage TestRequestStateKeptAcrossACatalogFetchedAgain (#6572). - Whole GUI suite (concurrency 8): 1355 of 29368 red in 221 files under load. Those 221 again at concurrency 3: 71 red; 66 of them red at base54117164ctoo. Of the other 5, 3 pass alone; codex-auto-reset-settings (#6108) and copilot-ghe (#1949) are red at base alone too (2 of 3 and 3 of 3 rounds), commented there. - After the rebase (f6452d777): internal/memory, internal/memdistill and -run "Memory|Budget|I18n" in gateway, gui, library ok. All 84 library-*.test.cjs: 1920 of 1950 pass; each red file alone, beside1622484a8: commands-import, group-steady, mcp-copy-config, mcp-off-fold, open-again and all are red at base too (#7097; all 3 of 3 at base); memory-suggest, mcp-json and bili pass alone. - At 3fabaf8f2 (b332ef7efbrought flying_crp's digest header and memory_save note; conflicts were only both sides adding tests and doc text): go vet memory, gateway, memdistill; go test memory, memdistill, access, and -run "Memory|Budget|I18n|Digest" in gateway, gui, library ok; library-memory*.test.cjs 112 of 112. - library-memory-lines.test.cjs: 5 langs x 980/420 x chromium/webkit. Broken by hand (old code, new tests): TestMultiLineMemoryKeepsItsLines red at the digest step only (save, edit and the file passed: the store kept the breaks), TestIndented and TestMemorySearchKeepsTheLines red, library-memory-lines red ("Release steps: …" expected). Not tried: a macOS run (mote, mica busy), Windows, the real app.
815 lines
30 KiB
Go
815 lines
30 KiB
Go
package gateway
|
||
|
||
import (
|
||
"encoding/json"
|
||
"fmt"
|
||
"maps"
|
||
"net/http"
|
||
"net/url"
|
||
"os"
|
||
"path/filepath"
|
||
"slices"
|
||
"strings"
|
||
"sync"
|
||
"time"
|
||
|
||
"github.com/yetone/magpie/internal/access"
|
||
// search by meaning, when switched on (memory.Semantic)
|
||
_ "github.com/yetone/magpie/internal/memembed"
|
||
"github.com/yetone/magpie/internal/memory"
|
||
"github.com/yetone/magpie/internal/usage"
|
||
)
|
||
|
||
// magpie's memory (internal/memory) is an MCP server every agent can mount,
|
||
// so what one agent learns of the user, another knows: memory_search,
|
||
// memory_save, memory_forget and memory_context (who the caller is taken
|
||
// for), Streamable HTTP at MemoryMCPPath, served
|
||
// as SearchMCPPath is (serveMCP), to the agents on this computer alone.
|
||
// The Library gives it as `magpie mcp memory`, which passes each message on with the folder the
|
||
// agent started it in (MemoryCwdHeader) and the client's name from its
|
||
// initialize (MemoryClientHeader); behind the hub, the call's _meta names
|
||
// the agent's roots and client (HubRootsMeta, HubClientMeta).
|
||
//
|
||
// A memory is kept for everyone (global), for one project (the git
|
||
// repository the agent works in, by its remote, so every clone and
|
||
// worktree shares it) or for one agent. Searches look in the global ones,
|
||
// the agent's own and the project's.
|
||
|
||
// MemoryMCPPath is where the memory MCP server is served.
|
||
const MemoryMCPPath = "/mcp/magpie/memory"
|
||
|
||
// MemoryCwdHeader and MemoryClientHeader are the folder `magpie mcp
|
||
// memory` was started in and the client name the agent gave at initialize.
|
||
const (
|
||
MemoryCwdHeader = "X-Magpie-Cwd"
|
||
MemoryClientHeader = "X-Magpie-Mcp-Client"
|
||
)
|
||
|
||
const (
|
||
memorySearchTool = "memory_search"
|
||
memorySaveTool = "memory_save"
|
||
memoryForgetTool = "memory_forget"
|
||
memoryContextTool = "memory_context"
|
||
)
|
||
|
||
const memoryServerName = "magpie-memory"
|
||
|
||
func (s *Server) memoryMCP(w http.ResponseWriter, r *http.Request) {
|
||
if !memoryReaches(r) {
|
||
http.Error(w, "magpie's memory MCP server answers the agents on this computer, and another computer's only while magpie is shared and by a gateway key let use Magpie Memory (the key's ··· › Advanced in magpie's gateway keys, or `magpie gateway-key memory <id> on`); never a web page", http.StatusForbidden)
|
||
return
|
||
}
|
||
serveMCP(w, r, "magpie's memory", memoryServerName, 1<<20, s.memoryMCPCall)
|
||
}
|
||
|
||
// memoryReaches is whether r may read and write magpie's memory: what is
|
||
// known about this computer's user, and what goes into every agent's
|
||
// instructions here (the digest). An agent on this computer may; another
|
||
// computer's only while magpie is shared, by a gateway key the user let
|
||
// use it themselves (access.Key.Memory, Niapyaya on X: an agent on a
|
||
// remote machine saving to it), as the hub gives it (HubVisitor's
|
||
// Memory). Any other key, which may be a friend's and uses every MCP
|
||
// server unless held to some, and a web page, one Settings lists and that
|
||
// sends a key included, are turned away. From elsewhere a page is told by
|
||
// hubFromPage, not fromBrowser, whose Sec-Fetch-Mode Node's fetch sends
|
||
// too (#5522): the MCP SDK's own transport, which a remote agent uses.
|
||
func memoryReaches(r *http.Request) bool {
|
||
if local(r) {
|
||
return !fromBrowser(r)
|
||
}
|
||
return sharedWith(r) && access.Caller(r.Context()).Memory && !hubFromPage(r)
|
||
}
|
||
|
||
var memoryKinds = strings.Join(memory.Kinds, ", ")
|
||
|
||
func memoryMCPTools() []any {
|
||
return []any{
|
||
map[string]any{
|
||
"name": memorySearchTool,
|
||
"title": "Search memory",
|
||
"description": "Searches what is remembered from earlier conversations with the user, in any agent: their preferences, rules, facts about them and their projects, how things are done. " +
|
||
"Search before asking the user something they may have told you before, and when starting work in a project. With no query, lists the memories.",
|
||
"inputSchema": map[string]any{
|
||
"type": "object",
|
||
"properties": map[string]any{
|
||
"query": map[string]any{"type": "string", "description": "What to look for, in a few words"},
|
||
"scope": map[string]any{"type": "string", "enum": []string{"all", "project", "global"}, "description": "project: this project's memories; global: those for every project; all (default): both, and yours"},
|
||
"kind": map[string]any{"type": "string", "description": "Only memories of this kind: " + memoryKinds},
|
||
"project": map[string]any{"type": "string", "description": "Another project than the one you work in: its folder on this computer (absolute, or relative to yours), or its key as memory_context shows it (github.com/owner/repo)"},
|
||
"tags": map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": "Only memories with every one of these tags"},
|
||
"limit": map[string]any{"type": "integer", "minimum": 1, "maximum": 50, "default": 10},
|
||
},
|
||
},
|
||
"annotations": map[string]any{"readOnlyHint": true, "openWorldHint": false},
|
||
},
|
||
map[string]any{
|
||
"name": memorySaveTool,
|
||
"title": "Save memory",
|
||
"description": "Remembers one thing for later conversations, in every agent: what the user asks you to remember, a preference or rule they state, a correction they make, a fact about them or the project that will still hold next time. " +
|
||
"One fact per memory, written so it reads on its own. Don't save what is in the code or its history, a task's progress, or secrets. " +
|
||
"Memory is for what holds for the user across projects. A rule, convention or fact of one project belongs in that project's own instruction files or docs (AGENTS.md and the like) when it keeps them: offer to write it there instead, and don't save what they already say or what disagrees with them. " +
|
||
"Saving what is already remembered merges into it; with id, changes that memory.",
|
||
"inputSchema": map[string]any{
|
||
"type": "object",
|
||
"properties": map[string]any{
|
||
"text": map[string]any{"type": "string", "description": "The memory, one self-contained fact or instruction"},
|
||
"kind": map[string]any{"type": "string", "enum": memory.Kinds, "description": "profile: who the user is; preference: how they like things; rule: what must or must not be done; reference: where something is; fact: something true of a project; procedure: how something is done; episode: a decision or event worth recalling"},
|
||
"scope": map[string]any{"type": "string", "enum": []string{"project", "global", "agent"}, "description": "project: holds only in this project (default for facts, references, procedures and episodes); global: holds everywhere (default for profile, preference and rule); agent: only for you"},
|
||
"tags": map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": "A few words to find it by (a topic, a tool, a language)"},
|
||
"why": map[string]any{"type": "string", "description": "Why it holds, when the user said, so it can be judged later"},
|
||
"id": map[string]any{"type": "string", "description": "A memory's id, to change that memory rather than save a new one"},
|
||
"project": map[string]any{"type": "string", "description": "Another project than the one you work in: its folder on this computer (absolute, or relative to yours), or its key as memory_context shows it (github.com/owner/repo)"},
|
||
},
|
||
"required": []string{"text"},
|
||
},
|
||
"annotations": map[string]any{"readOnlyHint": false, "destructiveHint": false, "idempotentHint": true, "openWorldHint": false},
|
||
},
|
||
map[string]any{
|
||
"name": memoryForgetTool,
|
||
"title": "Forget memory",
|
||
"description": "Sets a memory aside when the user says it is wrong or no longer holds. It is kept for the user to look at, but no longer searched or given to agents.",
|
||
"inputSchema": map[string]any{
|
||
"type": "object",
|
||
"properties": map[string]any{"id": map[string]any{"type": "string", "description": "The memory's id, from memory_search"}},
|
||
"required": []string{"id"},
|
||
},
|
||
"annotations": map[string]any{"readOnlyHint": false, "destructiveHint": true, "idempotentHint": true, "openWorldHint": false},
|
||
},
|
||
map[string]any{
|
||
"name": memoryContextTool,
|
||
"title": "Memory context",
|
||
"description": "Says who the memory server takes you for: the agent \"only for you\" is kept for, the project \"this project\" means, how each was found, and where a search looks. Check it before saving or moving memories for an agent or a project.",
|
||
"inputSchema": map[string]any{
|
||
"type": "object",
|
||
"properties": map[string]any{"project": map[string]any{"type": "string", "description": "A project to check instead of the one you work in, as memory_search and memory_save take it"}},
|
||
},
|
||
"annotations": map[string]any{"readOnlyHint": true, "openWorldHint": false},
|
||
},
|
||
}
|
||
}
|
||
|
||
// memoryMCPCall answers one request: its result, or its JSON-RPC error.
|
||
func (s *Server) memoryMCPCall(r *http.Request, m mcpMessage) (any, map[string]any) {
|
||
switch m.Method {
|
||
case "initialize":
|
||
rememberMemoryClient(r, m)
|
||
return map[string]any{
|
||
"protocolVersion": mcpVersion(m),
|
||
"capabilities": map[string]any{"tools": map[string]any{}},
|
||
"serverInfo": map[string]any{"name": memoryServerName, "title": "Magpie Memory", "version": Version},
|
||
"instructions": "Memory shared by every agent the user works with. Search it before asking the user something they may have said before; save what they ask to be remembered, and preferences, rules and corrections they state; forget what they say no longer holds.",
|
||
}, nil
|
||
case "ping":
|
||
return map[string]any{}, nil
|
||
case "tools/list":
|
||
return map[string]any{"tools": memoryMCPTools()}, nil
|
||
case "tools/call":
|
||
var p struct {
|
||
Name string `json:"name"`
|
||
Arguments json.RawMessage `json:"arguments"`
|
||
Meta json.RawMessage `json:"_meta"`
|
||
}
|
||
if err := json.Unmarshal(m.Params, &p); err != nil {
|
||
return nil, map[string]any{"code": -32602, "message": "invalid params: " + err.Error()}
|
||
}
|
||
var a memoryArgs
|
||
if len(p.Arguments) > 0 {
|
||
if err := json.Unmarshal(p.Arguments, &a); err != nil {
|
||
return toolResult("the arguments don't read: "+err.Error(), true), nil
|
||
}
|
||
}
|
||
c := memoryCallerOf(r, p.Meta)
|
||
var said string
|
||
var err error
|
||
switch p.Name {
|
||
case memorySearchTool, memorySaveTool, memoryContextTool:
|
||
if c, err = c.inProject(a.Project); err != nil {
|
||
return toolResult(err.Error(), true), nil
|
||
}
|
||
}
|
||
switch p.Name {
|
||
case memorySearchTool:
|
||
said, err = memorySearch(c, a)
|
||
case memorySaveTool:
|
||
said, err = memorySave(c, a)
|
||
case memoryForgetTool:
|
||
said, err = memoryForget(a)
|
||
case memoryContextTool:
|
||
said, ctx := memoryContext(c)
|
||
res := toolResult(said, false)
|
||
res["structuredContent"] = ctx
|
||
return res, nil
|
||
default:
|
||
return nil, map[string]any{"code": -32602, "message": "unknown tool " + p.Name + ": this server has " + memorySearchTool + ", " + memorySaveTool + ", " + memoryForgetTool + " and " + memoryContextTool}
|
||
}
|
||
if err != nil {
|
||
return toolResult(err.Error(), true), nil
|
||
}
|
||
return toolResult(said, false), nil
|
||
}
|
||
return nil, map[string]any{"code": -32601, "message": "method not found: " + m.Method}
|
||
}
|
||
|
||
type memoryArgs struct {
|
||
Query string `json:"query"`
|
||
Text string `json:"text"`
|
||
Kind string `json:"kind"`
|
||
Scope string `json:"scope"`
|
||
Tags flexTags `json:"tags"`
|
||
Why string `json:"why"`
|
||
ID string `json:"id"`
|
||
Limit flexCount `json:"limit"`
|
||
// Project is another project than the caller's: a folder, or a
|
||
// project's key (memoryCaller.inProject)
|
||
Project string `json:"project"`
|
||
}
|
||
|
||
// flexTags are tags as a model may write them: a list, or one string of
|
||
// them split at commas.
|
||
type flexTags []string
|
||
|
||
func (t *flexTags) UnmarshalJSON(b []byte) error {
|
||
var l []string
|
||
if json.Unmarshal(b, &l) == nil {
|
||
*t = l
|
||
return nil
|
||
}
|
||
var s string
|
||
if err := json.Unmarshal(b, &s); err != nil {
|
||
return nil // anything else is no tags
|
||
}
|
||
*t = strings.FieldsFunc(s, func(r rune) bool { return r == ',' || r == ',' })
|
||
return nil
|
||
}
|
||
|
||
// flexCount is a count as a model may write it: a number, or one in a
|
||
// string; 0 for anything else.
|
||
type flexCount int
|
||
|
||
func (c *flexCount) UnmarshalJSON(b []byte) error {
|
||
if n := searchCountArg(b); n != nil {
|
||
*c = flexCount(*n)
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// memoryCaller is who calls: the agent, by magpie's id for it ("" when
|
||
// it can't be told), and the project it works in (nil when none).
|
||
type memoryCaller struct {
|
||
agent string
|
||
project *memory.Project
|
||
dir string
|
||
// how the agent and the project were found, for memory_context
|
||
agentFrom, projectFrom string
|
||
// asked is the project argument the call named ("" for none)
|
||
asked bool
|
||
}
|
||
|
||
// memoryCallerOf is the caller of r: the agent its key or User-Agent
|
||
// names, else the client the hub's _meta or `magpie mcp memory` names;
|
||
// the project of the folder the hub's _meta names, else the folder `magpie
|
||
// mcp memory` runs in, else the one the agent says when asked (roots/list)
|
||
// or the Codex turn names. An agent on another computer has no folder
|
||
// here.
|
||
func memoryCallerOf(r *http.Request, rawMeta json.RawMessage) memoryCaller {
|
||
var meta hubCallMeta
|
||
var extra struct {
|
||
Roots *[]string `json:"magpie/roots"`
|
||
Client string `json:"magpie/client"`
|
||
}
|
||
if len(rawMeta) > 0 {
|
||
json.Unmarshal(rawMeta, &meta)
|
||
json.Unmarshal(rawMeta, &extra)
|
||
}
|
||
// the client the hub or `magpie mcp memory` names first: their own
|
||
// requests go under magpie's key and a Go User-Agent
|
||
c := memoryCaller{}
|
||
for i, name := range []string{extra.Client, r.Header.Get(MemoryClientHeader)} {
|
||
if c.agent == "" && strings.TrimSpace(name) != "" {
|
||
c.agent = memoryAgent(usage.AgentOf(name))
|
||
c.agentFrom = []string{"the client the MCP router names", "the client named at magpie mcp memory's initialize"}[i]
|
||
}
|
||
}
|
||
if c.agent == "" {
|
||
if c.agent = memoryAgent(callerOf(r).agent); c.agent != "" {
|
||
c.agentFrom = "the request's key or User-Agent"
|
||
}
|
||
}
|
||
if c.agent == "" {
|
||
// the client the session's initialize named (#6392): Codex's
|
||
// HTTP client says nothing of itself but there
|
||
if c.agent = memoryClients.of(r.Header.Get("Mcp-Session-Id")); c.agent != "" {
|
||
c.agentFrom = "the client named at this session's initialize"
|
||
}
|
||
}
|
||
if !local(r) {
|
||
return c
|
||
}
|
||
var dirs []string
|
||
var from string
|
||
if extra.Roots != nil {
|
||
// behind the hub: its roots, none when the agent has none
|
||
dirs, from = rootDirs(*extra.Roots), "the roots the MCP router names"
|
||
} else if d := strings.TrimSpace(r.Header.Get(MemoryCwdHeader)); d != "" {
|
||
dirs, from = []string{d}, "the folder the client runs in"
|
||
} else {
|
||
dirs, from = rootDirs(hubRoots(r, meta)), "the agent's roots or its Codex thread"
|
||
}
|
||
for _, d := range dirs {
|
||
if p := memory.ProjectOf(d); p != nil {
|
||
c.project, c.dir, c.projectFrom = p, d, from
|
||
break
|
||
}
|
||
}
|
||
return c
|
||
}
|
||
|
||
// memoryAgent is id when it names an agent: not magpie itself, nor an
|
||
// HTTP library (curl, Go's), which says nothing of which agent; else "".
|
||
func memoryAgent(id string) string {
|
||
l := strings.ToLower(strings.TrimSpace(id))
|
||
if strings.HasPrefix(l, "codex") {
|
||
// codex-mcp-client, codex-tui, codex_cli_rs: Codex, as `magpie
|
||
// mcp memory` and the sessions know it
|
||
return "codex"
|
||
}
|
||
if l == "" || l == "magpie" || l == "other" || l == "go-http-client" || usage.IsLibrary(l) {
|
||
return ""
|
||
}
|
||
return id
|
||
}
|
||
|
||
// rootDirs are the folders of file URIs.
|
||
func rootDirs(uris []string) []string {
|
||
out := []string{}
|
||
for _, u := range uris {
|
||
p, err := url.Parse(u)
|
||
if err != nil || p.Scheme != "file" || p.Path == "" {
|
||
continue
|
||
}
|
||
d := filepath.FromSlash(p.Path)
|
||
if len(d) > 2 && d[0] == filepath.Separator && d[2] == ':' {
|
||
d = d[1:] // file:///C:/p is C:\p
|
||
}
|
||
out = append(out, d)
|
||
}
|
||
return out
|
||
}
|
||
|
||
// inProject is c in the project a call names (memoryArgs.Project): a
|
||
// folder on this computer, absolute or under the caller's own, or the key
|
||
// (or the one name) of a project memory knows. "" leaves c as it is.
|
||
// Behind the router or stdio the folder is the caller's, so a migration
|
||
// run from one project can keep memories for another, and say which.
|
||
func (c memoryCaller) inProject(arg string) (memoryCaller, error) {
|
||
arg = strings.TrimSpace(arg)
|
||
if arg == "" {
|
||
return c, nil
|
||
}
|
||
folder := func(d string) (memoryCaller, bool) {
|
||
st, err := os.Stat(d)
|
||
if err != nil || !st.IsDir() {
|
||
return c, false
|
||
}
|
||
p := memory.ProjectOf(d)
|
||
if p == nil {
|
||
return c, false
|
||
}
|
||
c.project, c.dir, c.projectFrom, c.asked = p, d, "the project argument (a folder)", true
|
||
return c, true
|
||
}
|
||
if filepath.IsAbs(arg) {
|
||
if out, ok := folder(filepath.Clean(arg)); ok {
|
||
return out, nil
|
||
}
|
||
return c, searchMCPError(fmt.Sprintf("project %q isn't a folder on this computer", arg))
|
||
}
|
||
_, known, err := memory.All()
|
||
if err != nil {
|
||
return c, fmt.Errorf("memory can't be read now: %v", err)
|
||
}
|
||
key := strings.TrimPrefix(arg, "project:")
|
||
var byName []*memory.Project
|
||
for k, p := range known {
|
||
if strings.EqualFold(k, key) {
|
||
byName = []*memory.Project{p}
|
||
break
|
||
}
|
||
if strings.EqualFold(p.Name, key) {
|
||
byName = append(byName, p)
|
||
}
|
||
}
|
||
if len(byName) == 1 {
|
||
p := byName[0]
|
||
c.project, c.dir, c.projectFrom, c.asked = &memory.Project{Key: p.Key, Name: p.Name, Roots: p.Roots}, "", "the project argument (a key)", true
|
||
if len(p.Roots) > 0 {
|
||
c.dir = p.Roots[len(p.Roots)-1]
|
||
}
|
||
return c, nil
|
||
}
|
||
if c.dir != "" {
|
||
if out, ok := folder(filepath.Join(c.dir, arg)); ok {
|
||
return out, nil
|
||
}
|
||
}
|
||
if len(byName) > 1 {
|
||
var keys []string
|
||
for _, p := range byName {
|
||
keys = append(keys, p.Key)
|
||
}
|
||
slices.Sort(keys)
|
||
return c, searchMCPError(fmt.Sprintf("project %q names %d projects: give one's key (%s)", arg, len(keys), strings.Join(keys, ", ")))
|
||
}
|
||
keys := slices.Sorted(maps.Keys(known))
|
||
if len(keys) > 10 {
|
||
keys = append(keys[:10], "…")
|
||
}
|
||
have := "none yet"
|
||
if len(keys) > 0 {
|
||
have = strings.Join(keys, ", ")
|
||
}
|
||
return c, searchMCPError(fmt.Sprintf("project %q is neither a folder here nor a project memory knows (it knows %s)", arg, have))
|
||
}
|
||
|
||
// memoryContext is who the server takes c for, and where its searches
|
||
// look: as text, and as an object for a script to check.
|
||
func memoryContext(c memoryCaller) (string, map[string]any) {
|
||
scopes, _ := c.scopes("")
|
||
ctx := map[string]any{"server": map[string]any{"name": memoryServerName, "version": Version}, "scopes": scopes}
|
||
var b strings.Builder
|
||
if c.agent != "" {
|
||
ctx["agent"] = map[string]any{"id": c.agent, "from": c.agentFrom}
|
||
fmt.Fprintf(&b, "Agent: %s (from %s); scope agent keeps memories for it alone.\n", c.agent, c.agentFrom)
|
||
} else {
|
||
ctx["agent"] = nil
|
||
b.WriteString("Agent: unknown. Nothing named the client: an MCP client names itself at initialize (clientInfo.name) on this session; until then scope agent can't be used.\n")
|
||
}
|
||
if c.project != nil {
|
||
p := map[string]any{"key": c.project.Key, "name": c.project.Name, "scope": memory.ScopeOf(c.project), "from": c.projectFrom}
|
||
if c.dir != "" {
|
||
p["folder"] = c.dir
|
||
}
|
||
ctx["project"] = p
|
||
fmt.Fprintf(&b, "Project: %s (%s), from %s", c.project.Key, c.project.Name, c.projectFrom)
|
||
if c.dir != "" {
|
||
fmt.Fprintf(&b, ", folder %s", c.dir)
|
||
}
|
||
b.WriteString("; scope project keeps memories there.\n")
|
||
} else {
|
||
ctx["project"] = nil
|
||
b.WriteString("Project: none. None of your folders is known here: give memory_search and memory_save a project (a folder, or a key), or run magpie mcp memory in the project's folder.\n")
|
||
}
|
||
fmt.Fprintf(&b, "A search with scope all looks in: %s.\nmagpie-memory %s", strings.Join(scopes, ", "), Version)
|
||
return b.String(), ctx
|
||
}
|
||
|
||
// whereSaid is where a search for c looked, the last line of its answer.
|
||
func (c memoryCaller) whereSaid(scopes []string) string {
|
||
var parts []string
|
||
for _, s := range scopes {
|
||
switch {
|
||
case s == memory.Global:
|
||
parts = append(parts, "everywhere")
|
||
case strings.HasPrefix(s, "project:"):
|
||
parts = append(parts, "project "+strings.TrimPrefix(s, "project:"))
|
||
case s == "agent:codex-mcp-client" && c.agent == "codex":
|
||
case strings.HasPrefix(s, "agent:"):
|
||
parts = append(parts, "agent "+strings.TrimPrefix(s, "agent:"))
|
||
}
|
||
}
|
||
return "(looked in: " + strings.Join(parts, ", ") + ")"
|
||
}
|
||
|
||
// scopes are the scopes a search for c looks in.
|
||
func (c memoryCaller) scopes(which string) ([]string, error) {
|
||
proj := memory.ScopeOf(c.project)
|
||
switch strings.ToLower(strings.TrimSpace(which)) {
|
||
case "", "all":
|
||
out := []string{memory.Global}
|
||
if proj != "" {
|
||
out = append(out, proj)
|
||
}
|
||
if c.agent != "" {
|
||
out = append(out, "agent:"+c.agent)
|
||
if c.agent == "codex" {
|
||
// kept under Codex's MCP client name before it was Codex
|
||
out = append(out, "agent:codex-mcp-client")
|
||
}
|
||
}
|
||
return out, nil
|
||
case "global":
|
||
if c.asked {
|
||
return nil, searchMCPError("a project goes with scope project or all, not global")
|
||
}
|
||
return []string{memory.Global}, nil
|
||
case "project":
|
||
if proj == "" {
|
||
return nil, memoryNoProject()
|
||
}
|
||
return []string{proj}, nil
|
||
}
|
||
return nil, fmt.Errorf("scope %q isn't all, project or global", which)
|
||
}
|
||
|
||
func memoryNoProject() error {
|
||
return searchMCPError("there is no project here: the folder you work in isn't known to the memory server. Use scope global, or work in a project folder")
|
||
}
|
||
|
||
func memorySearch(c memoryCaller, a memoryArgs) (string, error) {
|
||
scopes, err := c.scopes(a.Scope)
|
||
if err != nil {
|
||
return "", err
|
||
}
|
||
q := memory.Query{Text: a.Query, Scopes: scopes, Tags: a.Tags, Limit: min(max(int(a.Limit), 0), 50)}
|
||
if q.Limit == 0 {
|
||
q.Limit = 10
|
||
}
|
||
if k := strings.ToLower(strings.TrimSpace(a.Kind)); k != "" {
|
||
if !slices.Contains(memory.Kinds, k) {
|
||
return "", fmt.Errorf("kind %q isn't one of %s", a.Kind, memoryKinds)
|
||
}
|
||
q.Kinds = []string{k}
|
||
}
|
||
hits, err := memory.Search(q)
|
||
if err != nil {
|
||
return "", fmt.Errorf("memory can't be read now: %v", err)
|
||
}
|
||
if len(hits) == 0 {
|
||
if strings.TrimSpace(a.Query) == "" {
|
||
return "Nothing is remembered here yet. " + c.whereSaid(scopes), nil
|
||
}
|
||
return "Nothing remembered matches " + quotedQuery(a.Query) + ". " + c.whereSaid(scopes), nil
|
||
}
|
||
var b strings.Builder
|
||
for _, h := range hits {
|
||
b.WriteString(memoryLine(h.Memory, c))
|
||
b.WriteString("\n")
|
||
}
|
||
b.WriteString(c.whereSaid(scopes))
|
||
return b.String(), nil
|
||
}
|
||
|
||
// memoryLine is one memory as an agent reads it: its id, kind, where it
|
||
// holds, tags, text and why.
|
||
func memoryLine(m *memory.Memory, c memoryCaller) string {
|
||
where := "everywhere"
|
||
switch {
|
||
case strings.HasPrefix(m.Scope, "agent:"):
|
||
where = "only for you (" + strings.TrimPrefix(m.Scope, "agent:") + ")"
|
||
case strings.HasPrefix(m.Scope, "project:"):
|
||
where = "this project (" + strings.TrimPrefix(m.Scope, "project:") + ")"
|
||
if s := memory.ScopeOf(c.project); s != m.Scope {
|
||
where = "project " + strings.TrimPrefix(m.Scope, "project:")
|
||
}
|
||
}
|
||
l := fmt.Sprintf("[%s] %s, %s", m.ID, m.Kind, where)
|
||
if len(m.Tags) > 0 {
|
||
l += ", #" + strings.Join(m.Tags, " #")
|
||
}
|
||
if m.Pinned {
|
||
l += ", pinned"
|
||
}
|
||
l += ", " + memoryStamp(m.Updated) + ": " + memory.Indented(m.Text, " ")
|
||
if m.Why != "" {
|
||
l += " (why: " + strings.Join(strings.Fields(m.Why), " ") + ")"
|
||
}
|
||
return l
|
||
}
|
||
|
||
func quotedQuery(s string) string { b, _ := json.Marshal(strings.TrimSpace(s)); return string(b) }
|
||
|
||
func memorySave(c memoryCaller, a memoryArgs) (string, error) {
|
||
in := memory.Input{}
|
||
text := strings.TrimSpace(a.Text)
|
||
if text == "" && a.ID == "" {
|
||
return "", searchMCPError("memory_save needs the text to remember")
|
||
}
|
||
if text != "" {
|
||
in.Text = &text
|
||
}
|
||
kind := strings.ToLower(strings.TrimSpace(a.Kind))
|
||
if kind != "" {
|
||
in.Kind = &kind
|
||
}
|
||
if a.Tags != nil {
|
||
tags := []string(a.Tags)
|
||
in.Tags = &tags
|
||
}
|
||
if w := strings.TrimSpace(a.Why); w != "" {
|
||
in.Why = &w
|
||
}
|
||
which := strings.ToLower(strings.TrimSpace(a.Scope))
|
||
if c.asked {
|
||
// a project named is where the memory goes
|
||
if which == "" {
|
||
which = "project"
|
||
}
|
||
if which != "project" {
|
||
return "", searchMCPError("a project goes with scope project, not " + which)
|
||
}
|
||
}
|
||
if which == "" && a.ID == "" {
|
||
which = "global"
|
||
if c.project != nil && !slices.Contains([]string{"", memory.Profile, memory.Preference, memory.Rule}, kind) {
|
||
which = "project"
|
||
}
|
||
}
|
||
var scope string
|
||
switch which {
|
||
case "":
|
||
case "global":
|
||
scope = memory.Global
|
||
case "project":
|
||
if c.project == nil {
|
||
return "", memoryNoProject()
|
||
}
|
||
scope = memory.ScopeOf(c.project)
|
||
case "agent":
|
||
if c.agent == "" {
|
||
return "", searchMCPError("the memory server can't tell which agent you are, so it can't keep a memory for you alone: use scope global or project")
|
||
}
|
||
scope = "agent:" + c.agent
|
||
default:
|
||
return "", fmt.Errorf("scope %q isn't project, global or agent", a.Scope)
|
||
}
|
||
if scope != "" {
|
||
in.Scope = &scope
|
||
}
|
||
if id := strings.TrimSpace(a.ID); id != "" {
|
||
if scope != "" && scope == memory.ScopeOf(c.project) {
|
||
// its name and folders, for the Memory tab
|
||
if err := memory.NoteProject(c.project); err != nil {
|
||
return "", err
|
||
}
|
||
}
|
||
m, err := memory.Edit(id, in, false)
|
||
if err != nil {
|
||
return "", err
|
||
}
|
||
return "Changed: " + memoryLine(m, c), nil
|
||
}
|
||
if kind == "" {
|
||
k := memory.Fact
|
||
in.Kind = &k
|
||
}
|
||
src := &memory.Source{Agent: c.agent, Dir: c.dir}
|
||
var proj *memory.Project
|
||
if scope == memory.ScopeOf(c.project) {
|
||
proj = c.project
|
||
}
|
||
m, added, err := memory.Save(in, memory.FromAgent, src, proj)
|
||
if err != nil {
|
||
return "", err
|
||
}
|
||
if !added {
|
||
return "Already remembered, merged: " + memoryLine(m, c), nil
|
||
}
|
||
return "Remembered: " + memoryLine(m, c) + projectFilesNote(c, m), nil
|
||
}
|
||
|
||
// projectInstructionFiles are the files, under a project's root, an agent
|
||
// reads the project's own instructions from.
|
||
var projectInstructionFiles = []string{"AGENTS.md", "CLAUDE.md", "GEMINI.md", ".github/copilot-instructions.md", ".cursorrules"}
|
||
|
||
// projectFilesNote points a save that belongs in the project's own
|
||
// instruction files there: a project's rules kept in memory too disagree
|
||
// with those files once the files are tidied (flying_crp on X). It is for
|
||
// a memory of the caller's project, or a rule or procedure kept for
|
||
// everyone, saved in a project that keeps such files; "" otherwise. It
|
||
// names only the files found, never this app nor a vendor.
|
||
func projectFilesNote(c memoryCaller, m *memory.Memory) string {
|
||
if c.project == nil || m == nil {
|
||
return ""
|
||
}
|
||
inProject := m.Scope == memory.ScopeOf(c.project)
|
||
switch {
|
||
case inProject && m.Kind != memory.Profile && m.Kind != memory.Preference:
|
||
case m.Scope == memory.Global && (m.Kind == memory.Rule || m.Kind == memory.Procedure):
|
||
default:
|
||
return ""
|
||
}
|
||
var found []string
|
||
for _, root := range c.project.Roots {
|
||
for _, f := range projectInstructionFiles {
|
||
if fi, err := os.Stat(filepath.Join(root, filepath.FromSlash(f))); err == nil && !fi.IsDir() {
|
||
found = append(found, f)
|
||
}
|
||
}
|
||
if len(found) > 0 {
|
||
break
|
||
}
|
||
}
|
||
if len(found) == 0 {
|
||
return ""
|
||
}
|
||
files := strings.Join(found, ", ")
|
||
if inProject {
|
||
return "\nThis project keeps its own instructions in " + files + ". A rule or fact of the project is better written there, where everyone working on it reads it and it is kept up to date with the project: offer the user to add it there, and forget this memory once it is."
|
||
}
|
||
return "\nIf this holds only in this project, it belongs in the project's own " + files + " rather than in memory: offer the user to add it there, and forget this memory once it is."
|
||
}
|
||
|
||
func memoryForget(a memoryArgs) (string, error) {
|
||
id := strings.TrimSpace(a.ID)
|
||
if id == "" {
|
||
return "", searchMCPError("memory_forget needs the memory's id, from memory_search")
|
||
}
|
||
m, err := memory.Forget(id)
|
||
if err != nil {
|
||
return "", err
|
||
}
|
||
return "Forgotten: [" + m.ID + "] " + memory.Indented(m.Text, " "), nil
|
||
}
|
||
|
||
// memoryStamp is when a memory was last changed, in the reader's own zone
|
||
// with its offset (2026-11-11T04:30+08:00). A date alone, taken in UTC,
|
||
// put a memory on the day before or after the one the user lived
|
||
// (Norethcy on X). Memories saved before this are stored in UTC ("…Z")
|
||
// and are shown the same way.
|
||
func memoryStamp(t time.Time) string { return t.In(memoryZone()).Format("2006-01-02T15:04Z07:00") }
|
||
|
||
// memoryZone is the zone memoryStamp writes in: time.Local, a variable for
|
||
// tests, which must never swap time.Local itself (every goroutine still
|
||
// running reads it, so the swap is a race).
|
||
var memoryZone = func() *time.Location { return time.Local }
|
||
|
||
// memoryClients are the agents the clients of the memory server named at
|
||
// initialize, by Mcp-Session-Id: a client of the HTTP route says who it is
|
||
// there alone, and its calls carry no User-Agent of an agent's (#6392).
|
||
var memoryClients = &sessionClients{m: map[string]sessionClient{}}
|
||
|
||
type sessionClient struct {
|
||
agent string
|
||
at time.Time
|
||
}
|
||
|
||
type sessionClients struct {
|
||
mu sync.Mutex
|
||
m map[string]sessionClient
|
||
}
|
||
|
||
const (
|
||
memoryClientsKept = 1024
|
||
memoryClientsFor = 24 * time.Hour
|
||
)
|
||
|
||
func (c *sessionClients) set(sid, agent string) {
|
||
if sid == "" || agent == "" {
|
||
return
|
||
}
|
||
c.mu.Lock()
|
||
defer c.mu.Unlock()
|
||
now := time.Now()
|
||
if len(c.m) >= memoryClientsKept {
|
||
for k, v := range c.m {
|
||
if now.Sub(v.at) > memoryClientsFor {
|
||
delete(c.m, k)
|
||
}
|
||
}
|
||
for k := range c.m {
|
||
if len(c.m) < memoryClientsKept {
|
||
break
|
||
}
|
||
delete(c.m, k)
|
||
}
|
||
}
|
||
c.m[sid] = sessionClient{agent, now}
|
||
}
|
||
|
||
func (c *sessionClients) of(sid string) string {
|
||
if sid == "" {
|
||
return ""
|
||
}
|
||
c.mu.Lock()
|
||
defer c.mu.Unlock()
|
||
return c.m[sid].agent
|
||
}
|
||
|
||
// rememberMemoryClient keeps the client name an initialize gave under the
|
||
// session it was given (or sent on).
|
||
func rememberMemoryClient(r *http.Request, m mcpMessage) {
|
||
var p struct {
|
||
ClientInfo struct {
|
||
Name string `json:"name"`
|
||
} `json:"clientInfo"`
|
||
}
|
||
if json.Unmarshal(m.Params, &p) != nil {
|
||
return
|
||
}
|
||
agent := memoryAgent(usage.AgentOf(p.ClientInfo.Name))
|
||
sid := r.Header.Get("Mcp-Session-Id")
|
||
if x, _ := r.Context().Value(mcpExchangeKey{}).(*mcpExchange); x != nil && sid == "" {
|
||
sid = x.w.Header().Get("Mcp-Session-Id")
|
||
}
|
||
memoryClients.set(sid, agent)
|
||
}
|
||
|
||
// RunClient names the agent behind a request to /mcp/run/<server>, the
|
||
// route only Codex is given: what its headers say, else Codex.
|
||
func RunClient(r *http.Request) string {
|
||
if a := memoryAgent(agentOf(r)); a != "" {
|
||
return a
|
||
}
|
||
return "codex"
|
||
}
|