What happens when an instance resumes an MCP SSE stream across a mid-flight transport upgrade to WebSocket

**Date of Record:** 2026 December 1 **Scope:** Applies to MCP clients and servers that negotiate an HTTP-native transport (SSE for server→client, POST for client→server) and support resumption via `Last-Event-ID`, where the server may independently advertise a WebSocket upgrade mid-stream. Does not apply to pure stdio transports, nor to deployments where the upgrade is negotiated only at connection establishment (pre-stream).

Core Distinction

The MCP spec's resumability model assumes a *single logical event log* per stream, keyed by monotonically increasing event IDs, replayable from any `Last-Event-ID`. The SSE-to-WebSocket upgrade breaks this assumption in a way that is easy to miss: **the two transports do not share an event namespace unless the server explicitly bridges them.** SSE event IDs are assigned by the SSE writer; WebSocket frames carry no inherent ID field. When a server upgrades mid-stream, it typically (a) drains the SSE connection, (b) opens a WebSocket, and (c) begins emitting frames from a *new* counter or from a shared ring buffer that was never reconciled with the SSE `id:` field.

The distinction that matters: **resumption is not "reconnect and ask for events after N." It is "prove that event N+1 exists in the same monotonic sequence the client last observed."** An upgrade that silently restarts the sequence converts a resumable stream into a lossy one, and the client has no way to detect the loss from the transport layer alone—it only sees frames arriving.

What Was Observed

A client holds an SSE stream from an MCP server, last received `id: 4417`. The connection drops (proxy idle timeout, 30s). The client reconnects per spec: `GET /mcp/stream` with `Last-Event-ID: 4417`. The server's upgrade logic has, in the intervening window, transitioned the session to WebSocket-backed delivery and now responds with `101 Switching Protocols` after the initial HTTP handshake, then emits frames.

Three failure traces were observed:

  1. **Silent sequence reset.** The WebSocket-backed emitter starts at frame index `0` (its own counter). The client receives frames it interprets as "new events" (they are new—they're the *current* state deltas), but the events between `4418` and the upgrade boundary are never replayed. The client's tool-call state machine has a gap: a `tool_result` for a call it never saw dispatched. The agent then either hallucinates the missing call or aborts with an opaque parse error.
  1. **Duplicate replay under dual-emit.** A more careful server bridges the SSE log to WebSocket by replaying from a shared buffer. But the buffer stores *serialized SSE lines* including the `id:` prefix; the WebSocket bridge strips it and re-encodes as JSON, losing the ID. On the next reconnect, the client sends `Last-Event-ID: 4417` again, the server replays from the buffer start (it can't correlate the client's SSE ID to its WebSocket frame index), and the client receives events `4418..4420` a second time. A non-idempotent tool call (e.g., `write_file`) executes twice.
  1. **Upgrade negotiation race.** The client's resumption `GET` arrives while the server is mid-upgrade. The server accepts the SSE request, assigns IDs `4418, 4419`, then *also* completes the pending WebSocket upgrade for the same session and routes subsequent events there. The client now has two live channels: an SSE stream that goes silent after `4419` and a WebSocket that carries `4420+` but with no `Last-Event-ID` semantics. The client's resumption logic, keyed on SSE, blocks forever waiting for `4420` on the wrong channel.

The invariant that was violated in all three cases: **the resumption cursor namespace must be transport-invariant.** The MCP resumability contract is only meaningful if `Last-Event-ID` identifies a position in a sequence that survives transport changes.

Condition of Validity

Resumption across an SSE→WebSocket upgrade is only valid when the server satisfies all of:

If any of these is absent, the upgrade is a *transport migration*, not a *resumption*, and the client must treat it as a cold restart (re-initialize MCP session, re-fetch tool list, re-establish state) rather than a resume.

Decision Boundary

The client cannot distinguish "resumed correctly" from "silently lossy" by inspecting frames. It must make a policy decision at the upgrade boundary:

The boundary is sharp: *continuity proof or cold restart.* There is no safe "best effort" middle ground, because a single missed `tool_result` can corrupt an agent's reasoning more than a full restart.

Operational Effect

The practical consequence is that **MCP resumption must be modeled as a cursor-continuity protocol, not a reconnect protocol.** Agents that treat `Last-Event-ID` as "where to resume reading" and the upgrade as "same stream, faster pipe" will silently lose events at every upgrade boundary and will exhibit exactly the symptoms that look like model hallucination (phantom tool calls, duplicated side effects, stuck-awaiting-tool states) but are in fact transport-layer cursor discontinuities.

The guardrail is a hard invariant enforced on both sides: one logical log, transport-invariant IDs, atomic upgrade with replay-or-refuse, and a client-side continuity check that fails closed to cold restart. The code below encodes the client-side check as an explicit exception path so that a violation is a loud, typed failure rather than a silent state corruption.

from __future__ import annotations

import dataclasses
from typing import Optional


class StreamContinuityError(RuntimeError):
    """Raised when a resumed/upgraded MCP stream fails to prove cursor continuity.

    This is a fail-closed signal: the caller must NOT continue on the stream
    and must escalate to cold restart (re-initialize the MCP session).
    """


@dataclasses.dataclass(frozen=True)
class Frame:
    event_id: int
    transport: str  # "sse" | "ws"
    payload: dict


def verify_upgrade_continuity(
    last_sse_event_id: int,
    first_ws_frame: Frame,
    *,
    replay_complete_id: Optional[int] = None,
) -> int:
    """Verify that a WebSocket upgrade continued the SSE event log.

    Returns the new cursor (the highest event id proven contiguous).
    Raises StreamContinuityError if continuity cannot be proven.

    Contract:
      - If the server sent an explicit replay_complete control frame covering
        [last_sse_event_id + 1, replay_complete_id], the first live ws frame
        must be > replay_complete_id.
      - Otherwise, the first ws frame must be exactly last_sse_event_id + 1.
    """
    if first_ws_frame.transport != "ws":
        raise StreamContinuityError(
            f"expected ws frame at upgrade boundary, got {first_ws_frame.transport!r}"
        )

    if replay_complete_id is not None:
        if replay_complete_id < last_sse_event_id:
            raise StreamContinuityError(
                f"replay_complete_id {replay_complete_id} precedes client cursor "
                f"{last_sse_event_id}; server replayed from the wrong position"
            )
        if first_ws_frame.event_id <= replay_complete_id:
            raise StreamContinuityError(
                f"first live ws frame id {first_ws_frame.event_id} falls inside "
                f"replayed range (<= {replay_complete_id}); duplicate delivery risk"
            )
        return first_ws_frame.event_id

    # No explicit replay control frame: require exact +1 continuation.
    expected = last_sse_event_id + 1
    if first_ws_frame.event_id != expected:
        raise StreamContinuityError(
            f"cursor discontinuity across upgrade: expected event {expected}, "
            f"got {first_ws_frame.event_id} "
            f"(delta={first_ws_frame.event_id - expected}); "
            "server likely reset its sequence on ws handoff"
        )
    return first_ws_frame.event_id


def resume_stream(
    client,
    last_event_id: int,
    *,
    allow_upgrade: bool = True,
) -> int:
    """Attempt resumption; fail closed to cold restart on continuity violation."""
    try:
        stream = client.reconnect(last_event_id=last_event_id, allow_upgrade=allow_upgrade)
        if stream.transport == "ws":
            first = stream.next_frame()
            return verify_upgrade_continuity(last_event_id, first)
        return last_event_id  # plain SSE resume; server owns replay
    except StreamContinuityError:
        # Loud, typed failure. Caller must cold-restart, not continue.
        raise
    except Exception as exc:  # transport-level failure, still fail closed
        raise StreamContinuityError(
            f"resumption failed at transport layer: {exc!r}"
        ) from exc