diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index 69ba82134..a5f9df9be 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -69,6 +69,7 @@ Pi's extensions and packages. - A copy's mark establishes that it is unchanged only after its whole folder was scanned. If a subtree or its metadata can't be read, the copy stays in place and the sync reports a `Problem`; it isn't replaced, relinked or removed. A later sync tries again once it can be read. The same scan failure stops replacing a project's or Claude Desktop's copy. - A failure for one agent is a `Problem` in the result. It doesn't stop the others. - LiveAgent (zero2sin on Discord) keeps its MCP servers in K-brain's `config.json.live-mcp.json` beside its `config.json`, in the folder `agent.liveAgentDir` finds: a list of servers by `id`, each `enabled` and `stdio` or `http` (streamable HTTP only, so SSE is refused). Until that file is there K-brain reads `config.json`'s `mcp` object, so magpie's first write carries those servers over. A non-empty `selected` is the only servers LiveAgent uses, so magpie adds its server there and takes it out again, never the last one. The app holds the list in memory once started, so a change is seen at its next start. Its skills folder takes copies, as K-brain refuses a link, and a skill there is used only once picked in `skills-settings.json`: `syncLiveAgentPicks` picks each copy magpie makes once (`Applied.Picked`), so one the user unpicks stays unpicked, and unpicks it when the copy goes. A name K-brain refuses (lowercase letters, digits and single hyphens, up to 64) is copied but never picked. Its built-in `skills-creator` and `skills-installer` are not offered to bring in (`liveagent.go`, `TestLiveAgentMCP`, `TestLiveAgentSkills`). +- OpenClaw (JeffreyCalm on X) keeps its MCP servers under `mcp.servers` in the `openclaw.json` magpie sets its model in (`agent.openClawPaths`), and takes a change there without a restart. A url with no `transport` is SSE to OpenClaw, so a streamable HTTP server, the MCP router's `magpie` entry among them, is written with `transport: "streamable-http"`. OpenClaw refuses the whole file over a key it doesn't know (`openclaw config validate`), so an entry holds only its own keys: magpie's slow servers get `requestTimeoutMs` (OpenClaw's default is a minute), never a `timeout`. An unset `${NAME}` anywhere in the file fails it too, so a server that references a variable isn't given to OpenClaw (`envref.go`). `enabled`, `cwd`, the timeouts, `auth`, `oauth`, `toolFilter` and the TLS keys are the user's (`TestOpenClawMCP`, `TestOpenClawMCPHub`). - An MCP OAuth sign-in canceled or timed out before its callback commits never saves a late token or changes an existing sign-in. The callback's write and the flow's ending share a lock (`flow.keep` in [`mcpauth.go`](../../internal/mcpauth/mcpauth.go)); if the write wins first, it completes and tells the agents before saying done. A cancellation is not a sign-out of credentials already committed. - A server an agent can't reach is not written there, and `mcpFile.supports` says why. For example, Claude Desktop takes no remote server, and Codex, Goose, dsh, Grok, Command Code and Zed take no SSE. - A server's headers (remote) or environment (command) can name a variable as `${NAME}` (#1250). `library.json` keeps the placeholder, and `refsOf` gives each MCP format the agent's own syntax, with the agent's source cited beside it: `${NAME}` for most, `{env:NAME}` for OpenCode and MiMo, `${env:NAME}` for Cursor, and Codex's own keys (`bearer_token_env_var`, `env_http_headers`, `env_vars`). Goose gets `${NAME}` plus `env_keys`. dsh (DeepSeek Harness) gets a `!!js` expression it evaluates as it loads the server (#1435): a whole `${NAME}` is `!!js process.env.NAME`, and a value mixing text and variables is the text as JSON string literals joined with `(process.env.NAME ?? "")`, so the user's text is never run as code and an unset variable inside it is empty. A whole variable that isn't set makes dsh leave the server out as invalid. magpie reads only those forms back as `${NAME}`; any other `!!js` keeps the entry the user's. An agent with no syntax (Claude Desktop, Antigravity, Kimi, Cline, ZCode, Zed, Devin, Alma, Pi with pi-mcp-extension) is never written the value: `refsProblem` makes `supports` refuse the server, a magpie entry already there is taken out, and `AgentView.NoEnvRefs` greys its chip with the reason. Codex and Goose's extra keys are magpie's only while the server names a variable there (`refKeys`), so the user's own `env_vars` or `env_keys` are kept. `CheckServers`, the router (`dialHub`) and Codex's run through the gateway (`specOf`) expand the variable in memory (`expandAll`): from magpie's own environment, else from what a terminal opened now has (`proc.LoginVars`: what the login shell, or fish or nushell, exports, kept a minute; the registry's user then machine variables on Windows), since a magpie opened from the Finder has none of the profile's variables and a server whose token was exported in .zshrc showed no tools (Cyrus on Discord, `TestEnvRefsFromLoginShell`, `TestLoginVars`). The value is never set in magpie's environment, written to library.json or an agent's file, or logged. One set nowhere is `novar`, naming it. The page paints that as not checked (a ring, `lib-health unknown`), not red: it says nothing of the server, which the agent may start with the variable set, as Codex does its host-only `codex_app` (#2308). It starts a command server in home, with `PWD` set to it (not on Windows), as an agent started from home would, never in magpie's own working folder: a magpie started from the Windows Start menu has `C:\Windows\system32`, where a server that writes into `.` exits before it answers (#1727, `TestCheckStdio`). diff --git a/internal/library/envref.go b/internal/library/envref.go index fabc8be9a..ca348d9aa 100644 --- a/internal/library/envref.go +++ b/internal/library/envref.go @@ -201,7 +201,10 @@ func (f *mcpFile) refsOf() envSyntax { // Alma // 0.4.164 JSON.parses mcp.json and hands a command its env and a url // its headers as written (out/main/index.js createStdioTransport, - // connectRemoteServer). Devin's docs name ${env:NAME} for OAuth + // connectRemoteServer). OpenClaw expands ${NAME} anywhere in + // openclaw.json as it loads it, but an unset or empty one fails the + // whole file, every setting with it (docs/gateway/configuration.md), + // so a server that references one isn't written there. Devin's docs name ${env:NAME} for OAuth // fields only (extensibility/mcp/configuration.mdx), so its headers // and env aren't known to read one. return envSyntax{} diff --git a/internal/library/every_agent_test.go b/internal/library/every_agent_test.go index d4a7f0832..359f9d194 100644 --- a/internal/library/every_agent_test.go +++ b/internal/library/every_agent_test.go @@ -32,7 +32,6 @@ var noLibrary = map[string]string{ "ante": "not looked at (#5897)", "astrbot": "not looked at (#5897)", "qwenpaw": "not looked at (#5897)", - "openclaw": "not looked at (#5897)", "pencil": "not looked at (#5897)", "openpencil": "not looked at (#5897)", "newmax": "not looked at (#5897)", diff --git a/internal/library/mcp.go b/internal/library/mcp.go index b91816be8..7300d1174 100644 --- a/internal/library/mcp.go +++ b/internal/library/mcp.go @@ -309,6 +309,10 @@ const ( // config.json.live-mcp.json: a list of servers, each by its id, stdio // or streamable HTTP (liveagent.go) fmtLiveAgent + // fmtOpenClaw is OpenClaw's openclaw.json mcp.servers: command/args/ + // env, or url/headers with a transport, where a url with none is SSE + // (OpenClaw 2026.11.6 docs/cli/mcp.md, McpServerSchema) + fmtOpenClaw ) // mcpFile is the file an agent keeps its user-wide MCP servers in. @@ -349,7 +353,7 @@ func (f *mcpFile) key() string { return "mcp" case fmtGoose: return "extensions" - case fmtZCode: + case fmtZCode, fmtOpenClaw: return "mcp.servers" case fmtZed: return "context_servers" @@ -753,6 +757,30 @@ func (f *mcpFile) encode(s *Server) ordered { add("transport", "stdio") } } + case fmtOpenClaw: + // as `openclaw mcp set` takes one: a url with no transport is + // SSE to OpenClaw, so streamable HTTP is named, and `type: "http"` + // is an alias its doctor rewrites (docs/cli/mcp.md) + if s.Remote() { + add("url", s.URL) + t := "streamable-http" + if s.Transport == "sse" { + t = "sse" + } + add("transport", t) + optional("headers", s.Headers) + } else { + add("command", s.Command) + add("args", list(s.Args)) + optional("env", s.Env) + } + // OpenClaw gives a request a minute unless the entry says more + // (mcp-transport-config DEFAULT_REQUEST_TIMEOUT_MS); every other + // key fails the whole file (`openclaw config validate`), timeout + // among them + if t := selfTimeout(s, 0); t > 0 { + add("requestTimeoutMs", t*1000) + } case fmtKiro: // as the docs show them: command/args/env, or url/headers — no // type, the entry's shape saying which (kiro.dev/docs/mcp/ @@ -1077,6 +1105,23 @@ func (f *mcpFile) decode(name string, m map[string]any) (*Server, bool) { } else { local(str(m, "command"), m["args"], m["env"]) } + case fmtOpenClaw: + // streamable HTTP when the transport (or the type alias `openclaw + // mcp set` also takes) says so, else SSE: a url with no transport + // is SSE to OpenClaw (mcp-config-normalize.ts) + if u := str(m, "url"); u != "" { + named := str(m, "transport") + if named == "" { + named = str(m, "type") + } + t := "sse" + if n := strings.ToLower(strings.TrimSpace(named)); n == "streamable-http" || n == "http" { + t = "http" + } + remote(t, u, m["headers"]) + } else { + local(str(m, "command"), m["args"], m["env"]) + } case fmtLiveAgent: // K-brain's transport, or a url's or a command's when there is // none (normalizeLiveSettings); its http is streamable HTTP alone @@ -1380,6 +1425,10 @@ var owned = map[mcpFormat][]string{ // enabled, and the id's description, docsUrl, cwd, timeoutMs, // workspaceRoots, policy and auth, are the user's fmtLiveAgent: {"transport", "url", "headers", "command", "args", "env"}, + // enabled, cwd, the timeouts, auth, oauth, toolFilter, sslVerify and + // the client certificate are the user's; a type is the alias OpenClaw + // rewrites to transport + fmtOpenClaw: {"transport", "type", "url", "headers", "command", "args", "env"}, // a url agy read in place of serverUrl goes when magpie writes one fmtAntigravity: {"type", "serverUrl", "url", "headers", "command", "args", "env"}, diff --git a/internal/library/openclaw_mcp_test.go b/internal/library/openclaw_mcp_test.go new file mode 100644 index 000000000..dbc82bca4 --- /dev/null +++ b/internal/library/openclaw_mcp_test.go @@ -0,0 +1,196 @@ +package library + +import ( + "encoding/json" + "errors" + "path/filepath" + "strings" + "testing" + + "github.com/yetone/magpie/internal/gateway" +) + +// openClawSandbox is a sandbox with OpenClaw installed: its program and +// its ~/.openclaw/openclaw.json holding the user's own settings and server. +func openClawSandbox(t *testing.T) (h, p string) { + h = hubSandbox(t) + holdCLI(t, h, "openclaw") + p = filepath.Join(h, ".openclaw", "openclaw.json") + write(t, p, `{ + "gateway": {"mode": "local"}, + "mcp": { + "sessionIdleTtlMs": 60000, + "servers": { + "mine": { + "command": "uvx", + "args": ["mine-mcp"], + "requestTimeoutMs": 30000, + "toolFilter": {"include": ["read"]} + } + } + } +}`) + return h, p +} + +func openClawServers(t *testing.T, p string) map[string]map[string]any { + t.Helper() + var f struct { + MCP struct { + Servers map[string]map[string]any `json:"servers"` + } `json:"mcp"` + } + if err := json.Unmarshal([]byte(read(t, p)), &f); err != nil { + t.Fatalf("%v:\n%s", err, read(t, p)) + } + return f.MCP.Servers +} + +// OpenClaw had no Library target, so neither a server nor the MCP router's +// magpie entry could be given to it (JeffreyCalm on X). It keeps its +// servers under mcp.servers in openclaw.json, where a url with no transport +// is SSE: streamable HTTP has to be named (OpenClaw 2026.11.6 +// docs/cli/mcp.md, McpServerSchema). +func TestOpenClawMCP(t *testing.T) { + _, p := openClawSandbox(t) + tg := targetByID("openclaw") + if tg == nil || tg.MCP == nil { + t.Fatalf("openclaw has no MCP target: %+v", tg) + } + if tg.MCP.Path != p || tg.MCP.Format != fmtOpenClaw { + t.Errorf("mcp: %+v", tg.MCP) + } + if id, err := Takes("openclaw", "mcp"); id != "openclaw" || err != nil { + t.Errorf("Takes(openclaw, mcp): %q %v", id, err) + } + + agents := []string{"openclaw"} + stdio := Server{Name: "fs", Transport: "stdio", Command: "npx", Args: []string{"-y", "@mcp/fs"}, Env: map[string]string{"K": "V"}, Agents: agents} + web := Server{Name: "web", Transport: "http", URL: "https://example.com/mcp", Headers: map[string]string{"X-Team": "a"}, Agents: agents} + old := Server{Name: "old", Transport: "sse", URL: "https://example.com/sse", Agents: agents} + for _, s := range []Server{stdio, web, old} { + ok(t)(SaveServer("", s)) + } + + got := openClawServers(t, p) + if fs := got["fs"]; fs["command"] != "npx" || fs["transport"] != nil || fs["type"] != nil { + t.Errorf("fs: %v", fs) + } else if e, _ := fs["env"].(map[string]any); e["K"] != "V" { + t.Errorf("fs env: %v", fs) + } + if w := got["web"]; w["url"] != "https://example.com/mcp" || w["transport"] != "streamable-http" { + t.Errorf("web, streamable HTTP named so OpenClaw doesn't take it for SSE: %v", w) + } else if hd, _ := w["headers"].(map[string]any); hd["X-Team"] != "a" { + t.Errorf("web headers: %v", w) + } + if o := got["old"]; o["transport"] != "sse" { + t.Errorf("old: %v", o) + } + if m := got["mine"]; m["command"] != "uvx" || m["requestTimeoutMs"] != float64(30000) || m["toolFilter"] == nil { + t.Errorf("the user's server and its fields kept: %v", m) + } + for _, want := range []string{`"sessionIdleTtlMs": 60000`, `"mode": "local"`} { + if !strings.Contains(read(t, p), want) { + t.Errorf("lost the user's %s:\n%s", want, read(t, p)) + } + } + + // read back, and left as they are by a sync that changes nothing + back, err := tg.MCP.read() + if err != nil { + t.Fatal(err) + } + for _, want := range []Server{stdio, web, old} { + if s := back[want.Name]; s == nil || !s.same(&want) { + t.Errorf("%s read back as %+v", want.Name, s) + } + } + before := read(t, p) + ok(t)(Sync()) + if read(t, p) != before { + t.Errorf("a sync rewrote servers that are as the library has them:\n%s", read(t, p)) + } + + // how OpenClaw reads a url: no transport is SSE, and `type: "http"` + // is the alias its doctor rewrites to streamable-http + for _, c := range []struct { + m map[string]any + want string + }{ + {map[string]any{"url": "https://e/x"}, "sse"}, + {map[string]any{"url": "https://e/x", "transport": "sse"}, "sse"}, + {map[string]any{"url": "https://e/x", "transport": "streamable-http"}, "http"}, + {map[string]any{"url": "https://e/x", "type": "http"}, "http"}, + } { + if s, _ := tg.MCP.decode("x", c.m); s == nil || s.Transport != c.want { + t.Errorf("%v read as %+v, want %s", c.m, s, c.want) + } + } + + // magpie's own slow servers get OpenClaw's own key for more than its + // minute; a "timeout" would fail the whole file + o := tg.MCP.encode(&Server{Name: searchServerName, Transport: "stdio", Command: "/x/magpie", Args: []string{"mcp", "search"}}) + keys := map[string]any{} + for _, e := range o { + keys[e.k] = e.v + } + if keys["requestTimeoutMs"] != 120000 || keys["timeout"] != nil { + t.Errorf("magpie-web-search: %v", o) + } + + // an unset ${NAME} anywhere in openclaw.json fails the whole file, so + // a server referencing one isn't written there + ref := Server{Transport: "http", URL: "https://example.com/mcp", Headers: map[string]string{"Authorization": "Bearer ${TOKEN}"}} + if err := tg.MCP.supports(&ref); !errors.Is(err, errNoEnvRef) { + t.Errorf("a ${NAME} header: %v", err) + } + + for _, s := range []string{"fs", "web", "old"} { + ok(t)(RemoveServer(s)) + } + after := openClawServers(t, p) + if len(after) != 1 || after["mine"]["toolFilter"] == nil { + t.Errorf("after: %v\n%s", after, read(t, p)) + } +} + +// With the MCP router on, OpenClaw is given magpie's one entry, streamable +// HTTP at the hub, in place of the servers it was given, and its own +// server is left as it is (JeffreyCalm on X: the router couldn't be turned +// on for it). +func TestOpenClawMCPHub(t *testing.T) { + _, p := openClawSandbox(t) + ok(t)(SaveServer("", Server{Name: "fs", Transport: "stdio", Command: "npx", Args: []string{"-y", "fs"}, Agents: []string{"openclaw"}})) + r, err := SetMCPHub(true) + if err != nil { + t.Fatal(err) + } + for _, pr := range r.Problems { + if pr.Agent == "openclaw" { + t.Errorf("problem: %+v", pr) + } + } + got := openClawServers(t, p) + hub := got[HubEntry] + if u, _ := hub["url"].(string); !strings.HasSuffix(u, gateway.HubMCPPath+"openclaw") || hub["transport"] != "streamable-http" { + t.Errorf("openclaw's magpie entry: %v\n%s", hub, read(t, p)) + } + if got["fs"] != nil || got["mine"] == nil { + t.Errorf("with the hub on: %v", got) + } + v, err := Read(nil) + if err != nil { + t.Fatal(err) + } + for _, a := range v.Agents { + if a.ID == "openclaw" && a.Hub != "on" { + t.Errorf("openclaw's hub %q, want on", a.Hub) + } + } + + ok(t)(SetMCPHub(false)) + got = openClawServers(t, p) + if got[HubEntry] != nil || got["fs"] == nil || got["mine"] == nil { + t.Errorf("with the hub off again: %v\n%s", got, read(t, p)) + } +} diff --git a/internal/library/targets.go b/internal/library/targets.go index cf8b8a614..1b80e0ac8 100644 --- a/internal/library/targets.go +++ b/internal/library/targets.go @@ -630,6 +630,13 @@ func targetOf(a *agent.Agent) *Target { t.MCP = &mcpFile{Path: filepath.Join(a.Dir, liveAgentMCP), Format: fmtLiveAgent} t.Skills = filepath.Join(a.Dir, "skills") t.Copy = true + case "openclaw": + // OpenClaw keeps its MCP servers under mcp.servers in the + // openclaw.json magpie sets its model in (agent.openClawPaths), + // and takes a change to mcp without a restart (OpenClaw + // 2026.11.6 docs/cli/mcp.md, config-reload-plan "mcp" hot; + // JeffreyCalm on X) + t.MCP = &mcpFile{Path: a.Path, Format: fmtOpenClaw} case "claude-desktop": // Claude Desktop reads only commands from its file: a remote server // is added in its own Connectors settings. In its 3p mode (magpie's