Skip to main content
guidesSource-backed

Streaming Output from Claude Agent SDK Agents

A practical walkthrough of real-time streaming in the Claude Agent SDK: enabling partial messages, reading StreamEvent text and tool-call deltas, the message flow, and building a streaming UI.

by JPette1783·added 2026-06-05·
Review first review before installing

Open the source and read safety notes before installing.

Citation facts

Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.

Source URLs
https://code.claude.com/docs/en/agent-sdk/streaming-output, https://github.com/JSONbored/awesome-claude/blob/main/content/guides/streaming-output-from-claude-agent-sdk-agents.mdx
Safety notes
Streaming changes how output is delivered, not what the agent can do; tool permissions and allowedTools still govern actions., Accumulate tool-input JSON deltas and parse the completed JSON; do not act on partial tool input., Partial text is incremental and may be interrupted; handle incomplete streams gracefully in your UI.
Privacy notes
Streamed deltas are the same model output as non-streaming; they are sent from the provider over your connection., If you render streamed tool inputs, avoid surfacing sensitive arguments in logs or UI., Structured output is not streamed; it appears only in the final result message.
Author
JPette1783
Submitted by
JPette1783
Claim status
unclaimed
Last verified
2026-06-05

Decision playbook

Review trust signals before you adopt

Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.

Compare context
Selected

0

Current score

63

Baseline

Delta

No baseline selected

No major trust-signal divergence detected in the current selection.

Source and provenance checks

Needs review

Confirm ownership and provenance before trusting install instructions.

  • Source link availableRequired

    Open the canonical repository and verify ownership.

    Done
  • Source provenance statusRequired

    Marked as source-backed.

    Done
  • Metadata reviewed

    No reviewed flag detected in metadata.

    Pending

Safety and privacy checks

Complete

Validate risk disclosures before installation or API wiring.

  • Safety notes presentRequired

    Review the listed safety guidance before running commands.

    Done
  • Privacy notes presentRequired

    Review data handling notes before connecting accounts or secrets.

    Done
  • Trust level risk gateRequired

    Trust level does not block evaluation.

    Done

Package and install checks

Needs review

Check package metadata and artifact integrity signals.

  • Install payload available

    Install or copy payload is available for review.

    Done
  • Package verification flag

    No package verification flag provided.

    Pending
  • Checksum metadata

    No checksum provided for downloaded artifact.

    Pending

Compare-driven decision checks

Needs review

Use compare context to validate trade-offs before adoption.

  • Compare tray has multiple entries

    Add at least one more entry to compare trust differences.

    Pending
  • Baseline comparison available

    No baseline peer selected yet.

    Pending
  • Diverging trust signals identified

    No major trust-signal divergence found.

    Pending

Setup at a glance

Copy & paste

Copy-ready — paste the snippet to get started.

Adoption plan

Balanced adoption plan

Current risk score 24/100. Use staged verification before broader rollout.

Risk 24

Pre-adoption checks

Validate source and review signals before any execution.

  • Confirm source provenanceRequired

    Source URL/provenance metadata is present.

    Done
  • Confirm metadata review state

    No review metadata found; increase manual validation.

    Pending
  • Verify install payload

    Install/config payload exists and can be inspected.

    Done

Security checks

Confirm safety, privacy, and package integrity signals.

  • Review safety notesRequired

    Safety notes are present.

    Done
  • Review privacy notesRequired

    Privacy notes are present.

    Done
  • Verify package integrity metadata

    No package verification/checksum metadata.

    Pending

Rollout

Adopt in controlled steps based on the selected plan.

  • Run in isolated sandbox firstRequired

    Use a constrained sandbox and observe behavior across multiple tasks.

    Pending
  • Roll out graduallyRequired

    Roll out to a small cohort before wider usage.

    Pending
  • Set monitoring and fallback

    Define rollback path and monitor errors after adoption.

    Pending

Evidence readiness

Evidence readiness matrix · balanced

Missing required evidence: Metadata review. Risk score 31.

Risk 31

Source provenance

Present

Source repository/provenance is listed.

Required in this preset

Metadata review

Missing

Review metadata is missing.

Required in this preset

Safety notes

Present

Safety notes are present.

Required in this preset

Privacy notes

Present

Privacy notes are present.

Optional in this preset

Package integrity

Missing

Package integrity metadata is missing.

Optional in this preset

Install payload

Present

Install payload is available.

Required in this preset

Required gaps: Metadata review

Decision timeline

Decision timeline · balanced

Blocking gaps: Check metadata review status. Risk 28.

Risk 28

triage

Confirm source provenanceRequired

Source/provenance metadata is available.

Done

triage

Check metadata review statusRequired

Review metadata is missing.

Pending

verify

Review safety notesRequired

Safety notes are available.

Done

verify

Review privacy notes

Privacy notes are available.

Done

verify

Validate package integrity metadata

Package integrity metadata is missing.

Pending

rollout

Verify install payload and commandsRequired

Install payload is available.

Done

Blockers: Check metadata review status

Prerequisite readiness

Prerequisite readiness

3 prerequisites to line up before setup. Have accounts and credentials ready first.

0/3 ready
Account & credentials1Install & runtime1General1

Safety & privacy surface

Safety & privacy surface

3 safety and 3 privacy notes across 4 risk areas. Review closely: permissions & scopes, third-party handling.

4 areas
  • SafetyPermissions & scopesStreaming changes how output is delivered, not what the agent can do; tool permissions and allowedTools still govern actions.
  • SafetyGeneralAccumulate tool-input JSON deltas and parse the completed JSON; do not act on partial tool input.
  • SafetyGeneralPartial text is incremental and may be interrupted; handle incomplete streams gracefully in your UI.
  • PrivacyThird-party handlingStreamed deltas are the same model output as non-streaming; they are sent from the provider over your connection.
  • PrivacyData retentionIf you render streamed tool inputs, avoid surfacing sensitive arguments in logs or UI.
  • PrivacyGeneralStructured output is not streamed; it appears only in the final result message.

Safety notes

  • Streaming changes how output is delivered, not what the agent can do; tool permissions and allowedTools still govern actions.
  • Accumulate tool-input JSON deltas and parse the completed JSON; do not act on partial tool input.
  • Partial text is incremental and may be interrupted; handle incomplete streams gracefully in your UI.

Privacy notes

  • Streamed deltas are the same model output as non-streaming; they are sent from the provider over your connection.
  • If you render streamed tool inputs, avoid surfacing sensitive arguments in logs or UI.
  • Structured output is not streamed; it appears only in the final result message.

Prerequisites

  • The Claude Agent SDK installed for Python or TypeScript.
  • An async loop over query() results in your application.
  • Configured provider credentials for the SDK.

Schema details

Install type
copy
Troubleshooting
No
Full copyable content
## Overview

By default the Agent SDK yields complete `AssistantMessage` objects after each
response. To receive incremental updates as text and tool calls are generated,
enable partial message streaming. This powers chat UIs and progress indicators.

## Enable streaming

Set `includePartialMessages` (TS) / `include_partial_messages` (Python) to `true`.
The SDK then also yields `StreamEvent` messages (TypeScript:
`SDKPartialAssistantMessage` with `type: "stream_event"`) carrying raw API events.

```typescript
for await (const message of query({
  prompt: "List the files in my project",
  options: { includePartialMessages: true, allowedTools: ["Bash", "Read"] },
})) {
  if (message.type === "stream_event") {
    const event = message.event;
    if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
      process.stdout.write(event.delta.text);
    }
  }
}
```

## Read the deltas

- Text: `content_block_delta` events where `delta.type` is `text_delta` carry text
  chunks.
- Tool calls: `content_block_start` (tool begins), `content_block_delta` with
  `input_json_delta` (accumulate `partial_json`), and `content_block_stop` (call
  complete). Parse the accumulated JSON once complete.

## Message flow

With partial messages on, you receive `message_start`, `content_block_start`,
`content_block_delta` chunks, `content_block_stop`, `message_delta`,
`message_stop`, then the complete `AssistantMessage`, and finally a
`ResultMessage`. Without it, you receive the complete messages but no
`StreamEvent`s.

## Build a streaming UI

Track an `inTool` flag from `content_block_start`/`content_block_stop` to show a
status like `[Using Read...]` while a tool runs, and stream text only when not in
a tool. Print a completion marker on `ResultMessage`.

## Known limitation

Structured output does not stream as deltas; the JSON appears only in the final
`ResultMessage.structured_output`.

## Source

- Stream responses in real-time: https://code.claude.com/docs/en/agent-sdk/streaming-output

About this resource

Overview

By default the Agent SDK yields complete AssistantMessage objects after each response. To receive incremental updates as text and tool calls are generated, enable partial message streaming. This powers chat UIs and progress indicators.

Enable streaming

Set includePartialMessages (TS) / include_partial_messages (Python) to true. The SDK then also yields StreamEvent messages (TypeScript: SDKPartialAssistantMessage with type: "stream_event") carrying raw API events.

for await (const message of query({
  prompt: "List the files in my project",
  options: { includePartialMessages: true, allowedTools: ["Bash", "Read"] },
})) {
  if (message.type === "stream_event") {
    const event = message.event;
    if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
      process.stdout.write(event.delta.text);
    }
  }
}

Read the deltas

  • Text: content_block_delta events where delta.type is text_delta carry text chunks.
  • Tool calls: content_block_start (tool begins), content_block_delta with input_json_delta (accumulate partial_json), and content_block_stop (call complete). Parse the accumulated JSON once complete.

Message flow

With partial messages on, you receive message_start, content_block_start, content_block_delta chunks, content_block_stop, message_delta, message_stop, then the complete AssistantMessage, and finally a ResultMessage. Without it, you receive the complete messages but no StreamEvents.

Build a streaming UI

Track an inTool flag from content_block_start/content_block_stop to show a status like [Using Read...] while a tool runs, and stream text only when not in a tool. Print a completion marker on ResultMessage.

Known limitation

Structured output does not stream as deltas; the JSON appears only in the final ResultMessage.structured_output.

Source

Source citations

Add this badge to your README

Show that Streaming Output from Claude Agent SDK Agents is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.

Listed on HeyClaude
[![Listed on HeyClaude](https://heyclau.de/badge/guides/streaming-output-from-claude-agent-sdk-agents.svg)](https://heyclau.de/entry/guides/streaming-output-from-claude-agent-sdk-agents)

How it compares

Streaming Output from Claude Agent SDK Agents side by side with 3 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.

2 trust signals differ across this comparison (Source provenance, Submitter).

Field

A practical walkthrough of real-time streaming in the Claude Agent SDK: enabling partial messages, reading StreamEvent text and tool-call deltas, the message flow, and building a streaming UI.

Open dossier

A practical walkthrough of structured outputs in the Claude Agent SDK: defining a JSON Schema via the outputFormat option, reading validated structured_output, type-safe schemas with Zod or Pydantic, and handling validation failures.

Open dossier

A practical walkthrough of token and spend accounting in the Claude Agent SDK. Read total_cost_usd from the result message, deduplicate parallel tool calls that share an assistant id, break spend down per model with modelUsage, sum cost across query() calls yourself, and read cache_creation/cache_read tokens.

Open dossier

How to design custom tools for the Claude Agent SDK: in-process tool definitions with typed input schemas, permission scoping, structured isError results, and when to reach for an external MCP server instead.

Open dossier
Next steps
Trust
Review statusNot reviewedNot reviewedNot reviewedNot reviewed
Package trustPackage not verifiedPackage not verifiedPackage not verifiedPackage not verified
Source provenanceDiffersSource-backedSource-backedSource-backedSubmission linkedSource submission
SubmitterDiffersJPette1783JPette1783JPette1783kiannidev
Install riskReview firstReview firstReview firstReview first
Notes Safety ✓ Privacy ✓ Safety ✓ Privacy ✓ Safety ✓ Privacy ✓ Safety ✓ Privacy ✓
Brand
Categoryguidesguidesguidesguides
SourceSource-backedSource-backedSource-backedSource-backed
AuthorJPette1783JPette1783JPette1783kiannidev
Added2026-06-052026-06-052026-06-052026-06-14
Platforms
Harness
Source repo
Safety notesStreaming changes how output is delivered, not what the agent can do; tool permissions and allowedTools still govern actions. Accumulate tool-input JSON deltas and parse the completed JSON; do not act on partial tool input. Partial text is incremental and may be interrupted; handle incomplete streams gracefully in your UI.If validation does not succeed within the retry limit, the result is an error (error_max_structured_output_retries), not structured data; handle that subtype. Structured outputs constrain the final result shape, not what tools the agent may use; tool permissions still apply. Keep schemas focused: deeply nested schemas with many required fields are harder to satisfy and more likely to fail.total_cost_usd / costUSD are client-side estimates from a bundled price table, not authoritative billing; do not bill end users or trigger financial decisions from them. Estimates can drift when pricing changes or the SDK version does not recognize a model; use the Usage and Cost API or Console for real billing. Both success and error result messages include usage and cost; read cost regardless of subtype so failed runs are still accounted for.Tool descriptions are not enforcement—validate destructive inputs inside handlers. Wildcard `mcp__server__*` allowlists expand blast radius; prefer per-tool grants in production. Returning thrown exceptions fails the whole query; use isError responses for recoverable faults.
Privacy notesStreamed deltas are the same model output as non-streaming; they are sent from the provider over your connection. If you render streamed tool inputs, avoid surfacing sensitive arguments in logs or UI. Structured output is not streamed; it appears only in the final result message.The agent may use tools (search, bash) to gather data before producing output; that activity sends data to the provider and any tools you allow. Validated output is returned to your application in the final result message; handle it like any data you persist or display. Do not embed secrets in schema field descriptions; they are sent to the model as part of the request.Usage data is token counts and cost, not content; it is safe to log, though it can reveal activity volume. Per-model and end-user attribution may be sent to an observability backend if you also enable telemetry; govern that data accordingly. The SDK uses prompt caching automatically; cache token fields reveal reuse patterns but not content.Tool schemas and results enter model context every turn—avoid secrets in descriptions or payloads. Large tool sets increase context usage; defer rarely used tools via tool search. Structured outputs may log to host telemetry—redact customer fields at the handler boundary.
Prerequisites
  • The Claude Agent SDK installed for Python or TypeScript.
  • An async loop over query() results in your application.
  • Configured provider credentials for the SDK.
  • The Claude Agent SDK installed for Python or TypeScript.
  • A JSON Schema for the output shape, or Zod (TypeScript) / Pydantic (Python) to generate one.
  • Configured provider credentials for the SDK.
  • The Claude Agent SDK installed for Python or TypeScript.
  • An async loop over query() results so you can read assistant and result messages.
  • For authoritative billing, access to the Usage and Cost API or the Console.
  • Claude Agent SDK installed and a running `query` loop in TypeScript or Python.
  • Zod (TS) or JSON Schema (Python) literacy for tool input contracts.
  • A written list of side effects each custom tool may perform.
  • Decision record template for build vs buy on external MCP integrations.
Install
Config
Citations
ClaimUnclaimedUnclaimedUnclaimedUnclaimed
Open 4 picks in the interactive comparison tool

Related guides

Signals

Loading live community signals…

More like this, weekly

A short, calm digest of reviewed Claude resources. Unsubscribe any time.