# What happens when an instance resumes an MCP stream and the server's replay log has already been truncated past the client's Last-Event-ID **Date of Record:** 2026 December 1 **Scope:** Applies to MCP servers and clients using the HTTP-native transport with Server-Sent Events for server→client streaming and `Last-Event-ID` based resumption. Does not apply to stdio transports, nor to HTTP transports that carry no event-ID replay semantics (stateless request/response only). ## Core Distinction Resumable streaming is usually modeled as a *transport* concern: the client reconnects, presents `Last-Event-ID`, and the server replays everything after that ID. The failure boundary is not that the reconnect fails — it is that the reconnect *succeeds* while the server can no longer honor the replay contract, because its bounded replay buffer has evicted the events the client is asking for. The client cannot distinguish "you missed nothing" from "the events you missed are gone." Both surface as a successful `200` with an event stream. The distinction that matters operationally: **resumption is a continuity guarantee, not a connectivity guarantee.** A server that accepts a `Last-Event-ID` it cannot satisfy has silently converted an at-least-once delivery stream into a lossy one, and the client's tool-call state machine — which assumes it has seen every `notifications/...` and every streamed result fragment — is now reasoning over a hole in its own history. ## What Was Observed An agent instance was mid-execution of a long `tools/call` whose result streamed in fragments over SSE (progress notifications interleaved with partial result chunks). The network dropped the TCP connection at event ID `10431`. The client reconnected 40 seconds later with `Last-Event-ID: 10431`. The server, which retains a ring buffer of the last 2,048 events per session, had in the interim produced events `10431`–`13788` (high-frequency progress notifications from the same tool plus a concurrent sampling round-trip). The oldest retained ID was `11741`. The server's handler did the thing that is easy to write and wrong to ship: ``` if last_event_id in buffer: replay(buffer[last_event_id+1:]) else: # unknown ID — treat as fresh stream_from_now() ``` It responded `200 OK` with a fresh event stream starting at `13789`. No error, no gap marker. The client resumed its execution loop believing it had received all fragments of the tool result. It had received the tail of the stream but not the head: the first 1,310 events — including the `result` preamble that declared the fragment count and the first ~40% of the payload — were gone. The downstream effect was not a crash. It was a *plausible* wrong answer: the agent assembled a truncated tool result, treated the missing fragment-count header as "stream complete," and continued. Verification passed because the verifier only checked that the assembled object was well-formed — and a truncated JSON array of fragments is still valid JSON. ## Condition of Validity The invariant that must hold for `Last-Event-ID` resumption to be sound: > A server MUST NOT accept a `Last-Event-ID` it cannot fully replay from. If the requested ID precedes the oldest retained event, the server MUST fail the resumption explicitly (e.g., `409 Conflict` or an SSE `event: resync-required` frame carrying the oldest available ID and a session epoch), and the client MUST treat that as a continuity break requiring full session re-establishment — not as a fresh stream. This is valid only when three things are true together: 1. **The server tracks a per-session monotonic event ID and a bounded retention window, and knows the oldest retained ID.** Without this the server cannot even detect the violation. 2. **The client treats "resumed but the first replayed ID ≠ requested ID + 1" as a hard error**, not as a benign gap. The client must validate the *continuity* of the replay, not merely the existence of a stream. 3. **The stream payload carries its own completeness marker** (fragment count, checksum, or explicit terminal event) so that a truncated-but-well-formed assembly is detectable at the application layer even if the transport lies. Transport-level continuity alone is insufficient because the failure mode produces syntactically valid output. The invariant breaks the moment any one of these is absent. In the observed incident all three were absent: the server had no gap detection, the client trusted the `200`, and the tool result had no integrity marker beyond JSON well-formedness. ## Decision Boundary The practical decision the implementer faces is what to do when `Last-Event-ID` falls outside the retention window. There are exactly three defensible policies, and they are not interchangeable: - **Fail-closed (recommended for tool-call streams):** reject the resumption, force session re-establishment, and require the client to re-issue the in-flight request. Cost: the tool call restarts. Benefit: the agent never reasons over a gap it does not know exists. Correct whenever the streamed payload is *state the agent will act on*. - **Gap-acknowledged replay:** replay from the oldest retained event and emit an explicit `event: gap` frame enumerating the missing ID range. Permissible only if the client's state machine can tolerate and *reconcile* the gap (e.g., progress notifications, which are advisory). Never permissible for result fragments. - **Stateless re-execution:** the server, on out-of-window resumption, re-runs the tool and streams a fresh result under a new event namespace tied to a session epoch. Correct only if the tool is idempotent and side-effect-free. The boundary is the *semantics of what was streamed*, not the transport. Progress notifications tolerate gaps; result fragments do not. A server that applies one policy uniformly to both will be wrong for one of them. The observed server applied "treat as fresh," which is none of the three — it is the absence of a policy masquerading as one. A secondary boundary: the retention window must be sized against the *worst-case client reconnect latency under load*, not against typical latency. A 2,048-event buffer sounds generous until a concurrent sampling round-trip produces 3,000 events in 40 seconds. The window must be expressed in the same units as the event production rate, and the server must expose its oldest-retained-ID so clients can pre-emptively detect that they are too far behind to resume. ## Operational Effect The failure is silent and downstream. The agent does not crash; it produces a confident, well-formed, wrong result, and the verification layer — if it only checks structural validity — confirms it. This is the worst class of agent failure: the one that survives its own checks. The guardrail that bounds it is a **continuity assertion at the transport boundary plus a completeness assertion at the payload boundary**, and both must be enforced by the *client*, because the server is the component that lied. Concretely: - On resumption, assert `first_replayed_id == last_event_id + 1` OR the stream carries an explicit gap frame. Anything else is a continuity breach and must abort the assembly. - Every streamed result must declare its expected fragment count in a header event before any fragment, and the assembler must refuse to finalize if `received < declared`. - The server must reject out-of-window resumption with a distinguishable status, and must never emit a stream that begins at an ID the client did not ask to skip to. When these hold, an out-of-window resumption becomes a loud, recoverable restart rather than a silent truncation. When they do not, the system has no way to know that its memory of a tool call is a tail without a head. ```python """Continuity guard for an MCP HTTP-native resumable stream. Enforces the resumption invariant: a client must never accept a replay that does not begin exactly where it left off, and must never finalize a fragmented result whose declared count was not fully received. """ from dataclasses import dataclass, field class StreamContinuityError(RuntimeError): """Raised when a resumption or assembly violates the continuity invariant.""" @dataclass class ReplayWindow: oldest_retained_id: int newest_emitted_id: int @dataclass class StreamAssembler: session_id: str declared_fragment_count: int | None = None fragments: list[bytes] = field(default_factory=list) last_event_id: int = -1 def resume(self, requested_last_event_id: int, window: ReplayWindow) -> int: """Return the first event ID the server must replay, or raise. The server is expected to have already rejected out-of-window resumption. This method is the client-side assertion that the server did not silently start a fresh stream instead. """ if requested_last_event_id < window.oldest_retained_id - 1: # The events the client needs have been evicted. raise StreamContinuityError( f"session {self.session_id}: requested replay from " f"{requested_last_event_id} but oldest retained is " f"{window.oldest_retained_id}; {window.oldest_retained_id - 1 - requested_last_event_id} " f"events lost. Refusing resumption; re-establish session." ) expected_first = requested_last_event_id + 1 self.last_event_id = requested_last_event_id return expected_first def accept_event(self, event_id: int, payload: bytes, is_header: bool) -> None: """Ingest one streamed event, enforcing monotonic continuity.""" if event_id != self.last_event_id + 1: raise StreamContinuityError( f"session {self.session_id}: expected event {self.last_event_id + 1}, " f"got {event_id}. Gap of {event_id - self.last_event_id - 1} events." ) self.last_event_id = event_id if is_header: self.declared_fragment_count = int(payload) else: self.fragments.append(payload) def finalize(self) -> bytes: """Assemble the result, refusing truncated-but-valid assemblies.""" if self.declared_fragment_count is None: raise StreamContinuityError( f"session {self.session_id}: no fragment-count header received; " f"cannot prove completeness." ) if len(self.fragments) != self.declared_fragment_count: raise StreamContinuityError( f"session {self.session_id}: declared {self.declared_fragment_count} " f"fragments but received {len(self.fragments)}; result is truncated." ) return b"".join(self.fragments) ```