Getting Started·
advanced
·14 min read·Nov 20, 2026·Updated Nov 24, 2026
·Independent maintainer·Verification Charter

Gemini 4 MCP: Deferred Tool Retrieval

Connect Gemini 4 to remote MCP servers with tool_search and defer_loading on the Interactions API. Covers Streamable HTTP, signatures, and exact error messages.

MCPGemini 4GoogleGenAIAntigravityintegrationStreamable HTTPtool-search
Interactive Tool
1-Click Export

Generate & Validate Multi-Client MCP Config

One-click export with environment variables & path locators for Claude Desktop, Cursor, Windsurf, and OpenAI Codex CLI.

Open in Generator

Gemini 4 MCP: Deferred Tool Retrieval on the Interactions API

A dozen MCP tool schemas with full JSON parameter definitions consume tens of thousands of input tokens on every request. Tool selection accuracy drops as the candidate list grows, so adding a second remote server can make an agent worse even though it knows more. Google shipped two things in the Gemini 4 generation that address this directly: four generally available models with 1M-token context windows, and a preview tool retrieval mechanism that loads only the schemas the model actually needs.

Tool retrieval requires the Interactions API on v1beta. The generateContent method does not support it. Everything below targets that API version and the four GA Gemini 4 endpoints.

Which Gemini 4 model should call your MCP tools

All four models accept text, image, audio, video, and PDF input, carry a 1M-token context window, and allow 64K tokens of output with a 1M-token ceiling for long decodes. The difference is cost and reasoning depth.

ModelEndpointGA datePaid input / output per 1M tokensMCP fit
Gemini 4 Carbongemini-4-carbon2026-11-10$2.00 / $10.00 introductory through 2026-11-30Sustained agentic coding and multi-step tool chains
Gemini 4 Neongemini-4-neon2026-11-18$3.00 / $15.00Frontier reasoning with fast end-to-end task completion
Gemini 4 Hydrogengemini-4-hydrogen2026-11-12Free tier, then $1.50 / $7.50Default model for the Antigravity agent; everyday tool workloads
Gemini 4 Argongemini-4-argon2026-10-13See current pricingLower token spend per turn than Carbon for the same agentic tasks

Carbon, Neon, and Hydrogen are the practical choices for MCP-heavy work. Neon and Hydrogen expose a fourth xhigh thinking level alongside low, medium, and the default high. Use xhigh when a tool chain requires long planning before execution, and medium or low when the agent mostly dispatches lookups.

Tool retrieval is supported on all four Gemini 4 endpoints and on gemini-3.8-flash and gemini-3.6-flash. A request that sets defer_loading on an unsupported model returns deferred loading is not supported for this model.

Connect a remote MCP server

Remote MCP in the Interactions API takes a tool descriptor rather than a subprocess. The descriptor has type, name, url, and optional headers and allowed_tools fields:

python
import os
from google import genai

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

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Check the weather in San Francisco.",
    tools=[
        {
            "type": "mcp_server",
            "name": "weather_service",
            "url": "https://gemini-api-demos.uc.r.appspot.com/mcp",
            "headers": {"Authorization": f"Bearer {os.environ['MCP_GATEWAY_TOKEN']}"},
            "allowed_tools": ["get_forecast", "get_alerts"],
        }
    ],
)

for step in interaction.steps:
    print(step.type, getattr(step, "name", ""))

The same descriptor in JavaScript:

javascript
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });

const interaction = await ai.interactions.create({
  model: "gemini-4-hydrogen",
  input: "Check the weather in San Francisco.",
  tools: [
    {
      type: "mcp_server",
      name: "weather_service",
      url: "https://gemini-api-demos.uc.r.appspot.com/mcp",
      headers: { Authorization: `Bearer ${process.env.MCP_GATEWAY_TOKEN}` },
      allowed_tools: ["get_forecast", "get_alerts"],
    },
  ],
});

Two constraints are easy to miss. Remote MCP only works with Streamable HTTP servers; SSE transport is not supported. Server names should use snake_case and should not contain a hyphen, so weather_service is preferred over weather-service. Both line up with the transport guidance in our Streamable HTTP transport guide.

headers are sent with every request to the MCP endpoint, which is where an OAuth 2.1 Bearer token or gateway secret belongs. allowed_tools is the allowlist; treat it as a hard boundary and enumerate only the tool names the agent is permitted to reach.

Defer the long tail with tool_search

Attaching a server registers all of its tools eagerly. To withhold them, add one tool_search entry and set defer_loading: true on the mcp_server descriptor:

python
tools = [
    {"type": "tool_search"},
    {
        "type": "mcp_server",
        "name": "weather_service",
        "url": "https://gemini-api-demos.uc.r.appspot.com/mcp",
        "headers": {"Authorization": f"Bearer {os.environ['MCP_GATEWAY_TOKEN']}"},
        "allowed_tools": ["get_forecast", "get_alerts"],
        "defer_loading": True,
    },
]

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Check the weather in San Francisco.",
    tools=tools,
)

For a plain function declaration, the same flag applies and pairs with an optional short_description:

json
{
  "type": "function",
  "name": "convert_currency",
  "description": "Convert an amount between currencies using live mid-market rates, with optional rounding and historical date lookup.",
  "short_description": "Convert an amount between currencies.",
  "defer_loading": true,
  "parameters": {
    "type": "object",
    "properties": {
      "amount": { "type": "number" },
      "from_currency": { "type": "string" },
      "to_currency": { "type": "string" }
    },
    "required": ["amount", "from_currency", "to_currency"]
  }
}

short_description is valid only when defer_loading is true. It replaces the long description during retrieval, so a verbose tool docstring no longer bloats the deferred list. Keep the full parameters object anyway: unloaded schemas are not billed, but omitting them leaves the model unable to call the tool after it is retrieved.

One tool_search entry is allowed per request. Server-side retrieval is the default; you can set execution: "client" with a name, description, and search parameters to run your own registry lookup, but you cannot combine server-side and client-side retrieval in the same request.

Read the step stream, not just the status

A deferred call produces internal steps before the tool call. The response contains tool_search_call with the selected function_names, tool_search_result carrying the loaded schema, then the function_call your application executes. Deferred remote MCP servers add mcp_server_tool_call and mcp_server_tool_result instead, and the API executes against the remote server inside the same request.

Each retrieval step carries an encrypted signature. Inspect interaction.steps for function_call entries rather than checking interaction.status alone, because status is not always requires_action when a function call is returned.

Tool declarations are not persisted with an interaction. Send the complete tools array on every turn, including follow-ups that submit a function_result:

python
fc_step = next(s for s in interaction.steps if s.type == "function_call")

followup = client.interactions.create(
    model="gemini-4-hydrogen",
    previous_interaction_id=interaction.id,
    tools=tools,
    input=[
        {
            "type": "function_result",
            "name": fc_step.name,
            "call_id": fc_step.id,
            "result": [{"type": "text", "text": '{"amount": 92.4, "currency": "EUR"}'}],
        }
    ],
)

In stateless mode (store=False), append every model-generated step to your history unchanged. Dropping a tool_search_call, stripping a signature, or calling a deferred tool by name without searching first produces a 400 on the next request:

python
history = [
    {"type": "user_input", "content": [{"type": "text", "text": "Check the weather in San Francisco."}]}
]
interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    store=False,
    input=history,
    tools=tools,
)
for step in interaction.steps:
    history.append(step.model_dump())  # keeps signatures and step order intact

Loaded schemas remain in context for the rest of the conversation. There is no unload operation, so defer only the portion of the tool library you expect to leave unused.

Errors worth recognizing

Error stringCauseFix
tool_search tool must be specified when using defer_loading.A tool sets defer_loading: true but the request has no server-side tool_searchAdd {"type": "tool_search"} to tools on every request, or remove the flag
Server side tool call context must be circulated when using deferred loading functions.A stateless request omitted tool_search_call or tool_search_result, or a deferred tool was named directlyReplay both steps unchanged and do not defer tools named in system instructions
Tool call part is missing thought_signature.A replayed tool_search_call, tool_search_result, thought, or function_call step lost its signatureAppend response steps verbatim with signature preserved
deferred loading is not supported for this modelTarget model is outside the supported listUse a Gemini 4 endpoint, gemini-3.8-flash, or gemini-3.6-flash

A search that matches no deferred tool returns a plain text response instead of a structured error. Treat that as a prompt to tighten your tool descriptions rather than as a transport failure.

What deferring actually saves

Tool retrieval has no separate charge; all tokens bill at the model's standard input, cached, and output rates. A deferred tool contributes only its name and short_description, or the first sentence of description, to total_input_tokens. Parameter schemas are not billed until they are loaded. Each server-side search triggers an extra model call inside the same request, and those prompt tokens appear in total_tool_use_tokens at the input rate.

The saving appears when you have a large tool library and each turn uses a small fraction of it. With fewer than 20 stable tools, static loading is usually cheaper because every search adds another model call. Deferring also shrinks the prompt prefix, which can drop a request below the minimum cacheable size and remove implicit caching from that point onward.

Keep the core tools loaded

Leave defer_loading unset on the handful of tools used on most turns, and defer the long tail. Do not defer a tool that appears by name in system instructions or tool output; the model may call it without searching and hit the context-circulation error. Prefix similar tool names by service, such as billing_get_customer and crm_get_customer, and start each short_description with the service name.

For projects still using the Gemini 3 ClientSession binding with google-genai, see our Gemini 3 native MCP client guide. That pattern attaches an MCP session to GenerateContentConfig.tools through the Python SDK. Tool retrieval is a different surface: it lives on the Interactions API at v1beta and accepts remote server descriptors directly, so migrating means changing the request path and step handling rather than just the model string.

External references

Ready to Deploy?

Build your full agent toolstack in the Visual Generator

Combine MCP servers with databases, search APIs, and memory graphs in a single configuration file.

Customize in Generator
Developer Verification & Feedback
0 reports

Did this setup guide work with your AI host?

Help test this configuration across Claude, Cursor, and Codex CLI. Be the first to report:

Gemini 4 MCP: Deferred Tool Retrieval FAQ

Why does defer_loading fail with generateContent but work on the Interactions API?

Tool retrieval is only implemented on the Interactions API at the 'v1beta' API version. The generateContent method has no tool_search step, so a deferred function or 'mcp_server' entry there cannot be resolved. Initialize the client with httpOptions apiVersion 'v1beta' and call client.interactions.create instead.

Why does my remote MCP server descriptor get rejected when the name contains a hyphen?

Google's Remote MCP configuration requires snake_case server names and explicitly disallows the '-' character. Rename 'weather-service' to 'weather_service'. Also confirm the endpoint speaks Streamable HTTP on /mcp; legacy SSE servers are not supported by this API.

What breaks if I drop tool_search_call from a stateless conversation history?

Stateless mode with store=false must replay every model-generated step unchanged, including tool_search_call, tool_search_result, and their 'signature' fields. Omitting those steps or calling a deferred tool by name without a prior search returns a 400 error when the function_result is submitted.

RT✓

Written by Rad Tome

Independent maintainer, MCP Codex

Specializing in Model Context Protocol (MCP) integrations, autonomous AI agent orchestration, and distributed developer toolchains. Researches and benchmarks production MCP client-server architectures across OpenAI Codex, Claude, and Cursor.

Editorial Integrity: Package names verified via npm registry API. Repositories verified via GitHub REST API.
Verification Charter →

Related Guides