# Why does an instance lose tool authority when an MCP Streamable HTTP session resumes across a re-issued OAuth 2.1 access token **Date of Record:** 2026 November 23 **Scope:** Applies to MCP clients/servers using Streamable HTTP transport with `Mcp-Session-Id` resumption and OAuth 2.1 resource-bound bearer tokens, where the authorization server may rotate access tokens mid-session. Does not apply to stdio transport, nor to sessions whose tokens never expire or rotate within a session lifetime. ## Core Distinction The failure is not token expiry and it is not session expiry. It is the *decoupling* of two independently-rotating identifiers that the transport assumes are bound but never enforces on resume: - **Session authority**: the `Mcp-Session-Id` header, which the server uses to look up per-session server-side state (subscriptions, in-flight SSE streams, negotiated capabilities, pending `sampling`/`roots` callbacks). - **Resource authority**: the OAuth 2.1 access token, whose `aud` (resource indicator) and `scope` are validated per-request against the MCP server's canonical resource URI. Streamable HTTP lets a client resume a dropped SSE stream or a terminated POST by replaying `Mcp-Session-Id` with `Last-Event-ID`. When the client's token rotated between disconnect and resume (because the AS issued a new short-lived token, or the client refreshed proactively), the *session* is still valid server-side but the *token* now carries a different `jti`, a possibly narrower `scope`, and — the sharp edge — a `aud` that the server's resource-binding check compares byte-for-byte against a value it cached at session creation. The resume succeeds at the transport layer and fails at the authorization layer, but because MCP returns tool errors as JSON-RPC results rather than HTTP 401s inside an established stream, the client interprets the failure as a *tool execution error*, not an *auth failure*. The agent then retries the tool call with the stale session, compounding the mismatch. ## What Was Observed A client agent held a session `S` created at T0 with token `A` (aud=`https://mcp.example.com/v1`, scope `tools:read tools:write`). At T+40m the SSE stream for a long-running `execute_sql` tool call dropped (idle proxy timeout). At T+41m the client's token store rotated to token `B` (aud=`https://mcp.example.com`, scope `tools:read` — the AS canonicalized the resource URI by stripping the version path and the write scope was dropped by policy narrowing). The client resumed: ``` GET /mcp HTTP/1.1 Mcp-Session-Id: S Last-Event-ID: 8812 Authorization: Bearer B ``` Server behavior observed: 1. The session lookup on `S` succeeded — server-side state intact, in-flight tool result buffered. 2. The request-level resource check compared `B.aud` (`https://mcp.example.com`) against the session-cached `S.resource` (`https://mcp.example.com/v1`) and treated the mismatch as a *non-fatal* warning, because the session was already authenticated. It replayed the buffered SSE event. 3. The replayed event contained the tool result for `execute_sql`, but the subsequent `tools/call` for the *next* statement was rejected by the server's per-call scope check (`tools:write` absent in `B`) — returned as a JSON-RPC error object *inside* the 200 response stream. 4. The client's error classifier saw a JSON-RPC `-32603` and retried the same call 3× against session `S`, each time with token `B`, each time failing identically. No 401 was ever emitted, so the client never triggered its refresh-and-rebind path. Net effect: the agent lost `tools:write` authority silently, retried into a loop, and reported "tool failure" to its orchestrator instead of "authorization scope narrowed — rebind required." ## Condition of Validity The invariant that *should* hold: **a session's resource binding is a function of the current request's token, re-validated on every resume, not a property frozen at session creation.** The failure occurs precisely when a server caches `session.resource` and `session.scope` at creation and uses them as the authoritative binding for resumed requests, treating the presented token only as an identity check. This is a common and tempting optimization: it avoids re-running resource-indicator comparison and scope intersection on every SSE reconnect. The boundary is sharp: - If the token's `aud` and `scope` are unchanged across resume → no observable failure; the cache is correct. - If the token rotates but the AS preserves `aud` and scope → no failure. - If the token rotates *and* `aud` is re-canonicalized or scope narrows → the cached binding is now a lie, and every subsequent tool call inherits the stale authority. The invariant only holds when the server either (a) re-validates `aud`/`scope` on every request including resumes, or (b) invalidates the session on any token `jti` change, forcing a clean re-handshake. Servers that do neither are silently permissive on resume and silently restrictive on subsequent calls — the worst of both. ## Decision Boundary The architectural guardrail is a **binding-equivalence check at resume time** with a defined divergence policy: 1. On every request carrying `Mcp-Session-Id`, recompute the effective authority tuple `(aud, scope_set, jti)` from the presented token. 2. Compare against the session's stored tuple. Define three outcomes: - **Equal** → proceed, replay buffered events. - **Subset** (new scope ⊂ old scope, same aud) → **downgrade the session**: update stored tuple, replay, but mark any buffered tool results whose originating call required now-absent scopes as `stale_authority` and require client re-issue. - **Disjoint or aud-mismatch** → **terminate the session** with HTTP 401 + `WWW-Authenticate: Bearer error="invalid_token", resource=""`, do *not* replay buffered events, force full re-handshake. The boundary decision the server must make explicitly is: *is a scope-narrowing token rotation a session-continuation event or a session-termination event?* Treating it as continuation (the observed default) is what produces the silent authority loss. Treating it as termination is correct but requires the client to distinguish a resume-401 from a call-level-401 and re-establish rather than retry. The corresponding client-side guardrail: never classify a JSON-RPC error inside an established SSE stream as a terminal tool failure without checking whether the error `data` field carries an authorization marker. If the server emits `{"code":-32603,"data":{"mcp_error":"insufficient_scope","required":"tools:write"}}`, the client must route to re-authorization, not retry. ## Operational Effect The observable signature in logs is a **401-free authority loss**: the session stays `active`, the token stays `valid`, and tool calls fail with application-level errors whose rate correlates with token rotation events rather than with token expiry. Agents that key their retry logic on HTTP status codes will loop indefinitely; agents that key on JSON-RPC error codes will loop unless the server annotates scope failures distinctly. The downstream continuity consequence is severe for stateful tools: a tool that performed a partial write under token `A` (scope `tools:write`) and is then re-invoked under token `B` (scope `tools:read`) will fail its *second* step while its *first* step's side effect persists — the agent's episodic memory records "write succeeded, follow-up failed," which is a corrupt episodic trace. On cold-start distillation, this trace becomes a false semantic memory that the tool is unreliable, rather than the true fact that authority narrowed mid-task. The durable fix has two halves: server-side binding re-validation at resume with explicit downgrade/terminate semantics, and client-side authority-aware error classification. Neither alone closes the loop — a re-validating server that still returns `-32603` without an auth marker leaves the client unable to distinguish scope loss from tool bug. ```python import time from dataclasses import dataclass, field from typing import Optional class BindingDivergenceError(RuntimeError): """Raised when a resumed session's token authority diverges from the authority under which the session was established.""" pass @dataclass class Authority: aud: str scopes: frozenset jti: str @dataclass class Session: sid: str bound: Authority created_at: float buffered_events: list = field(default_factory=list) active: bool = True class StreamableHTTPSessionRegistry: def __init__(self, canonical_resource: str): self.canonical_resource = canonical_resource self._sessions: dict[str, Session] = {} def create(self, sid: str, token: Authority) -> Session: if token.aud != self.canonical_resource: raise BindingDivergenceError( f"session {sid} creation rejected: token aud={token.aud!r} " f"!= canonical resource {self.canonical_resource!r}" ) s = Session(sid=sid, bound=token, created_at=time.time()) self._sessions[sid] = s return s def resume(self, sid: str, presented: Authority, last_event_id: Optional[str]): s = self._sessions.get(sid) if s is None or not s.active: raise BindingDivergenceError(f"session {sid} unknown or terminated") if presented.aud != s.bound.aud: # aud re-canonicalization is never a continuation event. s.active = False raise BindingDivergenceError( f"session {sid} aud mismatch on resume: " f"bound={s.bound.aud!r} presented={presented.aud!r}; " f"terminating session, client must re-handshake" ) if presented.scopes == s.bound.scopes: return self._replay(s, last_event_id) if presented.scopes < s.bound.scopes: # Downgrade: update binding, but any buffered result whose # originating call required a now-absent scope is stale. lost = s.bound.scopes - presented.scopes s.bound = presented stale = [e for e in s.buffered_events if e.get("required_scope") in lost] if stale: raise BindingDivergenceError( f"session {sid} downgraded, lost scopes {sorted(lost)}; " f"{len(stale)} buffered events have stale_authority and " f"must be re-issued by the client" ) return self._replay(s, last_event_id) # Scope expansion on resume: token was re-scoped upward; this is # not a legitimate resume of the same authority lineage. raise BindingDivergenceError( f"session {sid} scope expansion on resume " f"{sorted(s.bound.scopes)} -> {sorted(presented.scopes)}; " f"client must re-handshake, not resume" ) def _replay(self, s: Session, last_event_id: Optional[str]): if last_event_id is None: return [] return [e for e in s.buffered_events if e.get("id", "") > last_event_id] ```