Skip to main content
Back to all articles
AI Engineering 6 min readUpdated August 31, 2026

Tool Selection Becomes an Information-Retrieval Problem at Scale

Once an agent has dozens of similar capabilities, tool selection should be measured like retrieval: generate a small candidate set, rank it, evaluate recall and confusion, then expose only the tools the planner needs.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#ai-agents#tool-selection#tool-retrieval#information-retrieval#mcp#evaluation#typescript#python
On this page

An agent with five tools can usually select by reading five descriptions.

An agent with eighty tools has a different problem.

The failure is not always that the model knows too little. It may know *too many overlapping interfaces at once*: search_customer, find_contact, lookup_account, query_crm, get_user, list_members, and another dozen tools with descriptions that all contain “customer” and “search.”

At that point, improving one system-prompt sentence is not the first thing I would try. Tool selection has started to look like information retrieval.

The application has a query—the user's task. It has a corpus—the capability catalog. It needs high recall in a small candidate set, then accurate ranking among those candidates.

That framing gives us useful engineering tools: lexical and semantic retrieval, metadata filters, ranking features, offline evaluation, confusion analysis, and explicit fallbacks when the right tool was not retrieved.

The example here is a SaaS operations assistant connected to billing, CRM, support, analytics, and deployment services.

Give tools metadata that helps distinguish them

A tool definition optimized only for execution is not necessarily a good search document.

I keep retrieval metadata separately from the runtime schema:

TypeScript
type ToolIndexDocument = {  toolId: string;  name: string;  domain: "billing" | "crm" | "support" | "analytics" | "deployments";  action: "read" | "search" | "create" | "update" | "delete";  resources: string[];  description: string;  examples: string[];  risk: "read-only" | "write" | "destructive";};

This gives retrieval more signal than a single paragraph.

For example, refund_payment and get_payment_status may both mention payments, but their action and risk fields are very different.

Python:

Python
from dataclasses import dataclass​@dataclass(frozen=True)class ToolIndexDocument:    tool_id: str    name: str    domain: str    action: str    resources: tuple[str, ...]    description: str    examples: tuple[str, ...]    risk: str

I can regenerate this index whenever the underlying tool catalog changes without changing the execution schema itself.

Candidate generation should optimize recall

The first stage asks: did the candidate set include the correct tool at all?

I often run lexical and semantic retrieval together because tool names contain exact vocabulary while user requests are often paraphrases.

TypeScript
type ToolCandidate = {  toolId: string;  lexicalRank?: number;  semanticRank?: number;};​async function generateToolCandidates(  query: string,  limit = 12,): Promise<ToolCandidate[]> {  const [lexical, semantic] = await Promise.all([    lexicalToolSearch(query, limit),    semanticToolSearch(query, limit),  ]);​  return reciprocalRankFuseTools(lexical, semantic).slice(0, limit);}

A candidate limit of twelve is illustrative. The right number depends on catalog size and evaluation.

The key metric for this stage is something like recall@K: across tasks with known appropriate tools, how often does the correct tool appear in the candidate set?

If recall@8 is 70%, the planner cannot possibly achieve 95% tool selection accuracy. Fix retrieval first.

Apply hard filters before asking a model to rank

Some constraints are deterministic.

If the actor has read-only access, destructive tools should not be candidates. If the task is scoped to the billing domain, a deployment rollback tool is unlikely to help. If a connector is unavailable, its tools should not be selected.

TypeScript
type SelectionContext = {  allowedToolIds: Set<string>;  availableDomains: Set<string>;  allowWrites: boolean;};​function filterCandidates(  candidates: ToolIndexDocument[],  context: SelectionContext,): ToolIndexDocument[] {  return candidates.filter((tool) => {    if (!context.allowedToolIds.has(tool.toolId)) return false;    if (!context.availableDomains.has(tool.domain)) return false;    if (!context.allowWrites && tool.risk !== "read-only") return false;    return true;  });}

This is not only a ranking optimization. It reduces the chance that the planner sees an action it could never execute.

Execution authorization still happens later. Candidate filtering should not be treated as the security boundary.

Ranking can use a smaller model than task execution

Once retrieval produces perhaps six plausible tools, a lightweight ranking model can decide which definitions deserve to reach the main planner.

I keep that interface structured:

TypeScript
type RankedTool = {  toolId: string;  score: number;  reason: string;};​interface ToolRanker {  rank(input: {    task: string;    candidates: ToolIndexDocument[];  }): Promise<RankedTool[]>;}

The ranker does not execute tools. It only compares capabilities against the task.

A model is not always necessary. For well-separated domains, retrieval score plus metadata rules can be sufficient. I add a model reranker when confusion remains among semantically similar interfaces.

Give the planner a small complete definition set

The ranking result is not the same thing as the execution prompt.

For the top few selected tools, the host fetches the full runtime definitions:

TypeScript
async function resolvePlannerTools(  task: string,  context: SelectionContext,): Promise<RuntimeToolDefinition[]> {  const ids = await generateToolCandidates(task, 12);  const docs = await toolIndex.load(ids.map((item) => item.toolId));  const filtered = filterCandidates(docs, context);  const ranked = await toolRanker.rank({ task, candidates: filtered });​  const selectedIds = ranked.slice(0, 4).map((item) => item.toolId);  return toolRegistry.getDefinitions(selectedIds);}

Now the expensive planner sees four detailed contracts rather than the whole catalog.

There is an important escape hatch: if none of the candidates look sufficient, the planner should be able to request another capability search with a refined query. Otherwise a retrieval miss becomes a forced bad selection.

Python implementation

Python
from typing import Protocol​@dataclass(frozen=True)class RankedTool:    tool_id: str    score: float    reason: str​class ToolRanker(Protocol):    async def rank(        self,        task: str,        candidates: list[ToolIndexDocument],    ) -> list[RankedTool]: ...​async def select_tool_ids(    task: str,    candidates: list[ToolIndexDocument],    ranker: ToolRanker,    limit: int = 4,) -> list[str]:    ranked = await ranker.rank(task, candidates)    return [item.tool_id for item in ranked[:limit]]

The Python version is deliberately small because the architectural value is in the separation: index documents, candidate retrieval, deterministic filters, ranking, then full definitions.

Evaluate with tasks, not tool descriptions

A tool retrieval benchmark should look like real work.

Each case contains a user task and one or more acceptable tools:

TypeScript
type ToolSelectionCase = {  task: string;  acceptableToolIds: string[];  forbiddenToolIds?: string[];};

Examples might include:

  • “Find whether customer C-184 has an unpaid invoice” → billing invoice search/read;
  • “Create a support ticket from this incident summary” → support ticket create;
  • “What percentage of trial accounts converted last week?” → analytics query, not CRM search;
  • “Show me deployment status” → deployment read, not rollback;
  • “Refund invoice INV-82” → payment/refund write path, with later authorization and approval checks.

I measure at least two stages separately:

candidate recall@K — did retrieval include an acceptable tool?

final selection accuracy — did ranking/planning choose an acceptable tool from those candidates?

That tells me whether to improve indexing or selection logic instead of randomly editing descriptions.

Build a confusion matrix for neighboring tools

Aggregate accuracy can hide a painful pair of tools that are constantly confused.

If search_accounts is selected instead of search_contacts in 30% of contact tasks, that pair deserves investigation.

The fix may be:

  • clearer names;
  • descriptions that emphasize the difference;
  • better example queries in the index;
  • metadata such as resource=contact;
  • combining two nearly identical tools behind one interface;
  • splitting one overloaded tool into narrower actions.

Tool-selection evaluation is useful because it can reveal API-design problems, not only model problems.

Descriptions should explain boundaries, not market the tool

This is weak:

Text
Powerful CRM tool for managing customer information.

It gives retrieval and the planner almost no distinguishing information.

This is better:

Text
Search individual CRM contacts by name, email, or company. Read-only. Use account_search for company-level account records.

The second description says what the tool does, what entity it operates on, what it does not do, and which neighboring capability handles the adjacent job.

That makes both retrieval and direct selection easier.

Be careful with examples in the index

Examples improve semantic retrieval, but they can also bias it.

If the only example for query_revenue_metrics is “monthly recurring revenue,” the tool may rank poorly for “trial conversion rate” even though it can answer both.

I prefer several representative examples covering the tool's genuine capability surface, not dozens of synthetic phrases designed to game the retriever.

The index should describe the interface honestly.

Tool popularity should not become an accidental ranking feature

Once an agent uses some tools frequently, it is tempting to boost them globally.

That can create a feedback loop: a slightly over-selected tool receives more usage, its popularity weight rises, and neighboring tools become even harder to discover.

If I use prior usage at all, I condition it on task/domain and keep the weight small. Relevance should dominate popularity.

Selection and authorization stay separate

A selection system may rank refund_payment first for “please refund this invoice.” That is semantically correct.

The execution layer still checks:

  • is the actor allowed to refund this payment?
  • does the invoice belong to this tenant?
  • is the amount within policy?
  • does the action require human approval?
  • is the write idempotent?

A good selector finds the right capability. It does not grant the capability.

When not to build retrieval

If your agent has twelve well-differentiated tools and evaluations show reliable selection, keep the direct tool set.

A retrieval layer adds indexing, freshness, ranking, evaluation, and another failure mode. It becomes worthwhile when schemas consume meaningful prompt space or selection quality drops because the catalog is large and overlapping.

That threshold is empirical.

The useful shift is to stop treating tool selection as mysterious model behavior once the capability surface grows. With a catalog, candidate recall, ranking accuracy, and confusion cases, it becomes an engineering subsystem you can measure and improve in the same way you would improve search.

KEEP READING

Related engineering notes