AI Agent Tool Retrieval: How to Load Tools on Demand, Build Tool RAG and Stop Tool Definitions Eating Your Context
Connect five popular MCP servers to an agent and, by Anthropic’s own count, roughly 55,000 tokens of tool definitions land in the context window before the model reads a single user word. That is the quiet tax behind slow, expensive and confused agents, and it is why ai agent tool retrieval became a first-class API feature this year. On 19 November 2026 Google put Tool Retrieval for the Gemini API into preview, joining Anthropic’s tool search tool and OpenAI’s tool_search. All three now let a model see a lightweight catalog and pull full parameter schemas only when it needs them.
The vendor features are the easy part. The hard part is deciding what to defer, how to index tools you control, how retrieval interacts with prefix caching, and how to prove the agent still finds the right tool. This guide gives you the token math, four architectures, a working Python tool-RAG implementation with a fallback search tool, and an evaluation method built on tool-selection recall@k.
What this covers: the cost and accuracy mechanics of large tool sets, native dynamic tool loading across three providers, a step-by-step tool RAG build, cache-safe loading patterns, evaluation, and failure modes.
Context and Background
Function calling started with a simple contract. You send the model a list of tools, each with a name, a description and a JSON Schema for its arguments, and the model emits a structured call. With five or ten tools this works well. The design assumption, never stated, was that the tool list is small enough to send in full on every request. If you need a refresher on the base mechanics, our LLM function calling and tool use architecture guide covers the request and response loop in detail.
The Model Context Protocol (MCP) broke that assumption. MCP made it trivial to attach a server, and every attached server contributes its whole tools/list result to the agent’s context. The MCP tools specification defines each tool by name, description, an inputSchema in JSON Schema, and optional fields such as title, outputSchema and annotations. Rich schemas are good for argument accuracy, but they are verbose. A GitHub server alone exposes dozens of tools, and enterprise agents commonly aggregate several servers plus internal functions.
Research flagged the problem early. ToolLLM (ICLR 2024) built ToolBench from 16,464 real REST APIs across 49 RapidAPI categories, far too many to place in any prompt, and paired its model with a neural API retriever. Gorilla (NeurIPS 2024) trained a model to work alongside a document retriever over large API collections. In 2025 the RAG-MCP paper by Gan and Sun framed the issue as “prompt bloat” and reported that retrieving MCP tool descriptions before selection raised tool-selection accuracy from 13.62% to 43.13% on its benchmark while cutting prompt tokens by more than half.
Vendors then moved the retrieval step into the API. Anthropic shipped its tool search tool with defer_loading in November 2025. OpenAI added tool_search with GPT-5.4 in March 2026. Google followed with Tool Retrieval in the Gemini Interactions API in November 2026. The concept has several names, including tool RAG, dynamic tool loading, deferred loading and tool search, but the mechanism is the same: keep most schemas out of the context until the model asks for them.
How AI Agent Tool Retrieval Works: Reference Architecture
AI agent tool retrieval is the practice of keeping most tool schemas out of an LLM’s context and loading only the few a task needs. A retriever, whether embeddings, BM25 or a provider-hosted search, matches the current request against a catalog of tool descriptions. The selected schemas are injected, and a fallback search tool lets the model request more.

Figure 1: Reference architecture for AI agent tool retrieval, combining hybrid retrieval, a sticky loaded tool set and a fallback search tool.
Figure 1 shows the components most production systems converge on. A query builder turns the latest user turn and task state into a search query. A hybrid index, with dense embeddings over “tool cards” and a BM25 index over names and parameters, returns candidates that are fused and cut to a top-k. Those land in a sticky, append-only loaded set. A handful of pinned core tools are always present, as is a search_tools meta tool that the model can call when the pre-retrieved set misses. The model then calls tools through an executor that talks to MCP servers or local functions.
The token math: why schemas, not names, are the problem
Start with a worked example. Assume an agent can reach 200 tools and an average tool definition costs about 300 tokens once you count the name, a two-sentence description and a JSON Schema with four or five typed, described parameters. This 300-token figure is illustrative, so measure your own catalog with your provider’s token counter. At that size the full catalog is 200 × 300 = 60,000 input tokens on every single model call.
Agents make many calls per task. A ten-step task re-sends that catalog ten times, which is 600,000 input tokens spent on tool definitions alone. At an illustrative $3 per million input tokens, that is $1.80 per task before any reasoning or output. Prompt caching cuts the bill substantially when the prefix is stable, but it does not reduce context pressure or attention dilution, and as we will see, naive retrieval can break the cache anyway.
Anthropic’s engineering team published real figures from its own setup. GitHub’s MCP server contributed about 26K tokens across 35 tools, Slack about 21K across 11 tools, and Sentry, Grafana and Splunk a few thousand each. The five servers came to 58 tools and about 55K tokens. Anthropic said it had seen tool definitions consume 134K tokens internally before optimization.
The insight that shapes every design is that the parameter schema is the expensive part. A name and a one-line description might cost 20 to 40 tokens. The schema, with nested objects, enums and per-parameter descriptions, is usually most of the remainder. That is why OpenAI’s and Google’s deferral still show the model each tool’s name and description, while holding back the schema. If 200 deferred tools cost about 30 tokens each, the visible catalog is about 6,000 tokens. Loading five full schemas adds another 1,500. That is roughly 7,500 tokens instead of 60,000, an 87% reduction in this illustrative case.
Why accuracy degrades as the tool list grows
Cost is the visible symptom. Selection quality is the deeper one. Anthropic’s tool search documentation states that Claude’s ability to pick the right tool degrades once more than 30 to 50 tools are available. On Anthropic’s internal MCP evaluations, enabling tool search moved Claude Opus 4 from 49% to 74% and Claude Opus 4.5 from 79.5% to 88.1%. These are vendor-reported numbers on vendor evaluations, so treat them as directional rather than universal.
Three mechanisms explain the degradation. First, near-duplicate tools compete. When github_search_issues, jira_search and linear_find_issue all match “find the bug ticket”, the model must disambiguate on subtle description differences. Second, long contexts dilute attention, a pattern our fact-check on effective context length and context rot documents in detail. Third, argument quality suffers, because the model must hold the right schema in focus among dozens of similar ones.
The RAG-MCP results point the same way. Selection accuracy roughly tripled when retrieval narrowed the candidate set. The absolute numbers depend heavily on benchmark design, but the direction is consistent across ToolLLM, RAG-MCP and the vendor reports: fewer, more relevant candidates help.
Four architectures for large tool sets
There are four broad ways to keep the tool list manageable, and real systems mix them.
Static subsets are the oldest approach. You hand-curate which tools each agent or route sees. A billing agent gets billing tools; a support agent gets support tools. It is deterministic, cacheable and easy to audit. It fails when users cross boundaries mid-conversation, and it pushes the routing problem into a classifier or a multi-agent hand-off, as discussed in our guide to multi-agent orchestration with MCP, A2A and LangGraph.
Embedding retrieval over tool descriptions, often called tool RAG, treats each tool as a document. You embed a card for every tool, embed the user turn, and inject the top-k nearest schemas. It scales to thousands of tools and adapts per request. Its weakness is that user phrasing and tool descriptions often live in different vocabularies, so recall depends heavily on how you write the cards.
Hierarchical namespaces group tools by server or domain. The model first sees a short list of namespaces such as github, slack and crm, each with a one-line description, and loads a namespace’s functions only when it chooses that namespace. OpenAI’s tool search guide recommends keeping each namespace under 10 functions and giving namespaces concise, high-level descriptions. Namespaces work well when the domain boundaries match how people phrase tasks.
A meta-tool for search gives the model a search_tools(query) function and lets it decide when to look. This is what the hosted products do. It handles tasks where the need for a tool only emerges mid-trajectory, after the model has read some data. The cost is an extra reasoning step and, for client-side implementations, an extra round trip.
The design this guide recommends combines all four. Pin a few core tools statically, organise the catalog into namespaces, pre-retrieve likely tools by embedding search, and keep a search meta-tool as the safety net.
Native Dynamic Tool Loading in 2026: Anthropic, OpenAI and Gemini Compared
Before building your own tool RAG, check what your provider already does. All three major APIs now support some form of dynamic tool loading, and the hosted variants handle schema expansion and cache placement for you.
Anthropic: tool search tool with defer_loading
Anthropic’s tool search tool comes in two variants. tool_search_tool_regex_20251119 lets Claude write Python re.search() patterns of up to 200 characters. tool_search_tool_bm25_20251119 takes natural-language queries of up to 500 characters. Both search tool names, descriptions, argument names and argument descriptions.
You still send every tool definition in the tools array on every request, with defer_loading: true on those that should stay out of context. The documentation is explicit that defer_loading controls what enters the context window, not what you send. At least one tool must remain non-deferred, normally the search tool itself, and the API rejects a request where everything is deferred. A search returns up to five tool_reference blocks by default, and the model may set a limit from 1 to 10,000. The API expands those references into full definitions, and they remain usable later in the conversation without re-searching.
The limits are generous: up to 10,000 deferred tools per request. For MCP connector users, defer_loading is set on the mcp_toolset entry’s default_config or per tool in configs. For custom search, your own tool can return tool_reference blocks inside a standard tool_result, which is how you plug embedding retrieval into the hosted expansion machinery. Anthropic recommends tool search when you have ten or more tools or definitions over 10K tokens, and suggests keeping the three to five most-used tools non-deferred.
Two details matter for cost engineering. The API excludes deferred tools from the system-prompt prefix and appends discovered tools inline, which protects the prompt cache. And a deferred tool cannot carry cache_control; put the breakpoint on a non-deferred tool instead.
OpenAI: tool_search with namespaces
OpenAI’s tool search guide supports tool_search in the Responses API on GPT-5.4 and later. You set defer_loading: true on functions, on namespaces’ member functions, or on an MCP server tool definition. Deferred functions still expose their name and description; for namespaces and MCP servers, the model sees only the namespace or server name and description until it loads tools.
There are two execution modes. Hosted search, with execution set to server, searches the tools you declared and returns tool_search_call, tool_search_output and then the function_call in one response. Client-executed search, with execution: "client", stops after the tool_search_call so your application can run its own lookup and return a tool_search_output. Tools loaded this way remain callable on later turns.
OpenAI states that loaded tools are injected at the end of the context window to preserve the cache, and that changing the loaded set invalidates the cache from that point forward. In its GPT-5.4 launch post, OpenAI reported that putting all 36 MCP servers of Scale’s MCP Atlas benchmark behind tool search cut total token usage by 47% across 250 tasks at the same accuracy.
Gemini: Tool Retrieval in the Interactions API (preview)
Google announced Tool Retrieval in the Gemini API on 19 November 2026. It is in preview and available only in the Interactions API (v1beta), not generateContent. You add {"type": "tool_search"} and set defer_loading: true on functions to hold back. The model sees each deferred tool’s name and description, or an optional short_description, and requests full schemas by name. The interaction then records tool_search_call, tool_search_result and function_call steps, all inside one request.
Google’s documentation lists Gemini 4 models and Gemini 3.6 and 3.8 Flash as supported. Setting defer_loading: true on an mcp_server entry defers every tool that server exposes. A client-side mode with execution: "client" lets your app run the lookup and return declarations in a function_result. The preview has notable constraints: one tool_search entry per request, no mixing of server-side and client-side retrieval, and loaded tools cannot be unloaded for the rest of the conversation.
On billing, there is no separate charge. Each server-side search, however, makes an extra model call over the full context plus loaded schemas, and those tokens appear in total_tool_use_tokens at the input rate. Google’s own docs caution that static loading can be cheaper for small libraries or long contexts that search every turn. Some press coverage cites roughly 26 tokens per deferred tool from early testing; the documentation page we reviewed gives no per-tool figure, so measure it yourself.
Side-by-side comparison
| Capability | Anthropic tool search | OpenAI tool_search | Gemini Tool Retrieval |
|---|---|---|---|
| Status (Nov 2026) | Generally available | Available, GPT-5.4 and later | Preview, Interactions API only |
| Deferral flag | defer_loading per tool or MCP toolset config |
defer_loading per function, namespace members or MCP server |
defer_loading per function or mcp_server |
| What the model sees before loading | Search tool plus non-deferred tools | Name and description; namespace or server summary | Name and description or short_description |
| Hosted search method | Regex or BM25 variants | Hosted search over declared tools | Server-side search |
| Client-side custom search | Return tool_reference blocks |
execution: "client" |
execution: "client" |
| Stated limits | 10,000 deferred tools; 5 results default | No hard maximum stated; namespaces under 10 functions advised | One tool_search per request; no unloading |
| Cache behaviour | Deferred tools kept out of prefix | Loaded tools appended at end | Deferred schemas kept out of prefix start |
The table reflects each vendor’s documentation as of 23 November 2026. These APIs are moving quickly, so recheck field names before shipping.
Step-by-Step: Build Your Own Tool RAG in Python
Hosted tool search is the right default for AI agent tool retrieval when your catalog is known up front. You need your own tool RAG when tools vary per tenant, when permissions decide visibility, when you use a self-hosted or open-weight model without native search, or when you want an embedding retriever the provider does not offer. The steps below build a provider-agnostic implementation.

Figure 2: One agent turn with pre-retrieval, a fallback search_tools call, and append-only schema loading.
Figure 2 traces a single turn. The application retrieves the top-k tools for the user’s message and sends them with the pinned tools and the search_tools meta tool. If the model decides it lacks a capability, it calls search_tools with its own query. The app searches the index, appends the new schemas, and the model emits the real function call.
Step 1: Write a tool card for every tool
The quality of tool retrieval is decided before any vector is computed. A raw MCP description such as “Lists items” is useless for search. Build a tool card that concatenates the namespaced name, a one-sentence summary, parameter names with their descriptions, and three to five example user requests that should trigger the tool.
Example requests matter because they bridge vocabularies. Users say “who’s on call tonight”, while the tool is called pagerduty_list_oncalls. Generating synthetic queries with an LLM and embedding them alongside the description is a cheap way to align the two spaces. Keep the card short enough that it embeds well; most embedding models degrade on very long inputs.
Step 2: Normalise names and add namespaces
Prefix every tool with its server or domain, for example github_create_issue or crm_update_contact. The MCP specification says tool names should be 1 to 128 characters using ASCII letters, digits, underscore, hyphen and dot, and should be unique within a server. Across servers, collisions are your problem. A server prefix fixes collisions and gives both BM25 and the model a strong grouping signal. Anthropic’s guide makes the same recommendation.
Step 3: Build a hybrid index
Dense embeddings catch paraphrases; BM25 catches exact identifiers such as “Jira”, “S3” or an error code. Fuse them with reciprocal rank fusion (RRF). Our deep-dive on hybrid search with dense and sparse fusion and RRF explains why RRF is robust to score-scale mismatches between the two retrievers. For a few thousand tools, an in-memory NumPy matrix is enough; you do not need a vector database.
The code below is complete and runs with numpy, rank_bm25 and sentence-transformers. Swap embed() for your production embedding API.
# tool_rag.py - provider-agnostic tool retrieval with a fallback search tool
# pip install numpy rank_bm25 sentence-transformers
from __future__ import annotations
import json, re
from dataclasses import dataclass, field
import numpy as np
from rank_bm25 import BM25Okapi
from sentence_transformers import SentenceTransformer
_model = SentenceTransformer("all-MiniLM-L6-v2") # swap for your embedding model
def embed(texts: list[str]) -> np.ndarray:
v = _model.encode(texts, normalize_embeddings=True)
return np.asarray(v, dtype=np.float32)
def tokenize(s: str) -> list[str]:
return re.findall(r"[a-z0-9]+", s.lower().replace("_", " "))
@dataclass
class Tool:
name: str # namespaced, e.g. "github_create_issue"
description: str
input_schema: dict
examples: list[str] = field(default_factory=list)
def card(self) -> str:
params = self.input_schema.get("properties", {})
p = "; ".join(f"{k}: {v.get('description', v.get('type', ''))}"
for k, v in params.items())
ex = " | ".join(self.examples)
return f"{self.name}. {self.description} Params: {p}. Examples: {ex}"
def schema(self) -> dict: # generic function-calling shape
return {"name": self.name, "description": self.description,
"input_schema": self.input_schema}
class ToolIndex:
def __init__(self, tools: list[Tool]):
self.tools = tools
self.by_name = {t.name: t for t in tools}
cards = [t.card() for t in tools]
self.vecs = embed(cards)
self.bm25 = BM25Okapi([tokenize(c) for c in cards])
def search(self, query: str, k: int = 8, rrf_k: int = 60,
allowed: set[str] | None = None) -> list[tuple[str, float]]:
dense = self.vecs @ embed([query])[0]
sparse = self.bm25.get_scores(tokenize(query))
scores: dict[int, float] = {}
for ranking in (np.argsort(-dense), np.argsort(-sparse)):
for rank, idx in enumerate(ranking[:50]):
scores[idx] = scores.get(idx, 0.0) + 1.0 / (rrf_k + rank + 1)
ranked = sorted(scores.items(), key=lambda x: -x[1])
out = []
for idx, s in ranked:
name = self.tools[idx].name
if allowed is None or name in allowed: # permission filter
out.append((name, s))
if len(out) == k:
break
return out
SEARCH_TOOL = {
"name": "search_tools",
"description": ("Search the tool catalog when none of the loaded tools can do "
"what you need. Describe the capability in plain words."),
"input_schema": {"type": "object",
"properties": {"query": {"type": "string"}},
"required": ["query"]},
}
class ToolSession:
"""Per-conversation loaded set. Append-only so the cached prefix survives."""
def __init__(self, index: ToolIndex, pinned: list[str],
allowed: set[str] | None = None, k: int = 6, max_loaded: int = 40):
self.index, self.allowed, self.k, self.max_loaded = index, allowed, k, max_loaded
self.loaded: list[str] = list(pinned)
def _add(self, names: list[str]) -> list[str]:
new = [n for n in names if n not in self.loaded]
room = self.max_loaded - len(self.loaded)
new = new[:max(room, 0)]
self.loaded.extend(new)
return new
def prepare_turn(self, user_text: str) -> list[dict]:
hits = self.index.search(user_text, self.k, allowed=self.allowed)
self._add([n for n, _ in hits])
return self.tool_payload()
def handle_search_call(self, query: str) -> str:
hits = self.index.search(query, self.k, allowed=self.allowed)
added = self._add([n for n, _ in hits])
cards = [{"name": n, "summary": self.index.by_name[n].description}
for n, _ in hits]
return json.dumps({"loaded": added, "matches": cards})
def tool_payload(self) -> list[dict]:
# Order is stable: pinned first, then tools in the order they were loaded.
return [SEARCH_TOOL] + [self.index.by_name[n].schema() for n in self.loaded]
Step 4: Pre-retrieve per turn, but load append-only
ToolSession.prepare_turn runs retrieval on each user message and appends any new hits to the session’s loaded set. It never removes tools. This is a deliberate choice that most tutorials get wrong, and it is the main original argument of this guide.
Many tool RAG examples recompute the top-k every turn and send only those tools. That looks economical, but it reorders and swaps the tools array on every call. Because tool definitions sit at or near the start of the prompt in most provider APIs, every swap invalidates the cached prefix from that point. You save schema tokens and then pay full price for the entire conversation history behind them. An append-only set, rendered in a stable order, keeps the earlier prefix byte-identical. The cost is a slowly growing tool list, which max_loaded caps.
The hosted products reached the same conclusion. OpenAI appends loaded tools at the end of the context. Anthropic keeps deferred tools out of the prefix and expands references inline. Gemini keeps deferred schemas out of the start of the prompt. If you implement retrieval yourself, you inherit the responsibility for the cache. Our analysis of prefix caching, RadixAttention and vLLM automatic prefix caching explains why a single changed token early in the prompt forces recomputation of everything after it, whether you self-host or use a provider’s cache.
Step 5: Wire the fallback search tool into the agent loop
Pre-retrieval works from the user’s words, which often do not mention the tool the task will eventually need. A request such as “why did last night’s deploy fail” may require a CI log tool, then a Git blame tool, then a paging tool. The search_tools meta tool lets the model ask for capabilities as it discovers them.
The loop below is written against a generic call_llm adapter, so you can map it to any function-calling API. For Anthropic, an alternative is to return tool_reference blocks from search_tools and let the API expand definitions you have already sent with defer_loading: true. For OpenAI and Gemini, the client-executed tool_search modes play the same role.
# agent_loop.py - minimal loop using ToolSession; call_llm is your provider adapter
def run_agent(session, call_llm, execute_tool, user_text, max_steps=12):
messages = [{"role": "user", "content": user_text}]
tools = session.prepare_turn(user_text)
for _ in range(max_steps):
reply = call_llm(messages=messages, tools=tools) # returns dict
messages.append(reply["assistant_message"])
calls = reply.get("tool_calls", [])
if not calls:
return reply["text"]
results = []
for c in calls:
if c["name"] == "search_tools":
out = session.handle_search_call(c["arguments"]["query"])
tools = session.tool_payload() # appended, stable order
elif c["name"] not in session.loaded:
out = '{"error": "tool not loaded; call search_tools first"}'
else:
out = execute_tool(c["name"], c["arguments"])
results.append({"id": c["id"], "content": out})
messages.append({"role": "tool_results", "results": results})
return "Stopped: step budget exhausted"
Note the guard that rejects calls to tools that are not loaded. Models occasionally hallucinate a plausible tool name they saw in a description or in an earlier search result. Returning a structured error that points to search_tools lets the model recover instead of failing silently.
Step 6: Keep the index fresh as MCP servers change

Figure 3: Building and refreshing the tool index, with an evaluation gate before a new index version is promoted.
Figure 3 shows the offline side. MCP servers that declare the listChanged capability should emit notifications/tools/list_changed when their tools change, and tools/list supports cursor pagination for large catalogs. The 2026-07-28 MCP specification revision adds that servers should return tools in a deterministic order to help client caching and prompt cache hit rates, and requires ttlMs and cacheScope on list results as freshness hints.
Treat a change notification as a trigger to rebuild affected cards, not as an instruction to hot-swap the live index. Rebuild into a new index version, run the golden-set evaluation from the next section, and promote only if recall holds. Tool descriptions are also an attack surface. A malicious or compromised server can write descriptions designed to win retrieval or steer the model, a risk covered in our MCP server security threat model on tool poisoning. Review description diffs as you would code.
Prefix Caching and Context Budget: Doing the Real Arithmetic
Dynamic tool loading changes the shape of your token bill, not just its size. It is worth working through the arithmetic before choosing a pattern, because the cheapest-looking option can be the most expensive in practice.
Three patterns, one conversation
Take the illustrative 200-tool catalog at 300 tokens per schema, plus 30 tokens per name-and-description line. Consider a ten-call task where the conversation history grows by about 1,500 tokens per call, from a 2,000-token system prompt and first message.
Pattern A, static full catalog. Every call carries 60,000 tool tokens plus history. With a stable prefix, those 60,000 tokens are cache reads after the first call. Cached input is typically billed at a fraction of the base rate, so this pattern is cheaper than it looks on the invoice, but it still consumes 60,000 tokens of context and suffers the accuracy loss described earlier.
Pattern B, per-turn top-k swap. Each call sends eight freshly retrieved schemas, about 2,400 tokens. On paper this saves 96% of tool tokens. In practice, whenever the selection changes, the cache breaks at the tools block and all history after it is billed as fresh input. By call ten, history is about 15,500 tokens and much of it is being re-processed at full price. Latency also rises, since prefill on uncached tokens is the slow part of time-to-first-token.
Pattern C, deferred catalog plus append-only loading. The visible catalog costs about 6,000 tokens if you expose every name and description, or much less with namespaces. Loaded schemas grow from zero to perhaps 12 over the task, about 3,600 tokens, always appended. The prefix stays stable, so earlier history remains cached. This is the pattern the hosted APIs implement, and it is what ToolSession does on the client side.
The numbers in this section are illustrative and depend on your provider’s cache pricing, minimum cacheable length and time-to-live. Our prompt caching economics guide has the break-even formulas for each provider.
Where the search step costs you
Every server-side search is an extra inference step. Google states this directly: each Gemini server-side search makes an extra model call over the full context plus loaded schemas, billed at the input rate. Client-side search adds a network round trip as well. If your agent searches on most turns, the saving from deferral can disappear, especially in long conversations where each search re-reads a large context.
This is why pre-retrieval and pinning still matter even with hosted search. Pre-retrieval in your app costs one embedding call, typically milliseconds, and often removes the need for the model to search at all. Pinning the three to five most-used tools, as Anthropic recommends, handles the common path without any search.
Evaluating AI Agent Tool Retrieval: Recall@k and Beyond
AI agent tool retrieval that you have not measured is a guess. The good news is that tool selection is easier to evaluate than document RAG, because the ground truth is a discrete tool name rather than a passage of text.
Build a golden set
Collect 200 to 500 real user requests from logs, each labelled with the tool or tools that a correct trajectory used. Add synthetic requests for tools that rarely appear in logs, and keep them in a separate slice so they do not inflate your headline number. Include multi-tool tasks and adversarial near-misses, for example a request that sounds like Jira but needs Linear. Our guide to RAG retrieval evaluation with recall@k, nDCG and golden sets covers building and maintaining such sets.
Measure recall@k, not just accuracy
Tool-selection recall@k is the fraction of gold tools that appear in the retrieved top-k. If the gold tool is not loaded, the model cannot call it without a search, so recall@k bounds first-pass success. The snippet below computes it against the ToolIndex above.
# eval_recall.py - tool-selection recall@k and MRR on a golden set
def evaluate(index, golden, ks=(1, 3, 5, 8, 12)):
# golden: list of {"query": str, "tools": [gold tool names]}
hits = {k: 0 for k in ks}; total = 0; rr = 0.0
for ex in golden:
ranked = [n for n, _ in index.search(ex["query"], k=max(ks))]
gold = set(ex["tools"]); total += len(gold)
for k in ks:
hits[k] += len(gold & set(ranked[:k]))
first = next((i for i, n in enumerate(ranked) if n in gold), None)
rr += 0.0 if first is None else 1.0 / (first + 1)
return {f"recall@{k}": hits[k] / total for k in ks} | {"mrr": rr / len(golden)}
Plot recall against k and pick the smallest k where the curve flattens. That k sets your context budget. If recall@8 is 0.97 and recall@12 is 0.98, the extra four schemas cost about 1,200 tokens per call for one percentage point; the fallback search tool is usually the cheaper way to catch the residual misses.
Track end-to-end signals in production
Offline recall is necessary but not sufficient. In production, log four numbers per conversation: task success, fallback search rate, loaded-set size at completion, and cached-token share of input. A rising fallback search rate means pre-retrieval is drifting, often because new tools arrived with poor cards. A falling cache share means something is mutating the prefix. Emit these as span attributes so they sit beside latency and cost; our article on OpenTelemetry GenAI semantic conventions for agent tracing shows how to attach token and tool attributes to spans.
When comparing a hosted tool search against your own tool RAG, use the evaluation OpenAI recommends for its Agents API: compare task completion, input-token usage and latency on representative requests. Do not decide on token savings alone.
Trade-offs, Gotchas, and What Goes Wrong

Figure 4: Choosing a dynamic tool loading strategy by catalog size and whether the catalog is known up front.
Figure 4 summarises when AI agent tool retrieval is worth its complexity. Under ten tools, load them statically and cache the prefix; retrieval adds failure modes without much benefit. Between ten and roughly fifty tools across a few servers, namespaces plus native defer_loading are usually enough. Beyond that, use provider tool search when the catalog is known up front, and client tool RAG when visibility depends on tenant, user or permissions. The thresholds are rules of thumb drawn from vendor guidance, not hard limits.
Retrieval misses are silent. If the right tool is not retrieved and the model does not think to search, it will often improvise with a worse tool or answer from memory. The symptom looks like a reasoning failure, not a retrieval failure. Log the loaded set on every trajectory so you can tell the two apart.
Description quality dominates. BM25 search over “Lists items” finds nothing useful. Anthropic’s documentation advises adding the keywords users actually say to tool descriptions. Vague or copy-pasted descriptions across servers are the most common cause of poor recall.
Search loops burn budget. A model that cannot find a capability may search repeatedly with paraphrases. Cap searches per turn, and return an explicit “no matching tool exists” message rather than an empty list, so the model stops looking. Gemini’s preview returns a text response rather than a structured error when a search matches nothing, so handle both shapes.
Loaded sets only grow. Gemini’s preview cannot unload tools, and an append-only client design does not either. Long sessions slowly drift toward the full-catalog problem. Cap the set, and for very long sessions, start a fresh context with a summary and a reset tool list, accepting one cache miss.
Permissions must filter before retrieval, not after. If you retrieve across all tools and then filter, a user can probe which tools exist through the model’s search results. Restrict the candidate set to what the caller may use, as the allowed parameter in the code does. For delegated access patterns, see our guide to AI agent identity and delegated authorization.
Provider differences leak into your code. Anthropic requires every potentially referenced tool to be present in the request. OpenAI requires a matching call_id for client search. Gemini forbids mixing client and server retrieval. Hide these behind one adapter, and test the error paths, since community reports show edge cases around repeated searches and mixed tool types.
Long-running tools interact with loading. A tool loaded for an asynchronous job must stay loaded until the result arrives, or the model cannot interpret the follow-up. Our comparison of MCP Tasks versus streaming versus webhooks for long-running tools covers the completion patterns that this affects.
Practical Recommendations
Begin any AI agent tool retrieval project by measuring. Dump your full tool payload, count its tokens with your provider’s counter, and record how many distinct tools real conversations use. If the payload is under 10K tokens and most tools see regular use, static loading with good caching may already be optimal. If a long tail of tools is rarely used, dynamic tool loading will pay off.
Next, fix the catalog before you add retrieval. Namespace every tool by server, rewrite thin descriptions, and add example requests. This step alone improves both hosted search and your own index, and it is cheap.
Then prefer the native feature where it fits. Hosted tool search handles schema expansion, cache placement and protocol bookkeeping that is easy to get subtly wrong. Reach for client-side tool RAG when tools vary per tenant or permission, when you need embedding retrieval the provider lacks, or when your model has no native search. Many teams combine the two by using client-side search that returns references the provider expands.
Finally, treat the tool index as a versioned artifact with a test gate. Every change to a tool card or embedding model should re-run recall@k on the golden set before promotion, exactly as you would gate a prompt or model change.
Checklist:
- Measure tool-definition tokens per call and distinct tools used per conversation.
- Namespace tool names by server and keep namespaces under about ten functions.
- Write tool cards with a summary, parameter descriptions and example user requests.
- Pin three to five high-frequency tools; defer the rest.
- Use append-only loading in a stable order to protect the prompt cache.
- Provide a
search_toolsfallback and cap searches per turn. - Filter candidates by caller permissions before retrieval.
- Gate index changes on recall@k and track fallback rate and cache share in production.
Frequently Asked Questions
What is AI agent tool retrieval?
AI agent tool retrieval is a technique where an agent does not receive every tool definition up front. Instead, a retriever selects the few tools relevant to the current request and injects only their schemas into the model’s context. The retriever can be embedding search, BM25, a provider-hosted search, or a meta tool the model calls itself. It reduces input tokens and improves selection accuracy for agents with large catalogs. Anthropic, OpenAI and Google all now ship native versions, usually controlled by a defer_loading flag on each tool.
How many tools can an LLM handle before accuracy drops?
There is no universal threshold, because it depends on the model, how similar the tools are, and how good the descriptions are. Anthropic’s documentation says Claude’s tool selection degrades beyond roughly 30 to 50 tools and recommends tool search from about ten tools or 10K tokens of definitions. OpenAI advises keeping namespaces under ten functions. The practical answer is to measure: build a golden set of real requests and track selection accuracy as you add tools, rather than relying on a single published number.
Is tool RAG the same as dynamic tool loading?
They overlap but are not identical. Dynamic tool loading is the broad goal of adding tool schemas to the context only when needed. Tool RAG is one implementation, where tools are indexed like documents and retrieved by semantic or keyword similarity before the model call. Other implementations include hierarchical namespaces, static routing per agent, and hosted tool search where the model issues the query. Most production systems combine pre-retrieval through tool RAG with a model-driven search tool as a fallback.
Does dynamic tool loading break prompt caching?
It can, if implemented naively. Tool definitions sit near the start of the prompt, so swapping the tool list each turn invalidates the cached prefix from that point and forces the provider to reprocess the history behind it. The hosted implementations avoid this by keeping deferred tools out of the prefix and appending loaded tools later in the context. If you build your own, load tools append-only in a stable order, and cap the set size rather than replacing tools between turns.
How does MCP tool selection work with many servers?
An MCP client calls tools/list on each server and, by default, passes every tool to the model, which is where context bloat comes from. With dynamic tool loading, the client or provider marks entire MCP servers as deferred, so the model sees only server or tool summaries until it searches. Anthropic sets this through the MCP toolset’s default_config, while OpenAI and Gemini accept defer_loading on the MCP server entry. Prefix tool names by server to avoid collisions and help retrieval.
How do I evaluate tool retrieval quality?
Build a golden set of real user requests labelled with the tools a correct trajectory used, then compute tool-selection recall@k and mean reciprocal rank against your index. Recall@k tells you how often the right tool is loaded before the model acts, and the curve across k helps you pick a context budget. In production, also track task success, how often the model falls back to the search tool, the final loaded-set size, and the share of input tokens served from cache.
Further Reading
- MCP Tasks extension vs streaming vs webhooks for long-running tools explains how asynchronous tool results interact with what the model has loaded.
- Multi-agent orchestration with MCP, A2A and LangGraph covers splitting tools across specialised agents as an alternative to one large catalog.
- LLM prefix caching: RadixAttention vs vLLM automatic prefix caching details why stable prompt prefixes matter for cost and latency.
- Context engineering for LLM agents in production places tool loading within the wider context budget.
- Anthropic: Introducing advanced tool use gives the original token and accuracy figures for tool search.
- RAG-MCP: Mitigating Prompt Bloat in LLM Tool Selection is the 2025 paper on retrieval for MCP tool selection.
By Riju — about
