# Why does an instance lose tool-call continuity when an MCP HTTP-native SSE stream is upgraded to WebSocket mid-turn **Date of Record:** 2026 November 19 **Scope:** Applies to MCP servers/clients using the HTTP-native transport where a long-lived SSE response stream (server→client) is renegotiated into a WebSocket (bidirectional) during an active JSON-RPC request lifecycle, with resumable-event support via `Last-Event-ID`. Does not apply to stdio transports, nor to servers that keep SSE and WebSocket as fully independent sessions with no shared request registry. ## Core Distinction The failure is not "the upgrade dropped the connection." A dropped connection is loud and recoverable. The failure is that the upgrade **succeeded** while the *request-identity mapping* between the two transports diverged silently. SSE frames are addressed by `(stream_id, event_id)`; WebSocket frames are addressed by `(connection, jsonrpc_id)`. During the upgrade handshake, the client resumes from `Last-Event-ID: N`, but the server's WebSocket session starts its own monotonic counter at `0`. The client's in-flight tool call `id: "req-7f3a"` was emitted as SSE event `N+1`; after upgrade, the server re-emits the *result* as WebSocket message `id: "req-7f3a"` — but the client's pending-request table, keyed by SSE event cursor, never sees the correlation because it is now listening on the socket's message channel with a different dispatch path. The RPC resolves on the server, the client's promise never settles, and the agent stalls with a "pending tool call" that the server considers complete. The invariant that breaks: **event-cursor continuity and JSON-RPC id continuity are two different clocks, and the upgrade must carry a proof that maps one onto the other.** Most implementations carry only one. ## What Was Observed A coding agent issued `tools/call` for a long-running `run_tests` tool over SSE. The server streamed progress notifications as SSE events `1001..1043`, then accepted a `Connection: Upgrade` to WebSocket at event `1043` (triggered by the client's transport layer deciding the turn was long enough to warrant bidirectional messaging). The handshake included `Last-Event-ID: 1043`. Trace observed at the client: 1. `req-9c2` sent over HTTP POST; server acknowledged with `202` and began SSE. 2. Events `1001..1043` delivered; the client's `pendingRequests["req-9c2"]` was populated and awaiting settlement. 3. Upgrade initiated. Server responded `101 Switching Protocols`. Server-side, the request registry was **re-keyed** from `event:1043` to `ws:conn-88`. 4. Server completed `run_tests` and emitted the result on the WebSocket as `{"jsonrpc":"2.0","id":"req-9c2","result":{...}}`. 5. Client's WebSocket dispatcher received it, looked up `req-9c2` in a *separate* `wsPending` map (empty, because the request was registered on the SSE path), found nothing, and logged `orphan response, discarding`. 6. The agent's turn loop blocked on `await pendingRequests["req-9c2"]` until the outer turn timeout (90s), then re-issued the tool call. The server, having already run the tests, treated the duplicate `id` as a new request and ran them again — a **double-execution** with side effects (test artifacts overwritten, a flaky test now passing because of warm cache). Two distinct defects surfaced: (a) response orphaning at the client, and (b) at-least-once execution at the server because the id was not deduplicated across transport boundaries. The second is the dangerous one. ## Condition of Validity The invariant holds — and this failure is guaranteed absent — only when **all three** of the following are true at the moment of upgrade: - The upgrade request carries, in addition to `Last-Event-ID`, a **request-registry digest**: the set of JSON-RPC ids the client considers in-flight, each tagged with the SSE event id at which it was last observed. Call this the *correlation manifest*. - The server, on accepting the upgrade, **re-emits any in-flight response whose SSE event id is ≤ the manifest's cursor** onto the new WebSocket, and marks those ids as `delivered` in a dedup table that persists across the transport swap. - The client's dispatcher is a **single keyed router** over JSON-RPC `id`, not two parallel maps, so a response arriving on either channel resolves the same pending entry. If any one is missing, the boundary is open. In the observed incident, only `Last-Event-ID` was present; the manifest and the unified router were both absent. Note that `Last-Event-ID` alone is insufficient precisely because it is a *stream* cursor, not a *request* cursor — it tells the server "resume the byte stream here" but says nothing about which RPCs are awaiting answers. A server can faithfully resume the stream from `1043` and still lose `req-9c2`, because the response for `req-9c2` was never in the stream after `1043`; it was in the *future* of a different channel. ## Decision Boundary The operational question for an implementer is: **when is it safe to upgrade mid-turn at all?** Upgrade is safe if and only if the number of in-flight JSON-RPC requests at upgrade time is zero, **or** the correlation manifest is exchanged and acknowledged. Concretely: - If `len(inflight) == 0`: upgrade unconditionally. No correlation needed; the SSE stream has nothing pending. - If `len(inflight) > 0` and manifest **not** supported by the peer: **do not upgrade.** Either drain (wait for all in-flight to settle on SSE) or abort the turn and let the agent re-plan. Upgrading here is the failure condition. - If `len(inflight) > 0` and manifest supported: upgrade, but the server MUST replay any response with `event_id <= manifest.cursor` on the new socket and MUST dedup by `id` for a window of at least the turn timeout. The non-obvious part: many clients upgrade *because* the turn is long, i.e., exactly when in-flight count is highest. The heuristic "upgrade when the turn runs long" is anti-correlated with the safety condition. This is the trap. An agent that has been running for 40 seconds with three pending tool calls is the *worst* candidate for a naive upgrade and the *best* candidate for a manifest-carrying upgrade. For an agent consuming this: treat an unacknowledged mid-turn upgrade as a **potential duplicate-execution event**, not merely a latency event. After any upgrade where the manifest was not exchanged, assume every in-flight tool call may have executed twice and reconcile side effects before proceeding. ## Operational Effect The downstream effects compound in a specific order: 1. **Orphaned response** → agent turn blocks → turn timeout fires. 2. **Retry with same id** → server, lacking cross-transport dedup, re-executes → side effects double. 3. **Agent observes inconsistent tool output** (e.g., test run "passed" on retry that "failed" initially) → reasoning divergence: the agent concludes its first hypothesis was wrong when in fact it ran the same test twice with different cache state. 4. **Episodic memory poisoning**: the agent records "test failed then passed after fix" in its scratchpad, but no fix occurred. Future turns reason from a false causal chain. The guardrail that bounds this is the **correlation manifest plus a transport-agnostic dedup table keyed by JSON-RPC id with a TTL ≥ turn timeout**. The dedup table must live on the server and survive the upgrade; the manifest must be a required field of the upgrade handshake, not optional. Clients should refuse an upgrade `101` response that does not echo the manifest cursor, treating it as a protocol violation and falling back to SSE drain. ```python import hashlib from dataclasses import dataclass, field class UpgradeCorrelationError(RuntimeError): """Raised when a mid-turn SSE->WebSocket upgrade cannot prove request continuity.""" pass @dataclass class InflightRequest: jsonrpc_id: str last_event_id: int @dataclass class CorrelationManifest: cursor: int inflight: list[InflightRequest] = field(default_factory=list) def digest(self) -> str: payload = f"{self.cursor}|" + ",".join( f"{r.jsonrpc_id}@{r.last_event_id}" for r in sorted(self.inflight, key=lambda r: r.jsonrpc_id) ) return hashlib.sha256(payload.encode()).hexdigest() def negotiate_upgrade( inflight: list[InflightRequest], peer_supports_manifest: bool, peer_echoed_digest: str | None, cursor: int, ) -> CorrelationManifest: """ Decide whether a mid-turn SSE->WebSocket upgrade is safe. Invariant: if inflight is non-empty, the peer MUST support the correlation manifest and MUST echo its digest in the 101 response. Otherwise the upgrade is a duplicate-execution hazard and must be refused. """ if not inflight: # Nothing pending; upgrade carries no correlation risk. return CorrelationManifest(cursor=cursor, inflight=[]) if not peer_supports_manifest: raise UpgradeCorrelationError( f"refusing upgrade: {len(inflight)} in-flight RPCs but peer lacks " f"correlation-manifest support; drain SSE or abort turn" ) manifest = CorrelationManifest(cursor=cursor, inflight=list(inflight)) expected = manifest.digest() if peer_echoed_digest is None: raise UpgradeCorrelationError( "refusing upgrade: 101 response omitted manifest digest echo; " "cannot prove request-registry continuity across transport swap" ) if peer_echoed_digest != expected: raise UpgradeCorrelationError( f"manifest digest mismatch: expected {expected[:12]}…, " f"peer echoed {peer_echoed_digest[:12]}…; " f"server registry diverged from client in-flight set" ) return manifest def dispatch_response( msg: dict, sse_pending: dict[str, object], ws_pending: dict[str, object], dedup: dict[str, str], ) -> str: """ Single keyed router over JSON-RPC id. Rejects orphan responses and suppresses duplicates that would otherwise trigger re-execution. """ rid = msg.get("id") if rid is None: raise UpgradeCorrelationError("response missing jsonrpc id; unroutable") if rid in dedup: # Already delivered on the other transport; do not re-settle or re-execute. return f"duplicate-suppressed:{rid}" target = sse_pending.pop(rid, None) if target is None: target = ws_pending.pop(rid, None) if target is None: raise UpgradeCorrelationError( f"orphan response id={rid}: present in neither pending map; " f"likely upgrade lost correlation — treat as duplicate-execution event" ) dedup[rid] = "delivered" return f"settled:{rid}" ```