gateway: memory is an MCP server every agent can mount
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.
This commit is contained in:
@@ -10,6 +10,10 @@
|
||||
// (lutra_fs on Discord: the search was an address in Settings alone).
|
||||
// `magpie mcp vision` is image recognition's (gateway.VisionMCPPath), the
|
||||
// Library's Magpie Image Recognition (matrix0487 on Discord, #4653).
|
||||
// `magpie mcp memory` is memory's (gateway.MemoryMCPPath), sent with the
|
||||
// folder the agent started it in, for the project its memories are kept
|
||||
// for, and the client name the agent gave at initialize, for which agent
|
||||
// it is.
|
||||
package browsermcp
|
||||
|
||||
import (
|
||||
@@ -56,6 +60,16 @@ func RunVision(args []string) error {
|
||||
return serveVision(os.Stdin, os.Stdout, gatewayBase())
|
||||
}
|
||||
|
||||
// RunMemory serves the memory MCP server on stdin and stdout until stdin
|
||||
// ends.
|
||||
func RunMemory(args []string) error {
|
||||
if len(args) > 0 {
|
||||
return fmt.Errorf("magpie mcp memory takes no arguments")
|
||||
}
|
||||
wd, _ := os.Getwd()
|
||||
return serveMemory(os.Stdin, os.Stdout, gatewayBase(), wd)
|
||||
}
|
||||
|
||||
func gatewayBase() string {
|
||||
base := strings.TrimRight(os.Getenv("MAGPIE_GATEWAY"), "/")
|
||||
if base == "" {
|
||||
@@ -94,6 +108,56 @@ func serveVision(in io.Reader, out io.Writer, base string) error {
|
||||
most: 32 << 20, fix: func(b []byte) []byte { return imageFrom(b, wd) }})
|
||||
}
|
||||
|
||||
// serveMemory passes each line to the gateway's memory server, with wd,
|
||||
// the folder the agent started this in, and the client name its
|
||||
// initialize gave.
|
||||
func serveMemory(in io.Reader, out io.Writer, base, wd string) error {
|
||||
var mu sync.Mutex
|
||||
client := ""
|
||||
b := &bridge{base: base, path: gateway.MemoryMCPPath, title: "Magpie Memory", client: &http.Client{Timeout: time.Minute}, out: out}
|
||||
b.fix = func(body []byte) []byte {
|
||||
// read in order, before the calls after it are passed on
|
||||
if name := clientName(body); name != "" {
|
||||
mu.Lock()
|
||||
client = name
|
||||
mu.Unlock()
|
||||
}
|
||||
return body
|
||||
}
|
||||
b.header = func(h http.Header) {
|
||||
if wd != "" {
|
||||
h.Set(gateway.MemoryCwdHeader, wd)
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if client != "" {
|
||||
h.Set(gateway.MemoryClientHeader, client)
|
||||
}
|
||||
}
|
||||
return relay(in, b)
|
||||
}
|
||||
|
||||
// clientName is the client's name an initialize message gives, "" for
|
||||
// any other message.
|
||||
func clientName(b []byte) string {
|
||||
var m struct {
|
||||
Method string `json:"method"`
|
||||
Params struct {
|
||||
ClientInfo struct {
|
||||
Name string `json:"name"`
|
||||
} `json:"clientInfo"`
|
||||
} `json:"params"`
|
||||
}
|
||||
if json.Unmarshal(b, &m) != nil || m.Method != "initialize" {
|
||||
return ""
|
||||
}
|
||||
n := strings.TrimSpace(m.Params.ClientInfo.Name)
|
||||
if len(n) > 64 || strings.ContainsAny(n, "\r\n") {
|
||||
return ""
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// imageFrom is the message b with analyze_image's image, when it is a path
|
||||
// relative to the agent's folder, made absolute against wd: the gateway,
|
||||
// which reads the file, doesn't know the agent's folder, and this process
|
||||
@@ -179,7 +243,8 @@ func relay(in io.Reader, s *bridge) error {
|
||||
// bridge passes one stdio session's messages to the gateway's server at
|
||||
// path, title naming it when the gateway can't be reached; a session ""
|
||||
// sends no session header. most is the longest line it reads (16 MiB when
|
||||
// 0), and fix, when set, makes each message what the gateway is sent.
|
||||
// 0), and fix, when set, makes each message what the gateway is sent;
|
||||
// header, when set, adds to each request's headers.
|
||||
type bridge struct {
|
||||
base, path, title, session string
|
||||
client *http.Client
|
||||
@@ -187,6 +252,7 @@ type bridge struct {
|
||||
out io.Writer
|
||||
most int
|
||||
fix func([]byte) []byte
|
||||
header func(http.Header)
|
||||
}
|
||||
|
||||
func (s *bridge) write(b []byte) {
|
||||
@@ -215,6 +281,9 @@ func (s *bridge) pass(m message, body []byte) {
|
||||
if s.session != "" {
|
||||
r.Header.Set(gateway.BrowserSessionHeader, callerSession(body, s.session))
|
||||
}
|
||||
if s.header != nil {
|
||||
s.header(r.Header)
|
||||
}
|
||||
resp, err := s.client.Do(r)
|
||||
if err != nil {
|
||||
s.fail(m.ID, "magpie isn't running, so "+s.title+" can't be reached: start magpie ("+err.Error()+")")
|
||||
|
||||
@@ -241,3 +241,60 @@ func TestBridgeTakesTheRoutersCaller(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// magpie mcp memory relays each line to the gateway's memory server with
|
||||
// the folder the agent started it in, and, from initialize on, the client
|
||||
// name the agent gave, so the gateway knows the project and the agent.
|
||||
func TestMemoryBridgeSendsFolderAndClient(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
type seen struct{ path, method, cwd, client string }
|
||||
var got []seen
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
var m struct {
|
||||
ID json.RawMessage
|
||||
Method string
|
||||
}
|
||||
json.Unmarshal(b, &m)
|
||||
mu.Lock()
|
||||
got = append(got, seen{r.URL.Path, m.Method, r.Header.Get(gateway.MemoryCwdHeader), r.Header.Get(gateway.MemoryClientHeader)})
|
||||
mu.Unlock()
|
||||
if len(m.ID) == 0 {
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
return
|
||||
}
|
||||
json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": m.ID, "result": map[string]any{}})
|
||||
}))
|
||||
defer srv.Close()
|
||||
in := strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"clientInfo":{"name":"claude-code","version":"2"}}}` + "\n" +
|
||||
`{"jsonrpc":"2.0","method":"notifications/initialized"}` + "\n" +
|
||||
`{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"memory_search","arguments":{"query":"x"}}}` + "\n")
|
||||
var out bytes.Buffer
|
||||
if err := serveMemory(in, &out, srv.URL, "/work/repo"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 3 {
|
||||
t.Fatalf("got %+v", got)
|
||||
}
|
||||
for _, g := range got {
|
||||
if g.path != gateway.MemoryMCPPath || g.cwd != "/work/repo" || g.client != "claude-code" {
|
||||
t.Fatalf("%s sent %+v", g.method, g)
|
||||
}
|
||||
}
|
||||
if n := strings.Count(strings.TrimSpace(out.String()), "\n") + 1; n != 2 {
|
||||
t.Fatalf("out: %q", out.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientName(t *testing.T) {
|
||||
for in, want := range map[string]string{
|
||||
`{"method":"initialize","params":{"clientInfo":{"name":" codex-mcp-client "}}}`: "codex-mcp-client",
|
||||
`{"method":"tools/call","params":{"clientInfo":{"name":"codex"}}}`: "",
|
||||
`{"method":"initialize","params":{"clientInfo":{"name":"a\nb"}}}`: "",
|
||||
`not json`: "",
|
||||
} {
|
||||
if got := clientName([]byte(in)); got != want {
|
||||
t.Errorf("clientName(%s) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -381,6 +381,9 @@ func run(args []string) error {
|
||||
if len(args) > 1 && args[1] == "vision" {
|
||||
return browsermcp.RunVision(args[2:])
|
||||
}
|
||||
if len(args) > 1 && args[1] == "memory" {
|
||||
return browsermcp.RunMemory(args[2:])
|
||||
}
|
||||
return imagemcp.Run(args[1:])
|
||||
case "claude-mcp-helper": // internal: stdio MCP subprocess spawned by Claude Code
|
||||
return claudebridge.RunMCP(args[1:])
|
||||
|
||||
@@ -1099,6 +1099,7 @@ func (s *Server) routes() *routeMux {
|
||||
mux.HandleFunc("/mcp/run/{name}", runMCP)
|
||||
mux.HandleFunc(SearchMCPPath, s.searchMCP)
|
||||
mux.HandleFunc(VisionMCPPath, s.visionMCP)
|
||||
mux.HandleFunc(MemoryMCPPath, s.memoryMCP)
|
||||
mux.HandleFunc(ImageMCPPath, s.imageMCP)
|
||||
mux.HandleFunc(BrowserMCPPath, s.browserMCP)
|
||||
mux.HandleFunc("GET "+BrowserExtensionPath, s.browserExtension)
|
||||
@@ -1142,7 +1143,7 @@ var catalogSize stamped[struct{}, int]
|
||||
|
||||
func (s *Server) info(w http.ResponseWriter, r *http.Request) {
|
||||
out := map[string]any{"name": "magpie", "version": Version, "models": catalogSize.get(struct{}{}, func() int { return len(provider.Catalog()) }), "window": Window,
|
||||
"apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", NativePath + "{provider}/{path}", "/v1/embeddings", "/v1/rerank", "/v1/decisions", "/v1/audio/transcriptions", "/v1/audio/translations", "/v1/audio/speech", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route", StatuslinePath, "/v1/magpie/trace", OwnMCPPath, SearchMCPPath, VisionMCPPath, ImageMCPPath, BrowserMCPPath, ToolsMCPPath, HubMCPAll, HubMCPPath + "{agent}"}}
|
||||
"apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", NativePath + "{provider}/{path}", "/v1/embeddings", "/v1/rerank", "/v1/decisions", "/v1/audio/transcriptions", "/v1/audio/translations", "/v1/audio/speech", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route", StatuslinePath, "/v1/magpie/trace", OwnMCPPath, SearchMCPPath, VisionMCPPath, MemoryMCPPath, ImageMCPPath, BrowserMCPPath, ToolsMCPPath, HubMCPAll, HubMCPPath + "{agent}"}}
|
||||
// which process serves, for another magpie on this computer to name it
|
||||
// on its Routing page (#2606); not told to another machine
|
||||
if local(r) {
|
||||
|
||||
@@ -28,7 +28,7 @@ var keySlotFree = []string{
|
||||
"DELETE " + KeysPath + "/{id}", "POST " + OIDCKeysPath, "POST " + provider.RemoteProvePath,
|
||||
"POST " + RestartPath, "POST " + provider.RemoteUpdatePath, "POST /v1/messages/count_tokens",
|
||||
"POST " + claudeMCPPath + "{token}", "/mcp/{name}", "/mcp/run/{name}", SearchMCPPath, VisionMCPPath,
|
||||
ImageMCPPath, BrowserMCPPath, ImageMCPFiles + "{name}", ToolsMCPPath, ToolsMCPOne + "{plugin}",
|
||||
ImageMCPPath, BrowserMCPPath, MemoryMCPPath, ImageMCPFiles + "{name}", ToolsMCPPath, ToolsMCPOne + "{plugin}",
|
||||
HubMCPPath + "{agent}", HubMCPAll, "/",
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,454 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"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 and memory_forget, Streamable HTTP at MemoryMCPPath, served
|
||||
// and guarded as SearchMCPPath is (serveMCP). 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"
|
||||
)
|
||||
|
||||
const memoryServerName = "magpie-memory"
|
||||
|
||||
func (s *Server) memoryMCP(w http.ResponseWriter, r *http.Request) {
|
||||
serveMCP(w, r, "magpie's memory", memoryServerName, 1<<20, s.memoryMCPCall)
|
||||
}
|
||||
|
||||
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},
|
||||
"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. 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"},
|
||||
},
|
||||
"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},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// 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":
|
||||
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:
|
||||
said, err = memorySearch(c, a)
|
||||
case memorySaveTool:
|
||||
said, err = memorySave(c, a)
|
||||
case memoryForgetTool:
|
||||
said, err = memoryForget(a)
|
||||
default:
|
||||
return nil, map[string]any{"code": -32602, "message": "unknown tool " + p.Name + ": this server has " + memorySearchTool + ", " + memorySaveTool + " and " + memoryForgetTool}
|
||||
}
|
||||
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"`
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// 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 _, name := range []string{extra.Client, r.Header.Get(MemoryClientHeader)} {
|
||||
if c.agent == "" && strings.TrimSpace(name) != "" {
|
||||
c.agent = memoryAgent(usage.AgentOf(name))
|
||||
}
|
||||
}
|
||||
if c.agent == "" {
|
||||
c.agent = memoryAgent(callerOf(r).agent)
|
||||
}
|
||||
if !local(r) {
|
||||
return c
|
||||
}
|
||||
var dirs []string
|
||||
if extra.Roots != nil {
|
||||
// behind the hub: its roots, none when the agent has none
|
||||
dirs = rootDirs(*extra.Roots)
|
||||
} else if d := strings.TrimSpace(r.Header.Get(MemoryCwdHeader)); d != "" {
|
||||
dirs = []string{d}
|
||||
} else {
|
||||
dirs = rootDirs(hubRoots(r, meta))
|
||||
}
|
||||
for _, d := range dirs {
|
||||
if p := memory.ProjectOf(d); p != nil {
|
||||
c.project, c.dir = p, d
|
||||
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(id)
|
||||
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
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
return out, nil
|
||||
case "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.", nil
|
||||
}
|
||||
return "Nothing remembered matches " + quotedQuery(a.Query) + ".", nil
|
||||
}
|
||||
var b strings.Builder
|
||||
for _, h := range hits {
|
||||
b.WriteString(memoryLine(h.Memory, c))
|
||||
b.WriteString("\n")
|
||||
}
|
||||
return strings.TrimSpace(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"
|
||||
case strings.HasPrefix(m.Scope, "project:"):
|
||||
where = "this 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 += ", " + m.Updated.Format(time.DateOnly) + ": " + strings.Join(strings.Fields(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 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 != "" {
|
||||
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), nil
|
||||
}
|
||||
|
||||
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 + "] " + strings.Join(strings.Fields(m.Text), " "), nil
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
)
|
||||
|
||||
// OwnMCPPath lists the MCP servers magpie serves itself (web search,
|
||||
// image recognition, image generation, the plugins' tools) that are on
|
||||
// image recognition, image generation, memory, the plugins' tools) that are on
|
||||
// now, for an app that gives a model the Library's servers and wants
|
||||
// magpie's own beside them: the community chat page (ferock on Discord),
|
||||
// which read only library.json. A server is listed while an agent that
|
||||
@@ -49,6 +49,8 @@ func ownMCP() []OwnMCP {
|
||||
if _, ok := drawer(); ok {
|
||||
out = append(out, OwnMCP{imageServerName, "Magpie Image", ImageMCPPath})
|
||||
}
|
||||
// memory is always there: it needs no model
|
||||
out = append(out, OwnMCP{memoryServerName, "Magpie Memory", MemoryMCPPath})
|
||||
if gwtool.Served(gwtool.PluginTools) {
|
||||
// a note that can't be read says nothing: the server is listed,
|
||||
// and its tools/list tells
|
||||
@@ -82,6 +84,8 @@ func OwnMCPTools(ctx context.Context) []OwnMCPServer {
|
||||
s.Tools = []string{visionMCPTool}
|
||||
case imageServerName:
|
||||
s.Tools = []string{GenerateImageTool, GenerateVideoTool, GenerationResultTool}
|
||||
case memoryServerName:
|
||||
s.Tools = []string{memorySearchTool, memorySaveTool, memoryForgetTool}
|
||||
case "magpie-tools":
|
||||
ts, _ := servedTools(ctx)
|
||||
for _, t := range ts {
|
||||
|
||||
@@ -42,12 +42,11 @@ func toolsAre(t *testing.T, n int) {
|
||||
t.Cleanup(func() { toolsOn = was })
|
||||
}
|
||||
|
||||
// With nothing set up, none of magpie's own servers is listed, and the
|
||||
// list is empty, not null.
|
||||
// With nothing set up, only memory, which needs no model, is listed.
|
||||
func TestOwnMCPNoneWhenNothingIsOn(t *testing.T) {
|
||||
fresh(t)
|
||||
toolsAre(t, 0)
|
||||
if got := ownMCPNames(t, New()); len(got) != 0 {
|
||||
if got := ownMCPNames(t, New()); len(got) != 1 || got[memoryServerName] != MemoryMCPPath {
|
||||
t.Fatalf("listed %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ var readOnlyRefused = []string{
|
||||
// MCP servers, plugins' and Codex's backends, Gemini, everything else
|
||||
"POST " + claudeMCPPath + "{token}", "/mcp/{name}", "/mcp/run/{name}",
|
||||
SearchMCPPath, VisionMCPPath, ImageMCPPath, ImageMCPFiles + "{name}",
|
||||
BrowserMCPPath, "GET " + BrowserExtensionPath, "GET " + BrowserStatusPath, ToolsMCPPath, ToolsMCPOne + "{plugin}",
|
||||
BrowserMCPPath, MemoryMCPPath, "GET " + BrowserExtensionPath, "GET " + BrowserStatusPath, ToolsMCPPath, ToolsMCPOne + "{plugin}",
|
||||
HubMCPPath + "{agent}", HubMCPAll, CodexPath + "/", "GET " + CodexCatalogPath,
|
||||
"GET /v1beta/models", "POST /v1beta/models/{call...}", "/",
|
||||
}
|
||||
|
||||
@@ -40,6 +40,7 @@ var OwnMCPServers = []struct{ Name, Path string }{
|
||||
{"image", ImageMCPPath},
|
||||
{"vision", VisionMCPPath},
|
||||
{"web-search", SearchMCPPath},
|
||||
{"memory", MemoryMCPPath},
|
||||
{"tools", ToolsMCPPath},
|
||||
}
|
||||
|
||||
|
||||
@@ -14,9 +14,10 @@ import (
|
||||
// a temp dir of their own: what they leave in it is theirs, and a skill's
|
||||
// download left there fails the run (#2321).
|
||||
func TestMain(m *testing.M) {
|
||||
// started as magpie's own image or browser server (Args mcp image,
|
||||
// mcp browser): the fake server, for the hub to take it for that one
|
||||
if len(os.Args) >= 3 && os.Args[1] == "mcp" && (os.Args[2] == "image" || os.Args[2] == "browser") {
|
||||
// started as magpie's own image, browser or memory server (Args mcp
|
||||
// image, mcp browser, mcp memory): the fake server, for the hub to
|
||||
// take it for that one
|
||||
if len(os.Args) >= 3 && os.Args[1] == "mcp" && (os.Args[2] == "image" || os.Args[2] == "browser" || os.Args[2] == "memory") {
|
||||
os.Args = []string{os.Args[0], "-test.run=^TestFakeMCPServer$"}
|
||||
}
|
||||
if os.Getenv(testenv.Marker) != "" {
|
||||
|
||||
@@ -99,6 +99,7 @@ var featured = []MarketServer{
|
||||
browserServer(),
|
||||
searchServer(),
|
||||
visionServer(),
|
||||
memoryServer(),
|
||||
remoteServer("context7", "Context7", "Upstash", gh("upstash"), "https://mcp.context7.com/mcp",
|
||||
"Up-to-date documentation and code examples for any library, straight into the prompt.", false,
|
||||
Input{Key: "CONTEXT7_API_KEY", Where: "header", Label: "API key", Description: "Optional — raises the rate limit. From context7.com/dashboard", Secret: true, format: "{}"}),
|
||||
@@ -234,6 +235,21 @@ func visionServer() MarketServer {
|
||||
return m
|
||||
}
|
||||
|
||||
// memoryServerName is the name Magpie Memory's server is written under,
|
||||
// the name the gateway's own memory server goes by (ownMCP).
|
||||
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,
|
||||
// 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
|
||||
// to every agent that can take it.
|
||||
func memoryServer() MarketServer {
|
||||
return localServer(memoryServerName, "Magpie Memory", "Magpie", "https://usemagpie.ai/favicon.png", "https://usemagpie.ai",
|
||||
"Memory shared by every agent: your preferences, rules and what each project needs, kept in Magpie. Agents search it before asking again, and save what you ask them to remember.", magpieCommand, []string{"mcp", "memory"})
|
||||
}
|
||||
|
||||
// selfCommand is the server's command and env for this magpie: its binary
|
||||
// by full path, and the gateway's address when it isn't the default one.
|
||||
func selfCommand(s *Server) {
|
||||
@@ -394,7 +410,7 @@ func serverKey(s *Server) string {
|
||||
if s.Remote() {
|
||||
return strings.TrimSuffix(strings.ToLower(s.URL), "/")
|
||||
}
|
||||
if len(s.Args) == 2 && s.Args[0] == "mcp" && (s.Args[1] == "image" || s.Args[1] == "browser" || s.Args[1] == "search" || s.Args[1] == "vision") {
|
||||
if len(s.Args) == 2 && s.Args[0] == "mcp" && (s.Args[1] == "image" || s.Args[1] == "browser" || s.Args[1] == "search" || s.Args[1] == "vision" || s.Args[1] == "memory") {
|
||||
return "magpie mcp " + s.Args[1] // magpie's own, wherever its binary is
|
||||
}
|
||||
for _, a := range s.Args {
|
||||
|
||||
@@ -473,3 +473,30 @@ func TestMagpieImageRecognitionIsOptIn(t *testing.T) {
|
||||
t.Fatal("vision and search share a key")
|
||||
}
|
||||
}
|
||||
|
||||
// Magpie Memory is offered beside magpie's other servers and, being there
|
||||
// to be shared, is given to every agent that can take it when added; a
|
||||
// copy at another path is the same server.
|
||||
func TestMemoryServerInDiscover(t *testing.T) {
|
||||
sandbox(t)
|
||||
list, err := MarketServers("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !slices.ContainsFunc(list, func(m MarketServer) bool { return m.ID == memoryServerName && !m.OptIn }) {
|
||||
t.Fatalf("%s not in Discover for everyone: %+v", memoryServerName, list)
|
||||
}
|
||||
ok(t)(InstallServer(memoryServerName, nil, nil))
|
||||
l, err := load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := l.server(memoryServerName)
|
||||
if s == nil || len(s.Agents) == 0 || !filepath.IsAbs(s.Command) || strings.Join(s.Args, " ") != "mcp memory" {
|
||||
t.Fatalf("added as %+v", s)
|
||||
}
|
||||
other := Server{Name: "mem", Transport: "stdio", Command: "/opt/other/magpie", Args: []string{"mcp", "memory"}}
|
||||
if serverKey(&other) != serverKey(s) {
|
||||
t.Fatalf("keys %q and %q", serverKey(&other), serverKey(s))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,9 @@ package library
|
||||
// a server started once for every agent can't ask its client for: the
|
||||
// gateway asks the agent for its roots on each call (gateway.HubCaller)
|
||||
// and the call carries them to it, in _meta (imageMeta). An agent in WSL
|
||||
// is given it directly still, run in the distro, whose paths it takes. A
|
||||
// is given it directly still, run in the distro, whose paths it takes.
|
||||
// magpie's memory server (isMemory) is sent the same, for the project and
|
||||
// the agent a memory is kept for. A
|
||||
// server the user keeps direct (Server.Hub, #4382) is each agent's own
|
||||
// too: a command that reads its project from the folder it starts in, or
|
||||
// keeps a session's state. What a server lists is kept until it says its
|
||||
@@ -224,7 +226,17 @@ func hubAbouts(ss []*Server) []gateway.HubServer {
|
||||
// hereOnly is whether s acts as this computer's user beyond what its
|
||||
// tools' arguments say (gateway.HubServer's HereOnly): Magpie Browser and
|
||||
// another magpie's router (keepsSession), and magpie's image server.
|
||||
func hereOnly(s *Server) bool { return keepsSession(s) || isSelf(s) }
|
||||
func hereOnly(s *Server) bool { return keepsSession(s) || isSelf(s) || isMemory(s) }
|
||||
|
||||
// isMemory is whether s is magpie's own memory server (`magpie mcp
|
||||
// memory`), which holds what is known about this computer's user.
|
||||
func isMemory(s *Server) bool {
|
||||
return !s.Remote() && len(s.Args) >= 2 && s.Args[0] == "mcp" && s.Args[1] == "memory"
|
||||
}
|
||||
|
||||
// wantsCaller is whether a call of s is made with the calling agent's
|
||||
// roots and name (imageMeta): magpie's image and memory servers.
|
||||
func wantsCaller(s *Server) bool { return isSelf(s) || isMemory(s) }
|
||||
|
||||
// visitorServers are ss without those the hub's caller of ctx isn't
|
||||
// given (gateway.HubVisitor): the gateway leaves them out too, and this
|
||||
@@ -265,7 +277,7 @@ func (theHub) Tools(ctx context.Context, agentID string) []gateway.HubTool {
|
||||
if json.Unmarshal(t["name"], &name) != nil || name == "" || slices.Contains(s.DisabledTools, name) {
|
||||
continue
|
||||
}
|
||||
lists[i] = append(lists[i], gateway.HubTool{Server: s.Name, Tool: name, Spec: t, Roots: isSelf(s)})
|
||||
lists[i] = append(lists[i], gateway.HubTool{Server: s.Name, Tool: name, Spec: t, Roots: wantsCaller(s)})
|
||||
}
|
||||
}()
|
||||
}
|
||||
@@ -297,7 +309,7 @@ func (theHub) Call(ctx context.Context, agentID, server, tool string, args json.
|
||||
return nil, errors.New("the tool is turned off in magpie's Library")
|
||||
}
|
||||
var meta map[string]any
|
||||
if isSelf(s) {
|
||||
if wantsCaller(s) {
|
||||
meta = imageMeta(gateway.HubCallerOf(ctx))
|
||||
}
|
||||
if c := gateway.HubCallerOf(ctx); c.Session != "" && keepsSession(s) {
|
||||
@@ -325,7 +337,8 @@ func keepsSession(s *Server) bool {
|
||||
return len(s.Args) >= 2 && s.Args[0] == "mcp" && s.Args[1] == "browser"
|
||||
}
|
||||
|
||||
// imageMeta is the _meta a call of magpie's image server is made with:
|
||||
// imageMeta is the _meta a call of magpie's image or memory server is
|
||||
// made with:
|
||||
// the calling agent's roots, which it saves into, and its name, which its
|
||||
// requests go under.
|
||||
func imageMeta(c gateway.HubCaller) map[string]any {
|
||||
|
||||
@@ -715,6 +715,44 @@ func TestHubGivesMagpieImage(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// magpie's memory server is told the calling agent's roots and name, as
|
||||
// the image server is, so a memory is kept for the agent's project and
|
||||
// the agent; another server is told neither.
|
||||
func TestHubTellsMagpieMemoryItsCaller(t *testing.T) {
|
||||
h := hubSandbox(t)
|
||||
write(t, filepath.Join(h, ".claude.json"), `{"mcpServers": {}}`)
|
||||
mem := fakeStdio(t, "ok", nil)
|
||||
mem.Name, mem.Args, mem.Agents = memoryServerName, []string{"mcp", "memory"}, []string{"claude"}
|
||||
ok(t)(SaveServer("", *mem))
|
||||
other := fakeStdio(t, "ok", nil)
|
||||
other.Agents = []string{"claude"}
|
||||
ok(t)(SaveServer("", *other))
|
||||
ok(t)(SetMCPHub(true))
|
||||
hub := theHub{}
|
||||
ctx := context.Background()
|
||||
|
||||
for _, x := range hub.Tools(ctx, "claude") {
|
||||
if x.Roots != (x.Server == memoryServerName) {
|
||||
t.Errorf("%s/%s: roots asked %v", x.Server, x.Tool, x.Roots)
|
||||
}
|
||||
}
|
||||
caller := gateway.WithHubCaller(ctx, gateway.HubCaller{Roots: []string{"file:///work/proj"}, Client: "codex-mcp-client"})
|
||||
res, err := hub.Call(caller, "claude", memoryServerName, "a", json.RawMessage(`{}`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := hubText(t, res); !strings.Contains(got, `meta={"magpie/client":"codex-mcp-client","magpie/roots":["file:///work/proj"]}`) {
|
||||
t.Errorf("memory called as %q", got)
|
||||
}
|
||||
res, err = hub.Call(caller, "claude", "fake", "a", json.RawMessage(`{}`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := hubText(t, res); strings.Contains(got, "meta=") {
|
||||
t.Errorf("another server was told the caller: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The router runs one Magpie Browser for every agent behind it, so each
|
||||
// call names its caller's session in _meta, for the browser to keep each
|
||||
// caller in a tab of its own; another server is sent no session, and a
|
||||
@@ -836,6 +874,7 @@ func TestHubKeepsThisComputersOwnServersHere(t *testing.T) {
|
||||
}{
|
||||
{Server{Transport: "stdio", Command: "magpie", Args: []string{"mcp", "browser"}}, true, true},
|
||||
{Server{Transport: "stdio", Command: "magpie", Args: []string{"mcp", "image"}}, true, true},
|
||||
{Server{Transport: "stdio", Command: "magpie", Args: []string{"mcp", "memory"}}, true, true},
|
||||
{Server{Transport: "http", URL: "http://10.0.0.2:3425/mcp/magpie/hub"}, true, false},
|
||||
{Server{Transport: "stdio", Command: "npx", Args: []string{"server-filesystem"}}, false, true},
|
||||
{Server{Transport: "http", URL: "https://mcp.example.com/mcp"}, false, false},
|
||||
|
||||
Reference in New Issue
Block a user