# What happens when an instance resumes an MCP SSE stream across an OAuth 2.1 token rotation boundary **Date of Record:** 2026 November 20 **Scope:** Applies to MCP servers using the HTTP-native transport where a client holds a long-lived Server-Sent Events stream with `Last-Event-ID` resumption, and authorization is enforced via OAuth 2.1 access tokens bound to a resource indicator (RFC 8707). Does not apply to stdio transports, or to SSE streams that are never resumed across a token lifetime. ## Core Distinction There are two distinct identities in an MCP HTTP session: the *stream identity* (the SSE session, keyed by an event ID cursor and a server-side session handle) and the *authorization identity* (the OAuth 2.1 access token, scoped to a resource indicator). Most implementations treat these as orthogonal — the stream is a transport concern, the token is a security concern. They are not orthogonal. When a token rotates mid-stream, the resumption path re-authenticates under a *new* authorization identity while attempting to rejoin an *old* stream identity. The failure is not that resumption is rejected; it's that resumption can succeed under an authorization context that never had the right to observe the buffered events it is about to receive. The invariant that is violated: **an event delivered on a resumed stream must be authorized under the same principal and same resource scope that was in force when the event was enqueued, not merely the principal presenting the resumption request.** ## What Was Observed A client opens an SSE stream to an MCP server. The server issues `event: endpoint` and then streams `message` events, each with an `id:` field. The client's access token (audience `mcp://tools.internal`, per its resource indicator) has a 15-minute TTL. The stream is idle for 20 minutes — a long-running tool call is in flight, or the agent is parked awaiting human input. The token expires. The client's OAuth 2.1 client refreshes and obtains a new access token. Critically, the new token may be minted with a *different* resource indicator if the client's resource resolution is dynamic, or it may be minted under a different subject if the refresh crosses an identity broker, or — the common case — the new token is valid but the server's session store still associates the SSE session handle with the *old* token's `sub` and `aud` claims. The connection drops (proxy idle timeout, not token expiry). The client reconnects with `Last-Event-ID: 4421` and `Authorization: Bearer `. The server's resumption handler: 1. Validates the new token (succeeds). 2. Looks up the session by the event ID cursor (succeeds — session store keyed by stream, not by principal). 3. Replays events `4422..N` from the buffer. Step 2 is the bug. The session lookup is keyed on the stream cursor, and the authorization check in step 1 is evaluated against the *presented* token, not the token under which the session was established. If the new token belongs to a different principal — a delegated sub-agent, a rotated service identity, a token whose `aud` now points at a broader resource — the replay hands that principal events it was never entitled to. The buffered events may contain tool results, partial model output, or resource contents scoped to the original principal. A subtler variant: the token is for the *same* principal but a *narrowed* resource indicator (the refresh was downscoped). The replay succeeds, but the events being replayed were produced under a broader scope. The client now holds data under a token that does not authorize that data's resource. Downstream, when the agent forwards those events to another MCP server, the propagation carries a scope mismatch that surfaces only at the second hop. ## Condition of Validity The failure is bounded by three conditions, all of which must hold: - The SSE buffer retains events across the token's lifetime (buffer TTL > token TTL). If the buffer is flushed on token expiry, no cross-identity replay is possible. - The session store is keyed by stream identity (event cursor / session handle) rather than by `(principal, resource, stream)` tuple. - The resumption handler authorizes the *request* but does not re-authorize the *buffer contents* against the original enqueue-time context. When any one of these is absent, the failure does not manifest. This is why it is easy to miss in testing: short-lived buffers and same-principal refresh flows mask it entirely. It appears in production when a buffer is lengthened for reliability (a common tuning response to flaky streams) and when identity brokers or delegated agents enter the picture. ## Decision Boundary The architectural guardrail is to make resumption a *two-key* operation. The stream cursor is one key; the authorization context captured at stream establishment is the other. On resume: - If the presented token's `(sub, aud, scope)` matches the captured context, replay proceeds. - If it does not match, the server MUST NOT replay. It must terminate the old stream with a distinct error (not a generic 401) and require the client to open a fresh stream, accepting that buffered events are lost. The loss is the correct outcome. Buffered events are not a durable log; they are a reliability affordance scoped to a single authorization context. Treating them as resumable across contexts converts a transport convenience into a cross-principal data channel. The second boundary: resource indicator comparison must be on the *canonicalized* indicator, not the raw string. `mcp://tools.internal` and `mcp://tools.internal/` and `mcp://TOOLS.internal` are the same resource to a human and different strings to a naive equality check. A resumed stream under a re-cased indicator will either wrongly reject (availability failure) or, if the check is case-insensitive but the buffer keying is case-sensitive, wrongly accept under a mismatched key. Canonicalize both sides before comparison, and key the session store on the canonical form. ## Operational Effect In practice, the observable symptom is not a security alert. It is a *consistency* bug: an agent resumes a stream, receives replayed events from a prior principal's context, and continues its reasoning loop with state it should not have. The agent's episodic memory now contains tool results attributed to the wrong session. If the agent later distills that episode into semantic memory, the contamination persists past the stream's lifetime. The failure compounds: a single cross-identity replay can poison a long-horizon memory store. The mitigation is defense in depth. First, bind the session store key to `(canonical_resource, sub, cursor)`. Second, tag every buffered event with the authorization context at enqueue time and re-check on replay. Third, emit a distinct, non-retryable error code on context mismatch so clients do not loop on resumption attempts. Fourth, cap buffer TTL at token TTL — a buffer that outlives its authorization context is a liability, not an asset. ```python from dataclasses import dataclass from typing import Optional import time class ResumptionContextMismatch(RuntimeError): """Raised when a resumed SSE stream presents an authorization context that does not match the context captured at stream establishment.""" pass class TokenExpired(RuntimeError): pass @dataclass(frozen=True) class AuthContext: sub: str canonical_resource: str scope: str def matches(self, other: "AuthContext") -> bool: return ( self.sub == other.sub and self.canonical_resource == other.canonical_resource and self.scope == other.scope ) @dataclass class BufferedEvent: event_id: int payload: dict enqueued_under: AuthContext enqueued_at: float def canonicalize_resource(indicator: str) -> str: # RFC 8707 resource indicators are URIs; normalize scheme/host casing # and strip a single trailing slash so equality is stable. s = indicator.strip() if s.endswith("/") and s.count("/") > 2: s = s[:-1] scheme, rest = s.split("://", 1) host, *path = rest.split("/", 1) normalized = f"{scheme.lower()}://{host.lower()}" if path: normalized += "/" + path[0] return normalized def resume_stream( cursor: int, presented: AuthContext, session_context: Optional[AuthContext], buffer: list[BufferedEvent], token_expires_at: float, now: Optional[float] = None, ) -> list[BufferedEvent]: now = now if now is not None else time.time() if token_expires_at <= now: raise TokenExpired( f"token for sub={presented.sub} expired at {token_expires_at}" ) if session_context is None: raise ResumptionContextMismatch( f"no session context recorded for cursor={cursor}; " "refusing to replay from an unbound buffer" ) if not session_context.matches(presented): # Do NOT fall through to replay. The buffer was produced under a # different authorization context and is not transferable. raise ResumptionContextMismatch( "resumption authorization context does not match stream " f"establishment context: session={session_context!r} " f"presented={presented!r}" ) replay = [e for e in buffer if e.event_id > cursor] for e in replay: if not e.enqueued_under.matches(presented): raise ResumptionContextMismatch( f"event {e.event_id} was enqueued under {e.enqueued_under!r} " f"but resumption presents {presented!r}" ) return replay ```