# Where must an instance draw the line between SSE replay and WebSocket resumption when an MCP session upgrades mid-stream? **Date of Record:** 2026 November 24 **Scope:** Applies to MCP servers exposing both a legacy HTTP+SSE transport and a WebSocket transport on the same session namespace, where a client is permitted to negotiate an upgrade of an in-flight streaming session. Does not apply to pure-SSE servers, pure-WebSocket servers, or stateless request/response MCP endpoints where no server-side session events are replayed. ## Core Distinction The failure is not "the upgrade dropped messages." It is a **sequence-identity split**: SSE replay and WebSocket resumption each carry their own notion of the last-delivered event, and the MCP session has exactly one authoritative `Last-Event-ID` cursor. An instance that treats the upgrade as a *transport swap* rather than a *cursor handoff* will silently accept a re-delivered or skipped event, because SSE replay is idempotent-by-ID while WebSocket frames are ordered-by-connection, and nothing in either transport reconciles the two orderings. Concretely: SSE guarantees "resume from `Last-Event-ID` + 1, replay anything missed." WebSocket guarantees "frames arrive in send order on this socket, and nothing before the socket opened exists." When a session upgrades at event `N`, the WebSocket server has no memory of events `1..N`; it must inherit the cursor from the SSE side. If it instead starts a fresh sequence counter at `0` (or at `N+1` with a *new* epoch), the client's dedup logic—keyed on `(session_id, event_id)`—will either drop legitimate post-upgrade events (collision) or accept a replayed pre-upgrade event as new (epoch mismatch). ## What Was Observed A client agent was mid-task, awaiting a long-running tool result streamed as MCP `notifications/tools/progress` events over SSE. At event `id=47` the client initiated an `Upgrade: websocket` handshake per the server's advertised capability. The server completed the 101 handshake, closed the SSE stream, and began emitting progress frames on the WebSocket. Two failures compounded: 1. **Cursor reset.** The WebSocket handler initialized its outbound sequence at `1`. The client, which had persisted `last_event_id=47` in its checkpoint, received `id=1, 2, 3...` and rejected them as stale (its invariant was monotonic non-decreasing event IDs within a session). The client then attempted SSE resumption against the now-closed SSE endpoint, received `410 Gone`, and declared the session `UNRECOVERABLE`. 2. **In-flight gap.** Events `48` and `49`—emitted between the server's decision to upgrade and the actual 101 response—were written to neither transport. The SSE writer had been detached; the WebSocket writer had not yet been attached. This is the classic **handoff gap window**, and it is bounded only by the server's internal scheduling, not by anything the client can observe. The agent's recovery logic then did the worst possible thing: it re-issued the original tool call, because it could not distinguish "session wedged" from "tool never started." The server, which had no idempotency key on the tool invocation, executed it twice. The observable symptom was a duplicated side effect (a file written twice), not a transport error—which is why this class of bug survives staging. ## Condition of Validity The invariant that must hold across the upgrade is: > For a session `S` with a monotonic event log `E = {e_1 ... e_k}` and a transport transition `T_sse → T_ws` at cursor `c`, the WebSocket transport MUST emit events starting at `e_{c+1}` under the *same* `session_id` and the *same* monotonic `event_id` namespace, and MUST NOT emit any event with `event_id ≤ c` unless explicitly requested via a resume frame carrying `Last-Event-ID = c`. This requires the upgrade to be a **stateful handoff**, not a fresh connection. The server must: - Freeze the SSE writer at a known cursor `c` *before* sending 101. - Buffer events `c+1 ...` emitted during the gap window into a per-session queue. - On 101 completion, drain the queue onto the WebSocket in order, tagged with the inherited cursor. - Reject any client resume frame whose `Last-Event-ID` is less than `c` (it has already been superseded) or greater than the highest emitted (client is ahead—impossible unless corrupt). The condition fails silently when the server treats the WebSocket as a new subscriber (fresh cursor) or when the gap window is not buffered (events lost). It also fails when the client's dedup key omits the transport epoch—so a legitimate post-upgrade `event_id` that happens to collide with a pre-upgrade one (because the server reset) is either wrongly dropped or wrongly accepted. ## Decision Boundary The boundary an instance must resolve before initiating an upgrade: - **If the current SSE cursor is quiescent** (no events in flight, no pending tool progress), upgrade is safe: the handoff has an empty gap window and cursor inheritance is trivially verifiable. Proceed. - **If the SSE cursor is active** (events flowing, tool in progress), upgrade is only safe if the server advertises a `session.resume` capability with explicit cursor inheritance, *and* the client has persisted `last_event_id`. Otherwise the client must **not** upgrade mid-stream; it must drain the SSE stream to completion or to a checkpointed quiescent point first. - **If the server advertises upgrade but not cursor inheritance**, treat the WebSocket as a *new session* with a new `session_id`, and require the client to re-establish tool context under an idempotency key. Do not reuse the old session's dedup state. The instance must also refuse to replay a tool invocation on transport failure without an idempotency key. Transport unrecoverability is not evidence of tool non-execution. ## Operational Effect The guardrail is a **cursor handoff contract** enforced at three points: (a) the server buffers the gap window and inherits the cursor; (b) the client validates monotonicity against the inherited epoch, not against a fresh counter; (c) the client distinguishes `TRANSPORT_UNRECOVERABLE` from `TOOL_FAILED` and never re-issues a side-effecting call without an idempotency key. Absent (a), events are lost in the gap. Absent (b), legitimate events are dropped as stale or replays are accepted as new. Absent (c), the transport bug manifests as duplicated side effects—the most expensive possible failure surface, because it is invisible to transport-level monitoring. The empirical rule: **an MCP session upgrade is a state transfer, and state transfer without a cursor is a fork.** The instance must either inherit the cursor or declare a new session; it must never do neither. ```python import time from dataclasses import dataclass, field from typing import Optional class CursorHandoffError(RuntimeError): """Raised when an SSE->WebSocket upgrade breaks the session event-cursor invariant.""" pass @dataclass class SessionEvent: session_id: str event_id: int epoch: str # transport epoch: "sse" or "ws:" @dataclass class SessionCursor: session_id: str last_event_id: int = 0 epoch: str = "sse" gap_buffer: list = field(default_factory=list) def negotiate_upgrade(cursor: SessionCursor, ws_epoch: str, gap_events: list, ws_first_event_id: int) -> SessionCursor: """ Enforce the cursor-handoff contract at the server boundary. Invariants: - ws_first_event_id MUST equal cursor.last_event_id + 1 (no reset, no gap). - Every gap event MUST be buffered and drained in order. - The new epoch MUST be recorded so the client can distinguish replays. """ expected_first = cursor.last_event_id + 1 if ws_first_event_id != expected_first: raise CursorHandoffError( f"WS cursor reset on session {cursor.session_id}: " f"expected first event_id={expected_first}, got {ws_first_event_id}. " f"Upgrade is a state transfer, not a new session." ) # Gap window must be accounted for: events emitted between SSE freeze and 101. for gap_ev in gap_events: if gap_ev.session_id != cursor.session_id: raise CursorHandoffError( f"Gap event belongs to foreign session {gap_ev.session_id}" ) if gap_ev.event_id != cursor.last_event_id + 1: raise CursorHandoffError( f"Gap window out of order: expected {cursor.last_event_id + 1}, " f"got {gap_ev.event_id}" ) cursor.gap_buffer.append(gap_ev) cursor.last_event_id = gap_ev.event_id if cursor.last_event_id + 1 != ws_first_event_id: raise CursorHandoffError( f"Gap buffer did not close the window: last_event_id=" f"{cursor.last_event_id}, ws_first={ws_first_event_id}" ) cursor.epoch = ws_epoch return cursor def client_accept(client_cursor: SessionCursor, incoming: SessionEvent) -> bool: """ Client-side dedup: monotonic within inherited epoch, reject stale replays. """ if incoming.session_id != client_cursor.session_id: raise CursorHandoffError( f"Event for foreign session {incoming.session_id}" ) if incoming.event_id <= client_cursor.last_event_id: # Replay of an already-delivered event: drop, do not re-execute. return False if incoming.event_id != client_cursor.last_event_id + 1: raise CursorHandoffError( f"Client cursor gap: expected {client_cursor.last_event_id + 1}, " f"got {incoming.event_id}. Transport lost events; do not re-issue tool." ) client_cursor.last_event_id = incoming.event_id client_cursor.epoch = incoming.epoch return True # --- Demonstration of the failure trace --- if __name__ == "__main__": cur = SessionCursor(session_id="s-1", last_event_id=47, epoch="sse") gap = [SessionEvent("s-1", 48, "sse"), SessionEvent("s-1", 49, "sse")] # Correct upgrade: inherits cursor, drains gap, starts at 50. negotiate_upgrade(cur, "ws:conn-a", gap, ws_first_event_id=50) assert cur.last_event_id == 49 and cur.epoch == "ws:conn-a" # Buggy upgrade: WS handler reset its counter to 1. try: bad = SessionCursor(session_id="s-2", last_event_id=47, epoch="sse") negotiate_upgrade(bad, "ws:conn-b", gap_events=[], ws_first_event_id=1) except CursorHandoffError as e: print(f"[BLOCKED] {e}") ```