How Claude Tool Calling Works
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
Lesson 4.1 showed one round trip. Real applications don't stop at one. Claude may call a tool, read the result, decide it needs another, and keep going until it has an answer. That repeating cycle is the agent loop, and almost every bug people hit with tool use comes from getting a detail of it slightly wrong. This lesson goes through the message shapes and rules, then builds a loop you can reuse.
What you'll learn
- The exact JSON shapes of
tool_use and tool_result blocks.
- The formatting rules that cause the most 400 errors.
- How a loop keyed on
stop_reason works, and how to stop it running away.
- What
tool_choice does, and why you usually can't force a tool on the newest models.
Before you start
The shapes
When Claude wants a tool, the response has stop_reason: "tool_use" and one or more tool_use blocks in content, often with a sentence of ordinary text before them:
{
"role": "assistant",
"stop_reason": "tool_use",
"content": [
{"type": "text", "text": "I'll check that order for you."},
{"type": "tool_use", "id": "toolu_01A09q90qw90lq917835lq9",
"name": "shop_lookup_order", "input": {"order_id": "A100"}}
]
}
Three fields matter: id (a unique id for this call), name, and input, an object that follows your tool's schema. Your answer goes in the next user message as a tool_result block:
{
"role": "user",
"content": [
{"type": "tool_result", "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
"content": "{\"status\": \"shipped\", \"tracking\": \"JD0146\"}"}
]
}
content can be a string, or a list of text, image or document blocks, and it's optional. is_error: true marks a failure. Notice there are no special "tool" or "function" roles, unlike some other APIs. Tool calls live inside ordinary assistant messages, and results live inside ordinary user messages.
The rules that bite
Anthropic's docs list formatting requirements, and each one maps to an error people actually see:
- The result message must come immediately after the tool call. You can't put another message between the assistant turn with the
tool_use and the user turn with the tool_result.
- Results go first in the content list. In the user message, every
tool_result block must come before any text. Text before a result is a 400 error; text after the results is fine.
- Answer every call. One
tool_result for each tool_use id. If you see "tool_use ids were found without tool_result blocks immediately after", this is where to look.
- Return the whole assistant turn unchanged. That includes any text, and any thinking blocks if thinking is on: with thinking and tools, the docs say to return the entire, unmodified thinking block with the tool result.
The loop
With the shapes clear, the loop is short. Anthropic describes the canonical form as a while loop keyed on stop_reason: while it's tool_use, run the tools and continue; on anything else, stop. Here is a reusable version. It takes an execute function, so the same loop works whether your tools are three lines of Python or a full registry (lesson 4.4):
from dataclasses import dataclass, field
from typing import Callable
import anthropic
# execute(name, tool_input) -> (content_string, is_error)
Execute = Callable[[str, dict], tuple[str, bool]]
class LoopLimitReached(RuntimeError):
pass
@dataclass
class AgentResult:
text: str
stop_reason: str
iterations: int
tool_calls: list = field(default_factory=list)
messages: list = field(default_factory=list)
input_tokens: int = 0
output_tokens: int = 0
def run_agent(
client: anthropic.Anthropic,
*,
model: str,
tools: list[dict],
execute: Execute,
user_text: str,
execute_many: Callable[[list[tuple[str, dict]]], list[tuple[str, bool]]] | None = None,
system: str | None = None,
max_iterations: int = 8,
max_tokens: int = 1024,
) -> AgentResult:
"""The whole tool loop in one function: ask, run what Claude requests, report back, repeat."""
messages: list[dict] = [{"role": "user", "content": user_text}]
result = AgentResult(text="", stop_reason="", iterations=0, messages=messages)
for iteration in range(1, max_iterations + 1):
kwargs = {"model": model, "max_tokens": max_tokens, "messages": messages}
if tools: # a signed-out user gets no tools at all, so send none
kwargs["tools"] = tools
if system:
kwargs["system"] = system
response = client.messages.create(**kwargs)
result.iterations = iteration
result.input_tokens += response.usage.input_tokens
result.output_tokens += response.usage.output_tokens
result.stop_reason = response.stop_reason or ""
# Always keep Claude's whole turn, exactly as returned, so the next request is valid.
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason == "tool_use":
blocks = [b for b in response.content if b.type == "tool_use"]
calls = [(b.name, dict(b.input)) for b in blocks]
# By default each call runs on its own. execute_many lets you run a whole batch (lesson 4.7).
outcomes = execute_many(calls) if execute_many else [execute(n, i) for n, i in calls]
tool_results = []
for block, (name, tool_input), (content, is_error) in zip(blocks, calls, outcomes):
result.tool_calls.append({"name": name, "input": tool_input, "is_error": is_error})
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": content,
**({"is_error": True} if is_error else {}),
})
# One user message holding every result; tool_result blocks first.
messages.append({"role": "user", "content": tool_results})
continue
if response.stop_reason == "pause_turn":
continue # a server-side tool paused the turn; sending it back lets Claude carry on
# end_turn, stop_sequence, max_tokens, refusal, model_context_window_exceeded: the loop is over.
result.text = "".join(b.text for b in response.content if b.type == "text")
return result
raise LoopLimitReached(f"Still calling tools after {max_iterations} iterations.")
def simple_execute(handlers: dict[str, Callable[..., str]]) -> Execute:
"""The smallest possible executor. Lesson 4.4 builds a safer one."""
def execute(name: str, tool_input: dict) -> tuple[str, bool]:
if name not in handlers:
return f"Unknown tool: {name}", True
try:
return str(handlers[name](**tool_input)), False
except Exception as e: # noqa: BLE001 - report every failure back to the model
return f"{type(e).__name__}: {e}", True
return execute
Walk through what each stop_reason does:
tool_use: run every tool_use block, put all the results in one user message, loop again.
end_turn or stop_sequence: Claude finished. Return the text.
max_tokens: the reply was cut off. It exits the loop so you can decide what to do; a tool call cut off halfway can't be trusted.
pause_turn: only relevant with server tools. A server-side loop hit its iteration limit, and sending the response back lets Claude continue.
refusal: Claude declined. Also ends the loop; treat it as the final answer for this turn.
The part people forget is the cap. max_iterations raises LoopLimitReached instead of looping forever. A confused model, a tool that keeps returning the same error, or an attacker's cleverly worded input can otherwise keep a conversation (and your bill) running. Eight is a sensible default for a support assistant; pick what suits your task.
We tested the loop against a mock API that scripts Claude's side. A single tool call finished in two iterations and the token counts were summed across both requests. Two calls in one turn produced a single user message holding two tool_result blocks with different ids. An unknown tool name came back as an is_error result and the loop carried on. A handler that threw an exception was reported as an error rather than crashing the loop. And a model that kept asking for a tool forever stopped with an error at exactly the iteration limit.
tool_choice: steering, not forcing
The tool_choice parameter has four values:
auto, the default when you provide tools: Claude decides.
any: Claude must call one of your tools.
tool: Claude must call a particular named tool.
none: no tools this turn.
Here's the catch for a 2026 reader. Anthropic's documentation says forced tool use (any and tool) is not supported on Claude Fable 5.2, Mythos 5.2, Opus 5.5, Sonnet 5.5 and a few others. It returns a 400 error. On those models you use auto, and if you need guaranteed valid inputs you combine it with strict tool use (lesson 4.3), or you use structured outputs when what you really want is a reply in a fixed JSON shape. So tutorials that say "just force the tool" are out of date for the newest models.
Two other facts worth knowing: when you do force a tool on a model that allows it, the model skips thinking and writes no text before the call; and changing tool_choice between requests invalidates cached message blocks (your tool definitions and system prompt stay cached).
What the loop costs
Every pass through the loop is a full request that resends the conversation so far, plus the tool definitions. A five-step task is five requests, each bigger than the last. That's another reason to cap iterations, keep results small (lesson 4.4), and not offer tools a request can't need.
The SDK helper
You don't have to write this loop yourself. The SDKs have a tool runner, currently in beta, that handles the loop, error wrapping and conversation state. In Python it's client.beta.messages.tool_runner(...) with tools defined by a @beta_tool decorator; in PHP you wrap each tool in a BetaRunnableTool. Anthropic's own advice is to use the manual loop when you need human-in-the-loop approval, custom logging or conditional execution, and all three of those come up in real applications, which is why this course builds the loop by hand.
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
A shop's assistant gets "Has my order shipped, and when will it arrive?" Turn one: Claude calls lookup_order. The result shows a tracking number. Turn two: Claude calls the carrier tool with that number. Turn three: it writes the answer. The loop ran three requests, and the developer wrote no special code for "look up the order, then the carrier". Claude worked out the sequence from the tool descriptions, and the loop just kept going while stop_reason was tool_use.
Mistakes to avoid
- Putting text before the
tool_result blocks.
- Putting each result in its own user message when Claude made several calls at once (it quietly teaches the model to stop making parallel calls).
- Forgetting the iteration cap.
- Dropping the assistant's text or thinking blocks when you rebuild the message list.
- Using
tool_choice: any or tool on a model that rejects it.
Security notes
Every tool_use is a request that came out of a model that read untrusted text. The loop is where you enforce limits: the iteration cap, an allow-list of tool names, and checks before anything runs. Anthropic also warns that tool results often carry content from outside your control (web pages, emails, API responses) and may contain instructions aimed at the model. Keep such content inside tool_result blocks, not in the system prompt or plain user text.
Key takeaways
tool_use blocks carry id, name and input; tool_result carries tool_use_id, optional content and optional is_error.
- Results must follow the call directly, come first in the message, and answer every call, in one user message.
- The loop continues while
stop_reason is tool_use and always needs an iteration cap.
- Forced tool use isn't available on the newest models; use
auto with strict tools or structured outputs.
Lesson recap: a call, a matching result, a capped loop, and results placed correctly.
Quick quiz
- Which stop reason tells you to run tools and continue?
- Where must
tool_result blocks sit inside the user message?
- What should you do if you choose not to run one of several tool calls?
- Why does every agent loop need a maximum number of iterations?
- Can you use
tool_choice: {"type": "tool"} on Claude Opus 5.5?
Answers and explanations
tool_use.
- Before any text content. Text may follow the results, but never come before them.
- Still return a
tool_result for it, with is_error: true and a short explanation, because every call needs an answer.
- A confused model or a malicious input can keep calling tools indefinitely, which costs money and never ends.
- No. Forced tool use returns a 400 error on that model. Use
auto, with strict tool use if you need schema-valid inputs.
Official references and further reading
Related tutorials