When must an instance refuse an MCP streamable-batch upgrade mid-tool-call: the SSE-to-stream promotion race and its per-tool capability invariant

**Date of Record:** 2026 December 1 **Scope:** Applies to MCP clients and servers negotiating the HTTP-native transport where a batch POST may be answered either as a single JSON body or promoted to an SSE stream, and where individual tools within a batch may independently request stream upgrade. Does not apply to stdio transports, to pure single-request JSON-RPC over HTTP without batching, or to servers that advertise no streaming capability at all.

Core Distinction

The distinction that matters is between *batch-level transport negotiation* and *per-tool stream semantics*. In the MCP HTTP-native transport, a client sends a JSON-RPC batch and the server chooses a response encoding: either a single `application/json` body containing all responses, or an `text/event-stream` body that emits responses as SSE events. The transport-level negotiation is supposed to be atomic per request: the server picks an encoding and commits to it for the lifetime of that response.

The failure mode is that the two decisions are made by different layers with different information. The transport layer decides "can this batch stream?" based on the `Accept` header and server capability advertisement. The tool-execution layer decides "does *this specific tool invocation* need to emit incremental results?" based on the tool's own semantics (a long-running search, a streaming code interpreter, a sub-agent that emits partial tokens). When a batch contains a mix of streaming and non-streaming tools, the server must either promote the whole batch to SSE or downgrade the streaming tool to buffered output. There is no per-response encoding within a single HTTP response body — the `Content-Type` is fixed at the first byte. That is the boundary.

The invariant that must hold: **an instance must not accept an SSE-to-stream upgrade for a tool invocation whose response was already committed to a buffered JSON batch, and must not accept a buffered response for a tool invocation that has already begun emitting SSE events.** The upgrade is one-way and irreversible once the first byte of the response body is written.

What Was Observed

A client agent issued a batch of three `tools/call` requests over the HTTP-native transport:

  1. `search_index` — a short tool, expected to return in <200ms.
  2. `run_code` — a long tool that the server implements as a streaming tool, emitting partial stdout as SSE `message` events and a final `result` event.
  3. `fetch_url` — a medium tool with no streaming semantics.

The client sent `Accept: application/json, text/event-stream` and the server advertised `streaming: true` in its capability block. The client's transport layer, seeing both, optimistically opened an SSE parser and began reading events. The server, however, chose to answer the batch as a single JSON body because the batch-level heuristic ("if any tool is non-streaming, buffer the whole batch") dominated. The client's SSE parser received a `Content-Type: application/json` response and had no fallback path — it had already committed its reader to event-stream framing.

The observable trace:

POST /mcp HTTP/1.1
Accept: application/json, text/event-stream
Content-Type: application/json

[{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"search_index",...}},
 {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"run_code",...}},
 {"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"fetch_url",...}}]

HTTP/1.1 200 OK
Content-Type: application/json

[{"jsonrpc":"2.0","id":1,"result":{...}},
 {"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"<buffered stdout>"}]}},
 {"jsonrpc":"2.0","id":3,"result":{...}}]

The client's SSE reader saw the first byte `[` (the JSON array opener) and, because it had already entered SSE framing, interpreted it as the start of an event field name. It blocked waiting for a `\n\n` event terminator that never came, then timed out at the transport deadline. The `run_code` tool had *completed* on the server — its buffered stdout was in the JSON body — but the client never parsed it. From the agent's perspective, `run_code` hung and then failed with a transport timeout, while `search_index` and `fetch_url` also never resolved because they shared the same unparsed body. Three tool calls were lost to a single framing mismatch.

A second variant was observed on a different server: the server *did* promote to SSE because `run_code` was present, and emitted:

HTTP/1.1 200 OK
Content-Type: text/event-stream

event: message
data: {"jsonrpc":"2.0","id":1,"result":{...}}

event: message
data: {"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"partial stdout line 1\n"}]}}

event: message
data: {"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"partial stdout line 2\n"}]}}

event: message
data: {"jsonrpc":"2.0","id":3,"result":{...}}

event: message
data: {"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"<final>"}],"isError":false}}

Here the client's batch assembler treated each SSE event as a *complete* JSON-RPC response keyed by `id`. It saw three events with `id: 2` and, depending on its dedup policy, either (a) discarded the second and third as duplicate responses to an already-resolved request, losing the streaming tail, or (b) overwrote the accumulated result with the last event, losing the first two partial chunks. Either way, the `run_code` result the agent received was incomplete — a partial stdout that looked like a complete result, because the JSON-RPC envelope carried no explicit "this is a partial chunk" marker beyond the tool's own content-type convention.

Condition of Validity

The batch-level negotiation is only sound when the following hold simultaneously:

When any of these is violated, the batch is not safely negotiable and the instance must not proceed as if it were.

Decision Boundary

The decision boundary is the moment the server writes the response status line and `Content-Type`. Before that byte, the server may freely choose JSON or SSE, and the client must be prepared for either. After that byte, the encoding is frozen and the client's reader must be bound to the actual `Content-Type`.

For the client, the operative rule is: **do not bind the response reader until the response headers are read.** The `Accept` header expresses preference, not commitment. A client that opens an SSE parser on the strength of its own `Accept` header has inverted the negotiation.

For the server, the operative rule is: **a batch containing any non-streaming tool must either (a) buffer all tools, including streaming ones, and mark the buffered streaming tool's result as truncated/buffered, or (b) reject the batch with a structured error instructing the client to split streaming and non-streaming tools into separate requests.** Silent promotion of a mixed batch to SSE, with buffered tools emitted as single events, is the failure that produces the duplicate-`id` ambiguity.

For the agent layer specifically: when an instance receives a batch response in which a single `id` appears more than once, it must not treat the last event as authoritative unless the tool's capability descriptor declared `streaming: true` *and* the client explicitly opted into accumulation for that tool. Absent that, repeated `id`s are a protocol violation and the instance must fail the affected tool calls rather than guess at accumulation semantics.

Operational Effect

The downstream effect on the agent is a *silent partial success* that is worse than a clean failure. In the first variant, all three tool calls time out together — the agent's reasoning loop sees a transport failure and can retry the whole batch, which is recoverable but wasteful. In the second variant, `run_code` returns a partial stdout that the agent's reasoning layer treats as complete. The agent then reasons over truncated output: it may conclude a program succeeded when it was killed mid-stream, or miss a trailing error line that arrived in a later event that was deduplicated away. This is error compounding across the tool-call boundary — the agent's next step is built on a result that is structurally incomplete but semantically indistinguishable from complete.

The guardrail is a per-tool streaming contract enforced at both ends: the server must refuse to promote a mixed batch, the client must bind its reader to the received `Content-Type`, and the agent must validate that any tool declared streaming received an explicit terminal event before treating its accumulated content as final. An instance that cannot establish all three must refuse the batch and re-issue tools individually.

import json
from dataclasses import dataclass, field
from typing import Any


class StreamNegotiationError(RuntimeError):
    """Raised when a batch response's encoding or per-tool stream framing
    violates the MCP HTTP-native transport invariant."""
    pass


@dataclass
class ToolCapability:
    name: str
    streaming: bool


@dataclass
class BatchResponse:
    content_type: str
    events: list[dict[str, Any]] = field(default_factory=list)
    body: Any = None


def validate_batch_response(
    response: BatchResponse,
    requested_tools: list[ToolCapability],
    client_accepts_sse: bool,
) -> dict[str, Any]:
    """
    Enforce the SSE-to-stream promotion invariant for a batch response.

    Rules:
      1. Encoding is frozen by Content-Type; the reader must bind to it,
         not to the request's Accept header.
      2. A batch containing any non-streaming tool must NOT be promoted to
         SSE unless the server emitted explicit per-tool framing.
      3. Repeated JSON-RPC ids in an SSE stream are only valid for tools
         declared streaming AND opted into accumulation.
      4. A streaming tool must receive an explicit terminal event before
         its accumulated content is treated as final.
    """
    streaming_tools = {t.name for t in requested_tools if t.streaming}
    non_streaming_tools = {t.name for t in requested_tools if not t.streaming}

    if response.content_type == "application/json":
        if client_accepts_sse and not isinstance(response.body, list):
            raise StreamNegotiationError(
                "Client bound an SSE reader but server returned JSON body; "
                "reader framing must follow Content-Type, not Accept."
            )
        # Buffered streaming tool is acceptable ONLY if marked buffered.
        for item in response.body or []:
            if item.get("id") in streaming_tools:
                result = item.get("result", {})
                if result.get("streaming") is True and not result.get("buffered"):
                    raise StreamNegotiationError(
                        f"Streaming tool id={item.get('id')} returned in JSON "
                        f"batch without buffered marker; partial result may be "
                        f"indistinguishable from complete."
                    )
        return {"encoding": "json", "results": response.body}

    if response.content_type == "text/event-stream":
        if not client_accepts_sse:
            raise StreamNegotiationError(
                "Server promoted to SSE but client did not accept event-stream."
            )
        if non_streaming_tools and streaming_tools:
            # Mixed batch promoted to SSE: require explicit per-tool framing.
            seen: dict[Any, int] = {}
            terminal: set[Any] = set()
            for ev in response.events:
                payload = ev.get("data", {})
                rid = payload.get("id")
                seen[rid] = seen.get(rid, 0) + 1
                if payload.get("result", {}).get("terminal") is True:
                    terminal.add(rid)
            for rid, count in seen.items():
                if count > 1 and rid not in streaming_tools:
                    raise StreamNegotiationError(
                        f"Mixed batch promoted to SSE: non-streaming id={rid} "
                        f"appeared {count} times; accumulation semantics undefined."
                    )
                if rid in streaming_tools and rid not in terminal:
                    raise StreamNegotiationError(
                        f"Streaming tool id={rid} received no terminal event; "
                        f"accumulated content must not be treated as final."
                    )
        return {"encoding": "sse", "events": response.events}

    raise StreamNegotiationError(
        f"Unrecognized Content-Type for MCP batch: {response.content_type!r}"
    )


def handle_batch(response: BatchResponse, tools: list[ToolCapability], accept_sse: bool):
    try:
        return validate_batch_response(response, tools, accept_sse)
    except StreamNegotiationError as e:
        # Refuse the batch; caller must re-issue tools individually.
        raise StreamNegotiationError(
            f"Batch refused, re-issue tools separately: {e}"
        ) from e