library: an MCP server switches off for every agent and app, and on again as it was (swang20201 on X)

An installed server in Library could only be removed. Each server row
now has a switch after its agent chips. Per-agent chips already
existed, but in Docker gateway mode there are none, and the MCP router
gives every server to any app at its address, so nothing could turn a
server off there.

ServerOn (POST /api/library/servers/on, `magpie library mcp off|on
<name>`) reuses the Hidden/Paused pair a plugin's hidden server
already has. Off: Hidden, with its agents kept in Paused. On: those
agents get it back, or none when it had none, so the router gives it
to other apps again. Its command, env, headers, sign-in, DisabledTools
and note stay in library.json. Off, it is also left out of every
project's files (syncProjectMCP) and of subagents' mcpServers
(renderSubagent), which before had only skipped a server gone from
the library. The router's held process ends on the next prune,
because Hidden/Paused are in its hubKey. An off row is dimmed, its
chips take no click, and it is health-checked only on a click.
Strings are in zh, zh-TW, ja and de. docs/subsystems/library.md has
a row for it, and mcp-router.md names it.

Run (mote):
- go test ./internal/library ./internal/cli ./internal/gui: ok.
- go vet ./..., GOOS=linux -tags nogui, GOOS=windows: ok.
- gofmt -l: empty.
- GUI: the 145 files that touch the Library, i18n-keys and gui-*, in
  chromium and webkit. 2798 of 2881 passed.
  - i18n-keys was red because the key "{name} on" also matched core's
    "{name} on magpie". The key is now "Turn {name} on or off", and
    i18n-keys and library-mcp-on are green (26/26).
  - Nine files are red the same way on a clean origin/main 217d77848,
    with the same set failing on this branch: library-hooks,
    library-subagents, library-loading, library-items, list-sort,
    market-have, mobile-web, sidebar-tab-top and skill-where. The Library's
    tab strip shows MCP and has no RTK. Filed as #5850.
- library-mcp-on.test.cjs: en, zh, zh-TW, ja and de, in the app at
  1100px and in gateway mode at 420px, both engines, 22/22.

Broken by hand, each went red:
- project_mcp without the Hidden skip: the project's .mcp.json kept it.
- subagents without it: the subagent still named it.
- ServerOn not giving Paused back: on again, claude's file lacked it.
- the row without its switch, and the CSS without pointer-events:none
  on an off row's chips: library-mcp-on red.
- A Hidden check added to hubPrune stayed green, because hubKey
  already ends the process, so it was left out. The test still checks
  that the process ends.

Not tried: the real Docker image, and a real MCP server with a
sign-in (the test's server is a fake stdio one). The TUI has no
switch (the CLI has one).
This commit is contained in:
yetone
2026-11-10 10:23:53 +08:00
parent 2545bce6e7
commit 4869d0c966
14 changed files with 445 additions and 12 deletions
File diff suppressed because one or more lines are too long
+2 -2
View File
@@ -1,6 +1,6 @@
# 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 (but a plugin's server hidden from agents). 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](library.md)'s; the endpoint is the gateway's, guarded as [Plugin tools](plugin-tools.md)' `/mcp/magpie/tools` is. The switch is off by default.
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 (but one turned off, `ServerOn`, or a plugin's server hidden from agents). 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](library.md)'s; the endpoint is the gateway's, guarded as [Plugin tools](plugin-tools.md)' `/mcp/magpie/tools` is. The switch is off by default.
## Responsibilities and sources of truth
@@ -9,7 +9,7 @@ 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 a plugin's server hidden from agents, `Server.Hidden`, [Plugin tools](plugin-tools.md)), 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), Pi, Droid (which defers every MCP tool to its ToolSearch) and omp (which names each in its catalog by its description's first line) (`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) |
| 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 one turned off, `Server.Hidden`: by its switch, `ServerOn` ([Library](library.md)), or a plugin's server hidden from agents, [Plugin tools](plugin-tools.md)), 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), Pi, Droid (which defers every MCP tool to its ToolSearch) and omp (which names each in its catalog by its description's first line) (`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. `find_tools`' description starts with `HubLine` (each server and what it is for: an agent such as omp shows a tool by its description's first line, and some, such as Droid, show no instructions), then how to search, then each server's tools (`hubDetails` within `hubFindSayMax`, 1200 characters; `hubFindSay`): told only how to search, a model asked for a picture searched and stopped (tao5010 on Discord, 11-04). `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` |
+4
View File
@@ -23,6 +23,7 @@ const libraryUsage = `magpie library what the library gives
magpie library mcp agents <name> <a,b…|none>
magpie library mcp local <name> on|off keep it to this computer: a sync or a backup never carries it, and one
coming in neither takes it away nor puts another computer's in its place
magpie library mcp off|on <name> take it from every agent, project and app, keeping its settings; on gives it back as it was
magpie library mcp rm <name>
magpie library mcp router 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 router <name> shared|direct with the router on, share the server through it (the default) or keep it each
@@ -142,6 +143,9 @@ func libraryCmd(args []string) error {
}
return nil
}
case len(rest) == 2 && (rest[0] == "on" || rest[0] == "off") && !strings.HasPrefix(rest[1], "-"):
// off for everyone, kept with its settings; on again as it was
res, err = library.ServerOn(rest[1], rest[0] == "on")
case len(rest) == 2 && rest[0] == "rm":
res, err = library.RemoveServer(rest[1])
case len(rest) == 2 && (rest[0] == "router" || rest[0] == "hub") && (rest[1] == "on" || rest[1] == "off"):
+59
View File
@@ -0,0 +1,59 @@
package cli
import (
"os"
"path/filepath"
"slices"
"testing"
"github.com/yetone/magpie/internal/library"
)
// magpie library mcp off|on <name> (swang20201 on X): off takes the
// server from its agents and keeps it; on gives it back to them; a flag
// is never taken as a name.
func TestLibraryMCPOffOn(t *testing.T) {
h := t.TempDir()
for k, v := range map[string]string{"HOME": h, "USERPROFILE": h, "XDG_CONFIG_HOME": filepath.Join(h, ".config"), "CLAUDE_CONFIG_DIR": "", "CODEX_HOME": "", "APPDATA": "", "LOCALAPPDATA": ""} {
t.Setenv(k, v)
}
if err := os.MkdirAll(filepath.Join(h, ".claude"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(h, ".claude/settings.json"), nil, 0o644); err != nil {
t.Fatal(err)
}
if _, err := library.SaveServer("", library.Server{Name: "fs", Transport: "stdio", Command: "npx", Env: map[string]string{"K": "v"}, Agents: []string{"claude"}}); err != nil {
t.Fatal(err)
}
server := func() library.ServerView {
t.Helper()
v, err := library.Read(nil)
if err != nil {
t.Fatal(err)
}
for _, s := range v.Servers {
if s.Name == "fs" {
return s
}
}
t.Fatal("fs is gone")
return library.ServerView{}
}
if err := libraryCmd([]string{"library", "mcp", "off", "fs"}); err != nil {
t.Fatal(err)
}
if s := server(); !s.Hidden || len(s.Agents) != 0 || !slices.Equal(s.Paused, []string{"claude"}) || s.Env["K"] != "v" {
t.Fatalf("off: %+v", s.Server)
}
if err := libraryCmd([]string{"library", "mcp", "on", "--help"}); err == nil {
t.Error("a flag was taken as a server's name")
}
if err := libraryCmd([]string{"library", "mcp", "on", "fs"}); err != nil {
t.Fatal(err)
}
if s := server(); s.Hidden || !slices.Equal(s.Agents, []string{"claude"}) || s.Env["K"] != "v" {
t.Fatalf("on: %+v", s.Server)
}
}
+18 -3
View File
@@ -2250,7 +2250,8 @@ magpie.plugin("library", (ctx) => {
// and again once it changed after that: a sign-in since isn't left
// beside "needs sign-in" (新v学员 on Discord)
// With no agent, the router is what starts them, so on it checks them too
const unchecked = lib.servers.filter((s) => (inUse(s) || (agentless() && lib.mcpHub && inHub(s)) || health.has(s.name)) && health.get(s.name)?.key !== healthKey(s));
// One turned off is started for nobody, and checked only on a click.
const unchecked = lib.servers.filter((s) => (!s.hidden && (inUse(s) || (agentless() && lib.mcpHub && inHub(s))) || health.has(s.name)) && health.get(s.name)?.key !== healthKey(s));
queueMicrotask(() => checkHealth(unchecked));
}
// an agent's own servers (Codex's node_repl, added each time it starts)
@@ -2681,7 +2682,8 @@ magpie.plugin("library", (ctx) => {
}
function serverRow(s, all) {
const row = el("div", "row lib-row click lib-server");
const row = el("div", "row lib-row click lib-server" + (s.hidden ? " off" : ""));
row.dataset.server = s.name;
const who = el("div", "who");
const nm = el("div", "name mono", s.name);
if (s.signIn?.dead) nm.append(tag(t("Sign-in ran out"), "warn", t("Open it to sign in again")));
@@ -2700,7 +2702,8 @@ magpie.plugin("library", (ctx) => {
who.append(noteSub(s.note, sub, serverLine(s)), toolsEl(s.name));
row.append(mark(s.icon, s.transport === "stdio" ? GLYPH.cmd : GLYPH.web), who, ...removeAct(() => confirmRemoveServer(s)),
// no agent to give it to: other apps reach it through the router
...(agentless() ? [] : [agentChips(withGone(all, s.agents), s.agents, chipsChange("servers/agents", s.name, "servers", (x) => serverRow(x, all)), { problems: s.problems, blocked: sseBlocked(s), all: true })]));
...(agentless() ? [] : [agentChips(withGone(all, s.agents), s.agents, chipsChange("servers/agents", s.name, "servers", (x) => serverRow(x, all)), { problems: s.problems, blocked: sseBlocked(s), all: true })]),
...serverSwitch(s));
if (picking) return pickRow(row, s.name);
// a line of its own under the row, not in the name's column (tao0194)
if (s.name === "magpie-browser" && !s.agents?.length) row.append(browserAsk(row));
@@ -2709,6 +2712,18 @@ magpie.plugin("library", (ctx) => {
return row;
}
// A server off for everyone, or on again as it was (swang20201 on X:
// an installed server could only be removed). Off, no agent, project or
// app at the router's address has it, and it keeps its settings, env
// and sign-in; on, the agents it had get it back. While picking, the
// bar is the one acting, as with Remove.
function serverSwitch(s) {
if (picking) return [];
const on = !s.hidden;
return [toggle(on, t("Turn {name} on or off", { name: s.name }), (v) => change("servers/on", { name: s.name, on: v },
v ? t("{name} is on again", { name: s.name }) : t("{name} is off; its settings are kept", { name: s.name })))];
}
// Magpie Browser connected and given to no agent: it is added opt-in, so
// until an agent is ticked the router offers it to none, and an agent
// asked to use the browser reached for something else (AppleScript).
@@ -2,6 +2,9 @@
// kernel adds them to i18n.js's (magpie.strings).
magpie.strings({
zh: {
"Turn {name} on or off": "开启或关闭 {name}",
"{name} is on again": "{name} 已重新开启",
"{name} is off; its settings are kept": "{name} 已关闭,设置都已保留",
"Learn from conversations": "从对话中学习",
"Reads each finished conversation for what to remember. You review each one before agents see it.": "读完成的对话,找出值得记住的内容。每条都要你确认后 Agent 才会看到。",
"Reading conversations…": "正在读对话…",
@@ -897,6 +900,9 @@ magpie.strings({
"billion-context is installed — switch it on for your agents below": "billion-context 已安装 — 在下方为你的 Agent 打开它",
},
"zh-TW": {
"Turn {name} on or off": "開啟或關閉 {name}",
"{name} is on again": "{name} 已重新開啟",
"{name} is off; its settings are kept": "{name} 已關閉,設定都已保留",
"Learn from conversations": "從對話中學習",
"Reads each finished conversation for what to remember. You review each one before agents see it.": "讀完成的對話,找出值得記住的內容。每條都要你確認後 Agent 才會看到。",
"Reading conversations…": "正在讀對話…",
@@ -1792,6 +1798,9 @@ magpie.strings({
"billion-context is installed — switch it on for your agents below": "billion-context 已安裝 — 在下方為你的 Agent 開啟它",
},
ja: {
"Turn {name} on or off": "{name} のオン/オフ",
"{name} is on again": "{name} を再びオンにしました",
"{name} is off; its settings are kept": "{name} をオフにしました。設定は残っています",
"Learn from conversations": "会話から学ぶ",
"Reads each finished conversation for what to remember. You review each one before agents see it.": "終わった会話を読み、覚えておく価値のあることを探します。エージェントに渡る前に、一つずつ確認します。",
"Reading conversations…": "会話を読んでいます…",
@@ -2687,6 +2696,9 @@ magpie.strings({
"billion-context is installed — switch it on for your agents below": "billion-context をインストールしました — 下でエージェントごとにオンにしてください",
},
de: {
"Turn {name} on or off": "{name} ein- oder ausschalten",
"{name} is on again": "{name} ist wieder an",
"{name} is off; its settings are kept": "{name} ist aus; seine Einstellungen bleiben",
"Learn from conversations": "Aus Unterhaltungen lernen",
"Reads each finished conversation for what to remember. You review each one before agents see it.": "Liest jede beendete Unterhaltung auf das, was sich zu merken lohnt. Du prüfst jede Erinnerung, bevor Agenten sie sehen.",
"Reading conversations…": "Unterhaltungen werden gelesen…",
@@ -200,6 +200,11 @@ button.row.lib-hubfolded:hover { background: var(--pill); }
/* off on this computer: its agents' ticks are the other computers', shown faded and not to be changed here */
.lib-skill.offhere > .lib-glyph, .lib-skill.offhere > .lib-logo, .lib-skill.offhere .sub { opacity: .55; }
.lib-skill.offhere > .lib-agents { opacity: .4; pointer-events: none; }
/* a server off for everyone (serverSwitch): its switch turns it on again,
giving back the agents it had, so its chips wait for that */
.lib-server.off > .lib-glyph, .lib-server.off > .lib-logo, .lib-server.off .name, .lib-server.off .sub { opacity: .55; }
.lib-server.off > .lib-agents { opacity: .4; pointer-events: none; }
.lib-server > .lib-switch { align-self: center; margin-left: 8px; }
.lib-hereline { display: flex; margin-top: 3px; min-width: 0; }
.lib-hereline > .lib-tag.lib-offhere { cursor: pointer; margin-left: 0; flex: 0 1 auto; max-width: 100%; overflow: hidden; text-overflow: ellipsis; }
.lib-tag.lib-offhere:hover { color: var(--fg); }
+5
View File
@@ -622,6 +622,11 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
// a plugin's tools off for every agent, or on again, from its
// row on the Plugins page (Name is the plugin's)
res, err = library.PluginServerOn(in.Name, in.On)
case "servers/on":
// off for every agent, project and app at the router's
// address, kept with its settings, or on again as it was
// (swang20201 on X)
res, err = library.ServerOn(in.Name, in.On)
case "servers/agents-all":
res, err = library.EveryServerAgents(in.Agents, in.On)
case "servers/agents-some":
+144
View File
@@ -0,0 +1,144 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// swang20201 on X (v0.1.3375, Docker gateway mode): an installed MCP server
// in Library could only be removed. Each server row has a switch: off
// posts servers/on {on:false}, says the settings are kept, and the row
// shows dimmed with its agent chips out of reach; on posts {on:true} and
// the row is as it was. The switch doesn't open the editor. In the app
// with an agent at 1100px and a browser in gateway mode at 420px, every
// language, both engines: no sideways scroll, no native select.
// 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 = "/srv/mg";
const fixture = (st) => ({
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
mcpHub: st.gateway, hubPath: "/mcp/magpie/hub/",
agents: [{ id: "claude", name: "Claude Code", icon: "claudecode-color", skills: `${HOME}/.claude/skills`, mcp: `${HOME}/.claude.json`, ...(st.gateway ? { hub: "on" } : {}) }],
instructions: { agents: [], sets: [] }, foundSkills: [], skills: [], problems: [], foundServers: [], projects: [],
servers: [
st.off
? { name: "notes", transport: "stdio", command: "uvx", args: ["notes-mcp"], env: { TOKEN: "x" }, agents: [], hidden: true, paused: ["claude"] }
: { name: "notes", transport: "stdio", command: "uvx", args: ["notes-mcp"], env: { TOKEN: "x" }, agents: ["claude"] },
{ name: "docs", transport: "http", url: "https://docs.example/mcp", 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.gateway}${st.gateway ? ",gateway:true" : ""}};` });
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" } });
if (url.pathname === "/api/library") return json(fixture(st));
if (url.pathname === "/api/library/servers/on") {
const body = req.postDataJSON();
st.sent.push(body);
st.off = !body.on;
return json({ ...fixture(st), result: { changed: [] } });
}
if (url.pathname === "/api/library/mcp/check") {
const names = req.postDataJSON().names;
st.checked.push(...names);
return json({ servers: Object.fromEntries(names.map((n) => [n, { state: "ok", tools: 2 }])) });
}
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 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-server, #view-library .lib-server > .lib-switch, #view-library .lib-server .lib-agents")) {
const r = e.getBoundingClientRect();
if (r.width && (r.right > w + 0.5 || r.left < -0.5)) over.push((e.className || e.tagName) + " " + Math.round(r.left) + "–" + Math.round(r.right));
}
return over;
});
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": an MCP server switched off and on", 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 gateway = width < 800;
const where = gateway ? "gateway mode" : "the app";
const st = { off: false, sent: [], checked: [], gateway };
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");
const row = v.locator('.lib-server[data-server="notes"]');
await row.waitFor();
const sw = row.locator(":scope > .lib-switch");
assert.equal(await sw.count(), 1, `${where}: no switch on the row`);
assert.equal(await sw.getAttribute("aria-checked"), "true");
assert.equal(await sw.getAttribute("aria-label"), w("Turn {name} on or off", { name: "notes" }));
assert.equal(await row.evaluate((r) => r.classList.contains("off")), false);
assert.equal(await v.locator('.lib-server[data-server="docs"] > .lib-switch').getAttribute("aria-checked"), "true");
assert.equal(await page.locator("select").count(), 0);
assert.deepEqual(await sideways(page), [], `${where}: sideways scroll, on`);
// off: kept, dimmed, the editor not opened
await sw.click();
await page.waitForFunction((x) => document.querySelector("#status")?.textContent === x, w("{name} is off; its settings are kept", { name: "notes" }));
assert.deepEqual(st.sent, [{ name: "notes", on: false }]);
await page.waitForFunction(() => document.querySelector('#view-library .lib-server[data-server="notes"]')?.classList.contains("off"));
const offRow = v.locator('.lib-server[data-server="notes"]');
assert.equal(await offRow.locator(":scope > .lib-switch").getAttribute("aria-checked"), "false");
assert.equal(await page.locator("#modal").evaluate((m) => !m.hidden && m.getBoundingClientRect().height > 0).catch(() => false), false, `${where}: the switch opened the editor`);
if (!gateway) assert.equal(await offRow.locator(".lib-agents").evaluate((e) => getComputedStyle(e).pointerEvents), "none", "the chips of a server off still take clicks");
assert.ok(Number(await offRow.locator(".name").evaluate((e) => getComputedStyle(e).opacity)) < 1, `${where}: not dimmed`);
assert.equal(await v.locator('.lib-server[data-server="docs"]').evaluate((r) => r.classList.contains("off")), false);
assert.deepEqual(await sideways(page), [], `${where}: sideways scroll, off`);
// on again, as it was
await offRow.locator(":scope > .lib-switch").click();
await page.waitForFunction((x) => document.querySelector("#status")?.textContent === x, w("{name} is on again", { name: "notes" }));
assert.deepEqual(st.sent, [{ name: "notes", on: false }, { name: "notes", on: true }]);
await page.waitForFunction(() => !document.querySelector('#view-library .lib-server[data-server="notes"]')?.classList.contains("off"));
assert.equal(await v.locator('.lib-server[data-server="notes"] > .lib-switch').getAttribute("aria-checked"), "true");
assert.deepEqual(errors, []);
await ctx.close();
});
}
});
}
+4 -4
View File
@@ -64,10 +64,10 @@ type Server struct {
// gateway serves them at its URL, and the hub calls the plugin itself
// (plugin_tools.go)
Plugin string `json:"plugin,omitempty"`
// Hidden is a plugin's server whose tools were hidden from every
// agent on the Plugins page (PluginServerOn, chengming0v0 on
// Discord): no agent is given it, nor an app at the MCP router's
// address. Paused are the agents it had, given back when it is shown
// Hidden is a server turned off in the Library (ServerOn), or a
// plugin's whose tools were hidden from every agent on the Plugins
// page (PluginServerOn, chengming0v0 on Discord): no agent is given
// it, nor a project, nor an app at the MCP router's address. Paused are the agents it had, given back when it is shown
// again. Both go once the server has an agent again (save).
Hidden bool `json:"hidden,omitempty"`
Paused []string `json:"paused,omitempty"`
+37
View File
@@ -0,0 +1,37 @@
package library
import (
"fmt"
"slices"
)
// ServerOn turns a server off for everyone, or on again as it was
// (swang20201 on X: a server in the Library could only be removed). Off,
// no agent is given it, nor a project's, nor an app at the MCP router's
// address, and the router ends it; the agents it had are kept (Paused),
// with its command or address, env, headers, tools turned off and
// magpie's sign-in to it, which stay in the library. On, those agents get
// it back, none when it had none (it is the router's alone again). A
// plugin's server is the same switch as its row on the Plugins page.
func ServerOn(name string, on bool) (*Result, error) {
return change(func(l *Library) error {
s := l.server(name)
if s == nil {
return fmt.Errorf("no server called %s", name)
}
if !on {
if !s.Hidden {
s.Hidden, s.Paused, s.Agents = true, s.Agents, []string{}
}
return nil
}
if !s.Hidden {
return nil
}
if len(s.Agents) == 0 {
s.Agents = slices.Compact(slices.Sorted(slices.Values(s.Paused)))
}
s.Hidden, s.Paused = false, nil
return nil
})
}
+149
View File
@@ -0,0 +1,149 @@
package library
import (
"context"
"encoding/json"
"path/filepath"
"slices"
"strings"
"testing"
"time"
)
// Off, a server is given to no agent, no project and no app at the MCP
// router's address, and a process the router holds for it ends; its
// settings, env and agents are kept. On, it comes back as it was
// (swang20201 on X: a server in Library could only be removed).
func TestServerOnKeepsAndRestores(t *testing.T) {
h := hubSandbox(t)
fake := fakeStdio(t, "ok", map[string]string{"TOKEN": "secret"})
fake.Agents = []string{"claude"}
fake.DisabledTools = []string{"b"}
ok(t)(SaveServer("", *fake))
proj := filepath.Join(t.TempDir(), "app")
write(t, filepath.Join(proj, ".mcp.json"), `{"mcpServers": {"team": {"command": "team-mcp"}}}`)
ok(t)(AddProject(proj))
ok(t)(ProjectServer(proj, fake.Name, []string{"claude"}))
sub := reviewer
sub.MCP, sub.Skills, sub.Agents = []string{fake.Name}, nil, []string{"claude"}
ok(t)(SaveSubagent("", sub))
ok(t)(Sync())
claude := filepath.Join(h, ".claude.json")
mcp := filepath.Join(proj, ".mcp.json")
kept := func(when string) {
t.Helper()
l, err := load()
if err != nil {
t.Fatal(err)
}
s := l.server(fake.Name)
if s == nil || !s.Hidden || len(s.Agents) != 0 || !slices.Equal(s.Paused, []string{"claude"}) ||
s.Env["TOKEN"] != "secret" || !slices.Equal(s.DisabledTools, []string{"b"}) {
t.Fatalf("%s: kept as %+v", when, s)
}
}
subFile := filepath.Join(h, ".claude", "agents", "reviewer.md")
inFiles := func() (user, project bool) {
t.Helper()
user = servers(t, claude, "mcpServers")[fake.Name] != nil
if named := strings.Contains(read(t, subFile), `mcpServers: ["fake"]`); named != user {
t.Fatalf("claude's file has it %v, the subagent names it %v:\n%s", user, named, read(t, subFile))
}
return user, servers(t, mcp, "mcpServers")[fake.Name] != nil
}
if u, p := inFiles(); !u || !p {
t.Fatalf("to begin with: in claude's file %v, the project's %v", u, p)
}
ok(t)(ServerOn(fake.Name, false))
for _, when := range []string{"off", "off twice", "synced"} {
switch when {
case "off twice":
ok(t)(ServerOn(fake.Name, false))
case "synced":
ok(t)(Sync())
}
if u, p := inFiles(); u || p {
t.Fatalf("%s: in claude's file %v, the project's %v", when, u, p)
}
if servers(t, mcp, "mcpServers")["team"] == nil {
t.Fatalf("%s: the project's own server went", when)
}
kept(when)
}
ok(t)(ServerOn(fake.Name, true))
if u, p := inFiles(); !u || !p {
t.Fatalf("on again: in claude's file %v, the project's %v", u, p)
}
env, _ := servers(t, claude, "mcpServers")[fake.Name].(map[string]any)["env"].(map[string]any)
if l, _ := load(); env["TOKEN"] != "secret" || l.server(fake.Name).Hidden || l.server(fake.Name).Paused != nil ||
!slices.Equal(l.server(fake.Name).Agents, []string{"claude"}) {
t.Fatalf("on again: env %v, %+v", env, l.server(fake.Name))
}
// at the MCP router's address, the way Docker's gateway mode gives it
ok(t)(SetMCPHub(true))
ctx := context.Background()
hub := theHub{}
listed := func(agentID string) bool {
return slices.Contains(hubNames(hub.Tools(ctx, agentID)), "fake/a")
}
if !listed("claude") || !listed("") {
t.Fatal("the router doesn't give it to begin with")
}
if _, err := hub.Call(ctx, "", fake.Name, "a", json.RawMessage(`{}`)); err != nil {
t.Fatal(err)
}
hubPool.Lock()
b := hubPool.m[fake.Name]
hubPool.Unlock()
if b == nil {
t.Fatal("no server held after a call")
}
b.mu.Lock()
c := b.conn
b.mu.Unlock()
ok(t)(ServerOn(fake.Name, false))
if listed("claude") || listed("") {
t.Fatal("off, the router still lists it")
}
if _, err := hub.Call(ctx, "", fake.Name, "a", json.RawMessage(`{}`)); err == nil {
t.Fatal("off, an app at the router's address ran it")
}
kept("off at the router")
hubPrune()
ended := false
for end := time.Now().Add(10 * time.Second); time.Now().Before(end); time.Sleep(10 * time.Millisecond) {
if !c.alive() {
ended = true
break
}
}
if !ended {
t.Fatal("the router's process for a server turned off still runs")
}
ok(t)(ServerOn(fake.Name, true))
if !listed("claude") || !listed("") {
t.Fatal("on again, the router doesn't give it")
}
// one ticked for no agent, which the router alone gives other apps
ok(t)(ServerAgents(fake.Name, nil))
if !listed("") {
t.Fatal("a server ticked for no agent isn't given to other apps")
}
ok(t)(ServerOn(fake.Name, false))
if listed("") {
t.Fatal("off, an app at the router's address still has it")
}
ok(t)(ServerOn(fake.Name, true))
if l, _ := load(); !listed("") || len(l.server(fake.Name).Agents) != 0 {
t.Fatalf("on again with no agent: %+v", l.server(fake.Name))
}
if _, err := ServerOn("nope", false); err == nil {
t.Fatal("no error for a server that isn't there")
}
}
+3 -1
View File
@@ -115,8 +115,10 @@ func (l *Library) syncProjectMCP(p *Project, fail func(what string, err error))
}
}
}) {
// one turned off (ServerOn) is off in every project too, and
// keeps the project's agents for when it is on again
s := l.server(name)
if s == nil {
if s == nil || s.Hidden {
continue
}
for _, id := range p.Servers[name] {
+2 -2
View File
@@ -261,7 +261,7 @@ func (l *Library) subagent(name string) *Subagent {
}
// renderSubagent is s as an agent's file: of its skills and servers,
// those the library still has.
// those the library still has, a server turned off (ServerOn) left out.
func (l *Library) renderSubagent(sp *subagentSpec, s *Subagent) []byte {
var skills, mcp []string
if sp.skills {
@@ -273,7 +273,7 @@ func (l *Library) renderSubagent(sp *subagentSpec, s *Subagent) []byte {
}
if sp.mcp {
for _, n := range s.MCP {
if l.server(n) != nil {
if x := l.server(n); x != nil && !x.Hidden {
mcp = append(mcp, n)
}
}