diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index f62cd54e2..130b51b89 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -24,6 +24,7 @@ Pi's extensions and packages. | Projects | A project (`Project`) is a folder given some of the library's skills and MCP servers, each for some agents. A skill is linked (or copied) into the folder the agent reads a project's skills from (`projectSkillsDirs`): `.claude/skills` for Claude Code, `.qoder/skills` for Qoder and Qoder CN, `.codebuddy/skills` for CodeBuddy Code, `.commandcode/skills` for Command Code, and `.agents/skills` for Codex, Gemini CLI, OpenCode, Pi, Cursor, Copilot CLI, Antigravity, Kimi, Goose, Grok, Droid, Cline and DeepSeek Harness (which reads it, and `.dsh/skills`, at the nearest folder up with a `.git`, else where it runs: a project folder inside a repository but not at its root doesn't reach it, #5172). A server is written into the file the agent reads a project's servers from (`projectMCPFiles`), in the shape its user-wide file has: `.mcp.json` for Claude Code and CodeBuddy Code (CodeBuddy's `mcp.json` when the project has that and no `.mcp.json`, since it reads only the first of the two), `.codex/config.toml`, `.gemini/settings.json`, `.cursor/mcp.json`, `opencode.json`, `.zcode/config.json`, `.pi/mcp.json`, `.qoder/settings.json`'s `mcpServers` for Qoder and Qoder CN, and `.factory/mcp.json` for Droid. Claude Code, Qoder and CodeBuddy ask the user to approve a project's server before using it. Only targets whose vendor source or docs name them are listed (each map's comment cites them); an agent with none (Copilot CLI's MCP, Zed, WorkBuddy, Command Code's MCP, whose `.mcp.json` has its own `transport` shape, DeepSeek Harness's MCP, whose servers are rows in its profiles' patch layers with no project layer) can't be picked for a project (eirc on Discord). `Placed`, `Wrote`, `Made` and `MadeFiles` record what magpie put there, the only things it takes away, and what it made is listed in the project's `.gitignore`. | [`projects.go`](../../internal/library/projects.go), [`project_mcp.go`](../../internal/library/project_mcp.go) | | Instructions | magpie's part of an agent's instructions file sits between two marker lines. The rest of the file is the user's. Several named sets can be switched between (#106). A set can be kept in a file of the user's own instead of `instruction-sets/` (`InstrSet.File`, 新v学员 on Discord): `~/.agents/AGENTS.md`, which Droid and omp read too. `textPath` reads it, `putText` keeps it aside and writes it but never removes it, removing the set lets go of it, and `linkable` refuses a file magpie writes into (an agent's own instructions, a file with the marker line), the library's own and another set's. The app's `KeepLinked` looks at the file every 30 s and writes a change into the agents (`SyncLinked`). A set's text is read without magpie's part (`setText`), and an agent whose instructions file is, links followed, the file the set on is kept in (`isSetFile`: `instructions.md` linked to `~/.claude/CLAUDE.md`, or both linked to one dotfile) gets no part written into it, and one written before is taken out with every part nested in it: read with its part, each sync wrote the whole file into that part again and it doubled, to gigabytes (#2349, `TestInstructionsSetLinkedToAgentsFile`). `Collect` carries the set's text, not where its file is; `Put` keeps this computer's file for the set and never empties it for a text not carried. Alma's file is `~/.config/alma/USER.md`, which its main chat reads into its system prompt as its owner's profile (0.4.164's `out/main/index.js`; a workspace's `USER.md` is read instead), and whose leading front matter (`name`, `telegram_id`, `discord_id`) is who its bots answer to (#2315, Jie211). The target is a `Profile`: magpie's part goes after the user's, so the front matter stays first, and `ImportInstructions` refuses it, as moving it out would take that front matter out of the file and into every agent's (`TestAlmaInstructionsKeepTheProfile`, `TestAlmaProfileIsNotImported`, `library-alma-profile.test.cjs`). | [`instructions.go`](../../internal/library/instructions.go) | | MCP servers | A `Server` is a command or a URL (`http`, `sse`). `mcpFile` encodes it in each agent's own format (one `mcpFormat` per agent family) and merges it with the user's own fields for that entry. A server's `StartupTimeout` (#3168) goes to Codex alone, as `startup_timeout_sec` in seconds (`RawMcpServerConfig` in codex-rs/config's mcp_types.rs; 0 leaves Codex's own 30s), in the user-wide config.toml and a project's alike. magpie keeps the value it wrote (`Applied.Startup`, `Project.Startup`): one in the entry other than that, or a `startup_timeout_ms`, is the user's and stays as it is (`startupTheirs`), and once it is taken out magpie's goes in again. The editor shows the field only when an agent that takes it is here (`AgentView.Startup`, `mcp_startup_test.go`, `mcp-startup-timeout.test.cjs`). `Also` files get the same servers; `Extra` files are only read when importing. `CheckServers` connects as an agent would and keeps the result in memory only: with each tool's name and the first paragraph of its description (`ToolList`, at most `maxToolList`, a description cut at `maxToolDesc` runes), which the page lists when the server's "N tools" is clicked, following tools/list's `nextCursor` up to `maxToolPages` pages (`listTools`). Each step (initialize, notifications/initialized, tools/list; connect for SSE) has its own budget, 60s for a URL and 30s for a command (`remoteStep`, `stdioStep`), and a timeout names its `Step` and how long it `Waited`; a timeout isn't kept, so the next look asks again (#1467). A command named bare that magpie's PATH lacks is started from where `proc.FindTool` finds it (fnm's Nodes on Windows among the folders), with that folder on the check's PATH, since npx's package runs the node beside it by name (`stdioProgram`, #2685, `TestStdioProgramFindsWhatPathLacks`). The page asks once a session for the servers some agent or project has (`inUse` in plugins/library/client.js); one no agent has shows "not checked" and is checked only when its status is clicked (#1597, `library-mcp-health.test.cjs`). A server checked once is checked again when it changes, its sign-in included, so a server signed in to after a click's "needs sign-in" isn't left showing both (新v学员 on Discord, `mcp-signin-health.test.cjs`). The check sends magpie's sign-in as the gateway does: on a 401 it renews the token once and asks again, and a server that refuses even the renewed token has the sign-in marked run out (`mcpauth.Rejected`, also from the gateway's `/mcp/`), which `ServerHealth.SignIn` carries back so the row's tag says "Sign-in ran out" rather than "Signed in" beside "needs sign-in". A server that refuses the check (401 or 403) but that an agent signed in to on its own is named so (`ServerHealth.AgentSignIn`, `readOwnSignIns` in `mcp_agent_signin.go`): each Claude Code target's `.credentials.json` beside its settings.json, a WSL distro's under the distro's home, is read for a `mcpOAuth` entry of the server's name and URL with a token, and each Codex target's `.credentials.json` beside its config.toml for a flattened entry of them, the file codex-rs falls back to when its config's `mcp_oauth_credentials_store` is `file` or the keyring is missing, whose executor's own entries are no `codex mcp login` (#3508); and the row says "signed in in Claude Code (Ubuntu)" — or Codex — instead of "needs sign-in" (CyberCaius on Discord: signed in to with Claude Code's /mcp in WSL). The tokens are never sent or kept; a file that can't be read or parsed names nobody, a stopped distro isn't started for it, and on a Mac only the file is read, never the Keychain Claude Code keeps them in nor Codex's keyring store. They are part of the check's key, so a sign-in in the agent since is checked anew (`TestCheckNamesAgentsSignedInThemselves`, `library-mcp-health-wsl.test.cjs`). A server that needs OAuth is signed in once in magpie, and agents reach it through the gateway's `/mcp/` (#615). The editor's Sign in saves the form first only when the sign-in is to another server than the saved one (a new server, a name or URL changed), and its button then reads "Save and sign in"; anything else edited (headers, env, arguments) stays unsaved until Save, so Cancel leaves the server as it was (新v学员 on Discord, `mcp-editor-cancel.test.cjs`). A server whose authorization server refuses magpie's dynamic client registration with 401 or 403 admits only the clients it lists (Figma's, #1619): the sign-in fails with `mcpauth.ErrClientRefused`, which says so and that each agent signs in itself, and the agents keep the server's own address. A server whose authorization server has no registration endpoint at all (GitHub's remote server, 新v学员 on Discord) fails with `mcpauth.ErrNoRegistration`, which says to make an OAuth app with the vendor and give it in the editor; the editor then opens its "OAuth app" fields. The app is the server's `oauth` (`OAuthApp`: `clientId`, `clientSecret`, `callbackPort`, Claude Code's names for `--client-id`, `--client-secret` and `--callback-port`), checked on save (HTTP only, a client ID, a port from 1 to 65535), and `SignInServer` signs in as it through `mcpauth.StartWith` without registering. The callback is Claude Code's, `http://localhost:/callback` (its docs' "Use pre-configured OAuth credentials"; 2.1.296 builds it so), listened for on 127.0.0.1 alone as Claude Code does, so an app made for Claude Code signs magpie in as it is; a server that matches the registered URL exactly refuses another host, which is why Claude Code's 2.1.231 went back to `localhost` from 2.1.229's `127.0.0.1` (`TestAppMadeForClaudeCode`). Without a `callbackPort` the port is any free one, which a loopback callback registered without a port takes (GitHub's, RFC 8252); a fixed `callbackPort` is for a vendor that matches the port too. magpie's own registration, when a server has one, still names `127.0.0.1`. The client secret is kept in library.json, as a header's or env's value is: a backup without keys leaves it out, and `WithSecrets` puts back this computer's secret only for the same client ID; no agent is given the app, and the TUI's editor, which doesn't show it, keeps it. GitHub answers a token request's error with a 200 and `error` in the body (`bad_refresh_token`, `incorrect_client_credentials`), which `tokenRequest` reads as the error it is, and a dead refresh token marks the sign-in run out (`github_app_test.go`, `mcp-oauth-app.test.cjs`). magpie never registers under another client's name; one that reaches the gateway from another machine (a WSL distro under NAT) is given it with the LAN sharing key as its `Authorization` (`agent.KeyAt`), as its models are, which the gateway takes in place of a sign-in and never passes on; turning sharing on or off, or a new key (`access.LANChanged`), writes such entries again. `ConfigOfServers` is the servers picked as an agent's project file (`projectMCPFiles`) would hold them, written by the same code into a folder of its own and read back, with those the agent can't take there named; the page's Copy config… puts it on the clipboard for a project magpie doesn't keep (#1478). The editor's command is a box that wraps, so a long line is read whole, and Enter still saves it (hema_17384 on Discord). Its Form | JSON switch shows the server as JSON in Claude Code's `.mcp.json` shape, the one Copy config… gives for it (`jsonOf` in plugins/library/client.js), with `${NAME}` references as written. An edit there is read as a paste is (`serversIn`) and becomes the form's at once. JSON that isn't one server's keeps the dialog from saving or going back to the form, and counts as unsaved. The note, the agents and sync stay in the form (`library-mcp-json.test.cjs`). A server's and a skill's `Note` (youyo.p_10001 on Discord) is the user's own word on what it is for: one line of at most `maxNote` (200) characters, whitespace run together (`checkNote`), as a hook's description is. The row shows it in place of the command or description, and its tooltip still gives that line. The skills' filter reads it too. A sync carries it (a server whole, a skill as `CarriedSkill.Note`), and no agent is given it, through the MCP router or not (`TestNoteNeverGiven`, `TestNoteCarried`). A skill's is set by itself (`SkillNote`, `skills/note`) from the skill's reader. Each listed tool has a switch: the tools turned off are the server's `DisabledTools`, set by `ServerTools`, and written into each agent given the server that can leave out a single tool (see the constraint below). A server run as `npx -y args` (a registry package, no other npx flag) is given to an agent on this machine as `node args` (`npxDirect`): magpie installs the package with npm into a folder of its own under `mcp-npm` in the background, the next sync writes the node form, and until then, or when npm fails (tried again after an hour), the agent keeps npx. npx otherwise stays as the server's parent for its whole life, a node and two cmd.exe beside each instance on Windows (#3885). An unpinned spec is installed again after a day, as npx would fetch the newer one; an install no library server runs goes a day after its last. The library, a server's check, Copy config… and agents in WSL keep npx (`TestNpxServerRunsByNode`, `TestReadNpx`). | [`mcp.go`](../../internal/library/mcp.go), [`mcp_npx.go`](../../internal/library/mcp_npx.go), [`mcp_check.go`](../../internal/library/mcp_check.go), [`mcp_signin.go`](../../internal/library/mcp_signin.go), [`mcp_agent_signin.go`](../../internal/library/mcp_agent_signin.go), [`mcp_copy.go`](../../internal/library/mcp_copy.go), [`mcp_tools_off.go`](../../internal/library/mcp_tools_off.go) | +| MCP server on/off | `ServerOn` (`POST /api/library/servers/on` with `name` and `on`, `magpie library mcp off|on `) turns a server off for everyone without removing it (swang20201 on X, Docker gateway mode, where a server ticked for no agent is still given to every app at the MCP router's address). Off, it is `Hidden` with its agents kept in `Paused` and `Agents` empty, as a plugin's server hidden from agents is (`PluginServerOn`, [Plugin tools](plugin-tools.md)): no agent's file has it, no project's (`syncProjectMCP` skips it, keeping the project's own agents for it), no subagent names it (`renderSubagent`), the router lists and calls it for nobody, and a process the router held for it ends, since `Hidden` and `Paused` are part of its `hubKey`. Its command, URL, env, headers, sign-in, `DisabledTools` and note stay in library.json. On, the agents in `Paused` get it back (none when it had none, so the router gives it to other apps again), as before it was turned off; giving it agents (`ServerAgents`, the CLI's `mcp agents`) turns it on with those (`save`), while Turn all on (`EveryServerAgents` with every agent) leaves it off. The row's switch sits after its agent chips (`serverSwitch` in plugins/library/client.js); off, the row is dimmed, its chips take no click, and it is health-checked only on a click (`TestServerOnKeepsAndRestores`, `TestLibraryMCPOffOn`, `library-mcp-on.test.cjs`). | [`mcp_on.go`](../../internal/library/mcp_on.go), [`project_mcp.go`](../../internal/library/project_mcp.go), [`subagents.go`](../../internal/library/subagents.go) | | MCP router | With `MCPHub` on, `syncMCP` gives each agent that can take it one entry, `magpie`, at the gateway's `/mcp/magpie/hub/`, in place of the servers ticked for it; magpie runs those servers itself, once for every agent. | [MCP router](mcp-router.md), [`mcp_hub.go`](../../internal/library/mcp_hub.go) | | MCP market | `MarketServers` lists the featured servers that match a search, then the MCP Registry's; a search that is an address (a repository, a page, an endpoint, a package; `market_addr.go`) finds the ones at it, and `CustomAt` offers one to fill in by hand when none is. The registry lists no server by a repository's folder, so a GitHub address naming one (`#subdirectory=`, `/tree//…`, `parseRepoAt`) is read first: the folder's `pyproject.toml` names the program, and the README's `"env": {…}` examples the keys, offered as `uvx --from git+https://github.com/o/r#subdirectory=p ` (`fromRepo`, CyberCaius on Discord: volcengine/mcp-server's askecho search). A bare repository is read so only when the registry has nothing at it, and a PyPI page, or a one-word search naming mcp the registry lists nothing by, asks PyPI (`fromPyPI`, `uvx `). Of several README keys none is required, since a README often has the user pick one way to sign in (`envInputs`; `TestMarketServerInRepoFolder`). Only Python projects are read from a folder; a Node one there still gets the blank form. | [`market.go`](../../internal/library/market.go), [`market_repo.go`](../../internal/library/market_repo.go) | | Skills | A skill is a folder with a `SKILL.md`. It goes by the `name` its front matter gives, made fit for a file name (ASCII letters, digits, `_` and `-`); a name that would lose a letter or digit that way (one in another script, `CTF•密码学`) or none goes by its folder's name instead, and a skill at a repository's top by the repository's (`nameFor`, `srcFolder`). A front matter setting `disable-model-invocation: true` marks it "Manual only" in the page, in the library and in the agents' own (`meta.Manual`, `SkillView.Manual`, `FoundSkill.Manual`; sunset3279 on Discord): Claude Code runs such a skill only on the user's `/name`. A front matter that doesn't parse, or a value that isn't a bool, is not known to be, and gets no mark (`TestSkillManualFromFrontMatter`, `skill-manual.test.cjs`). Two skills a probe names alike are listed once (`unhiddenFirst`), so names that fell to `CTF`, `Strix` and nothing listed asdfgh1445/ctf-super-hub's 35 skills as 16 (tnt1223 on Discord, `TestSkillsNamedInAnotherScriptAllListed`). It comes from GitHub, from any other git repository, from a folder on this machine (linked, so editing the folder edits the skill) or from the market. A git repository (`kind: git`, sunset on Discord: GitLab, a company's own GitLab) is any https, http, ssh or `file://` address, `git@host:group/repo.git`, a bare `host.name/group/repo`, or a GitLab or Gitea page of a folder (`/-/tree//`, `/-/blob/…`, `/src/branch/…`; a branch with a `/` in its name is read as its first segment) (`gitSource`). It is fetched by the user's own `git` (`proc.FindTool`), so their credential helpers and SSH keys reach an intranet host: `git init`, then `fetch --depth 1 --no-tags -- ` and `checkout FETCH_HEAD` into a `magpie-skill-*` folder, then its `.git` is removed (`fetchGit`). What the user typed is data: an address starting with `-` and a `transport::` address (`ext::`, `fd::`, `file::`) are refused before git runs, the address follows `--`, git runs with `protocol.ext.allow=never` and `core.symlinks=false`, no shell, `GIT_TERMINAL_PROMPT=0` and (unless the user set an SSH command) `ssh -o BatchMode=yes`, so a sign-in it can't make fails instead of waiting. An address with a password or token in it is refused: library.json is shown and backed up. Git missing, a sign-in refused, a host key unknown, a branch missing and a host unreachable each say so (`gitError`; `TestGitSourceReads`, `TestInstallFromGitRepo`, `TestGitTreeURLInstallsFolder`, `TestGitMissingSaysSo`, `TestGitSignInRefusedSaysSo`, `TestGitRefusesOptionsAndTransports`, `TestGitErrorsSaid`). Each agent gets a link or a marked copy (#896, `SkillHow`). An agent in a WSL distro gets a link too, to the distro's one copy of the skill, magpie's, in `~/.local/share/magpie/skills` (`Target.Store`, `storeSkill`; cutemmuu on X): the distro can't follow a link to the library's folder on Windows, and a link Windows makes through `\\wsl.localhost` is an empty folder in the distro, which in turn shows Windows its own links as entries it can't read, follow or remove, so the link is made, read and taken away in the distro by wsl.exe (`agent.WSLSymlink`, `WSLReadlink`, `WSLRemoveLink`; `TestWSLLinksLive` and `TestWSLSkillsLinkedLive` on a real distro with `MAGPIE_WSL_TEST_DISTRO`). An edit made through the link is in the distro's copy, which `takeEdits` reads as any copy of magpie's (`TestWSLEditThroughLinkReachesTheLibrary`); a copy no agent there links to or is given any more goes, to the backups when edited (`sweepWSLStores`, `TestWSLStoreSweepKeepsEdits`); a folder there that isn't magpie's is never touched, and each agent it is in the way of says so. The copy isn't put in the distro's `~/.agents/skills`, since every agent there reading that folder would get each skill, ticked for it or not. An agent set to copies gets one of its own, as does one whose skills folder or the store is on a Windows drive (#4502), where the distro's link is one Windows can't read. A copy an agent there was given before is made a link on the next sync, its edit taken first and a losing edit set aside (`wslRelink`, `TestWSLOldCopiesBecomeLinks`). A copy's mark keeps the hash of what was copied, so a sync knows a copy unchanged since then is current without reading its files (`copyIsFresh`, #1031); other copies are hashed. A skill an agent has of its own (`foundSkills`, the page's "In your agents") is brought in with `ImportSkill`, or taken out of every agent that has it with `RemoveFoundSkill` (#1303): its folders and copies of the very same files, its shared `~/.agents/skills` entry and a folder of it in the library's own folder go to the backups, its links are taken away, and a folder elsewhere it only links to, or another skill by that name, stays. Several go at once with `RemoveFoundSkills` (`POST /api/library/skills/remove-found-some`, wongxy on Discord): the "In your agents" heading's own Select picks them, and Remove… asks once, naming the count, before one change takes each out as `RemoveFoundSkill` would. A name that can't be taken out is left as it was, in `Result.Unremoved`, and stays picked with its error in its row's place (`foundErrs`); when none can go the change fails and nothing is touched. This Select and the library's are never on together: while one is on the other is dimmed, saying why, so neither click takes the other's bar away from above the pointer (`TestRemoveFoundSkills`, `found-skill-pick-remove.test.cjs`). A repository is fetched as one tarball of at most `maxFetch` (200 MB); a bigger one is fetched file by file from its tree (`fetchSkillFiles`), only as far as the caller reads: a link to a folder and an update ask GitHub for that folder's own list (`treeUnder`, git's `ref:path`; the whole list when that fails), the market fetches only the skills whose folder is the one it installs (#2794, sickn33/agentic-awesome-skills' 8,589 skills are 287 MB together), and a fetcher keeps such a part apart from another skill's of the same repository, which would otherwise read as removed (`fetcher.get`, `TestMarketSkillFromAHugeRepository`). GitHub's list is read up to `maxTree` (64 MB; that repository's is 11 MB) and an answer over the cap a caller gives `apiGet`, or one cut off, is an error saying so, never a body cut short for JSON to trip on (ye4241's `TestRepoTreeBigList`, `TestApiGetWholeAnswer`); a list GitHub truncated itself is too big (`TestTruncatedListIsTooBig`). And a skill over 200 MB on its own is left out rather than failing the rest: the probe lists the others and names it in `Probe.Left`, under the list in the page and in the TUI's flash. Only when every skill is too big does the fetch fail (#2062, mikubaka88/CCFA-Skills' 297 MB ccf-paper-writer; `TestOneSkillTooBigLeavesTheOthers`, `skill-too-big.test.cjs`). A probe keeps its download for the install from it for 15 minutes (`keepProbe`, `probeLife`), and removes it when it is probed again or that time is up, not at the next probe, which may never come. A download a magpie that quit left in the temp dir goes at the next probe once it is an hour old (`sweepStaleDownloads`). The package's TestMain gives the tests a temp dir of their own and fails a run that leaves a `magpie-skill-*` in it (#2321, `TestProbeDownloadEndsWithIt`, `TestStaleDownloadsSwept`). | [`skilltree.go`](../../internal/library/skilltree.go), [`skills.go`](../../internal/library/skills.go), [`skillgit.go`](../../internal/library/skillgit.go), [`skill_how.go`](../../internal/library/skill_how.go), [`skill_edits.go`](../../internal/library/skill_edits.go), [`skill_from.go`](../../internal/library/skill_from.go), [`skill_beside.go`](../../internal/library/skill_beside.go) | diff --git a/docs/subsystems/mcp-router.md b/docs/subsystems/mcp-router.md index 63190d8e6..9879150e1 100644 --- a/docs/subsystems/mcp-router.md +++ b/docs/subsystems/mcp-router.md @@ -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/` (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/` (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 ` 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/` 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 `__`: 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:`). 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 `__`: 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:`). 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 (), …`, 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`): `- (): . Tools: (), …`, the tools the Library turned off left out and a router's `[] ` 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 (``), 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: . …` on their second line (at the end when no server is behind it), `serverInfo.title` is `Magpie MCP hub · `, and each tool's description starts `[] ` (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` | diff --git a/internal/cli/library_cli.go b/internal/cli/library_cli.go index 0b05116f0..68a422414 100644 --- a/internal/cli/library_cli.go +++ b/internal/cli/library_cli.go @@ -23,6 +23,7 @@ const libraryUsage = `magpie library what the library gives magpie library mcp agents magpie library mcp local 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 take it from every agent, project and app, keeping its settings; on gives it back as it was magpie library mcp rm 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 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"): diff --git a/internal/cli/library_mcp_on_test.go b/internal/cli/library_mcp_on_test.go new file mode 100644 index 000000000..cef8b4f5d --- /dev/null +++ b/internal/cli/library_mcp_on_test.go @@ -0,0 +1,59 @@ +package cli + +import ( + "os" + "path/filepath" + "slices" + "testing" + + "github.com/yetone/magpie/internal/library" +) + +// magpie library mcp off|on (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) + } +} diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index fd63a15ac..3c100d296 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -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). diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index 23ed5a8b9..c3ff23b59 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -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…", diff --git a/internal/gui/assets/plugins/library/library.css b/internal/gui/assets/plugins/library/library.css index 35b0c5cf1..2e4cc4f7b 100644 --- a/internal/gui/assets/plugins/library/library.css +++ b/internal/gui/assets/plugins/library/library.css @@ -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); } diff --git a/internal/gui/library.go b/internal/gui/library.go index b0f67b364..d732672dd 100644 --- a/internal/gui/library.go +++ b/internal/gui/library.go @@ -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": diff --git a/internal/gui/tests/library-mcp-on.test.cjs b/internal/gui/tests/library-mcp-on.test.cjs new file mode 100644 index 000000000..d17a730dd --- /dev/null +++ b/internal/gui/tests/library-mcp-on.test.cjs @@ -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(); + }); + } + }); +} diff --git a/internal/library/mcp.go b/internal/library/mcp.go index cb2fb1e2b..86ab01469 100644 --- a/internal/library/mcp.go +++ b/internal/library/mcp.go @@ -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"` diff --git a/internal/library/mcp_on.go b/internal/library/mcp_on.go new file mode 100644 index 000000000..515df30ea --- /dev/null +++ b/internal/library/mcp_on.go @@ -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 + }) +} diff --git a/internal/library/mcp_on_test.go b/internal/library/mcp_on_test.go new file mode 100644 index 000000000..40fffe2ad --- /dev/null +++ b/internal/library/mcp_on_test.go @@ -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") + } +} diff --git a/internal/library/project_mcp.go b/internal/library/project_mcp.go index 47ce91ff1..007f6fa7b 100644 --- a/internal/library/project_mcp.go +++ b/internal/library/project_mcp.go @@ -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] { diff --git a/internal/library/subagents.go b/internal/library/subagents.go index 61ba601cf..c4d4d0f31 100644 --- a/internal/library/subagents.go +++ b/internal/library/subagents.go @@ -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) } }