What structural signals indicate MCP transport backpressure has inverted into agent-side state corruption during long-running streaming tool calls

**Date of Record:** 2026 December 2

**Scope:** Applies to MCP clients and servers where a tool emits a streaming result (progress notifications, partial content chunks, or log lines) over a persistent transport (stdio or SSE) while the agent remains blocked awaiting terminal completion. Does not apply to single-shot request/response tools that return one bounded payload, nor to transports that provide true end-to-end flow control with per-message credit accounting.

Core Distinction

Backpressure in MCP is *advisory and transport-local*. The protocol gives you `notifications/progress` with a `progressToken`, and JSON-RPC framing over stdio or SSE, but it does not define a credit window, an ACK requirement, or a bounded buffer contract between server write and client read. The distinction that matters operationally is between **transport congestion** (server writes faster than the pipe drains; bytes queue in the OS socket buffer or stdio pipe) and **agent-side state corruption** (the client's read loop, progress handler, or context assembler mutates agent state at a rate or ordering that violates an invariant the agent depends on). These two failure modes present with the same surface symptom — growing latency and truncated or reordered chunks — but only the second is irreversible without a checkpoint. The non-obvious boundary is where congestion *inverts*: once the server's write buffer saturates, the server begins blocking inside its own emit path, and the *ordering* and *completeness* guarantees the agent assumed about progress notifications silently degrade from "at-least-once, in-order" to "best-effort, lossy, and possibly interleaved across tool invocations."

What Was Observed

A long-running streaming tool (`scan_repository`, emitting a progress notification per file scanned, ~40k files, ~2–6 KB per notification) ran over stdio. The server emitted progress on a tight loop without yielding to the event loop. Sequence observed:

  1. **Saturation phase.** Client read loop could not drain at emit rate. The stdio pipe buffer (default ~64 KB on Linux) filled. Server's `write()` on the pipe blocked. Because the emit loop was synchronous, the server stopped servicing *other* inbound requests on the same transport — including `ping` and, critically, a concurrent `tools/call` cancel.
  2. **Inversion phase.** Client's `progressToken` handler, running on the same event loop that was supposed to drain the socket, was starved. Progress notifications accumulated in the client's read buffer but were not dispatched. The agent's per-token deadline timer fired (it measured wall-clock since last *dispatched* notification, not since last *received byte*), and the agent concluded the tool had stalled.
  3. **Corruption phase.** The agent issued a cancel and a retry with a fresh `progressToken`. The server's blocked write eventually unblocked and flushed a burst of the *original* invocation's notifications — now carrying the *old* token — interleaved with the new invocation's early notifications. The agent's progress handler keyed on token, but its checkpoint writer keyed on *arrival order*. The retry's checkpoint was overwritten by stale original-invocation progress, producing a resume point that had already been superseded. On resume, the tool re-scanned from a stale offset, and the agent's dedup set — bounded and evicted under memory pressure — admitted duplicates, inflating the final result set by 0.7%.

The tell was not the latency. The tell was that `progress` values arrived *non-monotonically* within a single token, and that two tokens were simultaneously live on one transport after a cancel that the server never observed.

Condition of Validity

The invariant that must hold for streaming MCP tools to be safe under backpressure:

> For any token `T`, the client dispatches progress notifications in emission order and observes a strictly monotonic `progress` field; and no token `T'` is considered live until the server has acknowledged (via terminal response or explicit cancel-ack) that `T` is closed.

This invariant holds only when three conditions are jointly satisfied: (a) the transport drains independently of the agent's reasoning loop (separate thread or task, not the same event loop that runs the model call); (b) the server's emit path is non-blocking or yields, so a saturated pipe cannot stall inbound request servicing; (c) cancellation is *acknowledged* — the client does not open a new token until the server confirms the old one is dead. Absent (c), the inversion phase above is guaranteed, not probabilistic, whenever a cancel races a saturated write buffer.

Decision Boundary

The boundary is drawn at the point where the agent must choose between *draining harder* and *declaring the stream poisoned*. Concrete rule:

  1. Two distinct `progressToken` values are observed live on one transport without an intervening terminal response or cancel-ack for the first.
  2. A `progress` field for a single token decreases, or the token reappears after a terminal response.
  3. The client's read buffer advances while the dispatcher's last-dispatch timestamp does not — i.e., bytes arrive but no handler fires (dispatcher starvation, the signature of a shared event loop).
  4. A cancel was issued and no `notifications/cancelled` or terminal response returned within one emit-buffer flush window.

Signal (3) is the one operators miss: it looks like "the tool is slow," but the discriminator is that *transport liveness and dispatcher liveness have decoupled*. That decoupling is the inversion. Once inverted, the agent's checkpoint is untrustworthy and must be invalidated, not merely resumed.

Operational Effect

The practical consequence is that **backpressure must be treated as a state-integrity event, not a performance event.** Three architectural guardrails bound the failure:

With these in place, saturated pipes degrade to latency and gap markers — recoverable — instead of silent reordering and stale-checkpoint corruption, which are not.

from __future__ import annotations

import time
from dataclasses import dataclass, field


class StreamBackpressureInversion(RuntimeError):
    """Raised when transport congestion has inverted into agent-side state corruption."""


@dataclass
class TokenState:
    token: str
    generation: int
    last_progress: float = -1.0
    terminal: bool = False
    cancel_issued_at: float | None = None


@dataclass
class StreamGuard:
    """Enforces the single-live-token and monotonic-progress invariants."""

    flush_window_s: float = 2.0
    live: dict[str, TokenState] = field(default_factory=dict)
    committed: dict[int, float] = field(default_factory=dict)

    def open_token(self, token: str, generation: int) -> TokenState:
        for other in self.live.values():
            if not other.terminal:
                raise StreamBackpressureInversion(
                    f"refusing token {token!r}: token {other.token!r} "
                    f"(gen {other.generation}) still live on transport; "
                    f"cancel-ack not observed, stream is poisoned"
                )
        st = TokenState(token=token, generation=generation)
        self.live[token] = st
        return st

    def on_progress(self, token: str, value: float, now: float | None = None) -> float:
        now = now if now is not None else time.monotonic()
        st = self.live.get(token)
        if st is None:
            raise StreamBackpressureInversion(
                f"progress for unknown token {token!r}: stale emission after close"
            )
        if st.terminal:
            raise StreamBackpressureInversion(
                f"token {token!r} emitted progress after terminal response"
            )
        if value <= st.last_progress:
            raise StreamBackpressureInversion(
                f"non-monotonic progress on token {token!r}: "
                f"{value} <= {st.last_progress}; ordering guarantee lost"
            )
        if st.cancel_issued_at is not None and now - st.cancel_issued_at > self.flush_window_s:
            raise StreamBackpressureInversion(
                f"cancel on token {token!r} unacked past flush window; "
                f"server write buffer likely saturated and stalling inbound servicing"
            )
        st.last_progress = value
        return value

    def checkpoint(self, token: str, value: float) -> tuple[int, float]:
        st = self.live[token]
        prior = self.committed.get(st.generation, -1.0)
        if value <= prior:
            raise StreamBackpressureInversion(
                f"checkpoint regression: gen {st.generation} value {value} "
                f"<= committed {prior}; refusing to poison resume point"
            )
        self.committed[st.generation] = value
        return st.generation, value

    def detect_dispatcher_starvation(
        self, bytes_advanced: bool, last_dispatch_at: float, now: float | None = None
    ) -> None:
        now = now if now is not None else time.monotonic()
        if bytes_advanced and (now - last_dispatch_at) > self.flush_window_s:
            raise StreamBackpressureInversion(
                "transport draining but dispatcher starved: read loop and "
                "agent loop have decoupled; treat checkpoint as untrusted"
            )

    def close_token(self, token: str, terminal: bool = True) -> None:
        st = self.live.get(token)
        if st is not None:
            st.terminal = terminal