memory: a search or save can name its project, and every answer says whose and where (Norethcy on X, #6392)
The memory tools had no target-project argument and no way to see the caller context they resolved, so a scoped migration run from one project couldn't keep memories for another or check where they went. - memory_search and memory_save take `project`: a folder on this computer (absolute, or relative to the caller's own folder), or the key of a project memory knows (github.com/owner/repo, with or without project:, or a project's one name). A project named goes with scope project (a save's default then) or a search's all; global or agent with a project is refused, and an unknown project says which ones memory knows. - Answers name what was used: a memory reads "this project (<key>)" and "only for you (<agent>)", and a search ends "(looked in: everywhere, project <key>, agent <id>)". - New read-only memory_context: the agent the server takes the caller for and how it was found (router _meta, magpie mcp memory's initialize, key/User-Agent, the session's initialize), the project with its folder and source, the scopes a search looks in and the server version, as text and structuredContent. Given `project`, it shows that one. - HTTP and stdio are the same server (magpie mcp memory relays), and OwnMCPTools lists memory_context with the others. Run (mote, -tags nogui unless noted): - TestMemoryMCPProjectArgumentAndContext (new): folder, key and relative folder; the caller's own project untouched; refusals; memory_context's text and structuredContent; tools/list. Red with the project argument ignored by hand. - TestMemoryBridgeContextAndProject (new): the real gateway behind magpie mcp memory over stdio, initialized as codex as in the report. - go test ./internal/browsermcp ./internal/cli ./internal/library: ok; go test -run 'Memory|OwnMCP|Hub|RootDirs|Tool' ./internal/gateway: ok. - Windows (xiaomi-gpu, win-run): the new gateway, browsermcp and cli tests ok (a test's own unquoted Windows path was fixed on the way). - go vet darwin, linux nogui, windows for the four packages; gofmt. Not tried: Codex desktop itself over /mcp/run/magpie-memory; the full suite runs after the tag.
This commit is contained in:
@@ -43,7 +43,7 @@ and refuses empty or over-long text, an unknown kind and a bad scope
|
||||
### MCP server
|
||||
|
||||
[internal/gateway/memory_mcp.go](../../internal/gateway/memory_mcp.go):
|
||||
`memory_search`, `memory_save`, `memory_forget`, Streamable HTTP at
|
||||
`memory_search`, `memory_save`, `memory_forget`, `memory_context`, Streamable HTTP at
|
||||
`MemoryMCPPath` (`/mcp/magpie/memory`), served like the search server
|
||||
(`serveMCP`) but to the agents on this computer alone, as the hub gives it
|
||||
(`HereOnly`): memory is what is known about this computer's user, and its
|
||||
@@ -58,12 +58,24 @@ away (`TestMemoryMCPGuarded`).
|
||||
which relays stdio to the gateway with the folder the agent started it in
|
||||
(`X-Magpie-Cwd`) and the client name from `initialize`
|
||||
(`X-Magpie-Mcp-Client`).
|
||||
- `magpie tool memory_*` names its folder the same way, and reads an
|
||||
answer sent as an event stream, answering a server's roots/list
|
||||
(`TestToolMemoryThroughTheGateway`, #6049).
|
||||
- Behind the [MCP router](mcp-router.md) the hub passes the caller in the
|
||||
call's `_meta` instead (`HubRootsMeta`, `HubClientMeta`;
|
||||
`TestMemoryMCPHubMetaNamesTheProject`).
|
||||
- Without a folder the server can't name the project, nor the agent without
|
||||
a client name: such a save says so instead of guessing, and a save with
|
||||
no scope is kept for everyone (`TestMemoryMCPSaysWhatItCantKnow`).
|
||||
- A search or save may name another project (`project`: a folder,
|
||||
absolute or under the caller's, or a key memory knows;
|
||||
`memoryCaller.inProject`), so a migration run from one project keeps
|
||||
memories for another. A project named goes with scope project (or a
|
||||
search's all). Every answer names what it used: a memory's line says
|
||||
`this project (<key>)` and `only for you (<agent>)`, and a search ends
|
||||
`(looked in: …)`. `memory_context` says who the caller is taken for,
|
||||
the project, and how each was found, as text and `structuredContent`
|
||||
(`TestMemoryMCPProjectArgumentAndContext`).
|
||||
- A save through MCP is active at once, origin `agent`.
|
||||
|
||||
### Other memory services
|
||||
|
||||
@@ -298,3 +298,61 @@ func TestClientName(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Over stdio, as over HTTP, memory_context says who the server takes the
|
||||
// agent for and which project, and a save names another project's folder
|
||||
// (#6392, Norethcy on X): the real gateway, behind magpie mcp memory.
|
||||
func TestMemoryBridgeContextAndProject(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("USERPROFILE", home)
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
t.Setenv("XDG_DATA_HOME", t.TempDir())
|
||||
gw := httptest.NewServer(gateway.New().Handler())
|
||||
defer gw.Close()
|
||||
d := t.TempDir()
|
||||
repo := func(name string) string {
|
||||
dir := filepath.Join(d, name)
|
||||
if err := os.MkdirAll(filepath.Join(dir, ".git"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg := "[remote \"origin\"]\n\turl = https://github.com/someone/" + name + ".git\n"
|
||||
if err := os.WriteFile(filepath.Join(dir, ".git", "config"), []byte(cfg), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return dir
|
||||
}
|
||||
here, target := repo("organizer"), repo("target")
|
||||
// the relay sends lines at once, so the search goes in a second run
|
||||
byID := map[string]string{}
|
||||
for _, calls := range []string{
|
||||
`{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"memory_context","arguments":{}}}` + "\n" +
|
||||
`{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"memory_save","arguments":{"text":"Builds run on mote","kind":"fact","project":"../target"}}}`,
|
||||
`{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"memory_search","arguments":{"scope":"project","project":"` + filepath.ToSlash(target) + `"}}}`,
|
||||
} {
|
||||
in := strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"codex","version":"memory-migration"}}}` + "\n" +
|
||||
`{"jsonrpc":"2.0","method":"notifications/initialized"}` + "\n" + calls + "\n")
|
||||
var out bytes.Buffer
|
||||
if err := serveMemory(in, &out, gw.URL, here); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, l := range strings.Split(strings.TrimSpace(out.String()), "\n") {
|
||||
var m struct{ ID json.RawMessage }
|
||||
json.Unmarshal([]byte(l), &m)
|
||||
byID[string(m.ID)] = l
|
||||
}
|
||||
}
|
||||
for id, want := range map[string]string{
|
||||
"2": `Agent: codex (from the client named at magpie mcp memory's initialize)`,
|
||||
"3": `this project (github.com/someone/target)`,
|
||||
"4": `(looked in: project github.com/someone/target)`,
|
||||
} {
|
||||
if !strings.Contains(byID[id], want) {
|
||||
t.Fatalf("call %s: %s, want %q", id, byID[id], want)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(byID["2"], "Project: github.com/someone/organizer") || !strings.Contains(byID["4"], "Builds run on mote") {
|
||||
t.Fatalf("answers: %v", byID)
|
||||
}
|
||||
}
|
||||
|
||||
+211
-28
@@ -3,8 +3,10 @@ package gateway
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"maps"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
@@ -19,7 +21,8 @@ import (
|
||||
|
||||
// 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 and memory_forget, Streamable HTTP at MemoryMCPPath, served
|
||||
// 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
|
||||
@@ -42,9 +45,10 @@ const (
|
||||
)
|
||||
|
||||
const (
|
||||
memorySearchTool = "memory_search"
|
||||
memorySaveTool = "memory_save"
|
||||
memoryForgetTool = "memory_forget"
|
||||
memorySearchTool = "memory_search"
|
||||
memorySaveTool = "memory_save"
|
||||
memoryForgetTool = "memory_forget"
|
||||
memoryContextTool = "memory_context"
|
||||
)
|
||||
|
||||
const memoryServerName = "magpie-memory"
|
||||
@@ -74,11 +78,12 @@ func memoryMCPTools() []any {
|
||||
"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},
|
||||
"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},
|
||||
"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},
|
||||
@@ -91,12 +96,13 @@ func memoryMCPTools() []any {
|
||||
"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"},
|
||||
"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"},
|
||||
},
|
||||
@@ -113,6 +119,16 @@ func memoryMCPTools() []any {
|
||||
},
|
||||
"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},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,14 +166,25 @@ func (s *Server) memoryMCPCall(r *http.Request, m mcpMessage) (any, map[string]a
|
||||
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 + " and " + memoryForgetTool}
|
||||
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
|
||||
@@ -176,6 +203,9 @@ type memoryArgs struct {
|
||||
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
|
||||
@@ -213,6 +243,10 @@ 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
|
||||
@@ -234,34 +268,40 @@ func memoryCallerOf(r *http.Request, rawMeta json.RawMessage) memoryCaller {
|
||||
// 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 _, name := range []string{extra.Client, r.Header.Get(MemoryClientHeader)} {
|
||||
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 == "" {
|
||||
c.agent = memoryAgent(callerOf(r).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
|
||||
c.agent = memoryClients.of(r.Header.Get("Mcp-Session-Id"))
|
||||
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 = rootDirs(*extra.Roots)
|
||||
dirs, from = rootDirs(*extra.Roots), "the roots the MCP router names"
|
||||
} else if d := strings.TrimSpace(r.Header.Get(MemoryCwdHeader)); d != "" {
|
||||
dirs = []string{d}
|
||||
dirs, from = []string{d}, "the folder the client runs in"
|
||||
} else {
|
||||
dirs = rootDirs(hubRoots(r, meta))
|
||||
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 = p, d
|
||||
c.project, c.dir, c.projectFrom = p, d, from
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -300,6 +340,130 @@ func rootDirs(uris []string) []string {
|
||||
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. No folder of yours 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)
|
||||
@@ -318,6 +482,9 @@ func (c memoryCaller) scopes(which string) ([]string, error) {
|
||||
}
|
||||
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 == "" {
|
||||
@@ -353,16 +520,17 @@ func memorySearch(c memoryCaller, a memoryArgs) (string, error) {
|
||||
}
|
||||
if len(hits) == 0 {
|
||||
if strings.TrimSpace(a.Query) == "" {
|
||||
return "Nothing is remembered here yet.", nil
|
||||
return "Nothing is remembered here yet. " + c.whereSaid(scopes), nil
|
||||
}
|
||||
return "Nothing remembered matches " + quotedQuery(a.Query) + ".", 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")
|
||||
}
|
||||
return strings.TrimSpace(b.String()), nil
|
||||
b.WriteString(c.whereSaid(scopes))
|
||||
return b.String(), nil
|
||||
}
|
||||
|
||||
// memoryLine is one memory as an agent reads it: its id, kind, where it
|
||||
@@ -371,9 +539,9 @@ func memoryLine(m *memory.Memory, c memoryCaller) string {
|
||||
where := "everywhere"
|
||||
switch {
|
||||
case strings.HasPrefix(m.Scope, "agent:"):
|
||||
where = "only for you"
|
||||
where = "only for you (" + strings.TrimPrefix(m.Scope, "agent:") + ")"
|
||||
case strings.HasPrefix(m.Scope, "project:"):
|
||||
where = "this 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:")
|
||||
}
|
||||
@@ -415,6 +583,15 @@ func memorySave(c memoryCaller, a memoryArgs) (string, error) {
|
||||
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) {
|
||||
@@ -443,6 +620,12 @@ func memorySave(c memoryCaller, a memoryArgs) (string, error) {
|
||||
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
|
||||
|
||||
@@ -314,3 +314,86 @@ func TestMemoryMCPAgentFromTheSessionsInitialize(t *testing.T) {
|
||||
t.Fatal("memoryAgent")
|
||||
}
|
||||
}
|
||||
|
||||
// A migration run from one project keeps memories for another and can
|
||||
// check where they went (#6392, Norethcy on X): memory_search and
|
||||
// memory_save take a project (a folder, absolute or under the caller's,
|
||||
// or a key memory knows), every answer names the agent and project it
|
||||
// used, and memory_context says who the caller is taken for and how.
|
||||
func TestMemoryMCPProjectArgumentAndContext(t *testing.T) {
|
||||
fresh(t)
|
||||
h := lanGuard(New().Handler())
|
||||
d := t.TempDir()
|
||||
here := gitRepo(t, filepath.Join(d, "organizer"), "https://github.com/someone/organizer.git")
|
||||
target := gitRepo(t, filepath.Join(d, "target"), "https://github.com/someone/target.git")
|
||||
codex := []string{MemoryClientHeader, "codex-mcp-client", MemoryCwdHeader, here}
|
||||
|
||||
said, bad := memPost(t, h, memorySaveTool, `{"text":"Builds run on mote","kind":"fact","project":`+quotedQuery(target)+`}`, codex...)
|
||||
if bad || !strings.Contains(said, "this project (github.com/someone/target)") {
|
||||
t.Fatalf("save into a folder's project: %s", said)
|
||||
}
|
||||
if all, _, _ := memory.All(); all[0].Scope != "project:github.com/someone/target" || all[0].Sources[0].Dir != target {
|
||||
t.Fatalf("kept %+v", all[0])
|
||||
}
|
||||
// its key, and a folder relative to the caller's, name it too
|
||||
if said, bad := memPost(t, h, memorySaveTool, `{"text":"Releases are tagged after a green run","kind":"procedure","project":"github.com/someone/target"}`, codex...); bad || !strings.Contains(said, "(github.com/someone/target)") {
|
||||
t.Fatalf("save by key: %s", said)
|
||||
}
|
||||
if said, bad := memPost(t, h, memorySearchTool, `{"scope":"project","project":"../target"}`, codex...); bad || !strings.Contains(said, "Builds run on mote") || !strings.Contains(said, "Releases are tagged") || !strings.Contains(said, "(looked in: project github.com/someone/target)") {
|
||||
t.Fatalf("search by relative folder: %s", said)
|
||||
}
|
||||
// the caller's own project has none of them, and says which it is
|
||||
if said, _ := memPost(t, h, memorySearchTool, `{"scope":"project"}`, codex...); strings.Contains(said, "mote") || !strings.Contains(said, "project github.com/someone/organizer") {
|
||||
t.Fatalf("own project: %s", said)
|
||||
}
|
||||
if said, _ := memPost(t, h, memorySearchTool, `{"query":"mote"}`, codex...); !strings.Contains(said, "Nothing remembered matches") || !strings.Contains(said, "(looked in: everywhere, project github.com/someone/organizer, agent codex)") {
|
||||
t.Fatalf("all, here: %s", said)
|
||||
}
|
||||
// what can't be: an unknown project, a project with another scope
|
||||
for args, want := range map[string]string{
|
||||
`{"text":"x","project":` + quotedQuery(filepath.Join(d, "nowhere")) + `}`: "isn't a folder",
|
||||
`{"text":"x","project":"nothing-like-it"}`: "neither a folder here nor a project memory knows",
|
||||
`{"text":"x","scope":"global","project":"target"}`: "goes with scope project",
|
||||
`{"text":"x","scope":"agent","project":"../target"}`: "goes with scope project",
|
||||
} {
|
||||
if said, bad := memPost(t, h, memorySaveTool, args, codex...); !bad || !strings.Contains(said, want) {
|
||||
t.Fatalf("%s: %v %s", args, bad, said)
|
||||
}
|
||||
}
|
||||
|
||||
// memory_context: the agent and the project, how each was found
|
||||
w := mcpPostTo(h, MemoryMCPPath, "127.0.0.1:50000", `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"memory_context","arguments":{}}}`, append(codex, "Accept", "application/json")...)
|
||||
var res struct {
|
||||
Result struct {
|
||||
Content []struct{ Text string } `json:"content"`
|
||||
Context struct {
|
||||
Agent struct{ ID, From string }
|
||||
Project struct {
|
||||
Key, Scope, Folder, From string
|
||||
}
|
||||
Scopes []string
|
||||
} `json:"structuredContent"`
|
||||
} `json:"result"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil {
|
||||
t.Fatalf("%v: %s", err, w.Body.String())
|
||||
}
|
||||
ctx := res.Result.Context
|
||||
if ctx.Agent.ID != "codex" || !strings.Contains(ctx.Agent.From, "initialize") || ctx.Project.Key != "github.com/someone/organizer" || ctx.Project.Folder != here || ctx.Project.From != "the folder the client runs in" ||
|
||||
strings.Join(ctx.Scopes, " ") != "global project:github.com/someone/organizer agent:codex agent:codex-mcp-client" || !strings.Contains(res.Result.Content[0].Text, "Agent: codex") {
|
||||
t.Fatalf("context: %s", w.Body.String())
|
||||
}
|
||||
said, bad = memPost(t, h, memoryContextTool, `{"project":"target"}`, codex...)
|
||||
if bad || !strings.Contains(said, "Project: github.com/someone/target (target), from the project argument") {
|
||||
t.Fatalf("context in another project: %s", said)
|
||||
}
|
||||
// nothing known: it says so, and how to make it known
|
||||
if said, bad := memPost(t, h, memoryContextTool, `{}`, "User-Agent", "curl/8"); bad || !strings.Contains(said, "Agent: unknown") || !strings.Contains(said, "Project: none") {
|
||||
t.Fatalf("context of no one: %s", said)
|
||||
}
|
||||
// the tool is listed, read-only
|
||||
w = mcpPostTo(h, MemoryMCPPath, "127.0.0.1:50000", `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`, "Accept", "application/json")
|
||||
if !strings.Contains(w.Body.String(), `"name":"memory_context"`) || strings.Count(w.Body.String(), `"project":{`) != 3 {
|
||||
t.Fatalf("tools: %s", w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,7 +85,7 @@ func OwnMCPTools(ctx context.Context) []OwnMCPServer {
|
||||
case imageServerName:
|
||||
s.Tools = []string{GenerateImageTool, GenerateVideoTool, GenerationResultTool}
|
||||
case memoryServerName:
|
||||
s.Tools = []string{memorySearchTool, memorySaveTool, memoryForgetTool}
|
||||
s.Tools = []string{memorySearchTool, memorySaveTool, memoryForgetTool, memoryContextTool}
|
||||
case "magpie-tools":
|
||||
ts, _ := servedTools(ctx)
|
||||
for _, t := range ts {
|
||||
|
||||
@@ -242,7 +242,8 @@ func visionServer() MarketServer {
|
||||
const memoryServerName = "magpie-memory"
|
||||
|
||||
// memoryServer is Magpie Memory: what is known about the user, kept by
|
||||
// magpie for every agent, as memory_search, memory_save and memory_forget,
|
||||
// magpie for every agent, as memory_search, memory_save, memory_forget and
|
||||
// memory_context,
|
||||
// through `magpie mcp memory`, which passes each call to the gateway's
|
||||
// MemoryMCPPath with the folder the agent started it in. It is there to be
|
||||
// shared and costs nothing, so, unlike magpie's other servers, it is given
|
||||
|
||||
Reference in New Issue
Block a user