# How to load agent tools on demand with the Gemini API

> When an agent has dozens of tools, sending every JSON schema on every turn burns tokens. Here's how Gemini's built-in tool_search and client-side Decisions API filtering work, tested across 50 real tools.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2026-12-06 | Topics: [AI](https://flaviocopes.com/tags/ai/) | Canonical: https://flaviocopes.com/gemini-dynamic-tool-retrieval/

If your agent only has 5 or 10 tools, you put every JSON parameter schema in the request and you're good to go.

But once you connect a billing system, a warehouse API, and a couple of [MCP servers](https://flaviocopes.com/what-is-mcp/), you end up with 50 or 100 tools, and most turns only need one of them.

Sending 50 full schemas on every turn burns thousands of input tokens before the user even says hello, and it makes tool selection noisier.

Google added **Dynamic Tool Retrieval** (via the `tool_search` tool) to the Gemini Interactions API in `v1beta`. If you're new to deferred schemas in general, see the [tool search](https://flaviocopes.com/ai-glossary/tool-search/) glossary entry.

Instead of sending every parameter schema upfront, you keep most tools on standby, and you load their full definitions only when a task calls for them.

I built a 50-tool catalog across 10 domains (billing, shipping, orders, accounts, inventory, support, CRM, analytics, notifications, and admin) and ran the same billing query against `gemini-4-hydrogen` in three setups: static loading, built-in server-side `tool_search`, and custom client-side retrieval backed by the [Gemini Decisions API](https://flaviocopes.com/gemini-decisions-api/).

## What I measured across 50 tools

Every test asked `gemini-4-hydrogen` the same question: `"Look up the billing history for user 123 and check if they have any unpaid invoices."` Each tool had a realistic description and four to five typed parameters.

| Mode | API turns | Turn 1 input tokens | Total model input tokens | Model output tokens | Decision 1 input tokens | Wall time |
| --- | ---: | ---: | ---: | ---: | ---: | ---: |
| Static (50 schemas) | 2 | 6,522 | 13,277 | 149 | 0 | 13.6 s |
| Server-side `tool_search` (3 loaded, 47 deferred) | 2 | 1,533 | 3,499 | 185 | 0 | 9.1 s |
| Client-side `tool_search` + Decision 1 | 3 | 129 | 1,826 | 181 | 3,469 | 12.2 s |

![Terminal output comparing static loading, server-side tool_search, and client-side Decisions API retrieval across 50 tools](https://images.flaviocopes.com/gemini-dynamic-tool-retrieval/retrieval-bench.webp?v=d46a65c6)

Two numbers stand out right away.

First, server-side `tool_search` cut total input tokens by 74% (from 13,277 down to 3,499) and finished 4.5 seconds faster than sending all 50 schemas, using the same two API turns.

Second, client-side retrieval with `gemini-decision-1` dropped Turn 1 on the main model down to 129 input tokens (a 98% drop) and cut total main-model input tokens by 86%. The search itself cost 3,469 input tokens on `gemini-decision-1` at $0.10 per 1M tokens and 0 output tokens.

## Two ways dynamic tool retrieval works

You pick between server-side search (zero retrieval code, one round trip) and client-side search (your own catalog, permissions, or custom ranker).

```mermaid
flowchart TB
  accTitle: Server-side vs client-side dynamic tool retrieval
  accDescr: In server-side retrieval Gemini searches deferred tools and calls the matching function in one turn. In client-side retrieval Gemini calls your search tool, your app scores an external catalog with Gemini Decision 1, and returns matching schemas in the function result.
  subgraph Server["Server-side tool_search"]
    S1["User prompt + 3 loaded tools + 47 deferred"] --> S2["Gemini searches and loads schema on server"]
    S2 --> S3["Returns function_call in same turn"]
  end
  subgraph Client["Client-side tool_search + Decision 1"]
    C1["User prompt + search_tool_registry only"] --> C2["Gemini calls search_tool_registry"]
    C2 --> C3["App scores 50 tools with gemini-decision-1"]
    C3 --> C4["App returns matching schemas in function_result"]
    C4 --> C5["Gemini calls the loaded function"]
  end
```

Dynamic tool retrieval does not add any extra cost on top of normal model pricing.

Deferred parameter schemas are not billed until the model loads them.

If you keep the `tools` list identical across turns, prompt caching stays in place.

## Setup

Install version 3.2 or later of the Google GenAI SDK and export your Gemini API key. In Node.js:

```bash
npm install @google/genai@latest
export GEMINI_API_KEY=your-key-here
```

In Python, install `google-genai`:

```bash
pip install -U google-genai
```

Both retrieval modes run on the `v1beta` Interactions API (`interactions.create`), the same endpoint behind the [Gemini API CLI](https://flaviocopes.com/gemini-api-cli/).

## Mode 1: built-in server-side retrieval

For most large tool sets, you'll want to start with server-side retrieval.

You add `{ type: 'tool_search' }` to `tools`, keep your 3 to 5 most common functions loaded normally, and mark the rest with `defer_loading: true`.

When `defer_loading` is `true`, Gemini strips the parameter schema from the initial prompt and only sees a one-line summary (around 26 tokens per tool, or fewer if you supply `short_description`):

```js
import { GoogleGenAI } from '@google/genai'

const ai = new GoogleGenAI({ apiVersion: 'v1beta' })

const tools = [
  { type: 'tool_search' },
  {
    type: 'function',
    name: 'get_user_profile',
    description: 'Read account metadata, plan tier, and team role.',
    parameters: {
      type: 'object',
      properties: { user_id: { type: 'integer' } },
      required: ['user_id']
    }
  },
  {
    type: 'function',
    name: 'get_billing_history',
    description: 'Retrieve past invoices, receipts, and payment status for a customer account.',
    short_description: 'Get customer invoices and payment history.',
    defer_loading: true,
    parameters: {
      type: 'object',
      properties: {
        user_id: { type: 'integer' },
        limit: { type: 'integer' }
      },
      required: ['user_id']
    }
  },
  {
    type: 'mcp_server',
    name: 'order_service',
    url: 'https://gemini-api-demos.uc.r.appspot.com/mcp',
    defer_loading: true
  }
]
```

Notice the remote MCP server at the end. Setting `defer_loading: true` on an `mcp_server` entry defers every tool exposed by that server without listing them one by one.

Be careful with one rule I hit right away while running my benchmark: you can only set `short_description` when `defer_loading: true` is also set on that tool. Leaving `short_description` on an always-loaded tool throws a 400 error:

```text
400 GenerateContentRequest.tools[1].function_declarations[10].short_description:
short_description can only be set if defer_loading is true
```

Strip `short_description` from your non-deferred tools before sending the array.

From there, your agent loop looks like normal function calling. Search, schema loading, and the function call happen inside one API call:

```js
let input = 'Look up the billing history for user 123 and check if they have any unpaid invoices.'
let prevId
let interaction

while (true) {
  interaction = await ai.interactions.create({
    model: 'gemini-4-hydrogen',
    previous_interaction_id: prevId,
    input,
    tools
  })
  prevId = interaction.id

  const calls = (interaction.steps ?? []).filter((s) => s.type === 'function_call')
  if (calls.length === 0) break

  input = calls.map((fc) => ({
    type: 'function_result',
    name: fc.name,
    call_id: fc.id,
    result: [{ type: 'text', text: JSON.stringify(runLocalTool(fc.name, fc.arguments)) }]
  }))
}

console.log(interaction.output_text)
```

Send the same `tools` array back on every turn so the prompt prefix stays cacheable.

### The same call in Python

In Python (`google-genai` 3.2 or later), pass `api_version` as `v1beta` and send the same `tool_search` and `defer_loading` dictionaries:

```python
from google import genai

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

tools = [
    {'type': 'tool_search'},
    {
        'type': 'function',
        'name': 'get_billing_history',
        'description': 'Retrieve past invoices, receipts, and payment status for a customer account.',
        'short_description': 'Get customer invoices and payment history.',
        'defer_loading': True,
        'parameters': {
            'type': 'object',
            'properties': {'user_id': {'type': 'integer'}},
            'required': ['user_id'],
        },
    },
]

interaction = client.interactions.create(
    model='gemini-4-hydrogen',
    input='Look up the billing history for user 123.',
    tools=tools,
)

calls = [s for s in (interaction.steps or []) if getattr(s, 'type', None) == 'function_call']
print([(c.name, c.arguments) for c in calls])
# [('get_billing_history', {'user_id': 123})]
```

## Mode 2: client-side retrieval with the Decisions API

Server-side retrieval expects all your tools to live in the request payload.

If your tools live in an external database, vary by user permissions, or need custom ranking logic, you can switch `tool_search` to `execution: 'client'`.

In this mode, you don't send your 50 tools in `tools` at all. You send one `tool_search` declaration with any name and parameters you want:

```js
const tools = [
  {
    type: 'tool_search',
    execution: 'client',
    name: 'search_tool_registry',
    description: 'Search the 50-tool catalog for billing, shipping, order, account, inventory, support, CRM, analytics, notification, or admin tools.',
    parameters: {
      type: 'object',
      properties: { query: { type: 'string' } },
      required: ['query']
    }
  }
]
```

When Gemini calls `search_tool_registry`, your app scores the external registry using [Gemini Decision 1](https://flaviocopes.com/gemini-decisions-api/) in one parallel request (up to 1,000 tools per call, 0 output tokens) and returns the matching full function schemas inside `function_result`:

```js
async function searchRegistryWithDecisions(query, registry, threshold = 0.35) {
  const questions = Object.fromEntries(
    Object.entries(registry).map(([name, schema]) => [
      name,
      {
        type: 'noul',
        instructions: `Is the tool '${name}' (${schema.description}) needed for this request?`
      }
    ])
  )

  const decision = await ai.decisions.create({
    model: 'gemini-decision-1',
    input: query,
    questions
  })

  return Object.entries(decision.answers ?? {})
    .filter(([, ans]) => ans.type === 'noul' && (ans.noul ?? 0) >= threshold)
    .sort((a, b) => b[1].noul - a[1].noul)
    .slice(0, 5)
    .map(([name]) => registry[name])
}
```

Then inside your loop, handle `search_tool_registry` by returning the matched tool objects directly in `result`:

```js
if (fc.name === 'search_tool_registry') {
  const query = String(fc.arguments?.query ?? '')
  const matches = await searchRegistryWithDecisions(query, registry)
  return {
    type: 'function_result',
    name: fc.name,
    call_id: fc.id,
    result: matches.length ? matches : [{ type: 'text', text: 'No matching tools found.' }]
  }
}
```

Here's the real three-turn trace from running `client-loop.mjs` against our 50-tool registry:

![Terminal output showing the 3-turn client-side tool retrieval loop scored by Gemini Decision 1](https://images.flaviocopes.com/gemini-dynamic-tool-retrieval/client-decisions-loop.webp?v=62b83b4d)

On Turn 1, `gemini-4-hydrogen` called `search_tool_registry({"query":"billing history unpaid invoices"})`. `gemini-decision-1` scored all 50 tools in 367 ms (3,470 input tokens, 0 output tokens) and injected 2 schemas: `get_billing_history` (0.96) and `get_company_account` (0.50).

On Turn 2, the main model saw those 2 schemas, called `get_billing_history({"user_id":123})`, and on Turn 3 wrote the final answer mentioning unpaid invoice `inv_914`.

The `tools` array stayed the same in every turn.

## When to use which mode

| Mode | Best for | Extra round trips | Remote MCP |
| --- | --- | --- | --- |
| Static loading | Under 20 stable tools | None | Supported |
| Server-side `tool_search` | 20+ fixed tools, zero retrieval code, lowest latency | None (1 API call) | Supported with `defer_loading` |
| Client-side `tool_search` + Decision 1 | External registries, per-user permissions, custom ranking | 1 per search | Handled in your app |

If you want to go deeper on how tool loops, prompt caching, and strict JSON schemas behave under load, see [structured outputs and few-shot examples](https://flaviocopes.com/structured-outputs-few-shot/) and my free [AI Fundamentals Handbook](https://flaviocopes.com/ebooks/ai-fundamentals-handbook/).

## How I would use it

I don't run a 50-tool production agent today, so I haven't put `tool_search` in front of live customer traffic yet. Most of my own scripts and coding workflows use fewer than ten tools, where static loading is simpler and faster to debug.

If I were building a multi-tenant support or ops agent with 30+ tools or multiple MCP servers, I would start with server-side `tool_search`, keep the 3 to 5 everyday tools loaded, and defer the rest. In my 50-tool test it cut input tokens by 74% and shaved 4.5 seconds off the run without writing a single line of search glue.

I would only move to client-side retrieval with `gemini-decision-1` when tools depend on the logged-in user's permissions or live in an external catalog that changes per workspace. That extra round trip is worth it when you need to filter out unauthorized tools before the model ever sees their schemas, and unnecessary when every user shares the same tool list.

For the full reference, see Google's [Dynamic tool retrieval guide](https://aistudio.google.com/learn/dynamic-tool-retrieval-gemini-api) and the [Gemini Decisions API tutorial](https://flaviocopes.com/gemini-decisions-api/).
