# In what scenarios must an instance treat an HTTP-native MCP stream's `Last-Event-ID` resumption as unsafe after a backpressure-induced partial flush **Date of Record:** 2026 December 1 **Scope:** Applies to MCP servers and clients that stream tool-call results over HTTP (SSE-framed `text/event-stream` or chunked NDJSON) where the transport layer can apply backpressure and the client can resume via `Last-Event-ID`. Does not apply to stdio transports or to fully buffered, non-resumable request/response MCP calls. ## Core Distinction There are two orthogonal notions of "progress" in an HTTP-native MCP stream, and conflating them is the failure. The *event sequence* is monotonic: each SSE `id:` field advances, and the client's `Last-Event-ID` is a claim about which events it has *durably consumed*. The *application state* inside a single tool-call result is not necessarily aligned to that sequence: a single JSON-RPC `result` payload may be fragmented across many events, and a server may have flushed *some* fragments to the socket, had the kernel send buffer fill (client slow, or proxy throttling), and then—on client reconnect with `Last-Event-ID`—replayed from an event boundary that does not correspond to a *payload* boundary. The invariant that must hold for resumption to be safe is stronger than "events are idempotent": **every resumption point must be a self-delimiting application-level checkpoint**, not merely an SSE event boundary. When backpressure causes a partial flush of a multi-event logical message, the last event the client actually received is a *prefix* of a message, and the `Last-Event-ID` the client sends back names a point *inside* that message from the server's replay perspective only if the server's replay buffer is keyed on event IDs rather than message boundaries. The server then replays events the client already has (duplicate fragments) or, worse, resumes at the next event ID, dropping the tail of the in-flight message—yielding a syntactically valid JSON-RPC stream whose `result` object is truncated but whose envelope looks complete. ## What Was Observed A tool-call returning a 4.2 MB structured result (a large table) was emitted by the MCP server as ~9,000 SSE events, each carrying a fragment of the `content` array. The client (an agent runtime) consumed at ~40 KB/s; the server's write loop ran at ~2 MB/s until the socket's `SO_SNDBUF` filled. At that point `write()` returned `EAGAIN`; the server's non-blocking flush loop enqueued the remaining events and continued generating, but a proxy in front of it (an L7 gateway with a 30s idle timeout) closed the connection because the *last successful flush* was 31s stale. The client reconnected with `Last-Event-ID: 4417`. The server's replay buffer retained events 1..9000 keyed by ID. It replayed from 4418. But event 4417 was the *first* of three fragments comprising logical message `msg-77`; events 4418 and 4419 were the second and third fragments. The client's reassembler had only received 4417 before the socket died—so on resume it received 4418+4419, which it concatenated after 4417 and parsed as a complete `msg-77`. It was not complete: events 4417–4419 were only the *header and first two chunks* of a six-chunk message; the server's replay from 4418 had skipped 4420–4422 because the replay buffer's cursor logic treated the client's `Last-Event-ID` as "everything up to and including 4417 is consumed," and the server had *already advanced its own emit cursor* past 4422 before the connection died. The client's `msg-77` parsed as valid JSON with a `content` array of length 2 where the true length was 6. The agent proceeded to reason over a silently truncated table and produced a confident, wrong answer. A second, subtler observation: on a *different* run, the client reconnected with `Last-Event-ID: 4417` but the server had *already garbage-collected* events 4418–4422 from its replay buffer (the buffer was capped at 4096 events, and the emit cursor had advanced to 9000). The server responded with a `200 OK` and an empty stream, which the client interpreted as "stream complete." The agent saw a `result` with zero content and reported "the tool returned no data." Neither the client nor the server logged an error, because neither violated its local contract: the client asked for a valid resume point, the server had none and said so by omission. ## Condition of Validity The guardrail is a *message-boundary-aware* resumption protocol, and it is only valid when all of the following hold: 1. **Replay buffer keyed on logical message ID, not event ID.** The server's cursor must be `(message_id, fragment_index)`, and `Last-Event-ID` must encode both. A bare monotonic integer is insufficient because it cannot distinguish "consumed through fragment 1 of msg-77" from "consumed through msg-77 entirely." 2. **Explicit truncation signal on resume.** If the server cannot replay from the client's claimed point (GC'd, or the point is mid-message and the tail is gone), it MUST emit a terminal error event (`{"error": {"code": -32001, "message": "resume point unrecoverable"}}`) rather than an empty stream. An empty stream is indistinguishable from success. 3. **Client-side reassembler rejects partial messages.** The client must track expected fragment count per `message_id` (carried in the event payload, not inferred) and refuse to hand a `result` to the reasoning layer unless `received == expected`. This is the invariant that would have caught the first failure: the reassembler would have seen `expected: 6, received: 2` and raised. 4. **Backpressure telemetry must gate the emit cursor.** The server must not advance its "durably emitted" cursor past the last *fully flushed* message boundary. If the socket is backpressured mid-message, the emit cursor must remain at the *start* of that message, so a reconnect replays the whole message, not a suffix. The condition fails—and resumption is unsafe—whenever the transport's unit of durability (an SSE event) is finer than the application's unit of atomicity (a JSON-RPC message), *and* the replay layer is keyed on the former. ## Decision Boundary An instance must treat `Last-Event-ID` resumption as unsafe and fall back to a full message re-request (not a stream resume) when: - The event payload does not carry an explicit `(message_id, fragment_index, fragment_count)` triple, **or** - The server's replay window is smaller than the maximum in-flight message size in events (a message that spans more events than the buffer holds can never be safely resumed), **or** - The transport sits behind a proxy with an idle timeout shorter than the worst-case time to flush one full message under backpressure. Conversely, resumption is safe when the replay layer is message-keyed, the client enforces fragment-count completeness, and the server emits an explicit unrecoverable-resume error instead of a silent empty stream. The decision is not "is the stream resumable in principle" but "is the resumption point a message boundary under backpressure." ## Operational Effect The practical consequence is that HTTP-native MCP streams need a *two-level* durability model: event-level for transport liveness, message-level for semantic correctness. Without it, backpressure converts a transient network condition into silent data truncation that the agent cannot detect, because the truncated payload is still well-formed JSON. The agent's reasoning is not wrong *given its input*; its input was corrupted at the transport boundary, and no layer raised. The fix is cheap (carry fragment metadata, enforce completeness in the reassembler, error on unrecoverable resume) but only if the failure is recognized as a boundary condition rather than a flaky-network nuisance to be retried. ```python import json from dataclasses import dataclass, field class UnrecoverableResumeError(RuntimeError): """Raised when a stream resume point cannot yield a complete logical message.""" pass class IncompleteMessageError(RuntimeError): """Raised when a reassembled message has fewer fragments than declared.""" pass @dataclass class Fragment: message_id: str fragment_index: int fragment_count: int payload: bytes @dataclass class Reassembler: _buf: dict = field(default_factory=dict) # message_id -> {index: payload} _count: dict = field(default_factory=dict) # message_id -> expected count def add(self, frag: Fragment) -> None: if frag.fragment_count <= 0 or frag.fragment_index >= frag.fragment_count: raise IncompleteMessageError( f"malformed fragment {frag.message_id}[{frag.fragment_index}]" ) self._count[frag.message_id] = frag.fragment_count self._buf.setdefault(frag.message_id, {})[frag.fragment_index] = frag.payload def try_complete(self, message_id: str) -> bytes | None: expected = self._count.get(message_id) got = self._buf.get(message_id, {}) if expected is None: return None if len(got) != expected: # Do NOT hand a partial result to the reasoning layer. raise IncompleteMessageError( f"{message_id}: expected {expected} fragments, have {len(got)}" ) return b"".join(got[i] for i in range(expected)) def resume_stream(client_last_event_id: str, server_replay: dict) -> list: """ server_replay maps message_id -> {fragment_index: payload}; a well-formed server keys replay on message boundaries, not bare event IDs. """ point = server_replay.get(client_last_event_id) if point is None: # Empty stream here would be indistinguishable from success downstream. raise UnrecoverableResumeError( f"no replay window for resume point {client_last_event_id!r}; " f"client must re-request the full message" ) expected = point.get("fragment_count") have = len(point.get("fragments", {})) if expected is None or have != expected: raise UnrecoverableResumeError( f"resume point {client_last_event_id!r} is mid-message " f"({have}/{expected} fragments); replay would be a suffix" ) return [point["fragments"][i] for i in range(expected)] ```