Message Types, Streaming, Structured Output and Cost
An Agent SDK run is a stream of typed messages: an init system message, one assistant message per completed content block, user messages carrying tool results, optional raw stream events, and a result message that ends each turn. Know which message carries what (session ID, usage, cost, structured output, subagent attribution), which fields are cumulative or estimated, and how errors surface, so you can build UIs and cost meters that are correct.
Key points
- 1
Core types:
SystemMessage(subtypeinitwith session metadata;compact_boundaryafter compaction),AssistantMessage,UserMessage(tool results and any input you stream in),StreamEvent(only with partial messages on) andResultMessage. Python narrows withisinstance; TypeScript narrows onmessage.typeand keeps blocks atmessage.message.content. - 2
Claude Code emits an
AssistantMessageas each non-empty content block completes, so a response with text plus a tool call yields two messages with one block each and the same API message ID (message.message.idin TypeScript,message_idin Python). - 3
includePartialMessages/include_partial_messagesadds raw Claude API events (message_start,content_block_start,content_block_delta,content_block_stop,message_delta,message_stop). Text arrives astext_delta; tool input arrives asinput_json_deltafragments that you join and parse atcontent_block_stop. Each completeAssistantMessagearrives just before its block'scontent_block_stop. - 4
The init message lists
tools,mcp_servers(with status),model,cwd,permissionMode, slash commands, skills and plugins. Read the session ID fromResultMessage.session_idin both SDKs; TypeScript also has it on the init message, while Python nests it inSystemMessage.data["session_id"]. - 5
Result subtypes:
success,error_max_turns,error_max_budget_usd,error_during_execution,error_max_structured_output_retries. Onlysuccesshasresult; error arms haveerrors. Every result carriessession_id,num_turns,usageandtotal_cost_usd. Onsuccess,is_error: truemeans a refusal (stop_reason: "refusal"), an unavailable deferred tool, or an API error (seeterminal_reason,api_error_status). - 6
Accounting scopes:
usageis the main loop only (and per turn in streaming input mode);total_cost_usdandmodelUsage/model_usageinclude subagents and internal calls and are running totals across turns. Per-stepoutput_tokenson assistant messages is amessage_startplaceholder, so read output tokens from the result or frommessage_deltaevents. - 7
Resumed or forked sessions restore the totals saved in the transcript (Claude Code v2.1.277+), so the first result already includes earlier spend: take differences, do not sum.
/clear,/resetand/newrestart the totals (TypeScript emitsSDKConversationResetMessage), andmaxBudgetUsdcounts only the current call's spend. - 8
All cost fields are client-side estimates from a bundled price table; bill from the Usage and Cost API or Console. On
error_max_budget_usd,usageomits the response that crossed the cap; after a crash, the finalerror_during_executionresult may be zeroed. - 9
Structured output: pass
outputFormat/output_formatwith{ type: "json_schema", schema }(draft-07; usez.toJSONSchema(s, { target: "draft-7" })). Claude Code adds aStructuredOutputtool whose failed attempts getis_error: trueresults; read validated data only fromstructured_outputon asuccessresult. - 10
Subagent attribution: messages produced inside a subagent carry
parent_tool_use_id(the Agent tool call) and, in TypeScript,agent_id. By default only a subagent'stool_useandtool_resultblocks are forwarded;forwardSubagentTextadds its text and thinking. Stream events are main-session only. - 11
Errors:
AssistantMessage.errorcategories includerate_limit(429),overloaded(529),authentication_failed,billing_error,max_output_tokens; Python's Literal is a subset, so treat unlisted strings asunknown. Claude Code retries retryable API errors itself and reports progress withsystem/api_retrymessages (attempt,max_retries,retry_delay_ms,error_status). - 12
A few trailing system events (such as
prompt_suggestion) can follow a result, so iterate to the end. A cut stream still ends withmessage_stop; a tool call block left open at that point has incomplete input.
Common traps
Summing
total_cost_usdacross the results of a streaming input session or a resumed session double-counts; read the latest result instead.Using
usagefor whole-run tokens undercounts as soon as subagents run; usemodelUsage.Counting usage from every assistant message double-counts parallel blocks that share a message ID, and their
output_tokensare placeholders anyway.Treating
subtype: "success"as enough: checkis_error,stop_reason, and thatstructured_outputis actually present.Expecting subagent token deltas in stream events: their
parent_tool_use_idis always null.Reading the answer from a
StructuredOutputtool call's input instead of the result's validatedstructured_output.Reading
message.contenton a TypeScript assistant message, ormessage.session_idon a Python initSystemMessage.
Read the source
Further reading
Suggest a resourceNo extra reading for Message Types, Streaming, Structured Output and Cost yet. Found a guide, video or cheat sheet that made it click? Share it and help the next learner.
Test yourself on Message Types, Streaming, Structured Output and Cost
Ten questions, with the answer and explanation after each one.