library: an MCP server signed in to in Codex itself says so instead of "needs sign-in" (#3508)

A server signed in to with `codex mcp login` was still "needs sign-in"
in the Library. Codex keeps those tokens in its keyring, or in a
.credentials.json of CODEX_HOME when its config's
mcp_oauth_credentials_store is file or the keyring is missing, and the
check read no such file.

It now reads it for each Codex target, beside the config.toml the
target already has, a distro's too (codexCredentialsOf, readCodex in
mcp_agent_signin.go). The file holds an entry per server under the key
codex-rs's compute_store_key makes of its name and a 16 hex of the
hash of its config, each entry naming its server and URL with the
tokens flattened into it (its FallbackTokenEntry, read from codex-rs's
rmcp-client/src/oauth.rs — not the StoredOAuthTokens of the login's
memory the report guessed at). An entry of the server's name and URL
with an access or refresh token names Codex in
ServerHealth.AgentSignIn, and the row says "signed in in Codex"
instead of "needs sign-in". An entry with neither token, one of the
executor's (executor_owned: codex answers no host's lookup with it),
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 keyring itself is
never read. A stopped distro has no target and isn't started. The
sign-ins are already part of the check's cache key, and the page names
any agent's id in the row, so mcp_check.go and the GUI needed nothing.

Run:
- TestCheckNamesCodexSignedInItself (internal/library): agent.FakeWSL
  forces the Windows+WSL switch (Ubuntu running, its home a temp root),
  sandbox HOME/USERPROFILE, CODEX_HOME 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): codexCredentialsOf
    returns "": "signed in in codex@wsl:Ubuntu, the check says
    {State:auth ... AgentSignIn:[]}".
  - counting an executor's entry: "only the executor's sign-in
    counted".
  - counting an entry with no token: "a sign-in with no token counted".
- gofmt -l (nothing); go vet on darwin, GOOS=linux -tags nogui and
  GOOS=windows for ./internal/library; go build darwin, GOOS=windows
  and GOOS=linux -tags nogui ./...; go test -tags nogui -count=1
  ./internal/library: ok (71s); the two sign-in tests also with -race:
  ok.

Codex's file format was read from codex-rs's source (rmcp-client/src/
oauth.rs, oauth/resolved_store.rs, core/src/config/mod.rs).

Not tried: a real `codex mcp login` (no .credentials.json on this
machine, whose Codex keeps its MCP tokens in the keyring, which is
never read); the test's file is built from codex-rs's writer
(save_oauth_tokens_to_file, its FallbackTokenEntry), and the WSL
distro's file is a temp root behind a FakeWSL probe.

Generated-by: GLM-5.3-Flash (ZCode)
This commit is contained in:
ggbdpq
2026-11-01 16:43:21 +08:00
committed by yetone
parent ec03bca72e
commit 655d23f790
3 changed files with 192 additions and 29 deletions
File diff suppressed because one or more lines are too long
+92 -28
View File
@@ -9,11 +9,14 @@ import (
)
// 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.
// does, and keeps the tokens in its own .credentials.json; `codex mcp
// login` does, keeping them in its keyring or, when its config's
// mcp_oauth_credentials_store is file or the keyring is missing, in a
// .credentials.json of its own. 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, from the files alone: the keyrings are never read.
//
// 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
@@ -62,36 +65,45 @@ func claudeCredentialsOf(t *Target) string {
return filepath.Join(filepath.Dir(t.Settings), ".credentials.json")
}
// codexCredentials is the part of Codex's .credentials.json that holds its
// MCP sign-ins: an entry per server, under the key codex-rs's
// compute_store_key makes of its name and a 16 hex of the hash of its
// config, each entry naming its server and URL with the tokens flattened
// into it (codex-rs's rmcp-client/src/oauth.rs, its FallbackTokenEntry —
// the file holds those, not the StoredOAuthTokens of the login's memory).
// An entry with neither token is a sign-in started and not finished, and
// one of the executor's (executor_owned) is no `codex mcp login`: codex
// itself answers no host's lookup with either.
type codexCredentials map[string]struct {
ServerName string `json:"server_name"`
ServerURL string `json:"server_url"`
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
ExecutorOwned bool `json:"executor_owned"`
}
// codexCredentialsOf is Codex's .credentials.json for t, beside the
// config.toml the target already has (in CODEX_HOME, a WSL distro's for
// one there), where codex-rs's own read of the file is; "" for any other
// agent.
func codexCredentialsOf(t *Target) string {
if id, _, _ := strings.Cut(t.Agent.ID, "@"); id != "codex" || t.MCP == nil || t.MCP.Path == "" {
return ""
}
return filepath.Join(filepath.Dir(t.MCP.Path), ".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
if p := claudeCredentialsOf(t); p != "" {
out.readClaude(t.Agent.ID, p)
}
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)
}
if p := codexCredentialsOf(t); p != "" {
out.readCodex(t.Agent.ID, p)
}
}
for _, ids := range out {
@@ -99,3 +111,55 @@ func readOwnSignIns() ownSignIns {
}
return out
}
// add names agent as signed in to a server called name at url.
func (o ownSignIns) add(agent, name, url string) {
key := signInKey(name, url)
if !slices.Contains(o[key], agent) {
o[key] = append(o[key], agent)
}
}
// readClaude adds the sign-ins of the Claude Code whose credentials are at
// p: its mcpOAuth entries, the key's prefix naming the server when the
// entry itself doesn't.
func (o ownSignIns) readClaude(agent, p string) {
b, err := os.ReadFile(p)
if err != nil {
return
}
var c claudeCredentials
if json.Unmarshal(b, &c) != nil {
return
}
for k, e := range c.MCPOAuth {
if e.AccessToken == "" && e.RefreshToken == "" || e.ServerURL == "" {
continue
}
name := e.ServerName
if name == "" {
name, _, _ = strings.Cut(k, "|")
}
o.add(agent, name, e.ServerURL)
}
}
// readCodex adds the sign-ins of the Codex whose credentials are at p: its
// file fallback's entries, each naming its server itself; the executor's
// say nothing of a `codex mcp login`.
func (o ownSignIns) readCodex(agent, p string) {
b, err := os.ReadFile(p)
if err != nil {
return
}
var c codexCredentials
if json.Unmarshal(b, &c) != nil {
return
}
for _, e := range c {
if e.AccessToken == "" && e.RefreshToken == "" || e.ServerURL == "" || e.ExecutorOwned {
continue
}
o.add(agent, e.ServerName, e.ServerURL)
}
}
+99
View File
@@ -101,3 +101,102 @@ func TestCheckNamesAgentsSignedInThemselves(t *testing.T) {
t.Fatalf("no agent signed in to this URL, unreadable credentials: %+v", l)
}
}
// codexOwnSignIn is Codex's .credentials.json after `codex mcp login` kept
// the tokens in the file, as codex-rs's rmcp-client writes it
// (FallbackTokenEntry in oauth.rs): an entry under the key its
// compute_store_key makes of the name and a 16-hex hash of the server's
// config, the tokens flattened into it; a second, unfinished sign-in (no
// token) that codex itself doesn't answer a lookup with.
func codexOwnSignIn(name, url string) string {
return `{
"` + name + `|0123456789abcdef":{"server_name":"` + name + `","server_url":"` + url + `","client_id":"c","access_token":"tok","refresh_token":"ref","expires_at":1893456000000,"scopes":["mcp"]},
"half|fedcba9876543210":{"server_name":"half","server_url":"` + url + `/half","client_id":"c","access_token":""}
}`
}
// codexOwnSignInExecutor is one entry of the executor's own, which codex
// never answers a host lookup with.
func codexOwnSignInExecutor(name, url string) string {
return `{"` + name + `:0123456789abcdef":{"server_name":"` + name + `","server_url":"` + url + `","client_id":"c","access_token":"tok","executor_owned":true}}`
}
// A remote server signed in to in Codex itself (`codex mcp login`) was
// "needs sign-in" in the Library, as magpie's check connects without the
// agent's tokens. The check reads the file codex-rs falls back to when
// mcp_oauth_credentials_store is file or the keyring is missing, beside
// the config.toml the target already has, a distro's too, and names the
// agents signed in; the keyring itself is never read, the executor's
// entries are not a `codex mcp login`, and a file that can't be read or
// parsed names nobody.
func TestCheckNamesCodexSignedInItself(t *testing.T) {
h := sandbox(t)
// every variable the reader's places come from: Codex's folder here,
// and the distro's, which only its probe says
t.Setenv("CODEX_HOME", "")
checked.Lock()
checked.m = map[string]checkedServer{}
checked.Unlock()
root := t.TempDir()
// the distro's Codex, its home \\wsl.localhost\Ubuntu\home\me
write(t, filepath.Join(root, "home", "me", ".codex", "config.toml"), "model = \"gpt-5.5\"\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:.codex\nnet:mirrored\n",
}, map[string]string{"Ubuntu": root}))
const wsl = "codex@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"
ok(t)(SaveServer("", Server{Name: "linear", Transport: "http", URL: url, Agents: []string{"codex", 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 Codex only
write(t, filepath.Join(root, "home", "me", ".codex", ".credentials.json"), codexOwnSignIn("linear", url))
got := check()
if l := got["linear"]; l.State != "auth" || !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 Codex too; a page opened again (not a fresh
// check) isn't given the answer from before it
write(t, filepath.Join(h, ".codex", ".credentials.json"), codexOwnSignIn("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{"codex", wsl}) {
t.Fatalf("signed in on both sides, the check says %+v", l)
}
// the executor's entry isn't a `codex mcp login`, and a file that
// can't be read or parsed names nobody
write(t, filepath.Join(root, "home", "me", ".codex", ".credentials.json"), codexOwnSignInExecutor("linear", url))
write(t, filepath.Join(h, ".codex", ".credentials.json"), "{not json")
if l := check()["linear"]; l.State != "auth" || len(l.AgentSignIn) != 0 {
t.Fatalf("only the executor's sign-in counted, unreadable credentials: %+v", l)
}
}