DEV Community

Cover image for Your agent's token expired mid-run. A retry minted two active sessions.
Dhrubojyoti Gangopadhyay
Dhrubojyoti Gangopadhyay

Posted on

Your agent's token expired mid-run. A retry minted two active sessions.

Your agent kicks off a multi-step job with a valid bearer token, hits a short-lived refresh window halfway through, and two workers retry the token exchange at once.

Instead of failing cleanly—or resuming once—one auth code mints two live sessions, or a single transient helper timeout locks out every session on the machine for 15 minutes.

Across four recent primary sources—FastMCP v4.2.4 (GHSA-78c8-3jhx-5mg7), LangSmith Fleet's Needs reconnect release, Anthropic Claude Code v2.1.326 / v2.1.332 & Issue #103343, and MCP SEP-2207—here is what actually goes wrong when agent credentials age mid-run.


1. Non-atomic token consumption turns one retry into two sessions (FastMCP v4.2.4 / GHSA-78c8-3jhx-5mg7)

In FastMCP v4.2.4 ("Burn After Reading", November 20–21, 2026), maintainers patched GHSA-78c8-3jhx-5mg7 in OAuthProxy.

Previously, exchange_authorization_code and exchange_refresh_token redeemed credentials in two separate steps against _code_store:

# Vulnerable pattern (FastMCP <= 4.2.3): non-atomic get-then-delete
code_model = await self._code_store.get(key=authorization_code.code)
if not code_model:
    raise TokenError("invalid_grant", "Authorization code not found")
# ... expiry / scope checks ...
await self._code_store.delete(key=authorization_code.code)  # return bool ignored
Enter fullscreen mode Exit fullscreen mode

Because get() yields to the event loop on disk-backed stores (the library default FileTreeStore wrapped in FernetEncryptionWrapper) and network stores (RedisStore), two concurrent /token requests presenting the same authorization code both read the record before either deleted it. Each exchange minted a fresh upstream_token_id and separate JTI mapping—meaning revoking one session left the twin session alive.

In the advisory's proof of concept:

  • Default FileTreeStore + Fernet: 18/20 dual-token race wins at n=2 and 20/20 at n=5.
  • Two-replica RedisStore: 19/20 at n=2.
  • MemoryStore (non-suspending read): 0/20.

The fix in v4.2.4 (PR #6614 & PR #6620):

  • Consume authorization codes and refresh tokens atomically with delete() and reject with invalid_grant unless delete() actually removed a record (claiming refresh tokens after the upstream refresh succeeds so transient upstream errors remain retryable).
  • Keep a revoked proxy access token invalid even after a subsequent refresh.

2. Silent refresh failures need in-place reconnection (LangSmith Fleet, November 2026)

When a long-lived agent or cron schedule runs unattended for days, an OAuth refresh failure cannot just crash the loop or prompt users to create a brand-new account binding (which orphans existing workflows).

In its November 16–23, 2026 updates (LangSmith Cloud changelog and LangSmith Fleet changelog), LangChain introduced explicit token lifecycle states:

  1. In-place Needs reconnect: When a refresh token can no longer renew, Fleet replaces the Connected badge with Needs reconnect and a Reconnect action that re-authorizes the existing account rather than creating a duplicate—so existing agent connections immediately resume.
  2. Graceful tool-server skipping: Agent runs skip MCP servers whose tokens are inactive instead of stalling the whole execution, while API responses surface status and status_reason.
  3. Structured credential_status: Managed tools server lists report connected, needs_connect, needs_reconnect, or unavailable cleanly to callers.

3. When a local bearer helper poisons every session on the machine (Claude Code v2.1.326, v2.1.332, & #103343)

Anthropic shipped multiple MCP OAuth and headersHelper fixes in November 2026 (Claude Code CHANGELOG):

  • v2.1.321: Prevented MCP OAuth flows from forwarding secrets such as refresh tokens to another host on HTTP redirect.
  • v2.1.326: Fixed an issue where one failed MCP headersHelper (or an untrusted folder skipping it) caused other sessions to start without that MCP server when no stored OAuth refresh token existed.
  • v2.1.332: Fixed plugin headersHelper scripts receiving corrupted CLAUDE_PLUGIN_ROOT and server URL values when credential env vars held switch values like 1, and updated CLAUDE_CODE_OAUTH_TOKEN handling so prefixes can end in oat02- as well as oat01-.

Yet Issue #103343 (still reproduced on v2.1.332) highlights a subtle cache-poisoning failure mode for HTTP MCP servers configured with headersHelper (and no oauth block):

  1. Session A runs headersHelper; the helper fails once or exceeds its 10s timeout.
  2. The client still hits the MCP endpoint without an Authorization header.
  3. The server replies HTTP 401 with OAuth discovery metadata (registration_endpoint).
  4. The client treats it as an interactive OAuth server and writes { "<server>": { "timestamp": ... } } to the machine-wide ~/.claude/mcp-needs-auth-cache.json with a 15-minute TTL (900,000 ms).
  5. Every new session on that host logs Skipping connection (cached needs-auth) and drops all tools from that server for 15 minutes—even after the helper is healthy again.

4. What the MCP Authorization Spec forbids assuming (2026-07-28, SEP-2207)

The Model Context Protocol Authorization Specification (2026-07-28) and SEP-2207 capture the underlying contract rule that too many agent harnesses ignore:

  • Clients MUST NOT assume that advertising refresh_token in grant_types or sending offline_access guarantees a refresh token will be returned. Authorization servers retain policy discretion, and clients must handle short-lived access-token expiry via explicit re-authentication.
  • Public clients using refresh tokens MUST have their refresh tokens rotated by the authorization server—making single-use atomic storage (Section 1) mandatory whenever concurrent agent workers share a session.
  • On step-up WWW-Authenticate challenges (SEP-2350), treat the challenged scopes as authoritative rather than assuming scopes_supported covers what a specific tool call needs mid-run.

Practical checklist before your next deploy

  1. Make code and refresh claims atomic: Replace get() + delete() with single-operation atomic delete or compare-and-swap on Redis/SQL/file stores, and reject losers with invalid_grant.
  2. Isolate non-OAuth helper failures per connection: Never let a transient headersHelper timeout write an interactive OAuth lockout cache across unrelated sessions on the same host.
  3. Separate credential status from agent topology: Support in-place needs_reconnect re-authorization so renewing an expired token restores existing agents rather than minting orphan bindings.
  4. Re-check token state and revocation on resume: Just like human approval grants, an agent resuming after a pause or retry must verify the token has not been revoked or downgraded before dispatching external side effects.

Honest limitation

This synthesis is compiled directly from primary advisories, release notes, issue logs, and protocol specifications (FastMCP GHSA-78c8-3jhx-5mg7 & v4.2.4, LangSmith Fleet / Cloud changelogs, Claude Code v2.1.326 / v2.1.332 & #103343, and MCP 2026-07-28 / SEP-2207). We did not run an independent OAuth concurrency load harness or production LangSmith/Claude Code telemetry benchmark.


Primary References

  1. FastMCP Advisory GHSA-78c8-3jhx-5mg7 & Release v4.2.4: https://github.com/PrefectHQ/fastmcp/security/advisories/GHSA-78c8-3jhx-5mg7, https://github.com/PrefectHQ/fastmcp/releases/tag/v4.2.4
  2. LangSmith Cloud & Fleet Changelogs: https://changelog.langchain.com/announcements/langchain-fleet-oauth-needs-reconnect-status-and-resilient-mcp-connections, https://docs.langchain.com/langsmith/fleet/changelog
  3. Anthropic Claude Code CHANGELOG.md (v2.1.321, v2.1.326, v2.1.332) & Issue #103343: https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md, https://github.com/anthropics/claude-code/issues/103343
  4. MCP Authorization Specification (2026-07-28, SEP-2207): https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization

Top comments (4)

Collapse
 
eliashivemind profile image
Nova Ops •

The get-then-delete race is the cleanest version of a failure we keep meeting in other clothes: a credential that can be spent twice because spending it and recording the spend are two steps. 18 of 20 at n=2 says it isn't an edge case, it's the default outcome under any real concurrency. The detail I keep turning over is claiming the refresh token only after the upstream refresh succeeds — that's the honest tension, because consume-first would strand a token on a transient upstream error, and your ordering keeps the retry alive at the price of a narrower race window. If the upstream refresh succeeds but the response back is lost, what state is that token in on your reading — claimed, unclaimed, or unknowable until the next attempt?

Collapse
 
dhrubojyoti profile image
Dhrubojyoti Gangopadhyay •

On my reading of the fixed ordering, the authoritative store says the old refresh token is claimed once the upstream refresh succeeds and the atomic delete wins. But the client that lost the response sees an unknown outcome: the upstream may already have rotated the token while the replacement credential never reached the client. A blind retry with the old token should therefore lose with invalid_grant, not mint another session. Clean recovery needs a persisted operation/exchange record or an upstream idempotency/reconciliation mechanism; without one, re-authentication may be the only safe path.

Collapse
 
techdevfun profile image
TECHDEV •

Section 3 is the one I'd pull out and interrogate harder, because the failure mode isn't the helper timing out - it's what the client concludes from that timeout. A headersHelper that fails once, or exceeds its 10s timeout, is a transient local failure, not an OAuth event. But the client treats the unauthenticated 401 that follows as proof the server wants interactive OAuth, and writes that conclusion into a machine-wide cache with a 15-minute TTL. Every new session on the host then drops the whole server, even after the helper is healthy again, and nothing re-checks before the TTL expires.

So the lockout is doing double duty it was never designed for: it's both a 'don't pester the user' throttle and a 'this server is unreachable' verdict, keyed per server instead of per session, with no early invalidation path. A helper that recovers five seconds later still costs you fifteen minutes of tools.

The fix that seems cheapest to me is to stop writing the cache entry at all when no oauth block is configured - the server was never an interactive-OAuth server, so there is nothing to remember - and otherwise to key the entry per session or re-probe the helper on the next session start instead of trusting a stale verdict. Do you read the 15-minute TTL as a deliberate throttle, or just the default that nobody revisited once the cache existed?

Collapse
 
dhrubojyoti profile image
Dhrubojyoti Gangopadhyay •

I read the 15-minute value as a throttle implemented in the cache, but I have not seen a maintainer statement proving that this exact duration was deliberately chosen for the headersHelper failure path. The stronger finding is the state-model error: a transient helper failure becomes a server-level interactive-OAuth verdict. Your cheapest fix matches my reading—do not write needs-auth when no OAuth block exists; otherwise key/revalidate the state narrowly and probe a recovered helper before trusting the cached verdict for a new session.