In short.
This is a cost-tracking guide for developers building Claude agents in TypeScript or Python, with estimated spending figures that cannot serve as authoritative billing records. Its main value is explaining which counters include subagents, when totals accumulate or reset, and why assistant-message output counts are incomplete. It also covers cache settings and recovery limits after failures. No examples were executed; runtime behavior, actual charges and achievable savings are not assessed.
Researched and written by an AI model and checked by a second AI model. How it works
Coverage is limited to the complete supplied documentation page at [https://code.claude.com/docs/en/agent-sdk/cost-tracking.md]. It includes the page's estimate warnings, examples, version caveats, failure cases and cache notices. Linked documentation, pricing, billing guidance, external image contents and SDK implementation files are excluded. No code was executed; runtime correctness, actual billing accuracy, performance and cache savings remain unassessed.
The overview
identity
Track cost and usage is a documentation guide for the Claude Agent SDK at [https://code.claude.com/docs/en/agent-sdk/cost-tracking.md]. The resource is the guide itself; it teaches an SDK feature rather than supplying a separate monitoring product.
It covers the TypeScript package @anthropic-ai/claude-agent-sdk and the Python module claude_agent_sdk. Both expose the same underlying usage information, with different field names and nesting.
assessment
The guide is useful for building development dashboards and approximate spending reports because it addresses concrete sources of incorrect totals: duplicate messages from parallel tools, cumulative resumed-session spending, missing subagent tokens and placeholder output counts.
Its usefulness depends on applying those accounting rules consistently. It does not establish billing accuracy, measured cache savings or production reliability, and it explicitly advises against billing end users or making financial decisions from its estimated dollar fields.
users
The main audience is developers adding usage reporting to Claude Agent SDK applications. Beginners get examples of reading result messages; experienced developers get distinctions needed for streaming conversations, multiple models, subagents, session resumption and failure handling.
The material is especially relevant when an application runs several agent steps for one user request. Teams needing invoice reconciliation or customer charge calculations require authoritative billing information beyond these SDK estimates.
capabilities
The guide explains how to read cumulative estimated cost, collect input and cache tokens per step, obtain output totals from results, and attribute tokens and estimated costs by model. Tokens are the units the model processes and generates; cache counters distinguish newly stored content from reused content.
It also explains combining independent calls, interpreting resumed sessions, accounting across streaming resets, retaining information from error results and requesting different cache lifetimes. It identifies maxBudgetUsd in TypeScript and max_budget_usd in Python as call-spending controls, with scope rules that matter when sessions resume or reset.
Using it
requirements
Applying the examples requires a working TypeScript or Python Claude Agent SDK environment and the ability to consume its asynchronous message stream. The page does not provide a complete installation procedure, general authentication setup or runtime-version requirements.
The optional Amazon Bedrock caching example requires working AWS credentials and sets CLAUDE_CODE_USE_BEDROCK. Those credentials are a requirement of that example, not an established requirement for every SDK deployment. Several accounting features also have version-specific requirements described in the page.
mechanism
A query() call can contain several model request-and-response steps. TypeScript exposes assistant-step identifiers and usage through message.message.id and message.message.usage; Python exposes message.message_id and message.usage. Parallel tool messages can share the same identifier and usage, so counting each identifier once prevents duplication. Per-step output_tokens is a placeholder; completed output counts must come from result data.
Result usage covers the main agent loop and excludes subagents. Result total_cost_usd includes subagents, while modelUsage in TypeScript and model_usage in Python include their activity with a model breakdown. In streaming input mode, usage covers only the current turn, while the cost and model breakdown are running totals.
Independent calls have separate totals that can be added. Resumed or forked sessions can restore earlier spending saved after a normal process exit, so adding their successive totals would double-count it. Streaming resets through /clear, /reset or /new start new accounting segments: add the last result before each reset to the call's final result.
Dollar estimates are computed locally from bundled prices or a modelPricing table. A model entry's costBasis identifies the pricing source for its latest request as list, managed or unknown; it does not establish agreement with an invoice.
setup
For simple estimated totals, handle result messages from query(). For detailed main-loop input accounting, keep a set of assistant-message identifiers and exclude subagent messages using parent_tool_use_id in the TypeScript example. Read whole-tree token totals from modelUsage or model_usage. Python cost and usage fields can be None, so missing values need explicit handling.
A streaming implementation needs to retain the last result before every reset, rather than summing every turn's cumulative result. The budget setting counts the call's own spend, excludes restored session spending and starts over after /clear.
Prompt caching is automatic. ENABLE_PROMPT_CACHING_1H requests a one-hour lifetime across both cache groups. More specific controls accept 5m or 1h and override it: CLAUDE_CODE_PROMPT_CACHE_TTL or promptCacheTtl for the main conversation, and CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL or subagentPromptCacheTtl for requests outside that conversation.
example
The simplest supplied example asks Claude to summarize a project, iterates over query() messages and prints total_cost_usd when a result arrives. TypeScript checks message.type; Python checks whether the message is a ResultMessage. Error handling surrounds the iteration because a single-shot call can yield an error result and then raise.
Another example accumulates input tokens once per unique main-loop message identifier and reads output tokens from result.usage.output_tokens. A separate example adds totals from two independent calls; that addition should not be copied unchanged for calls resuming the same session. These examples have not been executed.
Assessment & evidence
limitations
Failure accounting can be incomplete. An error_max_budget_usd result omits the budget-crossing response from usage, although total_cost_usd and modelUsage include it. Some connection or process failures provide no result message, while a session-crash result can contain zeroed counters. Such zeros do not establish that no spending occurred.
The guide recommends recovering an earlier result after a crash when available. Its assistant-message fallback recovers only main-loop input and cache tokens; it cannot recover output tokens, subagent usage or dollar cost. An earlier result should not be assumed to establish spending for unfinished work.
In single-message input mode, the SDK waits for background subagents before emitting the final result, but only up to a cap described on another page. This page does not specify that cap. No execution evidence establishes accounting completeness, crash recovery or behavior after that wait expires.
reasoning
The guide's central lesson is that a correct number needs a correct scope. Adding cumulative session totals inflates spending, while treating main-loop usage as whole-tree usage omits subagents. Neither error requires a pricing mistake.
For approximate all-agent reporting, the documented model breakdown is more suitable than summing assistant-message output counters. For actual financial records, the page's estimate warning remains decisive regardless of how carefully tokens are counted. These conclusions follow from the documented field scopes; they are not measured results.
alternatives
The page supports several approaches within the SDK. Read total_cost_usd for a simple approximate total, use modelUsage or model_usage for all-agent model attribution, or collect deduplicated assistant records for main-loop input and cache detail. These approaches answer different questions and are not interchangeable.
Authoritative billing records are the relevant alternative when estimated SDK costs are insufficient. Competing SDKs, external monitoring services and their pricing or capabilities are not assessed by the supplied evidence.
evidence
The evidence is the complete supplied text of Track cost and usage at [https://code.claude.com/docs/en/agent-sdk/cost-tracking.md]. It includes explanatory material, TypeScript and Python examples, version caveats and warnings about estimated costs.
Linked API references, pricing pages, session documentation and provider setup pages are outside the available evidence. Their contents have not been assessed. The supplied material contains documentation claims rather than execution results, independent benchmarks or reconciled bills.
Access & freshness
costs
The page supplies no per-model price list or measured workload bill, so an application's actual operating cost is unknown. total_cost_usd and per-model costUSD can diverge from billing when prices change, a model is unrecognized or billing rules are not represented locally. The page points to authoritative organization billing guidance at [https://code.claude.com/docs/en/costs.md#manage-costs-for-your-organization], whose contents are outside this resource.
One documented adjustment applies a 1.1 multiplier to a response's token list prices when usage reports inference_geo as us. Per-request fees such as web search are excluded from that multiplier. This behavior requires the SDK versions stated in the freshness section.
Cache creation tokens cost more than standard input tokens, while cache reads cost less. One-hour cache writes cost more than five-minute writes, so longer retention is a trade-off rather than a guaranteed saving. API-key and named cloud-provider deployments default to five minutes for main-conversation cache entries. Included Claude subscription usage receives one-hour caching for users' own turns and some helpers; usage credits normally revert those turns to five minutes unless an applicable setting keeps one hour.
rights
The supplied page contains no licence statement or explicit redistribution grant for its documentation or examples. Permission to redistribute the full page or reuse its code is therefore unknown from this evidence.
The SDK's software licence and provider terms are also not established by this page. Its public documentation address does not, by itself, establish those rights.
freshness
The supplied page was captured on 23 November 2026. Its publication and last-update dates are unknown, and later changes are not established.
The documented data-residency adjustment requires TypeScript Agent SDK v0.3.239 or later, or Python Agent SDK v0.2.144 or later. costBasis requires Claude Code v2.1.246 or later. Before Python SDK v0.2.137, the iterator dropped conversation-reset messages, requiring applications to track their own reset commands.
Before Claude Code v2.1.277, sessions resumed through the SDK or claude -p started cost totals at zero. That changes whether successive call totals should be added. The guide therefore needs to be interpreted against the installed SDK and Claude Code versions.
actions
Start by deciding whether the application needs main-loop tokens, all-agent attribution, approximate dollars or authoritative charges. Match the counter to that purpose, confirm installed versions, and retain session and reset boundaries so cumulative totals can be interpreted correctly.
Before relying on the integration, verify its handling of independent calls, resumed sessions, parallel tools, subagents, streaming resets, missing Python fields and error results. Preserve unavailable amounts as unknown rather than silently treating them as zero.
Evaluate longer cache retention against the workload's actual reuse intervals and charges. Use authoritative billing information for financial decisions; this guide alone cannot establish invoice accuracy or savings.
