MCP OAuth: a rejected refresh token stays "usable", so Codex retries it forever and never surfaces re-authentication
What version of Codex CLI is running?
Reproduced on 0.140.0, 0.144.0, 0.146.0, 0.147.0 (current release) and 0.148.0-alpha.20 (current alpha). All five behave identically.
What subscription do you have?
Not applicable — the reproduction below drives codex app-server against a local stub OAuth/MCP server and never makes a model call.
Which model were you using?
None. The repro uses the app-server JSON-RPC method mcpServerStatus/list, which forces an MCP connection without a model turn.
What platform is your computer?
macOS 26.5.2, arm64 (macos-aarch64).
What terminal emulator and version are you using (if applicable)?
Not applicable — driven programmatically over stdio.
Codex doctor report
codex doctor (trimmed)
Codex Doctor v0.147.0 · macos-aarch64
Environment
✓ system en-US
os Mac OS 26.5.2 [64-bit]
✓ runtime npm, version 0.147.0
✗ auth no Codex credentials were found
⚠ websocket Responses WebSocket failed; HTTPS fallback may still work
The install/updates/auth findings are expected: each version under test was installed into its own scratch directory with an isolated CODEX_HOME, and no Codex login is needed to reproduce this.
What issue are you seeing?
When an MCP server rejects a refresh with a spec-correct 400 invalid_grant, Codex does not discard the refresh token. It re-sends the identical token on every subsequent attempt, indefinitely, and never falls back to a fresh authorization flow. The app layer is simultaneously told the server is still authenticated, so no re-authenticate affordance appears.
The user sees the MCP server present but with zero tools, and nothing indicates that logging in again would fix it.
Observed, server side
Three consecutive attempts against the stub, with an expired access token:
POST /mcp -> 401 (no bearer)
GET /.well-known/oauth-protected-resource
GET /.well-known/oauth-authorization-server
POST /token grant_type=refresh_token -> 400 invalid_grant refresh_token=rt-ae49f761…
POST /mcp -> 401 (no bearer)
GET /.well-known/oauth-protected-resource
GET /.well-known/oauth-authorization-server
POST /token grant_type=refresh_token -> 400 invalid_grant refresh_token=rt-ae49f761…
POST /mcp -> 401 (no bearer)
GET /.well-known/oauth-protected-resource
GET /.well-known/oauth-authorization-server
POST /token grant_type=refresh_token -> 400 invalid_grant refresh_token=rt-ae49f761…
The same refresh_token value each time. No POST /register, no GET /authorize.
Note that Codex does honour WWW-Authenticate and re-fetches the protected-resource metadata on every attempt, then still chooses refresh_token. So a server cannot steer it into a fresh consent by advertising metadata.
Observed, client side
The failure appears only on stderr:
ERROR codex_rmcp_client::oauth::refresh_transaction: error=failed to refresh OAuth
tokens for server stub: OAuth token refresh failed: Server returned error response:
invalid_grant: Refresh token not found or already used
But the JSON-RPC response to the app is a success:
{"data":[{"name":"stub","serverInfo":null,"tools":{},"resources":[],
"resourceTemplates":[],"authStatus":"oAuth"}]}
authStatus still reports oAuth. There is no error field. Only tools is empty and serverInfo is null. That combination is why no re-auth prompt is offered — the app has nothing to trigger one from.
Root cause
Line references pinned to d7d526b81db92eb0ee6a47dfed9cee9f92b1935f.
codex-rs/rmcp-client/src/oauth.rs:278-291:
fn oauth_tokens_are_usable(tokens: &StoredOAuthTokens) -> bool {
if tokens.client_id.trim().is_empty() {
return false;
}
let token_response = &tokens.token_response.0;
if token_needs_refresh(tokens.expires_at) {
return token_response
.refresh_token()
.is_some_and(|token| !token.secret().trim().is_empty());
}
!token_response.access_token().secret().trim().is_empty()
}
When the access token needs refreshing, the credential is judged usable purely because a non-empty refresh-token string is present. Whether the authorization server accepted that token never enters the decision, and nothing records that it was rejected.
That feeds oauth_token_status (oauth.rs:203-220), which returns StoredOAuthTokenStatus::Usable, and auth_status.rs:163-175 maps it:
match oauth_token_status(server_name, url, store_mode, keyring_backend_kind)? {
StoredOAuthTokenStatus::Usable => {
return Ok(AuthStatusCheck::Complete(McpAuthState::OAuth));
}
StoredOAuthTokenStatus::AuthorizationRequired => {
return Ok(AuthStatusCheck::Complete(McpAuthState::LoggedOut(
McpLoginRequirement::Reauthentication,
)));
}
StoredOAuthTokenStatus::Missing => {}
}
The recovery path already exists — it is the AuthorizationRequired arm. A rejected refresh token simply never reaches that state.
Two supporting details:
invalid_grantis never inspected.grep -i invalid_grantreturns zero matches in bothoauth.rsandauth_status.rs. The OAuth error code is not read, so a permanent rejection and a transient network failure are treated identically.- The only credential-clearing path cannot fire here.
persist_if_needed(oauth.rs:679) deletes the stored credential in itsNone =>arm (oauth.rs:717) — that is, when a refresh succeeded and returned no tokens. A400is anErr, so it never reaches that arm.
Production impact
Our MCP server (mcp.arcade.software) saw 206 failed /token calls over the 3.6 days after we started returning 400 invalid_grant instead of 500. 163 of those 206 came from Codex clients that had no successful token exchange in the window — three machines retrying a dead grant every 5 to 9 minutes, continuously, for four days. Each user was signed out with no prompt and no way to notice.
We had switched to 400 invalid_grant precisely so clients would stop retrying and re-authorize. For Codex that made no difference.
What steps can reproduce the bug?
-
Save the stub server below and start it. It completes
authorization_codenormally and returns400 invalid_grantfor everyrefresh_tokengrant — the exact response a server gives for a genuinely dead token.stub.mjs— no dependenciesimport http from 'node:http' import { randomUUID } from 'node:crypto' const PORT = 8931, BASE = `http://localhost:${PORT}` const TTL = 120 // seconds; must exceed Codex's refresh margin const access = new Map() const json = (res, code, body, headers = {}) => { const s = JSON.stringify(body) res.writeHead(code, { 'content-type': 'application/json', ...headers }) res.end(s) } http.createServer(async (req, res) => { const url = new URL(req.url, BASE) let raw = '' for await (const c of req) raw += c const ct = req.headers['content-type'] ?? '' const body = ct.includes('json') ? (() => { try { return JSON.parse(raw) } catch { return {} } })() : Object.fromEntries(new URLSearchParams(raw)) console.log(new Date().toISOString(), req.method, url.pathname, body.grant_type ? `grant=${body.grant_type}` : '', body.refresh_token ? `rt=${String(body.refresh_token).slice(0, 12)}…` : '') if (url.pathname.startsWith('/.well-known/oauth-protected-resource')) return json(res, 200, { resource: `${BASE}/mcp`, authorization_servers: [BASE] }) if (url.pathname.startsWith('/.well-known/oauth-authorization-server')) return json(res, 200, { issuer: BASE, authorization_endpoint: `${BASE}/authorize`, token_endpoint: `${BASE}/token`, registration_endpoint: `${BASE}/register`, response_types_supported: ['code'], grant_types_supported: ['authorization_code', 'refresh_token'], code_challenge_methods_supported: ['S256'], token_endpoint_auth_methods_supported: ['none'], }) if (url.pathname === '/register' && req.method === 'POST') return json(res, 201, { client_id: `stub-${randomUUID().slice(0, 8)}`, redirect_uris: body.redirect_uris ?? [], token_endpoint_auth_method: 'none', }) if (url.pathname === '/authorize') { const loc = new URL(url.searchParams.get('redirect_uri')) loc.searchParams.set('code', `code-${randomUUID().slice(0, 12)}`) const state = url.searchParams.get('state') if (state) loc.searchParams.set('state', state) res.writeHead(302, { location: loc.toString() }) return res.end() } if (url.pathname === '/token' && req.method === 'POST') { if (body.grant_type === 'authorization_code') { const t = `at-${randomUUID()}` access.set(t, Date.now() + TTL * 1000) return json(res, 200, { access_token: t, token_type: 'Bearer', expires_in: TTL, refresh_token: `rt-${randomUUID()}`, scope: 'mcp', }) } // Every refresh is rejected, exactly as a server does for a dead token. return json(res, 400, { error: 'invalid_grant', error_description: 'Refresh token not found or already used', }) } if (url.pathname === '/mcp') { const t = (req.headers.authorization ?? '').replace(/^Bearer\s+/i, '') const exp = access.get(t) if (!exp || exp <= Date.now()) return json(res, 401, { error: 'invalid_token' }, { 'www-authenticate': `Bearer realm="mcp", error="invalid_token", resource_metadata="${BASE}/.well-known/oauth-protected-resource"`, }) const m = body?.method if (m === 'initialize') return json(res, 200, { jsonrpc: '2.0', id: body.id, result: { protocolVersion: '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'stub', version: '1.0.0' } } }) if (m === 'tools/list') return json(res, 200, { jsonrpc: '2.0', id: body.id, result: { tools: [{ name: 'stub_ping', description: 'pong', inputSchema: { type: 'object', properties: {} } }] } }) if (String(m).startsWith('notifications/')) { res.writeHead(202); return res.end() } return json(res, 200, { jsonrpc: '2.0', id: body?.id ?? null, result: {} }) } return json(res, 404, { error: 'not_found' }) }).listen(PORT, () => console.log(`stub on ${BASE}/mcp — refresh always 400 invalid_grant`))node stub.mjs -
Register it and complete the OAuth flow in an isolated home:
export CODEX_HOME=/tmp/codexhome-repro codex mcp add stub --url http://localhost:8931/mcp # → "Successfully logged in." -
Wait past the access-token TTL so Codex refreshes on its own clock:
sleep 130 -
Force a connection and observe. Any path that connects works;
codex app-server+mcpServerStatus/listis the deterministic one:codex app-server # {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"clientInfo":{"name":"repro","version":"1"}}} # {"jsonrpc":"2.0","id":2,"method":"mcpServerStatus/list","params":{}} -
Repeat step 4 a few times. Each attempt sends the same refresh token, gets
400 invalid_grant, and returns"tools":{}with"authStatus":"oAuth". No/authorizeis ever attempted. -
Confirm the credential is still considered good, and that only a manual login clears the state:
codex mcp login stub # succeeds; tools return immediately afterwards
A note on the TTL. TTL must be comfortably above Codex's refresh margin. With a 10s or 25s access token, Codex refreshes about 2.6s after a successful login, which makes step 6 look like it failed when it actually did not. 120s works; the margin sits somewhere between 25s and 120s.
What is the expected behavior?
Treat invalid_grant as what RFC 6749 §5.2 defines it to be — the refresh token is invalid, expired, or revoked — and stop reusing it.
Concretely, either:
- Delete the stored credential on
invalid_grant.oauth_token_statusthen returnsMissing, discovery runs, and the user gets a normal authorization flow. This also fixes the case where the credential lives in the keychain and survives restarts. - Or record the rejection and return
AuthorizationRequired. The existingauth_status.rs:167arm already maps that toMcpLoginRequirement::Reauthentication, so the re-auth affordance appears with no new UI work.
Either way, two smaller things would help a lot:
- Distinguish permanent from transient.
invalid_grant/invalid_clientare terminal; a 5xx or a network error is not. Right now they all take the same path, which is why an unparseable response latches the same way (#38198). - Surface the failure to the app layer. A refresh that failed should not present as a successful status response with an empty tool list and
authStatus: "oAuth". That combination is indistinguishable from "connected, server genuinely has no tools."
Additional information
A 401 from the resource server does not trigger a refresh. I also tried having /mcp reject every access token as expired, expecting the 401 to drive the refresh path. It does not — Codex sends the bearer, takes the 401, and stops without attempting a refresh. Combined with it reading and ignoring the protected-resource metadata, there is no server-side signal that can prompt a refresh, a re-auth, or a credential reset. The fix has to be client side.
Related issues. These describe the same latching behaviour from different angles; I am filing separately because this one has a spec-correct trigger and a specific root cause, but they may be worth consolidating:
- #38198 — same "connected but toolless, no Authenticate button" outcome; trigger there is an unparseable refresh response rather than a well-formed
400. - #14144 —
invalid_grantpersisting after re-auth (open since March, 15 👍). - #29630 — no re-registration on
invalid_client/ expired refresh token. - #32590 — broader MCP OAuth session-lifecycle umbrella.
If a maintainer would prefer this folded into #38198 as a comment, happy to move it.
Potential duplicates detected. Please review them and close your issue if it is a duplicate.
- #38198
Powered by Codex Action
Confirmed on main @ 1f41cc5d92 — every stage of the loop you captured is identifiable in code, and the interesting part is that all the classification machinery already exists; the one missing step is persisting the rejection.
1. invalid_grant is correctly classified — twice. The pinned rmcp maps a 400 invalid_grant token response to AuthError::TokenRefreshRejected (rmcp 3.0.0, transport/auth.rs#L2195-L2201), and codex's refresh transaction explicitly distinguishes that from transient failures and converts it to AuthorizationRequired:
https://github.com/openai/codex/blob/1f41cc5d92722748e45cae9cecc6d883a4e7cbb1/codex-rs/rmcp-client/src/oauth/refresh_transaction.rs#L178-L191
2. …but the rejection arm never touches the stored credential. It logs, wraps the error, and returns. No delete, no marker — the refresh token that the server just definitively rejected remains in the credential store byte-for-byte.
3. The status layer only reads stored bytes, so the loop closes. "Usable" is derived purely structurally — expired access token + non-empty refresh token = Usable (oauth.rs#L278-L291), which maps to McpAuthState::OAuth (authenticated, no affordance) in auth_status.rs#L163-L173. The ironic detail: StoredOAuthTokenStatus::AuthorizationRequired and the McpLoginRequirement::Reauthentication UI state both already exist — they're just unreachable for this case, because they only trigger when the stored tokens are structurally broken (e.g. empty refresh token), never when they were rejected by the server. So every new connection sees "usable" → refreshes → 400 invalid_grant → error → nothing persisted → repeat, while the app layer keeps reporting authenticated. Exactly your wire capture, and it also explains why all five versions behave identically — this gap predates them all.
Fix shape (small and localized): in the TokenRefreshRejected arm of refresh_transaction, persist the invalidation before returning — either clear the refresh token from the stored credential (keeping the client registration so re-auth can skip DCR), or store a rejected marker that oauth_tokens_are_usable honors. Either way the very next oauth_token_status read flips to AuthorizationRequired, the existing Reauthentication affordance appears, and connection attempts stop replaying the dead token. The transaction already holds the serialized store-lock machinery, so the write has a natural home; per RFC 6749 §5.2, discarding on invalid_grant is also simply the spec-mandated client behavior.
Your stub-server harness is the regression test nearly verbatim: expired access + refresh → 400 invalid_grant → assert exactly one refresh attempt, stored status flips to reauth-required, and mcpServerStatus/list reports the re-authentication requirement instead of authenticated-with-zero-tools.
The distinction that matters is fatal vs transient refresh failures, and invalid_grant is fatal by definition. RFC 6749 section 5.2: invalid_grant means the authorization grant (the refresh token) is invalid, expired, or revoked. Retrying it is guaranteed to fail, so treating it as retryable is a state-machine bug, not a tuning issue.
Suggested model:
- Classify refresh errors into buckets: fatal (invalid_grant, invalid_client) and transient (network, 5xx, temporarily_unavailable, slow_down). Fatal goes straight to the re-auth state and the token is marked unusable; transient gets exponential backoff with jitter and a cap.
- On fatal, surface re-authentication as a first-class state, the same flow as the initial connect, not a background retry the user only discovers when the server stops responding.
- Watch out for refresh-token rotation: if the provider rotates tokens, the old token becomes invalid after first use. A retry loop that reuses the pre-rotation token keeps getting invalid_grant even though auth is fine. Store the rotation response atomically so the loop always uses the latest token version.
The mcpServerStatus/list repro you built is exactly the right shape for this: a stub server makes the state machine observable, so you can assert that a fatal error transitions to re-auth within one attempt and that transient errors back off. Our OAuth gateway at corpusiq.io buckets refresh errors the same way and drops to interactive re-auth on invalid_grant; it is the difference between a session that self-heals and one that pins on a dead token forever.
I reproduced this against f97e77569352a2bf5be9955e623edad0a15d9b93 (current main at validation time).
The root cause is confirmed: RMCP already maps OAuth invalid_grant to AuthError::TokenRefreshRejected, and Codex maps that to AuthorizationRequired, but the rejected refresh token currently remains in durable storage and live authorization state. Startup/reconnect can therefore load and retry the same rejected capability indefinitely.
The invariant I used is: a definitively rejected refresh capability must no longer be reusable. Non-definitive failures—including 429, 5xx, timeouts, malformed responses, network failures, and invalid_client—must preserve the credential.
The focused fix is in the refresh transaction: remove only the rejected refresh_token, persist the sanitized state to the authoritative/pinned store, and synchronize both AuthorizationManager and the live credential snapshot. If that save fails, fall back to deleting the credential from the same pinned store and clear the live state. Concurrent persistors reread and adopt the authoritative sanitized state rather than replaying a stale token.
No app-server or protocol-state change appears necessary. Existing status propagation already reaches LoggedOut(Reauthentication) and ReauthenticationRequired.
Local Rust 1.95 validation:
- focused OAuth matrix: 14/14 passed;
- auth-status mapping: 1/1 passed;
ReauthenticationRequiredmapping: 1/1 passed;just fix -p codex-rmcp-client: passed (scoped Clippy);- Cargo fmt check: passed;
git diff --check: passed;just bench-smoke: passed.
The three remaining failures in the crate-wide run reproduced identically on a clean checkout of the same main SHA (two remote-executor timeout fixtures and one test environment missing the codex binary), so they are not regressions from this change.
Adversarial review also found and covered additional persistence/concurrency edges, including sanitized-save failure with deletion fallback, double storage failure reporting, stale-snapshot convergence, reconnect behavior, rotation followed by rejection, and cancellation-safe persistence.
I am not claiming GitHub CI passed: upstream/multiplatform CI remains pending because I have not opened a PR without maintainer authorization. Could a maintainer confirm whether this direction matches the intended OAuth semantics? If so, I can open a focused PR when invited/enabled.
Correction to my own root-cause section, since it is wrong about your code in a way that matters.
I wrote that invalid_grant is never inspected, on the basis that grep -i invalid_grant returns nothing in oauth.rs or auth_status.rs. That grep was accurate; the conclusion I drew from it was not, because I never opened refresh_transaction.rs.
@jdcodes1 is right. The classification already exists and is already correct. Verified at refresh_transaction.rs#L178-L191:
Ok(Err(error @ AuthError::TokenRefreshRejected(_))) => {
// RMCP 3 distinguishes definitive refresh-token rejection from transient
// provider failures. Only a rejected token requires a fresh authorization.
warn!(error = %error, "MCP OAuth refresh token was rejected; reauthorization required");
return Err(AuthError::AuthorizationRequired).with_context(|| { ... });
}
So the defect is narrower than I described. It is not a missing classification — it is a classification that is never persisted. That arm logs and returns without touching the credential store, so the next oauth_token_status read derives Usable from unchanged bytes and the loop closes. That also explains the identical behaviour across all five versions I tested better than my version did: the gap is in persistence, which none of those releases changed.
Two further corrections while I am here:
- I described the ask as "distinguish permanent from transient." @charle-z's invariant is the sharper form and the one I should have written: only a definitive rejection may clear the credential, while 429, 5xx, timeouts, malformed bodies and
invalid_clientmust preserve it. Clearing on any refresh failure would be a worse bug than the one reported. - My "Concrete upstream ask" section proposed either deleting the credential or marking it
AuthorizationRequired. Given that theAuthorizationRequiredreturn already happens, the useful half of that suggestion is only the persistence, not the classification.
The reproduction, the wire captures, the five-version sweep, and the observation that a 401 from the resource server does not trigger a refresh all stand unchanged.
Thanks for the correction — I revalidated this against current main at d68b85a0978e15c49c6e96bde1f73ddaeac35d79, and that matches what I’m seeing: classification is already correct; the remaining invariant break is persistence.
The validated patch only invalidates a refresh capability on TokenRefreshRejected: it removes the rejected refresh_token from the authoritative/pinned credential state, persists that sanitized state, and synchronizes both AuthorizationManager and the live credential snapshot. The legacy persistence hook is also fenced against stale writers so it cannot resurrect a refresh token after another refresher has invalidated it. If persisting the sanitized state fails, it falls back to removing the credential from the same authoritative store and clears live state; if both save and delete fail, the storage failure is surfaced rather than reported as a clean reauthorization state.
Non-definitive failures — including 429, 5xx, timeout, network failure, malformed provider response, and invalid_client — preserve the credential.
On current main, the focused adversarial matrix is 17/17 green and the full codex-rmcp-client unit binary is 163 passed / 0 failed / 1 ignored. That covers concurrent rejected refreshes, stale-persistor resurrection, restart/reconnect, persistence failure, rotated-token rejection, retryable failures, and successful reauthorization.
Validated commit: bc51f395d01da04673576ebb9f86ebe07ac42ead
Branch: https://github.com/charle-z/codex/tree/fix/mcp-oauth-rejected-refresh-persistence
Happy to open this as a PR if a maintainer wants to take this approach forward; otherwise the exact patch is there for review/cherry-pick.
This and the other already open issues related to refresh token use, and not honouring permitted scopes, are causing disruption to the use of our MCP servers and the use of third-party plugins that require auth. It would be nice to see more attention paid to these matters.
Facing the same issue.
face same issue....
The persistence fix is in f1fce9c243, based on a947db131.
A rejected refresh token is now removed from stored and live credentials. Concurrent refreshes and stale writers cannot restore it. If saving the updated credential fails, the code tries deletion in the same store and reports an error if that fails too.
Only TokenRefreshRejected clears the refresh capability. Other errors, including invalid_client, preserve the credentials.
On Linux/WSL with Rust 1.95.0, just test -p codex-rmcp-client passed 299 tests, with 8 child helpers skipped. That includes concurrent rejection, stale writes, reconnect/restart and storage failures. Scoped just fix and just fmt also passed.
Corroborating evidence from a self-hosted MCP server (so I could watch both ends), Codex 26.901.51231 / codex-mcp-client 0.153.4:
Server-side packet trace during the wedge (Cloudflare wrangler tail, 48 events across a full restart and a WorkOS session-revoke): every request is GET /mcp → 401 with no Authorization header, followed by GET /.well-known/oauth-protected-resource/mcp → 200, repeating indefinitely. Never a POST, never an initialize, never a request to the authorization server. The client fetches the discovery document that tells it exactly how to re-authorize, then stops.
Codex's own recorded cause (from ~/.codex/sqlite/thread_history_1.sqlite):
failed to refresh OAuth tokens for server <name>
Caused by: OAuth token refresh failed: Server returned error response: invalid_refresh_token
The authorization server (WorkOS AuthKit) rotates refresh tokens on every use — a normal lifecycle event — so invalid_refresh_token is expected and a compliant client should silently re-authorize. Consistent with #41133 as the underlying mechanism (rotated token not persisted).
Why users can't self-recover: the dead grant persists in the macOS Keychain (service Codex MCP Credentials, account <server>|<hash>) across in-app disable/enable, uninstall+reinstall, and full restart. While it's cached, the Authenticate button is hidden, so there is no UI path back. The only recovery is the CLI codex mcp logout <name> — after which a restart restores the Authenticate button and re-auth succeeds immediately.
The server is provably uninvolved: a verified-healthy discovery/DCR/authorize chain (correct 401 + WWW-Authenticate + RFC 9728 metadata; live dynamic client registration succeeds with Codex's own redirect URI), and a different client (Claude Desktop) authenticating the same server at the same moment.
Strongly seconding #40218: a visible per-server Logout / Re-authenticate control would turn this from an unrecoverable dead-end into a two-click fix.
More data on this one. Re-checked against main at 806d9732c.
We run an MCP server with single-use refresh token rotation. A single Codex install sent about 28.8k refresh requests in 7 days that we rejected with 400 invalid_grant. They come in bursts of 17–20 serialized POST /token calls about 1.2 s apart, each preceded by full OAuth discovery. That's one per concurrent session queued on the refresh lock: each one rereads the store under the lock, finds the same dead refresh token, and sends it again. We see it on 0.159.2, 0.160.0 and 0.162.0-alpha.2.
The root cause matches the discussion above. Both refresh paths classify the rejection correctly, but neither one touches the store:
codex-rs/rmcp-client/src/oauth/refresh_transaction.rs: theTokenRefreshRejectedarm inrefresh_transactionlogs and returnsAuthorizationRequired.codex-rs/rmcp-client/src/oauth/credential_store.rs:OAuthCredentialStore::refresh_if_needed(coordinated mode) does the same mapping.- Credentials are only deleted on logout and enterprise login.
A fix that worked in our reading of the code: on TokenRefreshRejected, while the refresh lock is still held, reread the store and delete the credential only if it still holds the rejected refresh token (so a login that finished during the request survives). Other failures (5xx, timeouts, malformed responses) should keep the credential as they do today.
This bug is confirmed by us and also by our OAuth vendor PropelAuth.com. Please fix urgently!
Revalidated on public source 5fff6378d6ab9730bc7cfbd5eb58f1867a5f14c0 on macOS. Two deterministic reproductions still fail before a local candidate repair:
- Rejected refresh replay across requests and restart. I extended
rejected_refresh_token_requires_reauthorizationwith a second preparation attempt and a fresh runtime loaded from the durable store. A local fake provider returns400 invalid_grant. It receives 3 refresh requests, where the regression assertion expects 1 followed by reconnect-required without another refresh. - A stale persistor overwrites a replacement login. In
stale_persistence_preserves_replacement_login, an older runtime has a changed old-generation access token, another login replaces the durable credentials, then the old runtime callspersist_if_needed. Before the repair, it returnsOkand overwrites the replacement. The desired outcome is to preserve the newer login and require the stale runtime to rebuild authorization.
The current source is more nuanced than earlier comments:
- The legacy refresh transaction correctly maps
TokenRefreshRejectedtoAuthorizationRequired, but still leaves the rejected capability in durable storage. - The coordinated credential-store callback already retires rejected credentials locally and persists retirement for supported authorities. However, it explicitly skips durable retirement for ordinary Direct-keyring entries, because these entries are shared across
CODEX_HOMEvalues while the refresh lock is home-scoped. - The legacy persistor writes against its cached generation without a locked authoritative comparison. That is a separate stale-writer path related to #48507.
The invariants exercised by the local candidate are:
- Retire only a definitively rejected refresh capability, preserving other token/client/issuer metadata. Do not reinterpret transient failures or
invalid_clientas rejection. - Pair the manager snapshot and cached generation under the manager mutex, then acquire the credential transaction lock, reread the pinned authority, and compare generations before persisting or deleting. An old runtime must not erase or overwrite a replacement login.
- Use a persistent user-local per-credential rendezvous for processes sharing an OS keyring, acquired before the existing home lock. This permits guarded Direct-keyring retirement across configuration homes. Retain the guard through provider refresh and durable mutation, including caller cancellation.
- Keep local rejected state even when durable mutation fails. A failed durable write still limits restart guarantees and must remain visible as a storage failure; it is not proof that every future runtime will observe retirement.
Synthetic coverage includes repeated preparation, a fresh legacy runtime, mocked Direct and Secrets keyrings, replacement-login preservation, and contention between distinct configuration homes. Full codex-rmcp-client library suite: 261 passed, 0 failed, 1 ignored child helper. Package library/test Clippy passed. Tested with Rust 1.98.0; the source-pinned 1.95.0 toolchain was not available locally.
All providers, credentials and keyrings in these reproductions were synthetic. No real tokens, customer identities, messages or provider logs are included. The installed desktop bundle reports codex-cli 0.162.0-alpha.17.2, but I have not established its exact source equivalence or installed the candidate into that signed app. These tests also do not identify the process responsible for any historical token reuse.
One remaining qualification boundary: legacy RMCP reactive-401 refresh is outside the complete coordinated runtime path. A shipping candidate should exercise the coordinated path across startup, reactive refresh, login/logout, cancellation and multiple processes. I am posting the reproductions and source analysis here rather than opening an external code PR, per the repository's contribution policy.
Additional evidence from 2026-10-16, with a newer bundled runtime. This matches the rejected-refresh replay described here, even though the desktop now reports notLoggedIn rather than the earlier oAuth status.
Environment
- Desktop app version: 26.1013.31256, build 20586 (installed app bundle metadata).
- Bundled executable: codex-cli 0.163.0-alpha.10.2 (
codex --version). - macOS 26.4, arm64.
- Remote Streamable HTTP MCP registered globally as
crm, using stored OAuth credentials. - The requesting process was the desktop-launched
codex app-server, PID 61381, parent desktop PID 61213. It started at 2026-10-16 08:57:08 UTC. - Endpoint URLs, credentials, client IDs, and conversation IDs are omitted.
Observed behavior and evidence
The desktop repeatedly called mcpServerStatus/list. Each of the following discovery cycles completed with another rejected OAuth refresh and an app-tool discovery failure, despite the client already recognizing that authorization was required.
Selected desktop log lines, with unrelated routing fields omitted; timestamps are UTC:
2026-10-16T16:55:25.315Z info [AppServerConnection] response_routed conversationId=null method=mcpServerStatus/list errorCode=null
2026-10-16T16:55:25.365Z warning [electron-message-handler] Failed to discover app tools authStatus=notLoggedIn error="MCP startup failed: failed to refresh OAuth tokens for server crm: OAuth refresh token was rejected: Server returned error response: invalid_grant: Refresh token is not valid for this FastAPI MCP resource.: OAuth authorization required" hostId=local server=crm
2026-10-16T16:56:01.728Z info [AppServerConnection] response_routed conversationId=null method=mcpServerStatus/list errorCode=null
2026-10-16T16:56:01.768Z warning [electron-message-handler] Failed to discover app tools authStatus=notLoggedIn error="MCP startup failed: failed to refresh OAuth tokens for server crm: OAuth refresh token was rejected: Server returned error response: invalid_grant: Refresh token is not valid for this FastAPI MCP resource.: OAuth authorization required" hostId=local server=crm
The app-server log database attributes the corresponding failures to the same PID 61381, including these messages from codex_rmcp_client::oauth::refresh_transaction:
MCP OAuth refresh token was rejected; reauthorization required
MCP OAuth refresh transaction failed server_name=crm refresh_reason="expiry"
error=failed to refresh OAuth tokens for server crm: OAuth refresh token was rejected: Server returned error response: invalid_grant: Refresh token is not valid for this FastAPI MCP resource.
Desktop logs also contain the same rejection on October 15 and overnight into October 16, including discovery failures from a hidden/unfocused app window. I am not asserting an uninterrupted fixed 20-second cadence, nor that a token-rotation race caused this incident; those were not established.
The provider's token endpoint returns HTTP 400 with error=invalid_grant. Its old human-readable description misleadingly grouped expired tokens with resource/client validation failures. The provider's subsequent investigation identified an expired refresh token and corrected that description. The machine-readable invalid_grant was already present, so handling must not depend on the description's wording.
Mitigation
At 16:57:02 UTC, set:
[mcp_servers.crm]
enabled = false
# Existing private URL unchanged.
The shared app-server was left running. The last recorded rejected CRM refresh was at 16:56:01 UTC. One later startup attempt at 16:57:56 failed at 16:57:57 with HTTP 503 during metadata discovery; subsequent status-list cycles at 16:57:57–58 reported authStatus=unsupported, runtimeStatus=null. No further CRM startup/failure events appeared through the original verification at 17:00:26 UTC. The config was checked again at 17:06 UTC and remains disabled.
The live CRM integration will remain disabled pending a verified fix; it was not re-enabled to produce this report.
Required behavior / regression coverage
- Treat a definitive refresh
invalid_grantas terminal for that credential generation. Persist a sign-in-required state and prevent subsequent discovery cycles, other sessions/windows, or a process restart from replaying the rejected refresh capability. - Clearly offer a new OAuth login. Resume normal initialization only after successful explicit reauthorization supplies usable credentials.
- Retire only the rejected credential generation; do not erase or overwrite a newer login that completed concurrently.
- Keep temporary transport failures, timeouts, and HTTP 5xx distinct: preserve credentials and use bounded backoff.
- A fake-provider regression test should return
400 invalid_grantonce, then observe no additional refresh requests across repeatedmcpServerStatus/listcalls, another session, and restart until a new login succeeds.
The newer runtime's notLoggedIn reporting is useful, but the terminal state also needs to stop outbound retry attempts.
Additional production evidence from October 17, 2026: the rejected-refresh retry behavior is still occurring with the desktop-bundled Codex 0.162.0-alpha.17.2.
Environment
- macOS 27.0.1 (26A434), Apple Silicon.
- Bundled runtime:
0.162.0-alpha.17.2, verified from the installed ChatGPT app's Codex package metadata. - Separately installed CLI:
0.155.1, verified from its installed npm package. - Remote HTTP MCP server: Korium, configured in the shared user-level Codex configuration.
- Endpoint URLs, credentials, client IDs, process identifiers, and conversation identifiers are omitted.
Observed impact
Our server-side load-balancer log review attributed these refused requests to Codex by the recorded client user agent. All times below are US Eastern (EDT).
| Period | Refused requests attributed to Codex | Client versions / comparison |
|---|---|---|
| October 17, 4:58 to 5:01 PM | 49 | Codex 0.162; app opened at 4:57:56 PM. Claude Code had zero refusals and successfully refreshed at 4:48 PM. |
| September 30 | 52 | Codex 0.155, 0.158, and 0.159. Claude Code had zero refusals. |
| October 1 to 13 | Approximately 1,300 | Codex. Claude Code had zero refusals. |
The reviewed server records show no successful Codex connection to Korium since September 30. The repeated rejected refresh attempts also trigger server-side token-reuse alerts.
Client-side confirmation
Read-only inspection of the installed client's logs_2.sqlite found repeated rejection events on October 17 at 5:16:38 to 5:16:39 PM EDT, from the same app-server process. The log messages include:
MCP OAuth refresh token was rejected; reauthorization required error=OAuth refresh token was rejected: Server returned error response: invalid_grant
MCP OAuth refresh transaction failed server_name=korium refresh_reason="expiry" error=failed to refresh OAuth tokens for server korium: OAuth refresh token was rejected: Server returned error response: invalid_grant
MCP server startup failed server_name="korium" error=failed to refresh OAuth tokens for server korium: OAuth refresh token was rejected: Server returned error response: invalid_grant: OAuth authorization required
The recorded source locations are rmcp-client/src/oauth/refresh_transaction.rs:202, rmcp-client/src/oauth/refresh_transaction.rs:73, and codex-mcp/src/rmcp_client.rs:412, respectively. These are locations recorded by the installed binary, not an assertion that the binary matches current public source. The same rejection pattern also appears in retained client logs on October 9, 11, and 13.
This corroborates the narrower failure discussed above: the client recognizes a definitive refresh-token rejection and reports that authorization is required, but later connection attempts still retry a rejected refresh.
Expected behavior and scope
Once a refresh capability is definitively rejected, subsequent connection attempts and process restarts should stop replaying that rejected credential generation and offer sign-in again. A newer login completed concurrently must be preserved.
We have not established what originally invalidated this token. The presence of two Codex installations is context, not proof of a rotation race. This report does not claim that every retry used byte-identical token contents, that the current UI reports oAuth, or that the exact current source-level cause was independently verified.
No credentials, configuration, application code, or server behavior were changed to collect this client-side evidence.
Server-side data from another MCP server operator (Better Auth OAuth provider, rotating refresh tokens, 1-hour access tokens), Sep 20 – Oct 20, 2026:
- 9,334
POSTs fromcodex-mcp-clientin 30 days, every one rejected with401and noAuthorizationheader. Zero authenticated Codex requests in that window. Wedged clients alternate between the MCP endpoint and protected-resource metadata discovery; we see no authorization or token requests from them. - Versions in the wedged traffic:
0.163.0-alpha.10.2(most),0.162.0-alpha.17.2,0.162.0-alpha.2,0.157.0,0.160.0,0.162.0,0.162.1,0.163.0. - One login on
0.157.1completed and we issued an access + refresh token pair. Codex never presented either, and the refresh token was never used. - Claude, ChatGPT and Cursor stay connected against the same server, metadata and tokens over the same period.
Affected users only recover by re-authenticating by hand; the desktop app never prompts them.
How is this no fixed yet? Seems like people have been having issues with this for quite some time now and it seriously effects the UX of plugins
Server-side data from another MCP server operator, plus one source finding on how the replayed token gets there in the first place.
Setup: django-oauth-toolkit 3.4 authorization server. Rotating refresh tokens with reuse protection, so replaying a rotated token revokes the whole token family. Hashed token storage, which rules out a refresh grace period. Access tokens last one hour.
What we see (Oct 16–20, 2026):
codex-mcp-clientretriesPOST /token(grant_type=refresh_token) with a dead token about once a second. Every attempt gets400 invalid_grant, and each one follows a fetch of/.well-known/oauth-authorization-server.- Almost all of this traffic is
0.162.0-alpha.17.2, with some0.158,0.161, and0.163. - For each affected user, the refresh that started the loop replayed a token that had already been rotated. The replay arrived 1.5 to 3.6 hours after the rotation, not seconds, so this is not a concurrent-refresh race. Reuse protection then revoked the user's live session as well, so the bug doesn't just strand one stale client: it disconnects the user's working one too.
Source finding (at rust-v0.162.0-alpha.17.2 and current main):
- Classification is right. rmcp maps
invalid_granttoTokenRefreshRejected, andrefresh_transaction.rsescalates that toAuthorizationRequired. - The rejected token is never cleared. Nothing on the rejection path deletes or marks the stored credential.
oauth_tokens_are_usablestill treats an expired access token plus a refresh token as usable, so every new session or startup replays the same token. That matches this issue. - The refresh lock doesn't span installs.
RefreshCredentialLockis scoped toCODEX_HOME(oauth/refresh_lock.rs, see the TODO about keyring coordination across homes), while the OS keyring entry is shared across homes. Two installs with different homes can share one credential without sharing the lock. Examples: the desktop-bundled runtime next to a separately installed CLI, as in the Oct 17 comment above. One install rotates the token, and the other later refreshes with a stale copy. Under reuse protection that kills the family. #53899 (stale duplicate file-store entry after rotation) and #48507 (rotation race in.credentials.json) look like other paths to the same stale replay. Unverified: I have not reproduced the cross-home case, and I could not confirm which store the affected users run.
What would fix it from the server side's point of view:
- On
TokenRefreshRejected, drop the stored refresh token, or mark it so it isn't retried, and surface the existing "requires OAuth reauthentication" state. - Coordinate refresh across everything that shares a keyring entry, not just one
CODEX_HOME.
Workaround for users: run codex mcp login <server>, or use the client's MCP OAuth sign-in. Nothing the server returns makes the client discard the token.
Reproduced on Codex CLI 0.163.0 (file-backed MCP credential store, local test server with single-use rotating refresh tokens). With a dead refresh token, Codex sends it again on every start and on /mcp: 2 attempts per interactive start and 1 per codex exec, always rejected with invalid_grant. The credential file is never changed. The interactive CLI warns that the server needs reauthentication; codex exec exits 0 and only logs the rejection to stderr. A 429 with Retry-After from the server is treated like the 400: it is not honored and the token is kept. Removing and re-adding the server did not clear the credential; codex mcp logout followed by codex mcp login and a restart did.