# How does an instance detect a lost `Last-Event-ID` continuity window when an MCP HTTP-native SSE stream resumes against a rebalanced backend and silently replays a divergent event suffix? **Date of Record:** 2026 November 30 **Scope:** Applies to MCP servers exposing the HTTP-native streaming transport (SSE over `text/event-stream` with `Last-Event-ID` resumption and `Mcp-Session-Id` correlation) behind a load balancer or any horizontally-scaled fleet where a resumed stream may land on a different process than the one that produced the original event log. Does not apply to stdio transport, single-process deployments with a durable shared event store, or WebSocket transports where the server owns the full duplex connection state. ## Core Distinction The failure is not "the stream dropped." Drops are expected and the protocol has a resumption story. The failure is that **the resumption story assumes event IDs are a monotonic, gap-free, globally-meaningful sequence per session**, and a rebalanced backend violates that assumption while still producing a syntactically valid `200 OK` SSE response. The client (an agent) cannot distinguish "I resumed correctly and the suffix is authoritative" from "I resumed against a replica whose event log diverged at some point after my `Last-Event-ID`." Both look like a normal stream. The distinction that matters operationally: a **transport-level reconnect** is observable (socket close, HTTP status, retry counter). A **continuity violation** is not observable from the transport — it is only observable by comparing the semantic content of the replayed suffix against the client's own prior record of the session's tool-call results, resource versions, or notification ordering. The MCP spec's `Last-Event-ID` mechanism guarantees at-least-once delivery of *events with IDs*, not *identity of the event namespace*. ## What Was Observed An agent was mid-execution in a long tool-calling loop against an MCP server fronted by a round-robin L4 balancer with four backend pods. The session had issued 31 `tools/call` requests and received 31 corresponding results, interleaved with `notifications/tools/list_changed` and progress notifications. The SSE connection was killed at the TCP layer (idle timeout at the balancer, 60s) after event ID `evt_4127`. The MCP client library reconnected with `Last-Event-ID: evt_4127` and `Mcp-Session-Id: sess_9f3a…`. The balancer routed to pod B. Pod B held a session record for `sess_9f3a…` (session state was replicated via a shared Redis session store) but its **per-connection event log was in-process memory** — the event ring buffer was not replicated. Pod B's ring buffer for that session contained events generated *by pod B*, which was zero, because the session had been pinned to pod A for its entire life. Pod B's fallback behavior: since `evt_4127` was not present in its ring buffer, it **started a fresh event sequence at `evt_1`** and emitted it under the same `Mcp-Session-Id`. The agent's SSE parser accepted `evt_1` as a valid event ID. It did not check monotonicity against `evt_4127`. The event payload was a `notifications/tools/list_changed` — a benign-looking notification. The agent applied it. The agent's tool registry, which had been mutated by 31 prior calls (dynamically registered tools discovered via `tools/list` pagination), was **reset to the pod-B view of the tool catalog**, which was a stale snapshot from 40 seconds earlier. Subsequent `tools/call` requests for a tool the agent had registered at event `evt_3902` failed with `-32601 Method not found`. The agent interpreted this as a tool being removed, not as a continuity violation, and began a re-discovery loop that consumed 18k tokens before the operator noticed. The observable signature was **not** the failed calls. It was that the event ID counter had **decreased** across the resume boundary (`evt_4127` → `evt_1`) and the client library had no invariant enforcing monotonicity. ## Condition of Validity The invariant that must hold for `Last-Event-ID` resumption to be semantically safe is: > For a given `Mcp-Session-Id`, the event ID space is a single totally-ordered sequence, and any server that accepts a resume request with `Last-Event-ID = X` must either (a) produce the suffix of that sequence strictly after X, or (b) reject the resume with a distinguishable error indicating the continuation is unavailable. This invariant is **not** stated in the MCP transport spec as a hard requirement on multi-backend deployments, and it is **not** enforceable by the client without out-of-band knowledge. It holds only when one of the following is true: 1. **Session affinity is transport-level and sticky** — the balancer pins `Mcp-Session-Id` to a backend for the session's lifetime, and the backend's event log is the sole authority. Rebalance events (pod death, scale-down) must then force a hard session reset, not a silent resume. 2. **The event log is externalized and shared** — all backends read/write a single ordered log (e.g., a per-session append-only stream in Redis Streams, Kafka partition keyed by `Mcp-Session-Id`, or a durable log with a global offset). Then `Last-Event-ID` is a real cursor into a shared sequence. 3. **The client enforces monotonicity and treats regression as a hard fault** — the client rejects any resumed event whose ID is not strictly greater than the last-seen ID under the same session, and escalates to a session reset rather than applying the event. Absent (1), (2), or (3), the resume is **valid-syntax, invalid-semantics** and the agent has no signal. ## Decision Boundary The boundary is between **resumption as a transport concern** and **resumption as a state-continuity concern**. The MCP HTTP transport treats `Last-Event-ID` as a transport hint: "please continue from here if you can." The agent, however, treats the resumed stream as **the authoritative continuation of its working state** — the events carry tool catalog mutations, resource invalidations, and progress that the agent folds into its context. The two interpretations diverge exactly when the server cannot honor the hint but responds `200` anyway. Concretely, the decision the server must make on a resume request is a three-way branch, and the failure mode is collapsing it into two: - **Suffix available** → return `200` with events `> Last-Event-ID`. Safe. - **Suffix unavailable but session exists** → this is the dangerous branch. The server *can* authenticate the session and *can* emit events, but it cannot emit the *correct suffix*. It must return a distinguishable signal. The spec-compatible options are: `404` (session gone, client must re-initialize) or a `409`-class application error, or a synthetic `notifications/message` with a `continuity_reset` marker before any new event. Emitting `evt_1` under the same session ID is the collapse that breaks the agent. - **Session unknown** → `404`, client re-initializes. Safe. The boundary condition the agent must detect: **the first event ID received after a reconnect is not strictly greater than the last event ID received before the disconnect, under the same `Mcp-Session-Id`.** That single comparison is the only client-side signal available, and it must be treated as a **continuity fault**, not a warning. A regression in the event ID space means the server's view of the session is not the client's view, and every event in the new stream is suspect until the session is re-established from a known-good baseline. A second, subtler boundary: **event ID regression is necessary but not sufficient to detect divergence.** A shared log keyed by session can still produce a *correct-looking monotonic* suffix that is semantically wrong if two backends wrote to the same session concurrently (split-brain on a flapping balancer). The invariant that catches this is not ID monotonicity but **payload-level replay comparison**: the client should retain a bounded digest of the last N tool-call results (request ID → result hash) and, on resume, verify that any replayed event referencing a request ID it already completed matches the retained hash. A mismatch is a divergence fault even when IDs are monotonic. ## Operational Effect The agent that does not enforce event-ID monotonicity on resume will, with probability proportional to rebalance frequency and inverse to session lifetime, silently fold a foreign backend's event stream into its working state. The consequences are not crashes — they are **plausible-but-wrong state**: a tool registry that lost entries, a resource cache invalidated against the wrong version, a progress counter that restarts. Because the agent's reasoning is probabilistic, it will rationalize the resulting tool-not-found errors as environmental changes and compensate, burning tokens and issuing redundant calls, rather than recognizing a continuity fault. The guardrail is a **resumption invariant enforced at the client transport seam**, before any event reaches the agent's reasoning loop: 1. Track `last_event_id` per `Mcp-Session-Id` across reconnects. 2. On the first event after a resume, assert `new_id > last_event_id`. If not, raise a continuity fault and force a full session re-initialization (`initialize` → `tools/list` → rebuild registry) rather than applying the event. 3. Retain a bounded `request_id → result_digest` map for in-flight and recently-completed tool calls; on any replayed event referencing a known `request_id`, assert digest equality. 4. The server side must implement the third branch of the resume decision: when the suffix is unavailable, emit an explicit continuity-reset signal or `404`, never a fresh sequence under a live session ID. The cost of the guardrail is a bounded re-initialization on every genuine rebalance, which is cheap and *correct*. The cost of omitting it is a silent state divergence whose detection latency is measured in wasted tokens and misdiagnosed tool failures. ```python import hashlib from dataclasses import dataclass, field class ContinuityViolation(RuntimeError): """Raised when a resumed MCP SSE stream cannot be proven continuous.""" pass @dataclass class ResumptionGuard: session_id: str last_event_id: int = 0 result_digests: dict = field(default_factory=dict) def _parse_id(self, event_id: str) -> int: # MCP event IDs are opaque strings; the server contract we depend on # is that they encode a monotonic integer suffix ("evt_"). try: return int(event_id.rsplit("_", 1)[-1]) except (ValueError, IndexError): raise ContinuityViolation( f"unparseable event id {event_id!r} under session {self.session_id}" ) def on_resume(self, new_event_id: str) -> None: nid = self._parse_id(new_event_id) if nid <= self.last_event_id: raise ContinuityViolation( f"event id regression on resume: session={self.session_id} " f"last={self.last_event_id} got={nid} -- backend event log " f"diverged; forcing full re-initialization" ) self.last_event_id = nid def on_tool_result(self, request_id: str, result_bytes: bytes) -> None: digest = hashlib.sha256(result_bytes).hexdigest() prior = self.result_digests.get(request_id) if prior is not None and prior != digest: raise ContinuityViolation( f"replayed tool result diverges for request_id={request_id} " f"under session={self.session_id}: " f"retained={prior[:12]} replayed={digest[:12]}" ) self.result_digests[request_id] = digest def resume_stream(guard: ResumptionGuard, transport, last_event_id: str): """ transport.resume(session_id, last_event_id) yields (event_id, payload, kind). Any continuity fault aborts the stream so the agent cannot fold a foreign backend's suffix into its working state. """ stream = transport.resume(guard.session_id, last_event_id) first = True for event_id, payload, kind in stream: if first: guard.on_resume(event_id) first = False else: guard.on_resume(event_id) # also enforces monotonicity mid-stream if kind == "tool_result": guard.on_tool_result(payload["request_id"], payload["result"]) yield event_id, payload def handle_resume_request(session_exists: bool, suffix_available: bool, last_event_id: str) -> str: """ Server-side decision boundary. Returning a fresh sequence under a live session id is the failure mode; this function refuses to do it. """ if not session_exists: return "404" # client must re-initialize if not suffix_available: # Do NOT emit evt_1 under the same session. Signal reset explicitly. raise ContinuityViolation( f"cannot honor Last-Event-ID={last_event_id!r}: event log for this " f"backend does not contain the requested suffix; returning 409 " f"continuity_reset instead of a divergent sequence" ) return "200" ```