# Under what conditions must an instance abandon SSE replay state when an MCP HTTP-native transport upgrades to WebSocket mid-session **Date of Record:** 2026 November 28 **Scope:** Applies to MCP HTTP-native transports that begin a session over Server-Sent Events (`text/event-stream`) and negotiate an in-band upgrade to a WebSocket channel for the same logical session, where the client relies on `Last-Event-ID` for resumption after disconnect. Does not apply to pure-SSE sessions that never upgrade, nor to sessions where the server assigns a fresh session identifier on upgrade. ## Core Distinction The failure is not "the connection dropped." The failure is that the SSE `id:` cursor and the WebSocket frame sequence are **two independent monotonic namespaces that the transport spec does not reconcile**. A client that reconnects after a mid-upgrade drop will present a `Last-Event-ID` drawn from the SSE stream to a server that has already switched its outbound ordering authority to WebSocket frame sequence numbers. The server cannot map one to the other, so it does one of three things: replays from an arbitrary SSE offset (duplicate tool results), replays nothing (silent gap), or rejects the resume (session death). The invariant that must hold — and that this transport does not guarantee — is: *event IDs are stable and totally ordered across a transport transition within a session.* ## What Was Observed A research agent executing a 14-step tool chain (web fetch → parse → summarize → write) over MCP HTTP-native transport. Step 6 (`parse`, a long-running tool call) triggered a server-side `101 Switching Protocols` upgrade because the response payload exceeded the SSE chunk budget and the server preferred binary frames. The client library accepted the upgrade, kept the same `Mcp-Session-Id` header, and continued reading frames. The upgrade itself succeeded. The bug surfaced on the *next* disconnect, three seconds later, when a load balancer recycled the SSE-side connection pool. The client reconnected with: ``` Last-Event-ID: 41 Mcp-Session-Id: sess_9f2c... ``` The server's WebSocket-side sequence counter had advanced to frame 58 during the upgrade window. Frames 42–58 (which included the completed `parse` result and two `progress` notifications for step 7) existed *only* as WebSocket frames — they had never been assigned SSE `id:` values. The server, receiving `Last-Event-ID: 41`, replayed SSE events 42 onward from the pre-upgrade ring buffer, which contained a *stale duplicate* of the `parse` invocation request but no result. The agent re-issued `parse` (it looked uncompleted), got a second result, and the downstream `summarize` step ran twice against two different parse outputs. The final written artifact was internally inconsistent: two summaries, one of a truncated parse, concatenated. The trace, condensed: | Time | Transport | Event | SSE id | WS frame | |------|-----------|-------|--------|----------| | t0 | SSE | `tool_call` parse | 40 | — | | t1 | SSE | `tool_call` parse (retry, server-side) | 41 | — | | t2 | upgrade → WS | `101` | — | — | | t3 | WS | `tool_result` parse | *(none)* | 57 | | t4 | WS | `progress` step 7 | *(none)* | 58 | | t5 | disconnect | — | — | — | | t6 | SSE resume | `Last-Event-ID: 41` | — | — | | t7 | SSE | replay `tool_call` parse | 42 | — | | t8 | SSE | replay `tool_call` parse | 43 | — | Two `tool_call` events for the same logical call, zero `tool_result`. The agent's step-6 state machine saw "call issued, no result" and re-executed. ## Condition of Validity The resume contract is only valid when **all three** hold simultaneously: 1. **Namespace continuity** — every outbound frame, regardless of transport, carries an identifier drawn from a single monotonically increasing sequence scoped to the session, and the server's replay buffer indexes on that sequence, not on transport-local counters. 2. **Cursor translation** — on upgrade, the server records the mapping `(last SSE id) ↔ (first WS frame)` and, on any subsequent SSE resume, translates the presented `Last-Event-ID` into the frame-space cursor before deciding what to replay. 3. **Atomicity of the upgrade boundary** — the frames emitted *during* the upgrade handshake (between `101` acceptance and the first client-acknowledged WS frame) are durably buffered and addressable by the replay mechanism. If any one is absent, `Last-Event-ID` is a lie. In the observed system, condition 1 failed (WS frames had no SSE id), condition 2 was never implemented, and condition 3 held only for the SSE side. The transport *looked* resumable because the SSE side was resumable; the illusion of continuity is what makes this non-obvious. ## Decision Boundary An agent instance must abandon its SSE replay cursor and treat the session as **fresh-but-tainted** (requiring idempotency reconciliation) when *any* of the following is true: - It presented a `Last-Event-ID` and observed a replay whose first event is a **duplicate of an already-completed tool call** — this is the signature of a cross-namespace replay, not a legitimate retry. - The server's `101` response did not include an explicit cursor-continuity header (e.g., `Mcp-Event-Cursor` carrying the unified sequence position), meaning the client has no basis to trust ordering across the boundary. - The number of events received since the last acknowledged checkpoint is **less than** the number the server's frame counter implies were emitted (detectable only if the server exposes a heartbeat or sequence watermark; if it does not, the client must assume loss). Conversely, the instance may *safely* resume with `Last-Event-ID` only when the upgrade response carried an explicit unified-cursor assertion and the replayed event stream's first id is strictly greater than the last id the client durably recorded. The boundary is sharp: **presence or absence of a server-asserted cursor-continuity token at the upgrade boundary.** No token → no resumption, regardless of how clean the SSE side looks. ## Operational Effect The correct response is not "reconnect harder." It is: on detecting a cross-namespace replay, the agent must (a) freeze the step state machine at the last *durably checkpointed* step, (b) mark all in-flight tool calls as `UNKNOWN_OUTCOME` rather than `FAILED`, and (c) re-drive them through an idempotency key derived from the logical step, not the transport event id. Treating an unacknowledged call as failed is exactly the error that produced the double-`parse`. Treating it as unknown forces the agent to query tool-side idempotency (`did call X with key K already produce a result?`) before re-issuing. The architectural guardrail: **the agent's step state must never be keyed on transport event ids.** Event ids are a delivery concern; step identity is a semantic concern. Conflating them makes every transport upgrade a potential state-corruption event. A session that upgrades transports must be treated as a *new delivery channel for the same semantic stream*, and the semantic stream's checkpoints must be independently persisted (e.g., a step ledger keyed by `(session, step_index, tool, args_hash)`) so that a resume gap of arbitrary size is recoverable by reconciliation rather than replay. The cost of getting this wrong is silent: no exception is raised, no connection error surfaces, the agent simply executes a branch of its plan twice and writes a subtly wrong artifact. This is the worst class of agent failure — it passes every liveness check while violating correctness. ```python import hashlib from dataclasses import dataclass, field from enum import Enum from typing import Optional class CrossNamespaceReplayError(RuntimeError): """Raised when an SSE resume cursor cannot be trusted across a transport upgrade.""" pass class CallOutcome(Enum): PENDING = "pending" COMPLETED = "completed" UNKNOWN = "unknown" # sent, no acknowledged result, transport boundary crossed @dataclass class StepLedger: session_id: str # keyed by (step_index, tool, args_hash) -> outcome; never keyed by event id entries: dict = field(default_factory=dict) def key(self, step_index: int, tool: str, args: dict) -> tuple: args_hash = hashlib.sha256( repr(sorted(args.items())).encode() ).hexdigest()[:16] return (step_index, tool, args_hash) def record(self, step_index: int, tool: str, args: dict, outcome: CallOutcome): self.entries[self.key(step_index, tool, args)] = outcome def outcome(self, step_index: int, tool: str, args: dict) -> Optional[CallOutcome]: return self.entries.get(self.key(step_index, tool, args)) def resume_after_upgrade( ledger: StepLedger, last_event_id: int, upgrade_response_headers: dict, replayed_first_event_id: int, frames_emitted_during_upgrade: int, ) -> None: """ Decide whether the SSE Last-Event-ID cursor is trustworthy across a mid-session SSE->WebSocket upgrade. Raises if the cursor is a lie. """ continuity_token = upgrade_response_headers.get("Mcp-Event-Cursor") # Guard 1: no server-asserted cursor continuity across the boundary. if continuity_token is None: # The transport gave us no basis to map SSE ids to WS frame order. # Any replay is untrustworthy; force reconciliation path. for (step_index, tool, args_hash), outcome in list(ledger.entries.items()): if outcome is CallOutcome.PENDING: ledger.entries[(step_index, tool, args_hash)] = CallOutcome.UNKNOWN raise CrossNamespaceReplayError( f"session={ledger.session_id}: upgrade to WebSocket carried no " f"Mcp-Event-Cursor; Last-Event-ID={last_event_id} cannot be mapped " f"to {frames_emitted_during_upgrade} WS frames. " f"Marked in-flight calls UNKNOWN; re-drive via idempotency keys." ) # Guard 2: replay must be strictly forward of our durable cursor. if replayed_first_event_id <= last_event_id: raise CrossNamespaceReplayError( f"session={ledger.session_id}: replay began at id " f"{replayed_first_event_id} <= Last-Event-ID {last_event_id}; " f"duplicate replay detected, refusing to advance step state." ) # Guard 3: continuity token must agree with the replay start. if int(continuity_token) != replayed_first_event_id - 1: raise CrossNamespaceReplayError( f"session={ledger.session_id}: continuity token {continuity_token} " f"inconsistent with replay start {replayed_first_event_id}." ) # Cursor is trustworthy; safe to replay forward. ```