# Gemini Tool Retrieval + Code Mode: Cut Agent Tokens by 95%

> Source: <https://www.mindstudio.ai/blog/gemini-tool-retrieval-code-mode/>
> Published: 2026-12-01 00:00:00+00:00

**Recommendation:** For agents with large or dynamic tool catalogs, defer full tool schemas behind retrieval and run tool calls in a sandboxed code-mode program so only final results enter context; the source measured a drop from about 564K to 30K tokens.
More in the playbook "Controlling LLM cost": <https://wpnews.pro/playbooks/llm-cost>

# Gemini Tool Retrieval + Code Mode: Cut Agent Tokens by 95%

How combining Gemini's deferred tool loading with code mode execution can shrink agent context usage from 564K to roughly 30K tokens.

## What is Gemini tool retrieval and why does it matter for agents?

Gemini tool retrieval is a feature in the Gemini API that lets a model search for the specific tools it needs instead of loading every connected tool’s full definition into context on every request. Agents connected to multiple MCP servers often end up with hundreds of available tools, and each one carries a name, description, and parameter schema that sits in the context window before the model even reads the user’s task. Tool retrieval defers most of that weight: the model sees short names and descriptions upfront, and only pulls in full parameter definitions for the tools it actually decides to use.

## TL;DR

- **Tool definitions alone can eat tens of thousands of tokens** before an agent even starts working, and that cost scales with every MCP server connected.
- **Tool selection accuracy drops as the tool list grows** , a problem that persists even with frontier models and large context windows.
- **Code mode has the agent write a program that calls tools inside a sandbox** , so only final results, not raw intermediate data, return to the model’s context.
- **Gemini’s tool retrieval adds a missing discovery step to code mode** by letting the model search for and load only the tool definitions it needs, inside a single API request.
- **A demo task run three ways went from about 564,000 input tokens (all tools loaded) to 326,000 (tool retrieval alone) to roughly 30,000 (both combined)** , with the same correct output each time.
- **Google’s file slicing applies the same philosophy to documents** , letting an agent load a single PDF page or spreadsheet range instead of an entire file.
- **Neither technique is universally necessary** : small, stable tool sets (fewer than 20, per Google’s own guidance) are often cheaper to load upfront thanks to prompt caching.

### Workers wait for instructions. Contractors deliver the outcome.

Describe what you need. **Remy** builds it, secures it and hands it over running.

## Why do AI agents waste so many tokens on tools?

Every tool an agent can call, whether it’s a CRM lookup, a Slack poster, or a ticketing API, needs a definition that tells the model what the tool does and what parameters it accepts. In a normal setup, all of that gets sent to the model on every single request, regardless of whether the task needs it. Connect a handful of MCP servers and that overhead compounds fast, sometimes consuming a meaningful chunk of a model’s context window before any actual work happens.

There’s a second, often bigger, source of waste: intermediate results. If an agent has to count open support tickets from a paginated API, the naive approach pulls every page of raw ticket data into the model’s context just to extract a handful of numbers. The model reads thousands of tokens of JSON to produce four integers. That pattern repeats across almost any data-heavy agent task, and it’s the one tool retrieval alone doesn’t fix.

Beyond the raw token cost, there’s an accuracy cost too. As the number of available tools grows, models get worse at picking the right one, even frontier models with large context windows. Dumping the entire tool catalog into context isn’t just expensive, it actively makes the agent less reliable.

## How does code mode reduce agent token usage?

Code mode (also called “code execution with MCP” by some vendors) exposes tools as callable functions in a programming language rather than as direct function calls the model invokes one at a time. Instead of the model calling a tool and receiving raw data back into its context, it writes a small program that calls the tools, runs loops, filters, and joins, and only prints the final answer. That program executes in a sandboxed environment, a locked-down separate process, and only what it explicitly outputs flows back to the model.

This is powerful because it moves the data-heavy work out of the model’s context entirely. A task that would otherwise require paging through hundreds of ticket records now just returns four numbers. Cloudflare and Anthropic both ship versions of this pattern under different names, but the mechanics are the same: tools become code-callable functions, and a sandbox absorbs the intermediate data.

The catch is that code mode still needs a discovery step. The model has to know the exact names and parameters of the tools available before it can write a program that calls them correctly. Different frameworks solve this differently: Anthropic’s approach has the agent browse a folder of tool files, Cloudflare added explicit search and describe functions. Google’s tool retrieval slots directly into this gap.

## How does Gemini’s tool retrieval work under the hood?

Setting it up involves adding one special entry, a tool search function, to the agent’s tool list, and flagging the tools you want held back with a “deferred loading” marker. Deferred tools show the model only their name and a short description at first. The full parameter schema stays hidden until the model explicitly asks for it.

### Build a credit limitreview app for800 relationshipmanagers

One prompt. Role-based access, audit trail and SSO come built in.

When the model decides it needs a tool, three steps happen inside a single API request, without extra round trips from the application:

1. The model issues a tool search call naming the function(s) it’s looking for.
2. The API returns the full definition of those tools, loading them into the conversation.
3. The model then makes the actual function call, which the application executes as normal.

This keeps the standing cost of tool availability low while still letting the model access anything it needs, on demand, within one request cycle.

## How do you combine tool retrieval and code mode in one agent?

The two techniques fix different halves of the same problem: tool retrieval controls which tool definitions the model knows about, and code mode controls where the actual work and data processing happens. Wiring them together means deferring essentially all tools except one: a “run code” tool that’s always loaded and executes a program in a sandbox.

The flow looks like this: the agent uses tool search to pull in only the handful of tool definitions a task requires, then writes a program against those tools, and the sandbox makes the actual API calls. The critical piece is a short standing instruction in the system prompt telling the model to read parameters via tool search but make the actual calls inside a program, rather than invoking tools one at a time directly. Without that instruction, nothing stops the model from calling loaded tools directly, which pulls raw results straight back into context and defeats the purpose.

In a demonstrated test task (counting open tickets from specific customers across two paginated APIs and posting results to Slack), three variations of the same agent produced identical correct answers with very different token costs: roughly 564,000 input tokens with all tools loaded normally, about 326,000 with tool retrieval alone, and around 30,000 with tool retrieval and code mode combined. Tool retrieval cut the up-front definition cost; code mode cut the ongoing cost of ticket data flowing through context on every page.

## Is tool retrieval or code mode always worth using?

Not always. For small, stable tool sets, loading everything upfront can actually be cheaper and simpler, largely because of how prompt caching works. Google’s own guidance suggests that below roughly 20 tools that don’t change often, deferred loading may not pay off. A reasonable rule of thumb: keep the tools used on nearly every request loaded normally, and defer the long tail of occasional, specialized tools.

Code mode adds its own operational considerations. Any tool that changes state, like posting a Slack message or updating a database record, probably needs an approval step before the sandboxed program executes it. Prefixing tool names by service (CRM, support, billing) also helps the model navigate a growing tool catalog, and a production sandbox should be a properly isolated environment like a dedicated container, not a lightweight demo process with a timeout.

### Build a claims

triage app for

4,000 insurance

adjusters

One prompt. Role-based access, audit trail and SSO come built in.

There are also hard constraints to know. Tool retrieval is currently in preview and tied to a specific API surface. Once a tool gets loaded in a conversation, it stays loaded for the rest of that session, and the full tool list has to be resent on return requests. Google’s documentation also advises against deferring any tool that’s explicitly named in the system prompt, since the model needs immediate awareness of it.

## What is file slicing and how does it relate to these techniques?

File slicing applies the same underlying idea, load only what’s needed, to large documents rather than tool catalogs. Instead of sending an entire PDF or spreadsheet into context, the API lets an agent specify which pages or cell ranges to load. In one demonstrated example, an agent needed a single number from a chart buried in a long annual report. Rather than loading the full document, it found the relevant page via a contents listing and loaded just that page as an image, using a few thousand tokens instead of the hundreds of thousands a full-document load would require.

One limitation worth noting: a text-only slice can’t “see” visual elements like charts. If the answer lives inside a graphic rather than in extractable text, the agent needs to load that specific page as an image rather than as plain text.

## Frequently Asked Questions

### What’s the difference between tool retrieval and code mode?

Tool retrieval controls which tool definitions the model loads into context, deferring most of them until they’re actually needed. Code mode controls where tool execution happens, running the actual API calls and data processing inside a sandbox so only final results return to the model. They solve different parts of the token problem and work best combined.

### Does tool retrieval require extra API calls or round trips?

No. The search, definition loading, and actual function call all happen within a single API request cycle, so the application doesn’t need to manage additional round trips to support deferred loading.

### When should I not bother with deferred tool loading?

If your agent has a small, stable set of tools, roughly under 20 according to Google’s guidance, loading them all upfront can be cheaper and simpler thanks to prompt caching. Deferred loading pays off most when tool catalogs are large or change frequently.

### Can code mode work without tool retrieval?

Yes, but the agent still needs some way to discover tool names and parameters before writing code against them. Different frameworks solve this discovery step differently (browsing tool files, search and describe functions); tool retrieval is simply Google’s built-in version of that same discovery mechanism.

### Is this approach specific to Gemini, or does it generalize?

The specific tool retrieval implementation described here is a Gemini API feature currently in preview. The broader pattern, deferring tool definitions and running code in a sandbox to keep raw data out of context, is a general architecture used across multiple frameworks under different names, including Cloudflare’s “code mode” and Anthropic’s “code execution with MCP.”
