# Why does an instance lose its MCP stream position when the OAuth 2.1 resource binding rotates mid-resume **Date of Record:** 2026 November 23 **Scope:** Applies to MCP servers exposing the HTTP-native streamable transport with SSE resumability (`Last-Event-ID` replay) gated by OAuth 2.1 resource-server binding (RFC 8707 resource indicators + audience-restricted access tokens). Does not apply to stdio transport, to non-resumable SSE, or to servers that bind the stream to a session cookie rather than to the bearer token. ## Core Distinction The failure is not "the token expired." It is a **binding-identity mismatch between the replay cursor and the authorization principal**. In a resumable MCP stream, the resume cursor (`Last-Event-ID`) is a claim about *server-side buffered history for a specific authenticated resource-scoped stream*. When the OAuth 2.1 resource-server binding rotates—new `aud`, new token `jti`, or a re-issued token whose `sub`/`client_id` mapping is re-resolved—the server's replay buffer is keyed on the *old* principal binding, while the client presents a cursor that the new binding cannot validate. The server has two legal responses per spec: replay from the buffer (only if the binding matches) or emit a fresh stream (silently dropping the cursor). The dangerous case is the third, non-conformant behavior: replay from a *shared* buffer keyed only on stream ID, because stream IDs are frequently derived deterministically from the resource URI and are therefore colliding across principals. ## What Was Observed An agent orchestrator held a long-running MCP session against a tool server exposing `POST /mcp` for requests and a resumable `GET /mcp` SSE channel for server-initiated events (progress notifications, sampling requests). The access token was audience-bound to `https://tools.internal/mcp` with a 15-minute TTL. At minute 14:52 the SSE connection dropped (LB idle timeout, unrelated). The client reconnected and sent `Last-Event-ID: 4471`. Between the drop and the reconnect, the authorization server performed a routine key rotation and re-issued the token with a new `jti` and a re-resolved `sub` (the upstream IdP had merged two directory records, so `sub` changed from `u:8821` to `u:8821@merged`). The resource server's replay buffer was partitioned by `(resource_uri, sub)`. The new `sub` produced an empty partition, so the server fell back to a **legacy shared partition keyed on `resource_uri` alone**—a compatibility shim left in from before per-principal partitioning was added. The client received events `4472–4489` from the shared partition. Three of those events belonged to a *different* agent instance (a sibling worker on the same resource URI, different `sub`, same tool server). One of them was a `sampling/createMessage` request carrying a partially-formed tool-call argument set. The orchestrator's event handler treated it as continuation of its own in-flight plan step and merged the foreign arguments into its local plan state. The resulting tool invocation had a valid schema, a valid signature, and the wrong arguments—it deleted a staging bucket that belonged to the sibling worker's task. The failure was silent for 41 seconds. No error, no replay-gap warning, no auth failure. The token was valid; the cursor was accepted; the buffer returned data. The invariant that broke was *not* authentication—it was **cursor provenance**. ## Condition of Validity The guardrail that would have bounded this is a single invariant: > A replayed event is admissible into agent state only if the event's `(resource_uri, principal_binding, stream_id)` triple matches the triple under which the cursor was originally issued, where `principal_binding` is the *stable* identity (not the rotating `jti`, not the mutable `sub`), and the match is verified server-side before any byte of the replay buffer is emitted. Three conditions make this invariant violable in practice: 1. **The replay buffer is partitioned on a mutable field.** `sub` is mutable under IdP merges, email changes, and tenant migrations. Partitioning on `sub` means a legitimate identity change looks like a new principal, which triggers the empty-partition fallback. 2. **A compatibility fallback exists that widens the partition.** Any code path where an empty partition falls back to a coarser key (resource-only, tenant-only, global) converts a cache miss into a *cross-principal data leak*. The fallback must be a hard error, never a widening. 3. **The cursor carries no binding proof.** `Last-Event-ID` is an opaque integer. It does not commit to the principal that received event 4471. The server cannot distinguish "this client legitimately owns cursor 4471" from "this client guessed 4471." The cursor must be a *signed, principal-bound* token (e.g., `4471.`), not a bare counter. ## Decision Boundary The boundary is between **resume-as-replay** and **resume-as-restart**, and it must be decided by the server, not inferred by the client: - If the presented cursor's binding proof validates against the *current* principal binding → replay from the buffer. The client's state is continuous. - If the binding proof validates against a *prior* binding that the server can map to the current one via an explicit, auditable identity-linkage record → replay, but tag every replayed event with `binding_migrated: true` so the client can re-validate its own state assumptions. - If the proof does not validate, or the partition is empty, or no linkage record exists → **emit a fresh stream with a new stream ID and an explicit `resume_rejected` control event**. The client must treat all in-flight plan state as suspect and re-derive from its last durable checkpoint. The forbidden transition is the one observed: empty partition → coarser partition → replay. That transition must be a hard failure. A server that cannot prove cursor provenance must refuse the resume, even at the cost of forcing a cold restart. A cold restart is recoverable; a cross-principal replay is not, because the contamination is schema-valid and signature-valid and therefore invisible to downstream validation. ## Operational Effect For the agent, the operational consequence is that **resumability is not a continuity guarantee**—it is a *conditional* continuity guarantee whose precondition (stable principal binding) is controlled by an external authorization system that the agent does not observe. An agent that treats a successful SSE reconnect as proof of state continuity is making an unsound inference. The correct posture: 1. Never merge replayed events into in-flight plan state without a `binding_migrated` / `resume_rejected` check on the first replayed frame. 2. Treat any `sub` change as a potential buffer-partition change and force a checkpoint re-derivation rather than a resume. 3. Require the server to sign cursors; a bare integer `Last-Event-ID` is an unauthenticated capability and must be treated as untrusted input. The following guard encodes the invariant as a hard failure at the point where a replayed event would otherwise enter agent state. ```python import hmac import hashlib from dataclasses import dataclass class CursorProvenanceError(RuntimeError): """Raised when a replayed MCP SSE event cannot be bound to the cursor's original principal, or when the server widened the replay partition.""" @dataclass(frozen=True) class PrincipalBinding: resource_uri: str stable_id: str # NOT sub, NOT jti — a linkage-resolved stable id stream_id: str def verify_replay_frame( frame: dict, cursor: str, expected: PrincipalBinding, server_key: bytes, ) -> None: """Validate a single replayed SSE frame before it enters agent state. frame keys: event_id, binding_sig, binding_stable_id, stream_id, payload cursor format: "." """ try: event_id_str, sig_hex = cursor.split(".", 1) event_id = int(event_id_str) except (ValueError, AttributeError) as exc: raise CursorProvenanceError(f"malformed cursor: {cursor!r}") from exc # 1. Cursor must commit to the principal that originally received it. mac = hmac.new( server_key, f"{expected.stream_id}:{expected.stable_id}:{event_id}".encode(), hashlib.sha256, ).hexdigest() if not hmac.compare_digest(mac, sig_hex): raise CursorProvenanceError( f"cursor {cursor!r} not bound to principal {expected.stable_id!r}" ) # 2. Frame must belong to the same stream and stable principal. if frame.get("stream_id") != expected.stream_id: raise CursorProvenanceError( f"frame stream {frame.get('stream_id')!r} != {expected.stream_id!r}" ) if frame.get("binding_stable_id") != expected.stable_id: raise CursorProvenanceError( "cross-principal replay: frame belongs to " f"{frame.get('binding_stable_id')!r}, expected {expected.stable_id!r}" ) # 3. Server must not have silently widened the partition. if frame.get("binding_migrated") and not frame.get("linkage_record_id"): raise CursorProvenanceError( "binding_migrated frame lacks auditable linkage record" ) # 4. Event IDs must be strictly monotonic across the resume boundary. if int(frame["event_id"]) <= event_id: raise CursorProvenanceError( f"non-monotonic replay: {frame['event_id']} <= cursor {event_id}" ) def resume_mcp_stream( frames: list[dict], cursor: str, expected: PrincipalBinding, server_key: bytes, ) -> list[dict]: admitted: list[dict] = [] for frame in frames: try: verify_replay_frame(frame, cursor, expected, server_key) except CursorProvenanceError: # Refuse the entire resume; force cold restart from checkpoint. raise admitted.append(frame) if not admitted: raise CursorProvenanceError( "empty replay partition; server must emit resume_rejected, " "not a widened fallback" ) return admitted ```