router: an agent with many tools is given them on demand

ArvinCharl on X: the MCP router's tools fill the context. An agent that
doesn't search its MCP tools itself (all but Claude Code, Claude
Desktop, Codex and Pi) sends every tool's whole schema on every
request. Given more than 10 router tools, such an agent now lists two in
their place: find_tools (matches by name and description, the first 5
with their inputSchema, 15 more by name) and call_tool (runs one by
<server>__<tool>, its bare name, or arguments sent as a string; an
unknown name is told the close ones). The instructions still name every
server and its tools, and a tool called by its own name still runs. The
request log names the tool call_tool ran. The address for any other app
lists every tool, since which app connects isn't known.

Library → MCP gains a "Tools on demand" toggle (settings
routerAllTools, kept by KeepOwn and the settings API); turned off,
every agent gets every tool whole as before.

Run on mote (after the rebase onto 083821dc9: gateway vet, -run
'Hub|MCP|Settings|Search' and the four GUI files again, ok, 70 of 70):
- gofmt -l: empty. go vet, GOOS=linux go vet -tags nogui, GOOS=windows
  go vet of gateway, settings, settingsapi, gui, library: ok.
- go test -tags nogui -count=1 -timeout 45m ./internal/settings
  ./internal/settingsapi ./internal/gui ./internal/library: ok;
  ./internal/gateway -run 'Hub|MCP|Settings': ok.
- GUI (Chromium + WebKit, every language): library-mcp-router-tools,
  library-mcp-router-note, library-mcp-hub, i18n-keys: 70 of 70.
Broken by hand: hubOnDemand forced false turns TestHubMCPToolsOnDemand
red.
Not tried: a real OpenCode or Gemini CLI session against the router;
the full gateway package and full GUI suite.
This commit is contained in:
yetone
2026-11-04 21:00:51 +08:00
parent 083821dc96
commit 93d5c76c0d
15 changed files with 778 additions and 36 deletions
+6 -5
View File
@@ -9,15 +9,16 @@ With the Library's switch "MCP router" on (#2679, @minggang123 on X), each agent
| 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`](../../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 <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, and started by that agent: Codex on magpie, which is otherwise given a command server as the gateway's `/mcp/run/<name>` that magpie starts from home ([`mcp_run.go`](../../internal/library/mcp_run.go), #3885), is given a direct one's `command`, `args` and `env` with no `cwd`, so Codex starts it in the thread's folder (codex-mcp's `LocalStdioServerLauncher` falls back to the session's `cwd`; `TestRunDirectServerIsCodexsCommand`); 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`](../../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 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). Every tool is listed in full; what keeps them out of each request is the agent's own tool search (Claude Code's `ENABLE_TOOL_SEARCH`, which magpie turns on, see [agent wiring](agent-wiring.md); Codex's `tool_search` on magpie's catalog). An agent with none sends them all. `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) |
| 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). An agent that searches its MCP tools itself is given every tool in full, and its tool search keeps them out of each request: Claude Code (`ENABLE_TOOL_SEARCH`, which magpie turns on, see [agent wiring](agent-wiring.md)), Claude Desktop, Codex (`tool_search` on magpie's catalog) and Pi (`hubSearchesItself`, by the agent's id without its `@wsl:<distro>`). So is the address for any other app (agent `""`) and an agent given 10 tools or fewer. Any other agent is given its tools on demand (below). `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) |
| What it serves | An agent that shows the router as one line, and its tools only once they are searched for, learns from that line alone which servers are behind it (a Pi asked about a GitHub repository cloned it rather than ask the DeepWiki behind the router, told only "The tools of the MCP servers in magpie's Library", 11-01). `initialize`'s `instructions` start with `HubLine`: `Tools of <name> (<what it is for>), …`, every server by name, each one's first clause (`hubClause`) cut at a word to an equal share of 250 characters (`hubLineMax`, Pi's `MAX_SERVER_DESCRIPTION_CHARS`), the short ones whole; names that don't fit are counted (`and N more`). Then, for an agent given several routers to tell them apart (packinggoodsllc_07668: magpies that only share MCP servers), the router's name sentence when it has one (Router name, below), then a line for each server (`hubDetails`): `- <name> (<its title>): <what it is for>. Tools: <tool> (<first clause of its description>), …`, the tools the Library turned off left out and a router's `[<name>] ` dropped; a line too long for its share of the room says its tools by name only, then as many names as fit and `and N more`. The whole is at most 2000 characters (`hubSayMax`, half the 4096 Claude Code keeps), the closing text kept whole. What a server is for is the market's (`serverAbout`): the featured or registry server it is by `serverKey`, whatever it is named, or the featured one it is named after; otherwise the server's own words, its `serverInfo.description` or else its `instructions`' first line (`saysOf`); another magpie's `Tools of a (…), b.` is said with `Tools of` once. Its title is its `serverInfo.title`. These and its tools are what the server last answered to `initialize` and `tools/list` (`noteCard`), kept in `mcp-hub-servers.json` beside settings.json (not in the synced library folder) by server name and `cardKey` (a hash of `hubKey`: an edit or a sign-in since is another server), written through a temporary file only when they change; a router started again describes its servers before running any. A server with no card for it as it is now (`Known` false) is listed by `initialize`, which waits up to 5 s (`hubDescribeWait`) for it. No model writes any of it. Which agents show the instructions, from their installed source (11-02): Claude Code (a `# MCP Server Instructions` message, 4096 characters), Codex (the namespace's description), OpenCode (`<mcp_instructions>`), Gemini CLI (in a trusted folder only), Qwen Code (the opening history), Pi (the first line in its prompt, the whole through codemode); Kimi CLI reads none, and none of them shows `serverInfo.title` to the model. Pi doesn't wait for a codemode server before writing the first prompt (`waitForDirectServers` waits for direct ones), so its instructions miss that prompt; Pi's own mcp.json (`fmtPiNative`) gets the same line as the hub entry's `description`, which Pi shows before connecting (`serverSummary`). It is magpie's on the hub entry only (`mine`), read back to tell a changed list of servers (`Server.about`, `same`), and any other entry's description is the user's. | `HubLine`, `hubAbout`, `hubDetails`, `hubServerLine`, `hubServersFor` in `hub_mcp.go`; `theHub.Servers`, `hubAbouts`, `hubServerFor` in `mcp_hub.go`; `hubServerOf`, `noteCard`, `saysOf` in [`mcp_hub_cards.go`](../../internal/library/mcp_hub_cards.go); `serverAbout` in [`market.go`](../../internal/library/market.go) |
| Tools on demand | An agent with no tool search of its own sends every tool, with its `inputSchema`, on every request (ArvinCharl on X, 11-04: the tools filled the context). Past `hubOnDemandOver` (10) tools, `hubOnDemand` gives it two in their place: `find_tools {query, server?}` scores each tool on the query's words (a word in its router name 3, in its description 1, the whole query in its name 5 more; `hubMatches`) and answers the best 5 with their name, description and `inputSchema`, then up to 15 more by name with their first clause; an empty query, or one nothing matches, names every tool. `call_tool {name, arguments}` runs the tool by its router name as `tools/call` finds it (`hubToolNamed`), else the one tool with that name on its server in any case (`hubCallNamed`); `arguments` given as a string holding an object is that object. It runs through the same caller, roots and key limit as `tools/call` (`hubCall`), and its request-log row names the tool that ran (`mcpUse.named`). A name nothing gives is an error naming the close ones. `tools/call` takes both names whatever was listed, and still runs a tool by its own name. `initialize`'s instructions add `Its tools are given on demand: …` (counted from `HubServer.Tools`), and still name each server's tools (`hubDetails`), so the model knows what there is to find. The Library's switch Tools on demand (on by default) turns it off for every agent: `settings.RouterAllTools`, this computer's own (`KeepOwn`), set alone (`SetRouterAllTools`) and kept by the Settings page's save. | `hubOnDemand`, `hubFind`, `hubCallByName` in [`hub_ondemand.go`](../../internal/gateway/hub_ondemand.go); `hubCall` in `hub_mcp.go`; `RouterAllTools`, `SetRouterAllTools` in `settings.go`; `servers/hub-tools` in `gui/library.go`; `View.HubAllTools` in `sync.go` |
| Router name | What a router says of itself, for an agent given the same tools by two routers (packinggoodsllc_07668 on Discord: one magpie in China, one in Los Angeles) to pick one. `hubWhere`: the user's words (`settings.RouterNote`, one line, 80 characters at most, `CleanRouterNote`), to every caller; with none, this computer's name (`hostName`) to a caller that isn't `local`, and nothing to one that is (one router at hand; the computer's name stays off its prompts). With a value, `initialize`'s `instructions` say `This router: <name>. …` on their second line (at the end when no server is behind it), `serverInfo.title` is `Magpie MCP hub · <name>`, and each tool's description starts `[<name>] ` (once: a description that starts so already, another magpie's router behind this one, isn't given it again). It is this computer's own (`KeepOwn`): a sync never brings another's. Set in the Library's MCP tab (below) or settings.json; the Settings page's save keeps it (`POST /api/settings`). | `hubWhere` in `hub_mcp.go`; `RouterNote`, `SetRouterNote` in [`settings.go`](../../internal/settings/settings.go); `servers/hub-note` in `gui/library.go`; `View.HubNote`, `View.HubName` in `sync.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`](../../internal/gateway/mcp_ask.go); `imageMeta` in `mcp_hub.go`; `project`, `rootOf` in [`imagemcp.go`](../../internal/imagemcp/imagemcp.go); [`codex_cwd.go`](../../internal/sessions/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`](../../internal/gateway/search_mcp.go) |
| Each caller's Magpie Browser session | One `magpie mcp browser` backend serves every agent behind the router, so it alone would be one browser session: every agent in one tab (packinggoodsllc_07668 on Discord). serveMCP gives a client that initializes an `Mcp-Session-Id` (`newMCPSession`; magpie keeps nothing by it and refuses nothing for it), and each `tools/call` is given the caller's session (`hubSession`): the `_meta` `magpie/session` a router in front of this one named, else `hub-<agent>-<Mcp-Session-Id>`, else none. The router passes it on in `_meta` `magpie/session` (`HubSessionMeta`) only to `magpie mcp browser` and to another magpie's router (`keepsSession`), and the bridge sends it as the `X-Magpie-Browser-Session` of that call (`callerSession`), so two agents, or two windows of one, work in tabs of their own; a call that names none goes as the bridge's own session, as before. | `hubSession`, `newMCPSession` in `hub_mcp.go` and `search_mcp.go`; `keepsSession` in `mcp_hub.go`; `callerSession` in [`browsermcp.go`](../../internal/browsermcp/browsermcp.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 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…, then a Router name row (`.lib-hubnoterow`) with a field (`.lib-hubname`, no native control) holding `hubNote` and `hubName` as its placeholder, saved on Enter or leaving it through `servers/hub-note` `{note}` (Escape puts the saved words back; an input method's Enter is its own), 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`](../../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…, then a Router name row (`.lib-hubnoterow`) with a field (`.lib-hubname`, no native control) holding `hubNote` and `hubName` as its placeholder, saved on Enter or leaving it through `servers/hub-note` `{note}` (Escape puts the saved words back; an input method's Enter is its own), then a Tools on demand row (`.lib-hubtoolsrow`) whose switch is on while `hubAllTools` is false and posts `servers/hub-tools` `{on}` (on: every tool whole), 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`](../../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 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`](../../internal/cli/library_cli.go)).
@@ -30,7 +31,7 @@ The gateway can't import the library (the library imports the gateway), so the g
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](gateway-sessions.md#calls-to-magpies-own-mcp-tools)).
5. Each call is a row of the request log (`serveMCP`'s `callMCPTool`): the router's tool name (for `call_tool`, the tool it ran), 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](gateway-sessions.md#calls-to-magpies-own-mcp-tools)).
## Constraints and failure behavior
@@ -46,12 +47,12 @@ The gateway can't import the library (the library imports the gateway), so the g
## Verification
```sh
go test -tags nogui ./internal/gui -run 'TestHubOpen|TestHubNote'
go test -tags nogui ./internal/gui -run 'TestHubOpen|TestHubNote|TestHubAllTools'
go test -tags nogui ./internal/library -run 'TestHub|TestRunDirect|TestFakeMCPServer|TestCheck|TestPluginTools'
go test -tags nogui ./internal/settings -run TestRouterNote
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 internal/gui/tests/library-mcp-router-note.test.cjs
node --test internal/gui/tests/library-mcp-hub.test.cjs internal/gui/tests/mcp-hub-direct.test.cjs internal/gui/tests/library-mcp-router-note.test.cjs internal/gui/tests/library-mcp-router-tools.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`.
+30 -25
View File
@@ -464,6 +464,9 @@ func (s *Server) hubMCPCall(r *http.Request, agent string, m mcpMessage) (any, m
if MCPHub != nil {
ss = hubServersFor(r.Context(), agent)
}
if hubOnDemand(agent, hubToolCount(ss)) {
say += hubOnDemandSay
}
say = hubAbout(ss, here, say)
if MCPHub == nil || !MCPHub.On() {
say = errHubOff
@@ -479,25 +482,12 @@ func (s *Server) hubMCPCall(r *http.Request, agent string, m mcpMessage) (any, m
case "tools/list":
ts := hubTools(r.Context(), agent)
where := hubWhere(r)
if hubOnDemand(agent, len(ts)) {
return map[string]any{"tools": hubOnDemandSpecs(where)}, nil
}
list := make([]any, 0, len(ts))
for _, t := range ts {
spec := make(map[string]json.RawMessage, len(t.Spec)+1)
for k, v := range t.Spec {
spec[k] = v
}
name, _ := json.Marshal(t.name)
spec["name"] = name
if s, ok := spec["inputSchema"]; !ok || !json.Valid(s) {
spec["inputSchema"] = json.RawMessage(`{"type":"object","properties":{}}`)
}
if where != "" {
var d string
json.Unmarshal(spec["description"], &d)
d, _ = strings.CutPrefix(d, "["+where+"]")
d = strings.TrimSpace("[" + where + "] " + strings.TrimSpace(d))
spec["description"], _ = json.Marshal(d)
}
list = append(list, spec)
list = append(list, hubSpecOf(t, where))
}
return map[string]any{"tools": list}, nil
case "tools/call":
@@ -513,14 +503,17 @@ func (s *Server) hubMCPCall(r *http.Request, agent string, m mcpMessage) (any, m
return toolResult(errHubOff, true), nil
}
ts := hubTools(r.Context(), agent)
t, ok := hubToolNamed(ts, agent, p.Name)
if ok {
c := HubCaller{Session: hubSession(r, agent, p.Meta)}
if t.Roots {
c.Roots, c.Client = hubRoots(r, p.Meta), hubClient(r)
}
r = r.WithContext(WithHubCaller(r.Context(), c))
return s.hubMCPRun(r, agent, t, p.Arguments), nil
// the two tools an agent given its tools on demand calls them by
// (hub_ondemand.go), taken whatever it was given: what it lists
// can change between its list and its call
switch p.Name {
case hubFindTool:
return hubFind(ts, p.Arguments, hubWhere(r)), nil
case hubCallTool:
return s.hubCallByName(r, agent, ts, p.Arguments, p.Meta), nil
}
if t, ok := hubToolNamed(ts, agent, p.Name); ok {
return s.hubCall(r, agent, t, p.Arguments, p.Meta), nil
}
if agent == "" {
return nil, map[string]any{"code": -32602, "message": "unknown tool " + p.Name + ": no MCP server in magpie's Library gives it"}
@@ -565,6 +558,17 @@ func hubToolNamed(ts []hubTool, agent, name string) (hubTool, bool) {
return found[0], true
}
// hubCall runs t for the caller r is: its session, and for a tool that
// reads them, its workspaces and client (HubCaller).
func (s *Server) hubCall(r *http.Request, agent string, t hubTool, args json.RawMessage, meta hubCallMeta) any {
c := HubCaller{Session: hubSession(r, agent, meta)}
if t.Roots {
c.Roots, c.Client = hubRoots(r, meta), hubClient(r)
}
r = r.WithContext(WithHubCaller(r.Context(), c))
return s.hubMCPRun(r, agent, t, args)
}
// hubMCPRun runs one tool on its server, held to the calling gateway key's
// limit. A server that is down or doesn't answer in time is an error
// result naming it, never a wait past the client's.
@@ -573,6 +577,7 @@ func (s *Server) hubMCPRun(r *http.Request, agent string, t hubTool, args json.R
use := mcpUseOf(r.Context())
use.on(t.Server)
use.as(agent)
use.named(t.name)
release, err := reserveFor(access.Caller(r.Context()), int64(len(args)), "", limitClock())
if err != nil {
return toolResult(err.Error(), true)
+302
View File
@@ -0,0 +1,302 @@
package gateway
import (
"cmp"
"encoding/json"
"net/http"
"slices"
"strings"
"unicode"
"github.com/yetone/magpie/internal/settings"
)
// The router's tools on demand (ArvinCharl on X, 11-04: MCP tools fill
// the context). An agent that searches its MCP tools itself, loading one
// only when its model asks for it, is given every tool: Claude Code
// (ENABLE_TOOL_SEARCH, agent/claude.go), Claude Desktop, whose Code tab is
// Claude Code, Codex (supports_search_tool, codexcat.go) and Pi, whose MCP
// extension lists a server's tools only when they are searched for. Any
// other agent sends every tool it is given, with its whole inputSchema, on
// every request, so past hubOnDemandOver tools it is given two in their
// place: find_tools, which gives the tools that match what the model looks
// for with their parameters, and call_tool, which runs one by name. The
// instructions still name every server and its tools (hubDetails), so the
// model knows what there is to find. settings' RouterAllTools turns it off.
// hubFindTool and hubCallTool are the two tools. A tool of the hub's is
// <server>__<tool>, so neither is ever one of its tools' names.
const (
hubFindTool = "find_tools"
hubCallTool = "call_tool"
)
// hubOnDemandOver is how many tools an agent is given whole at most: a
// few tools cost less than a search before each call.
const hubOnDemandOver = 10
// hubSearchesItself are the agents that load MCP tools only when searched
// for, by their id without a WSL distro (claude@wsl:Ubuntu is claude).
var hubSearchesItself = map[string]bool{"claude": true, "claude-desktop": true, "codex": true, "pi": true}
// hubFindFull is how many of find_tools' matches come with their
// parameters, and hubFindMore how many more it names after them.
const (
hubFindFull = 5
hubFindMore = 15
)
// hubOnDemand is whether agent is given find_tools and call_tool in place
// of its n tools. The address for any other app ("") lists every tool:
// which app connects there isn't known.
func hubOnDemand(agent string, n int) bool {
if agent == "" || n <= hubOnDemandOver {
return false
}
id, _, _ := strings.Cut(agent, "@")
if hubSearchesItself[id] {
return false
}
return !settings.Shared().RouterAllTools
}
// hubToolCount is how many tools ss have, as the instructions know them.
func hubToolCount(ss []HubServer) int {
n := 0
for _, s := range ss {
n += len(s.Tools)
}
return n
}
// hubOnDemandSay is what the instructions add when the tools are on demand.
const hubOnDemandSay = " Its tools are given on demand: " + hubFindTool + " gives a tool's description and parameters, and " + hubCallTool + " runs it by name."
// hubOnDemandSpecs are the two tools an agent is given in place of its
// tools, their descriptions after where, as each tool's are.
func hubOnDemandSpecs(where string) []any {
pre := ""
if where != "" {
pre = "[" + where + "] "
}
return []any{
map[string]any{
"name": hubFindTool,
"description": pre + "Finds the tools of the MCP servers behind this one that match query: words of what you want done, or a tool's name. Gives each match's name, description and parameters (inputSchema); run one with " + hubCallTool + ". An empty query names every tool.",
"inputSchema": json.RawMessage(`{"type":"object","properties":{"query":{"type":"string","description":"Words of what you want done, or a tool's name; empty names every tool"},"server":{"type":"string","description":"Only this server's tools"}}}`),
},
map[string]any{
"name": hubCallTool,
"description": pre + "Runs a tool of the MCP servers behind this one, by the name " + hubFindTool + " gives it (<server>__<tool>), with arguments as its inputSchema says.",
"inputSchema": json.RawMessage(`{"type":"object","properties":{"name":{"type":"string","description":"The tool's name, <server>__<tool>"},"arguments":{"type":"object","description":"The tool's arguments, as its inputSchema says"}},"required":["name"]}`),
},
}
}
// hubSpecOf is t as tools/list gives it: its own spec, named as the hub
// names it, with an inputSchema, its description after where.
func hubSpecOf(t hubTool, where string) map[string]json.RawMessage {
spec := make(map[string]json.RawMessage, len(t.Spec)+1)
for k, v := range t.Spec {
spec[k] = v
}
name, _ := json.Marshal(t.name)
spec["name"] = name
if s, ok := spec["inputSchema"]; !ok || !json.Valid(s) {
spec["inputSchema"] = json.RawMessage(`{"type":"object","properties":{}}`)
}
if where != "" {
var d string
json.Unmarshal(spec["description"], &d)
d, _ = strings.CutPrefix(d, "["+where+"]")
d = strings.TrimSpace("[" + where + "] " + strings.TrimSpace(d))
spec["description"], _ = json.Marshal(d)
}
return spec
}
// hubDesc is t's description as its server gives it.
func hubDesc(t hubTool) string {
var d string
json.Unmarshal(t.Spec["description"], &d)
return d
}
// hubWords are s's words, lower case, split at anything not a letter or
// digit (create_issue is create and issue).
func hubWords(s string) []string {
return strings.FieldsFunc(strings.ToLower(s), func(r rune) bool { return !unicode.IsLetter(r) && !unicode.IsDigit(r) })
}
// hubScore is how well t matches query's words: a word in its name
// counts three, in its description one, and the whole query in its name
// five more.
func hubScore(t hubTool, query string, words []string) int {
name := strings.ToLower(t.name)
desc := strings.ToLower(hubDesc(t))
n := 0
for _, w := range words {
switch {
case strings.Contains(name, w):
n += 3
case strings.Contains(desc, w):
n++
}
}
if q := strings.ToLower(strings.TrimSpace(query)); q != "" && n > 0 && (strings.Contains(name, q) || strings.EqualFold(t.Tool, q)) {
n += 5
}
return n
}
// hubMatches are ts best matching query first, those that don't left out.
func hubMatches(ts []hubTool, query string) []hubTool {
words := hubWords(query)
type scored struct {
t hubTool
n int
}
var out []scored
for _, t := range ts {
if n := hubScore(t, query, words); n > 0 {
out = append(out, scored{t, n})
}
}
slices.SortStableFunc(out, func(a, b scored) int { return cmp.Compare(b.n, a.n) })
ms := make([]hubTool, len(out))
for i, s := range out {
ms[i] = s.t
}
return ms
}
// hubOfServer are ts of the server named server, as the user or the hub
// names it, in any case; "" is every tool.
func hubOfServer(ts []hubTool, server string) []hubTool {
server = strings.TrimSpace(server)
if server == "" {
return ts
}
var out []hubTool
for _, t := range ts {
if strings.EqualFold(t.Server, server) || strings.EqualFold(unsafeToolChars.ReplaceAllString(t.Server, "-"), server) {
out = append(out, t)
}
}
return out
}
// hubNameLines name ts, one a line, each with the first clause of what it
// does.
func hubNameLines(ts []hubTool) string {
var b strings.Builder
for _, t := range ts {
b.WriteString("- " + t.name)
if c := hubToolClause(hubDesc(t)); c != "" {
b.WriteString(": " + c)
}
b.WriteByte('\n')
}
return b.String()
}
// hubFind answers find_tools: the matches with their parameters, then
// more by name; with no query, or none matching, every tool by name.
func hubFind(ts []hubTool, args json.RawMessage, where string) any {
var p struct {
Query string `json:"query"`
Server string `json:"server"`
}
json.Unmarshal(args, &p)
ts = hubOfServer(ts, p.Server)
if len(ts) == 0 {
if p.Server != "" {
return toolResult("No server called "+p.Server+" is behind this one. Call "+hubFindTool+" without server for every tool.", true)
}
return toolResult("No MCP server behind this one has a tool now.", true)
}
if strings.TrimSpace(p.Query) == "" {
return toolResult("Every tool, by name; "+hubFindTool+" with its name gives its parameters:\n"+hubNameLines(ts), false)
}
ms := hubMatches(ts, p.Query)
if len(ms) == 0 {
return toolResult("No tool matches \""+p.Query+"\". Every tool, by name:\n"+hubNameLines(ts), false)
}
full := ms[:min(len(ms), hubFindFull)]
specs := make([]any, 0, len(full))
for _, t := range full {
spec := hubSpecOf(t, "")
specs = append(specs, map[string]json.RawMessage{"name": spec["name"], "description": spec["description"], "inputSchema": spec["inputSchema"]})
}
b, _ := json.MarshalIndent(specs, "", " ")
out := "Run one with " + hubCallTool + ", its name and arguments as its inputSchema says.\n" + string(b)
if more := ms[len(full):min(len(ms), hubFindFull+hubFindMore)]; len(more) > 0 {
out += "\nAlso matching (" + hubFindTool + " with a name gives its parameters):\n" + hubNameLines(more)
}
return toolResult(out, false)
}
// hubCallArgs is call_tool's arguments: the tool's name, and its own
// arguments, an object; given as a string holding one, as some models
// send it, the object it holds.
func hubCallArgs(args json.RawMessage) (name string, inner json.RawMessage, err error) {
var p struct {
Name string `json:"name"`
Arguments json.RawMessage `json:"arguments"`
}
if err := json.Unmarshal(args, &p); err != nil {
return "", nil, err
}
inner = p.Arguments
var s string
if json.Unmarshal(inner, &s) == nil {
if s = strings.TrimSpace(s); s == "" {
inner = nil
} else if json.Valid([]byte(s)) {
inner = json.RawMessage(s)
}
}
return strings.TrimSpace(p.Name), inner, nil
}
// hubCallNamed is the tool call_tool names: as tools/call finds it
// (hubToolNamed), else the one tool of that name on its server, in any
// case.
func hubCallNamed(ts []hubTool, agent, name string) (hubTool, bool) {
if t, ok := hubToolNamed(ts, agent, name); ok {
return t, true
}
var found []hubTool
for _, t := range ts {
if strings.EqualFold(t.name, name) || strings.EqualFold(t.Tool, name) {
found = append(found, t)
}
}
if len(found) != 1 {
return hubTool{}, false
}
return found[0], true
}
// hubCallByName answers call_tool: the tool it names run as tools/call runs
// it, or, for a name no server gives, the tools close to it.
func (s *Server) hubCallByName(r *http.Request, agent string, ts []hubTool, args json.RawMessage, meta hubCallMeta) any {
name, inner, err := hubCallArgs(args)
if err != nil {
return toolResult(hubCallTool+" takes {\"name\": \"<server>__<tool>\", \"arguments\": {…}}: "+err.Error(), true)
}
if name == "" {
return toolResult(hubCallTool+" needs the name of the tool to run; "+hubFindTool+" gives the tools' names.", true)
}
t, ok := hubCallNamed(ts, agent, name)
if !ok {
why := "No tool is called " + name + "."
if ms := hubMatches(ts, name); len(ms) > 0 {
why += " Close to it:\n" + hubNameLines(ms[:min(len(ms), hubFindFull)])
} else {
why += " " + hubFindTool + " gives the tools' names."
}
return toolResult(why, true)
}
return s.hubCall(r, agent, t, inner, meta)
}
+162
View File
@@ -0,0 +1,162 @@
package gateway
import (
"encoding/json"
"fmt"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/usage"
)
// manyHubTools are n tools of two servers, github's create_issue among
// them, more than an agent is given whole.
func manyHubTools(n int) []HubTool {
ts := []HubTool{{Server: "github", Tool: "create_issue", Spec: map[string]json.RawMessage{
"name": json.RawMessage(`"create_issue"`),
"description": json.RawMessage(`"Opens a new issue in a GitHub repository. Needs a title."`),
"inputSchema": json.RawMessage(`{"type":"object","properties":{"title":{"type":"string"}},"required":["title"]}`),
}}}
for i := 1; len(ts) < n; i++ {
ts = append(ts, HubTool{Server: "fs", Tool: fmt.Sprintf("op%d", i), Spec: hubSpec(fmt.Sprintf("op%d", i))})
}
return ts
}
func listedNames(t *testing.T, m mcpReply) []string {
t.Helper()
var out []string
for _, x := range m.Result.Tools {
out = append(out, x.Name)
}
return out
}
func initInstructions(t *testing.T, body string) string {
t.Helper()
var m struct {
Result struct{ Instructions string }
}
if err := json.Unmarshal([]byte(body), &m); err != nil {
t.Fatalf("%v: %s", err, body)
}
return m.Result.Instructions
}
const hubInit = `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}`
// An agent that doesn't search its MCP tools itself, given more than
// hubOnDemandOver, is given find_tools and call_tool in their place
// (ArvinCharl on X: the tools filled the context); the instructions say
// so and still name each server's tools. find_tools gives a match's
// parameters, call_tool runs it by its name, its bare name or with its
// arguments as a string, and a name no server gives is told the close
// ones. A tool called by its own name still runs.
func TestHubMCPToolsOnDemand(t *testing.T) {
fresh(t)
tools := manyHubTools(hubOnDemandOver + 2)
f := &fakeHub{on: true, tools: map[string][]HubTool{"opencode": tools},
servers: map[string][]HubServer{"opencode": {
{Name: "github", Known: true, Tools: []HubToolNote{{Name: "create_issue", About: "Opens a new issue"}}},
{Name: "fs", Known: true, Tools: func() (ns []HubToolNote) {
for _, x := range tools[1:] {
ns = append(ns, HubToolNote{Name: x.Tool})
}
return
}()},
}}}
withHub(t, f)
h := lanGuard(New().Handler())
say := initInstructions(t, hubPost(h, "opencode", here, hubInit).Body.String())
if !strings.Contains(say, "on demand") || !strings.Contains(say, "create_issue") {
t.Fatalf("instructions: %s", say)
}
if got := listedNames(t, readMCP(t, hubPost(h, "opencode", here, toolsList))); !slices.Equal(got, []string{hubFindTool, hubCallTool}) {
t.Fatalf("listed %v", got)
}
found := readMCP(t, hubPost(h, "opencode", here, toolsCall(hubFindTool, `{"query":"open an issue"}`)))
if found.Result.IsError || len(found.Result.Content) == 0 {
t.Fatalf("find: %+v", found)
}
text := found.Result.Content[0].Text
if !strings.Contains(text, `"github__create_issue"`) || !strings.Contains(text, `"required"`) || strings.Contains(text, "fs__op") {
t.Fatalf("find gave: %s", text)
}
all := readMCP(t, hubPost(h, "opencode", here, toolsCall(hubFindTool, `{}`))).Result.Content[0].Text
for _, x := range []string{"github__create_issue", "fs__op1", "fs__op11"} {
if !strings.Contains(all, x) {
t.Fatalf("an empty query left out %s: %s", x, all)
}
}
if s := readMCP(t, hubPost(h, "opencode", here, toolsCall(hubFindTool, `{"query":"op","server":"github"}`))); strings.Contains(s.Result.Content[0].Text, "fs__") {
t.Fatalf("server not kept to: %s", s.Result.Content[0].Text)
}
for _, args := range []string{
`{"name":"github__create_issue","arguments":{"title":"a"}}`,
`{"name":"create_issue","arguments":{"title":"a"}}`,
`{"name":"github__create_issue","arguments":"{\"title\":\"a\"}"}`,
} {
ran := readMCP(t, hubPost(h, "opencode", here, toolsCall(hubCallTool, args)))
if ran.Result.IsError || ran.Result.Content[0].Text != "ran github create_issue" {
t.Fatalf("call_tool %s: %+v", args, ran)
}
}
for _, c := range f.ran() {
if c != `opencode github create_issue {"title":"a"}` {
t.Fatalf("ran %q", c)
}
}
missed := readMCP(t, hubPost(h, "opencode", here, toolsCall(hubCallTool, `{"name":"create_isue"}`)))
if !missed.Result.IsError || !strings.Contains(missed.Result.Content[0].Text, "github__create_issue") {
t.Fatalf("an unknown name: %+v", missed)
}
if direct := readMCP(t, hubPost(h, "opencode", here, toolsCall("fs__op3", `{"q":"x"}`))); direct.Result.IsError {
t.Fatalf("by its own name: %+v", direct)
}
// the row names the tool that ran, not call_tool
rows := mcpRows(t)
if len(rows) == 0 || !slices.ContainsFunc(rows, func(r usage.Record) bool { return r.Requested == "github__create_issue" && r.Host == "github" }) ||
slices.ContainsFunc(rows, func(r usage.Record) bool { return r.Requested == hubCallTool && r.Error == "" }) {
t.Fatalf("rows %+v", rows)
}
}
// An agent that searches its tools itself (a WSL one's id too), the
// address for any other app, an agent given a few tools, and every agent
// once the user turns on every tool whole, are given every tool.
func TestHubMCPToolsWhole(t *testing.T) {
fresh(t)
many := manyHubTools(hubOnDemandOver + 2)
f := &fakeHub{on: true, tools: map[string][]HubTool{
"claude": many, "claude@wsl:Ubuntu": many, "claude-desktop": many, "codex": many, "pi": many, "": many,
"gemini": manyHubTools(hubOnDemandOver), "opencode": many,
}}
withHub(t, f)
h := lanGuard(New().Handler())
for _, a := range []string{"claude", "claude@wsl:Ubuntu", "claude-desktop", "codex", "pi", "gemini"} {
if got := listedNames(t, readMCP(t, hubPost(h, a, here, toolsList))); len(got) != len(f.tools[a]) {
t.Fatalf("%s listed %v", a, got)
}
}
if got := listedNames(t, readMCP(t, hubPostAt(h, HubMCPAll, here, toolsList))); len(got) != len(many) {
t.Fatalf("any app listed %v", got)
}
s := settings.Load()
s.RouterAllTools = true
if err := settings.Save(s); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
s := settings.Load()
s.RouterAllTools = false
settings.Save(s)
})
if got := listedNames(t, readMCP(t, hubPost(h, "opencode", here, toolsList))); len(got) != len(many) {
t.Fatalf("with every tool whole, listed %v", got)
}
}
+18
View File
@@ -49,6 +49,9 @@ type mcpUseKey struct{}
type mcpUse struct {
mu sync.Mutex
agent, server, provider, model string
// tool is the tool that ran, when the call named another: the hub's
// call_tool runs the tool it names
tool string
}
func mcpUseOf(ctx context.Context) *mcpUse {
@@ -106,6 +109,16 @@ func (u *mcpUse) as(agent string) {
u.mu.Unlock()
}
// named names the tool that ran, for the hub's call_tool.
func (u *mcpUse) named(tool string) {
if u == nil || tool == "" {
return
}
u.mu.Lock()
u.tool = tool
u.mu.Unlock()
}
func (u *mcpUse) get() (agent, server, provider, model string) {
u.mu.Lock()
defer u.mu.Unlock()
@@ -122,6 +135,11 @@ func callMCPTool(r *http.Request, server string, m mcpMessage, call func(*http.R
}
json.Unmarshal(m.Params, &p)
agent, server, prov, model := use.get()
use.mu.Lock()
if use.tool != "" {
p.Name = use.tool
}
use.mu.Unlock()
logMCPCall(r, agent, server, r.URL.Path, p.Name, prov, model, start, time.Since(start), mcpFailure(result, rpcErr))
return result, rpcErr
}
+20 -1
View File
@@ -1741,7 +1741,7 @@ magpie.plugin("library", (ctx) => {
connect.classList.add("lib-hubconnect");
at.append(glyph(GLYPH.web), aw, copyBtn(hubURL(), t("Address")), connect);
list.append(at);
list.append(hubNoteRow());
list.append(hubNoteRow(), hubToolsRow());
const names = (why) => hubAgents().filter((a) => a.hub === why).map((a) => a.name).join(", ");
const why = [
["no-remote", "{agents} reaches no MCP server over HTTP, so it keeps each server's own entry."],
@@ -1803,6 +1803,25 @@ magpie.plugin("library", (ctx) => {
row.append(glyph(GLYPH.doc), who, f);
return row;
}
// Tools on demand (ArvinCharl on X: the router's tools filled the
// context): on, the default, an agent that doesn't search its MCP tools
// itself and is given more than a few is given two in their place, one
// finding a tool and one running it (gateway.hubOnDemand). Off gives
// every agent every tool whole (settings' routerAllTools).
function hubToolsRow() {
const row = el("div", "row lib-row lib-hubtoolsrow");
const who = el("div", "who");
who.append(el("div", "name", t("Tools on demand")));
who.append(el("div", "sub wraps", t("An agent given more than 10 tools gets two in their place, one that finds a tool and one that runs it, so their definitions stay out of every request. Claude Code, Claude Desktop, Codex and Pi find tools themselves and are given every one.")));
const on = !lib.hubAllTools;
row.append(glyph(GLYPH.search), who, toggle(on, t("Tools on demand"), (v) =>
change("servers/hub-tools", { on: !v }).then((ok) => {
if (ok) status(v
? t("Agents are given the router's tools on demand — restart them to use it")
: t("Agents are given every tool of the router — restart them to use it"), "ok");
})));
return row;
}
// every server is behind the hub, magpie's own image server too, but one
// the user keeps direct (#4382): each agent's own entry (inHub in
// mcp_hub.go)
@@ -2,6 +2,10 @@
// kernel adds them to i18n.js's (magpie.strings).
magpie.strings({
zh: {
"Tools on demand": "按需加载工具",
"An agent given more than 10 tools gets two in their place, one that finds a tool and one that runs it, so their definitions stay out of every request. Claude Code, Claude Desktop, Codex and Pi find tools themselves and are given every one.": "给一个 Agent 的工具超过 10 个时,改为给它两个工具:一个查找工具,一个运行工具,这样工具定义不会出现在每次请求里。Claude Code、Claude Desktop、Codex 和 Pi 会自己查找工具,仍会拿到全部工具。",
"Agents are given the router's tools on demand — restart them to use it": "Agent 现在按需拿到路由的工具 — 重启它们后生效",
"Agents are given every tool of the router — restart them to use it": "Agent 现在拿到路由的全部工具 — 重启它们后生效",
"Show more ({n} left)": "显示更多(还有 {n} 个)",
"Not through the router": "不经过路由",
"Each agent is given its own entry for it, as with the MCP router off": "每个 Agent 各自有它的条目,和关掉 MCP 路由时一样",
@@ -773,6 +777,10 @@ magpie.strings({
"{agents} can be changed once it runs.": "{agents} 要等它运行后才能修改。",
},
"zh-TW": {
"Tools on demand": "按需載入工具",
"An agent given more than 10 tools gets two in their place, one that finds a tool and one that runs it, so their definitions stay out of every request. Claude Code, Claude Desktop, Codex and Pi find tools themselves and are given every one.": "給一個 Agent 的工具超過 10 個時,改為給它兩個工具:一個尋找工具,一個執行工具,這樣工具定義不會出現在每次請求裡。Claude Code、Claude Desktop、Codex 和 Pi 會自己尋找工具,仍會拿到全部工具。",
"Agents are given the router's tools on demand — restart them to use it": "Agent 現在按需取得路由的工具 — 重新啟動它們後生效",
"Agents are given every tool of the router — restart them to use it": "Agent 現在取得路由的全部工具 — 重新啟動它們後生效",
"Show more ({n} left)": "顯示更多(還有 {n} 個)",
"Not through the router": "不經過路由",
"Each agent is given its own entry for it, as with the MCP router off": "每個 Agent 各自有它的條目,和關掉 MCP 路由時一樣",
@@ -1544,6 +1552,10 @@ magpie.strings({
"{agents} can be changed once it runs.": "{agents} 要等它執行後才能修改。",
},
ja: {
"Tools on demand": "ツールをオンデマンドで渡す",
"An agent given more than 10 tools gets two in their place, one that finds a tool and one that runs it, so their definitions stay out of every request. Claude Code, Claude Desktop, Codex and Pi find tools themselves and are given every one.": "エージェントに渡すツールが 10 個を超えると、代わりにツールを探すものと実行するものの 2 つを渡し、ツールの定義が毎回のリクエストに入らないようにします。Claude Code、Claude Desktop、Codex、Pi は自分でツールを探すので、すべてのツールが渡されます。",
"Agents are given the router's tools on demand — restart them to use it": "エージェントにルーターのツールをオンデマンドで渡します — 反映するにはエージェントを再起動してください",
"Agents are given every tool of the router — restart them to use it": "エージェントにルーターのすべてのツールを渡します — 反映するにはエージェントを再起動してください",
"Show more ({n} left)": "さらに表示(残り {n} 件)",
"Not through the router": "ルーターを通さない",
"Each agent is given its own entry for it, as with the MCP router off": "各エージェントに個別のエントリを渡します(MCP ルーターがオフのときと同じ)",
@@ -2315,6 +2327,10 @@ magpie.strings({
"{agents} can be changed once it runs.": "{agents} は起動後に変更できます。",
},
de: {
"Tools on demand": "Tools bei Bedarf",
"An agent given more than 10 tools gets two in their place, one that finds a tool and one that runs it, so their definitions stay out of every request. Claude Code, Claude Desktop, Codex and Pi find tools themselves and are given every one.": "Ein Agent, der mehr als 10 Tools bekäme, bekommt stattdessen zwei: eines findet ein Tool, das andere führt es aus, damit ihre Definitionen nicht in jeder Anfrage stehen. Claude Code, Claude Desktop, Codex und Pi suchen Tools selbst und bekommen alle.",
"Agents are given the router's tools on demand — restart them to use it": "Agents bekommen die Tools des Routers bei Bedarf — starte sie neu, damit sie es nutzen",
"Agents are given every tool of the router — restart them to use it": "Agents bekommen alle Tools des Routers — starte sie neu, damit sie es nutzen",
"Show more ({n} left)": "Mehr zeigen (noch {n})",
"Not through the router": "Nicht über den Router",
"Each agent is given its own entry for it, as with the MCP router off": "Jeder Agent bekommt einen eigenen Eintrag dafür, wie bei ausgeschaltetem MCP-Router",
+3
View File
@@ -498,6 +498,9 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
// what the router says of itself to the agents, this
// computer's own (settings.RouterNote)
err = settings.SetRouterNote(in.Note)
case "servers/hub-tools":
// every tool given whole, not on demand (settings.RouterAllTools)
err = settings.SetRouterAllTools(in.On)
case "servers/hub-open":
// the hub added to another app through its install link,
// built here: the page names the app, never the link
+33
View File
@@ -43,3 +43,36 @@ func TestHubNoteSaved(t *testing.T) {
t.Fatalf("cleared: %d %q", rec.Code, settings.Load().RouterNote)
}
}
// The router's switch for giving every agent its tools whole, not on
// demand (ArvinCharl on X), is this computer's setting, comes back in the
// page's view, and a save from the Settings page leaves it as it is.
func TestHubAllToolsSaved(t *testing.T) {
sandboxHome(t)
h := Handler(nil, nil)
post := func(path, body string) *httptest.ResponseRecorder {
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(body)))
return rec
}
rec := post("/api/library/servers/hub-tools", `{"on":true}`)
if rec.Code != http.StatusOK {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
var v struct{ HubAllTools bool }
if err := json.Unmarshal(rec.Body.Bytes(), &v); err != nil {
t.Fatal(err)
}
if !v.HubAllTools || !settings.Load().RouterAllTools {
t.Fatalf("view %+v, saved %v", v, settings.Load().RouterAllTools)
}
if rec := post("/api/settings", `{"theme":"dark","lang":"en"}`); rec.Code != http.StatusOK {
t.Fatalf("settings: %d %s", rec.Code, rec.Body)
}
if !settings.Load().RouterAllTools {
t.Fatal("the Settings page's save turned it off")
}
if rec := post("/api/library/servers/hub-tools", `{"on":false}`); rec.Code != http.StatusOK || settings.Load().RouterAllTools {
t.Fatalf("off: %d %v", rec.Code, settings.Load().RouterAllTools)
}
}
+1
View File
@@ -206,6 +206,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) {
was.PanelShortcut = "Ctrl+Alt+K"
was.SearcherThen = []string{"fake/m1", "fake/m2"} // set in its own row
was.RouterNote = "Los Angeles" // the Library's servers/hub-note
was.RouterAllTools = true // the Library's servers/hub-tools
was.BusyLoad = 150 // the Routing page's busy-load
if err := settings.Save(was); err != nil {
t.Fatal(err)
@@ -0,0 +1,154 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// ArvinCharl on X: the MCP router's tools fill an agent's context. With
// the router on, the Library's MCP tab has a Tools on demand row under the
// router's name: a switch, on by default (settings' routerAllTools off),
// saying that an agent given more than 10 tools gets two in their place,
// and which agents find tools themselves. A click posts servers/hub-tools
// {on: true} (every tool whole), says so, and the switch reads off; a click
// again posts {on: false}. Off, there is no row. In every language, both
// engines, wide and narrow: no sideways scroll, the switch inside its row.
// 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 { strings } = require("./strings.cjs");
const assets = path.resolve(__dirname, "../assets");
const HOME = "/Users/mg";
const fixture = (st) => ({
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
mcpHub: st.on, hubPath: "/mcp/magpie/hub/", hubNote: "", hubName: "la-box", hubAllTools: st.all,
agents: [{ id: "claude", name: "Claude Code", icon: "claudecode-color", skills: `${HOME}/.claude/skills`, mcp: `${HOME}/.claude.json`, ...(st.on ? { hub: "on" } : {}) }],
instructions: { agents: [], sets: [] }, foundServers: [], projects: [], foundSkills: [], skills: [], problems: [],
servers: [{ name: "fetch", transport: "stdio", command: "uvx", args: ["mcp-server-fetch"], agents: ["claude"] }],
});
let I18N;
function tr(lang, key, vars = {}) {
let s = key;
if (lang !== "en") {
assert.equal(typeof I18N[lang][key], "string", `${lang} has no ${JSON.stringify(key)}`);
s = I18N[lang][key];
}
return s.replace(/\{(\w+)\}/g, (m, k) => (k in vars ? String(vars[k]) : m));
}
function server(lang, st) {
return async (route) => {
const req = route.request(), url = new URL(req.url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:${st.web}};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light", gateway: "http://127.0.0.1:3425", publicURL: "https://mac.tail0.ts.net" } });
if (url.pathname === "/api/library") return json(fixture(st));
if (url.pathname === "/api/library/servers/hub-tools") {
const body = req.postDataJSON();
st.sent.push(body);
st.all = body.on;
return json(fixture(st));
}
if (url.pathname === "/api/library/mcp/check") return json({ servers: Object.fromEntries(req.postDataJSON().names.map((n) => [n, { state: "ok", tools: 1 }])) });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true } });
if (url.pathname.startsWith("/api/")) return json({});
if (url.host !== "magpie.test") return route.fulfill({ status: 404, body: "" });
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)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
const shot = async (page, name) => {
if (!process.env.ARTIFACT_DIR) return;
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `router-tools-${name}.png`) });
};
const sideways = (page) => page.evaluate(() => {
const over = [];
const w = document.documentElement.clientWidth;
if (document.documentElement.scrollWidth > w) over.push("page " + document.documentElement.scrollWidth);
for (const e of document.querySelectorAll("#view-library .lib-hubtoolsrow, #view-library .lib-hubtoolsrow .lib-switch, #view-library .lib-hubtoolsrow .who")) {
const r = e.getBoundingClientRect();
if (r.width && (r.right > w + 0.5 || r.left < -0.5)) over.push(e.className + " " + Math.round(r.left) + "–" + Math.round(r.right));
}
const row = document.querySelector("#view-library .lib-hubtoolsrow")?.getBoundingClientRect();
const f = document.querySelector("#view-library .lib-hubtoolsrow .lib-switch")?.getBoundingClientRect();
if (row && f && (f.right > row.right + 0.5 || f.top < row.top - 0.5 || f.bottom > row.bottom + 0.5)) over.push("switch out of its row");
return over;
});
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": the router's tools on demand", async (t) => {
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
I18N = strings().I18N;
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" }));
t.after(() => browser.close());
for (const width of [1100, 420]) for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
await t.test(`${lang} ${width}px`, async () => {
const w = (key, vars) => tr(lang, key, vars);
const st = { on: false, all: false, sent: [], web: width < 800 };
const errors = [];
const ctx = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" });
await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "mcp"); } catch {} });
const page = await ctx.newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang, st));
await page.goto("http://magpie.test/");
await page.locator('button[data-view="library"]').click();
const v = page.locator("#view-library");
await v.locator(".lib-hub").waitFor();
// off: no row
assert.equal(await v.locator(".lib-hubtoolsrow").count(), 0);
await ctx.close();
st.on = true;
const ctx2 = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" });
await ctx2.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "mcp"); } catch {} });
const p = await ctx2.newPage();
p.setDefaultTimeout(5000);
p.setDefaultNavigationTimeout(60000);
p.on("pageerror", (e) => errors.push(e.message));
await p.route("**/*", server(lang, st));
await p.goto("http://magpie.test/");
await p.locator('button[data-view="library"]').click();
const row = p.locator("#view-library .lib-hubtoolsrow");
await row.waitFor();
// under the router's name
const after = await p.evaluate(() => {
const at = document.querySelector("#view-library .lib-hubnoterow").getBoundingClientRect();
return document.querySelector("#view-library .lib-hubtoolsrow").getBoundingClientRect().top >= at.bottom - 0.5;
});
assert.ok(after, "the row isn't under the router's name");
assert.equal((await row.locator(".name").textContent()).trim(), w("Tools on demand"));
assert.equal((await row.locator(".sub").textContent()).trim(), w("An agent given more than 10 tools gets two in their place, one that finds a tool and one that runs it, so their definitions stay out of every request. Claude Code, Claude Desktop, Codex and Pi find tools themselves and are given every one."));
const sw = () => p.locator("#view-library .lib-hubtoolsrow .lib-switch");
assert.equal(await sw().getAttribute("aria-label"), w("Tools on demand"));
assert.equal(await sw().getAttribute("aria-checked"), "true");
assert.deepEqual(await sideways(p), [], "sideways scroll");
await shot(p, `${engine}-${lang}-${width}-on`);
// off: every tool whole
await sw().click();
await p.waitForFunction((x) => document.querySelector("#status")?.textContent === x, w("Agents are given every tool of the router — restart them to use it"));
assert.deepEqual(st.sent, [{ on: true }]);
await p.waitForFunction(() => document.querySelector("#view-library .lib-hubtoolsrow .lib-switch")?.getAttribute("aria-checked") === "false");
// on again
await sw().click();
await p.waitForFunction((x) => document.querySelector("#status")?.textContent === x, w("Agents are given the router's tools on demand — restart them to use it"));
assert.deepEqual(st.sent, [{ on: true }, { on: false }]);
await p.waitForFunction(() => document.querySelector("#view-library .lib-hubtoolsrow .lib-switch")?.getAttribute("aria-checked") === "true");
assert.deepEqual(await sideways(p), [], "sideways scroll, after");
assert.deepEqual(errors, []);
await ctx2.close();
});
}
});
}
+4 -1
View File
@@ -516,6 +516,9 @@ type View struct {
// name, to an agent on another computer (gateway.hubWhere)
HubNote string `json:"hubNote"`
HubName string `json:"hubName"`
// HubAllTools: every agent is given the router's tools whole, none on
// demand (settings' RouterAllTools, gateway.hubOnDemand)
HubAllTools bool `json:"hubAllTools"`
// CheckDue is set when the skills from GitHub weren't checked for
// updates since magpie started, or not for a while: the page checks
// them as it shows them (#1449)
@@ -578,7 +581,7 @@ func readView(problems []Problem, glance bool) (*View, error) {
// the agents are found once for the whole read: finding them looks
// through every agent's folders, in WSL too (#1624)
targets, asleep := targetsAsleep(false)
v := &View{Agents: []AgentView{}, Servers: []ServerView{}, Skills: []SkillView{}, FoundSkills: []FoundSkill{}, Instructions: l.instructionsView(targets, asleep), Dir: Dir(), Backups: BackupDir(), CopySkills: l.CopySkills, SharedSkills: l.SharedSkills, SharedDir: sharedSkillsDir(), MCPHub: l.MCPHub, HubPath: gateway.HubMCPPath, HubNote: settings.Shared().RouterNote, HubName: gateway.HostName(), Partial: glance}
v := &View{Agents: []AgentView{}, Servers: []ServerView{}, Skills: []SkillView{}, FoundSkills: []FoundSkill{}, Instructions: l.instructionsView(targets, asleep), Dir: Dir(), Backups: BackupDir(), CopySkills: l.CopySkills, SharedSkills: l.SharedSkills, SharedDir: sharedSkillsDir(), MCPHub: l.MCPHub, HubPath: gateway.HubMCPPath, HubNote: settings.Shared().RouterNote, HubName: gateway.HostName(), HubAllTools: settings.Shared().RouterAllTools, Partial: glance}
for _, t := range targets {
av := AgentView{ID: t.Agent.ID, Name: t.Agent.Name, Icon: t.Agent.Icon, Instructions: t.Instructions, Skills: t.Skills,
SkillsAlso: t.SkillsAlso, Note: t.Note, MCPVia: t.MCPVia, ProjectSkills: ProjectSkillsDir(t.Agent.ID), ProjectMCP: ProjectMCPFile(t.Agent.ID),
+9 -3
View File
@@ -11,9 +11,9 @@ import (
// alone, beside the rest of the file.
func TestRouterNote(t *testing.T) {
from := Settings{RouterNote: "China"}
from.KeepOwn(Settings{RouterNote: "Los Angeles"})
if from.RouterNote != "Los Angeles" {
t.Fatalf("a sync brought %q", from.RouterNote)
from.KeepOwn(Settings{RouterNote: "Los Angeles", RouterAllTools: true})
if from.RouterNote != "Los Angeles" || !from.RouterAllTools {
t.Fatalf("a sync brought %q, all tools %v", from.RouterNote, from.RouterAllTools)
}
if got := CleanRouterNote(" Los\tAngeles\n(US) "); got != "Los Angeles (US)" {
t.Fatalf("cleaned %q", got)
@@ -36,4 +36,10 @@ func TestRouterNote(t *testing.T) {
if s := Load(); s.RouterNote != "" {
t.Fatalf("not cleared: %q", s.RouterNote)
}
if err := SetRouterAllTools(true); err != nil {
t.Fatal(err)
}
if s := Load(); !s.RouterAllTools || s.Theme != "dark" {
t.Fatalf("saved %+v", s)
}
}
+19 -1
View File
@@ -221,6 +221,12 @@ type Settings struct {
// tool's description (gateway.hubWhere). "" is this computer's name, said
// only to an agent on another computer. This computer's own (KeepOwn).
RouterNote string `json:"routerNote,omitempty"`
// RouterAllTools gives every agent the router's tools whole. Off, an
// agent that doesn't search its MCP tools itself and is given more
// than a few is given two in their place, one that finds a tool and
// one that runs it (gateway.hubOnDemand; ArvinCharl on X: the tools
// filled the context). This computer's own (KeepOwn).
RouterAllTools bool `json:"routerAllTools,omitempty"`
// Port is the gateway's port on this computer, 0 for DefaultPort.
// MAGPIE_ADDR, where it is set, comes first (GatewayAddr).
Port int `json:"port,omitempty"`
@@ -1392,7 +1398,7 @@ func (s *Settings) KeepOwn(cur Settings) {
s.QuotaReads = cur.QuotaReads
s.NoAccountDiscovery = cur.NoAccountDiscovery
s.LAN, s.AllowIPs = cur.LAN, cur.AllowIPs
s.RouterNote = cur.RouterNote
s.RouterNote, s.RouterAllTools = cur.RouterNote, cur.RouterAllTools
s.FetchPrivate = cur.FetchPrivate
s.SessionTerminal = cur.SessionTerminal
s.PanelShortcut = cur.PanelShortcut
@@ -1903,6 +1909,18 @@ func SetRouterNote(note string) error {
return save(s, true)
}
// SetRouterAllTools sets RouterAllTools alone, from what the file holds
// now. A settings file that can't be read is left as it is, with the error.
func SetRouterAllTools(on bool) error {
defer lockFile()()
s, err := loadChecked()
if err != nil {
return err
}
s.RouterAllTools = on
return save(s, true)
}
// EditCheckinOff changes CheckinOff alone, as edit returns it from what the
// file holds now, so a save elsewhere from an older snapshot isn't undone.
// A settings file that can't be read is left as it is, with the error.
+1
View File
@@ -267,6 +267,7 @@ func Merge(body []byte, cur settings.Settings, web bool) (settings.Settings, err
in.AllowIPs = cur.AllowIPs // set on its own (allowips)
in.FetchPrivate = cur.FetchPrivate // in settings.json only
in.RouterNote = cur.RouterNote // set on its own (the Library's servers/hub-note)
in.RouterAllTools = cur.RouterAllTools // set on its own (the Library's servers/hub-tools)
in.GitHubToken = cur.GitHubToken // set on its own (github-token), never sent to the page
in.ProxyCustom = cur.ProxyCustom // set by settings.Save from the proxy, never by the page
in.RequestArchive = cur.RequestArchive // the Gateway page's, set on its own