diff --git a/docs/subsystems/mcp-hub.md b/docs/subsystems/mcp-hub.md index 1973345f6..bde6f4614 100644 --- a/docs/subsystems/mcp-hub.md +++ b/docs/subsystems/mcp-hub.md @@ -7,15 +7,15 @@ With the Library's switch "MCP hub" on (#2679, @minggang123 on X), each agent is | Part | Responsibility | Source | | --- | --- | --- | | Switch | `Library.MCPHub` (`mcpHub` in library.json) is the source of truth. `SetMCPHub` sets it through `change`, so every agent is synced at once; turning it off also ends every server the hub started (`hubStopAll`). The page posts `servers/hub` `{on}`. | `SetMCPHub` in [`mcp_hub.go`](../../internal/library/mcp_hub.go); `servers/hub` in [`gui/library.go`](../../internal/gui/library.go) | -| Entry | `syncMCP` gives an agent `hubServerFor(t)`, named `magpie` (`HubEntry`), in place of each server it would have written, and records it in `Applied.MCP` like any server, so turning the switch off takes out only that entry and writes each server's own again. The URL is the gateway as that agent reaches it (`gatewayOf`), so a WSL distro or a LAN computer gets its address, with `Authorization: Bearer ` when that address needs a key (`agent.KeyAt`). A LAN key or relay change re-syncs (`LANChanged`). magpie's own image server (`isSelf`) is never put behind the hub. | `hubFor`, `hubServerFor`, `inHub` in `mcp_hub.go`; `syncMCP` in [`sync.go`](../../internal/library/sync.go); [`mcp_signin.go`](../../internal/library/mcp_signin.go) | +| Entry | `syncMCP` gives an agent `hubServerFor(t)`, named `magpie` (`HubEntry`), in place of each server it would have written, and records it in `Applied.MCP` like any server, so turning the switch off takes out only that entry and writes each server's own again. The URL is the gateway as that agent reaches it (`gatewayOf`), so a WSL distro or a LAN computer gets its address, with `Authorization: Bearer ` when that address needs a key (`agent.KeyAt`). A LAN key or relay change re-syncs (`LANChanged`). magpie's own image server (`isSelf`) is never put behind the hub, nor is a server the user keeps direct (`Server.Hub` = `direct`, `hub` in library.json; #4382, cuipengcx90): each agent given it keeps its own entry, written as with the hub off, beside the hub's entry for the rest; an agent whose every server is direct is given no hub entry. `inHub` is the one test, so the hub neither lists nor runs a direct server, at `/mcp/magpie/hub` either, and `hubPrune` ends one it held. The default (`""`; `shared` is saved as `""`) is the hub's as before. Switching it (`ServerHub`, or a save) goes through `change`, so each agent is written again at once and the entry it had the other way is taken out (`TestHubDirectServer`). The policy is the server's, so a sync carries it. A per-project or per-session backend behind the hub (Option B in #4382, keying `hubPool` by roots) is not built. | `hubFor`, `hubServerFor`, `inHub` in `mcp_hub.go`; `syncMCP` in [`sync.go`](../../internal/library/sync.go); [`mcp_signin.go`](../../internal/library/mcp_signin.go) | | Who keeps their entries | An agent keeps each server's own entry, and `AgentView.Hub` says why: `no-remote` (it reaches no server over HTTP: `mcpFile.supports` refuses the entry, as for Claude Desktop), `taken` (a Library server is itself called magpie), `own` (the agent has an entry called magpie that magpie didn't write; it is left as it is). `on` is an agent given the hub's entry. An agent given none of the hub's servers has no value. | `hubFor` in `mcp_hub.go`; `AgentView.Hub`, `View.MCPHub`, `View.HubPath` in `sync.go` | | Serve | `tools/list` lists the tools of the servers ticked for that agent (at `/mcp/magpie/hub`, agent `""`: every server in the Library, ticked for any agent or none), but those in `DisabledTools`, as `__`: each part in `[A-Za-z0-9_-]` (other characters `_`), at most 64 characters (`cutName`), `_2`, `_3` on a name two would share. Each tool's description and `inputSchema` go on as the server listed them (an object schema with no properties when it has none). `tools/call` runs one; an unknown name, or another agent's, is error -32602. `initialize` and `ping` are answered; other methods are -32601. Tools only: no resources or prompts. | `hubMCPCall`, `hubNamed` in [`hub_mcp.go`](../../internal/gateway/hub_mcp.go) | | Guard | `serveMCP`, as `/mcp/magpie/tools`: a local request, or one with a gateway key; a browser page's Origin that `corsAllowed` doesn't allow is 403; POST only; a 4 MiB body (`hubBody`). The outer `lanGuard`/`corsGuard` already refuse `Origin: null`, a foreign site and a rebound Host. Each call is held to the calling key's limit (`reserveFor`) before anything runs. | `hubMCP`, `hubMCPRun` in `hub_mcp.go`; `serveMCP` in [`search_mcp.go`](../../internal/gateway/search_mcp.go) | | Backends | One `backend` per Library server, shared by every agent (`hubPool`, keyed by the server's name; an edit or a sign-in since makes it a new one and ends the old). A command is started as `CheckServers` starts one (`startServer`: `proc` tree, home as its folder, `${NAME}` env expanded), on its first list or call, and initialized once. A URL (`http`, `sse`) is reached with its headers and the Library's MCP sign-in (`mcpauth`), and a session the server forgot is opened again once. A `notifications/tools/list_changed` from a server makes the next list ask it again. | `backendOf`, `connect`, `dialHub`, `dialStdio`, `dialSSE`, `dialHTTP` in `mcp_hub.go`; `startServer`, `httpSession` in [`mcp_check.go`](../../internal/library/mcp_check.go) | | Lifetime | A server with no call for `hubIdle` (10 minutes) is ended; the tools it listed are kept, so a list doesn't start it again, and the next call does. A command that died is started again on the next call. Turning the switch off, an edit, and the gateway stopping (`StopHub` on drain) end them: stdin closed, then the process tree. The switch can be turned off, or a server edited or unticked, by another magpie (the window while `magpie serve` runs, the CLI), and an agent given each server's own entry again never asks the hub, so the serving gateway also prunes every `hubPruneEvery` (5s) while it holds a server: each one the library no longer has as it was started, or every one once the switch is off, is ended (`hubPrune`). A server ticked for no agent is still served at `/mcp/magpie/hub`, so it is kept. | `use`, `done`, `stop`, `hubStopAll`, `hubPrune` in `mcp_hub.go`; `StopHub`, `keepHubPruned` in `hub_mcp.go` | -| GUI | Below the server list in the Library's MCP tab: a row with the switch (`.lib-switch`, role=switch) saying what it does; on, a line counting what it serves (`.lib-hubstats`: servers, tools, the agents given it), then a row "Other apps" with the address (`.lib-hubURL`, copied with a click) and Connect…, and under them the agents that keep their own entries, grouped by why (`.lib-hub-why[data-why]`). The address is `mcpAddress`: the public one in a browser, the gateway in the app. Connect… opens a sheet (`connectHub`, `.lib-hubsheet`) of two tabs. Agents: agents → magpie → servers, drawn as icons with magpie's bird in the middle, a line of where things stand, then every agent `mcpAgents` lists (each detected, shown agent that takes MCP servers) in groups (`.lib-hubgrp[data-group]`): `off` (not connected), `on` (connected), `kept` (keeps each server's own entry). Each row (`.lib-hubagent[data-state]`: `on`, `none`, `own`, `taken`, `no-remote`) has a switch that posts `servers/agents-all` `{agents:[id], on}`, as By agent's Turn all on/off does: on gives it every Library server, so `hubFor` gives it the entry; off takes every Library server from it. A kept agent has a word for why and the reason in full behind (i) (`.lib-hubinfo`, `.lib-hubwhy`); an agent that reaches no server over HTTP says so even with none ticked. Connect all (`.lib-huball`) posts every `none` agent at once. With more than 8 agents a search (`.lib-hubsearch`) narrows every group, and the connected and the kept fold to one row each (`.lib-hubfolded`) until unfolded. The sheet stays open while it changes, and an agent is never handed to the user as a command to run. Other apps: the address (`.lib-hubaddr`), and a row per app (`.lib-hubapp[data-app]`): Cursor (only when it isn't one of the agents), VS Code, Windsurf and any JSON app, each with where its entry goes and a Copy entry (`.lib-hubcopy`) that copies its JSON. In the app, Cursor and VS Code also get Add (`.lib-hubadd`): the page posts `servers/hub-open` `{app}` and the window opens that app's install link (`HubLink`), which the app asks the user to confirm. The page never sends a link; an app with none is an error, and nothing is opened. In a browser there is no Add. | `hubPart`, `hubStats`, `connectHub` in [`client.js`](../../internal/gui/assets/plugins/library/client.js), [`library.css`](../../internal/gui/assets/plugins/library/library.css), [`i18n.js`](../../internal/gui/assets/plugins/library/i18n.js); `HubLink` in `mcp_hub.go`; `servers/hub-open` in `gui/library.go` | +| GUI | Below the server list in the Library's MCP tab: a row with the switch (`.lib-switch`, role=switch) saying what it does; on, a line counting what it serves (`.lib-hubstats`: servers, tools, the agents given it), then a row "Other apps" with the address (`.lib-hubURL`, copied with a click) and Connect…, and under them the agents that keep their own entries, grouped by why (`.lib-hub-why[data-why]`). The address is `mcpAddress`: the public one in a browser, the gateway in the app. Connect… opens a sheet (`connectHub`, `.lib-hubsheet`) of two tabs. Agents: agents → magpie → servers, drawn as icons with magpie's bird in the middle, a line of where things stand, then every agent `mcpAgents` lists (each detected, shown agent that takes MCP servers) in groups (`.lib-hubgrp[data-group]`): `off` (not connected), `on` (connected), `kept` (keeps each server's own entry). Each row (`.lib-hubagent[data-state]`: `on`, `none`, `own`, `taken`, `no-remote`) has a switch that posts `servers/agents-all` `{agents:[id], on}`, as By agent's Turn all on/off does: on gives it every Library server, so `hubFor` gives it the entry; off takes every Library server from it. A kept agent has a word for why and the reason in full behind (i) (`.lib-hubinfo`, `.lib-hubwhy`); an agent that reaches no server over HTTP says so even with none ticked. Connect all (`.lib-huball`) posts every `none` agent at once. With more than 8 agents a search (`.lib-hubsearch`) narrows every group, and the connected and the kept fold to one row each (`.lib-hubfolded`) until unfolded. The sheet stays open while it changes, and an agent is never handed to the user as a command to run. Other apps: the address (`.lib-hubaddr`), and a row per app (`.lib-hubapp[data-app]`): Cursor (only when it isn't one of the agents), VS Code, Windsurf and any JSON app, each with where its entry goes and a Copy entry (`.lib-hubcopy`) that copies its JSON. In the app, Cursor and VS Code also get Add (`.lib-hubadd`): the page posts `servers/hub-open` `{app}` and the window opens that app's install link (`HubLink`), which the app asks the user to confirm. The page never sends a link; an app with none is an error, and nothing is opened. In a browser there is no Add. With the hub on, the server editor has a switch "Through the MCP hub" (on for shared; not shown for magpie's own image server or with the hub off) saved as `hub`, a direct server's row has a tag (`.lib-tag.lib-direct`), and the line under the switch and the sheet name the direct servers with the image server as given directly (`inHub`, `directNames` in client.js; `mcp-hub-direct.test.cjs`). The TUI keeps the policy on edit. | `hubPart`, `hubStats`, `connectHub` in [`client.js`](../../internal/gui/assets/plugins/library/client.js), [`library.css`](../../internal/gui/assets/plugins/library/library.css), [`i18n.js`](../../internal/gui/assets/plugins/library/i18n.js); `HubLink` in `mcp_hub.go`; `servers/hub-open` in `gui/library.go` | -The CLI's `magpie library mcp hub on|off` calls `SetMCPHub`, and `magpie library` lists the agents given magpie's entry and those that keep their own, with why (`libraryStatus` in [`library_cli.go`](../../internal/cli/library_cli.go)). +The CLI's `magpie library mcp hub on|off` calls `SetMCPHub`, and `magpie library mcp hub shared|direct` calls `ServerHub`. `magpie library` lists the agents given magpie's entry and those that keep their own, with why (`libraryStatus` in [`library_cli.go`](../../internal/cli/library_cli.go)). The gateway can't import the library (the library imports the gateway), so the gateway declares `Hub` and `MCPHub`, and the library sets `MCPHub` in its `init`. @@ -46,7 +46,7 @@ go test -tags nogui ./internal/gui -run TestHubOpen go test -tags nogui ./internal/library -run 'TestHub|TestFakeMCPServer|TestCheck|TestPluginTools' go test -tags nogui ./internal/gateway -run 'HubMCP|OwnMCPRejects' -timeout 45m go test -tags nogui ./internal/cli -run TestLibraryMCPHub -node --test internal/gui/tests/library-mcp-hub.test.cjs +node --test internal/gui/tests/library-mcp-hub.test.cjs internal/gui/tests/mcp-hub-direct.test.cjs ``` The library tests run a fake stdio MCP server (`TestFakeMCPServer` in [`mcp_check_test.go`](../../internal/library/mcp_check_test.go): a tool that dies, one that never answers) and an `httptest` Streamable HTTP one (`mcpHandler`). The gateway tests use a fake `Hub`. diff --git a/internal/cli/library_cli.go b/internal/cli/library_cli.go index 57fc39f68..64ee6ef43 100644 --- a/internal/cli/library_cli.go +++ b/internal/cli/library_cli.go @@ -25,6 +25,8 @@ const libraryUsage = `magpie library what the library gives coming in neither takes it away nor puts another computer's in its place magpie library mcp rm magpie library mcp hub on|off give each agent one MCP server, magpie, in place of the library's (magpie runs them, once for every agent) + magpie library mcp hub shared|direct with the hub on, share the server through it (the default) or keep it each + agent's own entry, as with the hub off: for one that reads its project from the folder it starts in magpie library skill agents magpie library skill off-here turn it off on this computer only: a sync neither carries that nor turns it back on magpie library skill on-here …and on again here @@ -141,6 +143,9 @@ func libraryCmd(args []string) error { res, err = library.RemoveServer(rest[1]) case len(rest) == 2 && rest[0] == "hub" && (rest[1] == "on" || rest[1] == "off"): res, err = library.SetMCPHub(rest[1] == "on") + case len(rest) == 3 && rest[0] == "hub" && (rest[2] == "shared" || rest[2] == "direct") && !strings.HasPrefix(rest[1], "-"): + // a server out of the hub, each agent's own entry (#4382) + res, err = library.ServerHub(rest[1], rest[2] == "direct") default: return fmt.Errorf("usage:\n %s", libraryUsage) } @@ -445,6 +450,9 @@ func libraryStatus() error { if s.Local { fmt.Println(" ", muted.Render("this computer only: a sync never carries it · magpie library mcp local "+s.Name+" off")) } + if s.Hub == library.HubDirect { + fmt.Println(" ", muted.Render("direct: each agent's own entry, never through the hub · magpie library mcp hub "+s.Name+" shared")) + } for a, e := range s.Problems { fmt.Println(" ", amber.Render("!"), a, muted.Render(e)) } diff --git a/internal/cli/library_hub_test.go b/internal/cli/library_hub_test.go index 0b113aa42..5b408b3fb 100644 --- a/internal/cli/library_hub_test.go +++ b/internal/cli/library_hub_test.go @@ -60,6 +60,23 @@ func TestLibraryMCPHub(t *testing.T) { if got := names(); !slices.Equal(got, []string{"magpie"}) { t.Fatalf("after a word it doesn't know: %v", got) } + // a server kept direct (#4382) is its own entry again, beside no hub + // entry once no server is behind it; shared, behind the hub again + if err := libraryCmd([]string{"library", "mcp", "hub", "fs", "direct"}); err != nil { + t.Fatal(err) + } + if got := names(); !slices.Equal(got, []string{"fs"}) { + t.Fatalf("fs direct: %v", got) + } + if err := libraryCmd([]string{"library", "mcp", "hub", "fs", "solo"}); err == nil || !strings.Contains(err.Error(), "usage") { + t.Fatalf("hub fs solo: %v", err) + } + if err := libraryCmd([]string{"library", "mcp", "hub", "fs", "shared"}); err != nil { + t.Fatal(err) + } + if got := names(); !slices.Equal(got, []string{"magpie"}) { + t.Fatalf("fs shared: %v", got) + } if err := libraryCmd([]string{"library", "mcp", "hub", "off"}); err != nil { t.Fatal(err) } diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index c19c498eb..0ed5382b4 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -1698,10 +1698,14 @@ magpie.plugin("library", (ctx) => { // magpie's own image server is given as it is, never through the hub: it // asks its agent for the project's folder (inHub in mcp_hub.go) const isSelf = (s) => s.transport === "stdio" && s.args?.[0] === "mcp" && s.args?.[1] === "image"; + // nor is a server the user keeps direct (#4382): each agent's own entry + const inHub = (s) => !isSelf(s) && s.hub !== "direct"; + // the servers each agent is given directly, by name, for the hub's lines + const directNames = () => lib.servers.filter((s) => !inHub(s)).map((s) => s.name).join(", "); // what the hub serves: its servers, their tools as far as checked, and // the agents given it function hubStats() { - const servers = lib.servers.filter((s) => !isSelf(s)); + const servers = lib.servers.filter(inHub); const parts = [servers.length === 1 ? t("1 server") : t("{n} servers", { n: servers.length })]; const known = servers.filter((s) => health.get(s.name)?.h?.state === "ok"); if (known.length) { @@ -1711,8 +1715,8 @@ magpie.plugin("library", (ctx) => { const given = hubAgents().filter((a) => a.hub === "on").map((a) => a.name); if (given.length) parts.push(t("in {agents}", { agents: given.length > 3 ? t("{first} and {n} more", { first: given.slice(0, 2).join(", "), n: given.length - 2 }) : given.join(", ") })); // the owner, counting two servers and seeing one: where the other went - const own = lib.servers.find(isSelf); - if (own) parts.push(t("{name} is given to each agent directly", { name: own.name })); + const direct = directNames(); + if (direct) parts.push(t("{name} is given to each agent directly", { name: direct })); return parts.join(" · "); } const hubURL = () => mcpAddress(state.settings || {}, lib.hubPath.replace(/\/+$/, "")); @@ -1733,7 +1737,7 @@ magpie.plugin("library", (ctx) => { function connectHub() { const url = hubURL(); const json = (o) => JSON.stringify(o, null, 2); - const served = () => lib.servers.filter((s) => !isSelf(s)); + const served = () => lib.servers.filter(inHub); const ed = el("div", "editor lib-editor lib-hubsheet"); const head = el("div", "ehead"); head.append(hubMark(), el("b", "", t("Connect an app"))); @@ -1867,8 +1871,8 @@ magpie.plugin("library", (ctx) => { const left = can.length - on.length; const sub = [left ? t("{n} more can be connected", { n: left }) : t("Each server runs once, for all of them")]; if (kept.length) sub.push(kept.length === 1 ? t("1 keeps each server's own entry") : t("{n} keep each server's own entry", { n: kept.length })); - const own = lib.servers.find(isSelf); - if (own) sub.push(t("{name} is given to each agent directly", { name: own.name })); + const direct = directNames(); + if (direct) sub.push(t("{name} is given to each agent directly", { name: direct })); // each part whole on its line, the dot kept with the part before it const line = el("p", "lib-hubsub"); sub.forEach((x, i) => line.append(...(i ? [" "] : []), el("span", "", x + (i < sub.length - 1 ? "\u00a0·" : "")))); @@ -1973,6 +1977,8 @@ magpie.plugin("library", (ctx) => { else if (s.signIn?.signedIn) nm.append(tag(t("Signed in"), "lib-signed", t("The agents given it use magpie's sign-in"))); // kept to this computer: sync carries it nowhere (huhuy72219405 on X) if (s.local) nm.append(tag(t("This computer only"), "lib-local", t("Sync never carries it to your other computers"))); + // out of the hub, each agent's own entry (#4382): said only while the hub is on + if (lib.mcpHub && s.hub === "direct") nm.append(tag(t("Not through the hub"), "lib-direct", t("Each agent is given its own entry for it, as with the MCP hub off"))); // its status beside the name, not in it: the name is still the name who.classList.add("lib-srvwho"); who.append(nm, healthEl(s.name)); @@ -2648,6 +2654,17 @@ magpie.plugin("library", (ctx) => { const drawHere = () => hereBox.replaceChildren(toggle(d.local, t("This computer only"), (on) => { d.local = on; drawHere(); })); drawHere(); ed.append(...field(t("This computer only"), hereBox, t("Sync never carries it to your other computers, and a sync from them neither removes it nor puts theirs in its place"))); + // with the hub on, a server can stay each agent's own entry (#4382, + // cuipengcx90): one that reads its project from the folder it starts + // in, or keeps a session's state. Shown only while the hub is on, and + // never for magpie's own image server, which is always direct + d.hub = d.hub === "direct" ? "direct" : ""; + if (lib.mcpHub && !isSelf(d)) { + const hubBox = el("div", "lib-hubbox"); + const drawHub = () => hubBox.replaceChildren(toggle(d.hub !== "direct", t("Through the MCP hub"), (on) => { d.hub = on ? "" : "direct"; drawHub(); })); + drawHub(); + ed.append(...field(t("Through the MCP hub"), hubBox, t("Off gives each agent its own entry for it, as with the hub off: for a server that reads its project from the folder it starts in, or keeps a session's state"))); + } ed.append(err); function drawAgents() { @@ -2709,7 +2726,7 @@ magpie.plugin("library", (ctx) => { // send saves the form; s is then the server as saved, for a save after // a sign-in's to be of it const send = async () => { - const body = { old: s ? s.name : "", server: { name: d.name, transport: d.transport, agents: d.agents, startupTimeout: d.startupTimeout || 0, local: !!d.local } }; + const body = { old: s ? s.name : "", server: { name: d.name, transport: d.transport, agents: d.agents, startupTimeout: d.startupTimeout || 0, local: !!d.local, hub: d.hub || "" } }; if (d.transport === "stdio") Object.assign(body.server, { command: d.command, args: d.args, env: d.env }); else Object.assign(body.server, { url: d.url, headers: d.headers, oauth: d.transport === "http" && d.oauth?.clientId ? d.oauth : null }); take(await api("library/servers/save", body)); diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index 69f41c1b0..fb91ea35f 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -3,6 +3,10 @@ magpie.strings({ zh: { "This computer only": "只在这台电脑", + "Not through the hub": "不经过聚合", + "Each agent is given its own entry for it, as with the MCP hub off": "每个 Agent 各自有它的条目,和关掉 MCP 聚合时一样", + "Through the MCP hub": "经过 MCP 聚合", + "Off gives each agent its own entry for it, as with the hub off: for a server that reads its project from the folder it starts in, or keeps a session's state": "关掉后,每个 Agent 各自有它的条目,和关掉聚合时一样:适合从启动目录读取项目、或保存会话状态的服务器", "Sync never carries it to your other computers": "同步不会把它带到你的其他电脑", "Sync never carries it to your other computers, and a sync from them neither removes it nor puts theirs in its place": "同步不会把它带到你的其他电脑;其他电脑同步过来时,既不会删掉它,也不会用它们的同名服务器替换它", "Move into the library": "移入资源库", @@ -734,6 +738,10 @@ magpie.strings({ }, "zh-TW": { "This computer only": "只在這台電腦", + "Not through the hub": "不經過聚合", + "Each agent is given its own entry for it, as with the MCP hub off": "每個 Agent 各自有它的條目,和關掉 MCP 聚合時一樣", + "Through the MCP hub": "經過 MCP 聚合", + "Off gives each agent its own entry for it, as with the hub off: for a server that reads its project from the folder it starts in, or keeps a session's state": "關掉後,每個 Agent 各自有它的條目,和關掉聚合時一樣:適合從啟動目錄讀取專案、或保存工作階段狀態的伺服器", "Sync never carries it to your other computers": "同步不會把它帶到你的其他電腦", "Sync never carries it to your other computers, and a sync from them neither removes it nor puts theirs in its place": "同步不會把它帶到你的其他電腦;其他電腦同步過來時,既不會刪掉它,也不會用它們的同名伺服器取代它", "Move into the library": "移入資源庫", @@ -1465,6 +1473,10 @@ magpie.strings({ }, ja: { "This computer only": "このコンピュータだけ", + "Not through the hub": "ハブを通さない", + "Each agent is given its own entry for it, as with the MCP hub off": "各エージェントに個別のエントリを渡します(MCP ハブがオフのときと同じ)", + "Through the MCP hub": "MCP ハブを通す", + "Off gives each agent its own entry for it, as with the hub off: for a server that reads its project from the folder it starts in, or keeps a session's state": "オフにすると、各エージェントに個別のエントリを渡します(ハブがオフのときと同じ)。起動したフォルダからプロジェクトを読むサーバーや、セッションの状態を持つサーバー向けです", "Sync never carries it to your other computers": "同期でほかのコンピュータには送られません", "Sync never carries it to your other computers, and a sync from them neither removes it nor puts theirs in its place": "同期でほかのコンピュータには送られません。ほかのコンピュータからの同期で削除されたり、同じ名前のサーバーに置き換えられたりすることもありません", "Move into the library": "ライブラリへ移す", @@ -2196,6 +2208,10 @@ magpie.strings({ }, de: { "This computer only": "Nur dieser Computer", + "Not through the hub": "Nicht über den Hub", + "Each agent is given its own entry for it, as with the MCP hub off": "Jeder Agent bekommt einen eigenen Eintrag dafür, wie bei ausgeschaltetem MCP-Hub", + "Through the MCP hub": "Über den MCP-Hub", + "Off gives each agent its own entry for it, as with the hub off: for a server that reads its project from the folder it starts in, or keeps a session's state": "Aus bekommt jeder Agent einen eigenen Eintrag dafür, wie bei ausgeschaltetem Hub: für einen Server, der sein Projekt aus dem Ordner liest, in dem er startet, oder den Zustand einer Sitzung hält", "Sync never carries it to your other computers": "Die Synchronisierung bringt ihn nicht auf deine anderen Computer", "Sync never carries it to your other computers, and a sync from them neither removes it nor puts theirs in its place": "Die Synchronisierung bringt ihn nicht auf deine anderen Computer, und eine Synchronisierung von dort entfernt ihn weder noch ersetzt sie ihn durch ihren gleichnamigen Server", "Move into the library": "In die Bibliothek verschieben", diff --git a/internal/gui/tests/mcp-hub-direct.test.cjs b/internal/gui/tests/mcp-hub-direct.test.cjs new file mode 100644 index 000000000..9aa40afed --- /dev/null +++ b/internal/gui/tests/mcp-hub-direct.test.cjs @@ -0,0 +1,147 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// #4382 (cuipengcx90; nifengfanpan on Discord): with the MCP hub on, a +// server can stay each agent's own entry. Its editor has a switch, +// "Through the MCP hub", on for a server shared as before; off saves it +// with hub "direct", the row says so with a tag, and the hub's line +// counts it with magpie's own image server as given directly. With the +// hub off there is neither switch nor tag. Every language, Chromium and +// WebKit, 1100 and 390 wide; nothing scrolls sideways. No backend: the +// API is faked here. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const { I18N } = require("./strings.cjs").strings(); // i18n.js's and the plugins' +const tr = (lang, s, vars = {}) => ((lang === "en" ? s : I18N[lang][s]) || s).replace(/\{(\w+)\}/g, (_, k) => vars[k]); +const HOME = "/Users/xv"; +const agents = [{ id: "claude", name: "Claude Code", icon: "", skills: `${HOME}/.claude/skills`, mcp: `${HOME}/.claude.json`, hub: "on" }]; +const WORDS = ["Through the MCP hub", "Not through the hub", "Each agent is given its own entry for it, as with the MCP hub off", + "Off gives each agent its own entry for it, as with the hub off: for a server that reads its project from the folder it starts in, or keeps a session's state"]; + +function server(lang, calls, hubOn) { + const lib = { + dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME, + agents, mcpHub: hubOn, hubPath: "/mcp/magpie/hub/", + instructions: { agents: [], sets: [] }, foundServers: [], projects: [], foundSkills: [], skills: [], + servers: [ + { name: "index", transport: "stdio", command: "/opt/index/mcp", agents: ["claude"] }, + { name: "web", transport: "http", url: "https://example.com/mcp", agents: ["claude"] }, + { name: "magpie-image", transport: "stdio", command: "/Applications/magpie.app/Contents/MacOS/magpie", args: ["mcp", "image"], agents: ["claude"] }, + ], + }; + return async (route) => { + const req = route.request(), url = new URL(req.url()); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return route.fulfill({ json: { agents: [], profiles: [], settings: { lang, theme: "light", gateway: "http://127.0.0.1:3425" } } }); + if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } }); + if (url.pathname === "/api/library") return route.fulfill({ json: lib }); + if (url.pathname === "/api/library/mcp/check") return route.fulfill({ json: { servers: {} } }); + if (url.pathname === "/api/library/servers/save") { + const { old, server: s } = req.postDataJSON(); + calls.push(`${s.name} ${JSON.stringify(s.hub)}`); + const i = lib.servers.findIndex((x) => x.name === old); + lib.servers[i] = { ...lib.servers[i], ...s }; + if (!s.hub) delete lib.servers[i].hub; + return route.fulfill({ json: { ...lib, result: { changed: ["claude"] } } }); + } + if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] }); + if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } }); + if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } }); + if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} }); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": an MCP server kept out of the hub", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" })); + const errors = []; + t.after(async () => { + if (errors.length) console.log(errors); + await browser.close(); + }); + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + for (const width of [1100, 390]) { + await t.test(`${lang} ${width}`, async () => { + const w = (s, v) => tr(lang, s, v); + if (lang !== "en") for (const s of WORDS) assert.ok(I18N[lang][s], `${lang}: ${s}`); + for (const hubOn of [true, false]) { + const calls = []; + const ctx = await browser.newContext({ viewport: { width, height: 800 } }); + await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "mcp"); } catch {} }); + const page = await ctx.newPage(); + page.setDefaultTimeout(5000); + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, calls, hubOn)); + await page.goto("http://magpie.test/"); + await page.locator('button[data-view="library"]').click(); + const rowOf = (name) => page.locator("#view-library .lib-server", { has: page.locator(`.lib-health[data-server="${name}"]`) }); + const row = rowOf("index"); + const ed = page.locator("#modal .lib-editor"); + const sw = ed.getByRole("switch", { name: w("Through the MCP hub"), exact: true }); + const tag = row.locator(".lib-tag.lib-direct"); + const open = async (r = row) => { await r.locator(".name").click(); await ed.waitFor(); }; + const save = async () => { await ed.locator(":scope > .bar button.primary").click(); await ed.waitFor({ state: "detached" }); }; + const stats = () => page.locator("#view-library .lib-hubstats").textContent(); + await row.waitFor(); + + if (!hubOn) { + // the hub off: nothing to choose, nothing said; a save sends shared + await open(); + assert.equal(await sw.count(), 0, "a switch with the hub off"); + await save(); + assert.deepEqual(calls, ['index ""']); + assert.equal(await tag.count(), 0); + await ctx.close(); + continue; + } + assert.equal(await tag.count(), 0, "a shared server has no tag"); + assert.ok((await stats()).startsWith(w("{n} servers", { n: 2 })), await stats()); + // on for a server shared as before; the hint says what off does + await open(); + assert.equal(await sw.getAttribute("aria-checked"), "true"); + await ed.locator(".hint", { hasText: w(WORDS[3]) }).waitFor(); + await sw.click(); + assert.equal(await sw.getAttribute("aria-checked"), "false"); + await save(); + assert.deepEqual(calls, ['index "direct"']); + // the row says so, the hub counts it given directly, and the editor shows it off again + await tag.waitFor(); + assert.equal((await tag.textContent()).trim(), w("Not through the hub")); + assert.equal(await tag.getAttribute("title"), w(WORDS[2])); + await page.waitForFunction((x) => document.querySelector("#view-library .lib-hubstats")?.textContent.startsWith(x[0]) && + document.querySelector("#view-library .lib-hubstats")?.textContent.endsWith(x[1]), + [w("1 server"), w("{name} is given to each agent directly", { name: "index, magpie-image" })]); + await open(); + assert.equal(await sw.getAttribute("aria-checked"), "false"); + // on again, saved as shared + await sw.click(); + await save(); + assert.deepEqual(calls, ['index "direct"', 'index ""']); + await tag.waitFor({ state: "detached" }); + // magpie's own image server is always direct: no switch to offer + await open(rowOf("magpie-image")); + assert.equal(await sw.count(), 0, "a switch on magpie's own image server"); + await ed.locator(":scope > .bar button", { hasText: w("Cancel") }).click(); + await ed.waitFor({ state: "detached" }); + // Cancel keeps it as it was + await open(); + await sw.click(); + await ed.locator(":scope > .bar button", { hasText: w("Cancel") }).click(); + assert.deepEqual(calls, ['index "direct"', 'index ""']); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, "no sideways scroll"); + await ctx.close(); + } + }); + } + } + assert.deepEqual(errors, []); + }); +} diff --git a/internal/library/mcp.go b/internal/library/mcp.go index 487a00246..81b53b3da 100644 --- a/internal/library/mcp.go +++ b/internal/library/mcp.go @@ -60,6 +60,12 @@ type Server struct { // gateway serves them at its URL, and the hub calls the plugin itself // (plugin_tools.go) Plugin string `json:"plugin,omitempty"` + // Hub is how the MCP hub (Library.MCPHub) gives the server: "" shares + // it through the hub's one entry, as every server was before; + // HubDirect keeps it the agents' own entry, written as with the hub + // off, for a server that reads its project from the folder it is + // started in, or keeps a session's state (#4382, cuipengcx90). + Hub string `json:"hub,omitempty"` // startupWrote is the startup_timeout_sec magpie last wrote in the // entry being written, 0 for none: one the entry has otherwise is the @@ -118,6 +124,13 @@ func (s *Server) check() error { default: return fmt.Errorf("%s: unknown transport %q", s.Name, s.Transport) } + switch s.Hub { + case "", "shared": + s.Hub = "" + case HubDirect: + default: + return fmt.Errorf("%s: unknown hub policy %q: shared or direct", s.Name, s.Hub) + } // magpie signs in only to a streamable HTTP server if s.Transport != "http" { s.OAuth = nil diff --git a/internal/library/mcp_hub.go b/internal/library/mcp_hub.go index c4fb5c4d8..50a98f095 100644 --- a/internal/library/mcp_hub.go +++ b/internal/library/mcp_hub.go @@ -18,7 +18,9 @@ package library // (httpSession), or over its event stream (SSE). // // magpie's own image server is never behind the hub: it asks the agent -// that started it for its roots. What a server lists is kept until it says +// that started it for its roots. Nor is a server the user keeps direct +// (Server.Hub, #4382): a command that reads its project from the folder +// it starts in, or keeps a session's state, is each agent's own. What a server lists is kept until it says // its tools changed, or the server is edited. import ( @@ -66,9 +68,31 @@ func SetMCPHub(on bool) (*Result, error) { return res, err } +// HubDirect is Server.Hub for a server the hub leaves out: each agent +// given it keeps its own entry, as with the hub off (#4382). +const HubDirect = "direct" + // inHub is whether the hub gives s: every server but magpie's own image -// server, which asks its agent for its roots. -func inHub(s *Server) bool { return !isSelf(s) } +// server, which asks its agent for its roots, and one the user keeps +// direct (Server.Hub). +func inHub(s *Server) bool { return !isSelf(s) && s.Hub != HubDirect } + +// ServerHub shares a server through the hub, or keeps it each agent's own +// entry (direct); the agents are written again at once, so the entry it +// had the other way goes. +func ServerHub(name string, direct bool) (*Result, error) { + return change(func(l *Library) error { + s := l.server(name) + if s == nil { + return fmt.Errorf("no server called %s", name) + } + s.Hub = "" + if direct { + s.Hub = HubDirect + } + return nil + }) +} // hubServerFor is the entry agent t is given for the hub, at the address // the agent reaches the gateway at, with a key when it reaches it from diff --git a/internal/library/mcp_hub_test.go b/internal/library/mcp_hub_test.go index f3fac5c51..c004693fb 100644 --- a/internal/library/mcp_hub_test.go +++ b/internal/library/mcp_hub_test.go @@ -524,3 +524,83 @@ func TestHubLink(t *testing.T) { t.Fatal("an app with no install link was given one") } } + +// A server kept direct (#4382, cuipengcx90) stays each agent's own entry +// with the hub on, written as with the hub off, beside magpie's for the +// rest; switching it either way writes the agents again, the entry it had +// the other way gone, and the hub neither lists nor runs it. +func TestHubDirectServer(t *testing.T) { + h := hubSandbox(t) + claude := filepath.Join(h, ".claude.json") + write(t, claude, `{"mcpServers": {"mine": {"command": "x"}}}`) + codex := filepath.Join(h, ".codex/config.toml") + write(t, codex, "") + ok(t)(SaveServer("", Server{Name: "index", Transport: "stdio", Command: "npx", Args: []string{"-y", "indexer"}, Env: map[string]string{"K": "v"}, Agents: []string{"claude", "codex"}, Hub: "direct"})) + ok(t)(SaveServer("", Server{Name: "web", Transport: "http", URL: "https://example.com/mcp", Agents: []string{"claude", "codex"}, Hub: "shared"})) + entries := func(id string) map[string]map[string]any { + t.Helper() + e, err := targetByID(id).MCP.entries() + if err != nil { + t.Fatal(err) + } + return e + } + names := func(id string) []string { + var out []string + for k := range entries(id) { + out = append(out, k) + } + slices.Sort(out) + return out + } + off := map[string]string{} // each agent's index entry with the hub off + for _, id := range []string{"claude", "codex"} { + b, _ := json.Marshal(entries(id)["index"]) + off[id] = string(b) + } + if l, err := load(); err != nil || l.server("web").Hub != "" || l.server("index").Hub != HubDirect { + t.Fatalf("saved: %v %+v", err, l) + } + + ok(t)(SetMCPHub(true)) + for id, want := range map[string][]string{"claude": {"index", "magpie", "mine"}, "codex": {"index", "magpie"}} { + if got := names(id); !slices.Equal(got, want) { + t.Fatalf("%s with the hub on: %v, want %v\n%s\n%s", id, got, want, read(t, claude), read(t, codex)) + } + if b, _ := json.Marshal(entries(id)["index"]); string(b) != off[id] { + t.Errorf("%s's direct entry %s, with the hub off %s", id, b, off[id]) + } + } + for _, id := range []string{"claude", ""} { + var got []string + for _, s := range hubServers(id) { + got = append(got, s.Name) + } + if !slices.Equal(got, []string{"web"}) { + t.Errorf("the hub serves %q: %v, want only web", id, got) + } + } + + // shared again: behind the hub, its own entry gone + ok(t)(ServerHub("index", false)) + for _, id := range []string{"claude", "codex"} { + if got := names(id); slices.Contains(got, "index") || !slices.Contains(got, "magpie") { + t.Fatalf("%s with index shared: %v\n%s\n%s", id, got, read(t, claude), read(t, codex)) + } + } + // every server direct: the hub's entry goes, each written as with it off + ok(t)(ServerHub("index", true)) + ok(t)(ServerHub("web", true)) + if got := names("claude"); !slices.Equal(got, []string{"index", "mine", "web"}) { + t.Fatalf("claude with every server direct: %v\n%s", got, read(t, claude)) + } + if got := names("codex"); !slices.Equal(got, []string{"index", "web"}) { + t.Fatalf("codex with every server direct: %v\n%s", got, read(t, codex)) + } + if _, err := ServerHub("nope", true); err == nil { + t.Error("a server not in the library was set") + } + if _, err := SaveServer("", Server{Name: "odd", Transport: "stdio", Command: "x", Hub: "session"}); err == nil { + t.Error("an unknown hub policy was saved") + } +} diff --git a/internal/tui/library.go b/internal/tui/library.go index a3354e55d..a910ac7f0 100644 --- a/internal/tui/library.go +++ b/internal/tui/library.go @@ -424,8 +424,8 @@ func saveServer(old *library.Server, line string) tea.Cmd { if old != nil { was, done = old.Name, "saved "+s.Name // and its OAuth app and startup timeout, which only the GUI edits - // and whether it is kept to this computer - s.Agents, s.Env, s.Headers, s.OAuth, s.StartupTimeout, s.Local = old.Agents, old.Env, old.Headers, old.OAuth, old.StartupTimeout, old.Local + // and whether it is kept to this computer, and out of the hub + s.Agents, s.Env, s.Headers, s.OAuth, s.StartupTimeout, s.Local, s.Hub = old.Agents, old.Env, old.Headers, old.OAuth, old.StartupTimeout, old.Local, old.Hub } return libCmd(func() (*library.Result, error) { return library.SaveServer(was, s) }, done)() }