Repository navigation
fix(oauth): keep the token on a transient refresh failure; serialize refresh across processes - #455
Conversation
| an unparseable success — is treated as dead, as every failure was | ||
| before. | ||
| """ | ||
| if isinstance(e, OAuthTokenError): |
There was a problem hiding this comment.
R1F1 (blocking)
A token endpoint returning HTTP 429 with {"error":"rate_limit_exceeded"} or HTTP 503 with {"error":"internal_error"} is converted by _parse_token_response into OAuthTokenError, losing the HTTP status. This branch consequently classifies the failure as dead because the error code is not in _TRANSIENT_TOKEN_ERRORS, and ensure_token deletes the stored refresh token. Retain the response status and apply the 429/5xx exemption to OAuth error bodies too, rather than protecting only responses without an OAuth error body.
Advisory AI review — verify before acting. Round summary and ledger are in the ai-review comment.
| ] | ||
| for th in threads: | ||
| th.start() | ||
| time.sleep(0.05) # both snapshot the old token before the first saves |
There was a problem hiding this comment.
R1F2 (advisory)
The second thread is only assumed to snapshot the old token before the first callback’s 0.3-second sleep ends. If that thread is scheduled late or constructing its httpx.Client takes longer, it snapshots at-new and makes a second POST, causing the exactly-one-POST assertion to fail nondeterministically. The bare sleeps here and at line 8070 also conflict with the repository’s unit-test guidance; use events or barriers to prove both snapshots occurred before releasing the first response.
Advisory AI review — verify before acting. Round summary and ledger are in the ai-review comment.
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
Transient responses can still delete grants, and the lock timeout can reintroduce refresh-token races.
Review effort: Balanced
Findings: 1
Open (3)
What changed in this PR
Improves OAuth refresh durability and coordinates refresh-token rotation across processes.
Changes:
- Classifies transient versus terminal refresh failures.
- Adds bounded cross-process refresh locking and compare-and-delete.
- Adds tests and workaround documentation.
| File | Description |
|---|---|
src/mcp_stdio/oauth.py |
Adds refresh classification and serialization. |
src/mcp_stdio/token_store.py |
Adds refresh locking and conditional deletion. |
tests/test_oauth.py |
Tests refresh durability and concurrency. |
tests/test_token_store.py |
Tests locking and compare-and-delete. |
WORKAROUNDS.md |
Documents addressed OAuth failures. |
CLAUDE.md |
Documents token-store locking behavior. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| if isinstance(e, OAuthTokenError): | ||
| return e.error not in _TRANSIENT_TOKEN_ERRORS | ||
| if isinstance(e, httpx.HTTPStatusError): | ||
| status = e.response.status_code | ||
| return not (status >= 500 or status == 429) |
| # Upper bound on waiting for another process's refresh (#454). Its holder | ||
| # makes one token-endpoint round trip, so this only runs out when that | ||
| # process is stuck; then refreshing unlocked beats stalling this one. | ||
| _REFRESH_LOCK_WAIT_SECS = 30.0 |
| for th in threads: | ||
| th.start() | ||
| time.sleep(0.05) # both snapshot the old token before the first saves |
| an unparseable success — is treated as dead, as every failure was | ||
| before. | ||
| """ | ||
| if isinstance(e, OAuthTokenError): |
There was a problem hiding this comment.
A 5xx or 429 whose body carries a JSON error is classified as a dead grant, because the HTTP status is lost.
_parse_token_response raises OAuthTokenError for any status_code >= 400 with an error key, before raise_for_status(). So the OAuthTokenError branch here wins and the 5xx/429 check below never runs. Example: Auth0's rate limit answers 429 {"error":"too_many_requests"}, and Keycloak's internal errors answer 500 {"error":"unknown_error"}. Both come back dead=True, and ensure_token deletes the stored refresh token on a transient failure, which is exactly what #454 is meant to stop. The tests only cover 503/429 with an empty body (text: ""). Possible fix: carry the status code on OAuthTokenError (or check it here first) and treat status >= 500 or status == 429 as transient whatever the error code.
| # Upper bound on waiting for another process's refresh (#454). Its holder | ||
| # makes one token-endpoint round trip, so this only runs out when that | ||
| # process is stuck; then refreshing unlocked beats stalling this one. | ||
| _REFRESH_LOCK_WAIT_SECS = 30.0 |
There was a problem hiding this comment.
The 30 s waiter timeout is shorter than the holder's normal worst-case round trip, so a slow but healthy AS makes waiters refresh unlocked and spend the same rotating refresh token.
The holder's client uses --timeout-connect 10 s + --timeout-read 120 s (the defaults), and the #452 scope retry can double that. An AS that takes 30 to 260 s is not stuck, yet every waiter gives up after 30 s, reads the still-unrotated R1, and exchanges it in parallel with the holder. With single-use rotation that means invalid_grant or family revocation, the failure #454 targets. The comment "only runs out when that process is stuck" does not hold under the defaults. Either derive the wait from the client's timeouts (connect + 2 x read plus a margin), or bound the holder's token-endpoint call below the wait.
| # (cf. anthropics/claude-code#37747). Compare-and-delete | ||
| # (#454): if another process stored a newer token meanwhile, | ||
| # it survives. | ||
| delete_token( |
There was a problem hiding this comment.
Compare-and-delete runs after refresh_lock has been released and compares only refresh_token, so a successful refresh by another process in that gap can still be deleted.
_refresh_cached_token_ex returns and releases the lock, and delete_token runs afterwards. When the AS does not rotate refresh tokens, process B can take the lock in that gap, refresh successfully, and save T2 with the same R1. A's delete_token(expected_refresh_token=R1) then matches and removes B's fresh token. This is reachable with a misclassified "dead" (see the 5xx/oversized-body cases) or a per-attempt failure such as invalid_scope. Do the delete inside the lock (e.g. inside _refresh_cached_token_ex when dead), or also compare access_token against the one that failed.
| uses the LATEST stored refresh token. Two processes therefore never | ||
| spend the same rotating refresh token. | ||
| """ | ||
| snapshot = load_token(server_url) |
There was a problem hiding this comment.
The "another process already refreshed" snapshot is re-read from the store here instead of using the token the caller actually holds, so a refresh another process finished before this call goes unnoticed.
The 401 refresher and the proactive timer hold T1 in memory. If another process already stored T2, then snapshot = T2 = cached, and this process exchanges R2 again even though T2 is usable. With N relays, each extra exchange rotates the family again, and an AS that revokes the previous access token on refresh can ping-pong 401s between processes. In ensure_token, a fresh entry another process stored without a refresh_token (an AS that issues none) leads to _refresh_locked -> dead=True -> the interactive browser flow, despite a valid stored token. Pass the caller's access token (ensure_token's cached, the relay's current bearer) as the snapshot.
| return not (status >= 500 or status == 429) | ||
| if isinstance(e, httpx.TransportError): | ||
| return False | ||
| return True |
There was a problem hiding this comment.
Exceptions raised before the HTTP status is inspected fall into "dead", including oversized or compressed 5xx error pages from a proxy or CDN.
refresh_access_token calls _read_bounded before _parse_token_response. A 502/503 HTML error page larger than --max-message-size raises _MessageTooLargeError. A CDN error with an unnegotiated Content-Encoding raises from _reject_content_encoding. Neither is HTTPStatusError or TransportError, so the result is dead=True and the token is deleted on an infrastructure blip. Consider classifying on resp.status_code when one is available (e.g. attach it to the exception), or treating these body-size/encoding errors as transient.
| # A transient failure (no answer, 5xx/429, temporarily_unavailable) | ||
| # says nothing about the grant: keep the token for the next | ||
| # attempt instead of throwing away weeks of refresh token (#454). | ||
| log("keeping the stored OAuth token; its refresh failed transiently") |
There was a problem hiding this comment.
On a transient failure with interactive=True, ensure_token still falls through to the browser/device flow, so a single 503 still forces an interactive sign-in for this run.
Keeping the token only helps the next process. The current run (cold start, or _build_login's mid-session login) opens a browser because the AS returned 503 or 429 once, and that flow will likely hit the same outage. If that is intended (the PR body says "exactly as before"), fine. Otherwise, consider raising, or returning the stale cached token so the relay's 401 path retries later, instead of starting the interactive flow on a transient error.
| log(f"token refresh failed: {_sanitize_oauth_error(e)}") | ||
| return None | ||
| return _RefreshOutcome( | ||
| None, dead=_refresh_error_is_dead(e), refresh_token=cached.refresh_token |
There was a problem hiding this comment.
(Refers to the scope-less retry at L1706, outside the diff.) The scope-less retry also runs after a transient failure, and the classifier then judges the retry's error, which can be a permanent one caused only by dropping the scope.
The inner except (RuntimeError, httpx.HTTPStatusError) catches a 503/429/temporarily_unavailable too, and retries without scope. On Microsoft Entra ID, the reason #452 started sending scope, a refresh without scope is refused with 400 invalid_request (AADSTS90009). Sequence: the first attempt gets a 503, the retry gets invalid_request, _refresh_error_is_dead sees only the second exception, the result is dead=True, and the token is deleted. Possible fix: re-raise the first exception without retrying when _refresh_error_is_dead(e) is False, or classify on the first exception whenever it was transient.
| # flow below isn't blocked by cached failure state | ||
| # (cf. anthropics/claude-code#37747). | ||
| delete_token(server_url) | ||
| outcome = _refresh_cached_token_ex(server_url, client) |
There was a problem hiding this comment.
(Refers to the reconcile save_token(server_url, cached) at L2573, outside the diff.) The resource-flag reconcile writes the stale in-memory token back outside refresh_lock, which can overwrite a refresh token another process just rotated.
Process A starts with a changed --oauth-resource / --no-resource-indicator and loads T1/R1. Meanwhile process B refreshes under the lock and saves T2/R2. A's save_token(server_url, cached) then writes T1/R1 back, so R2 is lost and the consumed R1 is what remains, giving invalid_grant or family revocation on the next refresh. This predates the PR but sits in the touched function and breaks the "never spend the same rotating refresh token" invariant the PR claims. Re-load under refresh_lock and patch only the two resource fields.
…refresh across processes - Token-endpoint errors become OAuthTokenError(RuntimeError) carrying the RFC 6749 §5.2 error code (message unchanged). - ensure_token deletes the stored token only when the refresh failure proves the grant dead: anything but a transport error, a 5xx/429, or temporarily_unavailable/server_error. It deletes by comparison (delete_token(expected_refresh_token=...)), so a newer token another process saved survives. - refresh_lock (tokens.json.refresh.lock, separate from the non-reentrant _store_lock that save_token takes) wraps load -> exchange -> save, with a re-read after acquiring: a process that finds a token another one just refreshed uses it, and every exchange spends the latest refresh token. Bounded 30 s wait, then a warning and an unlocked refresh. - refresh_cached_token keeps its "None on failure" contract on top of the new _refresh_cached_token_ex. Fixes #454 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… under the lock (#455 review) - OAuthTokenError keeps the HTTP status; a 5xx/429 is transient whatever its body says. Any other httpx failure before a status was judged (decoding, oversized body) is transient too. - The scope-less retry runs only after a dead-looking answer, so a 503 can no longer be turned into Entra's AADSTS90009 and a deleted token. - refresh_lock yields False when its bounded wait runs out; the caller then never exchanges (the holder may just be slow): it returns a token stored meanwhile, else a transient failure. - ensure_token passes the token it holds as seen_access_token and asks for delete_if_dead: the dead grant is deleted while the lock is held, compared against both the failed refresh and access tokens (a non-rotating AS keeps the refresh token). - The resource-flag reconcile is applied to a fresh read under the lock instead of writing back a possibly stale copy. - Tests synchronize with events instead of sleeps. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
9ada7c1 to
e5d6e36
Compare
| try: | ||
| save_token(server_url, cached) | ||
| with refresh_lock() as acquired: | ||
| latest = load_token(server_url) if acquired else None |
There was a problem hiding this comment.
R2F1 (blocking)
If another process’s refresh takes longer than 30 seconds, ensure_token(..., resource_indicator=False) skips persisting the reconciled setting here but still proceeds into _refresh_cached_token_ex. If the holder then finishes with a transient failure, the subsequent locked exchange re-reads the unchanged store and sends resource= despite --no-resource-indicator; an --oauth-resource override can likewise be lost. An authorization server rejecting that old resource value can return a 400 that is classified as dead, deleting the grant despite the caller supplying the correct configuration. Apply the desired settings to the eventual locked exchange, or return a transient outcome when reconciliation times out.
Advisory AI review — verify before acting. Round summary and ledger are in the ai-review comment.
| if seen_access_token is None: | ||
| snapshot = load_token(server_url) | ||
| seen_access_token = snapshot.access_token if snapshot else None | ||
| with refresh_lock() as acquired: |
There was a problem hiding this comment.
R2F2 (advisory)
refresh_cached_token now enters refresh_lock even when the initial snapshot contains no token, whereas previously it returned None without acquiring a lock. If the store directory is absent and its parent is read-only or denies directory creation, _file_lock calls _ensure_store_dir outside its error guard and raises instead of preserving the public function’s “None on failure” contract. Skip locking when there are no cached credentials, or include directory bootstrap in the lock’s failure handling.
Advisory AI review — verify before acting. Round summary and ledger are in the ai-review comment.
…ock with nothing to refresh (#455 review) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| client, | ||
| seen_access_token=cached.access_token, | ||
| delete_if_dead=True, | ||
| resource_settings=(not resource_indicator, oauth_resource), |
There was a problem hiding this comment.
R3F1 (advisory)
The comment at oauth.py:2618–2619 still claims that refresh “would still use the old settings until the next successful save” when reconciliation cannot be persisted. Passing resource_settings=(not resource_indicator, oauth_resource) here and applying it at lines 1681–1682 now makes that refresh exchange use the current settings even after a skipped save. Update the comment so it no longer contradicts the behavior this fix establishes.
Advisory AI review — verify before acting. Round summary and ledger are in the ai-review comment.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
AI review (gpt-6.1-sol)Verdict: no blocking findings. Scope: new commits since No findings clear the reporting bar this round. Findings ledger (all rounds)
Advisory per-push review (round 4) generated by ai-review — verify findings before acting. |



Fixes #454
What
Failure classification
_raise_for_body_errorand_parse_token_responseraiseOAuthTokenError(RuntimeError). It carries the RFC 6749 §5.2errorcode (only a string of up to 64 characters is kept) and the HTTPstatus. The message is unchanged, and being aRuntimeErrorsubclass, existing handlers keep working._refresh_error_is_deadlists the transient cases narrowly:temporarily_unavailable/server_error;--max-message-size, an undecodable body.Everything else counts as dead, as every failure did before:
invalid_grant,invalid_client, other 4xx, a 200 without an access token, an expired client secret, an invalid cached endpoint.fix(oauth): send scope on refresh, keep the endpoint query, usable URL without a browser #452's scope-less retry now runs only after a dead-looking answer. A 503 is not the scope's fault, and a scope-less retry could turn it into Entra's
AADSTS90009and a deleted token.ensure_tokenkeeps the token on a transient failure and logs that. It then falls through to the interactive flow, so the browser still opens for this run, exactly as before; the kept token only helps the next attempt. Under--oauth-eager's non-interactive probe it returnsNoneinstead. This is deliberate: a transient AS failure does not prove the browser path will fail too.A dead grant is deleted while the refresh lock is still held, and only if the store still holds the failed refresh AND access token (
delete_token(..., expected_refresh_token=..., expected_access_token=...)). The access token catches an AS that does not rotate the refresh token.delete_tokennow returns whether it removed anything.Cross-process serialization
token_store.refresh_lock()is a separate lock file,tokens.json.refresh.lock, because_store_lockis not re-entrant andsave_tokentakes it._store_lock's body moved into_file_lock(name, wait)with every existing guard:O_NOFOLLOW,O_NONBLOCK, the fchmod re-tighten, the warn-once on a symlink or FIFO, and proceeding unlocked on lock trouble._store_lockstays blocking.refresh_lockwaits at most 30 s (LOCK_NBpolling, orLK_NBLCKon Windows) and yields whether it got the lock. Running out never leads to an unlocked exchange, because the holder may just be slow (its round trip can exceed 30 s). The caller re-reads the store, returns a token stored meanwhile, or else reports a transient failure. Only the degrade paths (no lock primitive, a planted special file) proceed unlocked, as_store_lockalways has._refresh_cached_token_ex(seen_access_token=...)takes the lock and re-reads the store. If the token there differs from the one the caller holds (ensure_tokenpasses its own; the 401 path reads the store first), another process refreshed and its token is returned without an exchange. Otherwise the exchange spends the latest stored refresh token, so two processes never spend the same rotating refresh token. Proactive refresh needs no jitter.ensure_token's--oauth-resource/--no-resource-indicatorreconcile now saves onto a fresh read under the lock, rather than writing back a possibly stale copy over a just-rotated refresh token.refresh_cached_token(used by the relay's 401 path incli.py) keeps its "None on failure" contract and gets the lock too.Out of scope: re-running the interactive flow when a refresh token dies mid-session.
Tests
OAuthTokenError.erroris extracted from a JSON 400, an in-body 200 and a form-urlencoded 400 (GitHub legacy), and is still aRuntimeErrorwith the same message.ensure_token:ConnectError, 503, 429 andtemporarily_unavailablekeep the token;invalid_grantandinvalid_clientdelete it; a token saved by another process between the failed exchange and the delete survives.nullcontext, this test fails with two POSTs.DecodingError, keep the token. A 503 with a scope set is not retried without scope.token_store: compare-and-delete on the refresh token and on the access token;refresh_lock(wait=0.1)yields False while another holder keeps it; with locking unavailable it yields True (unlocked, as before).test_server.py::test_concurrent_refresh_single_use, which also flakes locally on macOS onmain.Docs
Two WORKAROUNDS entries (claude-code#91641/#93537; mcp-remote#348/#349 and typescript-sdk#2915), and the CLAUDE.md
token_store.pynote.🤖 Generated with Claude Code