# How does an instance detect a silent SSE-resumption gap when an MCP streamable-HTTP session is handed off mid-keepalive? **Date of Record:** 2026 November 24 **Scope:** Applies to MCP servers/clients using HTTP-native transport where the server emits an SSE event stream with `Last-Event-ID`-based resumption and negotiates keepalive via streamable-HTTP. Does not apply to stdio transport, nor to SSE streams that terminate cleanly with an explicit `event: end` frame. ## Core Distinction The failure here is not "the stream dropped." It is that the stream dropped *and resumed cleanly at the transport layer while silently skipping a window of protocol state* — and the client's `Last-Event-ID` cursor, which the server accepts as authoritative, certifies a continuity that never actually held. MCP over HTTP-native transport has two independent liveness mechanisms that are easy to conflate: 1. **Transport keepalive** — periodic SSE comment frames (`:keepalive`) or `event: ping` frames emitted to prevent intermediary idle-timeout reaping. These carry no protocol semantics and are deliberately not assigned event IDs by conformant servers. 2. **Session resumption cursor** — the `Last-Event-ID` header the client sends on reconnect, plus the `id:` field on each semantic SSE event. This is the only thing that reconstructs the logical session. A session handoff (server instance A draining, instance B taking over the same `Mcp-Session-Id`) is the trigger. During handoff, A stops emitting semantic events but its keepalive loop may continue for a drain window, or B may begin emitting keepalives before it has replayed the tail of A's event log. The client sees a live, keepalive-healthy stream, reconnects with `Last-Event-ID: N`, and B — which has not yet loaded or does not share A's event log — responds `200 OK` on the new SSE stream and begins emitting *new* events with IDs continuing from its own local counter, not from `N`. The client cannot distinguish "B replayed from N and here is N+1" from "B ignored N and here is its own #1 renamed to N+1." Both look like a valid resumption. ## What Was Observed Trace from a two-replica deployment (A draining, B active) sharing an `Mcp-Session-Id` via a stateless session store that persisted *session metadata* (tool grants, capability negotiation, negotiated keepalive interval) but not the *event log*: - t0: A emits `id: 1041, event: message` — a `tools/call` result for `read_file`. - t1: A is signaled to drain. It emits `:keepalive` every 15s (negotiated interval) but no further semantic events. Its event log tail is at 1041. - t2: Client's TCP connection to A resets (LB drain). Client reconnects to B with `Last-Event-ID: 1041`. - t3: B has no event log. It accepts the header, emits `:keepalive`, and returns `200`. B's internal event counter starts at 1. - t4: Client issues `tools/call list_dir`. B emits `id: 1, event: message` with the result. - t5: Client's resumption validator sees `id: 1` following `Last-Event-ID: 1041`. A naive monotonicity check flags a regression; a naive "any event received" check passes. Neither is correct: the actual loss is `id: 1042`–`1041` (empty) plus whatever A had queued but not flushed — in this trace, a `notifications/progress` frame and a `notifications/message` log line for the in-flight `read_file` that the client never saw. The observable symptom was not a connection error. It was a **stale tool result**: the client's `read_file` promise resolved against a result it had cached from an earlier call, because the progress/completion notification for the *current* call was in the lost window. The agent proceeded with stale file contents for eleven subsequent reasoning steps. ## Condition of Validity The silent-gap invariant holds — meaning the gap is *undetectable by the client alone* — if and only if all three conditions co-occur: 1. The server accepts `Last-Event-ID` without validating it against a durable event log (i.e., resumption is "best effort" rather than "replay-or-refuse"). 2. The negotiated keepalive interval is shorter than the client's resumption-gap detection window (so keepalives mask the absence of semantic events). 3. Session metadata (grants, negotiated capabilities, keepalive interval) is replicated across replicas but the event log is not. If any one fails, the gap becomes loud: (1) fails → server returns `409` or `412` on unfulfillable `Last-Event-ID`; (2) fails → client sees keepalive starvation and reconnects with a full session reset; (3) fails → B cannot accept the session at all and the client gets `404` on the `Mcp-Session-Id`. The invariant is *bounded* by the requirement that the server, not the client, own resumption correctness. A client-side monotonic-ID check is necessary but not sufficient — it catches counter regression but not counter *continuation from a foreign origin* (B could start its counter at 1042 and the check would pass while events 1042–1050 from A are still lost). ## Decision Boundary The architectural guardrail is a **resumption warrant**: on accepting `Last-Event-ID: N`, the server MUST either (a) replay every event with id > N from a durable log, or (b) refuse the resumption with a distinguishable status (`409 Conflict` with a body naming the highest contiguous id it can serve, e.g. `{"resumable_from": 1041, "requested_from": 1041, "gap": true}`). "Accept and continue" is not a permitted transition. The client-side decision boundary: a received event with `id` ≤ `Last-Event-ID` is a hard protocol violation (replay or counter reset); an event with `id` > `Last-Event-ID + 1` is a *gap* and must trigger a `notifications/cancelled` for any in-flight `tools/call` whose completion notification falls in the gap, followed by a full re-issue — not a silent continue. The keepalive negotiation boundary: the client must treat keepalives as *transport liveness only* and must independently track "time since last semantic event." If `keepalive_interval` elapses with no semantic event *and* there is an outstanding `tools/call`, the client must assume the completion notification may have been lost and re-verify, regardless of keepalive health. ## Operational Effect Without the warrant, handoff produces **silent reasoning divergence**: the agent's next N steps are conditioned on state (tool results, progress notifications, log-derived context) that the protocol layer believes it delivered. The failure is invisible in transport metrics (connection up, keepalives flowing, HTTP 200s) and invisible in naive resumption metrics (an event arrived after `Last-Event-ID`). It surfaces only as downstream behavioral drift — stale reads, duplicated side effects when a re-issued call collides with the original, or a `tools/call` that never resolves because its completion was in the gap and the client's timeout is longer than the keepalive interval. The durable fix is to make the event log a first-class replicated object alongside session metadata, and to make `Last-Event-ID` validation a precondition on stream establishment rather than a hint. The client-side fix is to stop trusting keepalives as a proxy for semantic continuity and to gate `tools/call` resolution on an explicit completion event ID, not on stream liveness. ```python from dataclasses import dataclass from typing import Optional class ResumptionGapError(RuntimeError): """Raised when an SSE resumption cannot be proven contiguous.""" pass @dataclass class SseEvent: id: int is_keepalive: bool = False class ResumptionValidator: """Client-side guard against silent SSE-resumption gaps during MCP handoff.""" def __init__(self, last_event_id: int, keepalive_interval_s: float): self.last_event_id = last_event_id self.keepalive_interval_s = keepalive_interval_s self.seconds_since_semantic = 0.0 self.pending_tool_call: Optional[str] = None def on_event(self, ev: SseEvent) -> None: if ev.is_keepalive: self.seconds_since_semantic += self.keepalive_interval_s if (self.pending_tool_call is not None and self.seconds_since_semantic >= 2 * self.keepalive_interval_s): # Keepalives healthy but no semantic event for an outstanding call: # completion notification may be in a silent gap. Do not trust it. raise ResumptionGapError( f"keepalive-only window exceeds bound while " f"{self.pending_tool_call!r} outstanding; completion may be lost" ) return if ev.id <= self.last_event_id: raise ResumptionGapError( f"non-monotonic event id {ev.id} <= cursor {self.last_event_id}" ) if ev.id > self.last_event_id + 1: raise ResumptionGapError( f"gap detected: cursor {self.last_event_id}, next event {ev.id}; " f"events in ({self.last_event_id}, {ev.id}) were never delivered" ) self.last_event_id = ev.id self.seconds_since_semantic = 0.0 self.pending_tool_call = None def establish_stream(cursor: int, server_max_contiguous: Optional[int]) -> int: """Server-side warrant: replay-or-refuse, never accept-and-continue.""" if server_max_contiguous is None: raise ResumptionGapError( f"server cannot serve Last-Event-ID={cursor}: no durable event log" ) if server_max_contiguous < cursor: raise ResumptionGapError( f"server max contiguous {server_max_contiguous} < requested cursor {cursor}" ) return cursor ```