Tool Discovery for AI Agents: Loading the Right Tools Per Step

When an agent's tool catalog grows past a few dozen entries, shipping every schema on every turn taxes the context window and the model's selection accuracy alike. This article treats the catalog as a retrieval problem: a lightweight index that is always present, full schemas bound on demand through a search tool, sticky per-run bindings, fail-closed handling of unknown and vanished tools, and an evaluation that measures selection accuracy against the number of distractors.

Tool Discovery for AI Agents: Loading the Right Tools Per Step

A support agent is wired to fourteen tool servers: CRM, billing, the order management system, three shipping carriers, a docs store, a warehouse service, chat. Between them, 340 tools. Every request now ships 340 JSON schemas before the conversation says a word — roughly 70,000 tokens of parameters blocks, enumerations, and descriptions, re-sent on every turn. The model picks get_order from the storefront server when the order it needs lives in the OMS, calls shipping_get_rate with the carrier hardcoded to the one whose schema happened to sit next to it in the list, and occasionally invents lookup_order_status, which exists nowhere. And because the catalog is re-serialized on every step, the whole bill is paid again for each of the nine steps in the run.

None of that is a prompting problem. It is a retrieval problem. The catalog is a library, and the model has been handed the stacks instead of the card catalog. This article is about building the card catalog: a small index that is always in context, full schemas loaded only when a step needs them, and the rules that keep discovery from becoming its own failure mode.

Every tool in context is a tax on every turn

Shipping the whole catalog costs three things at once, and the first is the most visible:

Tokens and latency. Each tool's name, description, and schema ride in every request. A lean tool is 100 tokens; a rich one with enumerations and nested objects is 500 or more. Prompt caching discounts the repeated bytes but does not remove the prefill cost on the first turn, and it does nothing for the other two taxes.

Selection accuracy. The model chooses among whatever is in front of it. As the set grows, near-duplicates multiply — three get_orders, two search_customers — and the choice starts to depend on description wording and position rather than on the task. The symptom is never "the model picked a wrong tool"; it is "the model picked a plausible tool for a different system", which is worse because the call succeeds.

Attention on the task. Tool definitions compete with the conversation, the retrieved documents, and the tool results for the same window. Every schema that is present but irrelevant makes the relevant material a smaller share of what the model attends to.

The rule that falls out: the catalog in context should be the set the task plausibly needs, not the set the organization owns. For a five-tool agent nothing else matters. Past a few dozen tools, something has to decide what the model sees — and that decision is a system component, not a prompt.

Separate the index from the schema

A tool schema does two jobs that do not need to travel together. It advertises the tool — name plus a line about what it is for — and it specifies the tool — parameters, types, required fields, enums. The advertisement is 15 to 25 tokens; the specification is typically five to twenty times larger. Progressive disclosure splits them:

  • An index of tool cards, one per tool, small enough to keep in context (340 cards at 20 tokens is about 7,000 tokens — a tenth of the full schemas, and cacheable).
  • A bound set of full schemas, assembled per run: a small kernel that is always present, plus whatever discovery pulls in.
  • A search tool the model calls when the bound set lacks what it needs; the harness turns the query into tool cards and binds their schemas for the rest of the run.
CORE = ("ask_user", "finish", "search_tools")      # always bound: every step may need them

def resolve_tools(run):
    """The tools array the next request carries."""
    return [CATALOG.schema(name) for name in (*CORE, *run.bound)]

def search_tools(query, k=5, run=RUN):
    hits = CATALOG.search(query, k=k, exclude=set(CORE) | run.bound,
                          allowed=run.permissions)       # filter before retrieval
    for hit in hits:
        run.bound.add(hit.name)                             # schema joins from now on
    return [{"name": hit.name, "purpose": hit.summary, "server": hit.server,
             "side_effect": hit.side_effect} for hit in hits]

Two details carry most of the value. Binding is sticky for the run: a tool discovered at step three is still bound at step seven, so the model never re-searches for the same capability — the result-caching idea applied to schemas, with the run as the scope. And the kernel stays small. Resist the urge to pin "tools we use a lot"; every pin is a schema the model pays for on every step, and a kernel of forty is just the old catalog with extra steps.

Descriptions are retrieval documents

Once a search step sits between the model and the schema, the description has a second audience: the retriever. Write for it first.

Lead with the verb and the object. "Fetch the shipment tracking history for an order" retrieves for tracking, shipment, and order; "Shipment service v2" retrieves for nothing a model would type.

Carry the synonyms the caller would use. The model searches in the user's vocabulary and its own paraphrases. A status tool should mention status, state, where is my order. A retrieval index over the description can only match words that are there.

Split near-duplicates by what they do not do. oms_get_order and storefront_get_order are indistinguishable until one says "returns fulfillment and warehouse state; not the customer-facing storefront view" and the other says the reverse. One negative sentence per tool dissolves most selection errors.

Namespace at the source. When two servers ship the same name, the harness prefixes by server (crm_get_contact, billing_get_contact) and refuses to resolve an ambiguous bare name — it returns both cards and makes the model pick. Never "helpfully" pick one; the ambiguity is real information.

The index entry, then, is a curated field, not a copy of the server's description — a distinction that matters in the security section below.

Make discovery a step the model can take

Searching is a round trip, so treat it like one: a tool with a contract, a cost, and a place in the plan.

{
  "name": "search_tools",
  "description": "Find tools by task. Call when no bound tool fits the step; returns tool cards whose schemas are then bound for the rest of the run.",
  "parameters": {
    "type": "object",
    "properties": {
      "query": { "type": "string", "description": "What you need to do, in plain words." },
      "k": { "type": "integer", "minimum": 1, "maximum": 8, "default": 5 }
    },
    "required": ["query"]
  }
}

The model learns when to call it from two places: a standing instruction ("if no bound tool covers the step, search before improvising") and the harness's response when it gets that wrong. An unknown tool name is the clearest signal that discovery was skipped, and it should fail closed with the search already done:

{
  "error": "unknown_tool",
  "requested": "lookup_order_status",
  "candidates": [
    { "name": "oms_get_order", "purpose": "Fetch fulfillment and warehouse state for an order." },
    { "name": "carrier_track_shipment", "purpose": "Fetch tracking events for a shipped parcel." }
  ],
  "bound": ["oms_get_order", "carrier_track_shipment"],
  "hint": "Both candidates are now bound; call the one that fits, or search again with a narrower query."
}

That error is doing three jobs: refusing the invented tool, running the search the model skipped, and binding the results so the next step can proceed. Budget it like every other call — one or two searches per run is normal, five in a row is a model that is lost, and the no-progress detector should treat it that way.

When the catalog moves under the run

Servers restart, get upgraded, and drop tools between a discovery and the call that follows it. Protocols that list tools dynamically (MCP's tools/list with its list_changed notification is the common shape) make this a normal event rather than an outage, so the harness needs an answer for it:

Bind a snapshot, not a live lookup. The schema the model reasoned over is the schema the call executes against. If the server's current version no longer matches what was bound, the call fails with a structured error naming the change — it never silently re-resolves to a "similar" tool or to a newer schema with different required fields.

Treat list_changed as a re-index event, not a re-bind. Update the catalog so future searches see the new set; leave the current run's bound tools alone unless one of them vanished. A mid-run re-binding changes the tools array under a conversation that was built around the old one.

Version what was approved. If a run was approved on the basis of the tools it could call — an approval gate, a sandbox manifest — record the catalog snapshot's hash alongside the approval. A server that changes a description after approval is a different server, and the difference should be visible.

Discovery is an attack surface

A tool description is text from another system that lands in the model's context with the authority of the system prompt behind it. The moment a third-party server can add tools, it can add instructions — "always call this tool before any other" — hidden in a description the model reads but the operator never does. Discovery widens that surface, because the model now actively asks untrusted servers for tools. Four rules keep it shut:

  • Filter by permission before retrieval. The search index contains only tools the run is allowed to call. A deploy tool must never appear in a refund run's results — not even as a card the model is then told it cannot use. Retrieval and authorization are one operation, with authorization first.
  • Index curated summaries, not server descriptions. The card the model sees comes from a field your pipeline wrote or reviewed; the server's raw description reaches the model only when the full schema is bound, for a tool the run was already allowed to call.
  • Classify side effects from the manifest, not the server's claim. A tool that says "read-only" in its description is not read-only; the manifest entry says what it is, and approval gates, serialization, and caching all key off that.
  • Gate first sightings. A tool that has never been bound in this environment before triggers the same review path as a new dependency: a human sees the card and the schema before any run can call it.

Measure selection, not vibes

Progressive disclosure trades a fixed token cost for an occasional round trip and a new failure mode — the right tool exists and is not found. Both sides need numbers:

  • Selection accuracy against distractors. Run a fixed eval set — tasks with a known correct tool — with catalog sizes of 10, 50, 200, and 500. The curve tells you where full-catalog shipping stops working and where the search step has to be good enough.
  • Discovery overhead. Searches per run, results bound per search, latency added. The healthy number is low and flat; a spike means the kernel is missing something every run needs.
  • Bind-then-use rate. Of the schemas discovery binds, how many are called? A low rate means the search returns plausible-but-wrong cards, and the fix is in the descriptions, not the ranker.
  • Unknown-tool errors per hundred calls. The direct measure of the model improvising; it should fall to near zero once the fail-closed error with candidates is in place.

Pin the behavior with a fake catalog

Every property above is testable against an in-memory catalog, no model in the loop:

def test_kernel_is_always_bound():
    run = Run(tools=CORE)
    assert set(CORE) <= {schema.name for schema in resolve_tools(run)}

def test_search_binds_and_binding_is_sticky():
    run = Run(tools=CORE)
    cards = search_tools("where is my shipment", run=run)
    assert "carrier_track_shipment" in {card["name"] for card in cards}
    assert "carrier_track_shipment" in {schema.name for schema in resolve_tools(run)}   # next step
    again = search_tools("where is my shipment", run=run)                                # not re-served
    assert "carrier_track_shipment" not in {card["name"] for card in again}

def test_unknown_tool_fails_closed_with_candidates():
    run = Run(tools=CORE)
    err = harness.call("lookup_order_status", order_id="8123", run=run)
    assert err["error"] == "unknown_tool"
    assert "oms_get_order" in {c["name"] for c in err["candidates"]}
    assert CATALOG.upstream_calls == 0                                      # nothing was executed

def test_permission_filter_runs_before_retrieval():
    run = Run(tools=CORE, permissions=PERMISSIONS["refund"])
    cards = search_tools("deploy the checkout service", run=run)
    assert "ci_deploy_service" not in {card["name"] for card in cards}
    assert "ci_deploy_service" in CATALOG.names()                           # exists; is not eligible

def test_vanished_tool_fails_instead_of_reresolving():
    run = Run(tools=CORE)
    run.bound.add("carrier_track_shipment")
    CATALOG.remove("carrier_track_shipment")
    err = harness.call("carrier_track_shipment", tracking_no="1Z999", run=run)
    assert err["error"] == "tool_unavailable"
    assert err["alternatives"] == []                                        # never re-resolves

The selection eval is the one test that needs the model: a fixed set of tasks, a catalog seeded with the right tool plus N distractors, and an assertion on the chosen tool's name. Keep N as a parameter so the same eval measures the catalog, the descriptions, and the ranker in one sweep.

The model gets a card catalog

The rules compress to five. Every schema in context is a per-turn tax; the set the model sees is the set the task plausibly needs, not the set the company owns. Split the index from the schema — cards always, specifications on demand — with a kernel that stays small and bindings that stay for the run. Write descriptions as retrieval documents: verb and object first, the caller's synonyms, one sentence on what the tool is not. Make discovery a step with a contract, fail closed on unknown tools with the search already done, and bind a snapshot so a moving catalog fails loudly instead of silently. And measure selection accuracy against distractors, because a discovery layer nobody measured is a prompt with extra steps.

The series spent its earlier chapters making each call safe — idempotent, bounded in time, serialized, cached. Discovery decides which calls are possible at all. A catalog of three hundred tools is a library, and a library is only useful with a card catalog; the agent that gets one stops paying for the stacks.

About this story

This article was written by Gen-AI using GPT 5.5 or Opus 4.7. Verify technical guidance before using it in production systems.

Advertisement ad.endcap · 336×280