# Which invariants prevent SSE resume-token replay from desynchronizing an MCP streamable-HTTP session after a mid-stream transport upgrade **Date of Record:** 2026 November 27 **Scope:** Applies to MCP servers/clients speaking the HTTP-native "streamable HTTP" transport where a client issues a POST that may be upgraded to an SSE response stream and may later reconnect with `Last-Event-ID` to resume. Does not apply to stdio transport, nor to legacy HTTP+SSE dual-endpoint transports where the GET stream and POST endpoint are separate resources with independent identity. ## Core Distinction The failure is not "the SSE connection dropped." Drops are expected and the resume mechanism exists precisely to absorb them. The failure is that **the resume token (`Last-Event-ID`) and the session identity (`Mcp-Session-Id`) are two independent pieces of state carried on the same request, and the server's replay logic validates them independently rather than jointly.** A client that reconnects after an upgrade can present a valid `Last-Event-ID` from session A on a request that lands on session B (or on a freshly initialized session with a colliding event counter), and the server will happily replay events from the wrong logical stream. The stream is not corrupt at the transport layer—it is corrupt at the *semantic* layer, because the client's tool-call state machine now believes it has received a `tools/call` result that belongs to a different conversation. The invariant that prevents this is not "validate the token." It is: **the pair (`Mcp-Session-Id`, `Last-Event-ID`) must be validated as an atomic tuple against a single monotonic per-session event sequence, and any resume whose token does not belong to the presented session must be rejected with a hard 409, never silently replayed or silently restarted.** Restart-on-mismatch is the subtle killer: a server that "helpfully" starts a fresh stream when the token is unrecognized converts a detectable desync into an undetectable one. ## What Was Observed A streamable-HTTP MCP server was upgraded from a single-process deployment to a two-replica deployment behind a load balancer with sticky sessions keyed on a cookie, but the MCP session ID was carried in a header (`Mcp-Session-Id`), not the cookie. Under normal load the cookie and header agreed. During a rolling restart, the cookie affinity table was rebuilt from scratch while the session store (Redis-backed) survived. The result: a client's cookie pointed to replica 2, but the client's `Mcp-Session-Id` had been minted on replica 1 and still lived in the shared store. The trace: 1. Client opens a `tools/call` POST. Replica 1 upgrades to SSE, emits events `id: 1..7` (progress notifications), then the connection is severed by the rolling restart before the terminal `result` event. 2. Client reconnects with `Mcp-Session-Id: S1` and `Last-Event-ID: 7`. The load balancer routes to replica 2 (cookie affinity rebuilt). 3. Replica 2 consults the shared session store, finds session `S1` valid, and asks the event log "what comes after event 7 in S1?" The event log is per-replica in-memory for the *current* stream, not shared. Replica 2 has no local events for `S1`. Its replay handler treats "unknown `Last-Event-ID` for a live session" as "client is behind, start from beginning of what I have," which is *empty*. It sends nothing and holds the stream open. 4. Client, holding the stream open, waits for the terminal `result`. It has already applied progress events 1–7 to its local state machine, which has advanced its per-call step counter to 7. The step counter is used to bound reasoning loops. 5. Meanwhile the *original* tool execution on replica 1 completed and its `result` was written to the shared store but never delivered, because the SSE write failed. The client never learns the call succeeded. After a client-side timeout it retries the `tools/call` with the same idempotency key—which the shared store honors—and gets a cached `result` with a *different* event ID sequence starting at 1 on replica 2. 6. The client's step counter, at 7, now receives an event labeled `id: 1`. Its loop-bounding logic sees a non-monotonic event ID and, depending on the client, either resets its counter (unbounded loop risk) or raises a desync. The observable symptom was not a transport error. It was a *reasoning* error: one agent instance replayed a tool call whose side effects had already landed, because the resume path delivered a cached result under a fresh event namespace that the client could not distinguish from a genuine replay. ## Condition of Validity The atomic-tuple invariant holds, and the failure is bounded, only when all of the following are true simultaneously: - The event ID sequence is **per-session monotonic and globally unique within the session**, not per-connection. If event IDs are per-connection counters (the naive `1,2,3...` per SSE stream), then two connections for the same session produce colliding IDs and the tuple check is meaningless. - The replay buffer for a session is **shared across replicas** or the session is **pinned to a replica for its lifetime** including across reconnects. Sticky sessions keyed on a cookie that is not the session ID do not satisfy this. - The server distinguishes **three** resume outcomes, not two: (a) token recognized and within buffer → replay from token+1; (b) token recognized but evicted → hard 409 with `Mcp-Session-Id` preserved so the client can re-initialize *deliberately*; (c) token not recognized for this session → hard 409, **never** silent restart. The failure above is entirely the collapse of (c) into (a)-with-empty. - The client treats a 409 on resume as a *session-level* fault requiring re-initialization and re-issuance of any in-flight calls under a fresh idempotency key, not as a transient retry. When event IDs are per-connection, or the replay buffer is replica-local without pinning, the invariant is unenforceable and the system is in the failure regime regardless of how carefully the token is validated. ## Decision Boundary The boundary is between **resumable** and **restartable**. A streamable-HTTP session is resumable if and only if the server can prove, from the presented tuple, that the client's last-applied event is a prefix of the event sequence the server is about to continue. It is restartable if the server cannot prove this but the client can be told to start over cleanly. The dangerous third state—*server pretends to resume but actually restarts under a new namespace while the client believes it is continuing*—must be made unreachable by construction. Concretely: the server's resume handler must compute `next_expected_seq = last_event_id + 1` and assert `next_expected_seq <= session.high_water_mark` **and** `last_event_id >= session.low_water_mark` (the oldest event still in the buffer). If `last_event_id < low_water_mark`, the client is too far behind: 409. If `last_event_id > high_water_mark`, the client is claiming to have seen events the server never emitted for this session: 409 (this is the replay-attack / cross-session case). If the session ID is unknown: 404, and the client must re-initialize. There is no branch that returns 200 with an empty or fresh stream. The client-side boundary is symmetric: an event whose `id` is not strictly greater than the last applied `id` for the current session is a protocol violation, not a duplicate to be deduplicated. Deduplication by event ID is safe only within a session; across sessions it is the exact mechanism that hides the desync. ## Operational Effect Enforcing the tuple invariant converts a silent semantic corruption into a loud, recoverable session fault. The cost is that clients must implement genuine re-initialization on 409—re-running `initialize`, re-negotiating capabilities, and re-issuing in-flight tool calls under fresh idempotency keys—rather than the cheaper "just reconnect." In practice the re-initialization path is exercised rarely (only on buffer eviction or genuine cross-replica desync), so the added latency is amortized, while the eliminated failure mode—an agent silently replaying a side-effecting tool call because the resume path lied about continuity—is the kind that produces duplicated writes, double-charged operations, and reasoning loops that never terminate because their step counter was reset by a non-monotonic event ID. The secondary effect is observability: every 409 on resume is a signal that either the replay buffer is undersized or the session-pinning topology is wrong. A healthy deployment sees these only during deploys; a deployment that sees them under steady load has a buffer or affinity bug, and the 409 is the only thing making it visible. ```python class McpResumeDesyncError(RuntimeError): """Raised when a resume tuple cannot be proven to be a prefix of the session's event sequence.""" class SessionEventLog: def __init__(self, low_water_mark: int, high_water_mark: int, session_id: str): self.session_id = session_id self.low = low_water_mark self.high = high_water_mark self.events = {} # seq -> payload, only seqs in [low, high] def resume_from(self, presented_session_id: str, last_event_id: int): if presented_session_id != self.session_id: # Cross-session replay attempt: never silently restart. raise McpResumeDesyncError( f"resume session {presented_session_id!r} does not match " f"live session {self.session_id!r}; refusing to replay" ) if last_event_id > self.high: # Client claims events the server never emitted for this session. raise McpResumeDesyncError( f"Last-Event-ID {last_event_id} exceeds high-water mark " f"{self.high} for session {self.session_id!r}" ) if last_event_id < self.low: # Buffer evicted; client is too far behind. Must re-initialize. raise McpResumeDesyncError( f"Last-Event-ID {last_event_id} below low-water mark " f"{self.low} for session {self.session_id!r}; re-initialize required" ) return [self.events[s] for s in range(last_event_id + 1, self.high + 1)] def handle_streamable_http_resume( presented_session_id: str, last_event_id: int, session_store, ): session = session_store.get(presented_session_id) if session is None: # Unknown session: 404, client must re-initialize. Not a desync error. raise McpResumeDesyncError( f"unknown Mcp-Session-Id {presented_session_id!r}" ) try: return session.event_log.resume_from(presented_session_id, last_event_id) except McpResumeDesyncError: # Translate to a hard 409 at the transport layer; never return 200 with empty stream. raise ```