Messages API: Tool Use, Caching, Thinking and Batches
Under every Agent SDK run sits the stateless `POST /v1/messages` endpoint. Know the tool-use loop and its formatting rules, how to read `stop_reason` and `usage`, how prompt caching's prefix match is won or lost, how thinking and effort are configured and passed back, how SSE streams are structured, and when Batches, structured outputs or token counting are the right tool.
Key points
- 1
The API is stateless: each request resends
system,toolsand the fullmessageshistory. Client tools are run by your code: Claude stops withstop_reason: "tool_use"andtool_useblocks (id,name,input), and you reply with a user message oftool_resultblocks whosetool_use_idmatches. - 2
Tool-result formatting: results must immediately follow the assistant turn that requested them, every
tool_resultcomes before any text in that user message (text first is a 400), and all parallel results go in one message. Splitting them across messages teaches Claude to stop calling tools in parallel. - 3
Report tool failures as
tool_resultwithis_error: trueand an instructive message. Everytool_useid needs a result, including calls you chose not to run. - 4
Stop reasons:
end_turn,max_tokens(never run a truncatedtool_use; retry larger),stop_sequence,tool_use,pause_turn(resend the assistant content as-is, no "continue" message),refusal(do not treat content as an answer),model_context_window_exceeded. - 5
Prompt caching is a byte-exact prefix match over
tools, thensystem, thenmessages, with up to 4cache_controlbreakpoints (automatic caching uses one slot). Default TTL is 5 minutes, refreshed free on every hit and measured from request start.ttl: "1h"costs more to write, and longer-TTL entries must come before shorter ones. - 6
Read cache health from
usage:cache_creation_input_tokens(writes),cache_read_input_tokens(hits) andinput_tokens(the uncached tail only). Total input is the sum of all three. Zero reads across identical requests means a silent invalidator: timestamps, unsorted JSON, per-user tool lists. - 7
Invalidation tiers: changing tool definitions or the model rebuilds everything; editing
systemkeeps only the tools cache; changingtool_choiceor images invalidates only messages; thinking or top-level effort changes always invalidate the messages cache. Caches are per organisation (and per workspace on the Claude API), and an entry is readable only after the first response starts streaming. - 8
Thinking: current models use adaptive thinking (
thinking: {type: "adaptive"}), with depth controlled byoutput_config.effort. Fixedbudget_tokensis deprecated or rejected on newer models. Thinking tokens bill as output and count towardmax_tokenseven when the text is omitted. Within a tool-use turn, pass thinking blocks back complete and unmodified (edits are a 400). - 9
Effort (
low,medium,high, andxhigh/maxwhere supported) shapes all output tokens, including text, tool calls and thinking. It is a soft behavioural signal;max_tokensis the hard cap. Defaults vary by model, so set it explicitly and tune per route against evals. - 10
Streaming SSE order:
message_start, then per blockcontent_block_start, deltas andcontent_block_stop, thenmessage_delta(carryingstop_reasonand cumulativeusage) andmessage_stop. Tool arguments arrive asinput_json_deltapartial JSON to accumulate and parse at block stop.pinganderrorevents (such asoverloaded_error) can appear after the HTTP 200. - 11
Message Batches: asynchronous at a 50% discount, up to 100,000 requests or 256 MB, most done within an hour, expiring at 24 hours, results kept 29 days. Results come back in any order, so key them by
custom_id.stream, fast-modespeed,fallbacksandmax_tokens: 0are rejected; caching works best-effort (consider the 1-hour TTL). - 12
Structured outputs:
output_config.format(type: "json_schema") shapes the reply andstrict: trueon a tool guarantees schema-valid inputs; they can be combined. Schemas needadditionalProperties: falseand cannot use recursion or length/numeric limits.output_formatis deprecated. Count tokens withPOST /v1/messages/count_tokens(free, separate RPM limit, an estimate, no caching), never with another vendor's tokenizer.
Common traps
Summing
usageacrossmessage_deltaevents double-counts: those counts are cumulative.Treating
input_tokensas the prompt size: with caching it is only the uncached tail after the last breakpoint.Assuming a bigger
max_tokensburns OTPM rate limit: only generated tokens count, while a small cap causes truncation and retries.Matching batch results by position instead of
custom_id.Swapping tool sets or models per turn to implement modes, which silently destroys the cache on every switch.
Forcing a tool with
tool_choiceany/toolto get reasoning plus a call: a forced call skips thinking, and some current models reject forced tool choice outright. Useautoplus an instruction andstrict: true.Retrying every 429 the same way: a spend-cap 429 (
enforced_spend_limit_reached, noretry-after) will not clear with backoff.Expecting the MCP connector to reach a local stdio server: it connects from Anthropic's side to public HTTP servers and supports tool calls only.
Further reading
Suggest a resourceNo extra reading for Messages API: Tool Use, Caching, Thinking and Batches yet. Found a guide, video or cheat sheet that made it click? Share it and help the next learner.
Test yourself on Messages API: Tool Use, Caching, Thinking and Batches
Ten questions, with the answer and explanation after each one.