# What happens when an instance negotiates an SSE-to-WebSocket upgrade mid-stream and the MCP session ID is rebound to a different transport epoch **Date of Record:** 2026 December 3 **Scope:** Applies to MCP servers exposing HTTP-native streaming (SSE) that additionally offer a WebSocket upgrade path for the same logical session, where the client initiates the upgrade while an SSE event stream is still open. Does not apply to pure stdio transports, to servers that terminate the SSE stream before accepting the upgrade, or to stateless request/response MCP profiles. ## Core Distinction The failure is not "the upgrade failed." The failure is that the upgrade *succeeded* on the wire while the logical MCP session silently forked into two transport epochs that both believe they own the same `Mcp-Session-Id`. HTTP-native SSE and WebSocket are two different continuity substrates: SSE is a one-way, cursor-based, resumable stream keyed by `Last-Event-ID`; WebSocket is a bidirectional, unordered-at-framing, non-resumable channel keyed by the socket lifetime. When an instance upgrades without an explicit epoch handoff, in-flight JSON-RPC responses that were queued against the SSE cursor are never delivered on the WebSocket, and the WebSocket side has no mechanism to request them because it does not carry the SSE event cursor. The session ID survives; the *position within the session* does not. This is distinct from ordinary reconnect amnesia. On a clean reconnect, the client replays `Last-Event-ID` and the server resumes. On an upgrade, the client abandons the cursor by design — the WebSocket handshake has no field for it — so the server has to decide, unilaterally, what to do with responses that were serialized into the SSE buffer but not yet flushed. Most servers drop them. The instance then continues issuing tool calls against a session whose prior tool-call results were never observed, producing reasoning divergence that is invisible in the transcript because the *request* was acknowledged at the HTTP layer. ## What Was Observed A tool-calling agent running against an MCP server with `text/event-stream` responses issued `tools/call` for a long-running operation (a filesystem scan returning ~40 KB of structured results). At t+0 the SSE stream emitted the `message` event header for the response but the payload was chunked and the stream was still open. At t+180ms the client — reacting to a server-advertised `Upgrade: websocket` capability in the initial SSE `endpoint` event — opened the WebSocket handshake on the same session ID. The server accepted the upgrade at t+210ms, closed the SSE stream, and began routing subsequent JSON-RPC frames over the WebSocket. The `tools/call` response was flushed to the SSE stream at t+260ms — *after* the upgrade completed. The server's SSE writer had already been detached from the session's outbound queue; the response was written into a closed stream and discarded. The WebSocket side never saw it. The client's JSON-RPC layer, having sent the request before the upgrade and having received no response on either transport, timed out the request at t+30s and retried it. The retry succeeded. The agent now had *two* results for the same tool call — the retry's result, and (because the tool was not idempotent) a second filesystem mutation — and reasoned over a state that assumed one scan had occurred. The critical detail: no error was surfaced. The upgrade returned `101 Switching Protocols`. The SSE close was clean. The retry was a normal client-side timeout. Every layer reported success or a routine timeout; the divergence was entirely in the gap between the two transport epochs. ## Condition of Validity The invariant that must hold is: **a session's transport epoch must be monotonic, and every in-flight request must be either (a) resolved in the epoch in which it was issued, or (b) explicitly re-queued into the new epoch with a server-generated replay token that the client echoes.** The failure requires all of: 1. The server advertises an upgrade path while an SSE stream is open (rather than only at stream boundaries). 2. The server does not drain the SSE outbound queue to the WebSocket before detaching the SSE writer. 3. The client does not carry the SSE `Last-Event-ID` into the upgrade request (it cannot, per the WebSocket handshake — this is structural, not a client bug). 4. The agent's JSON-RPC layer treats a timeout as a retriable transport error rather than as an ambiguous-outcome condition requiring reconciliation. Remove any one and the failure does not occur. (4) is the one the agent controls, and it is the one most agents get wrong: a timeout on a *stateful* tool call is not a retry signal, it is an "unknown whether the side effect occurred" signal. ## Decision Boundary The boundary is between **transport-level resumption** and **session-level reconciliation**. These are not the same operation and must not share a code path. - Transport-level resumption (SSE `Last-Event-ID`, WebSocket reconnect with a resume token) assumes the server holds the outbound queue and can replay from a cursor. It is valid only within a single transport epoch. - Session-level reconciliation (re-issuing an ambiguous request with an idempotency key, or querying the server for the outcome of a specific request ID) is required whenever the epoch changes, because the cursor is not portable across epochs. An instance must classify every in-flight request at upgrade time as either *epoch-local* (safe to drop and retry) or *epoch-crossing* (must be reconciled by request ID, never blindly retried). The classification is a property of the tool, not the transport: read-only tools are epoch-local; mutating tools are epoch-crossing. An agent that does not carry this classification will retry mutating calls across an upgrade and double-apply side effects. ## Operational Effect The observable effect is a **silent duplicate side effect plus a reasoning divergence**. The agent's transcript shows one logical tool call, two transport attempts, one visible result. Its subsequent reasoning is built on a world model that is wrong in a way the transcript does not reveal — the second filesystem mutation exists but was never observed as a distinct event. Downstream, this manifests as state drift that only surfaces when a later tool reads the mutated resource and returns a value inconsistent with the agent's prior reasoning, at which point the agent typically re-derives a false causal story rather than suspecting the transport. The guardrail is an epoch fence: the server must, on accepting an upgrade, emit a `session/epoch` notification on the *new* transport listing every request ID that was in-flight at upgrade time and whose outcome is unknown, and the client must refuse to retry any of those IDs until it receives an explicit outcome or a `session/reconcile` response. The agent must treat the upgrade itself as a state transition requiring a checkpoint, not as a transparent transport swap. ```python import hashlib from dataclasses import dataclass, field from enum import Enum from typing import Optional class TransportEpochError(RuntimeError): """Raised when a request crosses a transport epoch boundary without reconciliation.""" pass class ToolClass(Enum): EPOCH_LOCAL = "epoch_local" # read-only; safe to retry across upgrade EPOCH_CROSSING = "epoch_crossing" # mutating; must reconcile by request_id @dataclass class InFlightRequest: request_id: str tool_name: str tool_class: ToolClass idempotency_key: str epoch: int @dataclass class SessionEpochFence: session_id: str current_epoch: int = 0 in_flight: dict[str, InFlightRequest] = field(default_factory=dict) reconciled: set[str] = field(default_factory=set) def register(self, req: InFlightRequest) -> None: if req.epoch != self.current_epoch: raise TransportEpochError( f"request {req.request_id} registered against stale epoch " f"{req.epoch}, current is {self.current_epoch}" ) self.in_flight[req.request_id] = req def upgrade(self) -> tuple[int, list[InFlightRequest]]: """Advance the epoch. Returns the new epoch and the requests that must be reconciled.""" self.current_epoch += 1 stranded = [ r for r in self.in_flight.values() if r.tool_class is ToolClass.EPOCH_CROSSING ] # Epoch-local requests are dropped from the ledger; they may be retried freely. for r in list(self.in_flight.values()): if r.tool_class is ToolClass.EPOCH_LOCAL: del self.in_flight[r.request_id] return self.current_epoch, stranded def retry(self, request_id: str) -> None: req = self.in_flight.get(request_id) if req is None: return if req.tool_class is ToolClass.EPOCH_CROSSING and request_id not in self.reconciled: raise TransportEpochError( f"refusing to retry epoch-crossing request {request_id} " f"(tool={req.tool_name}, idem={req.idempotency_key}) " f"without reconciliation; side effect may already have applied" ) del self.in_flight[request_id] def reconcile(self, request_id: str, outcome_hash: str) -> None: req = self.in_flight.get(request_id) if req is None: raise TransportEpochError(f"reconcile for unknown request {request_id}") expected = hashlib.sha256(req.idempotency_key.encode()).hexdigest()[:16] if not outcome_hash.startswith(expected): raise TransportEpochError( f"reconciliation hash mismatch for {request_id}: " f"expected prefix {expected}, got {outcome_hash[:16]}" ) self.reconciled.add(request_id) del self.in_flight[request_id] def handle_upgrade(fence: SessionEpochFence) -> None: new_epoch, stranded = fence.upgrade() if stranded: # The agent MUST NOT proceed until every stranded request is reconciled. ids = ", ".join(r.request_id for r in stranded) raise TransportEpochError( f"session {fence.session_id} advanced to epoch {new_epoch} with " f"{len(stranded)} stranded epoch-crossing request(s): {ids}. " f"Emit session/epoch fence and await reconciliation before any tool call." ) ```