Streaming makes an agent feel responsive, and it creates a bug class that a normal request never has. A tool call can exist in your client as a half-finished object. If the stream handler dispatches on the first event that names a tool, it may run write_file with a truncated argument, or run the first of two tool calls from a turn that was cut off before the second one finished. These bugs rarely show up in tests, because a short, clean response never reaches them.

This article covers what the stream sends for tool calls, a small gate that commits a call only when its arguments are complete and valid, and the failure paths: truncation at max_tokens, errors after the HTTP 200, and streams that simply stop.

What the stream sends for a tool call

For tool use, the relevant events are message_start; then, for each content block, content_block_start, zero or more content_block_delta events, and content_block_stop; then message_delta carrying the stop_reason; and finally message_stop. ping events can appear anywhere, and the docs say new event types may be added, so unknown types should be ignored.

A tool call arrives as a tool_use block. Its start event carries an id, a name, and input: {}. That empty object is a placeholder. The real arguments arrive as input_json_delta events, each with a partial_json string fragment. The final input is always an object, but the pieces you receive are not.

Every event carries an index matching the block's position in the final content array. With two tool calls in one response, deltas interleave, so key your buffers by index, never by "the tool currently open."

Two facts shape the design. By default the API buffers each key and value of a tool's input until it is complete. Fine-grained tool streaming, enabled per tool with eager_input_streaming: true, removes that buffering, and the docs warn that partial or invalid JSON can then reach you, and that max_tokens can cut a parameter off midway. Separately, errors can arrive inside the stream after the 200 status has gone out, such as overloaded_error. The SDK raises an exception that ends the stream; a raw SSE client receives an error event.

Accumulate by index, and commit only at block stop

The accumulation contract from the docs is simple: open a buffer on a tool_use start, append each partial_json, and parse on content_block_stop. Everything before the stop is provisional.

The gate below adds three things: it checks required keys, it records every rejection instead of dropping it silently, and it reports a turn as safe only when the stream reached message_stop with no error, no open blocks, and a stop_reason of tool_use. Several SDKs ship accumulator helpers for assembly, but the execution policy is yours.

import json
from dataclasses import dataclass, field


@dataclass
class ToolCall:
    id: str
    name: str
    input: dict


@dataclass
class _OpenBlock:
    id: str
    name: str
    fragments: list = field(default_factory=list)


class ToolCallGate:
    """Feed raw stream events in order; collect only tool calls that are complete."""

    def __init__(self, required_keys):
        self.required_keys = required_keys  # tool name -> set of required keys
        self.open = {}        # content block index -> _OpenBlock
        self.calls = []       # committed, validated ToolCall objects
        self.problems = []    # human-readable reasons something was rejected
        self.stop_reason = None
        self.error = None
        self.complete = False  # set by message_stop

    def feed(self, event):
        kind = event.get("type")
        if kind == "content_block_start" and event["content_block"]["type"] == "tool_use":
            block = event["content_block"]
            self.open[event["index"]] = _OpenBlock(block["id"], block["name"])
        elif kind == "content_block_delta" and event["delta"]["type"] == "input_json_delta":
            block = self.open.get(event["index"])
            if block is not None:
                block.fragments.append(event["delta"]["partial_json"])
        elif kind == "content_block_stop":
            block = self.open.pop(event["index"], None)
            if block is not None:
                self._commit(block)
        elif kind == "message_delta":
            self.stop_reason = event["delta"].get("stop_reason")
        elif kind == "error":
            self.error = event["error"]
        elif kind == "message_stop":
            self.complete = True
        # message_start, ping and unknown event types are ignored.

    def _commit(self, block):
        raw = "".join(block.fragments)
        try:
            args = json.loads(raw)
        except json.JSONDecodeError:
            self.problems.append(f"{block.name}: invalid JSON ({len(raw)} chars)")
            return
        if not isinstance(args, dict):
            self.problems.append(f"{block.name}: input is not an object")
            return
        missing = self.required_keys.get(block.name, set()) - args.keys()
        if missing:
            self.problems.append(f"{block.name}: missing {sorted(missing)}")
            return
        self.calls.append(ToolCall(block.id, block.name, args))

    def finish(self):
        """Call once the stream has ended, normally or by exception."""
        for block in self.open.values():
            self.problems.append(f"{block.name}: stream ended before block closed")
        self.open.clear()
        if self.error is not None:
            self.problems.append(f"stream error: {self.error.get('type')}")
        if not self.complete:
            self.problems.append("stream ended without message_stop")
        if self.stop_reason == "max_tokens":
            self.problems.append("turn truncated at max_tokens")
        return self.calls

    def safe_to_execute(self):
        return (
            self.error is None
            and self.complete
            and self.stop_reason == "tool_use"
            and not self.open
            and not self.problems
        )


def run_turn(events, required_keys):
    gate = ToolCallGate(required_keys)
    try:
        for event in events:
            gate.feed(event)
    except RuntimeError as exc:  # stands in for an SDK raising mid-stream
        gate.problems.append(f"exception: {exc}")
    gate.finish()
    return gate

A committed call is not a safe turn. The caller must check safe_to_execute(), not calls.

I ran the gate against simulated event sequences that follow the documented shapes. They are not captured live traffic, so they test the logic, not the API:

| Simulated stream | Calls committed | Safe to execute | |---|---|---| | Two interleaved calls, closed out of order, clean end | 2 | yes | | One call, truncated at max_tokens mid-argument | 0 | no: invalid JSON, turn truncated | | overloaded_error while a block was open | 0 | no | | Client raises connection reset mid-argument | 0 | no | | Valid JSON missing a required key | 0 | no | | Block closed cleanly, stream ended before message_stop | 1 | no | | Single clean call | 1 | yes |

Why one bad block stops the whole turn

The gate is all-or-nothing per response: if one block is rejected, nothing from that turn runs, even siblings that parsed. A model that emits two calls in one turn may have meant the second to depend on the first, and running one while its partner is missing can produce a state no correct sequence would reach.

Refusing to run is not the same as ignoring the calls. The docs require a tool_result for every tool_use block, even when the tool failed, placed immediately after the request. So answer each id with is_error: true and a message saying what went wrong. The fine-grained streaming docs suggest wrapping unparseable input in a JSON object under a key such as INVALID_JSON, so the model sees what it sent. Cap retries, since the model may simply call the tool again.

The cost is one extra round trip when a block is malformed, which is the right trade for side-effecting tools. Independent, read-only calls could be committed separately, but only if nothing in the turn depends on another call's result.

Failure modes and trade-offs

Truncation can hide missing calls. A truncated argument is usually invalid JSON, and the parse catches it. The harder case is a turn cut off after several blocks closed cleanly: later calls are missing, and no parse error reports that. Treat max_tokens as an incomplete turn and retry with a larger budget.

Eager streaming is a latency choice, not a correctness one. It helps when a UI should show a large string argument as it is written. The gate must be correct in both modes.

Previews are not execution. Render progress from a lenient partial parser, such as the Pydantic approach the docs mention, and keep that path separate from anything that executes.

Read-only tools are not exempt. A read with a truncated path returns wrong data, and the agent reasons from it.

The SDK path and the raw path must converge. Route an error event and an exception into the same failure handling. Two paths that treat errors differently are easy to get subtly wrong.

Checklist

  • Key every buffer by content block index, not by arrival order.
  • Open a buffer only on a tool_use start, and ignore its input: {} placeholder.
  • Parse on content_block_stop, never on a delta.
  • Check required keys before a call is eligible to run.
  • Require message_stop, a stop_reason of tool_use, and no error before executing anything from a turn.
  • Route in-stream error events and SDK exceptions to the same failure path.
  • Treat max_tokens as an incomplete turn, even when some blocks closed cleanly.
  • Ignore ping and unknown event types.
  • Answer every tool_use id, including rejected ones, with is_error where the call failed.
  • Test truncated, interleaved, errored and unterminated streams, not only the clean path.

Further reading