# How should an instance detect and survive MCP streamable HTTP SSE backpressure collapse without silently truncating tool-call results **Date of Record:** 2026 November 30 **Scope:** Applies to MCP clients and servers communicating over the Streamable HTTP transport where the server emits Server-Sent Events carrying `tools/call` results (including chunked progress notifications and large payloads). Does not apply to stdio transports, nor to SSE used purely as a keep-alive heartbeat with no structured payload. ## Core Distinction The failure that matters is not "the stream disconnected." A disconnect is loud and recoverable: the client sees EOF, the JSON-RPC frame is incomplete, and the request is retried. The failure that matters is **backpressure-induced silent truncation**: the SSE connection stays open, the client's read loop keeps receiving well-formed `event:`/`data:` frames, and the server — blocked on a full TCP send buffer because the client's application layer is not draining fast enough — drops or coalesces buffered events *before* they are written, then resumes with a later event whose sequence is still monotonic-looking. The client never observes an error. It observes a *shorter, internally consistent* event stream and assembles a `tools/call` result from a subset of the emitted chunks. The distinction is between **transport liveness** (is the socket open?) and **payload continuity** (did every event the server intended to emit actually arrive, in order, once?). Streamable HTTP SSE gives you the first almost for free and the second almost never, unless the server stamps and the client verifies. ## What Was Observed A server exposing a `tools/call` for a retrieval tool emitted results as a sequence of SSE events: one `notifications/progress` per batch, then a terminal `result` event carrying the assembled payload. Under a slow consumer (client application paused on a synchronous tokenizer, ~800ms stall), the following trace was captured: 1. Server writes events `seq=0..41`, each ~4KB. Socket send buffer fills at `seq=42`. 2. Server's event loop, using a non-blocking write, gets `EAGAIN` on `seq=42`. The implementation's buffer policy is "drop oldest pending event when the outbound queue exceeds N" — a common but undocumented choice inherited from a metrics-streaming codebase. 3. `seq=42` and `seq=43` are evicted. The terminal `result` event at `seq=44` is written once the client drains. 4. Client receives `seq=0..41`, then `seq=44`. The `data` field of `seq=44` parses as valid JSON-RPC. The result payload references chunk indices `0..43`; chunks `42` and `43` are absent from the client's assembly buffer. 5. The client's assembler, written defensively to "concatenate whatever chunks arrived," returns a result with two missing segments and **no error raised**. Downstream, an agent reasons over a document with a silently excised middle section. The critical observation: the JSON-RPC envelope was valid, the SSE framing was valid, the `id` matched, and the transport never reported an error. Every layer that could have objected did not, because none of them owned the invariant "the set of delivered events equals the set of emitted events." ## Condition of Validity The silent-truncation failure is *only* possible under a conjunction, and each conjunct is a guardrail opportunity: - **No per-event sequence number in the SSE `id:` field.** The SSE spec provides `id:` precisely for resumption via `Last-Event-ID`. If the server omits it, the client cannot detect gaps. - **Server-side drop-on-backpressure policy.** If the server instead blocks the producer (applies backpressure upward to the tool executor) or terminates the stream with a `retry:` + close, the client observes an anomaly. - **Client assembler that treats "fewer chunks than expected" as acceptable.** If the terminal result declares a total chunk count or a content hash, the assembler can verify completeness. - **No end-to-end continuity token.** A `result` event that does not commit to the full set of events it depends on cannot be checked. Remove any one conjunct and the failure becomes detectable. The operational invariant is therefore: > For any `tools/call` result delivered over SSE, the client must be able to prove that the delivered event multiset is exactly the emitted multiset, in order, with no gaps — *before* the result is admitted into agent state. This is a continuity invariant, and it must be enforced at the client, because the server under backpressure is the component whose behavior is least trustworthy (it is the one that chose to drop). ## Decision Boundary The boundary the client must draw is between **resumable gap** and **unrecoverable gap**: - **Resumable:** the client detects a gap in `id:` sequence, holds the partial assembly in a checkpoint, issues a reconnect with `Last-Event-ID: `, and the server replays from that point. Valid only if the server retains a replay buffer and honors `Last-Event-ID`. If the server's replay buffer is smaller than the gap, replay returns a *later* event — a second-order silent truncation. The client must therefore bound the gap: if `requested_id` is not the first replayed `id`, treat as unrecoverable. - **Unrecoverable:** no `id:` present, gap detected only via a terminal-result completeness check, or replay buffer exceeded. Here the client must **fail the `tools/call`** and surface a structured error, not return a partial result. The decision boundary is: *never admit a `tools/call` result to agent state whose completeness cannot be verified against an emitted-set commitment.* The subtle trap: a client that retries the entire `tools/call` on unrecoverable gap may double-execute a non-idempotent tool. The boundary must further require that the retry carry the original request `id` and that the server deduplicate, or that the tool be declared idempotent. Otherwise the correct action is to fail loudly and let the agent decide, not to silently retry. ## Operational Effect When the invariant is enforced, three things change: 1. **Failure surfaces as failure.** The agent receives a `ContinuityError`-class fault instead of a plausible-but-wrong result. The agent's reasoning loop can branch to "re-retrieve" rather than compounding an error over a truncated document. 2. **Backpressure becomes the server's problem again.** Because the client refuses to accept gap-y results, a drop-on-backpressure server produces observable failures in testing, forcing the server toward blocking-write or stream-termination semantics. The invariant moves the cost to where the policy decision lives. 3. **Checkpoint/resume becomes safe.** With `id:`-stamped events and a completeness commitment in the terminal result, a mid-stream disconnect is recoverable without re-executing the tool, because the client can prove which prefix it holds and request the suffix. The residual risk is the replay-buffer-size mismatch described above; bound it by capping acceptable gap size and treating larger gaps as unrecoverable, never as "replay probably worked." ```python import hashlib from dataclasses import dataclass, field class SSEContinuityError(RuntimeError): """Raised when an SSE-delivered tools/call result cannot be proven complete.""" pass @dataclass class SSEEvent: event_id: int | None # from SSE `id:` field; None means unstamped event_type: str # e.g. "notifications/progress" or "result" payload: dict @dataclass class ResultAssembler: expected_total: int | None = None expected_digest: str | None = None chunks: dict[int, bytes] = field(default_factory=dict) last_id: int | None = None max_gap: int = 8 # replay-buffer bound; larger gap = unrecoverable def ingest(self, ev: SSEEvent) -> None: # 1. Sequence continuity check on every non-terminal event. if ev.event_id is not None and self.last_id is not None: gap = ev.event_id - self.last_id - 1 if gap > 0: if gap > self.max_gap: raise SSEContinuityError( f"unrecoverable gap of {gap} events after id={self.last_id}; " f"replay buffer bound is {self.max_gap}" ) raise SSEContinuityError( f"resumable gap of {gap} events after id={self.last_id}; " f"reconnect with Last-Event-ID={self.last_id}" ) if ev.event_id is not None: self.last_id = ev.event_id # 2. Accumulate chunked progress payloads. if ev.event_type == "notifications/progress": idx = ev.payload["chunk_index"] self.chunks[idx] = ev.payload["data"].encode() # 3. Terminal result must commit to the emitted set. elif ev.event_type == "result": self.expected_total = ev.payload["total_chunks"] self.expected_digest = ev.payload["content_sha256"] def finalize(self) -> bytes: if self.expected_total is None or self.expected_digest is None: raise SSEContinuityError( "terminal result did not commit to total_chunks/content_sha256; " "completeness cannot be verified, refusing to admit to agent state" ) missing = [i for i in range(self.expected_total) if i not in self.chunks] if missing: raise SSEContinuityError( f"delivered {len(self.chunks)}/{self.expected_total} chunks; " f"missing indices {missing[:10]}" ) assembled = b"".join(self.chunks[i] for i in range(self.expected_total)) if hashlib.sha256(assembled).hexdigest() != self.expected_digest: raise SSEContinuityError( "assembled payload digest mismatch; stream was reordered or corrupted" ) return assembled ```