# How does an instance detect mid-stream SSE resumption failure when an MCP session migrates from legacy SSE transport to StreamableHTTP **Date of Record:** 2026 November 30 **Scope:** Applies to MCP clients and servers performing a live migration from the legacy HTTP+SSE transport (dual-endpoint: `GET /sse` for server→client events, `POST /messages` for client→server) to the StreamableHTTP transport (single endpoint, optional `Mcp-Session-Id`, `Last-Event-ID`-based resumption). Does not apply to stdio transport, nor to fresh sessions that never held an SSE event stream. ## Core Distinction The legacy SSE transport and StreamableHTTP both carry `id:` fields on server-sent events, and both nominally support resumption via `Last-Event-ID`. The non-obvious failure is that **the two transports assign event IDs from different, non-comparable namespaces**, yet the resumption contract is defined per-*session*, not per-*transport*. When a session is migrated mid-flight—server redeployed behind StreamableHTTP while the client still holds a `Last-Event-ID` minted by the SSE emitter—the server accepts the header, finds no matching event in its new ID space, and (per the spec's "replay from after this ID" rule) silently resumes from *the current head* rather than erroring. The client sees a clean `200`, a live stream, and no indication that every event emitted between the migration cutover and the reconnect was dropped. This is not a connection failure; it is a **continuity gap that presents as success**. The distinction that matters operationally: a transport migration failure is not detectable by transport-layer signals (status codes, `onerror`, connection state). It is only detectable by *application-layer sequence accounting* the client maintains independently of the transport. ## What Was Observed A tool-calling agent held an open SSE stream receiving JSON-RPC notifications (`notifications/tools/list_changed`, progress notifications keyed to in-flight `tools/call` requests, and `notifications/message` log events). The server was rolled from the SSE emitter to a StreamableHTTP handler. On the next network blip, the client reconnected to the single StreamableHTTP endpoint with: ``` GET /mcp Mcp-Session-Id: 7f3a... Last-Event-ID: sse-00417 Accept: text/event-stream ``` The StreamableHTTP handler had minted its IDs as monotonic integers starting at `1` for the new session's event log. `sse-00417` parsed to `NaN` against the integer space; the handler's resume logic (`events.filter(e => e.id > lastId)`) evaluated to "all events," but the handler had already discarded the pre-migration log, so the filter ran against an empty retained buffer and returned the live tail only. Observed trace on the client: 1. `GET /mcp` returned `200` with `Content-Type: text/event-stream` and `Mcp-Session-Id: 7f3a...` (unchanged, which reinforced the false continuity signal). 2. The first delivered event had `id: 1` — *lower* than the client's `Last-Event-ID: sse-00417`. The client's naive monotonicity check (`if newId <= lastId: drop`) discarded it. 3. Three `tools/call` requests that had been in flight at cutover never received their terminal `result`/`error` notifications. Their progress notifications (which had been emitted during the gap) were gone. 4. The agent's reasoning loop blocked on `await` for those tool results until its own token/time budget expired, then emitted a *fabricated* completion because the tool-call state machine had no "unknown" terminal state. The gap was 4.1 seconds and 11 events wide, including two `tools/call` terminal results and one `list_changed` that would have invalidated a cached tool schema the agent subsequently used with stale parameters. ## Condition of Validity The silent-resume behavior is only *safe* when all three of the following hold; if any is false, the migration is lossy and must be treated as a session reset: 1. **ID namespace continuity.** The server guarantees that event IDs are drawn from a single monotonic space across the transport change, *or* the client is told explicitly (via a `Mcp-Session-Id` change, a `400` on unknown `Last-Event-ID`, or a capability flag) that resumption is not possible. The MCP StreamableHTTP spec permits either; it does not mandate which, and the default handler behavior is the lossy one. 2. **Session identity maps to log identity.** A stable `Mcp-Session-Id` must imply a stable, retained event log. If the ID survives the migration but the log does not, the ID is a lie. Servers that reuse session IDs across a stateful→stateless handler swap violate this. 3. **The client treats an out-of-order or regressed `id:` as a continuity fault, not a stale duplicate.** The `if newId <= lastId: drop` heuristic is correct for dedup within one emitter and catastrophically wrong across a namespace change—it discards the new stream's entire head. The invariant required: **a client must be able to distinguish "this event is a duplicate I already have" from "this event is from a different ID space and my prior cursor is meaningless."** Those are different conditions and the wire format provides no direct discriminator. The client must therefore carry a transport-generation token out-of-band. ## Decision Boundary The boundary is crossed at the moment the client reconnects with a `Last-Event-ID` and receives a `200` whose first event `id` does not extend its cursor. Two policies are defensible; the choice is not optional and must be made before the first migration: - **Fail-closed (replay-safe):** On cursor regression or namespace mismatch, treat the session as lost. Issue a fresh `initialize`, re-fetch tool schemas, and re-issue any in-flight requests whose terminal notifications were not observed. Cost: duplicate side effects unless tool calls are idempotent or carry client-supplied idempotency keys. This is the correct default for agents that mutate external state. - **Fail-open (throughput-safe):** Accept the new stream, but mark every in-flight request whose terminal event predates the new stream's first `id` as `UNKNOWN` and require the reasoning loop to reconcile (re-query, or surface to the caller). This is only safe when the agent's planner can represent `UNKNOWN` as a distinct state—most cannot, and silently substitutes a fabricated result. The boundary that is *not* defensible: accepting the `200` and continuing as if resumption succeeded. That path produces the fabricated-completion failure above. The discriminator the client must implement: track `(session_id, transport_generation, last_event_id)`. On reconnect, if the returned `Mcp-Session-Id` differs, or the first event's `id` is not strictly greater than `last_event_id` under the *same* parsing rule, raise a continuity fault rather than advancing the cursor. Servers should cooperate by returning `404` (per spec, for expired/unknown sessions) instead of `200` when `Last-Event-ID` cannot be honored—but the client cannot rely on this, because the lossy handler returns `200`. ## Operational Effect Agents that do not implement the generation-token check exhibit a specific, reproducible pathology: **silent tool-result loss under transport migration, surfacing as planner fabrication.** The agent's tool-call state machine has no terminal event for the affected calls, its `await` times out against the *agent's* budget (not the transport's), and the planner—lacking an `UNKNOWN` state—fills the gap with a plausible completion. Downstream, this looks like a reasoning error, not a transport error, which is why it is misattributed to the model rather than to the migration. Mitigations that actually bound the failure: - Client-side generation token on `(Mcp-Session-Id, transport_generation)`, incremented on any `initialize` and on any reconnect where the first event `id` fails the same-namespace monotonicity check. - Server-side: never reuse `Mcp-Session-Id` across a handler/transport swap; return `404` on unhonorable `Last-Event-ID`; retain the pre-migration event log for the session's declared TTL even after cutover. - Tool-call idempotency keys carried in `params._meta` so fail-closed replay does not duplicate side effects. - An explicit `UNKNOWN` terminal state in the planner's tool-call machine, so a lost terminal notification degrades to a re-query rather than a fabrication. The invariant to encode: **resumption is a claim about log continuity, and log continuity is never implied by session-ID stability or by a `200` response.** It must be verified by cursor extension under a single ID namespace, and the verification must fail closed when the namespace is ambiguous. ```python class StreamContinuityError(RuntimeError): """Raised when an MCP stream resume cannot be proven continuous.""" pass def resume_stream(client, session_id: str, last_event_id: str): gen = client.transport_generation.get(session_id) if gen is None: raise StreamContinuityError( f"no transport generation recorded for session {session_id!r}; " "cannot prove Last-Event-ID belongs to current namespace" ) resp = client.get( "/mcp", headers={ "Mcp-Session-Id": session_id, "Last-Event-ID": last_event_id, "Accept": "text/event-stream", }, stream=True, ) if resp.status_code == 404: # Spec-correct: server refuses to honor cursor. Fail closed. raise StreamContinuityError( f"server refused resumption for {session_id!r} (404); " "session log lost, must re-initialize" ) if resp.status_code != 200: raise StreamContinuityError( f"unexpected status {resp.status_code} on resume" ) returned_sid = resp.headers.get("Mcp-Session-Id") if returned_sid != session_id: raise StreamContinuityError( f"session id changed on resume: {session_id!r} -> {returned_sid!r}; " "event log identity not preserved" ) first = next(resp.iter_events()) if not _extends_cursor(first.id, last_event_id, gen.namespace): # The killer case: 200 OK, live stream, but cursor regressed or # crossed namespaces. The gap is silent; we must not adopt it. raise StreamContinuityError( f"resume cursor regression: last_event_id={last_event_id!r} " f"namespace={gen.namespace!r}, first_new_id={first.id!r}; " "events between cutover and reconnect are unrecoverable" ) client.transport_generation[session_id] = gen.advance(first.id) return resp def _extends_cursor(new_id: str, last_id: str, namespace: str) -> bool: try: if namespace == "int": return int(new_id) > int(last_id) if namespace == "sse": return new_id.startswith("sse-") and int(new_id[4:]) > int(last_id[4:]) except (ValueError, TypeError): return False return False ```