Claude Tool Use: Code Execution, Text Editor & Web Search
By Learnia Team
Claude Tool Use: Code Execution, Text Editor & Web Search
๐ Last updated: March 10, 2026 โ Covers built-in tools, function calling, and advanced patterns.
๐ Pillar article: Claude API: Complete Guide
What is Tool Use?
Tool Use (or function calling) is Claude's ability to use external tools during a conversation. Instead of simply responding with text, Claude can:
- โDecide that a tool is needed to answer
- โGenerate the tool call parameters in JSON format
- โReceive the result of the tool execution
- โUse that result to formulate a complete response
The Tool Use Flow
User โ Claude (thinks) โ Tool call (JSON)
โ
Your code executes the tool
โ
Result โ Claude (uses the result) โ Final response
Built-in Tools
Claude has three built-in tools that require no implementation on your part.
1. Code Execution (Python Sandbox)
The Code Execution tool allows Claude to run Python code in a secure sandbox environment. Ideal for calculations, data analysis, and chart generation.
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=4096,
tools=[{
"type": "code_execution"
}],
messages=[{
"role": "user",
"content": "Calculate the mean, median, and standard deviation of this data: [23, 45, 67, 12, 89, 34, 56, 78, 91, 43]"
}]
)
Use cases: Mathematical calculations, statistical analysis, matplotlib chart generation, pandas data manipulation.
Limitations: Isolated sandbox, no network access, no persistence between calls, limited libraries (numpy, pandas, matplotlib available).
2. Text Editor
The Text Editor tool allows Claude to read, create, and modify files. Primarily used in Claude Code and development agents.
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=4096,
tools=[{
"type": "text_editor_20250429",
"name": "text_editor"
}],
messages=[{
"role": "user",
"content": "Read the config.json file and change the port from 3000 to 8080."
}]
)
Available commands:
| Command | Description |
|---|---|
view | Read file contents |
create | Create a new file |
str_replace | Replace text in a file |
insert | Insert text at a given line |
3. Web Search
The Web Search tool allows Claude to search for up-to-date information on the web.
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=4096,
tools=[{
"type": "web_search"
}],
messages=[{
"role": "user",
"content": "What are the latest AI news in March 2026?"
}]
)
Use cases: Up-to-date information, fact checking, documentation search, product pricing and availability.
Custom Tools (Function Calling)
Custom tools let you connect Claude to any API or function in your application.
Defining a Custom Tool
import anthropic
import json
client = anthropic.Anthropic()
# Tool definition
tools = [{
"name": "get_weather",
"description": "Gets the current weather for a given city. Use this tool when the user asks about the weather.",
"input_schema": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "The city name (e.g., 'Paris', 'London')"
},
"units": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "Temperature unit"
}
},
"required": ["city"]
}
}]
# First request
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
tools=tools,
messages=[{
"role": "user",
"content": "What's the weather like in Paris?"
}]
)
The Complete Tool Use Cycle
Tool Use works in a loop. Here is the complete pattern:
def run_tool_loop(user_message, tools, tool_handlers):
"""Execute a complete tool use loop."""
messages = [{"role": "user", "content": user_message}]
while True:
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=4096,
tools=tools,
messages=messages
)
# If Claude is done (no tool call)
if response.stop_reason == "end_turn":
return response.content[0].text
# Process tool calls
messages.append({"role": "assistant", "content": response.content})
tool_results = []
for block in response.content:
if block.type == "tool_use":
# Execute the tool
handler = tool_handlers[block.name]
result = handler(**block.input)
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": json.dumps(result)
})
messages.append({"role": "user", "content": tool_results})
# Tool handlers
def get_weather(city, units="celsius"):
# Call a real weather API
return {"city": city, "temp": 18, "condition": "Sunny"}
# Execution
result = run_tool_loop(
"What's the weather in Paris and London?",
tools=tools,
tool_handlers={"get_weather": get_weather}
)
Parallel Tools
Claude can call multiple tools simultaneously when it needs several independent pieces of information:
# Claude can generate multiple tool_use blocks in a single response:
# [
# {"type": "tool_use", "name": "get_weather", "input": {"city": "Paris"}},
# {"type": "tool_use", "name": "get_weather", "input": {"city": "London"}}
# ]
Advanced Patterns
Forcing Tool Use
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
tools=tools,
tool_choice={"type": "tool", "name": "get_weather"}, # Force this tool
messages=[{"role": "user", "content": "Paris"}]
)
tool_choice Value | Behavior |
|---|---|
{"type": "auto"} | Claude decides (default) |
{"type": "any"} | Claude MUST use a tool (any one) |
{"type": "tool", "name": "..."} | Claude MUST use this specific tool |
{"type": "none"} | Claude CANNOT use any tool |
Structured Extraction via Tool Use
A powerful pattern: using Tool Use to force Claude to return structured data.
tools = [{
"name": "extract_contact",
"description": "Extracts contact information from text.",
"input_schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"email": {"type": "string"},
"phone": {"type": "string"},
"company": {"type": "string"}
},
"required": ["name"]
}
}]
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
tools=tools,
tool_choice={"type": "tool", "name": "extract_contact"},
messages=[{
"role": "user",
"content": "Marie Dupont is a director at TechCorp. Contact her at marie@techcorp.com or at +33 6 12 34 56 78."
}]
)
# Guaranteed structured result:
# {"name": "Marie Dupont", "email": "marie@techcorp.com", "phone": "+33 6 12 34 56 78", "company": "TechCorp"}
Best Practices
Writing Good Tool Descriptions
The tool description is critical โ it's what Claude uses to decide when and how to use it.
| โ Bad description | โ Good description |
|---|---|
| "Searches data" | "Searches for products in the database by name, category, or price range. Returns the top 10 results sorted by relevance." |
| "Sends an email" | "Sends an email via the configured SMTP server. Use this tool only when the user explicitly asks to send a message." |
Best Practices Checklist
- โDetailed descriptions โ Explain when and why to use the tool
- โDocumented parameters โ Each parameter should have a clear description
- โServer-side validation โ Never trust parameters without validation
- โError handling โ Return clear error messages in tool_results
- โLimit the number of tools โ 10-20 tools maximum for optimal performance
- โExplicit names โ
search_productsrather thansearchorsp
Common Errors
| Error | Cause | Solution |
|---|---|---|
| Claude doesn't use the tool | Insufficient description | Improve the description with examples |
| Incorrect parameters | Ambiguous schema | Add description and enum to properties |
| Infinite loop | No stop condition | Limit the number of iterations in your loop |
Missing tool_use_id | Malformed result | Each tool_result must reference the correct tool_use_id |
Read Next
- โAgent-Computer Interface (ACI): Designing Tools for Agents โ Tool design principles optimized for AI agents
- โAdvanced MCP: Transports and Patterns โ Explore advanced Model Context Protocol patterns
Module 0 โ Prompting Fundamentals
Build your first effective prompts from scratch with hands-on exercises.
Weekly AI Insights
Tools, techniques & news โ curated for AI practitioners. Free, no spam.
Free, no spam. Unsubscribe anytime.
โRelated Articles
FAQ
What is Tool Use in Claude?+
Tool Use allows Claude to call external functions or tools during a conversation. Claude decides when to use a tool, generates the correct parameters, and uses the result to formulate its response.
What are Claude's built-in tools?+
Claude has three built-in tools: Code Execution (run Python code in a sandbox), Text Editor (read and modify files), and Web Search (search the web in real time).
How do I define a custom tool for Claude?+
Define a tool with a name, description, and JSON schema of its parameters in the 'tools' field of your API request. Claude will call the tool when needed and you return the result via a tool_result message.
Can Claude use multiple tools in a single response?+
Yes, Claude can call multiple tools in parallel or sequentially within a single conversation. It can also chain the results of one tool as input to another.