diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index cbf418c64..97eab2b6b 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -17,7 +17,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it. | Targets | `Targets` lists the detected agents (`agent.Detected`), plus apps like Claude Desktop, with where each keeps its instructions file (and an `Override` it reads instead), its MCP file and its skills folder. An agent in a running WSL distro has its places under the distro's home (`wslTargetOf`): Claude Code, Codex, Pi and OmO each by its own rule, and every agent that keeps all of them in its own folder (Hermes Agent, omp, OpenCode, Droid and the rest of `ownFolder`, #1323) by the same rule as on this machine, its MCP file marked as WSL's so a Windows program isn't given to it. An agent a plugin adds (`a.Plugin`) has the places its plugin's `agent.library` names (`pluginTarget`): an instructions file, an MCP file in one of `agentplug.MCPFormats` (each the `mcpFormat` of the agent it is named for, `pluginMCP`) and a skills folder, `~` and `$VAR` expanded as its config is; one that names none is no target. Before, a plugin's agent got models and keys only. | [`targets.go`](../../internal/library/targets.go) | | 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) | | 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). | [`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 library.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 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 `http://127.0.0.1:/callback`: GitHub, as RFC 8252 asks, takes any port on a loopback callback registered without one, and a fixed `callbackPort` is for a vendor that doesn't. Claude Code's callback says `localhost`, so an app made for it needs its callback URL changed. 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 library.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 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). 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) | | Skills | A skill is a folder with a `SKILL.md`. It comes from GitHub, from a folder on this machine (linked, so editing the folder edits the skill) or from the market. 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. | [`skills.go`](../../internal/library/skills.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) | diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index fbd2dca24..697d073f7 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1774,7 +1774,7 @@ const I18N = { "Client secret": "客户端密钥", "Callback port": "回调端口", "Made with its vendor (GitHub's under Settings › Developer settings › OAuth Apps), with {url} as its callback URL": "在服务方创建(GitHub 的在 Settings › Developer settings › OAuth Apps),回调 URL 填 {url}", - "the server's sign-in doesn't let an app register itself (no dynamic client registration), so magpie signs in to it only as an OAuth app of your own: make one with the server's vendor (GitHub's under Settings › Developer settings › OAuth Apps), with http://127.0.0.1/callback as its callback URL, then give its client ID and secret under \"OAuth app\" in the server's editor": "该服务器的登录不允许应用自行注册(不支持动态客户端注册),因此 magpie 只能以你自己的 OAuth 应用登录:在服务方创建一个(GitHub 的在 Settings › Developer settings › OAuth Apps),回调 URL 填 http://127.0.0.1/callback,再在该服务器编辑器的「OAuth 应用」中填入它的客户端 ID 和密钥", + "the server's sign-in doesn't let an app register itself (no dynamic client registration), so magpie signs in to it only as an OAuth app of your own: make one with the server's vendor (GitHub's under Settings › Developer settings › OAuth Apps), with http://localhost/callback as its callback URL, then give its client ID and secret under \"OAuth app\" in the server's editor": "该服务器的登录不允许应用自行注册(不支持动态客户端注册),因此 magpie 只能以你自己的 OAuth 应用登录:在服务方创建一个(GitHub 的在 Settings › Developer settings › OAuth Apps),回调 URL 填 http://localhost/callback,再在该服务器编辑器的「OAuth 应用」中填入它的客户端 ID 和密钥", "Sign-in required": "需要重新登录", "GitHub refused this Copilot sign-in; sign in again": "GitHub 拒绝了这个 Copilot 登录,请重新登录", "The vendor revoked this sign-in; sign in again": "服务商已撤销这个登录,请重新登录", @@ -6259,7 +6259,7 @@ const I18N = { "Client secret": "用戶端密鑰", "Callback port": "回呼連接埠", "Made with its vendor (GitHub's under Settings › Developer settings › OAuth Apps), with {url} as its callback URL": "在服務方建立(GitHub 的在 Settings › Developer settings › OAuth Apps),回呼 URL 填 {url}", - "the server's sign-in doesn't let an app register itself (no dynamic client registration), so magpie signs in to it only as an OAuth app of your own: make one with the server's vendor (GitHub's under Settings › Developer settings › OAuth Apps), with http://127.0.0.1/callback as its callback URL, then give its client ID and secret under \"OAuth app\" in the server's editor": "該伺服器的登入不允許應用程式自行註冊(不支援動態用戶端註冊),因此 magpie 只能以你自己的 OAuth 應用程式登入:在服務方建立一個(GitHub 的在 Settings › Developer settings › OAuth Apps),回呼 URL 填 http://127.0.0.1/callback,再在該伺服器編輯器的「OAuth 應用程式」中填入它的用戶端 ID 和密鑰", + "the server's sign-in doesn't let an app register itself (no dynamic client registration), so magpie signs in to it only as an OAuth app of your own: make one with the server's vendor (GitHub's under Settings › Developer settings › OAuth Apps), with http://localhost/callback as its callback URL, then give its client ID and secret under \"OAuth app\" in the server's editor": "該伺服器的登入不允許應用程式自行註冊(不支援動態用戶端註冊),因此 magpie 只能以你自己的 OAuth 應用程式登入:在服務方建立一個(GitHub 的在 Settings › Developer settings › OAuth Apps),回呼 URL 填 http://localhost/callback,再在該伺服器編輯器的「OAuth 應用程式」中填入它的用戶端 ID 和密鑰", "Sign-in required": "需要重新登入", "GitHub refused this Copilot sign-in; sign in again": "GitHub 拒絕了這個 Copilot 登入,請重新登入", "The vendor revoked this sign-in; sign in again": "服務商已撤銷這個登入,請重新登入", @@ -10720,7 +10720,7 @@ const I18N = { "Client secret": "クライアントシークレット", "Callback port": "コールバックポート", "Made with its vendor (GitHub's under Settings › Developer settings › OAuth Apps), with {url} as its callback URL": "提供元で作成し(GitHub は Settings › Developer settings › OAuth Apps)、コールバック URL に {url} を指定します", - "the server's sign-in doesn't let an app register itself (no dynamic client registration), so magpie signs in to it only as an OAuth app of your own: make one with the server's vendor (GitHub's under Settings › Developer settings › OAuth Apps), with http://127.0.0.1/callback as its callback URL, then give its client ID and secret under \"OAuth app\" in the server's editor": "このサーバーのサインインはアプリの自己登録(動的クライアント登録)を受け付けないため、magpie は自分で用意した OAuth アプリとしてのみサインインできます。提供元でアプリを作成し(GitHub は Settings › Developer settings › OAuth Apps)、コールバック URL に http://127.0.0.1/callback を指定してから、サーバーの編集画面の「OAuth アプリ」にクライアント ID とシークレットを入力してください", + "the server's sign-in doesn't let an app register itself (no dynamic client registration), so magpie signs in to it only as an OAuth app of your own: make one with the server's vendor (GitHub's under Settings › Developer settings › OAuth Apps), with http://localhost/callback as its callback URL, then give its client ID and secret under \"OAuth app\" in the server's editor": "このサーバーのサインインはアプリの自己登録(動的クライアント登録)を受け付けないため、magpie は自分で用意した OAuth アプリとしてのみサインインできます。提供元でアプリを作成し(GitHub は Settings › Developer settings › OAuth Apps)、コールバック URL に http://localhost/callback を指定してから、サーバーの編集画面の「OAuth アプリ」にクライアント ID とシークレットを入力してください", "Sign-in required": "サインインが必要です", "GitHub refused this Copilot sign-in; sign in again": "GitHub がこの Copilot のサインインを拒否しました。再度サインインしてください", "The vendor revoked this sign-in; sign in again": "ベンダーがこのサインインを取り消しました。再度サインインしてください", @@ -15200,7 +15200,7 @@ const I18N = { "Client secret": "Client-Secret", "Callback port": "Callback-Port", "Made with its vendor (GitHub's under Settings › Developer settings › OAuth Apps), with {url} as its callback URL": "Beim Anbieter angelegt (bei GitHub unter Settings › Developer settings › OAuth Apps), mit {url} als Callback-URL", - "the server's sign-in doesn't let an app register itself (no dynamic client registration), so magpie signs in to it only as an OAuth app of your own: make one with the server's vendor (GitHub's under Settings › Developer settings › OAuth Apps), with http://127.0.0.1/callback as its callback URL, then give its client ID and secret under \"OAuth app\" in the server's editor": "die Anmeldung dieses Servers lässt keine App sich selbst registrieren (keine dynamische Client-Registrierung), daher meldet sich magpie nur als eigene OAuth-App an: Lege beim Anbieter eine an (bei GitHub unter Settings › Developer settings › OAuth Apps) mit http://127.0.0.1/callback als Callback-URL und trage ihre Client-ID und ihr Secret unter „OAuth-App“ im Editor des Servers ein", + "the server's sign-in doesn't let an app register itself (no dynamic client registration), so magpie signs in to it only as an OAuth app of your own: make one with the server's vendor (GitHub's under Settings › Developer settings › OAuth Apps), with http://localhost/callback as its callback URL, then give its client ID and secret under \"OAuth app\" in the server's editor": "die Anmeldung dieses Servers lässt keine App sich selbst registrieren (keine dynamische Client-Registrierung), daher meldet sich magpie nur als eigene OAuth-App an: Lege beim Anbieter eine an (bei GitHub unter Settings › Developer settings › OAuth Apps) mit http://localhost/callback als Callback-URL und trage ihre Client-ID und ihr Secret unter „OAuth-App“ im Editor des Servers ein", "Sign-in required": "Anmeldung erforderlich", "GitHub refused this Copilot sign-in; sign in again": "GitHub hat diese Copilot-Anmeldung abgelehnt; bitte erneut anmelden", "The vendor revoked this sign-in; sign in again": "Der Anbieter hat diese Anmeldung widerrufen; bitte erneut anmelden", diff --git a/internal/gui/assets/library.js b/internal/gui/assets/library.js index 900308ab5..073694c19 100644 --- a/internal/gui/assets/library.js +++ b/internal/gui/assets/library.js @@ -1889,7 +1889,7 @@ appBox.append(id, secret, port, x); if (hint) hint.textContent = callback(); } - const callback = () => t("Made with its vendor (GitHub's under Settings › Developer settings › OAuth Apps), with {url} as its callback URL", { url: "http://127.0.0.1" + (d.oauth?.callbackPort ? ":" + d.oauth.callbackPort : "") + "/callback" }); + const callback = () => t("Made with its vendor (GitHub's under Settings › Developer settings › OAuth Apps), with {url} as its callback URL", { url: "http://localhost" + (d.oauth?.callbackPort ? ":" + d.oauth.callbackPort : "") + "/callback" }); const name = field2(d.name, t("e.g. github"), (v) => { d.name = v.trim(); signBox?.redraw(); }); ed.append(...field(t("Name"), name, t("Letters, digits, - and _ — what the agents call it"))); const kindOf = () => segs([["stdio", t("Command")], ["http", "HTTP"], ["sse", "SSE"]], d.transport, (v) => { d.transport = v; draw(); }); diff --git a/internal/gui/tests/mcp-oauth-app.test.cjs b/internal/gui/tests/mcp-oauth-app.test.cjs index ad4aa12a9..9ab6805fc 100644 --- a/internal/gui/tests/mcp-oauth-app.test.cjs +++ b/internal/gui/tests/mcp-oauth-app.test.cjs @@ -23,7 +23,7 @@ const agent = (id, name) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skill const GH = "https://api.githubcopilot.com/mcp/"; const ID = "Ov23liAbCdEfGhIjKlMn", SECRET = "0123456789abcdef0123456789abcdef01234567"; // mcpauth.ErrNoRegistration, as the backend says it -const NO_REG = "the server's sign-in doesn't let an app register itself (no dynamic client registration), so magpie signs in to it only as an OAuth app of your own: make one with the server's vendor (GitHub's under Settings › Developer settings › OAuth Apps), with http://127.0.0.1/callback as its callback URL, then give its client ID and secret under \"OAuth app\" in the server's editor"; +const NO_REG = "the server's sign-in doesn't let an app register itself (no dynamic client registration), so magpie signs in to it only as an OAuth app of your own: make one with the server's vendor (GitHub's under Settings › Developer settings › OAuth Apps), with http://localhost/callback as its callback URL, then give its client ID and secret under \"OAuth app\" in the server's editor"; function server(lang, calls) { const lib = { @@ -113,7 +113,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await box.locator(".lib-signin-err", { hasText: w(NO_REG) }).waitFor(); await input("Client ID").waitFor(); assert.equal(await page.evaluate(() => document.activeElement?.getAttribute("aria-label")), w("Client ID")); - await hint("http://127.0.0.1/callback").waitFor(); + await hint("http://localhost/callback").waitFor(); // typed but not saved: Cancel asks, and nothing is saved await input("Client ID").fill(ID); @@ -129,7 +129,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.equal(await input("Client secret").getAttribute("type"), "password"); await input("Callback port").pressSequentially("31a18"); assert.equal(await input("Callback port").inputValue(), "3118"); - await hint("http://127.0.0.1:3118/callback").waitFor(); + await hint("http://localhost:3118/callback").waitFor(); await box.getByRole("button", { name: w("Save and sign in"), exact: true }).click(); await box.getByRole("button", { name: w("Cancel"), exact: true }).click(); await box.getByRole("button", { name: w("Sign in"), exact: true }).waitFor(); diff --git a/internal/library/mcp.go b/internal/library/mcp.go index a612895de..c90627001 100644 --- a/internal/library/mcp.go +++ b/internal/library/mcp.go @@ -55,7 +55,7 @@ type OAuthApp struct { ClientID string `json:"clientId"` ClientSecret string `json:"clientSecret,omitempty"` // CallbackPort is the port of the callback URL the app was made with; - // 0 for one made with http://127.0.0.1/callback, which takes any + // 0 for one made with http://localhost/callback, which takes any CallbackPort int `json:"callbackPort,omitempty"` } diff --git a/internal/mcpauth/github_app_test.go b/internal/mcpauth/github_app_test.go index f9a754d52..6049814a5 100644 --- a/internal/mcpauth/github_app_test.go +++ b/internal/mcpauth/github_app_test.go @@ -30,6 +30,10 @@ type gitHub struct { id, secret string // the user's OAuth app refresh bool // tokens that run out, with a refresh token (a GitHub App's) + // exact is the app's one callback URL when the server matches it + // exactly, port and host too, as many do; empty, a loopback callback + // takes any port, as GitHub's does + exact string mu sync.Mutex codes map[string]string // code → its PKCE challenge @@ -72,9 +76,13 @@ func newGitHub(t *testing.T, id, secret string) *gitHub { mux.HandleFunc("/login/oauth/authorize", func(w http.ResponseWriter, r *http.Request) { q := r.URL.Query() back, err := url.Parse(q.Get("redirect_uri")) - // a loopback callback URL registered as http://127.0.0.1/callback - // takes any port - if q.Get("client_id") != g.id || err != nil || back.Hostname() != "127.0.0.1" || back.Path != "/callback" || q.Get("code_challenge_method") != "S256" { + // a loopback callback URL registered as http://localhost/callback + // takes any port; an exact one takes only itself + loopback := err == nil && (back.Hostname() == "localhost" || back.Hostname() == "127.0.0.1") && back.Path == "/callback" + if g.exact != "" { + loopback = q.Get("redirect_uri") == g.exact + } + if q.Get("client_id") != g.id || !loopback || q.Get("code_challenge_method") != "S256" { http.Error(w, "The redirect_uri is not associated with this application.", http.StatusBadRequest) return } @@ -114,7 +122,7 @@ func newGitHub(t *testing.T, id, secret string) *gitHub { challenge, ok := g.codes[r.PostForm.Get("code")] delete(g.codes, r.PostForm.Get("code")) sum := sha256.Sum256([]byte(r.PostForm.Get("code_verifier"))) - if !ok || base64.RawURLEncoding.EncodeToString(sum[:]) != challenge { + if !ok || base64.RawURLEncoding.EncodeToString(sum[:]) != challenge || (g.exact != "" && r.PostForm.Get("redirect_uri") != g.exact) { io.WriteString(w, `{"error":"bad_verification_code","error_description":"The code passed is incorrect or expired.","error_uri":"https://docs.github.com/apps/managing-oauth-apps/troubleshooting-oauth-app-access-token-request-errors/#bad-verification-code"}`) return } @@ -170,7 +178,7 @@ func TestGitHubWithoutAnApp(t *testing.T) { if !errors.Is(err, mcpauth.ErrNoRegistration) { t.Fatalf("err = %v", err) } - for _, s := range []string{"OAuth app of your own", "http://127.0.0.1/callback", "client ID"} { + for _, s := range []string{"OAuth app of your own", "http://localhost/callback", "client ID"} { if !strings.Contains(err.Error(), s) { t.Errorf("the error doesn't say %q: %v", s, err) } @@ -178,7 +186,7 @@ func TestGitHubWithoutAnApp(t *testing.T) { } // With the user's app, magpie registers nothing: it signs in as that app, -// called back at 127.0.0.1's /callback, and gives the secret in the form, +// called back at localhost's /callback as Claude Code is, and gives the secret in the form, // as GitHub's token endpoint takes it. The record keeps the app, to renew // as it. func TestGitHubSignInAsTheUsersApp(t *testing.T) { @@ -199,7 +207,7 @@ func TestGitHubSignInAsTheUsersApp(t *testing.T) { if f.Get("client_id") != id || f.Get("client_secret") != secret || f.Get("grant_type") != "authorization_code" { t.Errorf("token request = %v", f) } - if u, _ := url.Parse(g.redirect()); u.Hostname() != "127.0.0.1" || u.Path != "/callback" || u.Port() == "" { + if u, _ := url.Parse(g.redirect()); u.Hostname() != "localhost" || u.Path != "/callback" || u.Port() == "" { t.Errorf("redirect_uri = %s", g.redirect()) } } @@ -238,11 +246,37 @@ func TestGitHubCallbackPort(t *testing.T) { if st := signInAs(t, "github", g.URL, &mcpauth.App{ClientID: id, ClientSecret: secret, CallbackPort: port}); st.State != "done" { t.Fatalf("sign-in %s: %s", st.State, st.Error) } - if want := fmt.Sprintf("http://127.0.0.1:%d/callback", port); g.redirect() != want { + if want := fmt.Sprintf("http://localhost:%d/callback", port); g.redirect() != want { t.Errorf("redirect_uri = %s, want %s", g.redirect(), want) } } +// An app made for Claude Code signs magpie in as it is. Claude Code calls +// a pre-configured client back at http://localhost:/callback +// (code.claude.com/docs/en/mcp, "Use pre-configured OAuth credentials"; +// its 2.1.296 builds it as `http://localhost:${port}/callback` and listens +// on 127.0.0.1), and a server that matches the registered URL exactly +// refuses any other host: Claude Code's own 2.1.229 sent 127.0.0.1 and was +// refused, until 2.1.231 went back to localhost. +func TestAppMadeForClaudeCode(t *testing.T) { + home(t) + id, secret := "Ov23liAbCdEfGhIjKlMn", "0123456789abcdef0123456789abcdef01234567" + g := newGitHub(t, id, secret) + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + port := ln.Addr().(*net.TCPAddr).Port + ln.Close() + g.exact = fmt.Sprintf("http://localhost:%d/callback", port) + if st := signInAs(t, "github", g.URL, &mcpauth.App{ClientID: id, ClientSecret: secret, CallbackPort: port}); st.State != "done" { + t.Fatalf("sign-in %s: %s (registered %s)", st.State, st.Error, g.exact) + } + if f := g.lastForm(); f.Get("redirect_uri") != g.exact { + t.Errorf("token request's redirect_uri = %s", f.Get("redirect_uri")) + } +} + // A refresh token GitHub won't take again (its 200 bad_refresh_token) runs // the sign-in out, as invalid_grant does elsewhere. func TestGitHubBadRefreshToken(t *testing.T) { diff --git a/internal/mcpauth/mcpauth.go b/internal/mcpauth/mcpauth.go index 047fbc4e9..5c4ec94e2 100644 --- a/internal/mcpauth/mcpauth.go +++ b/internal/mcpauth/mcpauth.go @@ -88,7 +88,7 @@ var ErrClientRefused = errors.New("this server's sign-in admits only the apps it // OAuth app of the user's own, made with the server's vendor, as Claude // Code does with --client-id. The page opens the server's fields for one // on it. -var ErrNoRegistration = errors.New("the server's sign-in doesn't let an app register itself (no dynamic client registration), so magpie signs in to it only as an OAuth app of your own: make one with the server's vendor (GitHub's under Settings › Developer settings › OAuth Apps), with http://127.0.0.1/callback as its callback URL, then give its client ID and secret under \"OAuth app\" in the server's editor") +var ErrNoRegistration = errors.New("the server's sign-in doesn't let an app register itself (no dynamic client registration), so magpie signs in to it only as an OAuth app of your own: make one with the server's vendor (GitHub's under Settings › Developer settings › OAuth Apps), with http://localhost/callback as its callback URL, then give its client ID and secret under \"OAuth app\" in the server's editor") // Record is magpie's sign-in to one server. type Record struct { @@ -778,9 +778,12 @@ func randomToken(n int) string { // App is an OAuth app of the user's own, for a server whose sign-in // doesn't let magpie register itself: Claude Code's --client-id, -// --client-secret and --callback-port. Without a CallbackPort the -// callback comes to any free port of 127.0.0.1, which a loopback callback -// URL registered without one takes (GitHub's, RFC 8252). +// --client-secret and --callback-port. Its callback is Claude Code's, +// http://localhost:/callback, so an app made for Claude Code signs +// magpie in as it is; the callback is still listened for on 127.0.0.1 +// alone, as Claude Code does. Without a CallbackPort the port is any free +// one, which a loopback callback URL registered without one takes +// (GitHub's, RFC 8252). type App struct { ClientID string ClientSecret string @@ -814,7 +817,15 @@ func StartWith(ctx context.Context, name, serverURL string, app *App) (State, er } return State{}, err } - redirect := fmt.Sprintf("http://127.0.0.1:%d/callback", ln.Addr().(*net.TCPAddr).Port) + // magpie's own registration names 127.0.0.1, as RFC 8252 asks; an + // app of the user's own is called back as Claude Code calls it back, + // at localhost (its v2.1.231 went back to localhost because servers + // that match the registered URL exactly refused 127.0.0.1). + host := "127.0.0.1" + if app != nil { + host = "localhost" + } + redirect := fmt.Sprintf("http://%s:%d/callback", host, ln.Addr().(*net.TCPAddr).Port) var id, secret, method string if app != nil { id, secret, method = app.ClientID, app.ClientSecret, appMethod(m, app.ClientSecret)