Repository navigation
Description
Summary
Codex can lose a rotated MCP OAuth refresh token when an MCP client is shut down while transport cleanup is refreshing credentials. The provider successfully consumes RT1 and returns AT2/RT2, but Codex may drop the in-memory credential store before copying RT2 to its durable credential store. A later process then retries RT1, which a rotating-token provider correctly treats as reuse and may revoke the entire token family.
This is a lifecycle/persistence race, not an ordinary access-token expiration problem.
Observed case (redacted)
This happened with Codex desktop's bundled CLI 0.150.0-alpha.8 on macOS arm64. Provider and local credential-store timestamps showed:
07:50:40.602 UTC: AT2 expired.07:50:47.614 UTC: the Codex app-server began shutting down an inactive task instance.07:50:47.902 UTC: the OAuth provider committed the RT2 exchange and issued AT3/RT3, about 288 ms after task teardown began.- The durable MCP OAuth credential entry retained AT2/RT2 and its modification time did not advance past
06:50:40 UTC. 07:52:42.652 UTC: another Codex process retried RT2, about 115 seconds after the successful rotation. The provider detected reuse and revoked the token family.
Token values, client IDs, family IDs, workspace IDs, and private endpoints are intentionally omitted.
The exact client-side refresh-request start timestamp was not retained, so the shutdown-triggered request cannot be proven from timestamps alone. However, the source path below, the 288 ms overlap, the successful provider-side rotation, and the unchanged durable store make transport cleanup during teardown the strongest source-backed explanation.
Root cause
Codex configures RMCP with an InMemoryCredentialStore and separately copies changes into its durable credential store through OAuthPersistor after normal initialization and tool-call paths.
During RmcpClient::shutdown(), Codex previously replaced the state with Closed and dropped the prior ClientState::Ready. Dropping RMCP's running streamable-HTTP service asynchronously performs session cleanup, including an authenticated DELETE. RMCP obtains an access token for that request and can refresh it when the token is expired or near expiry. That refresh updates only RMCP's in-memory credential store.
At that point there is no later Codex persistence hook: the OAuthPersistor is being dropped together with the service. If the outer shutdown future or task instance is cancelled while the provider is answering, the replacement refresh token is lost even though the provider committed the rotation.
The current refresh request also has no Idempotency-Key, but adding request idempotency alone would not make the returned replacement token durable. Shutdown must not expose a provider-side rotation unless Codex can persist the replacement.
Expected behavior
MCP teardown must satisfy both properties:
- Cancellation of the shutdown caller must not discard an in-flight rotating refresh response.
- Transport cleanup must not independently consume a refresh token after the durable OAuth owner has begun shutting down.
Proposed fix and proof of concept
I implemented a proof of concept here:
- Commit: liangxiwei@adad1f0
- Branch comparison: main...liangxiwei:codex/mcp-oauth-refresh-lifecycle
The change:
- Moves ownership of the previous client state into an independently owned Tokio shutdown task, so cancelling the caller does not drop the service or OAuth state mid-response.
- Before dropping the transport, persists any RMCP-managed credential change and runs the existing serialized/cross-process refresh transaction when the token is near expiry.
- Persists the replacement before exposing it to transport cleanup.
- Removes the refresh token only from RMCP's cleanup-only in-memory view, so the final authenticated session
DELETEcan use the access token but cannot trigger another hidden rotation.
Regression test
The added integration test models the observed lifecycle race:
- Store AT1/RT1 with a 32-second access-token lifetime.
- Enter RMCP's 30-second refresh window.
- Start shutdown; delay the provider's RT1 -> AT2/RT2 response by 300 ms.
- Cancel the outer shutdown caller after 100 ms.
- Verify exactly one refresh exchange occurred, AT2/RT2 are in the durable store, and transport cleanup sends its session
DELETEwith AT2.
Targeted result:
just test -p codex-rmcp-client --test streamable_http_oauth_shutdown
1 passed, 1 skipped
The full codex-rmcp-client package run completed with 266 passing tests, 8 skipped, and 5 unrelated environment-dependent failures (proxy authorization expectations, two remote-executor mock expectations, and a missing locally built target/debug/codex binary). just fmt and just fix -p codex-rmcp-client completed successfully.
Related reports
- Codex MCP OAuth sessions expire and require application restart #32590 tracks the broader symptom that MCP OAuth sessions expire and require reauthentication/restart.
- MCP OAuth: a rejected refresh token stays "usable", so Codex retries it forever and never surfaces re-authentication #39054 describes a complementary failure mode where a rejected refresh token is retained and retried.
This issue focuses specifically on losing a successfully rotated refresh token during MCP task/client teardown.
Activity
liangxiwei commentedon Aug 31, 2026
Follow-up: reproduced on the exact current Desktop release source
I investigated a second, independent occurrence after filing this issue. This follow-up is specifically intended to separate the current-version evidence from the local proof-of-concept commit linked in the issue body.
Exact version under test
The affected Codex Desktop bundle reports:
The corresponding official release tag resolves to:
I fetched that tag and ran the regression against a checkout whose product source was exactly that release commit. The only added file was the integration test; no
rmcp-clientimplementation file was changed. The release locksrmcpto3.1.3.For an additional cross-check, the relevant files in my current checkout are byte-identical to the official tag (
git diff --exit-codereturned 0 foroauth.rs,oauth/refresh_transaction.rs,rmcp_client.rs, andstreamable_http_retry.rs).The earlier local PoC implementation was therefore not used as evidence that the bug exists in the current release. Only its black-box test scenario was applied to the exact release source.
Second production timeline
The provider database and the macOS credential-store metadata show the following sequence (UTC; all token values and private identifiers are omitted):
Important observations:
04:17:50.04:17:50; it still contained RT1.04:17and04:58, so this was not a process-restart persistence gap.04:58, Codex surfacedMCP OAuth refresh token was rejected; reauthorization required; the provider-side error wasinvalid_grantbecause the old rotating refresh token had been reused.This establishes that the first exchange succeeded at the provider, but the returned replacement credentials did not reach Codex's durable credential authority.
Current release source path
Normal foreground MCP operations are protected correctly: they run Codex's serialized refresh transaction before the operation and copy RMCP-managed changes to the durable store afterward. For example:
refresh_oauth_if_needed()before andpersist_oauth_tokens()after normal operationsOAuthPersistor::persist_if_needed()copies RMCP credentials to the resolved durable authorityrefresh_transaction()rereads and persists through the authoritative storeThe lifecycle gap is outside that path:
RmcpClient::shutdown()first replaces the state withClientState::Closed, then drops the previous ready state.Closed,oauth_persistor()can no longer return the persistor.DELETEduring that cleanup.get_access_token()for the cleanup request. If the token has less than its 30-second buffer remaining, or if the server challenges it, RMCP can perform a refresh itself.AuthorizationManager's configured credential store. In this integration, Codex deliberately configures that manager with anInMemoryCredentialStoreand separately owns durable persistence.shutdown(), and the persistor is no longer reachable from client state. The service and in-memory RT2 are then dropped, leaving RT1 in Keychain.The same general risk exists for any RMCP background/reconnect/challenge path that can refresh without passing through Codex's foreground pre-refresh/post-persist hooks. For example,
send_event_stream_request()has neither hook.Exact-release regression result
The test models the lifecycle window as follows:
Command:
Against the unmodified
f70e26c29product source, nextest retried the test and both attempts failed identically:Running the access-token assertion first independently produced:
Thus the exact current release reproduces the key invariant from production: the provider consumes RT1 and returns AT2/RT2 during transport cleanup, while the durable store remains on AT1/RT1.
Confidence and remaining ambiguity
The provider/Ingress configuration did not retain a request-level HTTP access log for the
04:17:50exchange, so I cannot prove whether that specific production refresh was initiated by the shutdownDELETEor by a background GET/SSE reconnect. Both paths use RMCP's authenticated transport wrapper and can enter the same in-memory refresh path.However, the root-cause layer is now directly supported by all three of the following:
The shutdown
DELETEremains the strongest matching trigger and is sufficient to reproduce the bug. This is not a provider failure to return a rotated refresh token, and it does not go through Codex's existing cross-process refresh transaction; it is an RMCP-managed refresh that bypasses the durable transaction entirely.petaxie commentedon Sep 10, 2026
Independently reproduced on the unmodified 0.153.4 Desktop binary (file store)
Adding a black-box reproduction of this issue on codex-cli 0.153.4, bundled in ChatGPT.app, macOS 26.6.2 arm64. No product source changes or real OAuth credentials are required. Two expired-token runs reproduced; a fresh-token shutdown control passed.
Unlike the cancellation regression above, this reproduction uses ordinary
thread/archivethrough the native app-server. It does not abort the shutdown caller or intentionally delay the token response.Reproduction
mcp_oauth_credentials_store_mode = "file".invalid_grant: Unknown refresh token.Observed expired-run sequence (synthetic labels):
[ {"event":"refresh_ok","old":0,"new":1}, {"event":"sse_open"}, {"event":"ping","generation":1}, {"event":"refresh_ok","old":1,"new":2}, {"event":"delete","access":"access-2","valid":true}, {"event":"sse_closed"}, {"event":"refresh_rejected","presented":"refresh-1","current_generation":2} ]The fixture observes SSE closure when its next heartbeat write notices the disconnect, so that event's list position is not an exact client-side close timestamp.
Source correspondence / scope
The observed behavior matches the issue's path:
RmcpClient::shutdown()transitions to Closed and drops the prior ready state; RMCP cleanup can refresh for DELETE, with no subsequent durable persistence hook.This is not evidence that ordinary file writes universally fail or that file credentials are being migrated to Keychain during refresh. Normal startup persists correctly in this test. Keychain mode and other releases have not been tested here.
thread/unsubscribealone is not an immediate shutdown trigger: the release has a 30-minute idle unload delay. Using a mock turn followed by archive avoids that wait while exercising transport cleanup.Runnable fixture
Save the two files below in one directory. Python 3 standard library only. Adjust
BINinrepro.pyto the exact installed binary under test.The script prints a temporary report path and structured results. All token values are synthetic, and each run has a separate temporary home. It terminates its children/server on completion. Native app-server startup can still attempt unauthenticated remote plugin/catalog requests; this is credential-isolated, not network-isolated. No real model endpoint is configured for the turn. ConnectionResetError noise from abandoned fixture HTTP connections is not the reproduction signal; use the report's
reproduced/control_passedfields and events.repro.py — shared synthetic OAuth server and native app-server client
shutdown_repro.py — stateful transport, local mock turn, archive, and control
No private service endpoints, production token fingerprints, or private project identifiers are included.
Investigated with GPT-6 Astra and Claude Opus 4.8.