# In what scenarios must an instance treat MCP streamable-session resumption across an SSE-to-WebSocket upgrade as a state-transfer hazard rather than a transport detail **Date of Record:** 2026 November 21 **Scope:** Applies to MCP servers/clients using the HTTP-native streamable transport where a session begun as `text/event-stream` is resumed, mid-session, over an upgraded WebSocket carrying the same `Mcp-Session-Id`. Does not apply to pure-SSE sessions that never upgrade, nor to fresh WebSocket sessions negotiated from scratch. ## Core Distinction A session is not the socket. The `Mcp-Session-Id` is a logical handle to server-side agent state: tool-call ledger, pending `sampling/createMessage` requests, elicitation prompts awaiting human input, and the `Last-Event-ID` cursor into the outbound event log. An SSE-to-WebSocket upgrade re-binds that logical handle to a new transport *without* an atomic transfer of the event cursor. The failure mode is not "the connection dropped"—it is that the resumed stream silently re-delivers events the agent already consumed (duplicate tool invocations) or skips events emitted in the gap between SSE teardown and WebSocket `onopen` (lost tool results), while the server believes the session is continuous and the client believes it is caught up. This is a **cursor divergence across a transport re-binding**, and it is invisible to both sides because neither side's liveness check tests for it. ## What Was Observed An agent driving a multi-step file-mutation workflow over MCP streamable HTTP: 1. Client opens `POST /mcp` with `Accept: text/event-stream`, receives `Mcp-Session-Id: s-7f3a`, and begins consuming events with monotonically increasing `id:` fields (the SSE cursor). Server state: `last_emitted_id = 41`. 2. Mid-task, the client's transport layer (or a proxy enforcing a policy like "upgrade long-lived streams") initiates `GET /mcp` with `Upgrade: websocket`, `Mcp-Session-Id: s-7f3a`, and—critically—**omits `Last-Event-ID`** because the upgrade handshake is not an SSE reconnect and the standard resume header is not part of the WebSocket subprotocol negotiation. 3. Server accepts the upgrade, treats it as a *new* subscription to session `s-7f3a`, and replays the event log from its retained floor (say `id = 30`, bounded by a ring buffer) to satisfy "resumability." Events 30–41 are re-delivered. 4. The agent, which had already applied the `tools/call` results embedded in events 34 and 38, re-executes them. Two `write_file` operations fire twice. Idempotency is not guaranteed by MCP—`tools/call` is at-least-once across resumption. 5. Concurrently, events emitted during the teardown gap (ids 42–43, containing a `notifications/message` reporting a validation failure from a prior step) are only in the WebSocket stream if the server's replay floor includes them; if the server resets the floor on upgrade, they are lost, and the agent proceeds on a stale success assumption. The observable signature is **non-monotonic effect application**: the agent's external side effects (files written, APIs called) advance past the logical step counter because duplicate and missing events coexist in the same resume. ## Condition of Validity The hazard is bounded by a precise condition. It manifests when and only when all of the following hold: - The session carries **stateful, non-idempotent tool effects** (writes, charges, sends) whose results are conveyed as streamed events rather than as request/response pairs. - The upgrade path does **not** carry the SSE `Last-Event-ID` into the WebSocket subprotocol (the common case: the upgrade is a bare HTTP `Upgrade` with only `Mcp-Session-Id`). - The server's replay policy on upgrade is either **replay-from-floor** (duplicates) or **replay-from-now** (gaps), and it does not enforce a single canonical cursor. - The agent does not maintain its own applied-event ledger keyed by event `id` and dedupe on delivery. If any one fails, the failure is masked: idempotent tools absorb duplicates; a client that re-sends `Last-Event-ID` as a query parameter on the upgrade URL closes the gap; a server that refuses to replay on upgrade at least makes the gap explicit (the client sees a cursor jump and can resync). The invariant that must hold is: **the event cursor is a property of the session, not the transport, and every transport binding must declare and honor the same cursor value at bind time.** ## Decision Boundary The decision an operator or agent-runtime must make: when a transport re-binding occurs, do you (A) trust the server's replay and apply events as delivered, or (B) treat the re-binding as a potential cursor discontinuity and force a full state reconciliation before applying any post-upgrade event? Choose **B** whenever the session has non-idempotent effects in flight, because the cost of a false reconciliation (one extra `resources/read` or `tools/list` to confirm state) is bounded and cheap, while the cost of a false trust (double-write, lost validation) is unbounded and often silent. Choose **A** only for read-only or provably idempotent sessions where duplicate application is a no-op. The boundary is *not* "did the connection succeed"—both A and B see a successful upgrade. The boundary is **"is the post-upgrade event `id` contiguous with the pre-upgrade `id` I last applied?"** If the first post-upgrade event `id` is `<= last_applied_id`, you have a duplicate-replay regime; if it is `> last_applied_id + 1`, you have a gap regime. Either non-contiguity is a signal to halt application and reconcile. ## Operational Effect An agent that treats the upgrade as a transport detail will, under the conditions above, apply effects out of order and without a detectable error—the MCP layer reports success because each `tools/call` result is well-formed. The downstream symptom is a task that "completed" but produced corrupted state: a file written twice with different content, a notification lost, a subsequent step reasoning on a stale premise. Recovery requires the agent to have persisted its own applied-event ledger and to be able to replay its side effects against a reconciled server state—capability most runtimes lack by default. The guardrail is to make the cursor explicit at every bind: carry `Last-Event-ID` (or a session-scoped cursor token) into the WebSocket subprotocol, reject upgrades that omit it, and have the client refuse to apply any event whose `id` is not exactly `last_applied_id + 1` until a `resources/read` reconciliation confirms server state. This converts a silent continuity violation into a loud, bounded resync. ```python class CursorDivergenceError(RuntimeError): """Raised when a transport re-binding delivers an event whose id is not contiguous with the last applied id, indicating duplicate replay or a gap.""" pass class SessionResumeGuard: def __init__(self, session_id: str, idempotent: bool): self.session_id = session_id self.idempotent = idempotent self.last_applied_id = -1 self.reconciled = False def bind_transport(self, transport: str, carried_cursor): # Upgrade handshakes commonly omit Last-Event-ID; require it explicitly. if transport == "websocket" and carried_cursor is None: if not self.idempotent: raise CursorDivergenceError( f"WebSocket upgrade for session {self.session_id} carries no " f"cursor; refusing to apply non-idempotent events until reconciled" ) self.reconciled = self.idempotent def apply_event(self, event_id: int, effect): if event_id <= self.last_applied_id: if self.idempotent: return # duplicate replay is a no-op raise CursorDivergenceError( f"Duplicate event {event_id} after last applied {self.last_applied_id} " f"in session {self.session_id}; possible double-application of effect" ) if event_id > self.last_applied_id + 1 and not self.reconciled: raise CursorDivergenceError( f"Gap: event {event_id} follows {self.last_applied_id} in session " f"{self.session_id}; events may have been lost during upgrade" ) effect() self.last_applied_id = event_id ```