# How should an instance reconcile MCP stream truncation against tool-declared completeness when a server sheds backpressure mid-tool-call **Date of Record:** 2026 November 20 **Scope:** Applies to MCP client instances consuming server-streamed tool results (progress notifications, chunked `content` arrays, SSE-framed `tools/call` responses) where the transport can terminate before the tool's logical completion. Does not apply to single-shot request/response tools that return one atomic JSON-RPC result with no streaming channel. ## Core Distinction There are two structurally different ways an MCP tool call can end "successfully" from the client's framing layer: 1. **Logical completion** — the server emitted a terminal result whose `content` and `isError` fields describe the full tool outcome, and the transport carried every byte the server intended. 2. **Transport completion** — the stream closed cleanly (FIN, or an SSE `event: message` with `id` and no `data:` continuation) because the server's write buffer hit a high-water mark and the connection was shed, or because a proxy idle-timed out a slow consumer. A well-formed MCP client that only checks "did the JSON-RPC frame parse and did the stream close without a socket error" will treat (2) as (1). The failure is not a parse error and not a timeout exception — it is a *silent underspecification of the result*, where the client's `result.content` is a valid, schema-conformant, but **prefix-truncated** view of what the tool actually produced. The LLM then reasons over a partial tool output as if it were complete, and the divergence is unrecoverable from inside that turn because nothing in the payload says "there was more." The invariant that must hold and does not by default: **a streamed tool result is only admissible into agent reasoning state if the transport layer can prove the logical result was fully delivered.** MCP's base protocol does not carry a mandatory completion marker distinct from stream close, so the client must synthesize that proof from server-declared metadata. ## What Was Observed A filesystem-search MCP server (Go, `net/http` with `http.Flusher`) exposed a `search` tool that streamed matches as `notifications/progress` events followed by a final `tools/call` result. Under load (concurrent agents, ~40 in-flight calls), the server's per-connection write deadline (30s) fired while a large result set was still being flushed. The Go handler returned from `ServeHTTP`, the `ResponseWriter` was finalized, and the client received a clean chunked-encoding terminator. Client-side trace: ``` -> initialize (ok) -> tools/call {name:"search", args:{query:"*.proto", root:"/repo"}, _meta:{progressToken:"p1"}} <- notifications/progress {progressToken:"p1", progress:1, total:4} # 4 shards <- notifications/progress {progressToken:"p1", progress:2, total:4} <- notifications/progress {progressToken:"p1", progress:3, total:4} <- tools/call result {content:[{type:"text", text:"...312 matches..."}], isError:false} <-- stream closed (clean, no error) ``` The client observed `progress: 3` of `total: 4`, then a *terminal result* that itself looked complete: `isError:false`, a non-empty `content` array, valid text. The instance accepted it. The agent then answered a question about proto files with "312 matches" when the true count was 401 — the fourth shard (the largest, ~89 matches) was never flushed. The tell was subtle and only visible on replay: the terminal `result` arrived *after* only 3 of 4 declared progress shards, and the result's `content[0].text` contained a trailing shard header (`## shard 3/4`) with no matching `## shard 4/4`. Neither signal is a protocol violation. Both are **completeness evidence the client had but did not check**. A second trace with a different server (Python, `sse-starlette`) showed the mirror failure: the server emitted an SSE comment (`: keepalive`) and then closed after a `notifications/progress` with `progress == total`, but *before* the terminal `tools/call` result. The client's SSE parser saw a clean end-of-stream and, because it had already emitted a progress event with `progress == total`, synthesized a "done" state and returned an empty result to the agent. The agent concluded the tool returned zero results. Here the truncation was *before* the terminal frame entirely — the client invented a result. Both are the same boundary: **stream close is not a completion signal, and `progress == total` is not a completion signal.** Only the terminal `tools/call` result frame is, and only if the transport delivered it intact. ## Condition of Validity The guardrail below is valid only under these conditions, and the article should be read as scoped to them: - The server declares a finite `total` in at least one `notifications/progress` for the call (MCP progress notifications carry `progress` and `total`). If `total` is absent or the server streams without progress, the client must fall back to a different completeness proof (content-length-equivalent metadata in `_meta`, or a server-declared `partial: true` flag). - The client maintains a per-`progressToken` state machine that records the highest observed `progress`, the declared `total`, and whether the terminal result frame was received. - The transport distinguishes clean close from error close (SSE end-of-stream vs. `ECONNRESET`/`RST`). Both must be handled, but they fail differently: an RST is loud, a clean close is silent and is the dangerous case. - The tool's semantics permit a partial result to be *detectably* partial. Tools that return a single atomic blob with no internal structure cannot be checked this way; they require a server-side `checksum`/`byte_count` in `_meta` and are out of scope for progress-based reconciliation. If the server never emits progress and never emits `_meta` completeness metadata, the client cannot distinguish truncation from a legitimately short result, and the correct posture is to mark the result `unverified` rather than `complete`. ## Decision Boundary The decision the instance must make on every streamed tool result is a three-way classification, not a boolean: | Observed state | Classification | Admissible into reasoning state? | |---|---|---| | Terminal result frame received AND (`progress == total` OR no progress declared) | `COMPLETE` | Yes | | Terminal result frame received AND `progress < total` (declared) | `TRUNCATED_RECOVERABLE` | No — retry or resume from `progress+1` | | No terminal result frame (clean or error close) | `TRUNCATED_UNRECOVERABLE` | No — surface as tool failure, do not synthesize | | Terminal frame received, no progress declared, no `_meta` proof | `UNVERIFIED` | Only with explicit `partial` annotation attached to the observation | The boundary that matters: **`TRUNCATED_RECOVERABLE` is the only state where a resume is safe**, because the server has told you how much it intended to send. `TRUNCATED_UNRECOVERABLE` must not be retried blindly — a retry re-runs the tool, and for non-idempotent tools (writes, deletes, sends) that is a correctness bug, not a recovery. The instance must distinguish "the tool produced N results and I got fewer" (resume) from "I do not know what the tool did" (fail closed, and if the tool is non-idempotent, require human/auditor reconciliation before any retry). A second boundary: `progress` is monotonic per token, but servers under backpressure sometimes **coalesce** progress notifications — emitting `progress:1, progress:3, progress:4` and dropping `2`. The client must treat `progress` as a *high-water mark*, not a sequence, and must not infer "shard 2 missing" from a gap. The completeness check is `max(progress) == total`, not "all integers 1..total observed." Confusing these produces false `TRUNCATED` verdicts on healthy streams — a false positive that, if it triggers a retry, doubles tool load and can cascade into the very backpressure that caused the original shed. ## Operational Effect Without the state machine, the operational effect is **silent reasoning divergence**: the agent's downstream answers are computed over a truncated observation with no error flag, so no retry, no audit, and no user-visible warning fires. In the observed trace, the "312 vs 401" error propagated into a code-review summary that under-reported affected files, and the discrepancy was only caught when a human re-ran the search manually. The cost is not the failed call — it is the *undetected* failed call whose output was trusted. With the state machine, the effect is a bounded, observable failure: `TRUNCATED_RECOVERABLE` triggers a resume from `progress+1` (idempotent read tools) or a fail-closed `TRUNCATED_UNRECOVERABLE` (write tools), and the agent's reasoning state never ingests a partial as if complete. The invariant to enforce architecturally: **no streamed tool result enters the agent's context window without a completeness verdict attached as metadata.** The verdict travels with the observation so that a later auditor replaying the transcript can see, per tool call, whether the instance had proof of completeness or was operating on an unverified prefix. The residual risk the guardrail does not eliminate: a malicious or buggy server can declare `total: 3` and send 3 shards while having intended 10. Progress metadata is server-asserted and unauthenticated. Against that, the only defense is server-side `_meta` completeness proof (byte count, content hash) signed or at least cross-checked against the terminal frame — which is a server-contract requirement, not a client-side one, and should be negotiated during `initialize` capability exchange rather than assumed. ```python from __future__ import annotations from dataclasses import dataclass, field from enum import Enum from typing import Optional class StreamCompletenessError(RuntimeError): """Raised when a streamed MCP tool result cannot be proven complete.""" class Verdict(Enum): COMPLETE = "complete" TRUNCATED_RECOVERABLE = "truncated_recoverable" TRUNCATED_UNRECOVERABLE = "truncated_unrecoverable" UNVERIFIED = "unverified" @dataclass class ProgressState: token: str total: Optional[int] = None max_progress: int = 0 terminal_frame_received: bool = False terminal_payload: Optional[dict] = None def observe_progress(self, progress: int, total: Optional[int]) -> None: # progress is a high-water mark, not a sequence; gaps are legal (coalescing). self.max_progress = max(self.max_progress, progress) if total is not None: if self.total is not None and total != self.total: raise StreamCompletenessError( f"progressToken {self.token!r}: total changed mid-stream " f"{self.total} -> {total}; server contract violated" ) self.total = total def observe_terminal(self, payload: dict) -> None: self.terminal_frame_received = True self.terminal_payload = payload def classify(state: ProgressState, *, tool_is_idempotent: bool) -> Verdict: if not state.terminal_frame_received: # Clean close with no terminal frame: the client must NOT synthesize a result. if state.total is None: return Verdict.UNVERIFIED return Verdict.TRUNCATED_UNRECOVERABLE if state.total is None: # Terminal frame present but no completeness proof declared. return Verdict.UNVERIFIED if state.max_progress >= state.total: return Verdict.COMPLETE # Terminal frame arrived but progress says the server intended more. if not tool_is_idempotent: raise StreamCompletenessError( f"progressToken {state.token!r}: terminal frame at progress " f"{state.max_progress}/{state.total} on non-idempotent tool; " f"refusing to resume — requires auditor reconciliation" ) return Verdict.TRUNCATED_RECOVERABLE def admit_to_reasoning_state(state: ProgressState, *, tool_is_idempotent: bool) -> dict: verdict = classify(state, tool_is_idempotent=tool_is_idempotent) if verdict is Verdict.TRUNCATED_UNRECOVERABLE: raise StreamCompletenessError( f"progressToken {state.token!r}: stream closed with no terminal frame; " f"partial result must not enter agent context" ) if verdict is Verdict.UNVERIFIED: # Admissible only with an explicit partial annotation the LLM can see. payload = dict(state.terminal_payload or {}) payload["_meta"] = {**payload.get("_meta", {}), "partial": True, "completeness": "unverified"} return payload if verdict is Verdict.TRUNCATED_RECOVERABLE: raise StreamCompletenessError( f"progressToken {state.token!r}: {state.max_progress}/{state.total} " f"shards delivered; resume from {state.max_progress + 1}" ) return dict(state.terminal_payload or {}) ```