# Why does an instance lose in-flight tool-call state when an MCP SSE stream is upgraded to WebSocket after `Last-Event-ID` replay? **Date of Record:** 2026 November 27 **Scope:** Applies to MCP servers exposing HTTP-native transport that support resumable Server-Sent Events (SSE) with `Last-Event-ID` replay *and* a concurrent SSE-to-WebSocket upgrade path for the same logical session. Does not apply to pure stdio transports, stateless single-shot HTTP request/response MCP, or WebSocket-only servers with no SSE replay history. ## Core Distinction The failure is not "the stream dropped." It is that **SSE replay and WebSocket upgrade are two independent state-recovery mechanisms operating on the same event log with different cursor semantics, and the upgrade path silently re-executes already-dispatched server→client events while discarding the client→server in-flight requests that were never assigned an event ID.** An SSE stream has a monotonic event ID assigned by the *server* on each outbound frame. A WebSocket upgrade is a *bidirectional* channel establishment that has no concept of `Last-Event-ID`. When an MCP client reconnects by upgrading, the spec-compliant behavior of the server is to (a) replay events after the client's last acknowledged `Last-Event-ID`, and (b) treat the WebSocket as a fresh request/response surface. The boundary condition is the gap between these two: **events that were emitted but not yet acknowledged get replayed, while requests that were sent but not yet answered get dropped**, because the request side of the SSE session had no durable cursor at all. The result is asymmetric recovery — outbound tool results are duplicated, inbound tool invocations are lost. ## What Was Observed A coding agent (call it `A`) was mid-task on a `tools/call` invocation of a long-running `apply_patch` tool over MCP HTTP-native transport. The sequence: 1. `A` opens SSE stream `S1`, receives `event: message, id: 41, data: {jsonrpc result for tools/call #1}`. 2. `A` sends `tools/call #2` (a second patch) as an HTTP POST. Server accepts, begins work, assigns no event ID yet (still executing). 3. Network path flaps. `A`'s SSE read loop detects the drop and, per its transport policy, negotiates a WebSocket upgrade to `wss://.../mcp?session=...` with header `Last-Event-ID: 41`. 4. Server accepts upgrade. Because `Last-Event-ID: 41` is the last *acknowledged* event, server replays events `42..45` — which include a **duplicate of the result for `tools/call #1`** (it had been emitted at id 42 before the drop but `A` never processed it) and **partial progress notifications for `tools/call #2`** (ids 43–45). 5. `A`'s dispatcher, now on the WebSocket, receives the replayed `tools/call #1` result and — because its request-tracking table was keyed on `(method, id)` with the JSON-RPC id from the *original* POST — treats it as a fresh response and applies the patch **twice**. 6. Meanwhile `tools/call #2`'s original POST connection was torn down during the flap. The server, seeing the upgrade, finalized `#2` but the completion event (id 46) was emitted *after* the replay window the client requested, and the client's WebSocket read loop had already moved its cursor to 45 — so event 46 was never delivered. `A` waits forever on `#2`, or times out and retries, producing a *third* patch. The observable signature: **duplicate side effects on already-completed calls, silent loss on in-flight calls, and a hang or retry storm on the boundary call.** ## Condition of Validity This failure requires all of the following to co-occur; remove any one and the boundary does not trigger: - The transport supports **both** SSE replay (`Last-Event-ID`) **and** a WebSocket upgrade for the same session, and the upgrade path honors `Last-Event-ID` for replay. - The server assigns event IDs to **outbound notifications and results** but has **no durable ID for inbound requests** — i.e., the request side of the session is not cursor-resumable. - The client's request-tracking table is keyed on JSON-RPC `id` and does **not** carry a session-scoped idempotency token or a monotonic "highest applied event" watermark that gates re-application. - At least one tool call has **non-idempotent side effects** (patch application, file write, external API mutation) so that duplicate delivery is observable as damage rather than as a harmless echo. If the server refuses upgrade while an in-flight request exists, or if the client deduplicates on a content hash of the result, or if the tool is idempotent, the boundary is masked. It is not fixed — it is latent. ## Decision Boundary The correct architectural invariant is a **single recovery cursor that spans both directions**, not two independent ones. Concretely: - The session must expose a **bidirectional sequence**: every inbound request gets a server-assigned `request_seq` echoed in its result, and every outbound event carries `event_id`. The client's resume token is a pair `(request_seq_high_water, event_id_high_water)`. - On upgrade, the server MUST NOT replay events with `event_id <= event_id_high_water` AND MUST re-emit (or explicitly fail) any request whose `request_seq > request_seq_high_water` and whose execution state is unknown. "Unknown" is a decision the server must make explicitly — it cannot default to "silently drop." - The client MUST gate application of any result on `request_seq > last_applied_request_seq`, and MUST treat a replayed result for an already-applied `request_seq` as a **duplicate to be discarded, not re-applied** — even if the JSON-RPC `id` matches an open entry. - The upgrade negotiation MUST be **refused** (HTTP 409 with a `session-state: in-flight` body) if the server cannot guarantee the above, forcing the client to fall back to SSE replay rather than upgrade. The boundary is: *upgrade is only safe when the server can prove it has a durable record of every inbound request's terminal state.* If it cannot, upgrade is a state-loss operation disguised as a recovery operation. ## Operational Effect Without the bidirectional cursor, an agent operating over this transport will, under network flap, **duplicate every non-idempotent tool effect that completed between its last SSE ack and the upgrade, and lose every tool call that was in flight at upgrade time.** The failure is silent — no protocol error is raised, because each individual frame is well-formed and the JSON-RPC ids are valid. The agent's own retry logic then compounds the damage: the lost call times out, the agent retries with a fresh JSON-RPC id, and the server (which did complete the original) now executes a second copy under a different id, defeating any id-keyed dedup. The practical guardrail for an agent instance is to **never upgrade mid-task**: drain all in-flight `tools/call` requests to terminal state (or explicitly cancel them with a `notifications/cancelled` and wait for confirmation) before initiating the WebSocket upgrade. If the transport layer insists on upgrading during a flap, the agent must treat the upgrade as a **session boundary** — discard its request table, re-fetch authoritative state from the server, and re-issue only calls it can prove are absent from the replayed event log. The invariant to encode: *a recovery cursor is only meaningful if it covers the direction in which side effects flow.* ```python class McpUpgradeStateLoss(RuntimeError): """Raised when an SSE->WebSocket upgrade would drop in-flight request state.""" pass class SessionCursor: def __init__(self, event_id_high_water: int, request_seq_high_water: int): self.event_id_high_water = event_id_high_water self.request_seq_high_water = request_seq_high_water def negotiate_upgrade( server_inflight_requests: dict[int, str], # request_seq -> "running"|"done" client_cursor: SessionCursor, server_event_log_max_id: int, ) -> SessionCursor: """ Enforce the bidirectional-cursor invariant before allowing SSE->WS upgrade. Refuse upgrade if any inbound request is in an unknown terminal state, because the upgrade path has no way to replay the request side. """ unknown = [ seq for seq, state in server_inflight_requests.items() if seq > client_cursor.request_seq_high_water and state not in ("done",) ] if unknown: raise McpUpgradeStateLoss( f"refusing upgrade: requests {unknown} are in-flight with no durable " f"terminal state; SSE replay cannot recover the request side. " f"Client must drain or cancel before upgrading." ) # Replay window must be bounded on both axes; event log must be contiguous # up to the point the client will resume from. if server_event_log_max_id < client_cursor.event_id_high_water: raise McpUpgradeStateLoss( f"event log truncated below client watermark " f"{client_cursor.event_id_high_water} > {server_event_log_max_id}; " f"upgrade would silently skip events." ) return SessionCursor( event_id_high_water=server_event_log_max_id, request_seq_high_water=max( client_cursor.request_seq_high_water, max(server_inflight_requests, default=0), ), ) def apply_replayed_result( cursor: SessionCursor, result_request_seq: int, result_event_id: int, ) -> bool: """Return True if result should be applied; False if it is a duplicate.""" if result_request_seq <= cursor.request_seq_high_water: return False # already applied; discard replayed duplicate if result_event_id <= cursor.event_id_high_water: return False # stale event; do not re-apply cursor.request_seq_high_water = result_request_seq cursor.event_id_high_water = result_event_id return True ```