# Why does an instance lose MCP tool-call state when a resumable SSE stream is upgraded to WebSocket mid-negotiation? **Date of Record:** 2026 November 23 **Scope:** Applies to MCP clients/servers that negotiate a stream transport starting as HTTP SSE and upgrade in-place to WebSocket, with `Last-Event-ID` resumption enabled. Does not cover pure stdio transports, single-shot HTTP request/response tool calls, or WebSocket-first sessions with no SSE preamble. ## Core Distinction The failure is not "the upgrade failed." The upgrade succeeds. The failure is that the **event-id namespace is not carried across the transport boundary**. During SSE, the server assigns monotonically increasing `id:` fields to each `event:` frame, and the client tracks the last one it *processed*. When the session upgrades to WebSocket, the server's new frame sequence starts a fresh counter (or restarts from a per-connection epoch), while the client's `Last-Event-ID` still references the *SSE* stream's numbering. On reconnect or resume, the client presents an `id` that the WebSocket-side stream cannot map to a position, and the server silently **replays from its own current head** rather than from the client's last-processed frame. The observable symptom is a tool call that executes twice, or a `tools/call` result that never arrives because its frame was in the gap between the SSE tail and the WebSocket head — a gap the resumption protocol believes it has closed. The invariant that breaks: *"a resumable stream's event-id is a stable, transport-independent cursor into a single logical event log."* SSE-to-WebSocket upgrade violates this by renumbering the log at the transport seam while leaving the client's cursor untouched. ## What Was Observed A concrete trace from an agent session driving an MCP server that exposes `filesystem.read` and `shell.exec`: 1. Client opens `GET /mcp/session` with `Accept: text/event-stream`. Server responds `200`, `Content-Type: text/event-stream`, and begins emitting `event: message` frames with `id: 1`, `id: 2`, ... `id: 47`. Frame `id: 44` carries the `tools/call` request for `filesystem.read`; the client has processed through `id: 43` and is awaiting the result. 2. Server negotiates upgrade: responds `101 Switching Protocols` on the same logical session (per the MCP HTTP-native transport spec's in-place upgrade path). The SSE stream is closed by the server after the `101`. 3. WebSocket frames begin. The server's first frame has no `id`, the second is `id: 1` (fresh counter for the new transport epoch). The `tools/call` result for `filesystem.read` — which the server had queued behind the upgrade — is emitted as WebSocket frame `id: 3`. 4. The client, which had recorded `Last-Event-ID: 43` from the SSE phase, treats the WebSocket as a *new* stream. It resets its cursor to "unset" and processes frames `1`, `2`, `3` normally — so far so good. 5. The connection drops (idle timeout on a NAT gateway). Client reconnects with `GET /mcp/session`, header `Last-Event-ID: 3` (the WebSocket-phase id). Server, however, has torn down the WebSocket epoch and re-established an SSE epoch whose counter restarts at `1`. It cannot find `id: 3` in the new epoch's log and, per its resumption implementation, **replays from the beginning of the current epoch**. 6. The client receives the replayed `tools/call` for `filesystem.read` as a *new* request (it has no dedup key tying it to the original `id: 44` from the SSE epoch), re-executes it, and the server now has two in-flight reads on the same file descriptor. The duplicate execution is the visible symptom. The deeper defect is that the `tools/call` request identity (`id: 44` in SSE space) and its result (`id: 3` in WebSocket space) were never correlated across the transport seam. The server's resumption logic is *locally* correct — it replays from its own head — but *globally* wrong because the client's cursor and the server's log numbering diverged at the upgrade. ## Condition of Validity This failure mode is bounded by three conditions, all of which must hold: - **In-place upgrade with renumbering.** The server assigns event ids per-transport-epoch rather than per-session. If the server carries a single monotonic counter across SSE and WebSocket, the client's `Last-Event-ID` remains valid and the failure does not occur. The bug is specifically the *epoch reset at the seam*. - **Resumption enabled with `Last-Event-ID`.** If the client does not send `Last-Event-ID` on reconnect, the server starts fresh and the client re-issues its pending `tools/call` — a different (and usually visible) failure, not this silent one. - **A `tools/call` in flight at the moment of upgrade or reconnect.** If no request is pending across the seam, the renumbered replay is harmless (the client discards replayed frames it has already seen by content hash, if it does content dedup). The failure requires an unacknowledged side-effecting call to straddle the boundary. It does *not* apply when the upgrade is a clean close-and-reopen (client explicitly tears down SSE, opens WebSocket, re-handshakes MCP `initialize`), because the client resets its cursor deliberately and the server treats it as a new session. ## Decision Boundary The guardrail is a **session-scoped monotonic event counter that survives transport epochs**, plus an explicit **transport-epoch marker** in the resume handshake so the client can detect when its cursor is stale. Concretely, the server must: - Assign event ids from a **session-level** counter, not a per-connection counter. The SSE epoch consumes `1..N`; the WebSocket epoch continues at `N+1`. The `id` space is the session's logical event log, not the transport's. - On upgrade, emit a control frame (e.g., `event: transport-epoch`, `data: {"from":"sse","to":"ws","cursor":N}`) so the client knows the numbering continues and can validate its `Last-Event-ID` against `N`. - On resume, if the presented `Last-Event-ID` is **greater than the server's current head** (impossible in a monotonic log — indicates the client is from a different epoch or a stale session), the server must reject with a `409`-equivalent MCP error rather than replay from head. Replaying from head is the silent-corruption path. The client must: - Treat `Last-Event-ID` as **opaque and session-scoped**, never reset it on transport upgrade, and never assume a WebSocket's first frame id is `1` in a resumed session. - Attach a **client-generated idempotency key** to every `tools/call`, independent of the transport event id, so a replayed request can be deduplicated server-side. The event id is a *stream cursor*; the idempotency key is a *request identity*. Conflating them is the root error. The decision boundary: **if the server cannot prove that the presented `Last-Event-ID` lies within its current session log's contiguous range, it must fail the resume, not guess.** A resume that replays from head is a correctness violation disguised as availability. ## Operational Effect Without the guardrail, the observable effects on an agent session are: - **Duplicate side-effecting tool calls.** `shell.exec` commands run twice; `filesystem.write` produces doubled appends; `http.post` fires twice. The agent's reasoning loop sees two results for one request and either double-counts or, worse, treats the second as a fresh observation and diverges. - **Lost results in the seam gap.** If the upgrade drops a frame between the SSE tail and the WebSocket head (a real race when the server closes SSE before the `101` is fully flushed), the `tools/call` result is simply gone. The client's cursor advances past it on the next epoch, and the agent waits on a future that will never resolve — a token-budget-exhausting hang. - **Non-deterministic replay.** Because the replay is triggered by reconnect timing (NAT timeout, load-balancer idle reset), the same agent trace can succeed or duplicate depending on network jitter. This makes the failure unreproducible in CI and invisible in logs unless the server logs both epochs' cursors side by side. The architectural fix is cheap once identified: one session counter, one epoch marker, one idempotency key. The cost of *not* fixing it is an agent that occasionally executes a destructive tool twice and cannot tell you why. ```python from dataclasses import dataclass class TransportEpochDesyncError(RuntimeError): """Raised when a client's Last-Event-ID cannot be placed in the server's current session log — typically because an SSE->WebSocket upgrade renumbered the event stream and the client's cursor is from the prior epoch.""" @dataclass class SessionLog: session_id: str head: int = 0 # session-scoped monotonic counter, survives epochs epoch: str = "sse" # current transport epoch label def next_id(self) -> int: self.head += 1 return self.head def resume_stream(log: SessionLog, last_event_id: int | None) -> int: """Return the id from which to replay. Must NOT replay from head on a desynced cursor — that silently duplicates in-flight tools/call frames.""" if last_event_id is None: return log.head # fresh client, no replay if last_event_id > log.head: # Cursor is ahead of the session log. In a monotonic session-scoped # counter this is impossible; it means the client is from a different # epoch (e.g. a WebSocket-phase id presented after an SSE re-establish) # or a stale session. Refuse rather than guess. raise TransportEpochDesyncError( f"session={log.session_id} epoch={log.epoch} " f"last_event_id={last_event_id} head={log.head}: " f"cursor outside contiguous log; refusing head-replay" ) if last_event_id < log.head - 1_000: # Cursor is far behind; replay window exceeded. Explicit failure is # safer than a partial replay that may drop a pending tools/call. raise TransportEpochDesyncError( f"session={log.session_id} last_event_id={last_event_id} " f"head={log.head}: replay window exceeded" ) return last_event_id def upgrade_transport(log: SessionLog, to_epoch: str) -> dict: """Upgrade SSE->WS while preserving the session-scoped id counter.""" if to_epoch == log.epoch: raise TransportEpochDesyncError( f"session={log.session_id}: upgrade to identical epoch {to_epoch!r}" ) prior = log.epoch cursor = log.head log.epoch = to_epoch return {"from": prior, "to": to_epoch, "cursor": cursor} ```