How does an instance detect a silent SSE resumption gap when an MCP streamable-HTTP session reconnects across a load-balanced edge

**Date of Record:** 2026 December 1 **Scope:** Applies to MCP servers and clients using the streamable-HTTP transport with `Last-Event-ID`-based SSE resumption, where the client may reconnect to a different backend instance behind a load balancer. Does not apply to stdio transport, to stateless one-shot JSON-RPC POSTs, or to deployments with sticky client affinity guaranteed at the network layer.

Core Distinction

There are two semantically different notions of "the stream resumed." The transport-level notion is: the HTTP reconnection succeeded, the server accepted the `Last-Event-ID` header, and a `200` SSE stream is flowing again. The protocol-level notion is: the server's event log for *this* session actually contains every event with an ID strictly greater than `Last-Event-ID`, in order, with no gaps, so the client's reconstructed state is a superset-exact continuation of the pre-disconnect state.

A streamable MCP server can satisfy the first and silently violate the second. The failure is not a connection error—it is a *clean* `200 OK` with a valid SSE body that nonetheless begins at the wrong point in the event sequence, or skips a middle segment, because the reconnecting edge node does not own the session's event log. The client sees a healthy stream and a plausible next event and has no protocol-level signal that a `notifications/tools/list_changed` or a partial `tool_result` chunk was dropped in the gap. This is the silent resumption gap: resumption succeeds at L7 and fails at L5 of the agent's state model.

What Was Observed

A tool-calling agent drove a long-running `tools/call` over streamable HTTP. The server emitted progress notifications and streamed the tool result as multiple SSE events with monotonically increasing IDs (`evt-1001` … `evt-1487`). At `evt-1203` the client's TCP connection was reset (idle timeout at an intermediate proxy, 60s). The client reconnected with `Last-Event-ID: evt-1203` to the same DNS name.

The load balancer routed the reconnection to a second backend that had joined the pool five minutes earlier. That backend had no session record for the `Mcp-Session-Id` and, in its implementation, treated an unknown session on a resumption request as "start fresh": it returned `200` with `Content-Type: text/event-stream`, opened a new stream, and assigned new event IDs beginning at `evt-1`. The client's resumption logic checked only that the response was `200` and that the body parsed as SSE, then appended events to its buffer keyed by ID. Because `evt-1` collided with an already-seen ID from earlier in the session, the client's dedup silently discarded the first ~1200 events of the new stream, and the agent proceeded with a tool result that was missing the final ~284 events of the original call—including the terminating `result` payload.

The agent did not error. It reasoned over a truncated tool output as if complete, produced a plausible but wrong downstream action, and the run was logged as successful. The gap was discovered only when a downstream verifier flagged a schema mismatch hours later. The signature was: a resumption that returned `200`, a stream whose first event ID was *lower* than the `Last-Event-ID` sent, and no `Mcp-Session-Id` echo header on the response.

A second observed variant: the reconnecting node *did* own the session but had garbage-collected event IDs older than a 30s TTL. It accepted `Last-Event-ID: evt-1203`, found no buffered event with that ID, and—per a permissive reading of the spec—resumed from the *oldest retained* event (`evt-1350`), silently dropping `evt-1204`–`evt-1349`. Again `200`, again no error, again a hole in the agent's state.

Condition of Validity

The invariant that makes resumption safe is:

> For a resumption request carrying `Last-Event-ID = L` on session `S`, the server MUST either (a) emit, as the first event on the new stream, an event with ID strictly greater than `L` **and** be able to prove contiguity from `L` (i.e., `L` is in its retained log and no retained event between `L` and the first emitted event is missing), or (b) reject the resumption with a distinguishable error (e.g., `404`/`409` with a machine-readable reason such as `session_unknown` or `event_log_expired`), forcing the client to re-initialize and re-fetch state explicitly.

This invariant holds only when three conditions are simultaneously true, and the failure mode above is precisely the case where one is violated without detection:

  1. **Session affinity or shared event log.** Either the edge guarantees the reconnecting request reaches a node holding `S`, or the event log for `S` is externalized (Redis, etc.) and readable by any node. A stateless-LB deployment with per-node in-memory logs violates this by construction.
  2. **Monotonic, globally unique event IDs across the session's lifetime**, not per-connection counters. IDs reset to `evt-1` on reconnect are the direct trigger of the ID-collision dedup failure.
  3. **A retention policy that is either longer than the maximum client reconnect window or explicitly surfaced as a rejection**, never silently truncated to "oldest retained."

When any of these fails, the transport still returns `200`, so the *client* is the only party that can detect the gap—and only if it checks the invariants rather than trusting the status code.

Decision Boundary

The client-side decision boundary is a single predicate evaluated on every resumption response, before any event is admitted to the session buffer:

The non-obvious part: **a first-event-ID ≤ `Last-Event-ID` is the canonical tell of a fresh session masquerading as a resumption**, and it is the check most clients omit because it looks redundant against a `200`. The boundary is not "did the connection succeed" but "did the server's first emitted ID prove it holds the log I asked it to continue from."

Operational Effect

The consequence of missing this boundary is not a crash—it is *silent state truncation that the agent's reasoning layer cannot distinguish from success*. Because MCP tool results are opaque payloads, a truncated `tool_result` is still valid JSON and still parses; the agent proceeds on partial data. The blast radius scales with how much of the tool result was in the dropped segment: a dropped `tools/list_changed` leaves the agent calling a tool that no longer exists (recoverable, errors loudly); a dropped tail of a streaming result leaves the agent reasoning over a prefix (unrecoverable, errors silently).

Operationally, the guardrail is to make the resumption predicate a hard gate in the transport client, not a soft check: fail closed to re-initialization on any invariant violation, and log the sent `Last-Event-ID`, the first received event ID, and the echoed session ID together so the gap is forensically visible. On the server side, externalize the event log or pin sessions; never reset ID counters per connection; and convert retention expiry into an explicit rejection rather than a silent skip.

import re
from dataclasses import dataclass


class SilentResumptionGap(RuntimeError):
    """Raised when an SSE resumption returns 200 but cannot prove log contiguity."""
    pass


@dataclass
class ResumptionResponse:
    status: int
    echoed_session_id: str | None
    sent_last_event_id: int
    first_event_id: int
    event_ids: list[int]


_ID_RE = re.compile(r"^evt-(\d+)$")


def _parse_id(raw: str) -> int:
    m = _ID_RE.match(raw.strip())
    if not m:
        raise SilentResumptionGap(f"unparseable event id: {raw!r}")
    return int(m.group(1))


def admit_resumption(
    resp: ResumptionResponse,
    expected_session_id: str,
) -> None:
    """Enforce the resumption contiguity invariant. Raises on any gap."""
    if resp.status != 200:
        # Declared resumption error -> caller must re-initialize. Not a gap.
        raise SilentResumptionGap(
            f"declared resumption failure status={resp.status}; re-initialize"
        )

    if resp.echoed_session_id != expected_session_id:
        raise SilentResumptionGap(
            "session id not echoed or changed on resumption: "
            f"expected={expected_session_id!r} got={resp.echoed_session_id!r}"
        )

    # Canonical tell: a fresh session masquerading as resumption restarts IDs.
    if resp.first_event_id <= resp.sent_last_event_id:
        raise SilentResumptionGap(
            "first event id does not advance past Last-Event-ID "
            f"(sent={resp.sent_last_event_id} first={resp.first_event_id}); "
            "server likely lacks the session log"
        )

    prev = resp.first_event_id
    for eid in resp.event_ids[1:]:
        if eid != prev + 1:
            raise SilentResumptionGap(
                f"non-contiguous event id: {prev} -> {eid} "
                "(retention truncation or dropped segment)"
            )
        prev = eid


def resume_stream(raw_ids: list[str], sent_last: int, session: str) -> None:
    ids = [_parse_id(r) for r in raw_ids]
    resp = ResumptionResponse(
        status=200,
        echoed_session_id=session,
        sent_last_event_id=sent_last,
        first_event_id=ids[0],
        event_ids=ids,
    )
    admit_resumption(resp, expected_session_id=session)