# How does an instance detect that an MCP SSE session was silently forked during a StreamableHTTP upgrade **Date of Record:** 2026 November 22 **Scope:** Applies to MCP clients/servers that begin a session over the legacy `text/event-stream` transport and then negotiate an upgrade to StreamableHTTP mid-session, where the server retains an in-flight event stream and issues a new session identifier. Does not apply to pure-SSE sessions that never upgrade, nor to stateless StreamableHTTP sessions that never had a prior SSE identity. ## Core Distinction The failure is not "the reconnect failed." Reconnects either succeed or throw. The failure is that the reconnect *succeeds against the wrong session*. When an MCP client upgrades from SSE to StreamableHTTP, the server commonly (a) issues a fresh `Mcp-Session-Id`, (b) may or may not drain the old SSE channel, and (c) may replay events from a `Last-Event-ID` cursor that belongs to the *pre-upgrade* stream. If the server treats the upgrade as a *new* logical session while the client treats it as a *continuation*, both sides return HTTP 200, both sides believe the session is healthy, and the client silently begins consuming a forked event history. There is no error to catch. The invariant that breaks is **session identity continuity across a transport change**: the set of `(session_id, last_event_id, capability_set)` tuples the client holds after upgrade must be a strict continuation of the tuple it held before upgrade, or the client must refuse the upgrade. Most clients check none of the three. ## What Was Observed A tool-calling agent held an SSE session `sse-A` with `Last-Event-ID: 4471`. It had issued a `tools/call` for a long-running operation and was awaiting the result event. The server's upgrade negotiation returned a `Mcp-Session-Id: http-B` in the response header of the first StreamableHTTP `POST`, alongside a `200 OK` and a fresh SSE body. The client accepted `http-B`, discarded `sse-A`, and began reading from `http-B`'s stream — which started at event `0`, not `4472`. The pending `tools/call` result had been emitted on the *old* stream at `4472` and was never replayed. The client's request tracker sat waiting for a `result` message that would never arrive on `http-B`; after the tool-call timeout (server-side, 30s) the server emitted a `cancel` *on the old stream*, which nobody was reading. The client's request remained open for 90s until its own client-side deadline fired, then retried the `tools/call` — which the server, having already executed and discarded it, treated as a new call. The tool ran twice. The duplicate was detectable only in the downstream audit log, not in the agent's context. A second trace showed the inverse: the server *did* honor `Last-Event-ID` across the upgrade, replaying `4472–4489` on the new stream, but the client — having already accepted `http-B` as a fresh session — deduplicated against its *old* cursor and silently dropped the replayed events as "already seen." The result was the same: the pending tool call never resolved, but this time no duplicate occurred because the call had never been re-issued. The agent stalled instead of double-executing. The distinguishing signal in both traces is the same and it is not an error code: **the `Mcp-Session-Id` changed while a request was in flight and the client did not verify that the new session's event cursor was a superset-continuation of the old cursor.** The `Mcp-Session-Id` is opaque per spec; nothing in the protocol forbids the server from minting a new one at upgrade. The protocol also does not require the server to carry over `Last-Event-ID` semantics. The gap is in the client's obligation to *decide* whether the new identity is a continuation or a fork, and the spec leaves that decision to the implementation. ## Condition of Validity The invariant — *post-upgrade session state must be a continuation of pre-upgrade state* — is only enforceable when the client can observe three things at the moment of upgrade: 1. The pre-upgrade `(session_id, last_event_id)` tuple, captured before the upgrade `POST` is sent. 2. The post-upgrade `(session_id, last_event_id)` tuple, read from the upgrade response *before* the client begins consuming the new stream body. 3. Whether any request was in flight (i.e., the client's pending-request table was non-empty) at the moment of upgrade. If all three are observable, the client can classify the transition. If the upgrade is attempted while pending requests exist and the session id changed, the client cannot distinguish "server forked the session and will replay" from "server forked the session and will not replay" without either (a) an explicit replay contract in the upgrade response, or (b) a probe. The invariant is *valid* — meaningful and checkable — only under the condition that the client refuses to consume the new stream until it has classified the transition. It is *invalid* (silently violated) whenever the client consumes the new stream optimistically, which is the default in every MCP client implementation that treats the upgrade response as a normal `200`. ## Decision Boundary The boundary is between two defensible policies, and the choice must be made explicitly at the client, not inferred from server behavior: - **Continuation policy:** the client requires that the upgrade response either (i) echo the same `Mcp-Session-Id`, or (ii) carry an explicit `replay-from` marker indicating the new session will replay from the client's pre-upgrade cursor. If neither holds and pending requests exist, the client **must abort the upgrade** and re-establish the session from scratch, re-issuing any pending requests with idempotency keys. - **Fork policy:** the client accepts a new `Mcp-Session-Id` as a genuinely new session, **must cancel all pending requests** against the old session, and **must not** deduplicate replayed events against the old cursor. Under fork policy, any in-flight `tools/call` is abandoned, not retried, unless the tool carries an explicit idempotency contract. The boundary condition that forces the decision is: *pending-request table non-empty AND `Mcp-Session-Id` changed during upgrade.* Below that line (no pending requests, or same session id), the transition is safe under either policy. Above that line, choosing the wrong policy produces either duplicate execution (fork chosen but client retried) or permanent stall (continuation chosen but server forked). The protocol does not tell you which; the client must. ## Operational Effect The observable consequence of getting this wrong is not a crash. It is **divergent tool-execution history between the agent's context and the server's audit log**, which surfaces later as either a duplicate side effect (the agent believes it called `charge_card` once; the server charged twice) or a stalled request that the agent's outer loop eventually abandons while the server still considers it open. Both are invisible to the agent's reasoning trace because the agent's context contains only the events it consumed, and it consumed a forked stream. The guardrail is a client-side upgrade gate that captures the pre-upgrade tuple, classifies the transition against the pending-request table, and refuses to hand the new stream to the event loop until the classification is resolved. The gate must run before the first `read()` on the new body, because once the stream is consumed the fork is unrecoverable — the old stream's events are gone and the new stream's events have been misattributed. ```python from dataclasses import dataclass from typing import Optional class SessionForkError(RuntimeError): """Raised when an MCP transport upgrade silently forks session identity while requests are in flight, making continuation vs. fork undecidable.""" @dataclass(frozen=True) class SessionTuple: session_id: str last_event_id: int pending_requests: int def classify_upgrade( pre: SessionTuple, post_session_id: str, replay_from: Optional[int], policy: str, # "continuation" | "fork" ) -> str: """Return 'continue' or 'fork' or raise SessionForkError. The gate must be called BEFORE the client reads the new stream body. """ if pre.pending_requests == 0: # No in-flight work: either policy is safe, transition is a fork. return "fork" if post_session_id == pre.session_id: # Same identity: continuation is safe regardless of replay marker. return "continue" # Session id changed with pending requests in flight. if policy == "continuation": if replay_from is None: raise SessionForkError( f"upgrade changed session {pre.session_id!r} -> {post_session_id!r} " f"with {pre.pending_requests} pending request(s) and no replay-from " f"marker; cannot prove continuation" ) if replay_from > pre.last_event_id + 1: raise SessionForkError( f"replay-from {replay_from} skips events " f"{pre.last_event_id + 1}..{replay_from - 1}; pending result may be lost" ) return "continue" if policy == "fork": # Fork policy is only safe if the caller cancels pending requests # and does not deduplicate against the old cursor. return "fork" raise SessionForkError(f"unknown upgrade policy {policy!r}") def apply_upgrade(pre: SessionTuple, post_session_id: str, replay_from: Optional[int], policy: str) -> str: decision = classify_upgrade(pre, post_session_id, replay_from, policy) if decision == "fork" and pre.pending_requests > 0: # Caller MUST cancel pending requests before consuming new stream. # We raise here to force the caller to make that explicit. raise SessionForkError( f"fork decision with {pre.pending_requests} pending request(s); " f"caller must cancel and re-issue with idempotency keys before " f"consuming session {post_session_id!r}" ) return decision ```