Repository navigation
Description
What version of Codex CLI is running?
codex-cli 0.157.1 (npm), Linux x86_64, KDE/Wayland. Home on persistent ext4. mcp_oauth_credentials_store = "file".
What issue are you seeing?
After every reboot (or closing all Codex sessions), all remote OAuth MCP servers demand reauthentication at startup:
⚠ The <server> MCP server requires OAuth reauthentication. Run `codex mcp login <server>`.
⚠ MCP startup incomplete (failed: stripe-a, stripe-b, stripe-c, supabase-x, supabase-y)
Setup that triggers it: 5 remote OAuth servers — three entries pointing at https://mcp.stripe.com (same login, different connected sub-accounts, so separate grants) and two at https://mcp.supabase.com/mcp?project_ref=<ref> (different projects). Typically ~6 concurrent TUI sessions plus the app-server daemon are running against the shared global credentials store.
Evidence (from ~/.codex/.credentials.json mtimes/expires_at and logs_2.sqlite)
Timeline of the last cycle:
| Event | Time |
|---|---|
codex mcp login all 5 servers |
T0 |
Last successful refresh write to .credentials.json |
T0+24h |
| Stripe access tokens expired (TTL = 1h, supabase = 24h) | T0+24h+1h |
| Machine rebooted | T0+27.5h |
Any subsequent write to .credentials.json |
none |
After the reboot, every startup logs:
WARN codex_rmcp_client::oauth::refresh_transaction|MCP OAuth refresh token was rejected; reauthorization required error=OAuth refresh token was rejected: Server returned error response: invalid_grant: Invalid refresh token
i.e. the on-disk refresh token was already consumed/invalidated server-side, but the newly rotated refresh token never landed on disk. While sessions were running, refresh worked and the file was rewritten regularly — the chain only breaks across process restarts.
Additional observations:
- Long-running sessions that were started before MCP server definitions were renamed kept refreshing under the old server names for days (extra dead-grant churn).
- Supabase servers also intermittently fail refresh with
OAuth token refresh failed: Failed to parse server response(28 occurrences in one day). ~/.codex/mcp-oauth-locks/accumulates lock files but apparently only serializes logins, not refresh write-backs.
Root-cause hypothesis
Stripe/Supabase rotate refresh tokens on every use (single-use). Multiple long-lived Codex processes (TUI sessions, app-server daemon, codex mcp invocations) each hold an in-memory copy of the credentials and can trigger a rotation. When a rotation happens shortly before shutdown/reboot — or a second process refreshes with a stale copy — the write-back of the new refresh token is lost or clobbered, leaving .credentials.json holding a refresh token the provider already invalidated. Every later start then fails with invalid_grant and surfaces the reauthentication warning for all affected servers.
Workaround that fully resolved it for us
- Moved all OAuth MCP server definitions out of the global
~/.codex/config.tomlinto per-project.codex/config.tomlfiles, so only sessions inside a given project load and refresh those servers (server → grant mapping preserved across three projects). - Hygiene: close Codex sessions before rebooting; avoid many concurrent sessions sharing one OAuth server.
- A one-shot
codex-mcp-reloginscript (runs the 5codex mcp logincalls with explicit--scopesfor Supabase) for when the chain does break.
After this change, tokens survive reboots; refreshes are now effectively single-writer per server.
Suggested fixes
- Route all MCP token refreshes through a single writer (e.g. the app-server daemon) with re-read-before-write under the existing file lock, instead of each process refreshing from its in-memory copy.
- Persist the rotated refresh token synchronously before the new access token is used anywhere.
- On
invalid_grant, discard the stored token immediately and surface the re-auth affordance (relates to MCP OAuth: a rejected refresh token stays "usable", so Codex retries it forever and never surfaces re-authentication #39054) instead of leaving a permanently-dead entry that every startup retries.
Activity
mrjw717 commentedon Sep 27, 2026
Follow-up: recurrence without reboot, isolating the mechanism
After the workaround above, all five servers were re-authenticated at T0 (2026-09-26 18:33 UTC). No reboot occurred (host uptime spans the entire window). Overnight:
codex mcp logincompletes (file written).credentials.jsonwritten againinvalid_grant/ "requires OAuth reauthentication"Notable details:
codex_rmcp_client::oauth::refresh_transactionevents were logged for any stripe server in that 24h window, yet the on-disk refresh token was dead by the next morning — so the token was invalidated server-side without a corresponding logged/persisted refresh through the CLI path.mcp.stripe.comat inspection time.Two candidate mechanisms we could not distinguish from outside:
Either way,
.credentials.jsonends up holding a refresh token the provider rejects, and the only recovery is interactivecodex mcp login— which is what makes this so disruptive: every morning, every stripe-backed MCP server is logged out. If (2) is true, a persistable session or longer-lived refresh tokens from the provider side would be needed; if (1) is true, the single-writer/persist-before-use fixes suggested above would resolve it.Happy to run instrumented tests (e.g.,
strace/file-watch on.credentials.jsonwith a scripted stripe tool call) if a maintainer wants to pin down which process, if any, performs the silent rotation.mrjw717 commentedon Sep 28, 2026
Day-2 reproduction: persistence works for young sessions, breaks after long-lived sessions
With the project-scoped config, refresh persistence worked correctly for most of a day, then failed overnight in a reproducible pattern:
Timeline (all UTC)
.credentials.jsonrewritten hourly: 13:0x, 13:3x, 13:5x, 14:1x, 14:39, 14:49).credentials.jsonrefresh_transactionlog events at allAt 02:04, the session (a TUI pane open since Sep 26, i.e. ~36h old) failed with two different error modes:
Key deduction: the last persisted stripe-shipwright rotation was at ~14:39 and was written to disk. For its refresh token to be
invalid_grant11.5h later, something must have consumed a later rotation without logging arefresh_transactionevent and without writing.credentials.json— i.e. a silent in-memory refresh inside a long-lived process (TUI pane and/or the app-server daemon), which orphans the on-disk refresh token. Meanwhile the same flow at 13:00–14:49 persisted correctly, so the write-back path works intermittently — consistent with a race between multiple processes holding cached credential copies.The "Failed to parse server response" mode for Supabase appears to be a separate client-side defect in the refresh path (we have seen it intermittently since before the workaround, sometimes alongside
invalid_grant, sometimes alone).Operational corollary: both observed breakages occurred after TUI panes were left open 20+ hours. Closing sessions daily avoids the failure in practice.
Happy to provide the full
refresh_transaction/credentials-file timeline as a script if useful for triage.mrjw717 commentedon Sep 28, 2026
Day-3 data point — the deciding variable is session activity, not age alone
Same environment, five servers. In one 24h window:
.credentials.jsonmtime matches, next expiry +1h). This repeated all day.invalid_grant) with norefresh_transactionevent logged anywhere in between — the rotation was consumed silently by some process holding cached credentials.So the failure signature is now: open-but-idle session → silent rotation without persistence → dead token on next use. Active sessions and fresh sessions both behave correctly. This looks like a background/keepalive refresh path (idle revalidation in the connection manager or app-server) that rotates the token in memory without going through the persisting refresh-transaction path used by foreground startup.
recursivemoon commentedon Oct 29, 2026
We see the same family of failures on macOS (Codex desktop 0.166.0-alpha.5.1, keyring store, one remote OAuth MCP server with rotating refresh tokens and a 60 s server-side reuse interval). Server audit for one incident: 8 sequential rotations of one token family within 5 seconds (many Codex threads/processes waking together), then ~1 hour later several requests presented already-rotated refresh tokens, so the server revoked the family and every thread needed re-login.
Two source-level contributors, both still present on current
main:1. rmcp refreshes again after another caller already refreshed (burst of rotations).
In the rmcp revision Codex pins (
98a54789,crates/rmcp/src/transport/auth.rs),get_access_tokendecides "expired or nearly expired" from an unlocked load, then callstry_refresh_or_reauth→refresh_token.refresh_tokentakesacquire_refresh_guard, reloads the store, and exchanges the reloaded refresh token without re-checking whether the reloaded access token is now fresh. So N waiters that all saw the old expiry each redeem the next token in turn: N rotations instead of 1. Any process that keeps an in-memory copy from the middle of that chain later presents a rotated token. Suggested fix: when the refresh was triggered by expiry (not by a 401 / explicit force), re-check remaining lifetime after the guarded reload and return the stored credentials if they are fresh. Keep explicit/forced refresh unchanged.2. File-store lookup can pick a stale legacy entry over the exact key.
codex-rs/rmcp-client/src/oauth.rs,load_oauth_tokens_from_file_with_lock_held, iterates theBTreeMapand returns the first URL/name match. Save writes the canonical key without removing legacy aliases, so a lexically earlier stale alias can win and trigger a refresh with a rotated token. Suggested fix: trystore.get_key_value(&key)first, then the other candidates, keeping every existing URL/name/executor/local identity check. A local installed-binary reproduction (synthetic credentials, fake localhost OAuth server) showed one refresh where zero were expected.Neither alone explains an hour-old token being replayed, but (1) creates the long rotation chains and (2) can resurrect an old link. On the server side we now let a lagging copy inside the reuse interval recover to the live tip of its own chain, which helps for (1) but cannot safely cover replays outside the interval.
Sessions sharing one sign-in survive a refresh race; room presence an…