Skip to content

MCP OAuth: concurrent processes race refresh-token rotation in .credentials.json; next startup hits invalid_grant and demands re-login #48507

Open

Description

@mrjw717

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

  1. Moved all OAuth MCP server definitions out of the global ~/.codex/config.toml into per-project .codex/config.toml files, so only sessions inside a given project load and refresh those servers (server → grant mapping preserved across three projects).
  2. Hygiene: close Codex sessions before rebooting; avoid many concurrent sessions sharing one OAuth server.
  3. A one-shot codex-mcp-relogin script (runs the 5 codex mcp login calls with explicit --scopes for Supabase) for when the chain does break.

After this change, tokens survive reboots; refreshes are now effectively single-writer per server.

Suggested fixes

Related issues

#17265, #24906, #27165, #39054, #45899, #40218

Activity

  1. added
    bug
    CLI
    mcp
    auth
    on Sep 26, 2026
  2. mrjw717 commented on Sep 27, 2026

    @mrjw717
    Author

    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:

    Event Time (UTC)
    codex mcp login completes (file written) Sep 26 18:33
    Stripe access tokens expired on disk (1h TTL) Sep 26 19:30–19:33
    .credentials.json written again never
    Sessions still exercising stripe-dojomojo tools (tool-catalog traces) Sep 26 20:13 – Sep 27 03:16
    New session start → invalid_grant / "requires OAuth reauthentication" Sep 27 ~11:49

    Notable details:

    • Zero codex_rmcp_client::oauth::refresh_transaction events 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.
    • All three stripe entries (same provider, different connected accounts) failed identically; the two supabase entries (24h access-token TTL, refresh not yet due) were still fine.
    • The app-server daemon (up the whole window) hosts MCP connections for TUI sessions; it had no persistent connection to mcp.stripe.com at inspection time.

    Two candidate mechanisms we could not distinguish from outside:

    1. A long-lived process (app-server daemon) refreshes in-memory without persisting the rotated refresh token, consuming the on-disk one server-side.
    2. Stripe MCP refresh tokens are invalidated provider-side after some short period (e.g., overnight inactivity), so any client would need daily re-auth regardless of persistence correctness.

    Either way, .credentials.json ends up holding a refresh token the provider rejects, and the only recovery is interactive codex 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.json with a scripted stripe tool call) if a maintainer wants to pin down which process, if any, performs the silent rotation.

  3. mrjw717 commented on Sep 28, 2026

    @mrjw717
    Author

    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)

    Event Time
    All 5 servers re-authenticated Sep 27 ~12:05
    Stripe tokens refreshed and persisted repeatedly while sessions were active (.credentials.json rewritten hourly: 13:0x, 13:3x, 13:5x, 14:1x, 14:39, 14:49) Sep 27 13:00–14:49
    Last write to .credentials.json Sep 27 14:49
    All stripe access tokens expired on disk Sep 27 14:59–15:49
    Supabase access tokens expired on disk Sep 27 18:32
    No refresh_transaction log events at all Sep 27 14:49 – Sep 28 02:04
    Session start → both failures below Sep 28 02:04

    At 02:04, the session (a TUI pane open since Sep 26, i.e. ~36h old) failed with two different error modes:

    server=supabase-shipwright  refresh_reason="expiry"  error=OAuth token refresh failed: Failed to parse server response
    server=stripe-shipwright    refresh_reason="expiry"  error=OAuth refresh token was rejected: Server returned error response: invalid_grant: Invalid refresh token
    

    Key deduction: the last persisted stripe-shipwright rotation was at ~14:39 and was written to disk. For its refresh token to be invalid_grant 11.5h later, something must have consumed a later rotation without logging a refresh_transaction event 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.

  4. mrjw717 commented on Sep 28, 2026

    @mrjw717
    Author

    Day-3 data point — the deciding variable is session activity, not age alone

    Same environment, five servers. In one 24h window:

    • A pane actively using a server at token-expiry time refreshed and persisted correctly (stripe entry rewritten on the hour, .credentials.json mtime matches, next expiry +1h). This repeated all day.
    • A pane left open but idle across its server's expiry did not write anything; hours later the stored refresh token was dead (invalid_grant) with no refresh_transaction event logged anywhere in between — the rotation was consumed silently by some process holding cached credentials.
    • A freshly restarted pane whose server's refresh token was still valid refreshed transparently on startup and persisted (observed at session start, file written within the same second).

    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.

  5. recursivemoon commented on Oct 29, 2026

    @recursivemoon

    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_token decides "expired or nearly expired" from an unlocked load, then calls try_refresh_or_reauth → refresh_token. refresh_token takes acquire_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 the BTreeMap and 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: try store.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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    CLIauthbugmcp

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions