# Under what conditions must an instance treat an MCP SSE-to-WebSocket upgrade as a session-resumption boundary rather than a transport swap **Date of Record:** 2026 November 27 **Scope:** Applies to MCP clients and servers that expose the HTTP-native transport with a `text/event-stream` (SSE) streaming leg and negotiate an in-place upgrade to WebSocket mid-session, where the client holds a resumption token (`Last-Event-ID` / `session_id`) issued before the upgrade. Does not apply to pure stdio transports, to fresh WebSocket sessions with no prior SSE leg, or to stateless one-shot request/response MCP deployments. ## Core Distinction A transport upgrade is not a session continuation. When an MCP server accepts an `Upgrade: websocket` request on a connection that previously carried an SSE stream, it establishes a *new* framing layer, a *new* flow-control regime, and — critically — a *new* server-side dispatch context unless the server explicitly rehydrates the pre-upgrade session. The SSE leg and the WebSocket leg are two different state machines that happen to share a `session_id` string. The invariant that must hold is: > For every event the server emitted on the SSE leg with sequence `n`, either that event was acknowledged by the client (via `Last-Event-ID` on resumption) *or* it is replayed on the WebSocket leg before any new event with sequence `> n` is dispatched. Most implementations violate this because the upgrade handshake is treated as an HTTP concern (RFC 6455) while the MCP session is treated as an application concern, and nothing in the protocol mandates that the two be joined atomically. The failure is silent: the client resumes, receives events `n+1, n+2, ...`, and never learns that event `n` — often a `tools/call` result or a `notifications/cancelled` — was dropped in the gap between the last SSE flush and the WebSocket `101 Switching Protocols` completion. ## What Was Observed A client agent issued `tools/call` for a long-running operation, received `202 Accepted` with `Mcp-Session-Id: s-7f3a` and an SSE stream. The server emitted `event: message` frames with `id: 41`, `id: 42` (a progress notification), then the client's HTTP/2 connection was reaped by an intermediate load balancer at the 60s idle boundary while the tool was still executing. The client reconnected with `Last-Event-ID: 42` and, per server config `upgrade_on_resume: true`, the server responded `101 Switching Protocols` and immediately pushed the tool result as a WebSocket text frame — but *without* an `id` field, because WebSocket frames have no native event-ID semantics and the server's replay buffer was keyed only on the SSE path. The trace: 1. SSE leg: events `41`, `42` delivered; client `Last-Event-ID=42`. 2. Connection dropped; server's tool completes, emits result as event `43` into the (now-dead) SSE writer, which buffers it keyed on `s-7f3a`. 3. Client reconnects, requests upgrade. Server's upgrade handler creates a fresh `WebSocketSession` bound to `s-7f3a` but *does not* consult the SSE replay buffer — it only re-attaches the live tool-result future. 4. Result arrives on WS as a raw frame. Client's resumption logic, which expected `id: 43` to reconcile against `Last-Event-ID: 42`, sees an un-sequenced frame and — depending on client strictness — either drops it as out-of-band or processes it while still believing event `43` is missing. 5. On the *next* reconnect (WS drop), the client sends `Last-Event-ID: 42` again (it never advanced), and the server — whose replay buffer now has `43` — replays it. The client processes the tool result **twice**. The duplicate `tools/call` result was idempotent in this case (a read), but the same mechanism on a `filesystem/write` or `payments/charge` tool would have double-applied. The observed non-obvious property: **the upgrade silently reset the client's sequence watermark to a stale value while simultaneously delivering the event that should have advanced it.** ## Condition of Validity The "transport swap is safe" assumption is valid only under the conjunction: - The server's replay buffer is keyed on `(session_id, last_event_id)` and is shared across *all* transport legs of that session, not per-connection. - Every event emitted on any leg carries a monotonically increasing `id` that the client can reconcile, including WebSocket frames (which requires the server to wrap WS payloads in an envelope that carries the SSE `id`, or to send a synthetic `id`-bearing control frame before each data frame). - The upgrade handshake is *transactional* with respect to the session: the server must, before sending `101`, compute `pending = buffer[session_id].events_after(last_event_id)` and either (a) flush `pending` as sequenced frames before any live event, or (b) reject the upgrade and force SSE resumption. If any of these fails, the upgrade is a resumption boundary and must be treated as such: the client must not advance its watermark on un-sequenced frames, and must re-request replay on the new leg before trusting any post-upgrade event as "new." A second, subtler validity condition: **the server must not emit live events on the WebSocket leg until replay is drained.** If the tool result (event `43`) is pushed live by the tool-completion callback racing the upgrade handler, the client can receive `43` live *before* the replay of `43`, producing a duplicate even when the buffer is correct. This is a classic baton-passing race between the SSE writer goroutine and the WS writer goroutine; the only safe ordering is to fence the live path behind replay completion. ## Decision Boundary The client agent must decide, on receiving `101 Switching Protocols` in response to a resumption request carrying `Last-Event-ID: k`: - **Treat as continuation** (do not reset watermark) iff the first frame(s) on the WS leg are sequenced and the highest observed `id` equals `k+1` with no gaps, *and* the server advertised `replay_drained: true` in an upgrade-accept control frame. - **Treat as boundary** (reset watermark to `k`, request explicit replay, ignore un-sequenced frames until a sequenced frame with `id > k` arrives) in all other cases — including the common "server sends live result immediately" pattern observed above. The boundary is *not* "did the upgrade succeed." A `101` is a transport-layer success and carries zero information about session continuity. The decision must be driven by the presence and monotonicity of application-layer sequence IDs across the leg change, which is exactly the signal most upgrade handlers omit. For the server side, the decision boundary is: an upgrade request on a session with a non-null replay buffer must be answered with either a sequenced replay-drain-then-live protocol or a `409 Conflict` (or `426 Upgrade Required`-style refusal on the SSE leg) — never with a bare `101` followed by live frames. The refusal is the safer default because it preserves the client's watermark semantics on a transport the client already knows how to resume. ## Operational Effect The practical consequence is that an agent resuming across an upgrade must run in *replay-verification mode* until the watermark is re-established. Concretely: buffer all post-upgrade events, do not dispatch tool results to the executor, and do not advance `Last-Event-ID` until a sequenced frame confirms continuity. If no sequenced frame arrives within a bounded window (typically a few hundred ms, or one round-trip), the agent should assume the boundary was crossed, re-issue the resumption against the SSE leg (downgrade), and reconcile. This costs one extra round-trip on the upgrade path but eliminates the double-apply class of failures. The architectural guardrail is to make the sequence ID a *session-level* invariant, not a transport-level one: the MCP server should maintain a single monotonic event log per `Mcp-Session-Id`, and both SSE and WebSocket writers should draw from that log with the same `id` space. The upgrade handler then becomes a log cursor hand-off rather than a fresh connection, and the replay-drain fence becomes a simple `for e in log.after(cursor): ws.send(envelope(e))` before subscribing to live tail. Without this, every upgrade is a potential silent event loss followed by a delayed duplicate — the worst of both failure modes, because the loss is invisible and the duplicate is deferred to the next reconnect. ```python import time from dataclasses import dataclass, field from typing import Optional class ResumptionBoundaryError(RuntimeError): """Raised when an SSE->WebSocket upgrade crosses a session-resumption boundary without preserving sequence continuity.""" @dataclass class Event: seq: int payload: dict @dataclass class SessionLog: session_id: str events: list = field(default_factory=list) def append(self, payload: dict) -> Event: ev = Event(seq=(self.events[-1].seq + 1) if self.events else 1, payload=payload) self.events.append(ev) return ev def after(self, cursor: int) -> list: return [e for e in self.events if e.seq > cursor] class UpgradeResumptionGuard: """Enforces the invariant: no live dispatch on the new leg until replay of events after the client's Last-Event-ID is drained and the watermark is re-established with a sequenced frame. """ def __init__(self, log: SessionLog, last_event_id: int, drain_timeout_s: float = 0.5): self.log = log self.cursor = last_event_id self.drain_timeout_s = drain_timeout_s self._drained = False self._deadline = time.monotonic() + drain_timeout_s def on_upgrade_accept(self, server_advertised_drain: bool) -> None: if not server_advertised_drain: # Server sent a bare 101; we cannot trust live frames. raise ResumptionBoundaryError( f"upgrade for session {self.log.session_id} accepted without replay-drain " f"advertisement; treating as boundary and refusing live dispatch" ) pending = self.log.after(self.cursor) for ev in pending: self._consume_sequenced(ev) self._drained = True def on_frame(self, frame: dict) -> Optional[dict]: seq = frame.get("id") if seq is None: if not self._drained: # Un-sequenced live frame before drain: boundary crossed. raise ResumptionBoundaryError( f"un-sequenced frame on session {self.log.session_id} before replay drain; " f"event loss or duplicate-apply risk at cursor {self.cursor}" ) # Post-drain un-sequenced frame: accept but do not advance watermark. return frame.get("payload") if seq <= self.cursor: # Duplicate replay; safe to drop. return None if seq != self.cursor + 1: raise ResumptionBoundaryError( f"sequence gap on session {self.log.session_id}: expected {self.cursor + 1}, got {seq}" ) self.cursor = seq return frame.get("payload") def _consume_sequenced(self, ev: Event) -> None: if ev.seq != self.cursor + 1: raise ResumptionBoundaryError( f"replay gap on session {self.log.session_id}: expected {self.cursor + 1}, got {ev.seq}" ) self.cursor = ev.seq def assert_drained(self) -> None: if not self._drained and time.monotonic() > self._deadline: raise ResumptionBoundaryError( f"replay drain timed out for session {self.log.session_id} at cursor {self.cursor}; " f"downgrade to SSE resumption required" ) ```