Claude Tool Use: Code Execution, Text Editor & Web Search
By Dorian Laurenceau
📅 Last reviewed: April 24, 2026. Updated with April 2026 findings and community feedback.
🔗 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
The honest read on tool use / function calling in 2026, from practitioners on r/LangChain, r/LocalLLaMA, and r/MachineLearning: tool use is where LLMs stop being chatbots and start being agents, and it's also where most production systems discover that agent loops are much harder to make reliable than single calls. The mechanics — Claude emits a JSON tool call, your code runs it, you pass the result back — are well-documented in the Anthropic tool use guide. What is under-documented is that every tool you expose is a new failure mode: wrong tool chosen, right tool with wrong arguments, tool execution error the model can't recover from, or (the classic) an infinite retry loop when the model doesn't understand why its last call failed.
Where the community correctly pushes back on "just give the agent every tool": tool-selection accuracy degrades quickly as the tool count rises. The Berkeley Function-Calling Leaderboard and the ToolBench research both show that models that are near-perfect on 3-5 tools fall off sharply past 15. The right answer is hierarchical tools (a dispatcher tool that routes to sub-tools), tight descriptions, and input schemas that are strict enough to refuse nonsense.
Pragmatic rule from engineers who've shipped agents without wake-up calls: start with three tools, log every tool call with its arguments and result, and only add a new tool when you have data showing the current set is insufficient. Every tool you add makes the ones you already have work slightly worse.
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"}
What Works Best
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 |
- →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.
Dorian Laurenceau
Full-Stack Developer & Learning DesignerFull-stack web developer and learning designer. I spent 4 years as a freelance full-stack developer and 4 years teaching React, JavaScript, HTML/CSS and WordPress to adult learners. Today I design learning paths in web development and AI, grounded in learning science. I founded learn-prompting.fr to make AI practical and accessible, and built the Bluff app to gamify political transparency.
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.