Learning path: Build Your First LLM App with Claude · Step 3 of 4
Claude Tool Use: How tool_use and tool_result Work in the Messages API
Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.
What you will learn
- Define a tool with a name, description and input_schema
- Write a tool loop that runs each tool_use block and sends back a tool_result
- Report a failed tool call with is_error
- Explain the pairing rules the API enforces for tool_use and tool_result
Before you start
- The Claude Messages API: your first call
- Basic Python
A customer asks the support desk: Where is order A-1042? Claude writes well, but it can't see your orders. Your code can. A tool is how Claude asks your code to fetch the data.
The short version: Claude asks, your code acts. In this article we follow that one question through the whole round trip, in a small SupportDesk project, and then look at the rules the API enforces.
A slip goes out and comes back
Picture a restaurant that works with order slips.
- Claude writes a slip with a slip number, a name and the details. That's the
tool_useblock. - The kitchen cooks it. That's your code doing the work. Claude never sees the kitchen.
- The plate comes back with the same slip number, and Claude matches it to the slip. That's the
tool_result.
The slip number is what ties the answer to the question: the same id on the way out and on the way back.
Two requests, two responses
- Request 1 carries the
toolslist. Each tool has aname, adescriptionand aninput_schema. - Response 1 comes back with
stop_reason: "tool_use"and atool_useblock with anid, anameand aninput. - Request 2 sends that assistant turn back unchanged, plus a user message holding the
tool_resultwith the matchingtool_use_id. - Response 2 ends with
stop_reason: "end_turn"and the text answer.
tools.py: the tool Claude reads about
"""The tool Claude reads about, and the function our code runs for it."""
ORDERS = {
"A-1042": "order A-1042 shipped Monday.",
"B-2201": "order B-2201 ships Friday.",
}
TOOLS = [{
"name": "get_order_status",
"description": "Look up the current status of one SupportDesk order by its id.",
"input_schema": {
"type": "object",
"properties": {"order_id": {"type": "string", "description": "like A-1042"}},
"required": ["order_id"],
},
}]
def get_order_status(order_id):
return ORDERS[order_id]
nameis how Claude calls the tool.descriptiontells Claude when to use it. Claude picks tools by reading this, so write it clearly.input_schemais a JSON Schema for the input. Here it's one required string, the order id.get_order_statusis your own function. It does the real lookup. Claude only sees its result.
agent.py: the tool loop
The project runs against a stand-in (an httpx mock transport that answers like the Messages API), so it works with no API key. The loop itself is exactly what you'd write for the real API:
"""The tool loop: call Claude, run the tools it asks for, send the results back."""
from anthropic import Anthropic, DefaultHttpxClient
import stand_in
from tools import TOOLS, get_order_status
def make_client():
http = DefaultHttpxClient(transport=stand_in.mock_transport())
return Anthropic(api_key="test-key", http_client=http)
def run_one(block):
result = {"type": "tool_result", "tool_use_id": block.id}
try:
result["content"] = get_order_status(**block.input)
except KeyError:
result["content"] = "no order " + block.input["order_id"]
result["is_error"] = True
return result
def answer(client, question, log=print):
messages = [{"role": "user", "content": question}]
while True:
response = client.messages.create(
model=stand_in.MODEL, max_tokens=512, tools=TOOLS, messages=messages)
log(f"stop_reason: {response.stop_reason}")
if response.stop_reason != "tool_use":
return response.content[0].text
messages.append({"role": "assistant", "content": response.content})
results = []
for block in response.content:
if block.type == "tool_use":
log(f"tool_use {block.id}: {block.name} {dict(block.input)}")
results.append(run_one(block))
messages.append({"role": "user", "content": results})
log(f"sent {len(results)} tool_result")
- Every call sends the
toolsarray. - If the stop reason is not
tool_use, the answer is final and the loop returns it. - If it is
tool_use, Claude's turn is kept, unchanged, as anassistantmessage. - For each
tool_useblock, the code runs the tool and builds onetool_resultthat copies the block'sidintotool_use_id. - If the lookup fails,
is_erroris set toTrue, so Claude knows the tool failed. - All the results go back together in one
usermessage, and the loop calls Claude again.
Because the API keeps nothing between calls, the second request carries the whole thread: the question, Claude's tool_use turn, and the results. The Messages API first-call article explains why.
What the loop printed
run_all.py sends three questions: one tool call, two tool calls in one turn, and an order that doesn't exist.
"""Three questions through the tool loop: one tool, two tools at once, and a failing tool."""
import stand_in
from agent import answer, make_client
client = make_client()
for title, question in [("one tool call", "Where is order A-1042?"),
("two tool calls in one turn", "Compare orders A-1042 and B-2201."),
("a tool that fails", "Where is order C-9999?")]:
print(title)
print("reply:", answer(client, question))
print("requests:", len(stand_in.WIRE), "| tools sent each time:", ", ".join(stand_in.WIRE[0]["tools"]))
print("last request roles:", ", ".join(stand_in.WIRE[-1]["roles"]))
one tool call
stop_reason: tool_use
tool_use toolu_test01: get_order_status {'order_id': 'A-1042'}
sent 1 tool_result
stop_reason: end_turn
reply: test model reply: order A-1042 shipped Monday.
two tool calls in one turn
stop_reason: tool_use
tool_use toolu_test01: get_order_status {'order_id': 'A-1042'}
tool_use toolu_test02: get_order_status {'order_id': 'B-2201'}
sent 2 tool_result
stop_reason: end_turn
reply: test model reply: order A-1042 shipped Monday. order B-2201 ships Friday.
a tool that fails
stop_reason: tool_use
tool_use toolu_test01: get_order_status {'order_id': 'C-9999'}
sent 1 tool_result
stop_reason: end_turn
reply: test model reply: sorry, I could not find that order.
requests: 6 | tools sent each time: get_order_status
last request roles: user, assistant, user
The reply text and ids come from the stand-in and are made up for the demo. What to notice:
- Each question took two calls, so three questions made six requests.
- The second question got two
tool_useblocks in one turn. Both results went back together, in one user message. - For
C-9999the lookup failed, the code sentis_error, and the reply says the order couldn't be found. - The last request held three messages:
user,assistant,user.
The rules: every tool_use gets its answer
- The user message holds the results, never an assistant message.
- Every
tool_usegets exactly onetool_result, even when the tool failed. tool_use_idcopies the block'sid. That's how Claude matches each result to its request.- The results come first in the very next user message. Any text goes after them.
Put text before a result and the API rejects the request with a 400 error. Break the pairing and the request fails too. Here's the user message the loop sent for the two-order question:
{
"role": "user",
"content": [
{"type": "tool_result", "tool_use_id": "toolu_test01", "content": "order A-1042 shipped Monday."},
{"type": "tool_result", "tool_use_id": "toolu_test02", "content": "order B-2201 ships Friday."}
]
}
The same tool in TypeScript
In @anthropic-ai/sdk the tool is typed as Anthropic.Tool. Same schema, same tools field, same blocks back:
import Anthropic from "@anthropic-ai/sdk";
import { MODEL, standInFetch } from "./stand_in.ts";
const tools: Anthropic.Tool[] = [{
name: "get_order_status",
description: "Look up the current status of one SupportDesk order by its id.",
input_schema: {
type: "object",
properties: { order_id: { type: "string", description: "like A-1042" } },
required: ["order_id"],
},
}];
const client = new Anthropic({ apiKey: "test-key", fetch: standInFetch });
const response = await client.messages.create({
model: MODEL,
max_tokens: 512,
tools,
messages: [{ role: "user", content: "Where is order A-1042?" }],
});
console.log("stop_reason:", response.stop_reason);
for (const block of response.content) {
if (block.type === "tool_use") {
console.log("tool_use", block.id, block.name, block.input);
}
}
stop_reason: tool_use
tool_use toolu_test01 get_order_status { order_id: 'A-1042' }
Common mistakes (and the exam's wrong answers)
A typical certification scenario asks how a tool result gets back to Claude. The tempting wrong answers:
| Wrong answer | Why it's wrong |
|---|---|
| Claude runs the function itself | Not for your own tools. Your code runs it. |
| Send the result back as plain text | It needs a tool_result block with the tool_use_id. |
| Put the result in an assistant message | Results go in a user message. |
| Skip the result when the tool fails | Every tool_use needs a result; send is_error instead. |
The right answer: a user message with a tool_result and the matching tool_use_id.
Quick recap
| Piece | Where it lives | Key fields |
|---|---|---|
| Tool definition | tools in every request | name, description, input_schema |
tool_use | Claude's response, stop_reason: tool_use | id, name, input |
tool_result | The next user message, results first | tool_use_id, content |
is_error | On the tool_result | true when the tool failed |
Try it yourself
Add a third order, C-3300, to ORDERS and ask "Compare orders A-1042, B-2201 and C-3300." How many tool_use blocks come back, and how many tool_result blocks does the loop send?
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →The Claude Messages API: Your First Call, Field by Field
Next →The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Claude Certified Developer - Foundations (CCDV-F) Exam Prep
Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (opens in a new tab)