library: an MCP server signed in to in Claude Code, in WSL too, says so instead of "needs sign-in" (CyberCaius on Discord)
CyberCaius signed in to a remote MCP server with Claude Code's /mcp in
WSL, and the Library still said 需要登录. The check connects as magpie,
without the agent's tokens, so an OAuth server answers it 401, and magpie
read no agent's own sign-in anywhere: not on Windows, not in a distro.
The check now reads each Claude Code target's .credentials.json, beside
the settings.json the target already has (readOwnSignIns,
mcp_agent_signin.go). A distro's Claude Code is a target under the
distro's home (wslTargetOf), so its file is read there through
\\wsl.localhost with no new setting. An mcpOAuth entry of the server's
name and URL with an access or refresh token, as Claude Code 2.1.310
counts one, names the agent in ServerHealth.AgentSignIn; the row says
"signed in in Claude Code (Ubuntu)" with the ok dot, and the tooltip says
magpie can't list its tools without signing in itself. An entry without
a token, another URL by the same name, and a file that can't be read or
parsed name nobody, so the row stays "needs sign-in". The tokens are
never sent or kept. A stopped distro has no target and isn't started.
On a Mac only the file is read, never the Keychain. The sign-ins are part
of the check's cache key, so a sign-in in the agent since isn't answered
from the session's earlier check. Strings in zh, zh-TW, ja and de.
Run:
- TestCheckNamesAgentsSignedInThemselves (internal/library): agent.FakeWSL
forces the Windows+WSL switch (Ubuntu running, its home a temp root),
sandbox HOME/USERPROFILE/XDG_CONFIG_HOME, CLAUDE_CONFIG_DIR cleared, a
real httptest server answering 401 with WWW-Authenticate.
- Broken by hand, each red with a FAIL naming the behavior:
- the old behavior (the reader names nobody): reading only this
computer's Claude folder (claudeDir()) instead of the target's:
"signed in in claude@wsl:Ubuntu, the check says {State:auth ...
AgentSignIn:[]}".
- counting an entry with no token: "a sign-in with no token counted".
- leaving the sign-ins out of healthKey: "signed in on both sides, the
check says ... AgentSignIn:[claude@wsl:Ubuntu]" (stale cache).
- library-mcp-health-wsl.test.cjs, chromium and webkit, en/zh/zh-TW/ja/de:
red on the old client.js (expected "signed in in Claude Code (Ubuntu)",
got "needs sign-in"), 12 of 12 after.
- gofmt -l (nothing); go vet on darwin, GOOS=linux -tags nogui and
GOOS=windows for ./internal/library ./internal/gui; go build darwin,
GOOS=windows and GOOS=linux -tags nogui ./...; go test -tags nogui
-count=1 -timeout 45m ./internal/library ./internal/gui: ok (187s, 63s).
- GUI: library-mcp-health, library-mcp-health-wsl, mcp-signin-health,
mcp-signin, mcp-oauth-app, library-mcp-tools, library-mcp-tool-switch,
library-mcp-unshown, library-items, i18n-keys, gui-zh-tw, gui-ja,
gui-de: 161 of 161 pass.
These ran first at a base before origin/main 1f589e3f4, then again at
this head (on 1f589e3f4): vet, builds, internal/library ok (149s), the 13
GUI files 161 of 161. internal/gui is red at this head on
TestCoreScriptBudget alone: app.js is 1321476 bytes, over 1321336. It is
the same on origin/main 1f589e3f4, from 2a8a17746 (this change doesn't
touch app.js, and its size is main's); #3367. The budget isn't raised.
Claude Code's file format was read from its 2.1.310 binary (td's key,
the token save's serverName/serverUrl/accessToken/refreshToken, $Ci's
"neither token is no sign-in").
Not tried: a real /mcp sign-in in Claude Code in WSL on the Windows box
(ssh to 10.0.0.132 timed out), and the full ./... suite. Not covered:
Codex's own MCP sign-ins (keyring, or a .credentials.json fallback whose
format wasn't checked against its source), #3508.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -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);
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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 := *s
|
||||
c.Name, c.Agents = "", nil
|
||||
b, _ := 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.Mutex
|
||||
var wg sync.WaitGroup
|
||||
slots := 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]S
|
||||
defer 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 := remoteStep
|
||||
if 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
|
||||
}
|
||||
|
||||
|
||||
@@ -180,7 +180,7 @@ func TestCheckMixedServerEachSide(t *testing.T) {
|
||||
// the agents moving from here into WSL is a check of its own
|
||||
a, b := *s, *s
|
||||
a.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")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user