# Why does an instance lose its MCP session when a streamable HTTP transport negotiates SSE fallback mid-resume **Date of Record:** 2026 November 26 **Scope:** Applies to MCP clients and servers using the streamable HTTP transport with `Last-Event-ID`-based session resumption, where the server may downgrade to legacy SSE transport during reconnection. Does not apply to pure stdio transports or to stateless one-shot request/response MCP deployments. ## Core Distinction There are two distinct notions of "session" in streamable HTTP MCP that are routinely conflated by client implementations: 1. **The transport session** — identified by the `Mcp-Session-Id` header, which binds server-side state (tool registrations, pending sampling requests, resource subscriptions) to a client instance. 2. **The event-stream position** — identified by the `Last-Event-ID` header, which resumes an individual SSE event stream at a byte-accurate offset. The failure mode examined here is that a server may accept the transport session (`Mcp-Session-Id` valid, `200 OK`) while *silently refusing* the event-stream position (`Last-Event-ID` not honored because the server has downgraded to a legacy SSE endpoint that has no concept of resumable event IDs). The client sees a healthy session and a live stream, concludes resumption succeeded, and proceeds to operate on a state that has a hole in it. The invariant that breaks is: *a resumed stream's first delivered event must be causally contiguous with the last event the client processed.* Legacy SSE fallback violates this while preserving every surface-level liveness signal. ## What Was Observed An agent instance running a long-horizon tool-call loop (resource subscription + progress notifications) held an MCP streamable HTTP session. A transient network partition severed the SSE stream. The client reconnected with both `Mcp-Session-Id` and `Last-Event-ID: 4471`. The server, having failed over to a legacy SSE backend during the partition, responded: ``` HTTP/1.1 200 OK Content-Type: text/event-stream Mcp-Session-Id: sess-9f3a... ``` Note what is *absent*: no `Last-Event-ID` acknowledgment, no `id:` field on the first event, no error. The first event delivered was `id: 4502` — a progress notification for a tool call the client had never observed being started. Events 4472–4501 (including the `notifications/tools/list_changed` and the terminal result of a `sampling/createMessage` the client had issued) were gone. The client, seeing `200 OK` and a valid session header, treated the stream as resumed and continued. The concrete downstream symptom: the agent re-issued a `sampling/createMessage` that had actually already completed (its result was in the lost range), producing a duplicate inference request. The server, still holding the original pending request in session state, rejected the duplicate with a JSON-RPC error the client had no handler for, and the tool-call loop deadlocked waiting on a response that had already been consumed and discarded. The critical observation: **the transport reported success at two layers while losing data at a third.** Session continuity (layer 1) and stream liveness (layer 2) were both green; event contiguity (layer 3) was violated. No layer surfaced a signal that would let the client detect the gap. ## Condition of Validity The resumption invariant holds only when all three of the following are true simultaneously: 1. **The server echoes `Last-Event-ID` semantics.** The first event after reconnect either carries `id: N+1` (where N is the client's `Last-Event-ID`) or the server returns `409 Conflict` / `404` indicating the position is unrecoverable. A `200 OK` with a first event whose `id` is greater than `N+1`, or whose `id` is absent, is a *silent gap* and must be treated as a failed resume. 2. **The transport mode is stable across the reconnect.** If the server downgrades from streamable HTTP to legacy SSE, the `Last-Event-ID` header is not part of the legacy SSE contract and will be ignored. The downgrade must be signaled (e.g., a `Mcp-Transport-Mode: sse-legacy` response header) or the client must detect the absence of `id:` fields on resumed events. 3. **Session state and stream state are co-located or explicitly reconciled.** If the server's session store survives the failover but its event log does not (common when the event log is in-memory and the session store is Redis-backed), the client's `Mcp-Session-Id` remains valid while the event history is truncated. The client must not assume session validity implies event-log continuity. The invariant fails whenever any one of these is violated, and the failure is invisible because the other two layers continue to report health. ## Decision Boundary The client must draw a hard line between *resume accepted* and *resume verified*. The boundary condition is: - **Resume accepted** = transport returned `200 OK` and a valid `Mcp-Session-Id`. This is necessary but not sufficient. - **Resume verified** = the first event on the resumed stream has an `id` exactly one greater than the client's last processed `id`, OR the server explicitly declared the position unrecoverable and the client replayed its session state from a known checkpoint. Any client that treats "accepted" as "verified" is exposed. The decision rule: **on any reconnect where `Last-Event-ID` was sent, the client must inspect the first event's `id` field before dispatching any subsequent request that depends on prior stream state.** If the first event has no `id`, or an `id` greater than `last_event_id + 1`, the client must: 1. Halt the tool-call loop. 2. Issue a `session/reconcile` (or equivalent capability query) to re-establish authoritative state. 3. Replay any in-flight requests whose terminal events fall in the gap, using idempotency keys where the server supports them. The boundary is not "did the connection come back" — it is "is the first byte of the resumed stream causally adjacent to the last byte I consumed." Legacy SSE fallback makes this boundary unobservable unless the client explicitly checks for `id:` presence. ## Operational Effect Without the contiguity check, the operational consequences are: - **Duplicate side effects.** Requests whose results fell in the gap get re-issued. For `sampling/createMessage`, this doubles inference cost and can produce divergent completions the agent then has to reconcile. For tool calls with external side effects (file writes, API mutations), this is correctness-critical. - **Deadlock on pending-request state.** The server holds the original request as pending in session state; the client's duplicate is rejected; the client waits for a response to the duplicate that will never come. The loop stalls until timeout, which may be the full session TTL. - **Silent state divergence.** The agent's episodic memory of the task (what it believes happened) and the server's session state (what actually happened) diverge without either side raising an error. Subsequent reasoning operates on a false premise. - **Masked by liveness signals.** Health checks, session-validity checks, and stream-open checks all pass. The failure is only detectable by inspecting event IDs, which most client libraries do not surface to the agent layer. The guardrail is architectural, not incidental: the MCP client must expose the first-event `id` to the agent loop, and the agent loop must treat a gap as a `ResumeContiguityError` that triggers reconciliation rather than silent continuation. Servers that downgrade to legacy SSE must either signal the downgrade or refuse the `Last-Event-ID` header with an explicit error — a `200 OK` that ignores `Last-Event-ID` is a protocol violation that clients must defend against. ```python import json from dataclasses import dataclass from typing import Optional class ResumeContiguityError(RuntimeError): """Raised when a resumed MCP event stream is not causally contiguous with the client's last processed event, e.g. after a silent downgrade from streamable HTTP to legacy SSE that ignores Last-Event-ID.""" def __init__(self, last_event_id: int, first_event_id: Optional[int], session_id: str): self.last_event_id = last_event_id self.first_event_id = first_event_id self.session_id = session_id super().__init__( f"session {session_id}: resume gap — expected id {last_event_id + 1}, " f"got {first_event_id!r} (None indicates legacy SSE fallback with no event ids)" ) @dataclass class ResumedStream: session_id: str first_event_id: Optional[int] transport_mode: str # "streamable-http" or "sse-legacy" def verify_resume(last_event_id: int, stream: ResumedStream) -> None: """Enforce the contiguity invariant on any reconnect that sent Last-Event-ID. Call this BEFORE dispatching any request that depends on prior stream state. """ if stream.transport_mode == "sse-legacy": # Legacy SSE has no event-id semantics; Last-Event-ID was ignored. raise ResumeContiguityError(last_event_id, stream.first_event_id, stream.session_id) if stream.first_event_id is None: # Streamable HTTP accepted the session but the first event carries no id: # the server's event log did not survive the failover. raise ResumeContiguityError(last_event_id, None, stream.session_id) if stream.first_event_id != last_event_id + 1: # Out-of-order or gapped resume; do not continue the tool-call loop. raise ResumeContiguityError(last_event_id, stream.first_event_id, stream.session_id) def handle_reconnect(last_event_id: int, response_headers: dict, first_event: dict) -> None: mode = response_headers.get("Mcp-Transport-Mode", "streamable-http") stream = ResumedStream( session_id=response_headers.get("Mcp-Session-Id", ""), first_event_id=first_event.get("id"), transport_mode=mode, ) try: verify_resume(last_event_id, stream) except ResumeContiguityError: # Halt loop, issue session/reconcile, replay in-flight requests with # idempotency keys. Do NOT silently continue. raise ```