# When must an instance reject SSE-to-WebSocket upgrade resumption after an MCP streamable-session reconnect **Date of Record:** 2026 November 29 **Scope:** Applies to MCP servers and clients using the streamable HTTP transport where a session may be resumed via `Last-Event-ID` replay and where the transport permits an in-band upgrade from `text/event-stream` to WebSocket. Does not apply to pure stdio transports, nor to stateless MCP servers that mint a fresh session per request. ## Core Distinction The failure is not "the WebSocket upgrade failed." The failure is that the upgrade *succeeded* and the resuming instance accepted a replayed event stream whose sequence numbers were generated under the SSE framing and then continued emitting under WebSocket framing, silently renumbering. There are two distinct notions of continuity that operators routinely conflate: 1. **Transport continuity** — the TCP-level session and the `Mcp-Session-Id` header survived across the reconnect. 2. **Logical stream continuity** — the ordered sequence of JSON-RPC messages the agent's reasoning loop has already consumed, identified by a monotonically increasing event ID. An SSE-to-WebSocket upgrade preserves (1) trivially and can destroy (2) invisibly, because the SSE `id:` field and the WebSocket message ordering are governed by different, non-interoperable cursors. The invariant that must hold: **a resumption is valid only if the event-ID namespace of the replay is byte-identical to the namespace the client last observed, and the framing transition does not renumber the cursor.** An upgrade that crosses the framing boundary without an explicit cursor handshake violates this invariant even though every individual message is well-formed. ## What Was Observed An agent worker held an MCP session against a streamable-HTTP server. The server emitted SSE events with `id:` values of the form `sess-7f3a:00000000000000000042`. The agent consumed through event `...0042`, then its HTTP/1.1 chunked connection was torn down by an intermediary proxy at the 60-second idle mark. The client reconnected with `Last-Event-ID: sess-7f3a:00000000000000000042` and, per server policy, the connection was offered an upgrade to WebSocket mid-stream (`HTTP/1.1 101 Switching Protocols` carried in the SSE comment channel as a non-standard `event: upgrade` hint). The server's WebSocket emitter used a *different* internal cursor counter — a per-connection `ws_seq` starting at 1 — because the WebSocket code path had never been wired to the SSE event-ID allocator. The replay therefore delivered: - Events `...0043` through `...0051` correctly over the SSE frame (the replay buffer). - Then, on upgrade, a WebSocket frame carrying a `notifications/tools/list_changed` message with sequence `1`, followed by `2`, `3`. The agent's stream-consumer tracked "highest seen ID" as an opaque string and compared lexicographically. `"1"` sorts below `"sess-7f3a:...0051"`, so the consumer treated the post-upgrade messages as *out of order* and buffered them indefinitely waiting for a gap-fill that would never arrive. The agent stalled mid-tool-call: it had issued a `tools/call` before the disconnect, the result arrived as post-upgrade sequence `4`, and the consumer refused to release it because `4 < 0051`. The task deadlocked with the tool result sitting in a reorder buffer, the model's context never receiving it, and no error surfaced — the transport was healthy, the WebSocket ping/pong was clean, and the session was "alive" for 40 minutes until the outer token budget expired. A second, subtler variant: when the server *did* share the cursor allocator but incremented it across the upgrade, the replayed SSE tail and the first WebSocket frame could carry the *same* sequence number (the allocator was read, not advanced, at the framing switch). The consumer deduplicated the legitimate post-upgrade message against the last replayed SSE message and dropped it. In this case the dropped message was a `notifications/progress` update; the agent's watchdog saw no progress and re-issued the same `tools/call`, producing a duplicate side effect (a file appended twice). ## Condition of Validity Resumption across a framing upgrade is valid **if and only if** all of the following hold simultaneously: 1. **Cursor namespace identity.** The event-ID emitted by the first post-upgrade WebSocket frame is strictly greater, under the *server's own comparison function*, than the last event ID the client consumed pre-upgrade — and the client is told which comparison function to use (numeric, lexicographic, or opaque-with-server-ordering). Opaque string IDs that "look numeric" are the classic trap: `"1"` vs `"sess-...:42"` is not a numeric comparison, it is a string-prefix comparison, and the two disagree. 2. **No cursor re-derivation at the framing boundary.** The upgrade must *inherit* the allocator state, not reinitialize it. A per-connection `ws_seq` that starts at 1 is a violation by construction. 3. **Explicit upgrade acknowledgment in the logical stream.** The upgrade itself must be represented as a sequenced event in the same namespace (e.g. `event: transport.upgrade` with its own `id:`), so the client can distinguish "the framing changed" from "the stream skipped." 4. **Replay completeness before upgrade.** The server must not offer the upgrade until it has drained the SSE replay buffer up to the client's `Last-Event-ID`; offering the upgrade mid-replay means the client's reorder buffer and the framing switch interleave. 5. **Idempotency of the in-flight call.** Because the duplicate-side-effect variant is reachable, any `tools/call` outstanding at the moment of upgrade must be paired with a server-side dedup key so a re-issue after a spurious progress-timeout does not double-apply. If any of these is unmet, the correct client behavior is to **reject the upgrade and force a fresh SSE resumption** (or a full session re-establishment with explicit state reconciliation), not to accept the WebSocket and hope the ordering works out. ## Decision Boundary The decision the client must make on receiving an upgrade hint is binary and must be made *before* consuming any post-upgrade frame: - **Accept the upgrade** only when the server advertises a cursor-compatibility token (e.g. `Mcp-Cursor-Namespace: ` in the 101 handshake) that matches the namespace hash the client recorded at session start, *and* the first post-upgrade frame's ID is strictly greater than the last consumed ID under the declared comparator. - **Reject the upgrade** when the namespace hash is absent, mismatched, or when the first post-upgrade ID fails the monotonicity check. Rejection means: close the WebSocket, reconnect over SSE with the last good `Last-Event-ID`, and if the SSE replay cannot bridge the gap, escalate to a full session re-init with an explicit `state/reconcile` exchange listing the last N consumed message IDs. The boundary is sharp because the cost of a wrong accept is a silent stall or a duplicate side effect (both expensive and hard to attribute), while the cost of a wrong reject is one extra SSE reconnect (cheap). The asymmetry means the default must be reject-on-ambiguity. A client that "tries the upgrade and falls back on error" will not fall back, because the failure mode produces no error — it produces a healthy socket and a frozen reasoning loop. ## Operational Effect Enforcing the invariant changes three things in practice: - **Server implementers** must thread a single monotonic allocator across both framings and emit a sequenced `transport.upgrade` event; the per-connection `ws_seq` shortcut is banned. - **Client implementers** must treat event IDs as namespace-scoped opaque tokens with a server-declared comparator, never as bare integers, and must gate upgrade acceptance on a namespace hash exchanged at session start. - **Operators** gain a detectable signal: a stall where the transport is healthy but no `tools/call` result reaches the model within the expected window should be triaged as a suspected cursor-namespace mismatch, not as a model hang. The triage query is "what was the last consumed event ID, and what was the first post-upgrade ID, and do they compare correctly under the declared comparator?" The deeper lesson for agent systems: session resumption is a *logical* guarantee, and transport-level continuity (a surviving `Mcp-Session-Id`, a clean 101 handshake) is not evidence of it. An agent that equates "the socket came back" with "my stream is intact" will, under exactly the upgrade conditions above, continue executing against a stream it has silently fallen behind on — and the failure will look like a reasoning failure rather than a transport one. ```python from __future__ import annotations from dataclasses import dataclass from typing import Optional class CursorNamespaceMismatch(RuntimeError): """Raised when an SSE->WebSocket upgrade would break logical stream continuity.""" @dataclass(frozen=True) class Cursor: namespace_hash: str # hash of the ID namespace, exchanged at session start last_event_id: str # opaque token, compared via server-declared comparator comparator: str # "numeric" | "lexicographic" | "server_ordered" def _compare(a: str, b: str, comparator: str) -> int: if comparator == "numeric": return (int(a) > int(b)) - (int(a) < int(b)) if comparator == "lexicographic": return (a > b) - (a < b) raise CursorNamespaceMismatch(f"unknown comparator {comparator!r}") def accept_upgrade( held: Cursor, advertised_namespace_hash: Optional[str], first_post_upgrade_id: Optional[str], ) -> None: """ Gate acceptance of an SSE->WebSocket upgrade on logical stream continuity. Returns None on accept; raises CursorNamespaceMismatch on reject. """ if advertised_namespace_hash is None: raise CursorNamespaceMismatch( "upgrade handshake omitted cursor namespace hash; " "cannot prove replay shares the pre-upgrade ID space" ) if advertised_namespace_hash != held.namespace_hash: raise CursorNamespaceMismatch( f"namespace hash mismatch: held={held.namespace_hash!r} " f"advertised={advertised_namespace_hash!r}" ) if first_post_upgrade_id is None: raise CursorNamespaceMismatch( "no sequenced frame after 101; upgrade event not represented in stream" ) if _compare(first_post_upgrade_id, held.last_event_id, held.comparator) <= 0: raise CursorNamespaceMismatch( f"post-upgrade id {first_post_upgrade_id!r} does not advance past " f"last consumed {held.last_event_id!r} under {held.comparator!r}; " "reject upgrade and resume over SSE" ) # accept: caller may now consume WebSocket frames under the same cursor def resume_session(held: Cursor, upgrade_offer: dict) -> str: try: accept_upgrade( held, upgrade_offer.get("namespace_hash"), upgrade_offer.get("first_id"), ) return "websocket" except CursorNamespaceMismatch: # Fall back to SSE resumption with the last known-good cursor. return "sse" ```