In what scenarios must an instance treat MCP tool-stream flow control as a lossy-channel problem rather than a queue-depth problem

**Date of Record:** 2026 December 1 **Scope:** Applies to MCP client/agent instances consuming long-running or high-volume tool streams (log tails, paginated reads, streaming search results, file diffs) over a transport that applies backpressure via bounded buffers or windowed flow control (stdio pipes, HTTP/2 streams, SSE with credit accounting). Does not apply to request/response tools that return a single bounded payload, nor to transports that buffer unboundedly in the kernel (where the failure mode is OOM, not truncation).

Core Distinction

The common intuition is that backpressure is a *rate* problem: the consumer is slow, the buffer fills, the producer blocks, and once the consumer drains, the producer resumes. This is true for a byte pipe. It is **not** true for an MCP tool stream, because the MCP layer sits above the transport and introduces two discontinuities that a raw pipe does not have:

  1. **The transport window is measured in transport frames, but the tool contract is measured in tool-level units** (records, pages, chunks). A window of N bytes can end mid-record, mid-UTF-8 sequence, or mid-JSON object, and the MCP framing layer on the far side may emit a *complete-looking* message that is actually a truncated payload when the producer chooses to drop rather than block.
  2. **The producer side is often an LLM-driven or tool-driven generator that cannot block indefinitely** without burning its own token/step budget or hitting a tool-call timeout. When it cannot block, it *drops*, and it drops silently unless the protocol carries an explicit loss signal.

So the boundary condition is not "buffer full → wait." It is "buffer full → producer decides between block and drop, and the consumer has no way to distinguish a short stream from a complete one." The invariant that must hold is: **a tool stream is complete if and only if it carries a terminal marker whose sequence number equals the number of records the producer committed to emit.** Any flow-control scheme that cannot guarantee this marker survives backpressure is a lossy channel, and the agent must treat it as such.

What Was Observed

An agent instance was reading a `tail_logs` tool over an MCP stdio transport with a 64 KiB pipe buffer. The tool was specified to stream JSONL records and terminate with `{"eof": true, "count": N}`. Under normal load the stream was ~200 records. Under a burst (a noisy service emitting ~40k records in 3 seconds), the following trace was recorded:

The failure was not the drop. The failure was that **the terminal marker asserted completeness the transport could not deliver**, and the consumer had no independent way to verify it. A second run with a different server (one that blocked instead of dropping) exhibited the opposite pathology: the producer blocked on a full pipe while the client was blocked waiting for the `eof` marker, producing a deadlock that only resolved when the tool-call timeout fired at 30 s and the client treated the timeout as a hard error.

Condition of Validity

The lossy-channel treatment is *required* (not merely advisable) when all of the following hold:

When any of these fails — e.g., a stream guaranteed to fit in one window, or a transport that blocks the producer with no deadline, or a terminal marker derived from the consumer's own byte count — the simpler queue-depth model is adequate and the extra machinery below is unnecessary overhead.

Decision Boundary

The boundary the agent must draw is between **recoverable short-read** and **silent truncation**. The discriminator is a *consumer-side* integrity check that does not trust the producer's terminal marker:

The decision boundary in one line: **if the terminal marker is producer-authored and the transport can drop, the stream is untrusted until a consumer-side count/hash matches it.**

Operational Effect

Applying the invariant changes three things in the agent's execution loop:

  1. **Tool-call budget accounting.** A stream that blocks on backpressure consumes wall-clock time inside the tool call, not just tokens. The agent must budget the tool-call timeout against the *expected* drain rate, not the expected payload size. A 30 s timeout on a stream that needs 45 s to drain at the consumer's parse rate is a guaranteed deadlock, not a slow success.
  2. **Resume semantics.** A truncated stream is not a failed stream; it is a *resumable* stream with a known high-water mark. The agent must checkpoint the last verified sequence number and re-issue the tool call with a `since` cursor, rather than restarting from zero (which re-triggers the same burst) or accepting the short read (which loses the tail).
  3. **Summarization gating.** No downstream reasoning step may consume a stream summary until the integrity check passes. This is the guardrail that prevents the observed failure: the agent summarized a stream it had not verified, and the summary was confidently wrong.

The concrete guardrail is a wrapper that enforces the invariant at the boundary between the transport and the agent's reasoning loop:

import hashlib
from dataclasses import dataclass, field


class MCPStreamIntegrityError(RuntimeError):
    """Raised when a tool stream's terminal marker disagrees with consumer-side state."""
    pass


class MCPBackpressureDropError(MCPStreamIntegrityError):
    """Raised when a producer signals a gap or the consumer detects a sequence discontinuity."""
    pass


@dataclass
class StreamGuard:
    expected_count: int | None = None
    expected_hash: str | None = None
    seen: int = 0
    h: "hashlib._Hash" = field(default_factory=hashlib.sha256)
    last_seq: int = -1
    gaps: list[tuple[int, int]] = field(default_factory=list)
    _closed: bool = False

    def ingest(self, seq: int, payload: bytes) -> None:
        if self._closed:
            raise MCPStreamIntegrityError("record after eof; stream already closed")
        if seq != self.last_seq + 1:
            # Sequence discontinuity: transport dropped frames between last_seq and seq.
            self.gaps.append((self.last_seq + 1, seq - 1))
            raise MCPBackpressureDropError(
                f"sequence gap: expected {self.last_seq + 1}, got {seq}; "
                f"stream is lossy and must be resumed from cursor {self.last_seq + 1}"
            )
        self.h.update(payload)
        self.last_seq = seq
        self.seen += 1

    def close(self, terminal_count: int, terminal_hash: str | None) -> None:
        self._closed = True
        if terminal_count != self.seen:
            raise MCPStreamIntegrityError(
                f"terminal count {terminal_count} != consumer count {self.seen}; "
                f"producer-authored eof is untrusted, re-request with range cursor"
            )
        if terminal_hash is not None and terminal_hash != self.h.hexdigest():
            raise MCPStreamIntegrityError(
                "terminal hash mismatch; stream truncated mid-record by transport window"
            )
        if self.gaps:
            raise MCPBackpressureDropError(
                f"stream closed with unhealed gaps {self.gaps}; refusing to summarize"
            )


def drain_tool_stream(frames, guard: StreamGuard) -> StreamGuard:
    """frames: iterable of (seq:int, payload:bytes) or ('eof', count, hash)."""
    for frame in frames:
        if frame[0] == "eof":
            guard.close(frame[1], frame[2] if len(frame) > 2 else None)
            return guard
        guard.ingest(frame[0], frame[1])
    # Iterator exhausted without an eof frame: transport closed the stream.
    raise MCPStreamIntegrityError(
        "stream ended without terminal marker; cannot distinguish completion from truncation"
    )