Back to all articles
8 MIN READ

Claude Tool Use: Code Execution, Text Editor & Web Search

By Learnia Team

๐Ÿ“… 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:

  1. โ†’Decide that a tool is needed to answer
  2. โ†’Generate the tool call parameters in JSON format
  3. โ†’Receive the result of the tool execution
  4. โ†’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:

CommandDescription
viewRead file contents
createCreate a new file
str_replaceReplace text in a file
insertInsert text at a given line

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 ValueBehavior
{"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

  1. โ†’Detailed descriptions โ€” Explain when and why to use the tool
  2. โ†’Documented parameters โ€” Each parameter should have a clear description
  3. โ†’Server-side validation โ€” Never trust parameters without validation
  4. โ†’Error handling โ€” Return clear error messages in tool_results
  5. โ†’Limit the number of tools โ€” 10-20 tools maximum for optimal performance
  6. โ†’Explicit names โ€” search_products rather than search or sp

Common Errors

ErrorCauseSolution
Claude doesn't use the toolInsufficient descriptionImprove the description with examples
Incorrect parametersAmbiguous schemaAdd description and enum to properties
Infinite loopNo stop conditionLimit the number of iterations in your loop
Missing tool_use_idMalformed resultEach tool_result must reference the correct tool_use_id

GO DEEPER โ€” FREE GUIDE

Module 0 โ€” Prompting Fundamentals

Build your first effective prompts from scratch with hands-on exercises.

Newsletter

Weekly AI Insights

Tools, techniques & news โ€” curated for AI practitioners. Free, no spam.

Free, no spam. Unsubscribe anytime.

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.