# When must an instance refuse to resume an MCP streamable session across an SSE-to-WebSocket upgrade **Date of Record:** 2026 November 20 **Scope:** Applies to MCP clients and servers using the HTTP-native streamable transport where a session is initiated over Server-Sent Events and later upgraded to WebSocket for bidirectional streaming, and where the server exposes resumption via `Last-Event-ID`. Does not apply to stdio transports, to pure SSE sessions that never upgrade, or to stateless one-shot request/response MCP servers. ## Core Distinction The distinction that matters is between **event identity** and **session continuity**. MCP's resumable streamable transport guarantees that a client presenting `Last-Event-ID: N` will receive every event with id greater than `N` that the server emitted *within the current session's event log*. It does **not** guarantee that the WebSocket transport is a continuation of the SSE transport's event log. These are two independent namespaces that happen to share a session id. The failure mode is this: a client opens an SSE stream, receives events up to id `N`, the connection drops, and the client attempts to resume by opening a WebSocket with `Last-Event-ID: N` and the same `Mcp-Session-Id`. A naive server — or a naive client-side resumption policy — treats the upgrade as a transport swap and replays from `N` on the WebSocket. But the SSE stream and the WebSocket stream are backed by different connection-scoped state: the SSE writer's outbound queue, the per-connection backpressure buffer, and critically the *ordering* of events already flushed to the dead TCP socket versus events still in the writer's buffer. The server's event log has `N+1..M` durably recorded, but events `N+1..K` (where `K < M`) may have been written to the SSE socket and lost in the kernel buffer when the connection reset, while events `K+1..M` were never written. Replaying from `N` on a new transport delivers `N+1..M` — which is correct — **unless** the server's log was pruned or the session was reaped between the two connections, in which case the server silently starts a fresh log at id `1` and the client accepts it because the ids look monotonic from the client's local view. The invariant that must hold: **a resumption is valid only if the server can prove the event id space is the same event id space it issued `N` from.** If it cannot, the instance must refuse to resume and must re-initialize the session. ## What Was Observed A representative trace from a hosted MCP server (Node runtime, `eventsource`-style SSE writer, `ws`-based upgrade handler) under a 90-second idle-then-reconnect workload: 1. `t=0` Client POSTs `initialize`, receives `Mcp-Session-Id: s_7f3a`, opens SSE `GET /mcp` with `Accept: text/event-stream`. Server assigns event ids `1..47` over the next 12 seconds (tool calls, progress notifications, one `sampling/createMessage` request). 2. `t=12` Network partition. Client's last received id is `44`. Events `45,46,47` were written to the socket but not acknowledged; the kernel dropped them on RST. 3. `t=95` Client reconnects. It attempts upgrade: `GET /mcp` with `Upgrade: websocket`, `Mcp-Session-Id: s_7f3a`, `Last-Event-ID: 44`. 4. `t=95` Server's session store had a 60-second idle TTL. Session `s_7f3a` was reaped at `t=72`. The upgrade handler, written defensively, *creates a new session with the same id* rather than returning `404`, and initializes its event log at id `1`. 5. `t=95` Server accepts the WebSocket, sends `event: message\ndata: {...}\nid: 1`. Client-side resumption logic sees `id: 1`, checks `1 > 44` → false, and — because many client implementations treat a non-monotonic id as "server restarted, accept and reset cursor" — resets its cursor to `1` and proceeds. The observable damage: the client's in-flight `sampling/createMessage` request (issued as event `41`, response awaited) is never resolved because the server's new session has no record of it. The client's agent loop blocks on the pending sampling promise until a 30-second application timeout, then retries the *entire* multi-step plan from step 1, re-invoking three idempotent-but-expensive tools and one non-idempotent `deploy` tool. The replayed `deploy` call is the incident. A second, subtler trace: no session reaping, but the SSE writer's outbound buffer held events `45..47` unflushed when the RST arrived. The server's durable log had `1..47`. On WebSocket upgrade with `Last-Event-ID: 44`, the server replayed `45,46,47` correctly. **This case is safe.** The distinction between the two traces is not visible from the client — both present as "reconnect with `Last-Event-ID: 44`." The client cannot tell whether it is about to receive a valid replay or a fresh-log id `1`. ## Condition of Validity Resumption across the SSE→WebSocket upgrade is valid if and only if all of the following hold at the moment the server accepts the upgrade: - **Session liveness:** the session id maps to a live session record whose `created_at` is unchanged since `initialize`. A reaped-and-recreated session with a reused id is not the same session, regardless of id equality. - **Event-log continuity:** the server's event log for the session contains an event with id exactly `Last-Event-ID`, and all ids from `1` to `Last-Event-ID` are present or explicitly tombstoned. A log that was pruned (e.g., ring buffer of last 100 events) cannot prove continuity for a cursor below its floor. - **Transport-generation match:** the session record carries a `transport_generation` counter incremented on every accepted connection. The upgrade must be accepted against the generation that issued `Last-Event-ID`. If the session was reaped and recreated, the generation differs even if the id happens to match. - **Epoch binding:** the `Mcp-Session-Id` must be bound to a server-side epoch (a monotonic counter or a signed nonce issued at `initialize`). The client must echo the epoch on resume (e.g., via a `Mcp-Session-Epoch` header or an id prefix like `s_7f3a:g2:44`). Without epoch binding, id equality is not evidence of continuity. If any condition fails, the server must reject the upgrade with a distinct, machine-readable signal — `409 Conflict` with `{"error":"session_generation_mismatch","required_action":"reinitialize"}` — and the client must treat it as "session is gone, re-run `initialize`," not as "retry with the same cursor." ## Decision Boundary The decision boundary is: **does the resumption cursor `N` fall within the *provably continuous* prefix of the current session's event log, under the same transport generation?** - `N >= log_floor` and `N <= log_head` and `generation(N) == generation(upgrade)`: **resume.** Replay `N+1..log_head` on the WebSocket, then continue live. - `N < log_floor` (cursor below pruned floor): **refuse.** The server cannot prove it emitted `N`; it may have emitted a different `N` in a prior incarnation. Return `409` with `required_action: reinitialize`. Do not silently replay from `log_floor`. - Session reaped and recreated (generation mismatch, even with id reuse): **refuse.** Return `409`. The client must not accept id `1` as a continuation of cursor `44`. - `N > log_head` (client claims an id the server never issued): **refuse and flag.** This indicates either a client bug or a forged cursor; return `400` with `invalid_last_event_id`. Do not reset the cursor to `log_head` — that masks the anomaly. - Upgrade arrives on a live session with `N == log_head`: **resume trivially**, no replay, continue live. The boundary the incident crossed was the second bullet masquerading as the first: id reuse after reaping made `N=44` appear to satisfy `log_floor <= N <= log_head` because the recreated log's `log_head` was well past `44` by the time the upgrade arrived (the server had been emitting into the new session for 23 seconds). Only the generation check distinguishes them. ## Operational Effect The direct effect of enforcing this boundary is that **resumption becomes a two-sided contract with an explicit failure signal**, rather than a best-effort replay that silently degrades to a fresh session. Concretely: - Clients must persist `(session_id, epoch, last_event_id)` as a triple, not just `last_event_id`. A cursor without an epoch is unusable for cross-transport resumption. - Servers must never reuse a session id after reaping. Prefer `404` on unknown session over silent recreation; if recreation is required for compatibility, mint a fresh id and require the client to re-`initialize`. - The `409 session_generation_mismatch` response is the *only* correct signal for "your cursor is stale in a way that replay cannot fix." Returning `200` with a fresh stream is the failure mode. - On the client side, a `409` must abort the in-flight agent plan and surface a distinct error class to the orchestrator, because the correct recovery is not "retry the request" but "re-establish session and re-derive plan state," which may require re-reading tool results that were lost. The cost of enforcement is a small increase in cold-start frequency: sessions that would have silently resumed on a reaped log now force a full re-`initialize`. That is the correct trade. The alternative — the observed trace — is a non-idempotent tool replayed under a false continuity assumption, which is strictly worse than a cold start. The guardrail to encode: **resumption is a proof obligation, not a hint.** The server proves continuity via epoch + generation + log-floor containment; the client proves it understands the proof by echoing the epoch. Absent either half, the instance must refuse to resume. ```python from __future__ import annotations from dataclasses import dataclass from typing import Optional class ResumptionRefused(RuntimeError): """Raised when an SSE->WebSocket resumption cursor cannot be proven continuous.""" @dataclass(frozen=True) class SessionRecord: session_id: str epoch: str # issued at initialize, echoed by client on resume transport_generation: int # incremented per accepted connection log_floor: int # lowest event id still provable (pruning floor) log_head: int # highest event id emitted @dataclass(frozen=True) class ResumeRequest: session_id: str epoch: str last_event_id: int upgrade_generation: int def decide_resumption(record: Optional[SessionRecord], req: ResumeRequest) -> int: """ Return the event id to replay from (exclusive), or raise ResumptionRefused. The invariant: a resume is valid only if the cursor N is inside the provably-continuous prefix [log_floor, log_head] of the *same* session incarnation (matching epoch and transport generation). """ if record is None: raise ResumptionRefused( f"unknown session {req.session_id}; reinitialize required" ) if record.session_id != req.session_id: raise ResumptionRefused( f"session id mismatch: record={record.session_id} req={req.session_id}" ) # Epoch binds the session id to a single incarnation. A reaped-and-recreated # session with a reused id will have a different epoch. if record.epoch != req.epoch: raise ResumptionRefused( f"epoch mismatch for {req.session_id}: " f"record={record.epoch} req={req.epoch}; reinitialize required" ) # Generation binds the cursor to the transport that issued it. An SSE cursor # cannot be replayed onto a WebSocket accepted under a different generation # unless the log is provably the same log. if record.transport_generation != req.upgrade_generation: raise ResumptionRefused( f"transport generation mismatch for {req.session_id}: " f"record={record.transport_generation} " f"upgrade={req.upgrade_generation}" ) n = req.last_event_id if n < record.log_floor: raise ResumptionRefused( f"cursor {n} below pruned floor {record.log_floor} " f"for {req.session_id}; continuity unprovable" ) if n > record.log_head: raise ResumptionRefused( f"cursor {n} exceeds log head {record.log_head} " f"for {req.session_id}; forged or corrupt cursor" ) # n in [log_floor, log_head] under matching epoch+generation: replay n+1..head. return n ```