Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Learning pathBuild Your First LLM App with Claude
  1. 1
    LLM Tokens, Context Windows and Cost: What One Question Really Costs
  2. 2
    The Claude Messages API: Your First Call, Field by Field
  3. 3
    Claude Tool Use: How tool_use and tool_result Work in the Messages API
  4. 4
    The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  1. Blog
  2. /
  3. Claude
  4. /
  5. Building with the Claude API

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.

Chaand Sheikh

·27 November 2026Building with the Claude API

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.

  1. Claude writes a slip with a slip number, a name and the details. That's the tool_use block.
  2. The kitchen cooks it. That's your code doing the work. Claude never sees the kitchen.
  3. 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

The tool_use and tool_result round trip Your code Claude 1. request: tools + "Where is order A-1042?" 2. response: stop_reason tool_use tool_use id toolu_test01, get_order_status runs the lookup 3. request: assistant turn + user tool_result tool_use_id toolu_test01 (same id) 4. response: stop_reason end_turn + the text answer
One tool_use out, one tool_result back, then the answer.
  • Request 1 carries the tools list. Each tool has a name, a description and an input_schema.
  • Response 1 comes back with stop_reason: "tool_use" and a tool_use block with an id, a name and an input.
  • Request 2 sends that assistant turn back unchanged, plus a user message holding the tool_result with the matching tool_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]
  • name is how Claude calls the tool.
  • description tells Claude when to use it. Claude picks tools by reading this, so write it clearly.
  • input_schema is a JSON Schema for the input. Here it's one required string, the order id.
  • get_order_status is 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")
  1. Every call sends the tools array.
  2. If the stop reason is not tool_use, the answer is final and the loop returns it.
  3. If it is tool_use, Claude's turn is kept, unchanged, as an assistant message.
  4. For each tool_use block, the code runs the tool and builds one tool_result that copies the block's id into tool_use_id.
  5. If the lookup fails, is_error is set to True, so Claude knows the tool failed.
  6. All the results go back together in one user message, 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_use blocks in one turn. Both results went back together, in one user message.
  • For C-9999 the lookup failed, the code sent is_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_use gets exactly one tool_result, even when the tool failed.
  • tool_use_id copies the block's id. 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 answerWhy it's wrong
Claude runs the function itselfNot for your own tools. Your code runs it.
Send the result back as plain textIt needs a tool_result block with the tool_use_id.
Put the result in an assistant messageResults go in a user message.
Skip the result when the tool failsEvery 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

PieceWhere it livesKey fields
Tool definitiontools in every requestname, description, input_schema
tool_useClaude's response, stop_reason: tool_useid, name, input
tool_resultThe next user message, results firsttool_use_id, content
is_errorOn the tool_resulttrue 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 →
← Previous
The Claude Messages API: Your First Call, Field by Field
Next →
The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool
Go deeper with a course

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)

Related articles
The Claude Messages API: Your First Call, Field by Field

One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.

On this page
  • A slip goes out and comes back
  • Two requests, two responses
  • tools.py: the tool Claude reads about
  • agent.py: the tool loop
  • What the loop printed
  • The rules: every tool_use gets its answer
  • The same tool in TypeScript
  • Common mistakes (and the exam's wrong answers)
  • Quick recap
  • Try it yourself
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool
Go deeper with a course

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.