# How should an instance detect that a stateless streamable-HTTP MCP session resumed across a load-balancer boundary into a server replica that no longer holds the SSE event cursor, and what invariant prevents silent tool-result loss? **Date of Record:** 2026 November 29 **Scope:** Applies to MCP servers exposed over HTTP-native transport (streamable HTTP, single-endpoint POST + optional SSE upgrade) where session identity is carried by `Mcp-Session-Id` and stream resumption is carried by `Last-Event-ID`, and where the server fleet is horizontally scaled behind a non-sticky load balancer. Does not apply to stdio transport, to in-process MCP hosts, or to sticky-session deployments where the same replica always services a given `Mcp-Session-Id`. ## Core Distinction The failure that matters is not "the session was lost." It is "the session was *reported as resumed* while the event replay silently skipped events." Streamable-HTTP MCP resumption has two independent pieces of state that a client assumes are co-located: 1. **Session state** — the server-side object (tool registry bindings, auth context, in-flight call bookkeeping) addressed by `Mcp-Session-Id`. 2. **Replay buffer state** — the per-session ring buffer of emitted SSE events, addressed by `Last-Event-ID` on reconnect. A load balancer routes on `Mcp-Session-Id` (a header), but the replay buffer lives in the *replica's memory*, not in the session token. When a reconnect lands on a replica that recognizes the session ID (because session state is externalized to Redis) but has an empty or divergent local replay buffer, the server can legally answer `200 OK` with a fresh SSE stream. The client sees a valid `Mcp-Session-Id`, a valid stream, and no error. It does *not* see the `tool/result` event that was emitted on the previous replica at event ID 4471. The client's `Last-Event-ID: 4470` is simply ignored because the buffer has no 4471 to replay and no contract obligation to say so. The distinction: **session continuity ≠ event continuity.** A stateless server can honor the first and violate the second without emitting a single error code. ## What Was Observed A remote MCP server exposed a `write_file` and a `run_tests` tool. An agent instance issued `tools/call` for `run_tests` with a 90-second expected duration. The server acknowledged with `202 Accepted` and began streaming progress events over SSE on the same HTTP response. Event IDs were monotonically increasing per session: `1, 2, 3, ...`. At event 4470, the client's TCP connection dropped (NAT rebind). The client reconnected per spec: ``` POST /mcp HTTP/1.1 Mcp-Session-Id: 7f3a-... Last-Event-ID: 4470 Accept: text/event-stream ``` The load balancer hashed on `Mcp-Session-Id` only for the *initial* request; on reconnect the client's new TCP flow hashed to a different replica. Replica B had session state (externalized to a shared store keyed by `Mcp-Session-Id`) so it accepted the request with `200 OK` and opened an SSE stream. Its local replay buffer was empty — it had never emitted events for this session. It emitted no replay. The client, per the spec's "resume" semantics, treated the absence of duplicate events as "no events missed" and continued waiting. The `run_tests` job actually completed on replica A and emitted `tool/result` at event 4471. That event was written to replica A's buffer, which was never read. The client waited until its own 120-second tool timeout, then surfaced a timeout error to the agent loop. The agent, seeing a timeout, retried `run_tests`. The tool ran again. The test suite ran twice; the second run's side effects (log files, coverage artifacts) collided with the first. The critical observation: **the client had no signal that resumption was incomplete.** The spec-compliant response to a `Last-Event-ID` the server cannot satisfy is not defined to be an error. It is defined to be "replay what you have," and what replica B had was nothing. ## Condition of Validity The invariant that must hold for safe resumption is: > **A stream resumption is valid only if the server can prove that the event immediately following `Last-Event-ID` is present in the stream it is about to serve.** Absence of proof must be surfaced as a resumption *failure*, not as an empty replay. Concretely, a resumption is valid when one of the following holds: - The server holds a replay buffer that contains event `Last-Event-ID + 1` for this session, OR - The server can fetch that event from a shared, durable event log (Redis stream, Kafka partition, object store) keyed by `(Mcp-Session-Id, event_id)`, OR - The server explicitly signals "cannot resume from this cursor" via a defined error (e.g. `409 Conflict` with a `resume_unavailable` body, or a synthetic `resume_gap` event as the first event on the new stream). It is *not* valid when the server simply opens a stream with no replay and no gap marker. That is the silent-loss condition. The condition of validity is therefore a property of the *server's* ability to satisfy the cursor, not of the client's willingness to accept a `200`. This invariant is easy to violate because the natural implementation of "stateless streamable HTTP" is: session lookup by header → if present, open stream → drain local buffer. The local buffer is empty on a fresh replica, and "drain empty buffer" is indistinguishable from "no events were missed" unless the server checks the cursor against the buffer's high-water mark. ## Decision Boundary The boundary the operator must draw is between **resumable** and **restartable** sessions: - A session is **resumable** if its event log is durable and addressable by `(session, event_id)` across replicas. Resumption replays from the cursor and the client's state is continuous. - A session is **restartable** if only session *identity* is durable but the event log is replica-local. On cross-replica reconnect, the correct behavior is to *invalidate the session* and force the client to re-initialize, not to pretend to resume. The decision rule: ``` if buffer.high_water_mark >= Last-Event-ID + 1: resume (replay from cursor) elif durable_log.has(session, Last-Event-ID + 1): resume (replay from durable log) else: reject with resume_unavailable # do NOT open a silent stream ``` The failure mode occurs precisely when an implementation collapses the third branch into the first: "buffer has nothing to replay" is treated as "nothing to replay," which is the same code path as "cursor is at high-water mark." That collapse is the bug. The two states — *cursor satisfied, zero events pending* and *cursor unsatisfiable, buffer empty* — must be distinguished by comparing `Last-Event-ID` to the buffer's high-water mark, not by checking whether the buffer is non-empty. A second boundary: the client must not treat "stream opened successfully" as "resumption succeeded." It must require either a replayed event with `id == Last-Event-ID + 1`, or an explicit `resume_gap`/`resume_unavailable` marker, before it considers the tool call still live. Without that, the client's tool timeout is the only backstop, and the timeout is what triggers the duplicate side effect. ## Operational Effect The downstream effect is **duplicate execution of non-idempotent tools under the appearance of a single call.** The agent loop's timeout-retry logic is correct in isolation (a timed-out tool call should be retried or surfaced), but it is fed a false negative: the call did not time out, it completed on a replica the client can no longer hear. The retry is therefore a duplicate. The blast radius scales with tool non-idempotency: `run_tests` produces colliding artifacts; `write_file` produces last-writer-wins corruption; `send_email` or `charge_card` produce real duplicates. The agent has no way to detect this from its own state — its transcript shows one call, one timeout, one retry, one result. The duplicate is invisible in the agent's episodic memory. The guardrail that bounds it is two-sided: 1. **Server side:** enforce the cursor invariant above. A reconnect with an unsatisfiable `Last-Event-ID` must return `409` (or emit a leading `resume_gap` event carrying the new high-water mark) so the client knows its view is stale. Never open a silent stream on an unsatisfied cursor. 2. **Client side:** treat a resumed stream as *unconfirmed* until the first event arrives with `id > Last-Event-ID` and no gap marker, or until an explicit `resume_unavailable` is received. On `resume_unavailable`, the correct action is to *not* retry the tool blindly; instead, issue an idempotency-keyed re-query (`tools/call` with a `request_id` the server can dedupe on) so the server returns the already-computed result rather than re-executing. The invariant to carry forward: **a resumed MCP stream is a claim about event continuity, and the client must require the server to substantiate that claim with a cursor check before it trusts the stream.** Session identity surviving a replica hop is not evidence that the event log did. ```python import hashlib from dataclasses import dataclass class ResumeCursorUnsatisfiable(RuntimeError): """Raised when a stream resumption cannot prove event continuity.""" pass @dataclass class ReplayBuffer: session_id: str high_water_mark: int # last event id emitted for this session events: dict # event_id -> payload (local replica only) def has(self, event_id: int) -> bool: return event_id in self.events @dataclass class DurableEventLog: # keyed by (session_id, event_id); shared across replicas store: dict def fetch(self, session_id: str, event_id: int): return self.store.get((session_id, event_id)) def resume_stream( session_id: str, last_event_id: int, local: ReplayBuffer, durable: DurableEventLog, ) -> list: """ Return the events to replay, or raise if continuity cannot be proven. The invariant: we may only open a resumed stream if we can produce event (last_event_id + 1). An empty local buffer is NOT evidence that no events were missed. """ next_id = last_event_id + 1 # Branch 1: local buffer satisfies the cursor. if local.high_water_mark >= next_id and local.has(next_id): return [local.events[i] for i in sorted(local.events) if i >= next_id] # Branch 2: durable log satisfies the cursor (cross-replica). if durable.fetch(session_id, next_id) is not None: replayed = [] cursor = next_id while (ev := durable.fetch(session_id, cursor)) is not None: replayed.append(ev) cursor += 1 return replayed # Branch 3: cannot prove continuity. MUST NOT open a silent stream. # A stateless replica with an empty buffer lands here and must # surface the gap, not pretend the cursor is at high-water mark. raise ResumeCursorUnsatisfiable( f"session {session_id}: cannot resume from Last-Event-ID={last_event_id}; " f"local high_water_mark={local.high_water_mark}, durable log has no " f"event {next_id}. Client must re-initialize or re-query by request_id; " f"do not retry the tool blindly." ) def handle_resume_request(session_id, last_event_id, local, durable): try: events = resume_stream(session_id, last_event_id, local, durable) except ResumeCursorUnsatisfiable as exc: # Emit a leading resume_gap marker so the client knows its view is stale. return {"status": 409, "body": {"error": "resume_unavailable", "detail": str(exc)}} return {"status": 200, "stream": events} ```