Skip to content
, ,

Gemini API Tool Retrieval: Load Only the Tools Your Agent Needs (Python Guide)

11–17 minutes
Shocked woman with locs in a white blazer at a tech conference holding a card with the Gemini logo, hook: Tool bloat fixed

Google added Tool Retrieval to the Gemini API on November 19, 2026, as a preview in the Interactions API. It lets an agent keep a big tool library while sending only the tool schemas it actually needs.

If your agent has dozens of functions or several MCP servers, every request pays for all those schemas. Tool Retrieval cuts that waste and can keep tool picking accurate as the library grows.

In this guide I walk through how it works, a full Python example, the token math, MCP setup, and how it compares with Anthropic and OpenAI.

TLDR

  • What: add a {"type": "tool_search"} tool and set defer_loading: True on rarely used tools.
  • Effect: the model sees only each deferred tool’s name and short description, then loads full schemas on demand.
  • Where: Interactions API only, v1beta, preview. Not in generateContent.
  • Models: Gemini 4 Carbon, Neon, Hydrogen, Argon, plus Gemini 3.8 Flash and 3.6 Flash.
  • Price: no extra fee. You pay normal token rates, including an extra internal search pass.
  • MCP: set defer_loading on an mcp_server tool to defer every tool on that server.

The Problem: Tool Bloat in Many-Tool Agents

With normal Gemini function calling, you send every function declaration with every request. Each one carries a name, a description and a JSON parameter schema.

That is fine for five tools. It hurts when you have 80 internal APIs or connect a few MCP servers that each expose 20 to 40 tools.

  • Cost: every schema is billed as input tokens on every turn, even if the model never calls it.
  • Accuracy: Google’s docs say that declaring many schemas upfront can reduce tool selection accuracy.
  • Context space: schemas eat room that your conversation, documents or code could use.
  • Caching: a big, changing tool list at the top of the prompt makes cache hits harder.

Anthropic’s own docs give a sense of scale. They say a typical setup with GitHub, Slack, Sentry, Grafana and Splunk servers can use about 55k tokens of definitions before the model does any work. Gemini has the same problem, and Tool Retrieval is Google’s answer.

How Gemini Tool Retrieval Works

You still send your whole tool library in the tools array. The difference is what the model sees in its context.

Server-side retrieval (the default)

  1. You add one search tool. Put {"type": "tool_search"} in the tools array.
  2. You mark tools as deferred. Set defer_loading: True on functions you rarely need. Keep your core tools undeferred.
  3. The model sees a short listing. For each deferred tool it sees the name plus the short_description (or the first sentence of the description), not the parameter schema.
  4. The model searches. When it needs a tool, it emits a tool_search_call step.
  5. The API loads schemas. Gemini returns the full declarations in a tool_search_result step.
  6. The model calls the function. You get a normal function_call step, run it, and send back a function_result.

All of this happens inside one API request. The steps show up in interaction.steps, and your code only has to execute the final function_call. There is no index to build or host.

Quick answer: Tool Retrieval is lazy loading for function schemas. The model reads a menu of tool names, picks what it needs, and only then gets the full parameter details.

Three ways to deliver tools

Google’s docs compare static loading with the two retrieval modes. Here is the summary.

Mode How schemas arrive Code you write Extra round trips Best for
Static (normal) All sent every request None None Fewer than 20 stable tools
Server-side retrieval Gemini loads on demand None None Large known libraries and MCP servers
Client-side retrieval Your app returns on demand Search, ranking, filtering One per search Dynamic registries, per-user tools

Supported Models, Limits and Pricing

Supported models

The blog post says Tool Retrieval works on “Gemini 3.6 and later models, including all Gemini 4 models.” The docs page lists these model IDs:

  • Gemini 4: gemini-4-carbon, gemini-4-neon, gemini-4-hydrogen, gemini-4-argon
  • Flash: gemini-3.8-flash, gemini-3.6-flash

A model outside this list returns an error saying deferred loading is not supported. If you are choosing a model, my Gemini 4 Neon guide covers where Neon sits in the family.

Key limits (preview)

  • API: Interactions API on v1beta only. The older generateContent method does not support it.
  • One search tool: only one tool_search entry per request.
  • No mixing: server-side and client-side retrieval cannot be combined in one request.
  • No unloading: once a schema loads, it stays in context for the rest of the conversation.
  • Resend tools: tool declarations are not stored between turns, so resend the full tools array every time, even with previous_interaction_id.
  • No-match behavior: a search with no match returns a text response, not a structured error.

Pricing

There is no separate charge. You pay the normal input, cached input and output rates of the model you call. Three things still add tokens:

  • Fixed block: enabling tool_search adds a small fixed block of input tokens.
  • Loaded schemas: each schema the model loads is billed as input for the rest of the conversation.
  • Search pass: each server-side search runs an extra internal model call, reported as total_tool_use_tokens and billed at the input rate.

Note: Google does not publish savings, accuracy or latency numbers for this preview. It recommends you measure against your own traffic. Field names may change before general availability.

Step-by-Step Python Tutorial

This example builds a small support agent with one core tool and several deferred ones. It follows the patterns in Google’s docs. If you are new to the SDK, start with my Gemini API Python tutorial.

  1. Install the SDK. The Interactions API needs google-genai version 2.3.0 or later. Run pip install -U google-genai.
  2. Set your key. Export GEMINI_API_KEY in your shell. The client picks it up automatically.
  3. Create a v1beta client. Tool Retrieval is a preview feature, so pass api_version in http_options.
  4. Declare tools. Add tool_search, keep core tools normal, and add defer_loading to the long tail.
  5. Call and read steps. Loop over interaction.steps and run any function_call.
  6. Send results back. Pass a function_result with previous_interaction_id and the same tools array.

Step 1: Client and tool library

import json
from google import genai

client = genai.Client(http_options={"api_version": "v1beta"})

def deferred(name, description, short, properties, required):
    return {
        "type": "function",
        "name": name,
        "description": description,
        "short_description": short,
        "defer_loading": True,
        "parameters": {
            "type": "object",
            "properties": properties,
            "required": required,
        },
    }

tools = [
    {"type": "tool_search"},
    # Core tool: always loaded, no search needed
    {
        "type": "function",
        "name": "orders_get_status",
        "description": "Get the status of a customer order by order ID.",
        "parameters": {
            "type": "object",
            "properties": {"order_id": {"type": "string"}},
            "required": ["order_id"],
        },
    },
    # Long tail: deferred
    deferred(
        "orders_issue_refund",
        "Issue a full or partial refund for an order.",
        "Orders: refund an order.",
        {"order_id": {"type": "string"}, "amount": {"type": "number"}},
        ["order_id", "amount"],
    ),
    deferred(
        "billing_convert_currency",
        "Convert an amount from one currency to another.",
        "Billing: convert currency.",
        {
            "amount": {"type": "number"},
            "from_currency": {"type": "string"},
            "to_currency": {"type": "string"},
        },
        ["amount", "from_currency", "to_currency"],
    ),
    # ...add dozens more deferred tools here
]

Notice the service prefixes (orders_, billing_). Google recommends prefixing related tools by service and naming the service early in short_description. That helps the model find the right group.

Step 2: Make the first call

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Refund 20 dollars on order A-1042.",
    tools=tools,
)

for step in interaction.steps:
    print(step.type)
# Typical sequence: tool_search_call, tool_search_result, function_call

Step 3: Run the function and reply

def orders_issue_refund(order_id, amount):
    # Call your real billing system here
    return {"order_id": order_id, "refunded": amount, "status": "ok"}

LOCAL_FUNCTIONS = {"orders_issue_refund": orders_issue_refund}

for step in interaction.steps:
    if step.type == "function_call":
        output = LOCAL_FUNCTIONS[step.name](**step.arguments)
        followup = client.interactions.create(
            model="gemini-4-hydrogen",
            previous_interaction_id=interaction.id,
            tools=tools,  # always resend the full array
            input=[{
                "type": "function_result",
                "name": step.name,
                "call_id": step.id,
                "result": [{"type": "text", "text": json.dumps(output)}],
            }],
        )
        print(followup.output_text)

Tip: check interaction.steps for function_call steps instead of relying on status. Google’s docs warn that status may not show requires_action when a call is returned.

Stateless mode (store=False)

If you manage history yourself with store=False, append every response step to your history unchanged. Keep the order and the signature fields.

The Python sample in the docs appends each step with model_dump(), then adds the function_result and calls create again with store=False, input=history and tools=tools. Dropping a tool_search_call or stripping signatures causes a 400 error.

Client-Side Retrieval With Your Own Registry

Server-side search covers most cases. Client-side mode is for when the tool list depends on the user, tenant or project, or when you want your own embeddings or ranking.

tools = [
    {
        "type": "tool_search",
        "execution": "client",
        "name": "search_tool_registry",
        "description": "Search tools. Namespaces: orders, billing, crm.",
        "parameters": {
            "type": "object",
            "properties": {
                "query": {"type": "string"},
                "namespace": {"type": "string"},
            },
            "required": ["query"],
        },
    },
]

When the model calls search_tool_registry, you run your lookup. Then you return matching declarations in a function_result, where each item is an object with type, name, description and parameters.

  • Bonus: retrieved tools do not need to be in the first tools array, so you can inject tools mid-conversation.
  • Cost: each search adds one round trip to your server.
  • Limit: defer_loading does not work in client mode, so do not set it.
  • Good habit: return objects, not JSON strings, and return a helpful category message when nothing matches.

Using Tool Retrieval With MCP Servers

MCP is where tool bloat gets worst, because one server can bring dozens of tools you did not write. With Gemini, you defer a whole remote MCP server with one flag.

tools = [
    {"type": "tool_search"},
    {
        "type": "mcp_server",
        "name": "github",
        "url": "https://your-mcp-server.example.com/mcp",
        "defer_loading": True,
    },
]

Every tool on that server now loads on demand. When the model calls one, the API runs it remotely and returns mcp_server_tool_call and mcp_server_tool_result steps in the same response.

This pairs well with a stack of servers from my best MCP servers list. You can keep GitHub, a database and a docs server connected without paying for every schema on every turn.

Warning: only connect MCP servers you trust. Deferring tools saves tokens, but it does not make a risky server safe. Treat tool outputs as untrusted input.

Token Savings Math

Google gives no official savings figure, so let us do the math with clear, made-up assumptions. Swap in your own numbers from the usage data.

Example assumptions

  • Library: 120 tools, 5 core and 115 deferred.
  • Full schema size: 400 tokens per tool on average.
  • Listing line: about 30 tokens per deferred tool (name plus short description).
  • Usage: each request loads 3 deferred schemas.
  • Price: $2.00 per million input tokens (Gemini 4 Argon’s introductory rate through November 30, 2026).
Item Static loading Tool Retrieval
Core tool schemas 5 x 400 = 2,000 5 x 400 = 2,000
Deferred tools 115 x 400 = 46,000 115 x 30 = 3,450
Loaded schemas 0 3 x 400 = 1,200
Tool tokens per request 48,000 6,650 + search pass + fixed block
Cost of tool tokens per 10,000 requests $960 about $133 + search cost

In this example, the schema part of each prompt shrinks by roughly 86 percent. The real saving is lower, because the internal search pass and the fixed block add tokens you cannot see in the table.

When retrieval does not pay off

  • Small libraries: with under 20 tools, static loading is often cheaper and simpler.
  • Search every turn: long chats that search on most turns pay the search pass again and again.
  • Cache minimum: deferring can shrink a prompt below the model’s implicit caching minimum, which may cost you cache discounts.

For more on cache behavior across vendors, see my guide to prompt caching for Claude, OpenAI and Gemini.

Gemini vs Anthropic vs OpenAI Tool Search

All three big API vendors now ship the same core idea with a defer_loading flag. The details differ.

Feature Gemini Tool Retrieval Anthropic tool search OpenAI tool search
Status Preview (Nov 2026) Stable Available in Responses API
API Interactions API, v1beta Messages API Responses API (also Agents API)
Search tool tool_search Regex or BM25 variants tool_search
Defer flag defer_loading defer_loading defer_loading
Client-side mode execution: "client" Custom tool returning tool_reference blocks execution: "client"
MCP defer_loading on mcp_server default_config on mcp_toolset defer_loading on server definition
Published limits No max tool count published 10,000 deferred tools, 5 results per search by default Fewer than 10 functions per namespace advised
Extra fee None, normal tokens None, loaded tools count as input No specific price given

A few small differences stand out. Anthropic requires at least one non-deferred tool and offers two search styles (regex and natural language). OpenAI adds namespaces, which group tools so one search can load a family.

OpenAI’s docs say only gpt-5.4 and later support tool_search in the Responses API. Anthropic lists support across its current Claude models, including Opus 5.5, Sonnet 5.5 and Haiku 5.5.

Best Practices From Google’s Docs

  • Keep core tools loaded: tools you use on most requests should not be deferred.
  • Defer the long tail: rare admin, reporting and edge-case tools are the best candidates.
  • Do not defer named tools: if your system instructions or other tool outputs mention a tool by name, keep it loaded.
  • Full schemas always: include complete parameter schemas for deferred tools, even though the model does not see them upfront.
  • Write good short descriptions: start with the service name, then the action.
  • Measure: compare input tokens and total_tool_use_tokens with and without retrieval on real traffic.

Troubleshooting Tool Retrieval Errors

These are the common errors listed in Google’s docs, in plain words. For general API errors, see my Gemini API errors fix guide.

Error (paraphrased) Cause Fix
Deferred loading requires a tool_search tool defer_loading set without server-side tool_search, or the follow-up request dropped it Include tool_search on every request, or remove defer_loading
Server side tool call context must be circulated A tool_search_call step was dropped in stateless mode, or a deferred tool was called without a search Replay search steps unchanged. Do not defer tools named in system instructions
Missing thought signature A replayed step lost its signature Append response steps exactly as returned
Deferred loading not supported for this model The model is not on the supported list Switch to a supported Gemini 4 or Flash model

Other common problems

  • Model answers in text instead of calling a tool: the search found no match. Improve the name and short_description of the tool you expected.
  • Tools vanish on turn two: you sent previous_interaction_id but not the tools array. Always resend it.
  • Loaded schemas disappear: in stateless mode you dropped the tool_search_result step. It does not error, but the schemas leave the context.
  • Feature not found: you are calling generateContent or not using v1beta. Switch to client.interactions.create with the v1beta client.

Frequently Asked Questions

What is Gemini API Tool Retrieval?

It is a preview feature that lets Gemini search your tool library and load only the function schemas it needs. Deferred tools show up as a short name and description until the model asks for them.

Does Tool Retrieval cost extra?

No. Google charges no separate fee, but loaded schemas, a small fixed block and the internal search pass are all billed at your model’s normal input rate.

Which Gemini models support Tool Retrieval?

The docs list Gemini 4 Carbon, Neon, Hydrogen and Argon, plus Gemini 3.8 Flash and Gemini 3.6 Flash. Other models return a deferred-loading error.

Can I use Tool Retrieval with generateContent?

No. It only works in the Interactions API on the v1beta version, using client.interactions.create in the Python SDK.

Does it work with MCP servers?

Yes. Set defer_loading to true on an mcp_server tool alongside a server-side tool_search, and every tool on that server loads on demand.

How many tools should I have before using it?

Google’s docs suggest static loading for fewer than 20 stable tools. Retrieval makes sense for large libraries where each request only uses a few tools.

Is it the same as Anthropic’s tool search?

The idea is the same and both use a defer_loading flag. The request formats, search methods, MCP setup and published limits differ, so code is not portable as-is.

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.

Shocked woman with locs in a white blazer at a tech conference holding a card with the Gemini logo, hook: Tool bloat fixed