What happens when an instance resumes an MCP stream across an SSE-to-WebSocket upgrade and replays a stale Last-Event-ID

**Date of Record:** 2026 December 1 **Scope:** Applies to MCP servers and clients using HTTP-native transport (Streamable HTTP with SSE response streams) that negotiate an upgrade to WebSocket mid-session while carrying resumption state via `Last-Event-ID`. Does not cover pure stdio transport, pure SSE (legacy HTTP+SSE), or stateless request/response MCP calls that never establish a resumable stream.

Core Distinction

The failure is not "the stream dropped." Streams drop constantly and MCP's resumption contract is designed for that: the client reconnects with `Last-Event-ID: N` and the server replays events `N+1…`. The non-obvious failure is that **the event-ID namespace is transport-scoped, not session-scoped**, and an SSE-to-WebSocket upgrade silently re-bases it. The SSE leg assigns monotonically increasing integer IDs from a per-connection counter; the WebSocket leg, when the server implementation reuses a generic event emitter, starts a *fresh* counter at 1 (or reuses a per-request counter). A resuming client that presents `Last-Event-ID: 47` to the upgraded WebSocket leg is asking for event 47 in a namespace where the highest emitted ID is 3. The server has two legal-looking responses: replay nothing (treat 47 as "beyond head, client is caught up") or replay from 1 (treat 47 as "unknown, restart"). Both are wrong in different ways, and the protocol does not distinguish them from a legitimate resume.

The invariant that is violated: **a resumption token is only meaningful within the identity domain of the stream that issued it.** MCP's SSE resumption assumes a single logical stream with a stable ID space for the life of the session. The HTTP-native upgrade path breaks that assumption because the transport identity changes (`text/event-stream` connection → WebSocket connection) while the session identity is supposed to persist. Nothing in the upgrade handshake carries the event-ID high-water mark across the boundary.

What Was Observed

A client agent was mid-task, executing a multi-step tool-call loop (read file → parse → invoke downstream tool → summarize) against an MCP server that had just been reconfigured to prefer WebSocket for bidirectional streaming. The sequence:

  1. Session established over SSE. Server emits events with IDs `1, 2, 3, … 47`. Client has consumed through 47 and is awaiting the result of a long-running `invoke_downstream` tool call (event 48 is the pending response).
  2. Network blip at t+90s. SSE connection drops. Client's resumption logic fires correctly: it reconnects to the MCP endpoint with `Last-Event-ID: 47`.
  3. The server, now behind a load balancer that routes to a WebSocket-capable backend, responds to the reconnect with `101 Switching Protocols` and opens a WebSocket. The upgrade negotiation succeeds. The server's WebSocket event emitter initializes a fresh counter.
  4. Server, on the upgraded leg, receives the client's resume request. Because the WebSocket framing does not carry `Last-Event-ID` as a header (it was sent on the HTTP request that *became* the upgrade), the server-side handler reads the header from the upgrade request object, sees `47`, and compares against its new counter head (`0`). It concludes the client is ahead of the stream and sends nothing.
  5. Client waits. The pending `invoke_downstream` result (event 48 on the old leg) was emitted to the old SSE buffer, which was discarded on connection close. On the new leg, the server's tool-call registry still holds the pending call, but the result will be emitted as event `1` in the new namespace — and the client is not listening for event 1 because it believes it is at 47.
  6. Deadlock. Client's read timeout (120s) fires, it reconnects again with `Last-Event-ID: 47`, gets `101`, gets silence. Loop.

The observable signature in logs: repeated `101 Switching Protocols` with no subsequent `event:` frames, client-side `resume timeout` warnings, and a server-side tool-call registry entry that never gets acknowledged. The agent's task state is frozen mid-loop with a tool call that has *completed server-side* but whose result is unreachable client-side.

A second variant was observed where the server, on seeing `Last-Event-ID: 47` against a fresh counter, chose to replay "from the beginning" and re-emitted events `1, 2, 3` — which were *different* events (a new tool invocation's progress frames), not the original events 1–3. The client applied them as if they were the continuation of the original stream, corrupting its reasoning state with progress frames from a tool call it never initiated on this leg.

Condition of Validity

This failure requires all of the following to hold simultaneously:

It does **not** apply when: the server maintains a session-scoped monotonic event log independent of transport (the correct design); when the client treats transport change as a session reset and re-initializes; or when the upgrade happens at session start before any events are emitted.

Decision Boundary

The architectural guardrail is a **transport-generation epoch** carried in both the upgrade handshake and every resumption token. Concretely:

The boundary condition: if the server cannot guarantee session-scoped event-log retention across the upgrade, it must **not** present the upgraded transport as session-preserving. It must force a session re-initialization and let the client replay its own task state from its last checkpoint. A partial guarantee (session preserved but event log not) is worse than no guarantee, because it produces the silent deadlock above.

Operational Effect

The practical consequence is that an agent's task can hang indefinitely with a tool call that has *succeeded server-side* but is *unreachable client-side*, and no timeout in either the client or server will surface the true cause — both sides believe they are behaving correctly per the protocol. The agent's reasoning loop sees "tool call pending," the server sees "result emitted, awaiting ack," and the reconciliation never happens because the ID namespaces don't intersect.

For agent operators, the mitigation is: (1) treat any transport upgrade as a session-event-log checkpoint boundary and verify the server's epoch handling before enabling WebSocket preference; (2) on the client side, never resume with a bare integer `Last-Event-ID` against a transport that differs from the one that issued it — require the epoch qualifier or force re-init; (3) instrument for the specific signature of `101` followed by no frames, which is the deadlock fingerprint, and fail fast rather than retrying the same resume token.

import time
from dataclasses import dataclass, field
from typing import Optional


class TransportEpochMismatch(RuntimeError):
    """Raised when a resumption token's transport epoch does not match the
    current transport epoch and the server cannot safely replay the gap."""
    pass


@dataclass
class EventLog:
    """Session-scoped event log. Survives transport re-binding. This is the
    source of truth; transports are views over it."""
    events: list = field(default_factory=list)  # list of (epoch, seq, payload)
    max_retention: int = 1000

    def append(self, epoch: int, seq: int, payload: dict) -> None:
        self.events.append((epoch, seq, payload))
        if len(self.events) > self.max_retention:
            self.events.pop(0)

    def replay_after(self, epoch: int, seq: int) -> list:
        """Return all events strictly after (epoch, seq) in session order.
        Ordering is by session-scoped seq, not by transport arrival."""
        out = []
        for e_epoch, e_seq, payload in self.events:
            if (e_epoch, e_seq) > (epoch, seq):
                out.append(payload)
        return out


@dataclass
class MCPSession:
    session_id: str
    transport_epoch: int = 0
    session_seq: int = 0
    log: EventLog = field(default_factory=EventLog)

    def bind_transport(self) -> int:
        """Called on every transport re-binding (SSE reconnect, WS upgrade).
        Advances the epoch but NOT the seq counter."""
        self.transport_epoch += 1
        return self.transport_epoch

    def emit(self, payload: dict) -> str:
        self.session_seq += 1
        self.log.append(self.transport_epoch, self.session_seq, payload)
        return f"{self.transport_epoch}:{self.session_seq}"


def resume_stream(session: MCPSession, last_event_id: str) -> list:
    """Resume a stream given a Last-Event-ID of the form '<epoch>:<seq>'.

    The critical guardrail: if the token's epoch is older than the current
    transport epoch, we MUST replay from the session log across the epoch
    boundary. If the log cannot cover the gap, we MUST raise an explicit
    error rather than silently returning nothing (which produces the
    deadlock where the client waits forever for an event it already missed).
    """
    try:
        token_epoch_str, token_seq_str = last_event_id.split(":", 1)
        token_epoch = int(token_epoch_str)
        token_seq = int(token_seq_str)
    except (ValueError, AttributeError) as exc:
        raise TransportEpochMismatch(
            f"malformed Last-Event-ID {last_event_id!r}: expected '<epoch>:<seq>'"
        ) from exc

    if token_epoch > session.transport_epoch:
        raise TransportEpochMismatch(
            f"token epoch {token_epoch} is ahead of current transport epoch "
            f"{session.transport_epoch}; client is from a future transport "
            f"binding and cannot be safely resumed"
        )

    if token_epoch < session.transport_epoch:
        # Transport re-based. The only safe behavior is to replay from the
        # session log across the epoch boundary. Verify the log can cover it.
        oldest = session.log.events[0] if session.log.events else None
        if oldest is None or (oldest[0], oldest[1]) > (token_epoch, token_seq):
            raise TransportEpochMismatch(
                f"transport epoch advanced {token_epoch}->{session.transport_epoch} "
                f"and event log cannot cover the gap from ({token_epoch},{token_seq}); "
                f"oldest retained is {oldest[:2] if oldest else None}. "
                f"Client must re-initialize the session, not resume."
            )
        return session.log.replay_after(token_epoch, token_seq)

    # Same epoch: normal in-transport resumption.
    if token_seq > session.session_seq:
        raise TransportEpochMismatch(
            f"token seq {token_seq} exceeds session head {session.session_seq} "
            f"within epoch {token_epoch}; refusing to treat as caught-up"
        )
    return session.log.replay_after(token_epoch, token_seq)


# --- Reproduction of the observed failure ---
if __name__ == "__main__":
    sess = MCPSession(session_id="s-1")
    sess.bind_transport()  # epoch 1: SSE
    for i in range(47):
        sess.emit({"progress": i})
    # client is at "1:47". SSE drops. Upgrade to WebSocket:
    sess.bind_transport()  # epoch 2: WS, seq counter NOT reset

    # A naive server that reset seq on upgrade would now have head=0 and
    # silently return [] for "1:47". The guarded version replays correctly:
    replayed = resume_stream(sess, "1:47")
    assert replayed == [], "nothing new since 1:47"

    # The pending tool result arrives on the new leg:
    new_id = sess.emit({"tool_result": "ok"})  # -> "2:48"
    replayed = resume_stream(sess, "1:47")
    assert replayed == [{"tool_result": "ok"}], replayed

    # Demonstrate the guardrail firing when the log cannot cover the gap:
    sess.log.events.clear()
    try:
        resume_stream(sess, "1:47")
    except TransportEpochMismatch as exc:
        print(f"guardrail fired: {exc}")