Skip to content

Lesson 19 ยท Tools and Structured Output

Tool Use with the Claude API

Let Claude call your functions: define tools, handle tool_use blocks, return tool_result blocks in the right order, report errors and validate every input.

Claude cannot see your database or send an email by itself. With tool use (also called function calling), you describe functions, Claude asks to call them, your code runs them, and you return the results. For a provider-neutral introduction, see what are tools?.

The round trip

sequenceDiagram
  participant A as Your app
  participant C as Claude
  A->>C: question + tool definitions
  C-->>A: tool_use block
  A->>A: validate and run
  A->>C: tool_result block
  C-->>A: final text

Claude requests; your application decides and executes.

Define a tool

A tool has a name, a description and an input_schema in JSON Schema form. The description should say what the tool does, when to use it, what it returns and what its limits are.

Python
tools = [{
    "name": "get_order_status",
    "description": (
        "Look up the status of one order for the signed-in customer. "
        "Use when the customer asks where an order is. "
        "Returns the status and expected delivery date."
    ),
    "input_schema": {
        "type": "object",
        "properties": {
            "order_id": {"type": "string", "description": "Like ORD-1234"}
        },
        "required": ["order_id"],
        "additionalProperties": False,
    },
    "strict": True,
}]

strict: true asks the API to make tool inputs match the schema. The schema still cannot know whether this customer may see that order.

Handle the call

When Claude wants one of your tools, stop_reason is "tool_use" and the content has one or more tool_use blocks, each with an id, a name and an input.

Python
messages = [{"role": "user", "content": "Where is order ORD-1001?"}]
response = client.messages.create(
    model="claude-opus-5-5", max_tokens=2000, tools=tools, messages=messages
)

if response.stop_reason == "tool_use":
    results = []
    for block in response.content:
        if block.type == "tool_use":
            output, failed = run_tool(block.name, block.input)  # your code
            results.append({
                "type": "tool_result",
                "tool_use_id": block.id,
                "content": output,
                "is_error": failed,
            })
    messages.append({"role": "assistant", "content": response.content})
    messages.append({"role": "user", "content": results})
    response = client.messages.create(
        model="claude-opus-5-5", max_tokens=2000, tools=tools, messages=messages
    )

Formatting rules from the documentation:

  • Send the assistant content back unchanged.
  • Put the results in the next user message, with nothing in between.
  • Give one result for every tool_use block, even failed ones.
  • Several results go in one user message, and result blocks come before any text.
  • Send the same tools again.

This example shows a single round. The follow-up may ask for another tool, which you handle in a loop in the next lesson.

Report errors usefully

When a tool fails, return a result with is_error: true and a message that helps: "No order with ID ORD-9. IDs look like ORD-1234." Claude may correct itself or explain the problem to the user. Do not return stack traces, secrets or internal details.

Control tool choice

By default, tool_choice is auto: Claude decides. According to Anthropic's API reference as of December 2026, forcing a tool (any or a named tool) is rejected on Fable 5.2, Opus 5.5 and Sonnet 5.5, among others. Guide behavior with clear descriptions and instructions instead. If you only need data in a fixed shape, use structured outputs. You can set disable_parallel_tool_use inside tool_choice to ask for at most one call per turn.

Treat inputs as untrusted

A tool request is a suggestion from a model that may have read hostile text. Your code must check:

  1. Is the tool name on your list?
  2. Are the arguments valid?
  3. Is this user allowed to do it? Take identity from your session, never from model input.
  4. Does the action need human confirmation?
Python Stand-in: a guarded tool dispatcher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Call t2 fails even though the order exists, because it belongs to another customer. Call t4 cannot change the user: the extra argument is rejected. The identity comes from session_user, which the model does not control.

Design tools that are easy to use well

Good tool design prevents many problems before they start.

  • Choose clear names. search_invoices and get_invoice say more than invoices and invoice2.
  • Describe the difference between similar tools, including when not to use each one.
  • Ask for few arguments. If your program already knows a value, such as the user ID, do not make the model supply it.
  • Use enums for fixed choices instead of free text.
  • Return compact results. Send the fields that matter, not an entire database row. Large results use context and cost tokens, and they may expose data that the user should not see.
  • Say when results are partial, for example "showing 20 of 340 matches".

Plan for repeated calls

A model may call the same tool twice, and a network failure may make your program try again. Reading twice is usually harmless. Paying, sending or creating twice is not. For such actions, create an identifier in your own code, store it, and refuse to perform the same operation again. For the riskiest actions, split the work into two tools: one that prepares a draft and returns it for review, and one that your application runs only after a person has confirmed it.

Test tools without a model first. Your functions are ordinary code, so call them with wrong types, empty strings, huge values and other users' IDs, and confirm that each fails safely.

When Claude does not call your tool

If Claude answers from memory when it should look something up, improve the tool description: say clearly which questions need the tool. A short instruction in the system prompt, such as "check order status with the tool before you answer questions about orders", can help too. If it calls a tool when it should not, state when the tool does not apply. Test both directions with a list of questions and the tool call you expect for each, including questions where no call is the right behavior. Then you can change a description and see what moved.

Keep that list with your code, and run it again whenever you edit a tool name, a description, the system prompt or the model that your application uses.

Common mistake: a tool such as run_sql(query) with write access. One manipulated request can then do almost anything. Offer narrow functions with least privilege, and require confirmation for actions that are hard to undo.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Who runs a client tool?

    Claude only requests the call.
  2. 2. A response contains three tool_use blocks. What do you send next?

    Every call needs a result, together in the next user message.
  3. 3. How should a failed tool be reported?

    A clear error lets the model recover without leaking internals.
  4. 4. Where should the current user's identity come from?

    Model input must not decide who is asking.

Summary

  • Tools have a name, a description and an input schema.
  • Return every result with its matching ID in the next user message.
  • Report failures with is_error and useful text.
  • Validate inputs, enforce permissions and confirm risky actions.

Next: Agent Loops and Built-in Tools

Your progress is saved in this browser. No account needed.