Claude Tool Use in Python: Schemas and the Tool-Use Loop

📚 Exam guide v1.1 (exams from 7 Dec 2026)🔄 Checked against official sources: 24 Nov 2026⏱️ 10 min read🎯 D8 Tool Design and Response Shaping · D2 Messages API Mechanics

👋 In plain words: Tools let Claude ask your code to do things it cannot do alone: look up an order, run a test, query a database. Claude never runs the tool itself; it asks, your code runs it and sends back the result. This lesson builds that request-run-reply loop one step at a time.

Advertisement

Tool use (often called function calling) turns Claude from a text generator into something that can act on your systems. In this lesson you will define a tool with a JSON schema, see Claude request it, run it in Python, return the result correctly, loop until Claude is done, handle several tool calls at once and tool failures, and then let the SDK’s Tool Runner drive the loop for you.

📖 What You’ll Learn: You will be able to define Claude tools, implement the tool-use loop with correct tool_result messages, handle parallel calls and tool errors, use tool_choice, and use the Tool Runner.

🔑 Key terms

  • Tool: a function you describe to Claude with a name, a description and an input schema.
  • tool_use block: Claude’s request to call a tool, with an id, the tool name and its input.
  • tool_result block: your reply with the tool’s output, linked by tool_use_id.
  • Tool-use loop: call Claude → run requested tools → send results → repeat until stop_reason is not tool_use.

🪜 The steps at a glance

  1. Write the Python function.
  2. Describe it as a tool.
  3. Send a request and read the tool_use block.
  4. Run the tool and return a tool_result.
  5. Loop until Claude finishes.
  6. Handle parallel calls and errors.
  7. Let the Tool Runner drive the loop.

🪜 Step 1: Write the function

Start with ordinary Python. This one looks up the latest CI result for a test (from a dictionary here; in real life, from your CI API):

📄 ci_tools.py

CI_RESULTS = {
    "test_checkout_total": {"status": "failed", "error": "AssertionError: expected 90.00 got 100.00", "build": 812},
    "test_login": {"status": "passed", "build": 812},
}


def get_test_result(test_name: str) -> dict:
    if test_name not in CI_RESULTS:
        raise KeyError(f"unknown test: {test_name}")
    return CI_RESULTS[test_name]

🪜 Step 2: Describe it as a tool

Claude only sees the name, description and input schema. Write the description for Claude: what the tool does, when to use it and what the input means:

📄 tool_defs.py

TOOLS = [{
    "name": "get_test_result",
    "description": ("Get the latest CI result for one automated test. Use this whenever the user asks whether "
                    "a test passed or why it failed. Returns status, error message and build number."),
    "input_schema": {
        "type": "object",
        "properties": {
            "test_name": {"type": "string", "description": "Exact pytest function name, e.g. test_checkout_total"},
        },
        "required": ["test_name"],
    },
}]

🪜 Step 3: Send a request and read the tool_use block

📄 first_call.py

import anthropic

from tool_defs import TOOLS

client = anthropic.Anthropic()

r = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=2000,
    tools=TOOLS,
    messages=[{"role": "user", "content": "Why did test_checkout_total fail last night?"}],
)
print("stop_reason:", r.stop_reason)
for b in r.content:
    if b.type == "tool_use":
        print("tool_use:", b.name, b.input, "id =", b.id)
    elif b.type == "text":
        print("text:", b.text)

⌨️ Terminal

python first_call.py

🖥️ Output (sample run)

stop_reason: tool_use
text: Let me look up the latest CI result.
tool_use: get_test_result {'test_name': 'test_checkout_total'} id = toolu_01zz9Tx1c5uRBaJ8BMZSMJky

stop_reason is tool_use: Claude is waiting for you. The reply can also contain text before the tool call. Claude has not run anything; it only asked.

Advertisement

🪜 Step 4: Run the tool and return a tool_result

Append Claude’s whole reply as the assistant turn, then send one user message containing a tool_result for each tool_use, matched by tool_use_id:

📄 one_round.py

import json

import anthropic

from ci_tools import get_test_result
from tool_defs import TOOLS

client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Why did test_checkout_total fail last night?"}]

r = client.messages.create(model="claude-opus-5-5", max_tokens=2000, tools=TOOLS, messages=messages)
messages.append({"role": "assistant", "content": r.content})

results = []
for b in r.content:
    if b.type == "tool_use":
        output = get_test_result(**b.input)
        results.append({"type": "tool_result", "tool_use_id": b.id, "content": json.dumps(output)})
messages.append({"role": "user", "content": results})

final = client.messages.create(model="claude-opus-5-5", max_tokens=2000, tools=TOOLS, messages=messages)
print(final.stop_reason, "->", final.content[0].text)

⌨️ Terminal

python one_round.py

🖥️ Output (sample run)

end_turn -> test_checkout_total failed in build 812: the order total was 100.00 instead of 90.00, so the 10% discount was not applied.
⚠️ Watch out: Three classic mistakes: (1) sending each tool_result in its own user message; (2) dropping the assistant turn that contains the tool_use; (3) sending a different tool_use_id. Each one either errors or confuses the model. All results for one turn go back together, in one user message.
Advertisement

🪜 Step 5: Loop until Claude finishes

Real tasks need several rounds. Loop on stop_reason, with a safety cap on iterations:

📄 loop.py

import json

import anthropic

from ci_tools import get_test_result
from tool_defs import TOOLS

client = anthropic.Anthropic()
REGISTRY = {"get_test_result": get_test_result}


def run_with_tools(question: str, max_rounds: int = 8) -> str:
    messages = [{"role": "user", "content": question}]
    for round_no in range(1, max_rounds + 1):
        r = client.messages.create(model="claude-opus-5-5", max_tokens=2000, tools=TOOLS, messages=messages)
        messages.append({"role": "assistant", "content": r.content})
        if r.stop_reason != "tool_use":
            return f"(after {round_no} calls) " + "".join(b.text for b in r.content if b.type == "text")
        results = []
        for b in r.content:
            if b.type == "tool_use":
                try:
                    output = json.dumps(REGISTRY[b.name](**b.input))
                    results.append({"type": "tool_result", "tool_use_id": b.id, "content": output})
                except Exception as e:  # report failures to Claude instead of crashing
                    results.append({"type": "tool_result", "tool_use_id": b.id, "content": str(e), "is_error": True})
        messages.append({"role": "user", "content": results})
    return "stopped: too many tool rounds"


print(run_with_tools("Did test_login and test_checkout_total pass?"))

⌨️ Terminal

python loop.py

🖥️ Output (sample run)

(after 2 calls) test_login passed in build 812, but test_checkout_total failed with AssertionError: expected 90.00 got 100.00.
  • Claude asked for two tools in one turn (parallel tool use). The loop runs both and returns both results in a single message.
  • A tool that raises becomes a tool_result with "is_error": True. Claude reads the error and can recover (try another name, ask the user) instead of the app crashing.
  • The iteration cap is a safety backstop, not the stop condition. The stop condition is stop_reason.

🪜 Step 6: Control tool use with tool_choice

tool_choice Meaning
{"type": "auto"} (default) Claude decides whether to call a tool
{"type": "none"} Claude must not call tools in this turn
{"type": "any"} / {"type": "tool", "name": ...} Force a tool call. Rejected with a 400 on Claude Opus 5.5, Sonnet 5.5, Fable 5.1/5.2.

On current models, steer with the prompt (“Always look up the result with get_test_result before answering”) and use auto. If you were forcing a tool only to get JSON, use structured outputs instead (Lesson 22). Add "disable_parallel_tool_use": True to tool_choice if your tools must run one at a time.

🪜 Step 7: Let the Tool Runner drive the loop

The SDK’s Tool Runner (beta) builds the schema from a decorated function and runs the loop for you:

📄 runner.py

import anthropic
from anthropic import beta_tool

from ci_tools import get_test_result as lookup

client = anthropic.Anthropic()


@beta_tool
def get_test_result(test_name: str) -> str:
    """Get the latest CI result for one automated test.

    Args:
        test_name: Exact pytest function name, e.g. test_checkout_total.
    """
    return str(lookup(test_name))


runner = client.beta.messages.tool_runner(
    model="claude-opus-5-5",
    max_tokens=2000,
    tools=[get_test_result],
    messages=[{"role": "user", "content": "Why did test_checkout_total fail last night?"}],
)
final = runner.until_done()
print(final.stop_reason, "->", final.content[-1].text)

⌨️ Terminal

python runner.py

🖥️ Output (sample run)

end_turn -> test_checkout_total failed in build 812: the order total was 100.00 instead of 90.00, so the 10% discount was not applied.
  • The docstring becomes the description, and the Args: section describes each parameter.
  • In anthropic 2.13 the Tool Runner uses message threads (a beta feature) by default: the first request creates a thread, and later requests send only the new messages plus a previous_message_id, while the API keeps the earlier turns. This makes long tool loops lighter. Anthropic describes threads as best-effort, so keep your own log of the turns if you need a full trace or a replay.
  • Use the manual loop when you need full control (approvals before risky tools, custom logging, special pause_turn handling); use the Tool Runner for the rest.
🎯 Exam focus: Tool-loop defects are a favourite: stopping on “the reply contains text” instead of stop_reason, splitting results across messages, losing the assistant turn, crashing on tool errors instead of returning is_error, and forcing tool_choice on models that reject it.

🌍 Real-world example: Ravi’s CI assistant

Ravi’s first CI bot stopped whenever Claude wrote “Let me check that”, because his loop ended on any text. Users saw only that sentence. Switching the condition to stop_reason != "tool_use" fixed it, and returning is_error for unknown test names let Claude ask “Did you mean test_checkout_totals?” instead of crashing.

Advertisement

🧪 Practice Questions

Question 1. Claude replies with text “Checking now.” plus a tool_use block, and the app shows “Checking now.” to the user and stops. What is the loop defect?

  • A. max_tokens is too low
  • B. The loop ends when it sees text instead of continuing while stop_reason is tool_use
  • C. The tool schema is wrong
  • D. Parallel tool use is enabled
Show answer

Answer: B. Claude can write text and request a tool in the same turn. stop_reason, not the presence of text, decides whether more work is pending.

Question 2. Claude requests three tools in one turn. How should the results be returned?

  • A. Three separate user messages, one per result
  • B. One user message with three tool_result blocks, each with the matching tool_use_id
  • C. One tool_result containing all three outputs joined together
  • D. Only the first result; Claude will ask again
Show answer

Answer: B. All results for a turn go back together in a single user message, each linked to its tool_use_id.

Question 3. A tool raises an exception because the requested record does not exist. What should the loop do?

  • A. Return a tool_result with is_error: true and the error message, so Claude can recover
  • B. Crash and show a stack trace
  • C. Drop the tool_use and continue
  • D. Retry the same call 5 times
Show answer

Answer: A. Reporting the error lets Claude choose a recovery, such as asking for a correct identifier.

Question 4. Code sends tool_choice={“type”: “any”} to Claude Opus 5.5 and receives a 400. Which two alternatives are correct? (Choose 2.)

  • A. Use tool_choice auto and instruct the tool use in the prompt
  • B. Use tool_choice “required”
  • C. Use structured outputs if the forced call only existed to get JSON
  • D. Downgrade the SDK
Show answer

Answer: A and C. Forced tool choice is not supported on Opus 5.5. Steer with the prompt, or use structured outputs for JSON.

📝 Assignment

  1. Task 1: Add a second tool, get_flaky_history(test_name, days), that returns how many times a test failed recently, and ask “Is test_login flaky?”.
    ✅ Done when: the loop calls your new tool and answers from its result.
  2. Task 2: Write pytest tests for run_with_tools using unittest.mock to return a scripted tool_use reply and then a text reply.
    ✅ Done when: the test checks that the tool was called once with the right input.
  3. Stretch: Add an approval step: before running any tool whose name starts with create_ or delete_, ask the user y/n in the terminal and return an is_error result “rejected by user” on n.
    ✅ Done when: rejecting a call makes Claude explain that the action was not performed.
Advertisement

❓ Frequently Asked Questions

🤔 What is tool use in Claude?

A way for Claude to request actions from your code. You describe tools with JSON schemas; Claude returns tool_use blocks; your code runs them and returns tool_result blocks.

🤔 Does Claude execute my tools?

No. Client tools always run in your code. Claude only decides which tool to call and with which input. (Anthropic-hosted server tools, such as web search, run on Anthropic’s side; see Lesson 25.)

🤔 How do I return a tool error to Claude?

Send a tool_result with "is_error": true and a clear message. Claude can then retry differently or explain the problem.

🤔 What is the difference between the Tool Runner and the Agent SDK?

The Tool Runner (in the anthropic SDK) loops over tools you define. The Agent SDK is Claude Code’s full harness with built-in file, shell and web tools.

🏁 Summary

  • Describe tools with a name, a description written for Claude and an input schema.
  • Loop while stop_reason == "tool_use"; append the full assistant reply every time.
  • Return all tool_result blocks for a turn in one user message, matched by tool_use_id.
  • Report tool failures with is_error: true; cap iterations as a backstop only.
  • Use auto tool choice on current models, and the Tool Runner when you do not need custom control.
📝 Test yourself: D8 Tools and MCP practice test (20 random questions, 20 minutes), or browse all CCDV-F mock tests (3 full 70-question exams and 8 domain practice tests, with explanations).

Next, continue with Claude Tool Design: Descriptions, Response Shaping and Errors.

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.