19 Tool Use in LLMs
19.6.1 Intuition: the schema is the only documentation Claude gets |
19.11 Core Concept 8: Streaming and Fine-Grained Tool Calling |
19.1 Learning Objectives
By the end of this lecture you should be able to:
Explain why a language model needs tools, and describe the four-step tool-use protocol between your application and Claude, including who runs the code at each step.
Write a tool function that validates its inputs and raises errors Claude can learn from, and describe it with a JSON Schema (name, description, input_schema).
Read a multi-block assistant message, pull out its tool_use blocks, execute them, and return matching tool_result blocks, including error results.
Implement the conversation loop that keeps calling Claude until stop_reason is no longer "tool_use", and trace the message history it produces.
Add a new tool to an existing agent in four mechanical steps, and explain how Claude chains several tools to answer one question.
Stream tool calls, explain why tool arguments arrive in bursts, and decide when to turn on fine-grained (eager) input streaming and what validation that leaves to you.
Distinguish client-executed tools (your functions, the built-in text editor) from server-executed tools (web search), and use both safely.
19.2 Motivation and Intuition
19.2.1 The model hits a wall
Ask Claude, with no tools, “What’s the weather in College Park, Maryland?” The best it can honestly say is:
I'm sorry, but I don't have access to up-to-date weather information. |
That answer is correct and useless. A language model is a closed-book exam taker: it knows what was in its training data, and nothing that happened afterwards. It cannot look at a clock, query your database, read a file on your disk, or send an email. Everything it “does” is produce text.
Tool use is the trick that turns “produce text” into “get things
done.” We let the model produce a very particular kind of text—
19.2.2 An analogy: the manager and the assistant
Picture a capable manager who is locked in an office with no phone and no computer, but who can pass notes under the door. Outside sits an assistant with a phone, a calendar, and a filing cabinet.
The manager (Claude) reads the customer’s question and decides what information is missing.
The manager writes a note: “Call the weather service, ask for College Park.” That note is a tool-use request.
The assistant (your application) makes the call and slides the answer back under the door. That is a tool result.
The manager writes the final reply to the customer using the fresh information.
Two consequences fall straight out of the analogy. First, the
manager can only ask for things the assistant has said it can do, so
you must describe your tools. Second, the assistant decides
whether to actually carry out a request—
19.2.3 Where tool use shows up
Tool use is the foundation of almost every “AI that does things”:
Fresh data: weather, stock prices, the current time, search results.
Your systems: look up an order, query a Postgres table, call your own REST API.
Actions: set a reminder, file a ticket, send a message, edit a file.
Reliable computation: date arithmetic, unit conversion, exact math—
things a model does unreliably in its head. Coding agents: Claude Code is, at its core, a loop that calls tools such as “read file,” “edit file,” and “run command.”
19.2.4 Connection to earlier material
AI APIs lecture: the Messages API is stateless—
you resend the whole conversation on every call. Tool use keeps that rule and adds new kinds of content blocks to the conversation. Every habit from that lecture (keys in .env, checking stop_reason, retries) still applies. REST lecture: a tool is, very often, a thin wrapper around an HTTP call to some service. Tool use is how an LLM becomes a client of your REST API.
Prompting lecture: a tool description is a prompt. The quality of your descriptions decides whether Claude calls the right tool with the right arguments.
Coming next—
MCP and agents: MCP is a standard way to package tools so any client can use them; an agent is the conversation loop in this lecture, given more tools and more autonomy.
19.3 Running Example: TerpRemind
Throughout the lecture we build TerpRemind, a reminder assistant. The goal is to type
Set a reminder for my doctor's appointment. It's a week from Thursday. |
and have Claude reply “OK, I will remind you”—
Gap | Why it matters | Tool that closes it |
Limited time awareness | Claude may know today's date roughly, but not the exact time | get_current_datetime |
Unreliable date arithmetic | "177 days after Jan 1" is easy to get wrong by a day | add_duration_to_datetime |
No way to act | Claude has no built-in mechanism to schedule anything | set_reminder |
We add the tools one at a time, starting with the simplest, so each new concept arrives with exactly one new piece of code. The lesson behind the project is a general principle: when the model has a limitation, extend it with a tool rather than trying to prompt your way around it.
Later sections use two smaller examples: a save_article tool (for streaming) and a sandboxed workspace/ folder (for the built-in text editor tool). All code in these notes comes from, or is a cleaned-up version of, the “Tool use with Claude” section of the Anthropic course Building with the Claude API. The complete, tested project is described in GitHub-Ready Project: claude-tool-use.
19.4 Core Concept 1: The Tool-Use Protocol
Tool use (also called function calling) is a protocol in which (1) the application tells the model which functions exist and what arguments they take, (2) the model may respond with a structured request to call one or more of them, (3) the application executes the requested functions, and (4) the application returns the results to the model, which continues its response.
In plain English: Claude fills in a form saying which function to call with which arguments; you run it; you tell Claude what happened.
19.4.1 The four steps
Your server Claude |
─────────── ────── |
1. user question + tool descriptions ───────────────▶ |
decides it needs data |
2. ◀─────────────── "call get_weather( |
location='College Park, MD')" |
3. run get_weather(...) → call a weather API |
(Claude is idle; YOUR code runs) |
4. original question + request + result ────────────▶ |
writes the final answer |
◀─────────────── "It's 64°F and foggy in |
College Park." |
Initial request. You send the question and instructions describing the tools that could fetch extra data.
Tool request. Claude decides it needs more information and replies with a request naming the tool and its arguments.
Data retrieval. Your server runs code—
calls an API, queries a database— to get the data. Final response. You send the data back. Claude combines it with the original question and answers.
19.4.2 Common misconceptions
“Claude runs my function.” It never does. Claude emits JSON describing a call. Your process executes it. (The exception is server tools such as web search, which run on Anthropic’s machines—
see Core Concept 10: Built-in Tools II— Web Search.) “Claude remembers the tool result.” The API is stateless. Step 4 resends the question, Claude’s request, and the result. Drop any of the three and Claude is confused.
“If I describe a tool, Claude will always use it.” Claude decides. For “What is 2 + 2?” it will usually just answer. Good descriptions say when to use the tool.
19.4.3 Practical implications
Because your code sits between the request and the action, you own correctness and safety: you validate arguments, enforce permissions, rate-limit expensive calls, and can refuse a request. Treat every tool argument as untrusted input, exactly as you would a field in an HTTP request body.
19.5 Core Concept 2: Tool Functions
A tool function is a plain Python function that your application runs when Claude requests it. Nothing about it is AI-specific: it takes keyword arguments and returns a value (or raises an exception).
19.5.1 Best practices
Use descriptive names for the function and every parameter: get_current_datetime(date_format), not gt(f). Claude reads these names.
Validate inputs and raise when they are empty or invalid.
Raise meaningful error messages. Claude sees the error text. “Location cannot be empty” gives it enough to retry with a proper value; a bare KeyError does not.
19.5.2 Worked example: our first tool
TerpRemind’s first gap is “Claude doesn’t know the exact time.”
from datetime import datetime
def get_current_datetime(date_format="%Y-%m-%d %H:%M:%S"):
if not date_format:
raise ValueError("date_format cannot be empty")
return datetime.now().strftime(date_format)The function formats the current time with Python’s strftime codes. The parameter lets Claude ask for exactly the format it needs:
get_current_datetime() # '2026-11-01 14:30:25' (default format)
get_current_datetime("%H:%M") # '14:30'
get_current_datetime("%S") # '25'
get_current_datetime("") # ValueError: date_format cannot be emptyThe empty-string check will rarely fire, but it demonstrates the pattern: validate, and fail with a sentence Claude can act on.
19.5.3 The other two TerpRemind tools
The remaining two tools are provided ready-made.
set_reminder is a stand-in for a real notification service—
def set_reminder(content, timestamp):
print(f"----\nSetting the following reminder for {timestamp}:\n{content}\n----")add_duration_to_datetime parses a date string, adds a duration in a chosen unit, and returns a verbose string such as "Monday, June 27, 2050 12:00:00 AM". Here is the abbreviated version:
from datetime import datetime, timedelta
def add_duration_to_datetime(
datetime_str, duration=0, unit="days", input_format="%Y-%m-%d"
):
date = datetime.strptime(datetime_str, input_format)
if unit == "seconds":
new_date = date + timedelta(seconds=duration)
elif unit == "minutes":
new_date = date + timedelta(minutes=duration)
elif unit == "hours":
new_date = date + timedelta(hours=duration)
elif unit == "days":
new_date = date + timedelta(days=duration)
elif unit == "weeks":
new_date = date + timedelta(weeks=duration)
elif unit == "months":
month = date.month + duration
year = date.year + month // 12
month = month % 12
if month == 0:
month = 12
year -= 1
day = min(date.day, [31, 29 if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) else 28,
31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1])
new_date = date.replace(year=year, month=month, day=day)
elif unit == "years":
new_date = date.replace(year=date.year + duration)
else:
raise ValueError(f"Unsupported time unit: {unit}")
return new_date.strftime("%A, %B %d, %Y %I:%M:%S %p")Note the output format: it includes the day of the week. That is deliberate. “A week from Thursday” requires knowing what day today is; a tool result that names the weekday gives Claude that fact for free.
19.5.4 Common misconceptions
“Tool functions should catch their own errors and return a friendly string.” Raise instead. The loop we write later turns exceptions into error results with is_error: True, which tells Claude unambiguously that the call failed.
“The model will only send valid arguments.” Usually, not always. The "years" branch, for instance, crashes on Feb 29 + 1 year (Feb 29, 2025 does not exist), and a fractional duration in months crashes on list indexing. Validation is your job; see Exercise I2.
19.6 Core Concept 3: Tool Schemas
A tool schema (tool definition) is a JSON object that tells Claude a tool exists. It has three parts:
Field | Purpose |
name | the identifier Claude will put in its request; match your function name |
description | what the tool does, when to use it, and what it returns |
input_schema | a JSON Schema describing the arguments: types, per-argument descriptions, which are required |
JSON Schema is not an AI invention. It is a long-standing specification for describing and validating JSON data; the AI community adopted it because it already did exactly this job.
19.6.1 Intuition: the schema is the only documentation Claude gets
Claude never sees your Python source. The schema is the man page. If the description says nothing about when to use the tool, Claude guesses. If an argument’s format is unstated, Claude guesses. Good descriptions:
run about 3–4 sentences;
say what the tool does and when Claude should use it;
say what kind of data it returns;
describe every argument, including format and defaults.
19.6.2 Worked example: the schema for get_current_datetime
Following the naming convention function_name → function_name_schema:
from anthropic.types import ToolParam
get_current_datetime_schema = ToolParam(
{
"name": "get_current_datetime",
"description": "Returns the current date and time formatted according to the specified format string. This tool provides the current system time formatted as a string. Use this tool when you need to know the current date and time, such as for timestamping records, calculating time differences, or displaying the current time to users. The default format returns the date and time in ISO-like format (YYYY-MM-DD HH:MM:SS).",
"input_schema": {
"type": "object",
"properties": {
"date_format": {
"type": "string",
"description": "A string specifying the format of the returned datetime. Uses Python's strftime format codes. For example, '%Y-%m-%d' returns just the date in YYYY-MM-DD format, '%H:%M:%S' returns just the time in HH:MM:SS format, '%B %d, %Y' returns a date like 'May 07, 2025'. The default is '%Y-%m-%d %H:%M:%S' which returns a complete timestamp like '2025-05-07 14:32:15'.",
"default": "%Y-%m-%d %H:%M:%S",
}
},
"required": [],
},
}
)Read it field by field:
"type": "object" —
the arguments arrive as a dictionary, which is what lets us call get_current_datetime(**input). properties lists each parameter with a type and a description containing examples. Examples are the cheapest way to remove ambiguity.
"required": [] —
the parameter has a default, so Claude may omit it. ToolParam(...) is a TypedDict from the Anthropic SDK. It changes nothing at runtime, but lets your editor and type checker catch a misspelled key before the API does.
19.6.3 The easy way: let Claude write the schema
Hand-writing JSON Schema is tedious. The course workflow:
Copy your tool function’s source.
Open Claude and paste the Anthropic tool-use documentation as context.
Ask: “Write a valid JSON schema spec for the purposes of tool calling for this function. Follow the best practices listed in the attached documentation.”
Paste the result into your code as <function>_schema and review it—
you are the one shipping it.
The long descriptions in the TerpRemind schemas were produced exactly this way.
19.6.4 Common misconceptions
“A short description is cleaner.” “Gets the time” leaves Claude guessing about format and when to call it. Longer, specific descriptions measurably improve tool selection.
“The schema validates the call for me.” By default Claude usually follows the schema, but your function should still validate. (Setting "strict": true on a tool definition makes the API guarantee schema-valid arguments; it is an optional extra.)
19.7 Core Concept 4: Multi-Block Messages
19.7.1 Making a tool-enabled request
Pass the schemas in the tools parameter:
messages = []
messages.append({"role": "user", "content": "What is the exact time, formatted as HH:MM:SS?"})
response = client.messages.create(
model=model,
max_tokens=1000,
messages=messages,
tools=[get_current_datetime_schema],
)Until now response.content has held a single text block. With tools, Claude returns a multi-block message: a list that can mix
text blocks—
human-readable text such as “I can help you find out the current time. Let me find that information for you.”— and tool_use blocks—
instructions for your code.
A tool_use block has four fields:
Field | Example | Meaning |
type | "tool_use" | marks the block as a tool request |
id | "toolu_013M9HM18jy..." | unique ID; your result must quote it |
name | "get_current_datetime" | which tool to run |
input | {’date_format’: ’%H:%M:%S’} | the arguments, already parsed into a dict |
The response also carries stop_reason = "tool_use", meaning “I stopped because I am waiting for a tool result.”
19.7.2 Worked example: what comes back
Printing the response from the request above gives (IDs shortened):
Message( |
stop_reason='tool_use', |
content=[ |
TextBlock(type='text', |
text='I can help you find out the current time. Let me find |
that information for you.'), |
ToolUseBlock(type='tool_use', id='toolu_01A...', name='get_current_datetime', |
input={'date_format': '%H:%M:%S'}), |
], |
... |
) |
19.7.3 Keeping every block in history
Because the API is stateless, the next request must include this
assistant turn—
messages.append({"role": "assistant", "content": response.content})If you append only the text, the next request contains a tool result that refers to a tool_use ID that no longer exists, and the API rejects it.
19.7.4 Updating the helper functions
The helpers from earlier lectures assumed every message was a string. Now we upgrade them to accept a string, a list of blocks, or a full Message, and make chat accept tools and return the whole message:
from anthropic.types import Message
def add_user_message(messages, message):
user_message = {
"role": "user",
"content": message.content if isinstance(message, Message) else message,
}
messages.append(user_message)
def add_assistant_message(messages, message):
assistant_message = {
"role": "assistant",
"content": message.content if isinstance(message, Message) else message,
}
messages.append(assistant_message)
def chat(messages, system=None, temperature=1.0, stop_sequences=[], tools=None):
params = {
"model": model,
"max_tokens": 1000,
"messages": messages,
"temperature": temperature,
"stop_sequences": stop_sequences,
}
if tools:
params["tools"] = tools
if system:
params["system"] = system
message = client.messages.create(**params)
return message # the whole Message, not message.content[0].text
def text_from_message(message):
return "\n".join([block.text for block in message.content if block.type == "text"])text_from_message exists because message.content[0].text is no longer safe: the first block might be a tool_use block, which has no text.
Updating for the current SDK. Version 1.x of the anthropic Python package removed the temperature parameter (current Claude models no longer expose it). The companion project’s chat() simply leaves out temperature and stop_sequences. The AI APIs lecture explains the background.
19.7.5 Common misconceptions
“The tool_use block is always content[1].” The text block is optional and there may be several tool calls. Always filter by block.type.
“input is a JSON string I must parse.” In the Python SDK, block.input is already a dict. Never string-match on it.
19.8 Core Concept 5: Sending Tool Results
19.8.1 Running the requested tool
The arguments are a dictionary; the function takes keyword arguments. Python’s ** unpacking bridges the two:
response.content[1].input # {'date_format': '%H:%M:%S'}
get_current_datetime(**response.content[1].input) # '15:04:22'(Indexing content[1] is fine for a first experiment; the loop below filters by type instead.)
19.8.2 Definition: the tool_result block
The result goes back to Claude as a tool_result block inside a
user message—
Field | Meaning |
type | "tool_result" |
tool_use_id | must equal the id of the tool_use block being answered |
content | the tool's output, serialized as a string |
is_error | True if running the tool failed |
19.8.3 Why IDs matter: several calls at once
Claude may request several tools in one response. Asked “What’s 10 + 10 and what’s 30 + 30?” with an add tool available, it can return two tool_use blocks:
assistant: ToolUse(id="toolu_A", name="add", input={"a": 10, "b": 10}) |
ToolUse(id="toolu_B", name="add", input={"a": 30, "b": 30}) |
|
user: ToolResult(tool_use_id="toolu_A", content="20") |
ToolResult(tool_use_id="toolu_B", content="60") |
The IDs tie each answer to its question, even if you run the calls in parallel and they finish in a different order. Every tool_use must get exactly one tool_result, and all results for one assistant turn go back together in a single user message.
19.8.4 Worked example: the full round trip by hand
Putting Concepts 4 and 5 together (this is demos/01_single_tool_by_hand.py in the companion project):
import json
messages = []
add_user_message(messages, "What is the exact time, formatted as HH:MM:SS?")
# Step 1: question + schema
response = chat(messages, tools=[get_current_datetime_schema])
# Step 2: keep the WHOLE assistant message
add_assistant_message(messages, response)
# Step 3: run the tool
tool_use = next(b for b in response.content if b.type == "tool_use")
output = get_current_datetime(**tool_use.input)
# Step 4: send the result back, matched by ID
add_user_message(messages, [{
"type": "tool_result",
"tool_use_id": tool_use.id,
"content": json.dumps(output),
"is_error": False,
}])
# Step 5: ask again -- STILL passing the schema
final = chat(messages, tools=[get_current_datetime_schema])
print(text_from_message(final)) # "The current time is 15:04:22."After step 4 the history has three entries:
[0] user "What is the exact time, formatted as HH:MM:SS?" |
[1] assistant [Text "Let me find that...", ToolUse id=toolu_01A get_current_datetime {...}] |
[2] user [ToolResult tool_use_id=toolu_01A content='"15:04:22"' is_error=False] |
Why pass tools in step 5 when we do not expect another call? Because entry [1] mentions get_current_datetime; Claude needs the schema to make sense of its own history. Send the same tool list on every request in a conversation.
19.8.5 Common misconceptions
“Results go in an assistant message.” They go in a user message.
“If a tool fails I should skip its result.” Never. A missing result for a tool_use ID is an API error. Send a result with is_error: True and the error text.
“One user message per result.” Put all results from one turn in one message; splitting them confuses the model and discourages parallel calls.
19.9 Core Concept 6: The Multi-Turn Tool Loop
19.9.1 Motivation
Ask “What day is 103 days from today?” and one tool call is not enough. Claude must first call get_current_datetime, see the answer, and only then call add_duration_to_datetime. Since it cannot know the second call’s arguments before seeing the first result, these happen in separate turns:
user "What day is 103 days from today?" |
assistant tool_use get_current_datetime() |
user tool_result "2026-11-01 10:00:00" |
assistant tool_use add_duration_to_datetime("2026-11-01", 103, "days") |
user tool_result "Friday, February 12, 2027 12:00:00 AM" |
assistant "103 days from today is Friday, February 12, 2027." |
We cannot hand-code a fixed number of steps; we need a loop.
The tool loop repeatedly (1) calls Claude, (2) appends its reply, (3) stops if the reply is not asking for tools, and otherwise (4) runs every requested tool and appends the results. The signal for step 3 is stop_reason:
stop_reason | Meaning in a tool loop |
tool_use | Claude wants tool results; run them and loop |
end_turn | Claude is finished; show the final text |
max_tokens | output was cut off; a tool_use block may be incomplete, so do not run it |
pause_turn | a server tool (e.g. web search) paused; resend to continue (Concept 10) |
refusal | Claude declined; do not run any tool from this turn |
19.9.2 Worked example: the loop
First, run_tools answers every tool_use block in a message, turning exceptions into error results:
import json
def run_tool(tool_name, tool_input):
if tool_name == "get_current_datetime":
return get_current_datetime(**tool_input)
def run_tools(message):
tool_requests = [block for block in message.content if block.type == "tool_use"]
tool_result_blocks = []
for tool_request in tool_requests:
try:
tool_output = run_tool(tool_request.name, tool_request.input)
tool_result_block = {
"type": "tool_result",
"tool_use_id": tool_request.id,
"content": json.dumps(tool_output),
"is_error": False,
}
except Exception as e:
tool_result_block = {
"type": "tool_result",
"tool_use_id": tool_request.id,
"content": f"Error: {e}",
"is_error": True,
}
tool_result_blocks.append(tool_result_block)
return tool_result_blocksThen the loop itself:
def run_conversation(messages):
while True:
response = chat(messages, tools=[get_current_datetime_schema])
add_assistant_message(messages, response)
print(text_from_message(response))
if response.stop_reason != "tool_use":
break
tool_results = run_tools(response)
add_user_message(messages, tool_results)
return messagesDesign notes:
run_tool is a router: it maps a tool name to a function. The loop never mentions a specific tool, so adding tools never touches it.
json.dumps(tool_output) serializes any JSON-able return value—
a string becomes ’"15:04"’, None becomes ’null’. The except branch is what makes “raise a meaningful error” (Concept 2) pay off: the message reaches Claude, which can retry.
19.9.3 Worked example: running it
messages = []
add_user_message(
messages,
"What is the current time in HH:MM format? Also, what is the current time in SS format?",
)
run_conversation(messages)Printed output:
I can help you get the current time in the requested formats. Let me fetch that for you. |
|
The current time in HH:MM format is 11:16. |
The current time in SS format (seconds only) is 30. |
The returned history shows two round trips (IDs shortened):
[0] user 'What is the current time in HH:MM format? Also, ... SS format?' |
[1] assistant [Text 'I can help you get the current time ... Let me fetch that for you.', |
ToolUse id=toolu_013M get_current_datetime {'date_format': '%H:%M'}] |
[2] user [ToolResult tool_use_id=toolu_013M content='"11:16"' is_error=False] |
[3] assistant [ToolUse id=toolu_01Dv get_current_datetime {'date_format': '%S'}] |
[4] user [ToolResult tool_use_id=toolu_01Dv content='"30"' is_error=False] |
[5] assistant [Text 'The current time in HH:MM format is 11:16.\nThe current time in SS ...'] |
Step by step: iteration 1 ends with stop_reason = "tool_use" after entry [1], so the loop runs the tool and appends [2]. Iteration 2 produces [3], another tool request. Iteration 3 produces [5] with stop_reason = "end_turn", and the loop exits. (Here Claude chose to make the two calls one at a time; it could equally have put both tool_use blocks in entry [1]. The loop handles either.)
19.9.4 Practical implications: bound the loop
while True trusts the model to stop. In production, cap the number of iterations so a confused model (or a tool that always fails) cannot burn money forever. The companion project’s version:
def run_conversation(messages, tools, registry, max_turns=10, verbose=True, **chat_kwargs):
for _ in range(max_turns):
response = chat(messages, tools=tools, **chat_kwargs)
add_assistant_message(messages, response)
if verbose and (text := text_from_message(response)):
print(text)
if response.stop_reason != "tool_use":
return messages
add_user_message(messages, run_tools(response, registry))
raise RuntimeError(f"Gave up after {max_turns} turns of tool use")It also takes the tool list and a registry dictionary as
parameters, so the same loop serves every demo—
19.9.5 Common misconceptions
“Check whether the content contains a tool_use block.” Check stop_reason. It is the API’s explicit statement of why generation stopped.
“The narration text is always there.” It is optional. On current models, text between tool calls may arrive as a thinking block instead of a text block, so don’t build UI that depends on it.
19.10 Core Concept 7: Using Multiple Tools
19.10.1 The four-step recipe
Once the loop exists, adding a tool is mechanical:
Write the tool function.
Write its schema.
Add the schema to the tools list.
Add a case for the tool in run_tool.
19.10.2 Worked example: finishing TerpRemind
Steps 1 and 2 are already done. Step 3:
response = chat(
messages,
tools=[
get_current_datetime_schema,
add_duration_to_datetime_schema,
set_reminder_schema,
],
)Step 4:
def run_tool(tool_name, tool_input):
if tool_name == "get_current_datetime":
return get_current_datetime(**tool_input)
elif tool_name == "add_duration_to_datetime":
return add_duration_to_datetime(**tool_input)
elif tool_name == "set_reminder":
return set_reminder(**tool_input)Now a request that needs two different tools:
messages = []
add_user_message(
messages,
"Set a reminder for my doctor's appointment. It's 177 days after Jan 1st, 2050.",
)
run_conversation(messages)I'll set a reminder for your doctor's appointment that's 177 days after January 1st, 2050. |
|
Let me calculate that date first. |
Now I'll set the reminder for your doctor's appointment on June 27, 2050: |
---- |
Setting the following reminder for 2050-06-27T00:00:00: |
Doctor's appointment |
---- |
Your reminder has been set successfully! You will be reminded of your doctor's appointment |
on Monday, June 27, 2050. If you need to set a specific time for this appointment rather |
than midnight (12:00 AM), please let me know and I can adjust the reminder. |
19.10.3 Trace: how Claude chained the tools
# | Role | Content |
0 | user | Set a reminder ... 177 days after Jan 1st, 2050. |
1 | assistant | text + add_duration_to_datetime(datetime_str=’2050-01-01’, duration=177, unit=’days’) |
2 | user | tool_result ’"Monday, June 27, 2050 12:00:00 AM"’ |
3 | assistant | text + set_reminder(content="Doctor’s appointment", timestamp=’2050-06-27T00:00:00’) |
4 | user | tool_result ’null’ (set_reminder returns None) |
5 | assistant | Your reminder has been set successfully! ... |
Observe what Claude did on its own:
It did not call get_current_datetime—
the start date was given, so the current time was irrelevant. It translated “Jan 1st, 2050” into the format the schema asked for (2050-01-01) and converted the verbose result back into the ISO timestamp set_reminder’s schema requires.
It noticed the reminder defaulted to midnight and offered to fix it.
That reformatting between tools is exactly why schema descriptions spell out formats.
19.10.4 Design improvement: a registry instead of if/elif
An if/elif chain grows by two lines per tool and silently returns None for an unknown name. A dictionary is shorter and fails loudly:
REGISTRY = {
"get_current_datetime": get_current_datetime,
"add_duration_to_datetime": add_duration_to_datetime,
"set_reminder": set_reminder,
}
SCHEMAS = [get_current_datetime_schema, add_duration_to_datetime_schema, set_reminder_schema]
def run_tool(registry, tool_name, tool_input):
if tool_name not in registry:
raise ValueError(f"Unknown tool: {tool_name}")
return registry[tool_name](**tool_input)The companion project also makes set_reminder validate its timestamp and return a confirmation string instead of None; a result of "Reminder #1 set for 2050-06-27T00:00:00" tells Claude much more than null.
19.10.5 Controlling tool selection: tool_choice
By default Claude decides whether and which tools to call. The tool_choice request parameter changes that:
Value | Behavior |
{"type": "auto"} | Claude decides (the default) |
{"type": "none"} | Claude may not call tools |
{"type": "any"} | Claude must call at least one tool |
{"type": "tool", "name": "..."} | Claude must call this specific tool |
The auto, any, and tool options can add "disable_parallel_tool_use": true to allow at most one call per turn. Caution: the newest models (Claude Opus 5.5, Sonnet 5.5, Fable 5.1) reject the forcing options any and tool with a 400 error. On those, use auto and say in the prompt which tool to use; check that a call was made.
19.10.6 Common misconceptions
“More tools is always better.” Each schema costs input tokens on every request, and overlapping tools (get_time and get_current_datetime) make selection harder. Expose the tools the task needs.
“Claude will call the tools in the order I list them.” Order in the tools list does not imply call order; Claude plans from the user’s request.
19.11 Core Concept 8: Streaming and Fine-Grained Tool Calling
19.11.1 Tool calls on a stream
With streaming, Claude’s response arrives as a sequence of events. For text you already handle text deltas. For a tool call you see:
content_block_start (content_block.type == "tool_use", name = "save_article") |
input_json partial_json = '{"abstract": "This paper ...' |
input_json partial_json = '", "meta": {"word_count": 847, ...' |
... |
content_block_stop |
In the Python SDK each input_json event has two fields:
partial_json—
the new chunk of JSON text; snapshot—
the arguments accumulated so far, already parsed into a Python object.
19.11.2 The running example: save_article
We use a tool with a nested argument so that streaming behavior is visible:
save_article_schema = ToolParam({
"name": "save_article",
"description": "Saves a scholarly journal article",
"input_schema": {
"type": "object",
"properties": {
"abstract": {"type": "string", "description": "Abstract of the article. One short sentence max"},
"meta": {
"type": "object",
"properties": {
"word_count": {"type": "integer", "description": "Word count"},
"review": {"type": "string", "description": "Eight sentence review of the paper"},
},
"required": ["word_count", "review"],
},
},
"required": ["abstract", "meta"],
},
})
def save_article(**kwargs):
return "Article saved!"The loop prints tool arguments as they stream (abridged):
with chat_stream(messages, tools=tools, tool_choice=tool_choice,
betas=["fine-grained-tool-streaming-2025-05-14"] if fine_grained else []) as stream:
for chunk in stream:
if chunk.type == "text":
print(chunk.text, end="")
if chunk.type == "content_block_start":
if chunk.content_block.type == "tool_use":
print(f'\n>>> Tool Call: "{chunk.content_block.name}"')
if chunk.type == "input_json" and chunk.partial_json:
print(chunk.partial_json, end="")
if chunk.type == "content_block_stop":
print("\n")
response = stream.get_final_message()19.11.3 Why arguments arrive in bursts
Run that loop and you notice something odd: long pauses, then a big chunk all at once. The reason is server-side validation. By default the API does not forward chunks as Claude generates them. It buffers each top-level key-value pair, checks it against your schema, and only then sends all its chunks:
Claude generates: You receive: |
|
{"abstract": ┐ |
"This pa|per pres|ents ...", │ buffered |
┘ ◀── burst: whole abstract |
"meta": { ┐ |
"word_count": 847, │ |
"review": "...8 sentences..." │ buffered |
} ┘ ◀── burst: whole meta object |
} |
For save_article that means nothing arrives until the abstract
is complete, then nothing until the entire meta
object—
19.11.4 Definition: fine-grained (eager) input streaming
Fine-grained tool streaming turns that buffering off. Chunks arrive as soon as Claude generates them, so word_count shows up early. The cost: the API no longer validates the JSON. Your code receives whatever the model produced, valid or not.
How you enable it has changed since the feature launched in beta:
How | Status | |
Beta (2025) | beta header fine-grained-tool-streaming-2025-05-14 via client.beta.messages.stream | legacy; do not use in new code |
Current API | "eager_input_streaming": true on each tool definition, regular client.messages.stream | generally available, no beta header |
The current form, from the companion project:
schema = {
"name": "save_article",
"description": "Saves a scholarly journal article",
"eager_input_streaming": True, # per tool, not per request
"input_schema": {...},
}
with client.messages.stream(model=model, max_tokens=64000,
messages=messages, tools=[schema]) as stream:
for event in stream:
if event.type == "input_json" and event.partial_json:
print(event.partial_json, end="", flush=True)
response = stream.get_final_message()19.11.5 Worked example: what invalid output looks like
To see this, we deliberately provoke bad output: force a
save_article call with tool_choice and a prompt asking for
“malformed output that includes "word_count": undefined”—
>>> Tool Call: "save_article" |
{"abstract": "This paper examines the impact of machine learning on healthcare diagnostics.", |
"meta": "{\n \"word_count\": undefined,\n \"review\": \"This study presents ...\"\n}"} |
Look closely at meta: it is a string, not an object.
Server-side validation could not accept undefined, so it wrapped
the whole value in a string. The JSON is now syntactically valid but
no longer matches the schema—
With fine-grained streaming on, nothing is wrapped: the raw undefined reaches your code. Either way, the lesson is the same: validate tool input before running the tool. The companion project checks the shape explicitly:
def validate_article(tool_input):
if not isinstance(tool_input, dict):
return "input is not an object"
if not isinstance(tool_input.get("abstract"), str):
return "abstract must be a string"
meta = tool_input.get("meta")
if not isinstance(meta, dict):
return "meta must be an object" # catches the stringified meta above
if not isinstance(meta.get("word_count"), int):
return "meta.word_count must be an integer"
if not isinstance(meta.get("review"), str):
return "meta.review must be a string"
return NoneWhen validation fails, do not run the tool; send back an error result (is_error: True) quoting the bad input so Claude can try again. Also skip tools when stop_reason is max_tokens: a truncated call can still parse as a valid-looking partial object.
A note on detecting bad JSON. It is tempting to call json.loads(chunk.snapshot) to detect bad JSON. In the Python SDK snapshot is already parsed, so that line would fail on every chunk. The SDK’s partial-JSON parser is also tolerant: it may silently truncate malformed input rather than raise. Schema validation of the final input is the reliable check.
19.11.6 When to use it
Turn eager streaming on when:
users should see tool arguments forming in real time;
you want to start processing partial results early;
a tool takes a large argument (a whole file, a long document), where buffering means a long silent gap;
and you are prepared to validate input yourself.
For short arguments the default buffered behavior is fine.
19.11.7 Common misconceptions
“Streaming means I see every token immediately.” Not for tool arguments, unless eager streaming is on.
“Fine-grained streaming makes the model faster.” Total generation time is the same; only delivery timing changes.
“Forcing a tool with tool_choice still works everywhere.” Forcing save_article with tool_choice works on older models; on Claude Opus 5.5 / Sonnet 5.5 that request is a 400. Ask for the tool in the prompt instead, as the companion demo does.
19.12 Core Concept 9: Built-in Tools I— The Text Editor
Claude ships with a few Anthropic-defined tools whose schemas
are built into the model. The text editor tool lets Claude
view, create, and edit files—
The confusing part: the schema is built in, but the implementation is yours. Claude knows how to ask for file operations; your code performs them.
schema implementation |
Your own tools you write it you write it |
Text editor built in YOU write it ← client-executed |
Web search built in Anthropic runs it ← server-executed |
19.12.1 The schema stub
You declare the tool with a two-field stub; Claude expands it into the full specification internally. The type is versioned:
def get_text_edit_schema(model):
return {
"type": "text_editor_20250728",
"name": "str_replace_based_edit_tool",
}Older models used text_editor_20250124 / text_editor_20241022 with the name str_replace_editor; those models are now retired. The current version strings for every model are listed in Anthropic’s text-editor-tool documentation.
19.12.2 The commands you must implement
Each tool_use block’s input has a command field:
command | Other inputs | Action |
view | path, optional view_range | return the file with line numbers, or list a directory |
create | path, file_text | create (or overwrite) a file |
str_replace | path, old_str, new_str | replace exactly one occurrence; error on 0 or more than 1 |
insert | path, insert_line, insert_text | insert after line N (0 = top of file) |
The “exactly one occurrence” rule for str_replace is a clever design: if old_str matches twice, the edit is ambiguous, and the error message tells Claude to include more surrounding context.
19.12.3 Worked example: implementing the text editor
We implement the editor as a TextEditorTool class. Its
str_replace shows the pattern every command follows—
def str_replace(self, file_path: str, old_str: str, new_str: str) -> str:
abs_path = self._validate_path(file_path)
if not os.path.exists(abs_path):
raise FileNotFoundError("File not found")
with open(abs_path, "r", encoding="utf-8") as f:
content = f.read()
match_count = content.count(old_str)
if match_count == 0:
raise ValueError("No match found for replacement. Please check your text and try again.")
elif match_count > 1:
raise ValueError(
f"Found {match_count} matches for replacement text. "
"Please provide more context to make a unique match."
)
self._backup_file(abs_path) # create backup before modifying
new_content = content.replace(old_str, new_str)
with open(abs_path, "w", encoding="utf-8") as f:
f.write(new_content)
return "Successfully replaced text at exactly one location."And a router dispatches on command:
def run_tool(tool_name, tool_input):
if tool_name == "str_replace_based_edit_tool":
command = tool_input["command"]
if command == "view":
return text_editor_tool.view(tool_input["path"], tool_input.get("view_range"))
elif command == "str_replace":
return text_editor_tool.str_replace(tool_input["path"], tool_input["old_str"], tool_input["new_str"])
elif command == "create":
return text_editor_tool.create(tool_input["path"], tool_input["file_text"])
elif command == "insert":
return text_editor_tool.insert(tool_input["path"], tool_input["insert_line"], tool_input["insert_text"])
...19.12.4 Running it
With the editor registered under its schema name, the same run_conversation loop drives it:
editor = TextEditorTool("workspace")
messages = []
add_user_message(messages,
"Open the ./main.py file and add a function that calculates pi to the 5th digit. "
"Then create a ./test_main.py file that tests your implementation.")
run_conversation(messages, tools=[TEXT_EDITOR_SCHEMA], registry={TEXT_EDITOR_NAME: editor})A typical run: Claude calls view on main.py, then str_replace or insert to add the function, then create for test_main.py, and finally summarizes what it did.
19.12.5 Why use it?
Editors like VS Code already have AI built in. The text editor tool matters when you are building the application: a documentation bot that edits a repo, an autograder that patches student code, an internal tool running where no IDE exists. It lets you rebuild the core of an AI code editor inside your own software, with full control over which files Claude may touch.
19.13 Core Concept 10: Built-in Tools II— Web Search
The web search tool is a server tool: Anthropic runs it. You add a schema; Claude searches, reads results, and cites sources, all inside one API call. There is no tool_use block for you to answer.
Your organization must first enable web search in the Claude Console (Settings → Privacy).
19.13.1 The schema
web_search_schema = {
"type": "web_search_20250305",
"name": "web_search",
"max_uses": 5,
"allowed_domains": ["nih.gov"],
}
messages = []
add_user_message(messages, "What's the best exercise for gaining leg muscle?")
response = chat(messages, tools=[web_search_schema])max_uses caps the number of searches. Claude may run follow-up searches based on what it finds; the cap bounds cost.
allowed_domains restricts results to trusted sources. For medical or fitness advice, limiting to nih.gov (PubMed) gives evidence-based results instead of random blogs. (blocked_domains is the opposite; use one or the other.)
On current models (Opus 5.5, Sonnet 5.5, and recent predecessors) use the newer type web_search_20260209, which adds dynamic filtering: Claude filters results with code before they enter its context. The parameters are the same.
19.13.2 The response
The response contains several new block types:
Block | Contains | Render as |
text | Claude's prose | regular content |
server_tool_use | the exact query Claude searched for | optional "Searched for ..." note |
web_search_tool_result | a list of results, each with title and url | a list of sources |
citations on text blocks | the quoted source text, page title, and URL backing a claim | inline citations |
A minimal renderer (demos/06_web_search.py):
for block in response.content:
if block.type == "server_tool_use":
print(f"[search] {block.input}")
elif block.type == "web_search_tool_result":
if isinstance(block.content, list):
for result in block.content:
print(f" source: {result.title} -- {result.url}")
else:
print(f" search error: {block.content.error_code}")
elif block.type == "text":
print(block.text, end="")
for citation in block.citations or []:
print(f" [{citation.url}]", end="")Two details: search errors do not raise exceptions—
19.13.3 pause_turn
Because server tools loop on Anthropic’s side, a long research turn
can hit the server’s iteration limit and return
stop_reason = "pause_turn". To continue, append the assistant
content and call again—
while response.stop_reason == "pause_turn":
add_assistant_message(messages, response)
response = chat(messages, tools=[web_search_schema])(The demo caps this at a few iterations.)
19.13.4 When to use it
Web search shines for current events, specialized information missing from training data, fact-checking, and research needing up-to-date sources. Include the schema and Claude decides when a search helps.
19.14 Client Tools vs. Server Tools
Your own tool | Text editor | Web search | |
Schema | you write | built in; stub text_editor_20250728 | built in; stub web_search_* |
Who executes | your code | your code | Anthropic |
You answer tool_use? | yes | yes | no |
Stop reason | tool_use | tool_use | end_turn (or pause_turn) |
Main risk | bad arguments | path traversal, destructive edits | untrusted web content, cost |
19.15 The Complete Picture
┌──────────────────────────── your application ─────────────────────────────┐ |
user ──────▶ │ messages = [user msg] │ |
│ │ │ |
│ ▼ │ |
│ chat(messages, tools=SCHEMAS) ───────────────▶ Claude ──┐ │ |
│ ▲ │ server tools │ |
│ │ │ (web search) │ |
│ │ response: text | tool_use | server blocks ◀──┘ run here │ |
│ │ │ │ |
│ │ add_assistant_message(response) │ |
│ │ │ │ |
│ │ stop_reason == "tool_use"? ── no ──▶ text_from_message ──────────────▶ user |
│ │ │ yes │ |
│ │ run_tools: for each tool_use block │ |
│ │ validate → REGISTRY[name](**input) → tool_result(id, ...) │ |
│ │ (exception → tool_result(is_error=True)) │ |
│ │ │ │ |
│ └──── add_user_message([all tool_results]) │ |
└───────────────────────────────────────────────────────────────────────────┘ |
The model decides; your loop executes. History grows by an assistant/user pair per round trip and is resent each time. The same tool list goes out on every request. Errors become results, not crashes.
19.16 Demos
Each demo is a file in the companion project and takes under a minute. Tests run offline; demos call the API.
Command | Concept | What to watch for |
python demos/01_single_tool_by_hand.py | 4, 5 | the text + tool_use blocks; the five manual steps |
python demos/02_multi_turn.py | 6 | history grows by user/assistant pairs; matching IDs |
python demos/03_reminder_agent.py | 7 | Claude chains add_duration_to_datetime into set_reminder |
python demos/03_reminder_agent.py "Remind me ... 3 weeks from today" | 7 | now it must call get_current_datetime first |
python demos/04_streaming.py | 8 | pauses, then bursts per top-level key |
python demos/04_streaming.py –eager | 8 | smooth chunks; our validator checks the result |
python demos/05_text_editor.py | 9 | view → edit → create; files appear in workspace/ |
python demos/06_web_search.py | 10 | queries, sources, and inline citations from nih.gov |
pytest -q | all | 25 tests pass with no key and no network |
19.17 GitHub-Ready Project: claude-tool-use
The companion project lives in notes/tool-use/code/claude-tool-use/ and can be dropped into a GitHub repository as is.
claude-tool-use/ |
├── README.md |
├── pyproject.toml # package metadata + pytest config |
├── requirements.txt # anthropic>=1.2, python-dotenv, pytest |
├── .env.example # ANTHROPIC_API_KEY, CLAUDE_MODEL |
├── .gitignore # .env is ignored |
├── tooluse/ |
│ ├── chat.py # add_user_message, add_assistant_message, chat, text_from_message |
│ ├── tools.py # the three TerpRemind tools, their schemas, REGISTRY, SCHEMAS |
│ ├── loop.py # run_tool, run_tools, run_conversation (bounded) |
│ ├── text_editor.py # TextEditorTool for text_editor_20250728, sandboxed |
│ └── streaming.py # save_article schema, eager streaming, validate_article |
├── demos/ # 01_single_tool_by_hand.py ... 06_web_search.py |
├── tests/ # offline: a FakeClient scripts Claude's responses |
│ ├── conftest.py |
│ ├── test_tools.py # date math edge cases, validation, schema/registry agreement |
│ ├── test_loop.py # ID matching, error results, loop termination, max_turns |
│ ├── test_text_editor.py # commands, backups, path-traversal refusal |
│ └── test_streaming.py # eager flag, the stringified-meta bug |
└── workspace/main.py # sandbox for the text-editor demo |
Quick start:
cd notes/tool-use/code/claude-tool-use
python -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install -r requirements.txt
pip install -e . # makes `tooluse` importable from demos/
pytest -q # offline -- no key needed
cp .env.example .env # then paste your key into .env
python demos/03_reminder_agent.py19.17.1 How the loop is tested without an API key
The loop is the part most worth testing and the part that seems to need Claude. The trick is dependency injection: chat() accepts an optional client, and run_conversation passes extra keyword arguments through. A fake client returns scripted responses and records every request:
class FakeClient:
def __init__(self, responses):
self.responses = list(responses)
self.requests = []
self.messages = self # so client.messages.create works
def create(self, **params):
self.requests.append({**params, "messages": list(params["messages"])})
return self.responses.pop(0)A test then scripts the TerpRemind conversation—
run_conversation(messages, tools=["schemas"], registry=registry, client=client, verbose=False)
assert len(client.requests) == 3
assert all(r["tools"] == ["schemas"] for r in client.requests) # schema sent every time
assert [m["role"] for m in messages] == ["user", "assistant"] * 3
assert messages[2]["content"][0]["tool_use_id"] == "t1" # results matched by IDThe model ID comes from the CLAUDE_MODEL environment variable (default claude-opus-5-5; claude-haiku-5-5 is the cheapest current option for experiments).
19.18 Practice Exercises
19.18.1 Basic
In your own words, explain who executes the code at each of the four steps of the tool-use protocol. Which step costs API tokens?
Write a tool function get_weather(location, unit) (return fake data) that validates its inputs, and write its schema using enum for unit. Justify each sentence of your description.
Given this response content, write the exact user message you must send back: [Text("Let me check both."), ToolUse(id="toolu_X", name="add", input={"a": 2, "b": 3}), ToolUse(id="toolu_Y", name="add", input={"a": 4, "b": 5})].
Why must the second request in Demo 1 still include tools=[get_current_datetime_schema]?
List the five stop_reason values from Concept 6 and what a tool loop should do for each.
19.18.2 Intermediate
Add a fourth tool, list_reminders(), to TerpRemind using the four-step recipe. Write a test with FakeClient showing that “What reminders do I have?” leads to a list_reminders call.
The add_duration_to_datetime above crashes on ("2024-02-29", 1, "years") and on ("2025-01-15", 1.5, "months"). Explain each crash, then show (by reading the tool_result block) what Claude would see after each one, and fix the function.
Modify run_tools to run independent tool calls concurrently with concurrent.futures.ThreadPoolExecutor, while still returning results in one user message. Why is the order of results in the list not important?
Make set_reminder ask the user for confirmation on the terminal before saving, and return a “user declined” result if they refuse. How does Claude respond to that result?
Write a streaming demo that prints event.snapshot instead of partial_json. Run it with and without eager_input_streaming and describe the difference you observe in meta.word_count.
19.18.3 Advanced
Red-team the text editor. List at least five paths or inputs a malicious prompt might make Claude send to TextEditorTool (symlinks, absolute paths, URL-encoded .., very large files, binary files). For each, state whether tooluse/text_editor.py defends against it, and write tests for any gaps you fix.
Budget-aware loop. Extend run_conversation to sum response.usage.input_tokens and output_tokens across iterations and stop with a clear error when a dollar budget would be exceeded. Explain why input tokens grow roughly quadratically with the number of round trips.
Tool selection at scale. Generate 40 plausible tool schemas for a campus-services assistant. Measure (with a small evaluation set of 20 requests) how often Claude picks the right tool when given all 40 versus the 5 most relevant. What does this suggest about how large agents should manage their tool lists?
19.19 Summary
19.19.1 Key takeaways
Tools let a closed-book model fetch fresh data, use your systems, take actions, and compute reliably. The model only requests; your code executes (except for server tools).
A tool is a function plus a schema. The schema’s description is a prompt: say what the tool does, when to use it, what it returns, and the format of every argument.
Tool responses are multi-block. Append the whole response.content to history; filter blocks by type.
Answer every tool_use with a tool_result carrying the same ID, all in one user message. Failures become results with is_error: True.
Loop until stop_reason != "tool_use", send the same tool list every time, and bound the number of iterations.
Adding a tool is four steps and never touches the loop.
Streaming buffers tool arguments per top-level key for validation; eager_input_streaming trades that validation for immediacy. Validate tool input yourself either way.
The text editor tool is built in but client-executed: you implement it and must sandbox every path. Web search is server-executed: add the schema, render the citations.
19.19.2 Terminology
Term | Meaning |
tool use / function calling | the protocol by which a model requests that the application run a function |
tool function | the ordinary code your application runs for a tool |
tool schema | JSON object with name, description, input_schema |
JSON Schema | a standard for describing the shape of JSON data |
tool_use block | content block in which Claude requests a call: id, name, input |
tool_result block | content block in a user message returning a tool's output: tool_use_id, content, is_error |
multi-block message | a message whose content list mixes text, tool_use, and other blocks |
stop_reason | why generation stopped; tool_use means results are expected |
tool loop | repeat: call Claude, run requested tools, send results, until no more tool use |
tool_choice | request parameter controlling whether/which tools Claude must call |
fine-grained / eager input streaming | streaming tool arguments without server-side buffering and validation |
Anthropic-defined tool | a tool whose schema is built into Claude (text editor, bash, web search) |
client tool vs. server tool | executed by your code vs. executed by Anthropic |
pause_turn | stop reason when a server tool's loop pauses; resend to continue |
19.19.3 Common mistakes
Appending only the text of a tool-use response to history.
Reading content[0].text or assuming the tool call is content[1].
Mismatched or missing tool_use_ids; skipping the result of a failed tool.
Leaving out tools on follow-up requests.
An unbounded while True loop.
Vague descriptions (“gets the time”) and prose where an enum belongs.
Running tool input without validation, especially with eager streaming or after max_tokens.
Checking file paths with str.startswith.
Using a stale tool name or version string (str_replace_editor, the fine-grained beta header) after upgrading models.
19.19.4 Where this leads
MCP: instead of hard-coding schemas and a registry in each app, an MCP server publishes tools that any MCP client (Claude Code, Claude Desktop, your own app) can discover and call.
Agents: an agent is today’s loop with more tools, more turns, and more autonomy—
plus planning, memory, and guardrails. AI security: tool use is where prompt injection becomes dangerous; a malicious web page or file can try to talk Claude into calling your tools. Least privilege and confirmation gates matter.
Evaluation and monitoring: measure tool-selection accuracy and log every call; tool failures are the most common way agents go wrong.