Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
library: an MCP server signed in to in Claude Code, in WSL too, says so instead of "needs sign-in" (CyberCaius on Discord)
yetone14b10f116671
diff --git a/docs/subsystems/library.md b/docs/subsystems/library.mdindex 08dbee14d..fb818641a 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. `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). 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 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_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. `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). 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) || 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`), 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`) go first, marked official: `magpie-quota`, in [magpie-community/plugins](https://github.com/magpie-community/plugins/tree/main/skills/magpie-quota), lets an agent read `magpie quota --json` and wait with `magpie quota wait`. 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) |@@ -76,11 +76,11 @@ agents RTK, a CLI that cuts shell output down before the model reads it.## Verification```sh-go test -tags nogui ./internal/library -run 'TestGit|TestInstallFromGitRepo|TestReadLooksAtEachFolderOnce|TestLinkChangedBetweenVisitsShows|TestUnreadablePartIsLookedAtAgain|TestCheckSkillsFindsNewOnes|TestNewBase|TestUpdateKeeps|TestCheckDue|TestCheckSkillsMarksItDone|TestTargets|TestServer|TestImportServer|TestCheck|TestInstructions|TestInstructionsSetLinkedToAgentsFile|TestInstructionSets|TestTakesAlma|TestAlma|TestLinkedSet|TestLinkRefused|TestSkill|TestRemoveFoundSkill|TestInstallSet|TestInstallLists|TestEverySkillAgents|TestEveryServerAgents|TestSomeServersAgents|TestRemoveServers|TestRTK|TestEnvRefs|TestDshRefRoundTrip|TestDshImportKeepsJS|TestAgentMCPFiles|TestCodeBuddyMCPFile|TestZedMCP|TestOwnServerFromElsewhereRunsThisMagpie|TestUsersOwnServerStaysAsItIs|TestCarriedOwnServerIsEachComputersMagpie|TestCarry|TestPageReadDoesntReadUnchangedSkillsAgain|TestJustWrittenSkillIsReadAgain|TestUnreadableSkillIsntRememberedAsDifferent|TestGlanceLeavesOutTheAgentsSkills|TestPluginAgent|TestPluginMCPFormatsAreWritten|TestToolsOff|TestOffList|TestHooks|TestSubagent|TestCheckRenewsMagpiesSignIn|TestCheckWSLOnlyServerInItsDistro|TestCheckWindowsServerHere|TestCheckMixedServerEachSide|TestCheckSaysSignInRanOut|TestSignInAsTheUsersOwnApp|TestOAuthAppChecked|TestOAuthAppSecretCarried|TestGoneAgentListedToTakeOut|TestUpdateFindsSkillsRemovedUpstream|TestGoneFromNeedsTheSourceRead'+go test -tags nogui ./internal/library -run 'TestGit|TestInstallFromGitRepo|TestReadLooksAtEachFolderOnce|TestLinkChangedBetweenVisitsShows|TestUnreadablePartIsLookedAtAgain|TestCheckSkillsFindsNewOnes|TestNewBase|TestUpdateKeeps|TestCheckDue|TestCheckSkillsMarksItDone|TestTargets|TestServer|TestImportServer|TestCheck|TestInstructions|TestInstructionsSetLinkedToAgentsFile|TestInstructionSets|TestTakesAlma|TestAlma|TestLinkedSet|TestLinkRefused|TestSkill|TestRemoveFoundSkill|TestInstallSet|TestInstallLists|TestEverySkillAgents|TestEveryServerAgents|TestSomeServersAgents|TestRemoveServers|TestRTK|TestEnvRefs|TestDshRefRoundTrip|TestDshImportKeepsJS|TestAgentMCPFiles|TestCodeBuddyMCPFile|TestZedMCP|TestOwnServerFromElsewhereRunsThisMagpie|TestUsersOwnServerStaysAsItIs|TestCarriedOwnServerIsEachComputersMagpie|TestCarry|TestPageReadDoesntReadUnchangedSkillsAgain|TestJustWrittenSkillIsReadAgain|TestUnreadableSkillIsntRememberedAsDifferent|TestGlanceLeavesOutTheAgentsSkills|TestPluginAgent|TestPluginMCPFormatsAreWritten|TestToolsOff|TestOffList|TestHooks|TestSubagent|TestCheckRenewsMagpiesSignIn|TestCheckWSLOnlyServerInItsDistro|TestCheckWindowsServerHere|TestCheckMixedServerEachSide|TestCheckSaysSignInRanOut|TestCheckNamesAgentsSignedInThemselves|TestSignInAsTheUsersOwnApp|TestOAuthAppChecked|TestOAuthAppSecretCarried|TestGoneAgentListedToTakeOut|TestUpdateFindsSkillsRemovedUpstream|TestGoneFromNeedsTheSourceRead'go test -tags nogui ./internal/cli -run 'TestLibrarySkillRm'go test -race ./internal/mcpauthgo test -tags nogui ./internal/library-node --test internal/gui/tests/library-items.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-mcp-health.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/library-items.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-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 thediff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.jsindex 9fc562ba2..a0fd4bc22 100644--- a/internal/gui/assets/plugins/library/client.js+++ b/internal/gui/assets/plugins/library/client.js@@ -1738,6 +1738,14 @@ magpie.plugin("library", (ctx) => {}function healthWords(h, s) {if (h.state === "ok") return [h.tools === 1 ? t("1 tool") : t("{n} tools", { n: h.tools }), t("It started and listed its tools")];+ // an agent signed in to it on its own (Claude Code's /mcp, in WSL too)+ // uses it, though magpie's check, without that sign-in, was asked for+ // one: the row says who, not "needs sign-in" (CyberCaius on Discord)+ if (h.state === "auth" && h.agentSignIn?.length) {+ const names = h.agentSignIn.map(nameOf);+ const text = t("signed in in {agent}", { agent: names[0] }) + (names.length > 1 ? " +" + (names.length - 1) : "");+ return [text, t("{agents}: signed in to it on its own, and uses it. magpie's check doesn't have that sign-in, so it can't list the tools: open it to sign in once in magpie too", { agents: names.join(", ") })];+ }if (h.state === "auth") {const why = h.oauth? (s?.transport === "http" ? t("The server asks for a sign-in — open it to sign in once in magpie") : t("The server asks for a sign-in"))@@ -1806,7 +1814,7 @@ magpie.plugin("library", (ctx) => {// agent's own launch sets says nothing of the server, so it isn't// painted as broken (#2308, ASD-max: Codex's host-only codex_app,// whose pipe Codex itself hands it)- b.className = "lib-health " + (e.h.state === "ok" ? "ok" : e.h.state === "auth" ? "auth" : e.h.why === "novar" || e.h.why === "wsldown" ? "unknown" : "err");+ b.className = "lib-health " + (e.h.state === "ok" || e.h.agentSignIn?.length ? "ok" : e.h.state === "auth" ? "auth" : e.h.why === "novar" || e.h.why === "wsldown" ? "unknown" : "err");b.replaceChildren(el("span", "", text));if (toolList(b.dataset.server).length) {const open = toolsOpen.has(b.dataset.server);diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.jsindex b958c5d51..42aa949cc 100644--- a/internal/gui/assets/plugins/library/i18n.js+++ b/internal/gui/assets/plugins/library/i18n.js@@ -56,6 +56,8 @@ magpie.strings({"The agents given it use magpie's sign-in": "分配到它的 agent 都用 magpie 的登录","{n} tools": "{n} 个工具","It started and listed its tools": "已启动并列出了它的工具",+ "signed in in {agent}": "已在 {agent} 登录",+ "{agents}: signed in to it on its own, and uses it. magpie's check doesn't have that sign-in, so it can't list the tools: open it to sign in once in magpie too": "{agents}:已自行登录并在使用。magpie 的检查没有这份登录,所以列不出工具:打开它,也在 magpie 中登录一次即可","The server asks for a sign-in — open it to sign in once in magpie": "服务器要求登录:打开它,在 magpie 中登录一次","The server asks for a sign-in": "服务器要求登录","The server refused magpie (HTTP {code}) — a key in its headers may be missing or wrong": "服务器拒绝了 magpie(HTTP {code})— Headers 里的密钥可能缺失或有误",@@ -684,6 +686,8 @@ magpie.strings({"The agents given it use magpie's sign-in": "分配到它的 agent 都用 magpie 的登入","{n} tools": "{n} 個工具","It started and listed its tools": "已啟動並列出了它的工具",+ "signed in in {agent}": "已在 {agent} 登入",+ "{agents}: signed in to it on its own, and uses it. magpie's check doesn't have that sign-in, so it can't list the tools: open it to sign in once in magpie too": "{agents}:已自行登入並在使用。magpie 的檢查沒有這份登入,所以列不出工具:開啟它,也在 magpie 中登入一次即可","The server asks for a sign-in — open it to sign in once in magpie": "伺服器要求登入:開啟它,在 magpie 中登入一次","The server asks for a sign-in": "伺服器要求登入","The server refused magpie (HTTP {code}) — a key in its headers may be missing or wrong": "伺服器拒絕了 magpie(HTTP {code})— Headers 裡的金鑰可能缺失或有誤",@@ -1307,6 +1311,8 @@ magpie.strings({"The agents given it use magpie's sign-in": "割り当てられたエージェントは magpie のサインインを使います","{n} tools": "{n} 個のツール","It started and listed its tools": "起動してツールを一覧表示しました",+ "signed in in {agent}": "{agent} でサインイン済み",+ "{agents}: signed in to it on its own, and uses it. magpie's check doesn't have that sign-in, so it can't list the tools: open it to sign in once in magpie too": "{agents}: 自身でサインインして使っています。magpie のチェックはそのサインインを持たないため、ツールを一覧できません。開いて magpie でも一度サインインしてください","The server asks for a sign-in — open it to sign in once in magpie": "サーバーがサインインを求めています。開いて magpie で一度サインインしてください","The server asks for a sign-in": "サーバーがサインインを求めています","The server refused magpie (HTTP {code}) — a key in its headers may be missing or wrong": "サーバーが magpie を拒否しました(HTTP {code})。ヘッダーのキーが不足しているか誤っている可能性があります",@@ -1933,6 +1939,8 @@ magpie.strings({"The agents given it use magpie's sign-in": "Die zugewiesenen Agenten nutzen die Anmeldung von magpie","{n} tools": "{n} Tools","It started and listed its tools": "Gestartet, Tools aufgelistet",+ "signed in in {agent}": "in {agent} angemeldet",+ "{agents}: signed in to it on its own, and uses it. magpie's check doesn't have that sign-in, so it can't list the tools: open it to sign in once in magpie too": "{agents}: selbst angemeldet und nutzt ihn. Die Prüfung von magpie hat diese Anmeldung nicht und kann die Werkzeuge daher nicht auflisten: Öffnen Sie ihn, um sich auch einmal in magpie anzumelden","The server asks for a sign-in — open it to sign in once in magpie": "Der Server verlangt eine Anmeldung — öffnen Sie ihn, um sich einmal in magpie anzumelden","The server asks for a sign-in": "Der Server verlangt eine Anmeldung","The server refused magpie (HTTP {code}) — a key in its headers may be missing or wrong": "Der Server hat magpie abgelehnt (HTTP {code}) — ein Schlüssel in seinen Headern fehlt möglicherweise oder ist falsch",diff --git a/internal/gui/tests/library-mcp-health-wsl.test.cjs b/internal/gui/tests/library-mcp-health-wsl.test.cjsindex d7913d4cc..e3080c7b9 100644--- a/internal/gui/tests/library-mcp-health-wsl.test.cjs+++ b/internal/gui/tests/library-mcp-health-wsl.test.cjs@@ -4,7 +4,9 @@// while his agents started it fine). The row's tooltip says where it was// checked; a failure names the place that failed on the row itself; a// distro that isn't running, which a check doesn't start, is said to be-// unknown, not broken. In every language, in both engines. No backend:+// unknown, not broken. A remote server signed in to in Claude Code in WSL+// itself says so, not "needs sign-in" (CyberCaius on Discord), and one no+// agent signed in to still needs it. 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");@@ -26,6 +28,8 @@ const fixture = () => ({{ name: "both", transport: "stdio", command: "npx", args: ["x-mcp"], agents: ["claude", WSL] },{ name: "down", transport: "stdio", command: "node", args: ["/home/loong/tools/y.js"], agents: ["claude@wsl:Arch"] },{ name: "here", transport: "stdio", command: "npx", args: ["h-mcp"], agents: ["claude"] },+ { name: "signed", transport: "http", url: "https://mcp.linear.app/mcp", agents: ["claude", WSL] },+ { name: "unsigned", transport: "http", url: "https://mcp.notion.com/mcp", agents: ["claude", WSL] },],});const found = {@@ -33,6 +37,8 @@ const found = {both: { state: "error", why: "exited", code: 1, detail: "Node.js v24.9.0", checked: ["", "Ubuntu"] },down: { state: "error", why: "wsldown", detail: "Arch" },here: { state: "ok", tools: 3 },+ signed: { state: "auth", code: 401, oauth: true, agentSignIn: [WSL] },+ unsigned: { state: "auth", code: 401, oauth: true },};function server(lang) {@@ -58,11 +64,11 @@ function server(lang) {}const words = {- en: { checked: "Checked in: ", failed: "Failed in: ", down: "WSL Arch not running", downTip: "magpie can't check it: the agents given it run in WSL Arch, which isn't running, and a check doesn't start it" },- zh: { checked: "检查位置:", failed: "失败位置:", down: "WSL Arch 未运行", downTip: "magpie 无法检查:用它的智能体运行在 WSL Arch 里,而它没有在运行,检查不会去启动它" },- "zh-TW": { checked: "檢查位置:", failed: "失敗位置:", down: "WSL Arch 未執行", downTip: "magpie 無法檢查:使用它的智慧體執行在 WSL Arch 裡,而它沒有在執行,檢查不會去啟動它" },- ja: { checked: "チェックした場所: ", failed: "失敗した場所: ", down: "WSL Arch は停止中", downTip: "magpie はチェックできません: これを使うエージェントが動く WSL Arch は起動しておらず、チェックのために起動はしません" },- de: { checked: "Geprüft in: ", failed: "Fehlgeschlagen in: ", down: "WSL Arch läuft nicht", downTip: "magpie kann ihn nicht prüfen: Die Agenten, die ihn bekommen, laufen in WSL Arch, das nicht läuft, und eine Prüfung startet es nicht" },+ en: { signed: "signed in in Claude Code (Ubuntu)", needs: "needs sign-in", checked: "Checked in: ", failed: "Failed in: ", down: "WSL Arch not running", downTip: "magpie can't check it: the agents given it run in WSL Arch, which isn't running, and a check doesn't start it" },+ zh: { signed: "已在 Claude Code (Ubuntu) 登录", needs: "需要登录", checked: "检查位置:", failed: "失败位置:", down: "WSL Arch 未运行", downTip: "magpie 无法检查:用它的智能体运行在 WSL Arch 里,而它没有在运行,检查不会去启动它" },+ "zh-TW": { signed: "已在 Claude Code (Ubuntu) 登入", needs: "需要登入", checked: "檢查位置:", failed: "失敗位置:", down: "WSL Arch 未執行", downTip: "magpie 無法檢查:使用它的智慧體執行在 WSL Arch 裡,而它沒有在執行,檢查不會去啟動它" },+ ja: { signed: "Claude Code (Ubuntu) でサインイン済み", needs: "サインインが必要", checked: "チェックした場所: ", failed: "失敗した場所: ", down: "WSL Arch は停止中", downTip: "magpie はチェックできません: これを使うエージェントが動く WSL Arch は起動しておらず、チェックのために起動はしません" },+ de: { signed: "in Claude Code (Ubuntu) angemeldet", needs: "Anmeldung nötig", checked: "Geprüft in: ", failed: "Fehlgeschlagen in: ", down: "WSL Arch läuft nicht", downTip: "magpie kann ihn nicht prüfen: Die Agenten, die ihn bekommen, laufen in WSL Arch, das nicht läuft, und eine Prüfung startet es nicht" },};for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {@@ -105,9 +111,18 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",const here = await tip("here");assert.ok(!here.some((l) => l.startsWith(w.checked) || l.startsWith(w.failed)), here.join(" | "));assert.doesNotMatch(await status("here").textContent(), / · /);+ // signed in in WSL's Claude Code: said, and not painted as wanting+ // a sign-in; the tooltip names the agent+ assert.equal(await status("signed").textContent(), w.signed);+ assert.equal(await status("signed").evaluate((b) => b.classList.contains("ok") && !b.classList.contains("auth")), true);+ assert.match((await tip("signed"))[0], /^Claude Code \(Ubuntu\)/);+ assert.equal(await status("unsigned").textContent(), w.needs);+ assert.equal(await status("unsigned").evaluate((b) => b.classList.contains("auth")), true);// one line high still- const box = await status("both").boundingBox();- assert.ok(box.height <= 18, "status wraps: " + box.height);+ for (const n of ["both", "signed"]) {+ const box = await status(n).boundingBox();+ assert.ok(box.height <= 18, n + " status wraps: " + box.height);+ }await ctx.close();});}diff --git a/internal/library/mcp_agent_signin.go b/internal/library/mcp_agent_signin.gonew file mode 100644index 000000000..e7bcb81a5--- /dev/null+++ b/internal/library/mcp_agent_signin.go@@ -0,0 +1,101 @@+package library++import (+ "encoding/json"+ "os"+ "path/filepath"+ "slices"+ "strings"+)++// An agent can sign in to a remote MCP server itself: Claude Code's /mcp+// does, and keeps the tokens in its own .credentials.json. magpie's check+// connects without them, so such a server answers it 401 and its row said+// "needs sign-in" while the agent used it fine (CyberCaius on Discord: the+// server signed in to in Claude Code in WSL). The check says which agents+// hold their own sign-in instead.+//+// Every target is read where it keeps its files, so an agent in a running+// WSL distro is read under the distro's home (wslTargetOf), as its+// settings are; a stopped distro has no target and is never started for+// this. On a Mac Claude Code keeps the tokens in the Keychain, which magpie+// never reads: there only the file, when Claude Code fell back to it.++// ownSignIns are the agents signed in to a server themselves, by+// signInKey of the server's name and URL.+type ownSignIns map[string][]string++func signInKey(name, url string) string {+ return name + "\n" + strings.TrimRight(url, "/")+}++// of are the agents signed in to s on their own; none for a command.+func (o ownSignIns) of(s *Server) []string {+ if s.Transport == "stdio" {+ return nil+ }+ return o[signInKey(s.Name, s.URL)]+}++// claudeCredentials is the part of Claude Code's .credentials.json that+// holds its MCP sign-ins: mcpOAuth, keyed "<server name>|<16 hex of the+// server's type, url and headers>", each entry naming its server and URL+// (Claude Code 2.1.310's td and its token save). An entry with neither+// token is a sign-in started and not finished, which Claude Code itself+// doesn't count as one.+type claudeCredentials struct {+ MCPOAuth map[string]struct {+ ServerName string `json:"serverName"`+ ServerURL string `json:"serverUrl"`+ AccessToken string `json:"accessToken"`+ RefreshToken string `json:"refreshToken"`+ } `json:"mcpOAuth"`+}++// claudeCredentialsOf is Claude Code's .credentials.json for t, beside its+// settings.json (in its config folder, a WSL distro's for one there); ""+// for any other agent.+func claudeCredentialsOf(t *Target) string {+ if id, _, _ := strings.Cut(t.Agent.ID, "@"); id != "claude" || t.Settings == "" {+ return ""+ }+ return filepath.Join(filepath.Dir(t.Settings), ".credentials.json")+}++// readOwnSignIns reads each target's own MCP sign-ins. A file that can't+// be read or parsed says nothing of the agent: it is left out, and the+// check's own answer stands.+func readOwnSignIns() ownSignIns {+ out := ownSignIns{}+ for _, t := range Targets() {+ p := claudeCredentialsOf(t)+ if p == "" {+ continue+ }+ b, err := os.ReadFile(p)+ if err != nil {+ continue+ }+ var c claudeCredentials+ if json.Unmarshal(b, &c) != nil {+ continue+ }+ for k, e := range c.MCPOAuth {+ if e.AccessToken == "" && e.RefreshToken == "" || e.ServerURL == "" {+ continue+ }+ name := e.ServerName+ if name == "" {+ name, _, _ = strings.Cut(k, "|")+ }+ key := signInKey(name, e.ServerURL)+ if !slices.Contains(out[key], t.Agent.ID) {+ out[key] = append(out[key], t.Agent.ID)+ }+ }+ }+ for _, ids := range out {+ slices.Sort(ids)+ }+ return out+}diff --git a/internal/library/mcp_agent_signin_test.go b/internal/library/mcp_agent_signin_test.gonew file mode 100644index 000000000..39e5ec982--- /dev/null+++ b/internal/library/mcp_agent_signin_test.go@@ -0,0 +1,103 @@+package library++import (+ "context"+ "net/http"+ "net/http/httptest"+ "path/filepath"+ "slices"+ "testing"++ "github.com/yetone/magpie/internal/agent"+)++// claudeOwnSignIn is Claude Code's .credentials.json after /mcp signed in+// to name at url, as Claude Code 2.1.310 writes it: under mcpOAuth, keyed+// by the name and a hash of the server's config, beside its own account's+// claudeAiOauth; a second, unfinished sign-in (no token) to another server+// that Claude Code doesn't count.+func claudeOwnSignIn(name, url string) string {+ return `{"claudeAiOauth":{"accessToken":"sk-ant-oat01-x","refreshToken":"sk-ant-ort01-x"},+"mcpOAuth":{+ "` + name + `|0123456789abcdef":{"serverName":"` + name + `","serverUrl":"` + url + `","accessToken":"tok","refreshToken":"ref","expiresAt":1893456000000,"clientId":"c"},+ "half|fedcba9876543210":{"serverName":"half","serverUrl":"` + url + `/half","accessToken":""}+}}`+}++// CyberCaius on Discord: a remote server signed in to in Claude Code in+// WSL was "needs sign-in" in the Library, as magpie's check connects+// without the agent's tokens. The check reads each Claude Code's own+// sign-ins where it keeps them, the WSL distro's home for one there, and+// names the agents signed in; a server no agent signed in to, and a+// sign-in left unfinished, still needs one.+func TestCheckNamesAgentsSignedInThemselves(t *testing.T) {+ h := sandbox(t)+ // every variable the reader's places come from: Claude Code's folder+ // here, and the distro's, which only its probe says+ t.Setenv("CLAUDE_CONFIG_DIR", "")+ checked.Lock()+ checked.m = map[string]checkedServer{}+ checked.Unlock()+ root := t.TempDir()+ // the distro's Claude Code, its home \\wsl.localhost\Ubuntu\home\me+ write(t, filepath.Join(root, "home", "me", ".claude", "settings.json"), "{}\n")+ // a Windows machine running Ubuntu, whatever the OS the test runs on+ t.Cleanup(agent.FakeWSL(map[string]string{+ "Ubuntu": "home:/home/me\ndir:.claude\nnet:mirrored\n",+ }, map[string]string{"Ubuntu": root}))+ const wsl = "claude@wsl:Ubuntu"+ if tg := targetByID(wsl); tg == nil {+ t.Fatalf("%s isn't a target: %v", wsl, ids(Targets()))+ }++ // a server that asks every client without a token to sign in+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("WWW-Authenticate", `Bearer resource_metadata="http://`+r.Host+`/.well-known/oauth-protected-resource"`)+ w.WriteHeader(401)+ }))+ t.Cleanup(srv.Close)+ url := srv.URL + "/mcp"+ write(t, filepath.Join(h, ".claude", "settings.json"), "{}\n")+ ok(t)(SaveServer("", Server{Name: "linear", Transport: "http", URL: url, Agents: []string{"claude", wsl}}))+ ok(t)(SaveServer("", Server{Name: "half", Transport: "http", URL: url + "/half", Agents: []string{wsl}}))++ check := func() map[string]ServerHealth {+ t.Helper()+ got, err := CheckServers(context.Background(), nil, true)+ if err != nil {+ t.Fatal(err)+ }+ return got+ }+ if got := check()["linear"]; got.State != "auth" || len(got.AgentSignIn) != 0 {+ t.Fatalf("no agent signed in yet: %+v", got)+ }++ // signed in in WSL's Claude Code only+ write(t, filepath.Join(root, "home", "me", ".claude", ".credentials.json"), claudeOwnSignIn("linear", url))+ got := check()+ if l := got["linear"]; l.State != "auth" || !l.OAuth || !slices.Equal(l.AgentSignIn, []string{wsl}) {+ t.Fatalf("signed in in %s, the check says %+v", wsl, l)+ }+ if hf := got["half"]; len(hf.AgentSignIn) != 0 {+ t.Fatalf("a sign-in with no token counted: %+v", hf)+ }++ // and in this computer's Claude Code too; a page opened again (not a+ // fresh check) isn't given the answer from before it+ write(t, filepath.Join(h, ".claude", ".credentials.json"), claudeOwnSignIn("linear", url+"/"))+ again, err := CheckServers(context.Background(), []string{"linear"}, false)+ if err != nil {+ t.Fatal(err)+ }+ if l := again["linear"]; !slices.Equal(l.AgentSignIn, []string{"claude", wsl}) {+ t.Fatalf("signed in on both sides, the check says %+v", l)+ }++ // another server's sign-in by the same name isn't this one's+ write(t, filepath.Join(h, ".claude", ".credentials.json"), claudeOwnSignIn("linear", "https://elsewhere.example/mcp"))+ write(t, filepath.Join(root, "home", "me", ".claude", ".credentials.json"), "{not json")+ if l := check()["linear"]; l.State != "auth" || len(l.AgentSignIn) != 0 {+ t.Fatalf("no agent signed in to this URL, unreadable credentials: %+v", l)+ }+}diff --git a/internal/library/mcp_check.go b/internal/library/mcp_check.goindex a99e4c33c..7122612d5 100644--- a/internal/library/mcp_check.go+++ b/internal/library/mcp_check.go@@ -57,6 +57,11 @@ type ServerHealth struct {// left it: one whose renewed token the server refused has run out// since, and the page's tag says so (新v学员 on Discord)SignIn *mcpauth.Status `json:"signIn,omitempty"`+ // AgentSignIn are the agents signed in to a server that refused+ // magpie's check on their own (Claude Code's /mcp, mcp_agent_signin.go),+ // by id: they use it, though the check, without their tokens, was asked+ // to sign in (CyberCaius on Discord)+ AgentSignIn []string `json:"agentSignIn,omitempty"`// Step is what a server that timed out was asked and didn't answer// (initialize, notifications/initialized, tools/list, or connect: an// SSE server's stream), and Waited how long it was waited for, in ms@@ -108,7 +113,7 @@ type checkedServer struct {h ServerHealth}-func healthKey(s *Server) string {+func healthKey(s *Server, own ownSignIns) string {c := *sc.Name, c.Agents = "", nilb, _ := json.Marshal(c)@@ -118,7 +123,9 @@ func healthKey(s *Server) string {if s.Transport == "stdio" {sides = checkSides(s)}- return fmt.Sprintf("%s|%v|%v|%d|%q", b, st.SignedIn, st.Dead, st.At, sides)+ // and the agents signed in to it themselves: one signed in since+ // isn't left as "needs sign-in"+ return fmt.Sprintf("%s|%v|%v|%d|%q|%q", b, st.SignedIn, st.Dead, st.At, sides, own.of(s))}// CheckServers checks the library's servers called names (every one when@@ -141,12 +148,13 @@ func CheckServers(ctx context.Context, names []string, fresh bool) (map[string]S}}}+ own := readOwnSignIns()out := map[string]ServerHealth{}var outMu sync.Mutexvar wg sync.WaitGroupslots := make(chan struct{}, checkAtOnce)for _, s := range list {- key := healthKey(s)+ key := healthKey(s, own)checked.Lock()c, ok := checked.m[s.Name]checked.Unlock()@@ -161,10 +169,10 @@ func CheckServers(ctx context.Context, names []string, fresh bool) (map[string]Sdefer wg.Done()slots <- struct{}{}defer func() { <-slots }()- h := CheckServer(ctx, s)+ h := checkServer(ctx, s, own)// as the server is now: a sign-in the check found run out// isn't one to check it again for- key := healthKey(s)+ key := healthKey(s, own)// a check cut short by the page going away isn't one, and a// server that didn't answer in time is asked again next time:// a slow server may answer then (#1467)@@ -189,6 +197,13 @@ func CheckServers(ctx context.Context, names []string, fresh bool) (map[string]S// CheckServer connects to one server and asks it for its tools.func CheckServer(ctx context.Context, s *Server) ServerHealth {+ return checkServer(ctx, s, nil)+}++// checkServer is CheckServer with the agents' own sign-ins read already,+// once for every server checked together; nil reads them when a server+// asks for a sign-in.+func checkServer(ctx context.Context, s *Server, own ownSignIns) ServerHealth {each := remoteStepif s.Transport == "stdio" {each = stdioStep@@ -214,6 +229,12 @@ func CheckServer(ctx context.Context, s *Server) ServerHealth {h.SignIn = &st}}+ if h.State == "auth" && s.Transport != "stdio" {+ if own == nil {+ own = readOwnSignIns()+ }+ h.AgentSignIn = own.of(s)+ }return h}diff --git a/internal/library/mcp_check_wsl_test.go b/internal/library/mcp_check_wsl_test.goindex bdac935bf..29b4f38a1 100644--- a/internal/library/mcp_check_wsl_test.go+++ b/internal/library/mcp_check_wsl_test.go@@ -180,7 +180,7 @@ func TestCheckMixedServerEachSide(t *testing.T) {// the agents moving from here into WSL is a check of its owna, b := *s, *sa.Agents, b.Agents = []string{"claude"}, []string{"claude@wsl:Ubuntu"}- if healthKey(&a) == healthKey(&b) {+ if healthKey(&a, nil) == healthKey(&b, nil) {t.Fatal("a server moved into WSL keeps its check from Windows")}}