Skip to content

Lesson 20 ยท Tools and Structured Output

Agent Loops and Built-in Tools

Turn tool use into an agent loop with step limits, budgets and approvals, and learn how server tools, Anthropic-schema tools, MCP and agent products differ.

One tool round answers a simple question. Many tasks need several: search, read, calculate, then write. An agent loop repeats the round trip until Claude stops asking for tools. The idea is short. The safety limits around it are the real work. For general agent design, see AI agents.

The loop

Python
MAX_STEPS = 8

for step in range(MAX_STEPS):
    response = client.messages.create(
        model="claude-opus-5-5", max_tokens=4000,
        tools=tools, messages=messages,
    )
    messages.append({"role": "assistant", "content": response.content})

    if response.stop_reason == "pause_turn":
        continue          # send it back so that the server tool can go on
    if response.stop_reason != "tool_use":
        break             # finished, truncated or declined: inspect it

    results = [execute(b) for b in response.content if b.type == "tool_use"]
    messages.append({"role": "user", "content": results})
else:
    print("Stopped: step limit reached")

Here execute is your own function that returns a tool_result dictionary. After the loop, still check stop_reason: leaving the loop does not always mean success.

The Python SDK also offers a tool runner that manages this loop for you. Write the loop yourself when you need custom control, or learn it first so that you know what the helper does.

Limits every agent needs

  • Maximum steps, to stop endless loops.
  • A budget for tokens, money and time.
  • Repeat detection for the same failing call.
  • Approval before actions that send, buy, delete or change access.
  • Logs of what was called, with what result.
Python Stand-in: an agent loop with limits and approval

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.

In the first run, sending is denied, and the denial goes into the history as a result. With a real model you would return it as a tool_result, so that the model can adapt. In the second run, the budget stops the loop before anything is sent.

Tools that Anthropic provides

Not every tool is one you write.

Where do tools run?

Your tools Your code runs them
Anthropic schema Your code runs them
Server tools Anthropic runs them

Check model and platform support

1 / 2
  • Anthropic-schema client tools include the memory, bash, text editor, computer use and browser use tools. Anthropic defines their interface, but your application executes the actions, so you must sandbox them.
  • Server tools include web search, web fetch, code execution and tool search. They run on Anthropic's infrastructure.
  • The MCP connector lets API requests use remote MCP servers.

A server tool is declared by a versioned type string. These strings change as new versions are released, so copy the current one from the documentation. As an example from the documentation as of December 2026:

Python
response = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=4000,
    tools=[{"type": "web_search_20260209", "name": "web_search"}],
    messages=[{"role": "user", "content": "What changed in the latest Python release?"}],
)

Some server tools add usage charges on top of tokens. Web results are untrusted content, and the cited links still deserve checking.

Higher-level options

Besides the Messages API, Anthropic offers the Claude Agent SDK, a library for building agents on the capabilities behind Claude Code, and Claude Managed Agents, a hosted option. Check their documentation for current features. A simple rule: start with a single request; add tools when the task needs them; build an agent only when the number or order of steps cannot be fixed in advance.

Powerful tools need isolation

A tool that can run shell commands or control a screen can cause real damage. Run it in an isolated container or virtual machine, without personal accounts or unnecessary network access, and require approval for consequential steps. Never rely on the system prompt as the only barrier.

Detect a stuck agent

A step limit stops a runaway loop, but you can often stop earlier. Compare each tool call with the previous ones. If the same tool is called with the same input and returns the same error several times, nothing new will happen. Return a clear message, stop the run or ask a person. Also set a time limit, because a single slow tool can hold a loop for a long while even when the step count is small.

Manage a growing history

Each turn adds the assistant content and the tool results, so input grows quickly. Keep tool results short, and return a summary or a page of results with a way to ask for more. Do not delete or edit blocks carelessly in the middle of a tool exchange, because requests and results must stay matched. The API also offers features for managing long conversations; check the context management documentation for what is currently available.

Record what happened

For every run, store the task, the model, each tool call with its input, whether it was approved, the result, the final stop reason and the token usage. Be careful with personal data in these logs, and limit who can read them. When an agent does something surprising, the log is how you find out whether the cause was the prompt, a tool description, a tool result or a missing limit. Turn each real failure into a test case.

Test an agent safely

Before an agent touches real systems, run it against fake tools that return realistic data, including errors, empty results and hostile text. Check which calls it tried, not only what it wrote at the end. Count how often it finished the task, how many steps it needed and whether it ever attempted a forbidden action. Only then give it real tools, starting with read-only ones, and add write access one tool at a time. Run each scenario several times, because behavior can differ between runs.

Keep a simple way to switch the agent off, and make sure that more than one person on your team knows how to use it.

Common mistake: looping with while True until the model says it is finished. A confused model or a failing tool can then run up costs without limit. Always bound the loop.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does a basic agent loop normally stop?

    Stop on completion or other final reasons, and enforce your own limits.
  2. 2. Who executes the bash tool that has an Anthropic-defined schema?

    Anthropic defines the schema; your code runs the command.
  3. 3. What should a denied action produce?

    The model needs the truth to continue sensibly.
  4. 4. When is an agent worth building?

    Simpler designs are cheaper and easier to check.

Summary

  • An agent loop repeats requests and tool results until a final stop reason.
  • Add step, budget, approval and logging controls.
  • Server tools run at Anthropic; client tools run in your code.
  • Sandbox powerful tools and treat fetched content as untrusted.

Next: Checking Accuracy and Reducing Errors

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