memory_search, memory_save and memory_forget at /mcp/magpie/memory, served and guarded as the search server is (serveMCP): another computer reaches it only while magpie is shared, with a gateway key. A save through it is active at once, origin agent, kept everywhere, for the project (the git repository the agent works in, by its remote) or for the agent alone; without a folder or a client name it says it can't know rather than guess. - The Library's market offers it as magpie-memory, run as `magpie mcp memory` (browsermcp.RunMemory): stdio relayed to the gateway with the folder it was started in (X-Magpie-Cwd) and the client name from initialize (X-Magpie-Mcp-Client). - Behind the MCP router the hub keeps it on this computer (hereOnly) and passes the caller's roots and client in _meta (wantsCaller), as it does for magpie's own server. - OwnMCPPath lists it among magpie's own servers. - Judged as its sibling servers are: a gateway key's MaxConcurrency doesn't hold it (a tool call of a turn already held), and a read-only key is refused (memory_save writes). The first full gateway run was red on TestKeySlotEveryRoute and TestReadOnlyKeyEveryRoute until the route was listed. Run (mote-run): - go test -tags nogui ./internal/gateway: ok (881.5s) - go test ./internal/browsermcp ./internal/cli ./internal/memory: ok - go test ./internal/library: ok (130.9s) - go vet, GOOS darwin, linux, windows: ok; gofmt -l clean Broken by hand, each red, then green restored: - the hub not sending memory its caller (wantsCaller without isMemory): TestHubTellsMagpieMemoryItsCaller "roots asked false" - the relay not setting X-Magpie-Cwd: TestMemoryBridgeSendsFolderAndClient - the gateway ignoring X-Magpie-Cwd: TestMemoryMCPSharedAcrossAgents (a project fact kept everywhere) Not tried: a real Claude Code or Codex mounting magpie-memory.
204 lines
8.5 KiB
Go
204 lines
8.5 KiB
Go
package gateway
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/yetone/magpie/internal/memory"
|
|
"github.com/yetone/magpie/internal/usage"
|
|
)
|
|
|
|
// memPost sends one tools/call of the memory server through h, from this
|
|
// computer, with hdr as name, value pairs, and gives the tool's text and
|
|
// whether it is an error.
|
|
func memPost(t *testing.T, h http.Handler, tool, args string, hdr ...string) (string, bool) {
|
|
t.Helper()
|
|
body := `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"` + tool + `","arguments":` + args + `}}`
|
|
return memSend(t, h, body, hdr...)
|
|
}
|
|
|
|
func memSend(t *testing.T, h http.Handler, body string, hdr ...string) (string, bool) {
|
|
t.Helper()
|
|
r := httptest.NewRequest(http.MethodPost, MemoryMCPPath, strings.NewReader(body))
|
|
r.RemoteAddr = "127.0.0.1:50000"
|
|
r.Host = "127.0.0.1:3425"
|
|
r.Header.Set("Content-Type", "application/json")
|
|
r.Header.Set("Accept", "application/json")
|
|
for i := 0; i+1 < len(hdr); i += 2 {
|
|
r.Header.Set(hdr[i], hdr[i+1])
|
|
}
|
|
w := httptest.NewRecorder()
|
|
h.ServeHTTP(w, r)
|
|
m := readMCP(t, w)
|
|
if m.Error != nil || len(m.Result.Content) != 1 {
|
|
t.Fatalf("%s: %s", tool(body), w.Body.String())
|
|
}
|
|
return m.Result.Content[0].Text, m.Result.IsError
|
|
}
|
|
|
|
func tool(body string) string {
|
|
var m struct{ Params struct{ Name string } }
|
|
json.Unmarshal([]byte(body), &m)
|
|
return m.Params.Name
|
|
}
|
|
|
|
// gitRepo makes a checkout at dir whose origin is remote.
|
|
func gitRepo(t *testing.T, dir, remote string) string {
|
|
t.Helper()
|
|
if err := os.MkdirAll(filepath.Join(dir, ".git"), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
cfg := "[core]\n\tbare = false\n[remote \"origin\"]\n\turl = " + remote + "\n"
|
|
if err := os.WriteFile(filepath.Join(dir, ".git", "config"), []byte(cfg), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return dir
|
|
}
|
|
|
|
// What one agent saves, another finds: a preference everywhere, a
|
|
// project's fact in every clone of that repository and nowhere else.
|
|
func TestMemoryMCPSharedAcrossAgents(t *testing.T) {
|
|
fresh(t)
|
|
h := lanGuard(New().Handler())
|
|
d := t.TempDir()
|
|
clone := gitRepo(t, filepath.Join(d, "magpie"), "git@github.com:yetone/magpie.git")
|
|
other := gitRepo(t, filepath.Join(d, "copy"), "https://github.com/yetone/magpie")
|
|
elsewhere := gitRepo(t, filepath.Join(d, "site"), "https://github.com/yetone/site.git")
|
|
claude := []string{"User-Agent", "claude-cli/2.1.314 (external, cli)", MemoryCwdHeader, filepath.Join(clone, "internal")}
|
|
|
|
said, bad := memPost(t, h, memorySaveTool, `{"text":"Answer in Chinese","kind":"preference","tags":"lang, style"}`, claude...)
|
|
if bad || !strings.Contains(said, "preference, everywhere, #lang #style") {
|
|
t.Fatalf("save a preference: %s", said)
|
|
}
|
|
said, bad = memPost(t, h, memorySaveTool, `{"text":"Heavy tests run on mote","kind":"fact"}`, claude...)
|
|
if bad || !strings.Contains(said, "fact, this project") {
|
|
t.Fatalf("save a project fact: %s", said)
|
|
}
|
|
all, _, _ := memory.All()
|
|
// "claude" in magpie, where package agent names it
|
|
if len(all) != 2 || all[0].Sources[0].Agent != usage.AgentOf("claude-cli/2.1.314") || all[0].Sources[0].Agent == "" {
|
|
t.Fatalf("kept %+v", all)
|
|
}
|
|
|
|
codex := func(dir string) []string {
|
|
return []string{MemoryClientHeader, "codex-mcp-client", MemoryCwdHeader, dir}
|
|
}
|
|
if said, _ := memPost(t, h, memorySearchTool, `{"query":"tests mote"}`, codex(other)...); !strings.Contains(said, "Heavy tests run on mote") {
|
|
t.Fatalf("the other clone didn't find it: %s", said)
|
|
}
|
|
if said, _ := memPost(t, h, memorySearchTool, `{"query":"tests mote"}`, codex(elsewhere)...); strings.Contains(said, "Heavy tests") {
|
|
t.Fatalf("another project found it: %s", said)
|
|
}
|
|
if said, _ := memPost(t, h, memorySearchTool, `{"query":"chinese"}`, codex(elsewhere)...); !strings.Contains(said, "Answer in Chinese") {
|
|
t.Fatalf("the preference wasn't everywhere: %s", said)
|
|
}
|
|
// the same text again merges, with the second agent as a source
|
|
if said, _ := memPost(t, h, memorySaveTool, `{"text":"answer in chinese.","kind":"preference"}`, codex(elsewhere)...); !strings.HasPrefix(said, "Already remembered") {
|
|
t.Fatalf("saved twice: %s", said)
|
|
}
|
|
hits, _ := memory.Search(memory.Query{Text: "Answer in Chinese"})
|
|
m, _ := memory.Get(hits[0].ID)
|
|
if len(m.Sources) != 2 || m.Sources[1].Agent != usage.AgentOf("codex-mcp-client") {
|
|
t.Fatalf("sources %+v", m.Sources)
|
|
}
|
|
}
|
|
|
|
// Behind the hub the server is one process for every agent, started in
|
|
// no project: the call's _meta names the agent's roots and client, and
|
|
// wins over the folder the process runs in.
|
|
func TestMemoryMCPHubMetaNamesTheProject(t *testing.T) {
|
|
fresh(t)
|
|
h := lanGuard(New().Handler())
|
|
d := t.TempDir()
|
|
repo := gitRepo(t, filepath.Join(d, "magpie"), "https://github.com/yetone/magpie.git")
|
|
body := `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"memory_save","arguments":{"text":"Use bun for scripts","kind":"rule","scope":"agent"},` +
|
|
`"_meta":{"magpie/roots":["` + fileURI(repo) + `"],"magpie/client":"claude-code/2.1.314"}}}`
|
|
said, bad := memSend(t, h, body, MemoryCwdHeader, d)
|
|
if bad || !strings.Contains(said, "only for you") {
|
|
t.Fatalf("hub save: %s", said)
|
|
}
|
|
all, _, _ := memory.All()
|
|
if all[0].Scope != "agent:"+usage.AgentOf("claude-code/2.1.314") || all[0].Sources[0].Dir != repo {
|
|
t.Fatalf("kept %+v", all[0])
|
|
}
|
|
body = strings.Replace(body, `"scope":"agent"`, `"scope":"project"`, 1)
|
|
if said, bad := memSend(t, h, body, MemoryCwdHeader, d); bad || !strings.Contains(said, "this project") {
|
|
t.Fatalf("hub project save: %s", said)
|
|
}
|
|
if all, _, _ := memory.All(); all[0].Scope != "project:github.com/yetone/magpie" {
|
|
t.Fatalf("kept in %s", all[0].Scope)
|
|
}
|
|
}
|
|
|
|
// Without a project or an agent it can tell, the server says why rather
|
|
// than keeping a memory where it doesn't belong.
|
|
func TestMemoryMCPSaysWhatItCantKnow(t *testing.T) {
|
|
fresh(t)
|
|
h := lanGuard(New().Handler())
|
|
if said, bad := memPost(t, h, memorySaveTool, `{"text":"x","scope":"project"}`); !bad || !strings.Contains(said, "no project") {
|
|
t.Fatalf("project with no folder: %s", said)
|
|
}
|
|
if said, bad := memPost(t, h, memorySaveTool, `{"text":"x","scope":"agent"}`, "User-Agent", "curl/8"); !bad || !strings.Contains(said, "which agent") {
|
|
t.Fatalf("agent unknown: %s", said)
|
|
}
|
|
if said, bad := memPost(t, h, memorySaveTool, `{"text":"x","kind":"mood"}`); !bad || !strings.Contains(said, "isn't one of") {
|
|
t.Fatalf("bad kind: %s", said)
|
|
}
|
|
// a fact with no project is kept for everyone
|
|
said, bad := memPost(t, h, memorySaveTool, `{"text":"The NAS is at nas.local","kind":"reference"}`)
|
|
if bad || !strings.Contains(said, "everywhere") {
|
|
t.Fatalf("no project: %s", said)
|
|
}
|
|
id := strings.TrimPrefix(strings.SplitN(strings.TrimPrefix(said, "Remembered: "), "]", 2)[0], "[")
|
|
if said, bad := memPost(t, h, memorySaveTool, `{"id":"`+id+`","text":"The NAS is at nas.lan"}`); bad || !strings.Contains(said, "nas.lan") {
|
|
t.Fatalf("change: %s", said)
|
|
}
|
|
if said, bad := memPost(t, h, memoryForgetTool, `{"id":"`+id+`"}`); bad || !strings.HasPrefix(said, "Forgotten") {
|
|
t.Fatalf("forget: %s", said)
|
|
}
|
|
if said, _ := memPost(t, h, memorySearchTool, `{"query":"nas"}`); !strings.HasPrefix(said, "Nothing remembered matches") {
|
|
t.Fatalf("found a forgotten memory: %s", said)
|
|
}
|
|
if said, bad := memPost(t, h, memoryForgetTool, `{"id":"m_none"}`); !bad || !strings.Contains(said, "no memory") {
|
|
t.Fatalf("forget nothing: %s", said)
|
|
}
|
|
}
|
|
|
|
// Another computer reaches memory only while magpie is shared, with a
|
|
// gateway key, as every other MCP server of magpie's; and has no folder
|
|
// here for a project.
|
|
func TestMemoryMCPGuarded(t *testing.T) {
|
|
fresh(t)
|
|
t.Setenv("MAGPIE_ADDR", "")
|
|
t.Setenv("MAGPIE_PUBLIC_URL", "")
|
|
h := lanGuard(New().Handler())
|
|
body := `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"memory_search","arguments":{}}}`
|
|
r := httptest.NewRequest(http.MethodPost, MemoryMCPPath, strings.NewReader(body))
|
|
r.RemoteAddr = "192.0.2.7:4000"
|
|
w := httptest.NewRecorder()
|
|
h.ServeHTTP(w, r)
|
|
if w.Code != http.StatusForbidden {
|
|
t.Fatalf("not shared: %d %s", w.Code, w.Body.String())
|
|
}
|
|
r = httptest.NewRequest(http.MethodPost, MemoryMCPPath, strings.NewReader(body))
|
|
r.RemoteAddr = "127.0.0.1:50000"
|
|
r.Header.Set("Origin", "https://evil.example")
|
|
w = httptest.NewRecorder()
|
|
h.ServeHTTP(w, r)
|
|
if w.Code != http.StatusForbidden {
|
|
t.Fatalf("a web page: %d %s", w.Code, w.Body.String())
|
|
}
|
|
}
|
|
|
|
func TestRootDirs(t *testing.T) {
|
|
got := rootDirs([]string{"file:///Users/a/p", "https://x/y", "file:///C:/w/p"})
|
|
if len(got) != 2 || got[0] != filepath.FromSlash("/Users/a/p") {
|
|
t.Fatalf("dirs %q", got)
|
|
}
|
|
}
|