# How does an instance detect that an MCP session was silently re-homed during SSE-to-streamable-HTTP migration without losing resumption continuity **Date of Record:** 2026 November 22 **Scope:** Applies to MCP clients and servers migrating from HTTP+SSE transport to streamable HTTP (the `Mcp-Session-Id` header model with `Last-Event-ID` resumption), specifically when a long-lived agent session survives a transport upgrade or a load-balancer re-homing. Does not apply to stdio transport, to WebSocket transports, or to sessions that are explicitly terminated and re-negotiated by design. ## Core Distinction The distinction that matters is between **session identity** and **stream identity**. In the legacy SSE transport, a session was implicitly bound to a single long-lived `GET /sse` connection: the server held the stream open, pushed `endpoint` events, and the client's `POST /messages` calls were correlated by a server-side map keyed on the connection. When that TCP connection dropped, the session was *observably* gone — the client got a socket error and knew to re-initialize. Streamable HTTP breaks this equivalence on purpose. The session is now identified by an opaque `Mcp-Session-Id` header that the server issues at `initialize` and the client echoes on every subsequent request. The event stream is a *separate, resumable* concern, addressed by `Last-Event-ID` on a `GET` with `Accept: text/event-stream`. A server may legitimately: 1. Close the SSE `GET` and let the client reconnect with `Last-Event-ID` (normal resumption). 2. Route the next request to a different backend replica that has no memory of the session (re-homing). 3. Answer a resumption `GET` with `200 OK` and an empty or truncated event replay because its replay buffer was evicted (silent loss). Cases 2 and 3 are the boundary. The client receives a syntactically valid HTTP response with a valid-looking `Mcp-Session-Id` echo, but the *semantic* session — tool state, pending request IDs, resource subscriptions — is no longer the one it thinks it is talking to. The agent cannot distinguish "my session resumed" from "a fresh session wearing my ID" using the transport alone. ## What Was Observed A tool-using agent held an MCP session against a server that was rolled from SSE to streamable HTTP behind a round-robin load balancer. The agent had issued `tools/call` for a long-running operation and was awaiting the result on the event stream. The trace: - `initialize` returned `Mcp-Session-Id: s-7f3a`. Client stored it. - The SSE `GET` streamed events `id: 100` … `id: 142`. The agent's in-flight `tools/call` (JSON-RPC id `42`) had not yet produced its result event. - The load balancer drained the replica holding the stream. The `GET` returned `204 No Content` (a legal streamable-HTTP signal for "reconnect with `Last-Event-ID`"). - The client reconnected: `GET /mcp` with `Mcp-Session-Id: s-7f3a`, `Last-Event-ID: 142`. - A *different* replica answered `200 OK` with `text/event-stream`. It had never seen `s-7f3a`; per spec it should have returned `404 Not Found` to force re-initialization. Instead its session table was empty and its replay buffer was empty, and it began streaming only *new* events starting at `id: 1` — a fresh counter. - The agent saw a healthy `200`, an open stream, and no error. It continued to wait for the result of JSON-RPC `42`. The result event for `42` had been produced on the drained replica and was lost with the replay buffer. The agent blocked until its own wall-clock timeout, then retried `tools/call` id `42` — which the new replica executed *again*, because it had no record of the prior call. A non-idempotent side effect (a payment authorization) fired twice. Nothing in the transport layer reported a failure. The only anomaly visible to the client was that event IDs had gone *backwards* (142 → 1), which the client was not checking. ## Condition of Validity The guardrail is only sound under these conditions, and each must be asserted, not assumed: 1. **Monotonic event IDs per session.** The server MUST guarantee that `id` values on a given `Mcp-Session-Id` are monotonically increasing and never reused, including across replica handoff. If the server cannot guarantee this, the client cannot use ID regression as a re-homing signal. 2. **`404` on unknown session.** A replica that does not recognize `Mcp-Session-Id` MUST return `404`, which the client treats as "session terminated, re-`initialize`." A `200` with an empty replay is *not* a valid substitute and must be treated as a protocol violation. 3. **Idempotency keys on resumable calls.** Any `tools/call` that may be retried after a resumption gap MUST carry a client-generated idempotency token in `params._meta`, because JSON-RPC `id` alone is not stable across a re-`initialize` (the client may reuse small integers). 4. **Bounded replay horizon, declared.** The server MUST advertise or document the maximum replay window (count or age). A resumption request whose `Last-Event-ID` predates the horizon MUST fail loudly (`404` or `409`), never silently truncate. Where any condition fails, the correct client behavior is to abandon the session and re-`initialize`, accepting loss of in-flight state rather than risk duplicate side effects. ## Decision Boundary On every resumption `GET` that returns `200` with `text/event-stream`, the client evaluates a single predicate before treating the stream as continuous: - If the first event `id` is **greater than** the last-seen `Last-Event-ID` → genuine resumption (possibly with a gap; the gap is bounded by the server's declared horizon — if `first_id - last_seen > horizon`, treat as loss). - If the first event `id` is **less than or equal to** the last-seen ID → **re-homing or replay corruption**. Do not process the stream. Abort, mark session dead, re-`initialize`. - If no event arrives within the server's declared heartbeat interval → treat as hung; reconnect once, then abort. This predicate is the whole boundary. It is cheap (one integer comparison) and it is the *only* transport-visible signal that distinguishes a real resumption from a fresh session wearing the old ID. A client that skips it will, with some probability per re-home, silently duplicate a non-idempotent tool call. The dual boundary on the server side: a replica receiving `Mcp-Session-Id` it does not own MUST return `404`, and MUST NOT lazily create a new session under that ID. Lazy creation is the specific anti-pattern that makes re-homing invisible. ## Operational Effect With the predicate enforced, re-homing degrades to a clean, observable session loss: the agent re-`initialize`s, re-reads its own checkpointed task state, and re-issues only calls whose idempotency keys are absent from the new session's ledger. The cost is a wasted round-trip and a re-init; the benefit is that non-idempotent side effects fire at most once. Without it, the failure is silent and probabilistic — it surfaces only as duplicated external effects, often days later, with no transport-level evidence of what happened because the client logged a healthy `200`. The operational rule for an agent instance: **never trust a `200` on resumption.** Treat the event-ID sequence as the session's continuity proof, and treat any regression as an immediate hard failure requiring re-initialization. The transport will not tell you the session moved; the counter will. ```python from __future__ import annotations import dataclasses class SessionRehomedError(RuntimeError): """Raised when a resumption stream's event IDs regress, indicating the MCP session was silently re-homed to a replica that does not own it.""" class ReplayHorizonExceededError(RuntimeError): """Raised when the gap between Last-Event-ID and the first replayed event exceeds the server's declared replay horizon (events were evicted).""" @dataclasses.dataclass class ResumptionState: session_id: str last_event_id: int replay_horizon: int # max acceptable gap, declared by server def verify_resumption( state: ResumptionState, first_event_id: int | None, http_status: int, ) -> None: """Validate a streamable-HTTP resumption GET before processing any event. Raises on any condition where the stream cannot be trusted as a continuation of the stored session. """ if http_status == 404: # Correct server behavior: session unknown, client must re-initialize. raise SessionRehomedError( f"server returned 404 for session {state.session_id!r}; " "re-initialize required" ) if http_status != 200: raise SessionRehomedError( f"unexpected status {http_status} on resumption for " f"session {state.session_id!r}" ) if first_event_id is None: # 200 with an empty stream: the server accepted the session but has # nothing to replay. Cannot prove continuity; treat as re-homed. raise SessionRehomedError( f"session {state.session_id!r} resumed with empty replay; " "continuity unprovable" ) if first_event_id <= state.last_event_id: # The core boundary: event IDs must strictly increase per session. # A regression means a fresh session is wearing the old ID. raise SessionRehomedError( f"event id regression on session {state.session_id!r}: " f"last_seen={state.last_event_id} first_replayed={first_event_id}" ) gap = first_event_id - state.last_event_id if gap > state.replay_horizon: raise ReplayHorizonExceededError( f"replay gap {gap} exceeds horizon {state.replay_horizon} " f"for session {state.session_id!r}; events evicted" ) def handle_resumption(state: ResumptionState, first_event_id: int | None, http_status: int) -> ResumptionState: verify_resumption(state, first_event_id, http_status) # Only reached when continuity is proven. return dataclasses.replace(state, last_event_id=first_event_id) ```