Files
magpie/docs/subsystems/mcp-router.md
T
yetone 7bc602236b library: the MCP hub is called the MCP router
The owner asked why it was a "hub". Composio calls the same thing a Tool
Router; "router" says what it does (one server that routes each call to
the right one), and "gateway" is taken by magpie's LLM gateway. Only
the words change: MCP router / MCP 路由 / MCP 路由 / MCP ルーター /
MCP-Router, "Router address", and the CLI's `magpie library mcp router
on|off`, where `hub` still works. The URL /mcp/magpie/hub, the mcpHub
setting, the servers/hub API and the Go names stay, so nothing a user
or an agent config holds changes. docs/subsystems/mcp-hub.md moves to
mcp-router.md and the pages that link it follow.

#4382's new words follow too: "Through the MCP router", "Not through
the router" and their hints in every language, and the CLI's
`magpie library mcp router <name> shared|direct` (`hub` works there
too; library_hub_test.go says router for direct, hub for shared).

Run at e2583df31 (this stack on 86fef947e), on mote: gofmt -l clean;
go vet for darwin, linux (-tags nogui) and windows; go build ./...;
go test -tags nogui ./... -timeout 45m, 81 packages ok, 0 FAIL;
library, gateway, imagemcp, sessions, cli and gui again alone, ok;
site's node --test, 49 of 49. GUI on xiaomi-gpu (Windows; mote's
browsers crashed under other sessions' suites): library-*, image*,
mcp-hub-direct, i18n-keys, list-sort and plugin-tools, both engines and
every language, 1055 of 1056: i18n-keys found "{name} is given to each
agent directly" dropped from the library's strings in the rebase. Put
back in the first commit; at the pushed head i18n-keys, mcp-hub-direct
and library-mcp-hub are 48 of 48. That is the only difference from
e2583df31.
Broken by hand at e2583df31: imagemcp ignoring magpie/roots fails
TestHubCallSavesInTheCallersProject; the router asking anything but
roots/list fails TestHubAsksTheAgentItsRoots and TestHubRootsUnasked;
inHub leaving magpie-image out fails TestHubGivesMagpieImage.
The CLI's TestProviderAddressMovesALocalServer red at -count=3 was
the same on origin/main 380032cda and is fixed in 65c792410.
Rebased once more onto 2570efb5f, which changed library-mcp-hub,
list-sort, mcp-hub-direct and gateway-routing.md. Run at the pushed
head: go build; gateway, library, cli and imagemcp tests ok; the GUI
budget tests ok; on xiaomi-gpu i18n-keys, mcp-hub-direct,
library-mcp-hub and list-sort, 51 of 54. The three reds were WebKit
420px library-mcp-hub cases with no Connect sheet after a reload.
origin/main d77da5bff goes red the same way (de 420px, 9 of 11). In a
second run of library-mcp-hub on WebKit at this head, 11 of 11 passed.
Filed as #4483.
2026-10-31 02:49:08 +08:00

15 KiB

MCP router

With the Library's switch "MCP router" on (#2679, @minggang123 on X), each agent is given one MCP server, magpie, in place of the Library's MCP servers ticked for it. magpie serves it at /mcp/magpie/hub/<agent> (Streamable HTTP) and hands each call on to the Library server behind it. Any other app (Cursor, VS Code, Windsurf, an app on another computer) connects at /mcp/magpie/hub, which serves every server in the Library. A server written once is then set up once, for every agent and app, and a command server runs once, not once in each. The servers themselves are the Library's; the endpoint is the gateway's, guarded as Plugin tools' /mcp/magpie/tools is. The switch is off by default.

Responsibilities and sources of truth

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 router started (hubStopAll). The page posts servers/hub {on}. SetMCPHub in mcp_hub.go; servers/hub in 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 <key> when that address needs a key (agent.KeyAt). A LAN key or relay change re-syncs (LANChanged). magpie's own image server (isSelf) is behind the router too, except for an agent in a WSL distro (its id has @wsl:), which keeps its own entry to the magpie in that distro. A server the user keeps direct is not (Server.Hub = direct, hub in library.json; #4382, cuipengcx90): each agent given it keeps its own entry, written as with the router off, beside the router's entry for the rest; an agent whose every server is direct is given no hub entry. inHub is the one test, so the router 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 router'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 router (Option B in #4382, keying hubPool by roots) is not built. hubFor, hubServerFor, inHub in mcp_hub.go; syncMCP in sync.go; 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 router's entry. An agent given none of the router'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 <server>__<tool>: 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
Magpie Image's project Magpie Image saves into the project of the agent that called it, though one server serves every agent. Its tools are HubTool.Roots: for such a call the router answers the POST as an event stream (mcpExchange) and asks the agent roots/list on it, waiting hubRootsWait (3s); Claude Code answers with its folder. An agent that answers no roots, or none (Codex answers []), is given the workspaces the call's _meta names (Codex's x-codex-turn-metadata.workspaces, keyed by the folder of each git repository it works in, absolute paths only), and failing those the folder of the call's _meta.threadId in Codex's sessions (sessions.CodexThreadCwd, its rollout's cwd), only with consent to read them; with neither (a folder that isn't a repository, no consent), none. A caller that isn't local gets no roots. The call goes on with _meta magpie/roots (file URIs, never null) and magpie/client (the first word of the agent's User-Agent, e.g. claude-code/2.1.314). The image server, seeing magpie/roots, saves into the first root, or ~/Pictures/Magpie with none (never its own folder), draws as <client> magpie-image/1, and sends no magpie/toolCalled report, since the router's row is the call's: its result's _meta magpie/model (provider/model) names the model it drew with, for that row (HubModelMeta). hubRoots, hubClient, WithHubCaller in hub_mcp.go; mcp_ask.go; imageMeta in mcp_hub.go; project, rootOf in imagemcp.go; codex_cwd.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
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
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 router, 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. magpie-image is drawn and counted with the others. 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 router on, the server editor has a switch "Through the MCP router" (on for shared; not shown with the router 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 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, library.css, i18n.js; HubLink in mcp_hub.go; servers/hub-open in gui/library.go

The CLI's magpie library mcp router on|off (hub, its name before, still works) calls SetMCPHub, and magpie library mcp router <name> 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).

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.

Runtime path

  1. The user turns the switch on. SetMCPHub(true) saves mcpHub and syncs: each agent that can take it gets the one magpie entry, and the servers behind it are taken out of that agent's file. Nothing is started yet.
  2. The agent starts and posts initialize, then tools/list, to /mcp/magpie/hub/<agent>. hubMCP passes the guard. Tools reads library.json for the servers ticked for that agent, and lists each in parallel, by hubListWait (40s): a server not reached by then is left out of that list, not an error. Another app does the same at /mcp/magpie/hub, under the same guard: from another computer it needs a gateway key, as every LAN request does.
  3. tools/call finds the tool by its router name in the same list, holds it to the key's limit, and calls Call under hubCallWait (50s, under the 60s an MCP client gives a call). The server's result goes back as it gave it. A Magpie Image call first asks the agent its roots on the call's stream (above), and the result goes back on that stream.
  4. An error comes back as isError text naming the server: The MCP server S couldn't run T: <why>, where why is how it exited and its last line on stderr, a sign-in it needs, its command not found, or it didn't answer in 50s.
  5. Each call is a row of the request log (serveMCP's callMCPTool): the router's tool name, the Library server as its host, the agent of the path, how long it took and its error, never its arguments. It counts in no total (Calls to magpie's own MCP tools).

Constraints and failure behavior

  • Off means off: no tool is listed, a call says the router is off, and no server is started (TestHubMCPOff, TestHubToolsAndCalls).
  • magpie takes out only the magpie entry it wrote (Applied.MCP). An entry called magpie of the agent's own, or a Library server called magpie, keeps every server's own entry for that agent, said on the page.
  • A tool turned off in the Library is neither listed nor run, for every agent, including those that have no setting of their own for it.
  • A call that times out leaves the server running for the next; a server that died is started again. A server that can't be started is an error on each call, not a retry loop.
  • Every process the router starts is in a proc tree magpie ends when the switch goes off, the server is edited, it has been idle, or the gateway stops. A test ends them in cleanup (hubSandbox).
  • A gateway key holder on the LAN reaches the Library's command servers through the router while it is on, as they reach plugin tools. They run with the user's rights on this computer.
  • A tools plugin's server (plugin set, Plugin tools) is behind the router as any server is, but its tools are listed and run in this process through the plugin host, not over its URL, and they aren't cached: the host has them.
  • The tools a server listed are cached until it says they changed, it is edited, or the switch is turned off. A server that changes its tools without saying so shows them after one of those.

Verification

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 internal/gui/tests/mcp-hub-direct.test.cjs

The library tests run a fake stdio MCP server (TestFakeMCPServer in 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.