Skip to content
,

Claude Tool Search Tool and Programmatic Tool Calling: Python Guide (2026)

12–19 minutes
Woman in a living room holding a tablet with a TOOL SEARCH card, hook 85% fewer tool tokens

Give Claude 200 tools and two things go wrong. The tool definitions eat tens of thousands of tokens before any work starts, and Claude gets worse at picking the right tool.

Anthropic’s answer is two API features that are now generally available: the tool search tool and programmatic tool calling. This guide shows both in Python, with real version strings, prices, limits and error messages.

TLDR

  • Tool search: add tool_search_tool_regex_20251119 or tool_search_tool_bm25_20251119, then mark big tool groups with defer_loading: true. Anthropic says it typically cuts tool-definition tokens by over 85%.
  • Programmatic tool calling: add the code_execution_20260120 tool and set allowed_callers on your tools. Claude writes Python that calls them in a sandbox, and only the final output reaches its context.
  • Tool use examples: the input_examples field is real and GA. Each example costs about 100-200 input tokens.
  • Status: all three need no beta header since 17 February 2026. I checked the docs on 4 December 2026 with the anthropic Python SDK 2.17.0.
  • Cost: tool search is not billed as a separate tool. Programmatic calling uses code execution pricing: 1,550 free hours per month, then $0.05 per container hour.

The Problem With Large Tool Sets

Normal tool use puts every tool definition into the prompt on every request. That is fine for five tools. It breaks down when you connect several MCP servers or a big internal API.

Anthropic’s tool search docs name two problems:

  • Context bloat: a typical setup with GitHub, Slack, Sentry, Grafana and Splunk can use about 55,000 tokens in definitions before Claude does any work.
  • Worse tool choice: Claude’s ability to pick the right tool drops once you pass 30 to 50 tools.

There is also a third cost that the programmatic tool calling docs focus on. Every tool call is a round trip through the model, and every raw result lands in the context window, even when Claude only needs one number from it.

Quick answer: use tool search when you have many tools but only a few matter per request. Use programmatic tool calling when one task needs many tool calls or returns big results that should be filtered first. You can use either one alone.

Current Version Strings and GA Status

Both features launched in beta on 24 November 2025. Anthropic’s release notes say the beta headers were dropped on 17 February 2026. Here is what exists today.

Feature Type / field Status (Dec 2026) Beta header?
Tool search (regex) tool_search_tool_regex_20251119, name tool_search_tool_regex GA No
Tool search (BM25) tool_search_tool_bm25_20251119, name tool_search_tool_bm25 GA No
Deferred loading defer_loading: true on a tool GA No
Programmatic tool calling allowed_callers + code execution code_execution_20260120 or later GA No
Code execution (newer) code_execution_20260521 (adds the 90-second cell limit to the tool description) GA No (Go SDK still uses its beta path)
Tool use examples input_examples array on a tool GA No

Nothing has been renamed or retired. The examples use the current API version 2026-10-21 and the model claude-opus-5-5.

Claude docs Limits section for the tool search tool showing 10,000 deferred tools per request and 5 search results by default
Official Claude tool search tool docs, Limits section (checked 4 Dec 2026).

Prerequisites and Setup

You need a Claude Console account with API access, Python 3.10 or newer, and the official SDK. If you are new to tools, read my Claude tool use tutorial first, because both features build on the same tool_use and tool_result loop.

  1. Install the SDK. Run pip install -U anthropic. Version 2.17.0 (3 December 2026) is current and needs Python 3.10+.
  2. Get a key or sign in. Create a key in the Claude Console, or use ant auth login on your own machine. See how to get a Claude API key.
  3. Set the key as an environment variable. Use export ANTHROPIC_API_KEY=... on macOS or Linux. Never paste the key into code.
  4. Pick a supported model. Tool search works on every current model, including Haiku 4.5. Programmatic calling works on Opus 4.5 and later, Sonnet 4.6 and later, Haiku 5.5, Fable and Mythos, but not Haiku 4.5.
  5. Measure your baseline. Count the tokens of your current tool list with the Claude token counting API, so you can see the savings later.

Tool search is a server-side tool. Anthropic runs the search, so you write no search code. You still send every tool definition on every request.

How it works

  1. You add a tool search tool to tools.
  2. You set defer_loading: true on tools that should not load up front.
  3. Claude starts with only the search tool and any non-deferred tools in context.
  4. When it needs more, it searches. The API returns tool_reference blocks (5 by default).
  5. The API expands those references into full definitions, and Claude calls them.

Regex or BM25?

Variant What Claude writes Max length Best for
Regex A Python re.search() pattern, case-insensitive, such as github_.* 200 characters Tools with consistent name prefixes
BM25 A natural language query, such as “send a chat message” 500 characters Messy catalogs with descriptive text

Both variants search tool names, descriptions, argument names and argument descriptions. Claude can set a limit from 1 to 10,000 in its search input.

Rules for defer_loading

  • Never defer the search tool itself. At least one tool must stay non-deferred.
  • Keep 3-5 favourites loaded. Your most-used tools should be non-deferred so Claude can call them without searching.
  • No cache_control on deferred tools. Put your cache breakpoint on a non-deferred tool.
  • MCP tools: set defer_loading on the mcp_toolset entry’s default_config or configs, not per tool.

Tip: Prefix tool names by service (github_, slack_, jira_). One regex search then pulls in the whole group, which the docs recommend.

Example 1: Tool Search With a Full Loop (Python)

This script defines six tools. Only get_weather and the search tool load up front. The rest are deferred and found by BM25 search.

import json
import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY

def schema(props, required):
    return {"type": "object", "properties": props, "required": required}

TOOLS = [
    {"type": "tool_search_tool_bm25_20251119", "name": "tool_search_tool_bm25"},
    {   # a frequently used tool stays loaded
        "name": "get_weather",
        "description": "Get the current weather for a city.",
        "input_schema": schema({"city": {"type": "string"}}, ["city"]),
    },
    {
        "name": "github_list_prs",
        "description": "List open pull requests in a GitHub repository.",
        "input_schema": schema({"repo": {"type": "string", "description": "owner/name"}}, ["repo"]),
        "defer_loading": True,
    },
    {
        "name": "github_create_issue",
        "description": "Create a new issue in a GitHub repository.",
        "input_schema": schema({"repo": {"type": "string"}, "title": {"type": "string"}}, ["repo", "title"]),
        "defer_loading": True,
    },
    {
        "name": "slack_send_message",
        "description": "Send a chat message to a Slack channel.",
        "input_schema": schema({"channel": {"type": "string"}, "text": {"type": "string"}}, ["channel", "text"]),
        "defer_loading": True,
    },
    {
        "name": "jira_create_ticket",
        "description": "Create a Jira ticket in a project.",
        "input_schema": schema({"project": {"type": "string"}, "summary": {"type": "string"}}, ["project", "summary"]),
        "defer_loading": True,
    },
]

# Fake handlers so the example runs end to end
HANDLERS = {
    "get_weather": lambda city: json.dumps({"city": city, "temp_c": 18}),
    "github_list_prs": lambda repo: json.dumps([{"number": 42, "title": "Fix login bug"}]),
    "github_create_issue": lambda repo, title: json.dumps({"number": 101}),
    "slack_send_message": lambda channel, text: json.dumps({"ok": True}),
    "jira_create_ticket": lambda project, summary: json.dumps({"key": project + "-7"}),
}

messages = [{"role": "user", "content": "List open PRs in acme/web, then post a summary to #dev on Slack."}]

while True:
    resp = client.messages.create(
        model="claude-opus-5-5",
        max_tokens=4096,
        tools=TOOLS,          # send the full list every time
        messages=messages,
    )
    # keep server_tool_use and tool_search_tool_result blocks unchanged
    messages.append({"role": "assistant", "content": resp.content})

    if resp.stop_reason == "pause_turn":
        continue              # server tool paused, just resend
    if resp.stop_reason != "tool_use":
        break

    results = []
    for block in resp.content:
        if block.type == "tool_use":   # only YOUR tools, never srvtoolu_ ids
            output = HANDLERS[block.name](**block.input)
            results.append({"type": "tool_result", "tool_use_id": block.id, "content": output})
    messages.append({"role": "user", "content": results})

for block in resp.content:
    if block.type == "text":
        print(block.text)

In the response you will see a server_tool_use block (the search), a tool_search_tool_result block with tool_references, and then normal tool_use blocks. You only answer the tool_use blocks.

Note: Do not send a tool_result for a srvtoolu_... id. The API rejects it. Discovered tools stay available in later turns, so Claude does not need to search again.

Bring your own search

You can also run your own search, for example with embeddings. Make a normal custom tool, and return tool_reference blocks in its tool_result content, like {"type": "tool_reference", "tool_name": "github_list_prs"}. Each referenced tool must still be in tools, usually deferred.

Programmatic Tool Calling Explained

With programmatic tool calling (PTC), Claude writes a Python script instead of calling tools one by one. The script runs in Anthropic’s code execution container and calls your tools as async functions.

Here is the flow:

  1. Claude writes code such as rows = json.loads(await query_database({"sql": "..."})).
  2. When the code calls your tool, the container pauses and the API returns a tool_use block with a caller field.
  3. You run the tool and send back a tool_result. The result goes to the running code, not into Claude’s context.
  4. When the script finishes, Claude sees only its printed output.

The allowed_callers field

  • ["direct"]: normal tool use. This is the default.
  • ["code_execution_20260120"]: Claude is guided to call it only from code.
  • Both values: Claude may do either. The docs suggest picking one per tool for clearer guidance.

code_execution_20260120 and code_execution_20260521 are interchangeable in allowed_callers. Response blocks always tag the caller as code_execution_20260120.

Warning: allowed_callers is guidance, not a security boundary. Your code should still handle a direct call to any tool you define, and should validate results that might be run as code.

Example 2: Programmatic Tool Calling in Python

This loop lets Claude query a sales database for several regions in one script. Note the container id: it is required on every request while a programmatic call is waiting.

import json
import anthropic

client = anthropic.Anthropic()

SALES = {"West": 120000, "East": 98000, "Central": 143000}

def query_database(sql):
    # demo only: return a row per region named in the SQL
    rows = [{"region": r, "revenue": v} for r, v in SALES.items() if r in sql]
    return json.dumps(rows)

TOOLS = [
    {"type": "code_execution_20260120", "name": "code_execution"},
    {
        "name": "query_database",
        "description": (
            "Run a SQL query on the sales database. "
            "Returns a JSON list of rows like [{'region': str, 'revenue': int}]."
        ),
        "input_schema": {
            "type": "object",
            "properties": {"sql": {"type": "string", "description": "SQL query"}},
            "required": ["sql"],
        },
        "allowed_callers": ["code_execution_20260120"],
    },
]

messages = [{"role": "user", "content": "Get revenue for West, East and Central, one query each, and tell me the top region."}]
container_id = None

while True:
    extra = {"container": container_id} if container_id else {}
    resp = client.messages.create(
        model="claude-opus-5-5",
        max_tokens=8192,
        tools=TOOLS,            # same tools array on every request
        messages=messages,
        **extra,
    )
    if getattr(resp, "container", None):
        container_id = resp.container.id
    messages.append({"role": "assistant", "content": resp.content})

    if resp.stop_reason == "pause_turn":
        continue
    if resp.stop_reason != "tool_use":
        break

    results = []
    for block in resp.content:
        if block.type == "tool_use" and block.name == "query_database":
            print("caller:", block.caller.type)   # code_execution_20260120
            results.append({
                "type": "tool_result",
                "tool_use_id": block.id,
                "content": query_database(**block.input),
            })
    # ONLY tool_result blocks here, no text
    messages.append({"role": "user", "content": results})

print(resp.content[-1].text)

Three rules matter when you return results to a paused script:

  • Only tool_result blocks: the user message can’t contain any text.
  • Text-only content: each result must be a string or text blocks. Images and documents are rejected.
  • Answer fast: a pending call times out after about 4 minutes and raises a TimeoutError inside Claude’s code.

Tip: Describe your tool’s output format in the description (JSON fields and types). Claude parses results in code, so a clear format means fewer broken scripts.

Example 3: The input_examples Field

Yes, “tool use examples” is a real, GA field. Add input_examples to a tool to show Claude valid inputs. It helps most with nested objects, optional fields and format-sensitive values.

import anthropic

client = anthropic.Anthropic()

response = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=1024,
    tools=[{
        "name": "get_weather",
        "description": "Get the current weather in a given location",
        "input_schema": {
            "type": "object",
            "properties": {
                "location": {"type": "string", "description": "City and state, e.g. San Francisco, CA"},
                "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
            },
            "required": ["location"],
        },
        "input_examples": [
            {"location": "San Francisco, CA", "unit": "fahrenheit"},
            {"location": "Tokyo, Japan", "unit": "celsius"},
            {"location": "New York, NY"},   # unit is optional
        ],
    }],
    messages=[{"role": "user", "content": "What's the weather in San Francisco?"}],
)
print(response.content)
  • Must match the schema: an invalid example usually returns a 400 error. Some schemas, such as ones with a pattern, skip the check.
  • Token cost: about 100 tokens for a flat example and about 200 for a nested one.
  • Works with tool search: when Claude discovers a deferred tool, its examples load with it.

Example 4: Tool Search With curl

The raw HTTP shape is the same. This request uses the regex variant with one deferred tool and one loaded tool.

curl https://api.anthropic.com/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2026-10-21" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-opus-5-5",
    "max_tokens": 2048,
    "messages": [{"role": "user", "content": "What is the weather in Paris?"}],
    "tools": [
      {"type": "tool_search_tool_regex_20251119", "name": "tool_search_tool_regex"},
      {"name": "search_files", "description": "Search files in the workspace",
       "input_schema": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}},
      {"name": "get_weather", "description": "Get the weather at a location",
       "input_schema": {"type": "object", "properties": {"location": {"type": "string"}}, "required": ["location"]},
       "defer_loading": true}
    ]
  }'

Token Savings and Pricing

What Anthropic reports

  • Tool search: typically cuts tool-definition tokens by over 85%, loading only the 3-5 tools a request needs.
  • PTC, 75-tool agent benchmark: about 38% fewer billed input tokens with no change in accuracy.
  • PTC, production traffic with 10-49 tools: typical savings of 20-40%.
  • PTC, simple sequential tasks: on τ²-bench it cost about 8% more with no score gain. Not every workload benefits.
  • PTC on agentic search: about 11% better scores with 24% fewer input tokens on BrowseComp and DeepSearchQA.
Claude docs Token efficiency section for programmatic tool calling showing 38 percent fewer input tokens and 20 to 40 percent typical savings
Official Claude programmatic tool calling docs, Token efficiency section (checked 4 Dec 2026).

What you pay

Item Price
Tool search tool No separate fee. Loaded definitions count as normal input tokens.
Programmatic tool calling Code execution pricing: 1,550 free hours per org per month, then $0.05 per container hour (5-minute minimum)
Results from programmatic calls Not counted as input or output tokens. Only the final code output and Claude’s reply count.
Claude Opus 5.5 $4 input / $20 output per million tokens (cache reads $0.20)
Claude Sonnet 5.5 $2 input / $10 output per million tokens
Claude Haiku 5.5 $0.10 input / $0.50 output per million tokens (prompts up to 100K)
Tool use system prompt 286 tokens on Opus 5.5, Sonnet 5.5 and Haiku 5.5

Worked cost example

Take the docs’ 55,000-token multi-server setup on Opus 5.5 at $4 per million input tokens. Loading all definitions costs about $0.22 per request before any work.

Now apply the “over 85%” figure. At an 85% cut you load about 8,250 tokens, or about $0.033 per request. Over 10,000 requests that is roughly $2,200 versus $330, before prompt caching.

Your real numbers depend on your tools, so measure with the token counting API. My Claude API pricing guide and prompt caching guide cover the other levers.

Limits and Platform Support

Limit Tool search Programmatic tool calling
Max tools 10,000 deferred tools per request Normal tool limits
Per call 5 results by default, limit 1-10,000 About 4 minutes to answer a paused call; 90 seconds per Python cell
Query size 200 chars (regex), 500 chars (BM25) Not applicable
Containers Not applicable Expire 30 days after creation; checkpointed after about 5 minutes idle
Not compatible with cache_control on a deferred tool strict: true, disable_parallel_tool_use, forcing via tool_choice, MCP connector tools, computer and browser toolsets, recursive $ref schemas
Platforms Claude API, Bedrock (InvokeModel only, not Converse), Claude Platform on AWS, Google Cloud (both kinds), Microsoft Foundry Claude API, Claude Platform on AWS, Google Cloud (Anthropic managed), Foundry hosted on Anthropic
Zero data retention Eligible (except Covered Models) Not eligible (container data kept up to 30 days)
Managed Agents Not available Not available

Tool search also works with the Message Batches API. On the newest models (Opus 5.5, Sonnet 5.5, Fable 5.2), forced tool_choice returns a 400 anyway, so use auto.

Troubleshooting: Real Error Messages and Fixes

Error or symptom Cause Fix
400: “At least one tool must have defer_loading=false. All tools cannot be deferred.” Every tool, maybe the search tool too, is deferred Remove defer_loading from the search tool
400: “Tool reference ‘unknown_tool’ not found in available tools” A tool_reference names a tool missing from tools Send every searchable tool’s full definition on every request
200 with tool_search_tool_result_error, code invalid_tool_input Bad regex or pattern over 200 characters Usually Claude retries. Use BM25 if patterns keep failing
Error codes unavailable or too_many_requests Search timed out, or rate limit on searches Retry with backoff. See Claude 429 and 529 fixes
Claude can’t find a tool Words in the query don’t appear in the tool’s name or descriptions Add the keywords users say to descriptions; test with re.search(pattern, text, re.IGNORECASE)
400 invalid_request_error on tool_choice tool_choice names a tool without "direct" in allowed_callers Add "direct", or drop the tool from tool_choice
400 containing “Circular $ref detected” Recursive schema on a programmatic tool Keep that tool direct-only, or unroll the recursion
Request rejected while a call is pending Missing container id, or text next to the tool results Pass the container id and send only tool_result blocks
stderr: “TimeoutError: Calling tool […] timed out” Your tool took longer than about 4 minutes Speed up the tool or split the work into smaller calls

Frequently Asked Questions

Is the Claude tool search tool still in beta?

No. Tool search, tool use examples and programmatic tool calling have needed no beta header since 17 February 2026. The current type strings are tool_search_tool_regex_20251119 and tool_search_tool_bm25_20251119.

Do I still send deferred tools in every request?

Yes. defer_loading controls what enters Claude’s context, not what you send. The API needs every definition to run the search and expand the results.

Does tool search cost extra?

There is no separate tool search fee. The definitions it loads count as normal input tokens, like any other tool.

Which models support programmatic tool calling?

Opus 4.5 and later, Sonnet 4.6 and later, Haiku 5.5, and the Fable and Mythos models. Haiku 4.5 accepts the code execution tool but not programmatic calling.

Can I use tool search with MCP servers?

Yes. With the MCP connector, set defer_loading on the mcp_toolset entry’s default_config or per tool in configs. MCP connector tools can’t be called programmatically, though.

When does programmatic tool calling not help?

It helps least with a few small, strictly sequential calls. Anthropic measured about 8% higher cost on τ²-bench, where each turn makes one or two calls.

Is programmatic tool calling covered by zero data retention?

No. It runs on code execution containers, which keep data for up to 30 days. Tool search is ZDR eligible, except for Covered Models.

Sources

Free weekly email

Get new AI guides every week

One short weekly email with our newest local AI, ComfyUI and AI tool guides. No spam, no pop-ups, just the good stuff.

Free. Unsubscribe anytime in one click. We only use your email to send this newsletter. See our privacy policy.

Woman in a living room holding a tablet with a TOOL SEARCH card, hook 85% fewer tool tokens