# How does an instance detect a half-resumed MCP stream when SSE-to-WebSocket upgrade silently rewinds the event cursor **Date of Record:** 2026 December 1 **Scope:** Applies to MCP clients that hold a streaming session over HTTP+SSE and attempt to resume after an `Last-Event-ID` reconnect, including the case where the server negotiates an upgrade to WebSocket mid-session. Does not apply to stateless request/response MCP calls or to pure WebSocket-first transports where the session cursor is never mirrored in SSE framing. ## Core Distinction The failure here is not "the stream dropped." Dropped streams are routine and the MCP SSE transport is explicitly designed to survive them: the client reconnects with `Last-Event-ID`, the server replays events after that cursor, and the session continues. The non-obvious distinction is between **resumption that replays the correct suffix** and **resumption that silently rewinds to an earlier cursor** because the upgrade negotiation reset the server's per-session event log to the WebSocket handshake's notion of "now." When an MCP server accepts an HTTP `Upgrade: websocket` on the same session that was previously served as SSE, two independent cursors exist: the SSE `Last-Event-ID` the client believes it holds, and the WebSocket frame sequence the server begins emitting after the 101 Switching Protocols. If the server does not translate the former into the latter, the client resumes into a stream that is *valid framing but wrong position*—it looks like a successful resume and produces duplicate or skipped tool-call results with no transport-level error. This is the boundary: **a resume is only valid if the post-upgrade stream's first event sequence number is strictly greater than the client's last acknowledged `Last-Event-ID`, and the server must prove this in-band.** ## What Was Observed A client agent was mid-task executing a multi-step tool chain: `read_file` → `grep` → `patch`. The SSE connection dropped after the server emitted event `id: 41` (the `grep` result). The client reconnected with `Last-Event-ID: 41`. The server, configured to prefer WebSocket for long-lived sessions, responded with `101 Switching Protocols`. The first WebSocket text frame carried `{"id": 42, "result": ...}` — but `id: 42` was the *patch* result, not a replayed `grep` tail. The server had advanced its internal cursor to 42 during the gap because the patch had already been dispatched to the sandbox, and the WebSocket channel had no knowledge that the client had never received 42's *predecessor* events (the `grep` streaming deltas at ids 39–40 that were emitted between the client's last read and the drop). The client's resume logic saw a contiguous-looking stream starting at 42 and treated it as a clean resume. It never saw the `grep` deltas 39–40. Its reasoning state now believed the grep returned zero matches (default when no delta arrived), and it issued a second `patch` against a file the first patch had already modified—producing a corrupt diff. No exception was raised anywhere: the transport was healthy, framing was valid, the session id matched. The observable signature was subtle: the first post-upgrade event id was `42`, but the client's last acknowledged id was `41`, and the server never sent a replay of `39–40` because it had already garbage-collected them under the assumption that the WebSocket upgrade implied "start fresh from current state." The gap was exactly the events emitted *between* the client's disconnect and the server's upgrade acceptance—a window the server treated as delivered but the client never received. ## Condition of Validity The invariant that makes resume safe across an SSE→WebSocket upgrade is: > For a session with last client-acknowledged event id `L`, the server MUST, on any transport transition, either (a) replay every event with id in `(L, first_post_upgrade_id)` before emitting the first post-upgrade event, or (b) refuse the upgrade and continue on SSE until the client's cursor catches up to the server's emission head. Violations occur when the server's event log is truncated at upgrade time, when the WebSocket channel is initialized with a fresh sequence space (ids restart at 0 or 1), or when the server treats the upgrade as a new session and only carries over the session *token* but not the *cursor*. The client-side validity check is necessary but not sufficient: the client can only detect a rewind if it compares the first post-upgrade event id against `L` and rejects any id `> L+1`. A first event id of exactly `L+1` is the only safe post-upgrade boundary. An id of `L+1` with a sequence-space reset (id restarts at 1 after upgrade) is indistinguishable from a legitimate continuation unless the server echoes a monotonic `stream_epoch` or the session's original `Last-Event-ID` in the upgrade response headers. The validity condition therefore requires an **epoch marker**: the 101 response must include a header (e.g., `Mcp-Stream-Epoch`) or the first WebSocket frame must carry `{"epoch": N, "resume_from": L}` such that the client can assert `epoch == prior_epoch` and `resume_from == L`. Without this, a rewound stream is cryptographically and structurally indistinguishable from a resumed one. ## Decision Boundary The decision the runtime must make at the upgrade boundary is binary and must be made *before* any post-upgrade event is admitted into the agent's reasoning state: - **Accept** the upgraded stream only if the first post-upgrade event's id is `L+1` (contiguous) **and** the epoch marker equals the pre-upgrade epoch **and** the server's `resume_from` echoes `L`. In this case the client may discard its SSE reconnect buffer and continue. - **Reject and rewind** if the first post-upgrade event id is `> L+1` (gap) or `<= L` (rewind) or the epoch marker is absent or mismatched. On rejection the client must not admit the event, must tear down the WebSocket, must re-establish SSE with the original `Last-Event-ID: L`, and must force the server to replay from `L` before any upgrade is reconsidered. The boundary is deliberately strict because the cost asymmetry is severe: a false accept injects a reasoning-state corruption that is silent and compounds across subsequent tool calls, whereas a false reject costs one reconnect round-trip. The runtime should treat *any* ambiguity—missing epoch header, non-contiguous id, id reset—as a reject. There is no "probably fine" branch. ## Operational Effect The operational consequence of missing this boundary is not a visible crash but a **reasoning-state fork**: the agent's belief about tool outputs diverges from the server's actual execution history, and every subsequent action is taken against the forked state. In the observed case the fork manifested as a duplicate `patch` and a corrupted diff—an error that surfaced three tool calls later and was attributed to the patch tool rather than to the transport. Debugging the patch tool would have been wasted effort; the root cause was a resume that admitted event 42 without 39–40. The guardrail is a client-side resume validator that runs on every transport transition, compares the first post-transition event against the last acknowledged id, and raises a hard failure rather than admitting an out-of-contiguity event. The validator must be transport-agnostic: the same check applies to SSE reconnect, WebSocket upgrade, and any future transport that carries the MCP session. The server-side obligation is symmetric: never truncate the event log below the client's acknowledged cursor, and always emit an epoch marker on upgrade. A server that cannot guarantee replay for `(L, head]` must refuse the upgrade and hold the client on SSE until the cursor catches up—the upgrade is an optimization, not a license to discard the client's position. ```python class StreamResumeViolation(RuntimeError): """Raised when a post-upgrade MCP stream does not contiguously resume from the client's last acknowledged event id.""" pass def validate_upgrade_resume( last_ack_id: int, prior_epoch: int, first_event: dict, upgrade_headers: dict, ) -> None: """Assert that the first event on the upgraded transport is a valid continuation of the pre-upgrade SSE stream. Raises StreamResumeViolation if the stream rewound, gapped, or lost its epoch marker. Must be called BEFORE admitting first_event into agent reasoning state. """ epoch = upgrade_headers.get("Mcp-Stream-Epoch") resume_from = upgrade_headers.get("Mcp-Resume-From") if epoch is None or resume_from is None: raise StreamResumeViolation( "upgrade missing epoch/resume_from headers; " "cannot distinguish resume from rewind" ) if int(epoch) != prior_epoch: raise StreamResumeViolation( f"epoch mismatch: prior={prior_epoch} upgrade={epoch}; " "server reset stream sequence space" ) if int(resume_from) != last_ack_id: raise StreamResumeViolation( f"resume_from={resume_from} != last_ack_id={last_ack_id}" ) first_id = first_event.get("id") if first_id is None: raise StreamResumeViolation("first post-upgrade event has no id") if first_id <= last_ack_id: raise StreamResumeViolation( f"stream rewound: first_id={first_id} <= last_ack_id={last_ack_id}" ) if first_id != last_ack_id + 1: raise StreamResumeViolation( f"stream gap: first_id={first_id} but expected {last_ack_id + 1}; " f"events ({last_ack_id}, {first_id}) were dropped" ) ```