Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
library: a server run with npx -y reaches the agent as node running the package (#3885)
yetone425a61322416
diff --git a/docs/subsystems/library.md b/docs/subsystems/library.mdindex b79167540..fe50d28a9 100644--- a/docs/subsystems/library.md+++ b/docs/subsystems/library.md@@ -19,7 +19,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it.| Sync | `sync` writes each target's instructions and MCP servers. It then takes edits made in agents' skill copies into the library (`takeEdits`) and links or copies the skills. `~/.agents/skills` goes first, so an agent that reads it gets no second link. Then it syncs projects' skills. | [`sync.go`](../../internal/library/sync.go) || 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 and Cline. 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) 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/<name>`), 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 the row says "signed in in Claude Code (Ubuntu)" 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. 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/<name>` (#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:<port>/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). 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). | [`mcp.go`](../../internal/library/mcp.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 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/<name>`), 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 the row says "signed in in Claude Code (Ubuntu)" 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. 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/<name>` (#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:<port>/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). 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 <package> args` (a registry package, no other npx flag) is given to an agent on this machine as `node <the package's bin> 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) || Skills | A skill is a folder with a `SKILL.md`. 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/<ref>/<path>`, `/-/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 -- <url> <ref>` 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 always gets a copy. 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) || Skills market | `MarketSkills` lists skills.sh's most installed and what its search finds. magpie's own skills (`featuredSkills`), in [magpie-community/plugins](https://github.com/magpie-community/plugins/tree/main/skills), go first, marked official: `magpie-setup` has an agent set magpie up as the user asks through its commands (providers, accounts, agents, routing groups and rules, gateway keys and limits, models, the library), and `magpie-quota` lets an agent read `magpie quota --json` and wait with `magpie quota wait`. Their commands live in magpie's CLI, so a change to a command either uses gets the skill updated in that repository. Until skills.sh lists one it has no count of installs and no skills.sh link (`featured`). `InstallMarketSkill` installs any of them from its repository. | [`market.go`](../../internal/library/market.go) || Skills a repository added | A check for updates (`CheckSkills`) also asks, for each GitHub repository and ref the library has skills from, GitHub's list of its files (`repoTree`, one API request, free when the ETag still matches). Only when that list has a skill folder beside the installed ones (under `newBase`, their deepest common folder) that the library doesn't have and hasn't offered does `findNew` fetch the repository for the skills' names and descriptions. `SeenSkills` records per `repo@ref` the paths the install picker showed and the ones set aside, so they aren't offered again. The finds live in memory (`newFound`) and reach the page as `View.NewSkills`; `AddNewSkills` gives each to the agents that have its repository's other skills, and `IgnoreNewSkills` sets it aside (`/api/library/skills/{add-new,ignore-new}`). | [`skillnew.go`](../../internal/library/skillnew.go), [`skillcheck.go`](../../internal/library/skillcheck.go) |diff --git a/internal/library/main_test.go b/internal/library/main_test.goindex 200df431f..a3b97de9a 100644--- a/internal/library/main_test.go+++ b/internal/library/main_test.go@@ -27,6 +27,8 @@ func TestMain(m *testing.M) {}// never the machine's own processes (mcp_reap.go)ending = func([]*Server) {}+ // never the registry (mcp_npx.go)+ npxInstall = nilcode := testenv.Run(m)forgetProbes()if left := leftDownloads(tmp); len(left) > 0 && code == 0 {diff --git a/internal/library/mcp_npx.go b/internal/library/mcp_npx.gonew file mode 100644index 000000000..6816820cd--- /dev/null+++ b/internal/library/mcp_npx.go@@ -0,0 +1,315 @@+package library++// A server run with `npx -y pkg` is given to an agent as node running the+// package's own program, from a folder magpie installs the package in.+// npx stays running as the server's parent for as long as the server+// does: on Windows a cmd.exe, npx's node (76 MB) and a second cmd.exe+// beside a 51 MB server, ~92 MB of wrapper a server for each instance an+// agent starts; Codex starts one a thread, 200 of them in #3885. Until+// the package is installed, and for any npx line not read here, the+// agent is given npx as the library has it; the library itself, and a+// server's check, keep npx.++import (+ "context"+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "log"+ "os"+ "os/exec"+ "path/filepath"+ "regexp"+ "runtime"+ "strings"+ "sync"+ "time"++ "github.com/yetone/magpie/internal/proc"+ "github.com/yetone/magpie/internal/settings"+)++// npxRun is an `npx -y <spec> args…` line: the package and its arguments.+type npxRun struct {+ spec, name string+ args []string+}++// npmSpec is a package from the registry, with a version or tag or none:+// npx's other specs (a path, a git or tarball URL, an alias) are left to+// npx.+var npmSpec = regexp.MustCompile(`^((?:@[a-z0-9][a-z0-9._~-]*/)?[a-z0-9][a-z0-9._~-]*)(?:@([A-Za-z0-9._~^<>=*| -]+))?$`)++// readNpx is s's npx line, ok false for anything else: a flag but -y+// before the package (-p, --package, -c, a registry), or no -y, which+// would have npx ask on the server's own stdin.+func readNpx(s *Server) (npxRun, bool) {+ if s.Remote() || progName(s.Command) != "npx" {+ return npxRun{}, false+ }+ yes := false+ for i, a := range s.Args {+ switch {+ case a == "-y" || a == "--yes":+ yes = true+ case strings.HasPrefix(a, "-"):+ return npxRun{}, false+ default:+ m := npmSpec.FindStringSubmatch(a)+ if !yes || m == nil {+ return npxRun{}, false+ }+ return npxRun{spec: a, name: m[1], args: s.Args[i+1:]}, true+ }+ }+ return npxRun{}, false+}++// pinned says the spec names an exact version, which never changes: one+// with none, or a tag or range, is installed again after a day, as npx+// would fetch the newer one.+func (r npxRun) pinned() bool {+ _, v, ok := strings.Cut(strings.TrimPrefix(r.spec, "@"), "@")+ return ok && exactVersion.MatchString(v)+}++var exactVersion = regexp.MustCompile(`^\d+\.\d+\.\d+([-+].*)?$`)++// npxDir is where magpie installs a spec: a folder of its own each.+func npxDir(spec string) string {+ h := sha256.Sum256([]byte(spec))+ return filepath.Join(settings.Dir(), "mcp-npm", hex.EncodeToString(h[:8]))+}++// nodeBeside is the node to run the package with: node by name for npx+// by name, as the agent finds both on its PATH, or the node in npx's own+// folder; "" when that folder has none.+func nodeBeside(npx string) string {+ if !strings.ContainsAny(npx, `/\`) {+ return "node"+ }+ node := filepath.Join(filepath.Dir(npx), "node")+ if runtime.GOOS == "windows" {+ node += ".exe"+ }+ if st, err := os.Stat(node); err != nil || st.IsDir() {+ return ""+ }+ return node+}++// npxBin is the program npx would run of the package installed in dir:+// its one bin, or the one named as the package; "" when there is none,+// or it isn't a script node runs.+func npxBin(dir, name string) string {+ pkg := filepath.Join(dir, "node_modules", filepath.FromSlash(name))+ b, err := os.ReadFile(filepath.Join(pkg, "package.json"))+ if err != nil {+ return ""+ }+ var m struct {+ Bin json.RawMessage `json:"bin"`+ }+ if json.Unmarshal(b, &m) != nil {+ return ""+ }+ var rel, one string+ var bins map[string]string+ switch {+ case json.Unmarshal(m.Bin, &one) == nil:+ rel = one+ case json.Unmarshal(m.Bin, &bins) == nil:+ if len(bins) == 1 {+ for _, v := range bins {+ rel = v+ }+ } else {+ rel = bins[name[strings.LastIndexByte(name, '/')+1:]]+ }+ }+ if rel == "" {+ return ""+ }+ bin := filepath.Join(pkg, filepath.FromSlash(rel))+ if rel, err := filepath.Rel(pkg, bin); err != nil || strings.HasPrefix(rel, "..") {+ return ""+ }+ head := make([]byte, 128)+ f, err := os.Open(bin)+ if err != nil {+ return ""+ }+ n, _ := f.Read(head)+ f.Close()+ ext := strings.ToLower(filepath.Ext(bin))+ if ext != ".js" && ext != ".cjs" && ext != ".mjs" {+ line, _, _ := strings.Cut(string(head[:n]), "\n")+ if !strings.HasPrefix(line, "#!") || !strings.Contains(line, "node") {+ return ""+ }+ }+ return bin+}++// npxDirect is s as node running the package's program, when magpie has+// the package installed; s when it hasn't, with the install started.+func npxDirect(s *Server) *Server {+ r, ok := readNpx(s)+ if !ok || npxInstall == nil {+ return s+ }+ node := nodeBeside(s.Command)+ if node == "" {+ return s+ }+ dir := npxDir(r.spec)+ bin := npxBin(dir, r.name)+ if bin == "" || !r.pinned() && npxStale(dir) {+ npxStart(r, s.Command, dir, bin == "")+ }+ if bin == "" {+ return s+ }+ c := *s+ c.Command = node+ c.Args = append([]string{bin}, r.args...)+ return &c+}++// npxStale says the install is a day old.+func npxStale(dir string) bool {+ st, err := os.Stat(filepath.Join(dir, ".installed"))+ return err != nil || time.Since(st.ModTime()) > 24*time.Hour+}++var npxQueue struct {+ sync.Mutex+ busy map[string]bool+ failed map[string]time.Time+}++// npxStart installs the spec in the background, once at a time; new says+// nothing is installed yet, and the agents are synced again once it is.+// A failed install is tried again after an hour.+func npxStart(r npxRun, npx, dir string, new bool) {+ npxQueue.Lock()+ if npxQueue.busy == nil {+ npxQueue.busy, npxQueue.failed = map[string]bool{}, map[string]time.Time{}+ }+ if npxQueue.busy[dir] || time.Since(npxQueue.failed[dir]) < time.Hour {+ npxQueue.Unlock()+ return+ }+ npxQueue.busy[dir] = true+ npxQueue.Unlock()+ go func() {+ err := npxInstall(r.spec, npx, dir)+ npxQueue.Lock()+ delete(npxQueue.busy, dir)+ if err != nil {+ npxQueue.failed[dir] = time.Now()+ }+ npxQueue.Unlock()+ if err != nil {+ log.Printf("library: installing %s for its MCP server: %v", r.spec, err)+ return+ }+ if new && npxBin(dir, r.name) != "" && npxSynced != nil {+ npxSynced()+ }+ }()+}++// npxInstall installs spec in dir with the npm beside npx; nil in tests,+// which never reach the registry.+var npxInstall = realInstall++func realInstall(spec, npx, dir string) error {+ npm := "npm"+ if strings.ContainsAny(npx, `/\`) {+ npm = filepath.Join(filepath.Dir(npx), "npm")+ if runtime.GOOS == "windows" {+ npm += ".cmd"+ }+ } else if _, err := exec.LookPath(npm); err != nil {+ if p := proc.FindTool(npm); p != "" {+ npm = p+ }+ }+ if err := os.MkdirAll(dir, 0o755); err != nil {+ return err+ }+ // a package.json of its own, so npm never takes a folder above for+ // the project+ if _, err := os.Stat(filepath.Join(dir, "package.json")); err != nil {+ if err := os.WriteFile(filepath.Join(dir, "package.json"), []byte("{\"private\":true}\n"), 0o644); err != nil {+ return err+ }+ }+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)+ defer cancel()+ cmd := proc.CommandContext(ctx, npm, "install", "--prefix", dir, "--no-save", "--no-package-lock", "--no-audit", "--no-fund", "--loglevel=error", spec)+ cmd.Dir = dir+ if out, err := cmd.CombinedOutput(); err != nil {+ return &npmError{err, strings.TrimSpace(string(out))}+ }+ return os.WriteFile(filepath.Join(dir, ".installed"), []byte(spec+"\n"), 0o644)+}++type npmError struct {+ err error+ out string+}++func (e *npmError) Error() string {+ if len(e.out) > 400 {+ e.out = e.out[len(e.out)-400:]+ }+ return e.err.Error() + ": " + e.out+}++// npxSynced syncs the agents again, for the servers an install has given+// a program; a var for tests.+var npxSynced func()++func init() {+ npxSynced = func() {+ if _, err := Sync(); err != nil {+ log.Printf("library: syncing after an MCP package install: %v", err)+ }+ }+}++// npxDirs are the folders of the packages the library's servers run.+func (l *Library) npxDirs() map[string]bool {+ dirs := map[string]bool{}+ for _, s := range l.MCP {+ if r, ok := readNpx(s); ok {+ dirs[filepath.Base(npxDir(r.spec))] = true+ }+ }+ return dirs+}++// npxPrune takes out the installs no server of the library's runs, a day+// after the last: a server taken out of the library leaves no package+// behind.+func npxPrune(keep map[string]bool) {+ if npxInstall == nil {+ return+ }+ root := filepath.Dir(npxDir(""))+ des, _ := os.ReadDir(root)+ for _, de := range des {+ dir := filepath.Join(root, de.Name())+ if !de.IsDir() || keep[de.Name()] || !npxStale(dir) {+ continue+ }+ npxQueue.Lock()+ busy := npxQueue.busy[dir]+ npxQueue.Unlock()+ if !busy {+ os.RemoveAll(dir)+ }+ }+}diff --git a/internal/library/mcp_npx_test.go b/internal/library/mcp_npx_test.gonew file mode 100644index 000000000..f8c92f57d--- /dev/null+++ b/internal/library/mcp_npx_test.go@@ -0,0 +1,161 @@+package library++import (+ "os"+ "path/filepath"+ "slices"+ "strings"+ "testing"+ "time"+)++// The npx lines read as a package and its arguments, and those left to npx.+func TestReadNpx(t *testing.T) {+ for _, c := range []struct {+ cmd string+ args []string+ spec string+ rest []string+ }{+ {"npx", []string{"-y", "@playwright/mcp@latest", "--headless"}, "@playwright/mcp@latest", []string{"--headless"}},+ {`C:\Program Files\nodejs\npx.cmd`, []string{"--yes", "[email protected]"}, "[email protected]", []string{}},+ {"/opt/homebrew/bin/npx", []string{"-y", "firecrawl-mcp"}, "firecrawl-mcp", []string{}},+ {"npx", []string{"firecrawl-mcp"}, "", nil}, // no -y: npx asks+ {"npx", []string{"-y", "-p", "a", "b"}, "", nil}, // -p+ {"npx", []string{"-y", "github:me/srv"}, "", nil}, // not the registry's+ {"npx", []string{"-y", "./srv"}, "", nil}, // a path+ {"bunx", []string{"-y", "srv"}, "", nil}, // not npx+ {"npx", []string{"-y", "--registry=https://x", "srv"}, "", nil}, // a flag of npm's+ {"node", []string{"-y", "srv"}, "", nil}, // node+ {"npx", []string{"-y", "mcp-remote", "https://hf.co/mcp"}, "mcp-remote", []string{"https://hf.co/mcp"}},+ } {+ r, ok := readNpx(&Server{Transport: "stdio", Command: c.cmd, Args: c.args})+ if ok != (c.spec != "") || r.spec != c.spec || len(r.args)+len(c.rest) > 0 && !slices.Equal(r.args, c.rest) {+ t.Errorf("%s %q: read %q %q %v, want %q %q", c.cmd, c.args, r.spec, r.args, ok, c.spec, c.rest)+ }+ }+ for spec, pinned := range map[string]bool{"[email protected]": true, "@s/[email protected]": true, "a": false, "@s/a": false, "a@latest": false, "a@^1.2.0": false} {+ if (npxRun{spec: spec}).pinned() != pinned {+ t.Errorf("%s pinned = %v", spec, !pinned)+ }+ }+}++// An agent is given an npx server as node running the package's program+// from magpie's install of it, with the server's arguments after: no npx+// left between the agent and the server, which held a node and two+// cmd.exe a server on Windows (#3885). Before the install is done the+// agent has npx, as the library does; the install is asked for once.+func TestNpxServerRunsByNode(t *testing.T) {+ h := sandbox(t)+ cfg := filepath.Join(h, ".codex/config.toml")+ installs := make(chan string, 4)+ release := make(chan struct{})+ npxInstall = func(spec, npx, dir string) error {+ installs <- spec+ <-release+ pkg := filepath.Join(dir, "node_modules", "@acme", "mcp")+ if err := os.MkdirAll(filepath.Join(pkg, "dist"), 0o755); err != nil {+ return err+ }+ write(t, filepath.Join(pkg, "package.json"), `{"name":"@acme/mcp","bin":{"acme-mcp":"dist/cli.js"}}`)+ write(t, filepath.Join(pkg, "dist", "cli.js"), "#!/usr/bin/env node\n")+ return nil+ }+ synced := make(chan struct{}, 1)+ npxSynced = func() { synced <- struct{}{} }+ t.Cleanup(func() { npxInstall, npxSynced = nil, nil })++ srv := Server{Name: "acme", Transport: "stdio", Command: "npx", Args: []string{"-y", "@acme/[email protected]", "--port", "0"}, Agents: []string{"codex"}}+ ok(t)(SaveServer("", srv))+ if e := codexEntry(t, cfg, "acme"); e["command"] != "npx" {+ t.Fatalf("before the install, Codex has %v, want npx:\n%s", e["command"], read(t, cfg))+ }+ select {+ case got := <-installs:+ if got != "@acme/[email protected]" {+ t.Fatalf("installed %q", got)+ }+ case <-time.After(30 * time.Second):+ close(release)+ t.Fatal("the package was never installed")+ }+ ok(t)(Sync()) // while installing: asked for no second time+ close(release)+ select {+ case <-synced:+ case <-time.After(30 * time.Second):+ t.Fatal("the install never asked for a sync")+ }+ if len(installs) > 0 {+ t.Fatalf("the package was installed again: %s", <-installs)+ }+ ok(t)(Sync())+ e := codexEntry(t, cfg, "acme")+ args, _ := e["args"].([]any)+ if e["command"] != "node" || len(args) != 3 || !strings.HasSuffix(filepath.ToSlash(args[0].(string)), "/node_modules/@acme/mcp/dist/cli.js") || args[1] != "--port" || args[2] != "0" {+ t.Fatalf("Codex runs %v %v, want node …/@acme/mcp/dist/cli.js --port 0:\n%s", e["command"], args, read(t, cfg))+ }+ before := read(t, cfg)+ ok(t)(Sync())+ if read(t, cfg) != before {+ t.Fatalf("a sync wrote the entry again:\n%s", read(t, cfg))+ }+ if l, _ := load(); l.server("acme").Command != "npx" {+ t.Fatalf("the library's own server became %s", l.server("acme").Command)+ }++ // taken off, the processes running the program are the ones ended+ var ended []*Server+ ending = func(s []*Server) { ended = append(ended, s...) }+ t.Cleanup(func() { ending = func([]*Server) {} })+ ok(t)(ServerAgents("acme", nil))+ if len(ended) != 1 || !launchedBy(ended[0])(`"node" "`+args[0].(string)+`" --port 0`) {+ t.Fatalf("ended %v, want node's run of the program", ended)+ }++ // out of the library, the install goes a day after its last+ dir := npxDir("@acme/[email protected]")+ write(t, filepath.Join(dir, ".installed"), "@acme/[email protected]\n")+ ok(t)(Sync())+ if _, err := os.Stat(dir); err != nil {+ t.Fatalf("the install of a server the library has went: %v", err)+ }+ ok(t)(RemoveServer("acme"))+ ok(t)(Sync())+ if _, err := os.Stat(dir); err != nil {+ t.Fatalf("an install under a day old went at once: %v", err)+ }+ old := time.Now().Add(-25 * time.Hour)+ os.Chtimes(filepath.Join(dir, ".installed"), old, old)+ ok(t)(Sync())+ if _, err := os.Stat(dir); err == nil {+ t.Fatal("the install of a server taken out of the library stays")+ }+}++// A package whose program isn't a script node runs, or with no bin to+// pick, stays with npx.+func TestNpxBinPicks(t *testing.T) {+ dir := t.TempDir()+ put := func(name, pkgJSON string, files map[string]string) {+ pkg := filepath.Join(dir, "node_modules", filepath.FromSlash(name))+ os.MkdirAll(pkg, 0o755)+ write(t, filepath.Join(pkg, "package.json"), pkgJSON)+ for f, b := range files {+ os.MkdirAll(filepath.Dir(filepath.Join(pkg, f)), 0o755)+ write(t, filepath.Join(pkg, f), b)+ }+ }+ put("one", `{"bin":"cli.mjs"}`, map[string]string{"cli.mjs": "import x from 'y'"})+ put("@s/two", `{"bin":{"other":"o.js","two":"bin/two"}}`, map[string]string{"bin/two": "#!/usr/bin/env node\n", "o.js": ""})+ put("native", `{"bin":{"native":"bin/native"}}`, map[string]string{"bin/native": "\x7fELF"})+ put("many", `{"bin":{"a":"a.js","b":"b.js"}}`, map[string]string{"a.js": "", "b.js": ""})+ put("out", `{"bin":"../one/cli.mjs"}`, nil)+ for name, want := range map[string]string{"one": "cli.mjs", "@s/two": "bin/two", "native": "", "many": "", "out": "", "none": ""} {+ got := npxBin(dir, name)+ if want == "" && got != "" || want != "" && !strings.HasSuffix(filepath.ToSlash(got), name+"/"+want) {+ t.Errorf("%s: bin %q, want %q", name, got, want)+ }+ }+}diff --git a/internal/library/sync.go b/internal/library/sync.goindex 26dc98333..f7bd5f494 100644--- a/internal/library/sync.go+++ b/internal/library/sync.go@@ -154,7 +154,8 @@ func Sync() (*Result, error) {return nil}// the agents are found under the lock, as a change finds them- if err := step(func(l *Library) { all = Targets(); gone = l.held(all) }); err != nil {+ var npxDirs map[string]bool+ if err := step(func(l *Library) { all = Targets(); gone = l.held(all); npxDirs = l.npxDirs() }); err != nil {return nil, err}for _, f := range syncSteps(all, gone, b, res) {@@ -171,6 +172,7 @@ func Sync() (*Result, error) {if len(res.dropped) > 0 {ending(res.dropped)}+ npxPrune(npxDirs)return res, nil}@@ -245,6 +247,9 @@ func (l *Library) syncMCP(t *Target, b *backups, res *Result) {continue}s, _ = t.MCP.side(s)+ if !t.MCP.WSL {+ s = npxDirect(s)+ }s = wroteStartup(s, a.Startup[s.Name])old := entries[s.Name]if err := t.MCP.foreign(old); err != nil {