diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index fa1f8d1a2..3b10cd5ed 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -24,7 +24,7 @@ Pi's extensions and packages. | 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 (`sweepShared`, then `syncShared` for the Put skills in setting), 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, 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. Nothing of magpie's goes into the project's git: what it placed is listed in the repository's own `info/exclude` (`writeExclude`, one block per project between `excludeBegin(dir)` and `ignoreEnd`, read by every worktree, never committed), and the project's `.gitignore` is left as it is (a block an older magpie wrote there is taken out, `TestProjectKeptOutOfGitByExclude`). A folder outside git gets no ignore file; once it is `git init`ed, `treesChanged` sees no block and the next `KeepLinked` writes it (`TestProjectOutsideGit`). A project is the global set ± its own (WhyULose0 on X): `ServersOff` and `SkillsOff` turn a global server or skill off in the project for some agents (`ProjectServerOff`, `ProjectSkillsOff`; `POST /api/library/projects/server-off` and `skill-off` with `dir`, `name`/`names`, `agents`; none gives it back). Each is done the way the agent reads it for a folder (`project_scope.go`): Claude Code's record of the project in `~/.claude.json` (`projects[
]`, `claudeRoot`) gets the name in `disabledMcpServers`, where magpie takes out only names it added (`Claude.Off`); Codex gets `[mcp_servers.] enabled = false` in the project's `.codex/config.toml`, only for a server in its own config (`CodexOff`); a skill is `skillOverrides. = "off"` in the project's `.claude/settings.local.json` (`Overrides`), a value the user set there is theirs (`TestProjectServerOff`, `TestProjectSkillOff`). Only those (`ProjectOffAgents`, `ProjectSkillOffAgents`) can take an off, and a skill an agent reaches through the [skill router](skill-router.md) can't; the card shows a global agent that can't as always on, with why. With the [MCP router](mcp-router.md) on, a project that adds or turns off a server the router serves gives Claude Code and Codex their own hub entry, `~` (`projectHubs`): Claude Code's in its record's `mcpServers` (local scope), Codex's in the project's `.codex/config.toml`; the server added isn't written into `.mcp.json` then (`TestProjectSetThroughRouter`). Claude Code keys its record by the repository's main top folder, so a project in a subfolder turns its offs on for the whole repository. A git worktree of the project's repository follows the project (`treeDirs`, `Trees`): the project's folder in each worktree gets the same skills, servers and offs, and is let go when the worktree is removed; `KeepLinked` checks for new ones (`keepProjectTrees`, `TestProjectWorktreeFollows`). `magpie library project …` (#5193, [`library_project_cli.go`](../../internal/cli/library_project_cli.go)) adds and removes a project and its skills through the same calls as the page (`AddProject`, `RemoveProject`, `ProjectSkills`, `ProjectSkill`, `ProjectCopy`); a skill added with no `agents=` goes to the agents the page's Skills menu picks (those the project's skills are for already, else every agent here with a project skills folder), and one not placed exits 1 with why (`TestLibraryProjectCmd`). A project card's Skills menu lists the skills by source as the Library does (`skillGroups(true)`, whatever sort the list has; one group is the flat list), a heading over each that ticks or unticks the whole group (`group` in `openProtoMenu`, half-ticked while some are in; Elorynth on X, `project-skills-groups.test.cjs`). | [`projects.go`](../../internal/library/projects.go), [`project_mcp.go`](../../internal/library/project_mcp.go), [`project_scope.go`](../../internal/library/project_scope.go), [`project_git.go`](../../internal/library/project_git.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`). MiniMax Code reads `AGENTS.md` in its data folder (`$MINIMAX_DATA_DIR`, else `~/.minimax`) before every conversation, so its target is that file (`TestMiniMaxCodeInstructions`). WorkBuddy and WorkBuddy AI keep theirs as a string in a JSON file: `personalization.customPrompt` in `app/app-config.json` of their folder, the Custom Instructions of the app's Personalization settings (`Target.Field`, `instr_field.go`). magpie's part goes into that string between the same marker lines, after the user's own prompt, and a `Field` write goes through `edit.SetJSON`, so every other key, its order and its indentation stay as the app wrote them; taking the part back leaves the file as it was, the field (and a `personalization` object nothing else is in) going out when it holds nothing. A file that is not JSON, or a field that holds something other than text, is unknown: it is reported and written over by nothing (`TestWorkBuddyInstructionsAreAJSONField`, `TestWorkBuddyInstructionsFromNothing`, `TestWorkBuddyInstructionsUnreadFileIsLeftAlone`, `TestWorkBuddyInstructionsImport`). The app's config service loads the file as it starts and writes it whole on a save (`AppConfigService`, 5.5.6's app.asar), so a change made while it runs may need a restart of the app, and may be lost to its next save of any setting; this has not been tried against a running app. | [`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 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`). A remote server holds several accounts (Elorynth on X), one in use that every agent is given: sets of headers are `Server.Accounts` with `Server.Account` the one in use ("" is the server's own `Headers`), laid over `Headers` by `live` in `through`, `remoteHeaders` and `hubKey`, so a switch rewrites each agent's file (`TestServerAccountsSwitchEveryAgent`); a save from the editor, which doesn't send them, keeps them, and a backup carries no account's key (`TestServerAccountKeysAreSecrets`). magpie's OAuth sign-ins are `mcpauth` records, the one in use at `m[name]` and the others in `Spare` (`Use`, `RemoveAccount`, `StartAccount`), which the gateway's `/mcp/` sends from its next request on; an agent's existing upstream `Mcp-Session-Id` isn't reset by a switch. API `/api/library/mcp-account`; GUI `headerAccounts` and `acctList` (`mcp-accounts.test.cjs`). | [`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. A registry package is started the way its entry says (`launchLine`): its `runtimeArguments` are the runner's options (`uvx -p 3.13`, `npx --package`, docker's mounts) and the program's own words (Serena's `start-mcp-server`), then its `packageArguments`; an executable not named after the package is reached with `uvx --from ` or `npx --package `. The shipped crawl keeps each package's executables (`bins`, from npm's `bin` and the wheel's console scripts); a package with none, several with none standing out (`pickBin`), or a required option magpie can't fill isn't offered. A server installed from the market before, still on the line magpie gave it then, is given the new one on load (`healMarketLines`; fwxkogaia on X, `TestRegistryLaunchLines`, `TestInstalledMarketLineHealed`). | [`market.go`](../../internal/library/market.go), [`market_launch.go`](../../internal/library/market_launch.go), [`market_repo.go`](../../internal/library/market_repo.go) | @@ -124,7 +124,7 @@ node --test internal/gui/tests/library-pi-extensions.test.cjs internal/gui/tests node --test internal/gui/tests/library-rtk-wsl.test.cjs node --test internal/gui/tests/library-wsl-asleep.test.cjs node --test internal/gui/tests/skill-off-here.test.cjs internal/gui/tests/mcp-local-server.test.cjs internal/gui/tests/skill-handover.test.cjs -node --test internal/gui/tests/library-items.test.cjs internal/gui/tests/library-mcp-hub.test.cjs internal/gui/tests/library-alma-profile.test.cjs internal/gui/tests/library-rtk-gain.test.cjs internal/gui/tests/library-rtk-nohook.test.cjs internal/gui/tests/library-servers-bulk.test.cjs internal/gui/tests/library-pick-remove.test.cjs internal/gui/tests/library-env-refs.test.cjs internal/gui/tests/library-zed-mcp.test.cjs internal/gui/tests/library-workbuddy-trust.test.cjs internal/gui/tests/skill-new-in-repo.test.cjs internal/gui/tests/skill-update-edited.test.cjs internal/gui/tests/skill-gone.test.cjs internal/gui/tests/skill-git-source.test.cjs internal/gui/tests/remove-found-skill.test.cjs internal/gui/tests/found-skill-pick-remove.test.cjs internal/gui/tests/library-loading.test.cjs internal/gui/tests/library-mcp-tools.test.cjs internal/gui/tests/library-mcp-tool-switch.test.cjs internal/gui/tests/library-hooks.test.cjs internal/gui/tests/library-subagents.test.cjs internal/gui/tests/library-plugins.test.cjs internal/gui/tests/library-mcp-health.test.cjs internal/gui/tests/library-mcp-health-wsl.test.cjs internal/gui/tests/mcp-signin-health.test.cjs internal/gui/tests/mcp-signin.test.cjs internal/gui/tests/mcp-editor-cancel.test.cjs internal/gui/tests/mcp-oauth-app.test.cjs internal/gui/tests/library-ime-scroll.test.cjs +node --test internal/gui/tests/mcp-accounts.test.cjs internal/gui/tests/library-items.test.cjs internal/gui/tests/library-mcp-hub.test.cjs internal/gui/tests/library-alma-profile.test.cjs internal/gui/tests/library-rtk-gain.test.cjs internal/gui/tests/library-rtk-nohook.test.cjs internal/gui/tests/library-servers-bulk.test.cjs internal/gui/tests/library-pick-remove.test.cjs internal/gui/tests/library-env-refs.test.cjs internal/gui/tests/library-zed-mcp.test.cjs internal/gui/tests/library-workbuddy-trust.test.cjs internal/gui/tests/skill-new-in-repo.test.cjs internal/gui/tests/skill-update-edited.test.cjs internal/gui/tests/skill-gone.test.cjs internal/gui/tests/skill-git-source.test.cjs internal/gui/tests/remove-found-skill.test.cjs internal/gui/tests/found-skill-pick-remove.test.cjs internal/gui/tests/library-loading.test.cjs internal/gui/tests/library-mcp-tools.test.cjs internal/gui/tests/library-mcp-tool-switch.test.cjs internal/gui/tests/library-hooks.test.cjs internal/gui/tests/library-subagents.test.cjs internal/gui/tests/library-plugins.test.cjs internal/gui/tests/library-mcp-health.test.cjs internal/gui/tests/library-mcp-health-wsl.test.cjs internal/gui/tests/mcp-signin-health.test.cjs internal/gui/tests/mcp-signin.test.cjs internal/gui/tests/mcp-editor-cancel.test.cjs internal/gui/tests/mcp-oauth-app.test.cjs internal/gui/tests/library-ime-scroll.test.cjs ``` The package's `TestMain` runs in a home of its own (`testenv`), never the diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index c56df6802..9591c0988 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -3486,11 +3486,15 @@ magpie.plugin("library", (ctx) => { draw(); signMoved(name); })); + } else if (cur.accounts?.length > 1) { + // several sign-ins: the one in use is what every agent is given + box.append(acctList(cur.accounts.map((a) => ({ id: a.id, name: a.label || t("Account {n}", { n: cur.accounts.indexOf(a) + 1 }), on: a.active, bad: a.dead })), "signin", name, draw)); + line.append(addSign(), el("span", "grow"), button(t("Sign out"), "", signOut)); } else if (cur.signedIn && !cur.dead) { - line.append(tag(t("Signed in"), "lib-signed"), el("span", "note", t("The agents given it use magpie's sign-in")), el("span", "grow"), button(t("Sign out"), "", signOut)); + line.append(tag(t("Signed in"), "lib-signed"), el("span", "note", t("The agents given it use magpie's sign-in")), el("span", "grow"), name ? addSign() : "", button(t("Sign out"), "", signOut)); } else { if (cur.dead) line.append(tag(t("Sign-in ran out"), "warn")); - line.append(button(ready?.saves?.() ? t("Save and sign in") : cur.dead ? t("Sign in again") : t("Sign in"), "action", start)); + line.append(button(ready?.saves?.() ? t("Save and sign in") : cur.dead ? t("Sign in again") : t("Sign in"), "action", () => start())); } box.append(line); // the browser didn't start (#2043): the page to open by hand, rather @@ -3507,7 +3511,19 @@ magpie.plugin("library", (ctx) => { } if (sg?.state === "failed") box.append(el("div", "lib-signin-err", sg.error)); }; - async function start() { + // another sign-in to the server, called what the reader types + let adding = false; + function addSign() { + if (!adding) return button(t("+ Add account"), "lib-addacct", () => { adding = true; draw(); box.querySelector(".lib-acct-new input")?.focus(); }); + const f = el("span", "lib-acct-new"); + const i = field2("", t("Name"), () => {}); + i.maxLength = 60; + const go = () => { adding = false; start(i.value.trim()); }; + i.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.isComposing) { e.preventDefault(); e.stopPropagation(); go(); } }); + f.append(i, button(t("Sign in"), "action", go), button(t("Cancel"), "", () => { adding = false; draw(); })); + return f; + } + async function start(label) { const was = name; mcpSigning = { name, state: "starting" }; draw(); @@ -3519,7 +3535,7 @@ magpie.plugin("library", (ctx) => { name = saved; mcpSigning = { name, state: "starting" }; } - const st = await api("library/mcp-signin", { name }); + const st = await api("library/mcp-signin", typeof label === "string" ? { name, add: true, label } : { name }); if (web && st.url) api("open", { url: st.url }).catch(() => {}); mcpSigning = { ...st, name }; draw(); @@ -3546,6 +3562,76 @@ magpie.plugin("library", (ctx) => { return box; } + // the accounts of a server, one in use (Elorynth on X): a click on a row + // puts it in use, in place; every agent given the server follows. kind is + // "signin" for magpie's OAuth sign-ins, "header" for sets of headers + function acctList(rows, kind, name, redraw) { + const list = el("div", "lib-accts"); + list.setAttribute("role", "radiogroup"); + const call = async (op, id) => { + try { + take(await api("library/mcp-account", { name, kind, op, id })); + render(); + redraw(); + } catch (e) { status(e.message, "err", 6000); } + }; + for (const r of rows) { + const row = el("div", "lib-acct" + (r.on ? " on" : "")); + const pick = el("button", "lib-acct-pick"); + pick.setAttribute("role", "radio"); + pick.setAttribute("aria-checked", r.on ? "true" : "false"); + pick.append(el("span", "lib-acct-dot"), el("span", "lib-acct-name", r.name)); + if (r.bad) pick.append(tag(t("Sign-in ran out"), "warn")); + pick.onclick = (e) => { e.stopPropagation(); if (!r.on) call("use", r.id); }; + row.append(pick); + if (r.id !== "") { + const x = button("", "lib-x", () => call("remove", r.id)); + x.append(svg("M4.5 4.5l7 7M11.5 4.5l-7 7", 11, 1.6)); + x.title = t("Remove"); + row.append(x); + } + list.append(row); + } + return list; + } + // Authorization headers a server can be asked with, besides its own + function headerAccounts(name) { + const box = el("div", "lib-hdr-accts"); + let adding = false; + const draw = () => { + box.replaceChildren(); + const s = lib.servers.find((x) => x.name === name); + if (!s) return; + const l = s.accounts || []; + if (l.length) { + box.append(acctList([{ id: "", name: t("Default"), on: !s.account }, ...l.map((a) => ({ id: a.id, name: a.name, on: a.id === s.account }))], "header", name, draw)); + } + if (!adding) { + box.append(button(t("+ Add account"), "lib-addacct", () => { adding = true; draw(); box.querySelector(".lib-acct-form input")?.focus(); })); + return; + } + const form = el("div", "lib-acct-form"); + let label = "", headers = { Authorization: "" }; + const add = async () => { + try { + take(await api("library/mcp-account", { name, kind: "header", op: "add", label, headers })); + adding = false; + render(); + draw(); + } catch (e) { status(e.message, "err", 6000); } + }; + const n = field2("", t("Name"), (v) => { label = v; }); + n.maxLength = 60; + form.append(n, pairs(headers, "Authorization", "Bearer …", (v) => { headers = v; }), + el("div", "lib-acct-act"), ); + form.lastChild.append(button(t("Add"), "action", add), button(t("Cancel"), "", () => { adding = false; draw(); })); + box.append(form); + }; + box.redraw = draw; + draw(); + return box; + } + function foundServerRow(f) { const s = f.server; const row = el("div", "row lib-row"); @@ -3902,6 +3988,7 @@ magpie.plugin("library", (ctx) => { url.classList.add("mono"); g.append(...field("URL", url)); g.append(...field(t("Headers"), pairs(d.headers, "Authorization", "Bearer …", (v) => { d.headers = v; drawAgents(); }), refHint())); + if (s && s.transport === d.transport && s.url) g.append(...field(t("Accounts"), headerAccounts(s.name))); // Sign in saves the form first when it is of another server than // the saved one, so a URL just changed (or a server just added) is // the one signed in to diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index 5867fcbd7..caac196ea 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -2,6 +2,8 @@ // kernel adds them to i18n.js's (magpie.strings). magpie.strings({ zh: { + "+ Add account": "+ 添加账号", + "Account {n}": "账号 {n}", "New skill": "新建技能", "e.g. my-skill": "例如 my-skill", "e.g. Writes release notes. Use when asked for a changelog.": "例如:撰写发布说明。需要更新日志时使用。", @@ -979,6 +981,8 @@ magpie.strings({ "{name} read again from its source": "已重新从来源读取 {name}", }, "zh-TW": { + "+ Add account": "+ 新增帳號", + "Account {n}": "帳號 {n}", "New skill": "新增技能", "e.g. my-skill": "例如 my-skill", "e.g. Writes release notes. Use when asked for a changelog.": "例如:撰寫發佈說明。需要更新日誌時使用。", @@ -1956,6 +1960,8 @@ magpie.strings({ "{name} read again from its source": "已重新從來源讀取 {name}", }, ja: { + "+ Add account": "+ アカウントを追加", + "Account {n}": "アカウント {n}", "New skill": "新しいスキル", "e.g. my-skill": "例: my-skill", "e.g. Writes release notes. Use when asked for a changelog.": "例: リリースノートを書く。変更履歴を求められたときに使う。", @@ -2933,6 +2939,8 @@ magpie.strings({ "{name} read again from its source": "{name} をソースから読み直しました", }, de: { + "+ Add account": "+ Konto hinzufügen", + "Account {n}": "Konto {n}", "New skill": "Neuer Skill", "e.g. my-skill": "z. B. my-skill", "e.g. Writes release notes. Use when asked for a changelog.": "z. B. Schreibt Release Notes. Zu verwenden, wenn ein Changelog verlangt wird.", diff --git a/internal/gui/assets/plugins/library/library.css b/internal/gui/assets/plugins/library/library.css index 8905fb12a..7fd23426b 100644 --- a/internal/gui/assets/plugins/library/library.css +++ b/internal/gui/assets/plugins/library/library.css @@ -901,3 +901,21 @@ body.window .lib-list .lib-row { --lib-indent: 38px; } input.lib-memq, input.lib-memtags, input.lib-memwhy { padding: 0 9px; border-radius: 7px; border: 1px solid var(--line); background: var(--card); color: var(--fg); font-size: 12.5px; outline: none; box-sizing: border-box; transition: border-color .12s, box-shadow .12s; } input.lib-memq:focus, input.lib-memtags:focus, input.lib-memwhy:focus { border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 22%, transparent); } .lib-follow .link { font-size: inherit; padding: 0; margin-left: 2px; } + +/* a server's accounts, one in use (Elorynth on X) */ +.lib-accts { display: flex; flex-direction: column; gap: 4px; margin-bottom: 6px; } +.lib-acct { display: flex; align-items: center; gap: 4px; border: 1px solid var(--line); border-radius: 8px; background: var(--card); transition: background-color .12s ease, border-color .12s ease; } +.lib-acct.on { border-color: var(--accent); background: var(--accent-soft); } +.lib-acct-pick { flex: 1; min-width: 0; display: flex; align-items: center; gap: 8px; padding: 6px 10px; border: 0; background: none; color: var(--fg); font: inherit; text-align: left; cursor: pointer; } +.lib-acct.on .lib-acct-pick { cursor: default; } +.lib-acct-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.lib-acct-dot { flex: none; width: 8px; height: 8px; border-radius: 50%; border: 1.5px solid var(--faint); box-sizing: border-box; transition: background-color .12s ease, border-color .12s ease; } +.lib-acct.on .lib-acct-dot { background: var(--accent); border-color: var(--accent); } +.lib-acct .lib-x { margin-right: 4px; } +.lib-acct-new { display: inline-flex; align-items: center; gap: 6px; flex-wrap: wrap; } +.lib-acct-new input { width: 11em; max-width: 100%; } +.lib-acct-form { display: flex; flex-direction: column; gap: 6px; } +.lib-acct-form > input { max-width: 16em; } +.lib-acct-act { display: flex; gap: 8px; } +@media (hover: hover) and (pointer: fine) { .lib-acct:not(.on):hover { background: var(--hover, var(--accent-soft)); } } +@media (prefers-reduced-motion: reduce) { .lib-acct, .lib-acct-dot { transition: none; } } diff --git a/internal/gui/library.go b/internal/gui/library.go index 8e19d6c63..383733053 100644 --- a/internal/gui/library.go +++ b/internal/gui/library.go @@ -519,12 +519,22 @@ func libraryRoutes(mux *http.ServeMux, w Windows) { }) // magpie signs in to a remote server once, for every agent given it (#615) mux.HandleFunc("POST /api/library/mcp-signin", func(rw http.ResponseWriter, r *http.Request) { - var in struct{ Name string } + var in struct { + Name string + Add bool // as another account of the server, called Label + Label string + } if err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.Name == "" { http.Error(rw, "no server", http.StatusBadRequest) return } - st, err := library.SignInServer(r.Context(), in.Name) + var st mcpauth.State + var err error + if in.Add { + st, err = library.SignInServerAccount(r.Context(), in.Name, in.Label) + } else { + st, err = library.SignInServer(r.Context(), in.Name) + } if err != nil { fail(rw, err) return @@ -543,6 +553,45 @@ func libraryRoutes(mux *http.ServeMux, w Windows) { mcpauth.Cancel(r.PathValue("id")) rw.WriteHeader(http.StatusNoContent) }) + // a server's accounts (Elorynth on X): Kind "signin" is magpie's OAuth + // sign-ins to it, "header" the sets of headers it is asked with; ID "" in + // a use is the server's own headers + mux.HandleFunc("POST /api/library/mcp-account", func(rw http.ResponseWriter, r *http.Request) { + var in struct { + Name, Kind, Op, ID, Label string + Headers map[string]string + } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.Name == "" { + http.Error(rw, "no server", http.StatusBadRequest) + return + } + var err error + switch in.Kind + "/" + in.Op { + case "signin/use": + err = library.UseSignIn(in.Name, in.ID) + case "signin/remove": + err = library.RemoveSignIn(in.Name, in.ID) + case "header/add": + _, err = library.AddServerAccount(in.Name, in.Label, in.Headers) + case "header/use": + _, err = library.UseServerAccount(in.Name, in.ID) + case "header/remove": + _, err = library.RemoveServerAccount(in.Name, in.ID) + default: + http.Error(rw, "not an account call", http.StatusBadRequest) + return + } + if err != nil { + fail(rw, err) + return + } + v, err := libraryView(nil) + if err != nil { + fail(rw, err) + return + } + writeJSON(rw, v) + }) mux.HandleFunc("POST /api/library/mcp-signout", func(rw http.ResponseWriter, r *http.Request) { var in struct{ Name string } if err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.Name == "" { diff --git a/internal/gui/tests/mcp-accounts.test.cjs b/internal/gui/tests/mcp-accounts.test.cjs new file mode 100644 index 000000000..21bf1fe2a --- /dev/null +++ b/internal/gui/tests/mcp-accounts.test.cjs @@ -0,0 +1,162 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Elorynth on X: a remote MCP server holds several Authorization headers or +// several OAuth sign-ins, one in use, switched in place. With one, the +// editor looks as it did, plus a quiet "Add account". In every language, in +// both engines. 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 assets = path.resolve(__dirname, "../assets"); +const HOME = "/Users/aimer"; +const agent = (id, name) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json` }); +const base = () => ({ + dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME, + agents: [agent("codex", "Codex"), agent("claude", "Claude Code")], + instructions: { agents: [], sets: [] }, foundServers: [], projects: [], foundSkills: [], skills: [], + servers: [ + { name: "web", transport: "http", url: "https://web.example/mcp", headers: { Authorization: "Bearer base" }, agents: ["codex", "claude"] }, + { name: "two", transport: "http", url: "https://two.example/mcp", headers: {}, agents: ["codex"], account: "2", + accounts: [{ id: "1", name: "personal", headers: { Authorization: "Bearer p" } }, { id: "2", name: "work", headers: { Authorization: "Bearer w" } }] }, + { name: "one", transport: "http", url: "https://one.example/mcp", agents: ["codex"], signIn: { signedIn: true, at: 1 } }, + { name: "many", transport: "http", url: "https://many.example/mcp", agents: ["codex"], + signIn: { signedIn: true, at: 1, accounts: [{ id: "1", label: "me", active: true }, { id: "2", label: "team" }] } }, + ], +}); + +function server(calls) { + const lib = base(); + const lang = process.env.LANG_UNDER_TEST; + return async (route) => { + const req = route.request(), url = new URL(req.url()); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return route.fulfill({ json: { agents: [], profiles: [], settings: { lang, theme: "light" } } }); + if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } }); + if (url.pathname === "/api/library") return route.fulfill({ json: lib }); + if (url.pathname === "/api/library/mcp-account") { + const b = req.postDataJSON(); + calls.push([b.name, b.kind, b.op, b.id ?? "", b.label ?? "", JSON.stringify(b.headers ?? {})].join("|")); + const s = lib.servers.find((x) => x.name === b.name); + if (b.kind === "header") { + s.accounts = s.accounts || []; + if (b.op === "add") { const id = String(s.accounts.length + 1); s.accounts.push({ id, name: b.label, headers: b.headers }); s.account = id; } + if (b.op === "use") s.account = b.id; + if (b.op === "remove") { s.accounts = s.accounts.filter((a) => a.id !== b.id); if (s.account === b.id) s.account = ""; if (!s.accounts.length) delete s.accounts; } + } else if (b.op === "use") s.signIn.accounts.forEach((a) => { a.active = a.id === b.id; }); + return route.fulfill({ json: lib }); + } + if (url.pathname === "/api/library/mcp-signin") { + calls.push("signin " + JSON.stringify(req.postDataJSON())); + return route.fulfill({ status: 400, json: { error: "stop here" } }); + } + if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] }); + if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } }); + if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } }); + if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} }); + 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)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +// core words (i18n.js) and the Library plugin's own +const words = { + en: { add: "+ Add account", name: "Name", def: "Default", addBtn: "Add", accounts: "Accounts", signIn: "Sign in" }, + zh: { add: "+ 添加账号", name: "名称", def: "默认", addBtn: "添加", accounts: "账号", signIn: "登录" }, + "zh-TW": { add: "+ 新增帳號", name: "名稱", def: "預設", addBtn: "新增", accounts: "帳號", signIn: "登入" }, + ja: { add: "+ アカウントを追加", name: "名前", def: "デフォルト", addBtn: "追加", accounts: "アカウント", signIn: "サインイン" }, + de: { add: "+ Konto hinzufügen", name: "Name", def: "Standard", addBtn: "Hinzufügen", accounts: "Konten", signIn: "Anmelden" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": a server's accounts are switched in its editor", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const errors = []; + t.after(async () => { + if (errors.length) console.log(errors); + await browser.close(); + assert.deepEqual(errors, []); + }); + for (const lang of Object.keys(words)) { + await t.test(lang, async () => { + const w = words[lang]; + const calls = []; + process.env.LANG_UNDER_TEST = lang; + const ctx = await browser.newContext({ viewport: { width: 980, height: 800 } }); + 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(calls)); + await page.goto("http://magpie.test/"); + await page.locator('button[data-view="library"]').click(); + const row = (name) => page.locator("#view-library .lib-row", { has: page.locator(".name", { hasText: new RegExp("^" + name) }) }); + const close = async () => { await page.keyboard.press("Escape"); await page.locator("#modal .lib-editor").waitFor({ state: "detached" }); }; + await row("web").waitFor(); + + // one set of headers: no list, only the quiet button + await row("web").click(); + const accts = page.locator("#modal .lib-hdr-accts"); + await accts.waitFor(); + assert.equal(await accts.locator(".lib-acct").count(), 0); + await accts.getByRole("button", { name: w.add, exact: true }).click(); + await accts.locator(".lib-acct-form > input").fill("work"); + await accts.locator(".lib-pair input").nth(1).fill("Bearer sk-work"); + await accts.getByRole("button", { name: w.addBtn, exact: true }).click(); + await accts.locator(".lib-acct.on", { hasText: "work" }).waitFor(); + assert.equal(calls.at(-1), 'web|header|add||work|{"Authorization":"Bearer sk-work"}'); + assert.deepEqual(await accts.locator(".lib-acct-name").allTextContents(), [w.def, "work"]); + + // a click on Default puts the server's own headers back in use + await accts.locator(".lib-acct-pick", { hasText: w.def }).click(); + await accts.locator(".lib-acct.on", { hasText: w.def }).waitFor(); + assert.equal(calls.at(-1), "web|header|use|||{}"); + assert.equal(await accts.locator('[aria-checked="true"]').count(), 1); + await accts.locator(".lib-acct", { hasText: "work" }).locator(".lib-x").click(); + await accts.locator(".lib-acct").first().waitFor({ state: "detached" }); + assert.equal(calls.at(-1), "web|header|remove|1||{}"); + await close(); + + // several: the one in use is marked; another is put in use in place + await row("two").click(); + const two = page.locator("#modal .lib-hdr-accts"); + await two.locator(".lib-acct.on", { hasText: "work" }).waitFor(); + await two.locator(".lib-acct-pick", { hasText: "personal" }).click(); + await two.locator(".lib-acct.on", { hasText: "personal" }).waitFor(); + assert.equal(calls.at(-1), "two|header|use|1||{}"); + assert.equal(await two.locator(".lib-acct.on").count(), 1); + await close(); + + // an OAuth server with one sign-in: its line as before, and the quiet button + await row("one").click(); + const one = page.locator("#modal .lib-signin"); + await one.waitFor(); + assert.equal(await one.locator(".lib-accts").count(), 0); + await one.getByRole("button", { name: w.add, exact: true }).click(); + await one.locator(".lib-acct-new input").fill("team"); + await one.getByRole("button", { name: w.signIn, exact: true }).click(); + await one.locator(".lib-signin-err").waitFor(); + assert.equal(calls.at(-1), 'signin {"name":"one","add":true,"label":"team"}'); + await close(); + + // several sign-ins: a list, the one in use marked + await row("many").click(); + const many = page.locator("#modal .lib-signin"); + await many.locator(".lib-acct.on", { hasText: "me" }).waitFor(); + await many.locator(".lib-acct-pick", { hasText: "team" }).click(); + await many.locator(".lib-acct.on", { hasText: "team" }).waitFor(); + assert.equal(calls.at(-1), "many|signin|use|2||{}"); + assert.equal(await many.locator(".lib-acct.on").count(), 1); + // the page doesn't overflow sideways at a narrow width + await page.setViewportSize({ width: 420, height: 800 }); + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1)); + await ctx.close(); + }); + } + }); +} diff --git a/internal/library/carry.go b/internal/library/carry.go index 62d7b306b..ceb18052f 100644 --- a/internal/library/carry.go +++ b/internal/library/carry.go @@ -317,6 +317,11 @@ func (b *Bundle) WithoutSecrets(secret func(string) bool) { for i, s := range b.MCP { c := *s c.Env, c.Headers = blank(s.Env, secret), blank(s.Headers, secret) + c.Accounts = nil + for _, a := range s.Accounts { + a.Headers = blank(a.Headers, secret) + c.Accounts = append(c.Accounts, a) + } // an OAuth app's secret is a key too; its client ID isn't if s.OAuth != nil && s.OAuth.ClientSecret != "" { a := *s.OAuth @@ -355,6 +360,13 @@ func (b *Bundle) WithSecrets(have *Bundle, secret func(string) bool) *Bundle { i := slices.IndexFunc(have.MCP, func(h *Server) bool { return h.Name == s.Name }) if i >= 0 { c.Env, c.Headers = filled(s.Env, have.MCP[i].Env, secret), filled(s.Headers, have.MCP[i].Headers, secret) + c.Accounts = nil + for _, a := range s.Accounts { + if j := slices.IndexFunc(have.MCP[i].Accounts, func(h Account) bool { return h.ID == a.ID }); j >= 0 { + a.Headers = filled(a.Headers, have.MCP[i].Accounts[j].Headers, secret) + } + c.Accounts = append(c.Accounts, a) + } // the same app's secret, kept here if h := have.MCP[i].OAuth; s.OAuth != nil && s.OAuth.ClientSecret == "" && h != nil && h.ClientID == s.OAuth.ClientID { a := *s.OAuth diff --git a/internal/library/mcp.go b/internal/library/mcp.go index b61558ab0..342adcb68 100644 --- a/internal/library/mcp.go +++ b/internal/library/mcp.go @@ -52,6 +52,12 @@ type Server struct { // (GitHub's, 新v学员 on Discord). It is magpie's alone: the agents are // given the server as before. OAuth *OAuthApp `json:"oauth,omitempty"` + // Accounts are further sets of headers for the server (Elorynth on X: + // several keys, one in use), each laid over Headers, and Account is the + // one the agents are given ("" for Headers as they are). magpie's own + // OAuth sign-ins to the server have their accounts in mcpauth. + Accounts []Account `json:"accounts,omitempty"` + Account string `json:"account,omitempty"` // StartupTimeout is the seconds an agent waits for the server to start // and list its tools: Codex's startup_timeout_sec (#3168), the only // agent given it. 0 leaves it to the agent (Codex's own is 30s). @@ -188,7 +194,7 @@ func (s *Server) check() error { delete(s.Headers, k) } } - return nil + return s.checkAccounts() } // spacedProgram is a program by full path that has spaces in it, typed diff --git a/internal/library/mcp_accounts.go b/internal/library/mcp_accounts.go new file mode 100644 index 000000000..456d05c82 --- /dev/null +++ b/internal/library/mcp_accounts.go @@ -0,0 +1,169 @@ +package library + +import ( + "context" + "fmt" + "maps" + "slices" + "strconv" + "strings" + + "github.com/yetone/magpie/internal/mcpauth" +) + +// A remote server can hold several accounts (Elorynth on X: several OAuth +// sign-ins or Authorization headers, one in use, switched in a click). A +// key is an Account of the server's own, headers laid over the server's +// Headers; an OAuth sign-in is one of mcpauth's, kept with the others. The +// one in use is what every agent is given: a key's headers are written +// into each agent's entry by `live` before the entry is built (through), +// and a sign-in is what the gateway's /mcp/ sends, so a switch is a +// change like any other and each agent's file follows it. + +const maxAccountName = 60 + +// Account is one set of headers a server is asked with. +type Account struct { + ID string `json:"id"` + Name string `json:"name"` + Headers map[string]string `json:"headers,omitempty"` +} + +// live is the server as the agents are given it: with the headers of the +// account in use laid over its own, a name either has by any case going +// to the account's. +func (s *Server) live() *Server { + i := slices.IndexFunc(s.Accounts, func(a Account) bool { return a.ID == s.Account }) + if s.Account == "" || i < 0 { + return s + } + c := *s + c.Headers = maps.Clone(s.Headers) + if c.Headers == nil { + c.Headers = map[string]string{} + } + for k, v := range s.Accounts[i].Headers { + for have := range c.Headers { + if strings.EqualFold(have, k) { + delete(c.Headers, have) + } + } + c.Headers[k] = v + } + return &c +} + +// checkAccounts cleans the accounts: a server by command has none, each +// has a name (not another's, at most maxAccountName characters) and an id, +// and the one in use is one of them. +func (s *Server) checkAccounts() error { + if !s.Remote() { + s.Accounts, s.Account = nil, "" + return nil + } + seenName, seenID := map[string]bool{}, map[string]bool{} + for i := range s.Accounts { + a := &s.Accounts[i] + a.Name = strings.TrimSpace(a.Name) + if a.Name == "" || len([]rune(a.Name)) > maxAccountName { + return fmt.Errorf("%s: an account's name is from 1 to %d characters", s.Name, maxAccountName) + } + if key := strings.ToLower(a.Name); seenName[key] { + return fmt.Errorf("%s: two accounts are called %s", s.Name, a.Name) + } else { + seenName[key] = true + } + if a.ID == "" || seenID[a.ID] { + return fmt.Errorf("%s: an account has no id of its own", s.Name) + } + seenID[a.ID] = true + for k := range a.Headers { + if strings.TrimSpace(k) == "" { + delete(a.Headers, k) + } + } + } + if len(s.Accounts) == 0 { + s.Accounts = nil + } + if s.Account != "" && !seenID[s.Account] { + s.Account = "" + } + return nil +} + +// AddServerAccount gives the server another account, a set of headers (a +// key as Authorization), and puts it in use. +func AddServerAccount(name, label string, headers map[string]string) (*Result, error) { + h := map[string]string{} + for k, v := range headers { + if k = strings.TrimSpace(k); k != "" { + h[k] = v + } + } + if len(h) == 0 { + return nil, fmt.Errorf("an account needs a header, as Authorization") + } + return change(func(l *Library) error { + s := l.server(name) + if s == nil { + return fmt.Errorf("no server called %s", name) + } + if !s.Remote() { + return fmt.Errorf("%s runs as a command: accounts are for a server by URL", name) + } + top := 0 + for _, a := range s.Accounts { + n, _ := strconv.Atoi(a.ID) + top = max(top, n) + } + s.Accounts = append(s.Accounts, Account{ID: strconv.Itoa(top + 1), Name: label, Headers: h}) + s.Account = s.Accounts[len(s.Accounts)-1].ID + return s.checkAccounts() + }) +} + +// UseServerAccount puts an account of the server in use: "" is the +// server's own headers. +func UseServerAccount(name, id string) (*Result, error) { + return change(func(l *Library) error { + s := l.server(name) + if s == nil { + return fmt.Errorf("no server called %s", name) + } + if id != "" && !slices.ContainsFunc(s.Accounts, func(a Account) bool { return a.ID == id }) { + return fmt.Errorf("%s has no such account", name) + } + s.Account = id + return nil + }) +} + +// RemoveServerAccount takes an account away from the server; the one in +// use going puts the server's own headers back in use. +func RemoveServerAccount(name, id string) (*Result, error) { + return change(func(l *Library) error { + s := l.server(name) + if s == nil { + return fmt.Errorf("no server called %s", name) + } + i := slices.IndexFunc(s.Accounts, func(a Account) bool { return a.ID == id }) + if i < 0 { + return fmt.Errorf("%s has no such account", name) + } + s.Accounts = slices.Delete(slices.Clone(s.Accounts), i, i+1) + return s.checkAccounts() + }) +} + +// SignInServerAccount is SignInServer as another account of the server, +// put in use once signed in. +func SignInServerAccount(ctx context.Context, name, label string) (mcpauth.State, error) { + return signInServer(ctx, name, &label) +} + +// UseSignIn puts one of magpie's sign-ins to the server in use. +func UseSignIn(name, id string) error { return mcpauth.Use(name, id) } + +// RemoveSignIn forgets one of magpie's sign-ins to the server. +func RemoveSignIn(name, id string) error { return mcpauth.RemoveAccount(name, id) } diff --git a/internal/library/mcp_accounts_test.go b/internal/library/mcp_accounts_test.go new file mode 100644 index 000000000..d156e415c --- /dev/null +++ b/internal/library/mcp_accounts_test.go @@ -0,0 +1,99 @@ +package library + +import ( + "path/filepath" + "strings" + "testing" +) + +// A server holds several Authorization headers, one in use (Elorynth on +// X): switching rewrites what every agent is given, adding and removing +// keep the server's own headers, and the account stays through a save +// from the editor, which doesn't send it. +func TestServerAccountsSwitchEveryAgent(t *testing.T) { + h := sandbox(t) + codex := filepath.Join(h, ".codex/config.toml") + srv := Server{Name: "web", Transport: "http", URL: "https://x.example/mcp", + Headers: map[string]string{"Authorization": "Bearer base-key", "X-Team": "a"}, Agents: []string{"codex", "claude"}} + ok(t)(SaveServer("", srv)) + if !strings.Contains(read(t, codex), "base-key") { + t.Fatalf("the server's own key isn't written:\n%s", read(t, codex)) + } + + ok(t)(AddServerAccount("web", "work", map[string]string{"authorization": "Bearer work-key"})) + cfg := read(t, codex) + if !strings.Contains(cfg, "work-key") || strings.Contains(cfg, "base-key") { + t.Fatalf("the new account isn't the one in use:\n%s", cfg) + } + if !strings.Contains(cfg, "X-Team") { + t.Errorf("a header the account doesn't set went:\n%s", cfg) + } + _, err := AddServerAccount("web", "Work", map[string]string{"Authorization": "x"}) + if err == nil { + t.Errorf("two accounts called alike") + } + + // an editor's save doesn't send the accounts + got := lib(t).server("web") + save := *got + save.Accounts, save.Account = nil, "" + ok(t)(SaveServer("web", save)) + if s := lib(t).server("web"); len(s.Accounts) != 1 || s.Account != s.Accounts[0].ID { + t.Fatalf("a save lost the accounts: %+v", s) + } + + ok(t)(UseServerAccount("web", "")) + if cfg := read(t, codex); !strings.Contains(cfg, "base-key") || strings.Contains(cfg, "work-key") { + t.Fatalf("back to the server's own headers:\n%s", cfg) + } + _, err = UseServerAccount("web", "nope") + if err == nil { + t.Errorf("an account that isn't there was put in use") + } + id := lib(t).server("web").Accounts[0].ID + ok(t)(UseServerAccount("web", id)) + ok(t)(RemoveServerAccount("web", id)) + if s := lib(t).server("web"); len(s.Accounts) != 0 || s.Account != "" { + t.Errorf("not removed: %+v", s) + } + if cfg := read(t, codex); !strings.Contains(cfg, "base-key") || strings.Contains(cfg, "work-key") { + t.Errorf("the account in use removed, the agents keep its key:\n%s", cfg) + } +} + +func TestServerAccountsNotForACommand(t *testing.T) { + sandbox(t) + ok(t)(SaveServer("", Server{Name: "loc", Transport: "stdio", Command: "x", Agents: []string{"codex"}})) + if _, err := AddServerAccount("loc", "a", map[string]string{"Authorization": "x"}); err == nil { + t.Errorf("a command was given an account") + } + if _, err := AddServerAccount("loc", "a", nil); err == nil { + t.Errorf("an account with no header") + } +} + +// A backup or a sync carries no account's key, and brings it back from +// the copy here. +func TestServerAccountKeysAreSecrets(t *testing.T) { + secret := func(k string) bool { return strings.EqualFold(k, "Authorization") } + s := Server{Name: "web", Transport: "http", URL: "https://x.example/mcp", + Accounts: []Account{{ID: "1", Name: "w", Headers: map[string]string{"Authorization": "Bearer sk-secret-123456"}}}} + b := &Bundle{MCP: []*Server{&s}} + b.WithoutSecrets(secret) + if strings.Contains(mustJSON(t, b), "sk-secret-123456") { + t.Errorf("an account's key is carried: %s", mustJSON(t, b)) + } + back := b.WithSecrets(&Bundle{MCP: []*Server{&s}}, secret) + if back.MCP[0].Accounts[0].Headers["Authorization"] != "Bearer sk-secret-123456" { + t.Errorf("not brought back: %s", mustJSON(t, back)) + } +} + +func lib(t *testing.T) *Library { + t.Helper() + l, err := load() + if err != nil { + t.Fatal(err) + } + return l +} diff --git a/internal/library/mcp_check.go b/internal/library/mcp_check.go index 4058ca617..69a7520f4 100644 --- a/internal/library/mcp_check.go +++ b/internal/library/mcp_check.go @@ -805,6 +805,7 @@ func exitHealth(err error, errs *tail) ServerHealth { // remoteHeaders are the server's own headers, with magpie's token when it // is signed in to it: the agents reach it with that too. func remoteHeaders(ctx context.Context, s *Server) (http.Header, *ServerHealth) { + s = s.live() h := http.Header{} headers, unset := expandAll(s.Headers) if len(unset) > 0 { diff --git a/internal/library/mcp_hub.go b/internal/library/mcp_hub.go index 6711980f5..0ed601263 100644 --- a/internal/library/mcp_hub.go +++ b/internal/library/mcp_hub.go @@ -419,10 +419,12 @@ var hubPool = struct { // hubKey is the server as it is run: an edit, or a sign-in since, is // another to start. func hubKey(s *Server) string { - c := *s - c.Agents, c.DisabledTools = nil, nil + c := *s.live() + c.Agents, c.DisabledTools, c.Accounts, c.Account = nil, nil, nil, "" b, _ := json.Marshal(c) - return fmt.Sprintf("%s|%v", b, s.Transport == "http" && mcpauth.SignedIn(s.Name, s.URL)) + // the sign-in in use too: another account is another to start + in := s.Transport == "http" && mcpauth.SignedIn(s.Name, s.URL) + return fmt.Sprintf("%s|%v|%s", b, in, map[bool]string{true: mcpauth.InUse(s.Name)}[in]) } func backendOf(s *Server) *backend { diff --git a/internal/library/mcp_rename_test.go b/internal/library/mcp_rename_test.go index b08bd7c17..4918e77cf 100644 --- a/internal/library/mcp_rename_test.go +++ b/internal/library/mcp_rename_test.go @@ -4,6 +4,7 @@ import ( "bytes" "os" "path/filepath" + "reflect" "testing" "github.com/yetone/magpie/internal/gateway" @@ -66,7 +67,7 @@ func TestSaveServerRenameKeepsOAuth(t *testing.T) { } assertRecord := func(name string, want mcpauth.Record) { t.Helper() - if got, found := mcpauth.Get(name); !found || got != want { + if got, found := mcpauth.Get(name); !found || !reflect.DeepEqual(got, want) { t.Errorf("OAuth record for %s changed: found=%v got=%+v want=%+v", name, found, got, want) } if token, err := mcpauth.Token(t.Context(), name); err != nil || token != want.Access { diff --git a/internal/library/mcp_rename_windows_test.go b/internal/library/mcp_rename_windows_test.go index 672d8c518..6294ac2be 100644 --- a/internal/library/mcp_rename_windows_test.go +++ b/internal/library/mcp_rename_windows_test.go @@ -6,6 +6,7 @@ import ( "bytes" "os" "path/filepath" + "reflect" "testing" "github.com/yetone/magpie/internal/mcpauth" @@ -68,7 +69,7 @@ func TestSaveServerRenameSignInWriteFailure(t *testing.T) { t.Errorf("file changed after failed sign-in rename: %s", p) } } - if got, found := mcpauth.Get("alpha"); !found || got != before { + if got, found := mcpauth.Get("alpha"); !found || !reflect.DeepEqual(got, before) { t.Errorf("failed rename changed the old sign-in: found=%v record=%+v", found, got) } if _, found := mcpauth.Get("gamma"); found { diff --git a/internal/library/mcp_signin.go b/internal/library/mcp_signin.go index a530f7592..81b89ab11 100644 --- a/internal/library/mcp_signin.go +++ b/internal/library/mcp_signin.go @@ -48,6 +48,7 @@ func relaysAny() bool { // given it. Only a streamable HTTP server is relayed: an SSE one's stream // names the address to post to, which would have to be rewritten. func through(s *Server, base string) *Server { + s = s.live() if s.Plugin != "" { // a plugin's tools, which the gateway serves itself c := *s @@ -99,6 +100,10 @@ var errNotHTTP = errors.New("magpie signs in only to a server reached over strea // SignInServer starts signing magpie in to the library's server called // name: the State's URL is the page to open in a browser. func SignInServer(ctx context.Context, name string) (mcpauth.State, error) { + return signInServer(ctx, name, nil) +} + +func signInServer(ctx context.Context, name string, label *string) (mcpauth.State, error) { mu.Lock() l, err := load() mu.Unlock() @@ -116,6 +121,9 @@ func SignInServer(ctx context.Context, name string) (mcpauth.State, error) { if s.OAuth != nil { app = &mcpauth.App{ClientID: s.OAuth.ClientID, ClientSecret: s.OAuth.ClientSecret, CallbackPort: s.OAuth.CallbackPort} } + if label != nil { + return mcpauth.StartAccount(ctx, s.Name, s.URL, app, *label) + } return mcpauth.StartWith(ctx, s.Name, s.URL, app) } diff --git a/internal/library/sync.go b/internal/library/sync.go index b29ea2623..402759f9a 100644 --- a/internal/library/sync.go +++ b/internal/library/sync.go @@ -812,6 +812,11 @@ func SaveServer(old string, s Server) (*Result, error) { if s.DisabledTools == nil { s.DisabledTools = l.MCP[i].DisabledTools } + // so do the accounts, which have calls of their own + if s.Accounts == nil && s.Account == "" { + s.Accounts, s.Account = l.MCP[i].Accounts, l.MCP[i].Account + _ = s.checkAccounts() + } // a plugin's server stays the plugin's, and on this computer if p := l.MCP[i].Plugin; p != "" && s.Plugin == "" { s.Plugin, s.Local = p, true diff --git a/internal/mcpauth/accounts_test.go b/internal/mcpauth/accounts_test.go new file mode 100644 index 000000000..e393fdb53 --- /dev/null +++ b/internal/mcpauth/accounts_test.go @@ -0,0 +1,125 @@ +package mcpauth_test + +import ( + "context" + "slices" + "testing" + + "github.com/yetone/magpie/internal/mcpauth" + "github.com/yetone/magpie/internal/mcpauth/mcpauthtest" +) + +func accountLabels(name string) []string { + var out []string + for _, a := range mcpauth.Accounts(name) { + l := a.Label + if a.Active { + l += "*" + } + out = append(out, l) + } + return out +} + +// A second sign-in to a server joins the first and is the one in use; the +// first is kept, and switching back gives its token again, with every +// reader (Get, Token) seeing only the account in use. +func TestAccountsSwitchInPlace(t *testing.T) { + home(t) + f := mcpauthtest.New(t) + f.SignIn(t, "neon") + first, _ := mcpauth.Get("neon") + if st := mcpauth.StatusOf("neon", f.URL); len(st.Accounts) != 0 { + t.Fatalf("one sign-in lists accounts: %+v", st.Accounts) + } + mcpauthtest.SignInAccount(t, "neon", f.URL, "work") + mcpauthtest.SignInAccount(t, "neon", f.URL, "side") + if got := accountLabels("neon"); !slices.Equal(got, []string{"", "work", "side*"}) { + t.Fatalf("accounts = %q", got) + } + cur, _ := mcpauth.Get("neon") + if cur.Access == first.Access { + t.Fatal("the new sign-in is not in use") + } + if err := mcpauth.Use("neon", "1"); err != nil { + t.Fatal(err) + } + // the list keeps its places; only the one in use moves + if got := accountLabels("neon"); !slices.Equal(got, []string{"*", "work", "side"}) { + t.Fatalf("after Use: %q", got) + } + tok, err := mcpauth.Token(context.Background(), "neon") + if err != nil || tok != first.Access { + t.Fatalf("Token = %q, %v; want the first account's %q", tok, err, first.Access) + } + if err := mcpauth.Use("neon", "nope"); err != mcpauth.ErrNoAccount { + t.Errorf("Use of no account: %v", err) + } +} + +// Signing in again (a sign-in that ran out) replaces the account in use and +// leaves the others and its place in the list. +func TestSignInAgainKeepsTheOtherAccounts(t *testing.T) { + home(t) + f := mcpauthtest.New(t) + f.SignIn(t, "neon") + mcpauthtest.SignInAccount(t, "neon", f.URL, "work") + before, _ := mcpauth.Get("neon") + f.SignIn(t, "neon") + after, _ := mcpauth.Get("neon") + if after.Access == before.Access { + t.Fatal("not signed in again") + } + if got := accountLabels("neon"); !slices.Equal(got, []string{"", "work*"}) { + t.Fatalf("accounts = %q", got) + } +} + +func TestRemoveAccount(t *testing.T) { + home(t) + f := mcpauthtest.New(t) + f.SignIn(t, "neon") + mcpauthtest.SignInAccount(t, "neon", f.URL, "work") + mcpauthtest.SignInAccount(t, "neon", f.URL, "side") + // the one in use goes: the first of the others is put in use + if err := mcpauth.RemoveAccount("neon", "3"); err != nil { + t.Fatal(err) + } + if got := accountLabels("neon"); !slices.Equal(got, []string{"*", "work"}) { + t.Fatalf("accounts = %q", got) + } + // another goes: the one in use stays + if err := mcpauth.RemoveAccount("neon", "2"); err != nil { + t.Fatal(err) + } + if got := accountLabels("neon"); !slices.Equal(got, []string{"*"}) { + t.Fatalf("accounts = %q", got) + } + if err := mcpauth.RemoveAccount("neon", "1"); err != nil || mcpauth.SignedIn("neon", f.URL) { + t.Fatalf("the last one: %v, signed in %v", err, mcpauth.SignedIn("neon", f.URL)) + } + if err := mcpauth.RemoveAccount("neon", "1"); err != mcpauth.ErrNoAccount { + t.Errorf("no account: %v", err) + } +} + +// A name an account has is not given to another, and the sign-ins go with a +// renamed server and out with a signed-out one. +func TestAccountsFollowTheServer(t *testing.T) { + home(t) + f := mcpauthtest.New(t) + mcpauthtest.SignInAccount(t, "neon", f.URL, "work") + if _, err := mcpauth.StartAccount(context.Background(), "neon", f.URL, nil, " WORK "); err != mcpauth.ErrLabelUsed { + t.Fatalf("a used label: %v", err) + } + mcpauthtest.SignInAccount(t, "neon", f.URL, "side") + if err := mcpauth.Rename("neon", "lime"); err != nil { + t.Fatal(err) + } + if got := accountLabels("lime"); !slices.Equal(got, []string{"work", "side*"}) { + t.Fatalf("renamed: %q", got) + } + if err := mcpauth.SignOut("lime"); err != nil || len(mcpauth.Accounts("lime")) != 0 { + t.Fatalf("sign-out leaves %v (%v)", mcpauth.Accounts("lime"), err) + } +} diff --git a/internal/mcpauth/mcpauth.go b/internal/mcpauth/mcpauth.go index c26b0731c..3c81a8adf 100644 --- a/internal/mcpauth/mcpauth.go +++ b/internal/mcpauth/mcpauth.go @@ -32,6 +32,8 @@ import ( "net/url" "os" "path/filepath" + "slices" + "strconv" "strings" "sync" "time" @@ -118,6 +120,18 @@ type Record struct { // Dead is a sign-in the server refused to renew: the page asks for it // again Dead bool `json:"dead,omitempty"` + + // More than one sign-in to a server (Elorynth on X: several accounts, + // one in use). This record is always the one in use, so every reader of + // a server's sign-in (the gateway's relay, the check, a renewal) reads + // the account in use without knowing there are others; the others wait + // in Spare, and a switch swaps them. Seq keeps each account's place in + // the list, which a swap doesn't move. A sign-in made before accounts + // has none of these: it is account 1, with no label. + ID string `json:"id,omitempty"` + Label string `json:"label,omitempty"` + Seq int `json:"seq,omitempty"` + Spare []*Record `json:"spare,omitempty"` } // fileMu is held for a change to mcp-signins.json read afresh under it, @@ -200,7 +214,9 @@ func Get(name string) (Record, bool) { if r == nil { return Record{}, false } - return *r, true + c := *r + c.Spare = nil + return c, true } // SignedIn says whether magpie holds a sign-in to the server by that name @@ -217,6 +233,8 @@ type Status struct { SignedIn bool `json:"signedIn"` Dead bool `json:"dead,omitempty"` At int64 `json:"at,omitempty"` + // Accounts are the sign-ins, when there is more than one + Accounts []Account `json:"accounts,omitempty"` } // StatusOf is the sign-in to the server by that name at that URL. @@ -225,7 +243,11 @@ func StatusOf(name, serverURL string) Status { if !ok || r.URL != serverURL { return Status{} } - return Status{SignedIn: true, Dead: r.Dead, At: r.At} + st := Status{SignedIn: true, Dead: r.Dead, At: r.At} + if l := Accounts(name); len(l) > 1 { + st.Accounts = l + } + return st } // SignOut forgets magpie's sign-in to the server. @@ -252,6 +274,157 @@ func Forget(name string) error { }) } +// Account is one of a server's sign-ins, as the page lists it. +type Account struct { + ID string `json:"id"` + Label string `json:"label,omitempty"` // "" for one made before labels + Active bool `json:"active,omitempty"` + Dead bool `json:"dead,omitempty"` + At int64 `json:"at,omitempty"` +} + +var ( + // ErrNoAccount is an account the server has no sign-in for. + ErrNoAccount = errors.New("magpie has no such sign-in to this server") + // ErrLabelUsed is a label another sign-in to the server has. + ErrLabelUsed = errors.New("another sign-in to this server has that name") +) + +// the record's id and place, which a sign-in made before accounts lacks +func idOf(r *Record) string { + if r.ID == "" { + return "1" + } + return r.ID +} + +func seqOf(r *Record) int { + if r.Seq == 0 { + return 1 + } + return r.Seq +} + +// all is the record with its spares, in the order they were signed in. +func all(r *Record) []*Record { + a := *r + a.Spare = nil + out := append([]*Record{&a}, r.Spare...) + slices.SortStableFunc(out, func(x, y *Record) int { return seqOf(x) - seqOf(y) }) + return out +} + +// Accounts are the sign-ins to the server by that name, in the order they +// were made; none when magpie isn't signed in to it. +func Accounts(name string) []Account { + fileMu.Lock() + defer fileMu.Unlock() + r := load()[name] + if r == nil { + return nil + } + var out []Account + for _, x := range all(r) { + out = append(out, Account{ID: idOf(x), Label: x.Label, Active: x == nil || idOf(x) == idOf(r), Dead: x.Dead, At: x.At}) + } + return out +} + +// InUse is the id of the sign-in in use, "" when there is none. +func InUse(name string) string { + for _, a := range Accounts(name) { + if a.Active { + return a.ID + } + } + return "" +} + +// Use puts the sign-in by that id in use: what the gateway sends the +// server, and the check, from the next request on. The agents are told +// through Changed as for a new sign-in. +func Use(name, id string) error { + found := false + err := update(func(m map[string]*Record) bool { + cur := m[name] + if cur == nil { + return false + } + if idOf(cur) == id { + found = true + return false + } + i := slices.IndexFunc(cur.Spare, func(x *Record) bool { return idOf(x) == id }) + if i < 0 { + return false + } + found = true + was := *cur + was.ID, was.Seq, was.Spare = idOf(cur), seqOf(cur), nil + next := *cur.Spare[i] + next.ID, next.Seq = idOf(&next), seqOf(&next) + rest := slices.Clone(cur.Spare) + rest[i] = &was + next.Spare = rest + m[name] = &next + return true + }) + if err != nil { + return err + } + if !found { + return ErrNoAccount + } + if Changed != nil { + Changed(name) + } + return nil +} + +// RemoveAccount forgets one sign-in to the server. The one in use going +// puts the first of the others in use; the last going is a sign-out. +func RemoveAccount(name, id string) error { + found := false + err := update(func(m map[string]*Record) bool { + cur := m[name] + if cur == nil { + return false + } + l := all(cur) + i := slices.IndexFunc(l, func(x *Record) bool { return idOf(x) == id }) + if i < 0 { + return false + } + found = true + active := idOf(cur) + l = slices.Delete(l, i, i+1) + if len(l) == 0 { + delete(m, name) + return true + } + // the one in use stays, unless it is the one removed + next := 0 + if id != active { + next = slices.IndexFunc(l, func(x *Record) bool { return idOf(x) == active }) + } + n := *l[next] + n.ID, n.Seq = idOf(&n), seqOf(&n) + n.Spare = slices.Delete(slices.Clone(l), next, next+1) + m[name] = &n + return true + }) + if err != nil { + return err + } + if !found { + return ErrNoAccount + } + if Changed != nil { + Changed(name) + } + return nil +} + // Rename moves a sign-in to the server's new name. func Rename(old, name string) error { return update(func(m map[string]*Record) bool { @@ -829,6 +1002,28 @@ func Start(ctx context.Context, name, serverURL string) (State, error) { // StartWith is Start as app when there is one, which magpie then doesn't // register in its place. func StartWith(ctx context.Context, name, serverURL string, app *App) (State, error) { + return start(ctx, name, serverURL, app, nil) +} + +// StartAccount is StartWith as another account of the server: the sign-in +// it makes is added to the ones there are and put in use, with the label, +// and the others are kept. With no sign-in yet it is the first. +func StartAccount(ctx context.Context, name, serverURL string, app *App, label string) (State, error) { + label = strings.TrimSpace(label) + if len([]rune(label)) > 60 { + return State{}, errors.New("the name of a sign-in is at most 60 characters") + } + if label != "" { + for _, a := range Accounts(name) { + if strings.EqualFold(a.Label, label) { + return State{}, ErrLabelUsed + } + } + } + return start(ctx, name, serverURL, app, &label) +} + +func start(ctx context.Context, name, serverURL string, app *App, add *string) (State, error) { ctx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() m, err := discover(ctx, serverURL) @@ -930,7 +1125,7 @@ func StartWith(ctx context.Context, name, serverURL string, app *App) (State, er if t.Scope != "" { r2.Scope = t.Scope } - if err := f.keep(name, r2); err != nil { + if err := f.keep(name, r2, add); err != nil { page(w, http.StatusOK, "Magpie couldn't keep the sign-in: "+err.Error()) return } @@ -960,13 +1155,13 @@ func (f *flow) status() State { // keep commits the callback only while the flow is still live. Cancel or // timeout and the write take the same lock, so a late token cannot save a // sign-in the user already ended, or replace their previous sign-in. -func (f *flow) keep(name string, r Record) error { +func (f *flow) keep(name string, r Record, add *string) error { f.mu.Lock() if f.finished { f.mu.Unlock() return errors.New("the sign-in has ended; start it again") } - err := update(func(m map[string]*Record) bool { m[name] = &r; return true }) + err := update(func(m map[string]*Record) bool { m[name] = signedAs(m[name], r, add); return true }) f.finished = true f.mu.Unlock() if err != nil { @@ -982,6 +1177,31 @@ func (f *flow) keep(name string, r Record) error { return nil } +// signedAs is the record a new sign-in leaves for the server: an added +// account joins the ones there are, in use; any other replaces the one in +// use (signing in again), and the other accounts stay. +func signedAs(old *Record, r Record, add *string) *Record { + if old == nil || old.URL != r.URL { + if add != nil { + r.Label = *add + } + return &r + } + if add == nil { + r.ID, r.Label, r.Seq, r.Spare = old.ID, old.Label, old.Seq, old.Spare + return &r + } + l := all(old) + top := 0 + for _, x := range l { + top = max(top, seqOf(x)) + x.ID, x.Seq = idOf(x), seqOf(x) + } + r.Seq, r.ID, r.Label = top+1, strconv.Itoa(top+1), *add + r.Spare = l + return &r +} + func (f *flow) finish(st State) { f.mu.Lock() if f.finished { diff --git a/internal/mcpauth/mcpauthtest/fake.go b/internal/mcpauth/mcpauthtest/fake.go index 02be77635..6dfe2c87f 100644 --- a/internal/mcpauth/mcpauthtest/fake.go +++ b/internal/mcpauth/mcpauthtest/fake.go @@ -321,6 +321,19 @@ func (f *Fake) SignIn(t *testing.T, name string) mcpauth.State { func SignIn(t *testing.T, name, u string) mcpauth.State { t.Helper() st, err := mcpauth.Start(t.Context(), name, u) + return finishSignIn(t, st, err) +} + +// SignInAccount signs magpie in to the server at u as name as another +// account, labelled, standing in for the browser. +func SignInAccount(t *testing.T, name, u, label string) mcpauth.State { + t.Helper() + st, err := mcpauth.StartAccount(t.Context(), name, u, nil, label) + return finishSignIn(t, st, err) +} + +func finishSignIn(t *testing.T, st mcpauth.State, err error) mcpauth.State { + t.Helper() if err != nil { t.Fatal(err) }