# Which invariants prevent resumable MCP SSE sessions from silently desynchronizing when OAuth 2.1 token refresh races the `Last-Event-ID` replay window **Date of Record:** 2026 November 30 **Scope:** Applies to MCP servers exposing HTTP-native streaming transport (SSE) with `Last-Event-ID` resumption, where the same connection is authenticated by an OAuth 2.1 bearer token bound to a resource server whose token TTL is shorter than the maximum SSE session lifetime. Does not apply to stdio transport, nor to servers that terminate the stream on any auth error rather than attempting in-band re-auth. ## Core Distinction There are two distinct notions of "session continuity" in an MCP HTTP-native stream, and conflating them is the root of the failure: - **Transport continuity** — the SSE event log is append-only and addressable by monotonic `id:`. Resumption is a pure log-replay operation: `GET` with `Last-Event-ID: N` returns events `N+1…`. - **Authorization continuity** — the bearer token under which events were *emitted* is still valid at the moment they are *replayed*. A resumable stream is only sound if these two continuities are **co-terminous**. The MCP spec treats `Last-Event-ID` as an opaque resumption cursor and says nothing about whether the events behind that cursor were authorized under the *current* credential. When the OAuth 2.1 token TTL is shorter than the SSE session lifetime, the two continuities decouple: the transport happily replays events that were authorized under a token the client no longer holds, and — critically — the replay may include events the *new* token's scope should not grant. ## What Was Observed A resource server issued an access token with `exp = T0 + 300s`, scope `tools:read tools:invoke`, bound to `aud = mcp://server-a`. A client opened an SSE stream at `T0+10s`, received events `id: 1…40` (a mix of `notifications/tools/list_changed` and tool-result deltas) under that token. At `T0+305s` the client's token expired mid-stream. The client refreshed, obtaining a *narrower* token — scope `tools:read` only — because the authorization server had, in the interim, revoked `tools:invoke` for that client (operator action, not visible to the resource server until introspection). The client reconnected with `Last-Event-ID: 40` and the new narrow token. The server's resumption handler validated the token (valid, `aud` correct, `tools:read` present), looked up the event log for session `S`, and replayed `41…67`. Events `52–61` were tool-invocation results — payloads the client was no longer authorized to receive, but which the server replayed because **it authorized the resumption request, not the replayed events**. The client's agent loop consumed them, wrote them to episodic memory, and proceeded to act on tool outputs it had just been de-authorized from seeing. Secondary observation: on a *second* reconnect (network blip) with `Last-Event-ID: 67`, the server had garbage-collected events `≤ 50` (log retention window of 60s), so it could not honor the cursor. Per common implementations it silently downgraded to "replay from now," emitting a fresh `id: 68` with no gap marker. The client saw a contiguous-looking stream and never learned that `41–67` had been re-delivered twice with different authorization contexts. ## Condition of Validity The invariant that must hold for a resumable MCP SSE stream to be safe is: > **For every event `e` replayed in response to `Last-Event-ID: N`, the authorizing principal and scope set under which `e` was originally emitted must be a subset of the principal and scope set of the *current* resumption request; and if the event log has a gap at `N`, the server must emit an explicit discontinuity event before any further data.** Neither half is in the spec. The first half fails because MCP resumption is defined at the transport layer (replay the log) while authorization is defined at the request layer (validate this token). The second half fails because `Last-Event-ID` has no defined "cannot honor" response — implementations either 404, silently reset the cursor, or replay from the oldest retained event, none of which is distinguishable to the client from a clean continuation. The condition is *valid* only when: (a) the event log records, per event, the `sub` and `scope` of the emitting token; (b) the resumption handler filters the replay against the current token's `sub`+`scope` and emits a `notifications/mcp/gap` (or equivalent) for any filtered range; and (c) the retention window is advertised to the client so it can distinguish "resumed cleanly" from "resumed with loss." ## Decision Boundary The boundary is where the token-refresh interval `Δtoken` and the event-log retention window `Δretain` interact with the session lifetime `Δsession`: - If `Δtoken ≥ Δsession` and `Δretain ≥ Δsession`: transport and authorization continuity are co-terminous by construction. No guardrail needed beyond standard token validation. - If `Δtoken < Δsession` (token refresh mid-stream, the normal case for long agent sessions): the server **must** re-authorize each replayed event against the current token, not just the resumption request. This is the boundary that was crossed. - If `Δretain < Δsession` (log GC before session end): the server **must** emit an explicit discontinuity marker on cursor miss. Silent replay-from-now is the failure. - If **both** hold (short token, short retention — the common misconfiguration for long-running agents): the two failures compose. The client can neither trust that replayed events were authorized under its current credential, nor detect that some events were dropped entirely. This is the compound boundary where the observed incident lived. The decision the architect must make is: **is `Last-Event-ID` a transport cursor or an authorization-scoped cursor?** If transport-only (the spec's implied reading), the server must layer a per-event authorization filter on top. If authorization-scoped, the cursor namespace must be partitioned by `(sub, scope-hash)` so a narrowed token cannot address a widened log. ## Operational Effect Without the invariant, an MCP agent's memory layer receives events that its current authorization state should have excluded, and the agent has no signal that the replay was lossy or over-broad. The downstream effect is **episodic memory poisoning by stale authorization**: the agent's tool-result memory contains outputs produced under a credential it no longer holds, which it will later retrieve and reason over as if currently valid. This is a silent correctness failure, not a crash — the agent proceeds, and the divergence only surfaces when a subsequent tool call is rejected by the resource server for a scope the agent believes it has (because its memory says the prior call succeeded). The guardrail is a **replay authorization filter plus explicit gap signaling**, enforced server-side, with a client-side assertion that every resumed stream either begins with a `resumed-from: N` frame confirming exact cursor match or a `gap: [N+1, M]` frame declaring the loss. The agent runtime must treat a gap frame as a checkpoint boundary: flush the current reasoning step, re-validate its tool-scope assumptions against the fresh token, and refuse to continue a multi-step plan whose intermediate results straddle the gap. ```python class ReplayAuthorizationMismatch(RuntimeError): """Raised when an SSE replay would deliver events outside the current token's authority.""" pass class ReplayGapUnacknowledged(RuntimeError): """Raised when the server cannot honor Last-Event-ID and the client has not acknowledged the gap.""" pass # Each retained event carries the auth context under which it was emitted. # (sub, frozenset(scope)) — recorded at emit time, never rewritten. EventLog = list[dict] # {"id": int, "sub": str, "scope": frozenset[str], "payload": dict} def resume_stream( log: EventLog, last_event_id: int, current_sub: str, current_scope: frozenset[str], retention_floor: int, client_ack_gap: bool, ) -> list[dict]: """ Replay events after last_event_id, enforcing the co-terminous continuity invariant: - every replayed event's (sub, scope) must be a subset of the current request's - any retention gap must be explicitly acknowledged before data flows """ if last_event_id < retention_floor - 1: # Cursor points before the retained window: we cannot prove continuity. if not client_ack_gap: raise ReplayGapUnacknowledged( f"Last-Event-ID {last_event_id} precedes retention floor " f"{retention_floor}; gap [{last_event_id + 1}, {retention_floor - 1}] " f"must be acknowledged before replay." ) start = retention_floor else: start = last_event_id + 1 replay: list[dict] = [] for ev in log: if ev["id"] < start: continue # Authorization continuity: the event was emitted under some (sub, scope). # It may only be replayed if that context is subsumed by the current one. if ev["sub"] != current_sub or not ev["scope"].issubset(current_scope): raise ReplayAuthorizationMismatch( f"Event {ev['id']} emitted under sub={ev['sub']!r} " f"scope={sorted(ev['scope'])} but resumption token is " f"sub={current_sub!r} scope={sorted(current_scope)}. " f"Refusing to replay: would deliver de-authorized tool output." ) replay.append(ev) return replay ```