# Why does an instance lose tool-scope authorization when an SSE session resumes mid-stream after a token refresh **Date of Record:** 2026 December 3 **Scope:** Applies to MCP servers exposing HTTP-native streaming transport (SSE) with resumable sessions via `Last-Event-ID` and per-tool OAuth scope negotiation, where the client can re-establish a stream after a disconnect. Does not apply to stdio transport, non-resumable one-shot HTTP, or servers that bind tool scopes to the transport session only. ## Core Distinction The failure is not "the token expired." The failure is that **resumption restores the transport event cursor but not the authorization context that was negotiated at stream-open time**. MCP over SSE carries two orthogonal pieces of state across a reconnect: 1. The **event cursor** (`Last-Event-ID`), which the server uses to replay buffered SSE frames — this is transport-layer continuity. 2. The **per-tool OAuth scope grant**, which is bound to the access token presented at the original `GET /sse` handshake and is *not* carried in the SSE frame stream. A resumable session treats these as independent. When a client reconnects with a refreshed token after a `401`/`403` mid-stream, the server replays events from the cursor — but the replayed `tool_call` frames were authorized under the *old* scope set. If the refreshed token has a narrower or differently-scoped grant (common when refresh exchanges down-scope, or when the AS returns a token for a different `resource` audience), the server will either replay frames the current token cannot honor, or accept the reconnect and then fail the *next* tool invocation with a scope error that surfaces far from its cause. The invariant that must hold: **the scope set under which a replayed frame was produced must be reconstructible at replay time, or the replay must be refused.** Most implementations violate this because SSE replay is stateless with respect to OAuth. ## What Was Observed A client opens `GET /sse` with an access token carrying scopes `tools:read tools:write files:rw`. The server opens an SSE session, assigns `session_id=S`, and streams events with monotonically increasing `id` values. At event `id=47`, the client invokes a tool that requires `files:rw`; the server begins a long-running operation and emits partial-progress events `48..52`. The access token expires at T+900s. The client's SSE connection drops (network blip) at `id=52`. The client refreshes its token. The authorization server, per its policy, issues a refresh token exchange that returns a token scoped to `tools:read` only — because the refresh grant was registered against a *different* client registration that never requested `files:rw`, or because the AS applies scope-downscoping on refresh (RFC 6749 §6 allows the AS to issue a narrower scope than requested). The client reconnects: `GET /sse` with `Last-Event-ID: 52` and the new token. The server: - Validates the new token — passes (it is a valid `tools:read` token). - Looks up session `S`, finds the cursor at 52, and replays buffered frames `48..52` from the ring buffer. - The replayed frames include the partial-progress events for the `files:rw` operation, and a final `tool_result` frame for a tool the new token is not authorized to invoke. The server has now delivered, over an authenticated channel, the *output* of a tool invocation that the presented credential could not itself authorize. If the tool output contains file contents, this is a scope-confused data exfiltration path: a `tools:read`-only token received `files:rw`-derived data because the frame was authorized at production time, not at replay time. A second, quieter variant: the client reconnects *without* `Last-Event-ID` (some SDKs drop it on refresh). The server treats this as a fresh session, assigns `session_id=S'`, and the client now has two live sessions — `S` still buffering events, `S'` fresh. The in-flight `files:rw` operation under `S` completes and its result is buffered into `S`'s ring buffer forever, never delivered, and `S` is never garbage-collected because the server keys GC on client disconnect events it never saw (the disconnect was a TCP reset, not a clean close). This is a session leak with an authorization shadow: an orphaned session holding a `files:rw`-authorized operation result, reachable by anyone who can present *any* valid token and guess or replay `session_id=S`. ## Condition of Validity The resumption-and-replay model is only sound when the following holds at the moment of replay: - `scope(replay_token) ⊇ scope(original_token_at_frame_production)` for every frame in the replay window, **or** - the server refuses to replay frames whose producing scope is not a subset of the replay token's scope, and instead emits a terminal `session_invalidated` event forcing a fresh session. This requires the server to **persist the scope set alongside each buffered event** (or alongside the session, if scopes are fixed for the session's lifetime). Most implementations persist only the event payload and `id`. The scope is assumed to be a session-level property recoverable from the session record — but the session record stores the *original* token's scopes, and the reconnect presents a *different* token. The comparison is never made. The condition also requires that the authorization server's refresh behavior be *bounded*: if refresh can downscope, the client must treat a downscoped refresh as a session-invalidating event and abandon the SSE session rather than resume it. MCP clients generally do not inspect the scope of the refreshed token before resuming. ## Decision Boundary The decision boundary is at the reconnect handler, and it is a three-way branch that implementations collapse to two: 1. **Cursor present, token scopes ⊇ session scopes** → replay from cursor. Sound. 2. **Cursor present, token scopes ⊂ session scopes** → *must* refuse replay and invalidate session. Implementations instead replay (the bug) or silently drop the cursor and open fresh (the leak). 3. **Cursor absent** → open fresh session *and* explicitly terminate the prior session keyed by the authenticated principal, not by clean-close. Implementations rely on TCP close and leak. The boundary is sharp because the two states (2) and (3) are indistinguishable from the server's perspective if it does not persist scope-per-event: in both cases the presented token does not obviously match the session's recorded scope, and the server has no per-frame scope to compare against. The guardrail is to make scope-per-session an explicit, compared field at reconnect, and to make session termination principal-keyed rather than connection-keyed. ## Operational Effect Without the guardrail, the observable effects are: - **Scope-confused replay**: a downscoped token receives data produced under a broader scope. This is a silent authorization widening at the transport layer, invisible to per-tool scope checks because the tool was already invoked. - **Orphaned authorized sessions**: sessions holding in-flight broad-scope results persist after TCP-reset disconnects, reachable by `session_id` replay under any valid token. - **Delayed scope errors**: when replay is accepted but the *next* tool call fails scope validation, the error surfaces at the tool layer with no reference to the token-refresh event that caused it, making root-cause analysis expensive and encouraging retry loops that re-trigger the same path. The bounded fix is to persist `scopes_at_production` per buffered event, compare at replay, refuse on non-subset, and key session GC on authenticated principal with a short TTL independent of connection liveness. The code below encodes the reconnect decision as an explicit invariant check that raises on the unsafe branch rather than silently replaying. ```python from dataclasses import dataclass, field from typing import Optional class ScopeReplayViolation(RuntimeError): """Raised when an SSE resume would replay frames produced under scopes the reconnecting token does not hold.""" @dataclass class BufferedEvent: event_id: int payload: dict scopes_at_production: frozenset @dataclass class SSESession: session_id: str principal: str session_scopes: frozenset buffer: list = field(default_factory=list) def append(self, event_id: int, payload: dict, scopes: frozenset) -> None: self.buffer.append(BufferedEvent(event_id, payload, scopes)) def resume_session( session: SSESession, presented_scopes: frozenset, last_event_id: Optional[int], ) -> list: """Return the frames to replay, or raise if the resume is unsafe. Invariant: every replayed frame's producing scopes must be a subset of the presented token's scopes. A downscoped refresh cannot resume a session that produced broader-scope frames. """ if last_event_id is None: # No cursor: caller must open a fresh session and terminate this one # keyed by principal, not by connection close. return [] replay = [e for e in session.buffer if e.event_id > last_event_id] for ev in replay: if not ev.scopes_at_production.issubset(presented_scopes): raise ScopeReplayViolation( f"session={session.session_id} event={ev.event_id}: " f"produced under {sorted(ev.scopes_at_production)} " f"but reconnect token holds {sorted(presented_scopes)}; " f"refusing replay, invalidate session" ) return [ev.payload for ev in replay] ```