Skip to content
Blog

Tool Discovery for Agent Fleets: Registries and MCP Catalogs

Hard-coded tool lists stop scaling at a handful of tools. Build a registry with ownership metadata, MCP-based discovery, and semantic tool selection that loads tools on demand.

Published on • November 16, 2026

AI Assistant

You started with six tools. Then another team shipped an MCP server, someone added a second search tool, and now your agent has 80 tools in its system prompt — most of which are irrelevant to any given request. Selection accuracy drops, token bills climb, and nobody can tell you who owns delete_rows_v2 or whether it is safe to call in production.

Hard-coded tool lists are fine for a prototype and a liability for a fleet. In this post, you will learn how to build tool discovery for multiple agents: the MCP discovery model (tools/list, capabilities, server catalogs), a central registry with versioning and ownership metadata, semantic search over tool descriptions so each agent loads only the tools it needs, and an approval workflow before a tool joins the fleet — with runnable Python for an MCP client and an embedding-based tool picker, plus a registry schema you can commit as YAML.

Prerequisites

  • Python 3.10+ and pip (or uv).
  • pip install mcp anthropic for the MCP client, and an embedding provider of your choice (pip install openai in the examples below; any provider with a embed(text) -> vector function works).
  • An MCP server to talk to. The MCP build-server tutorial or the official servers-archived repo are good starting points.
  • Prior knowledge: what a tool call is, JSON Schema basics, and roughly how vector similarity search works.

MCP’s Tool Discovery Model

MCP is the closest thing we have to a standard for exposing tools to AI applications — “a standardized way to connect AI applications to external systems.” Its discovery model is small and worth internalizing even if you never ship an MCP server:

  • Capabilities are declared at handshake. A server that supports tools declares {"capabilities": {"tools": {"listChanged": true}}}. listChanged means the server will push notifications/tools/list_changed when its tool set changes — so your client can re-fetch instead of caching stale.
  • Discovery is a request, not a config file. Clients send tools/list and get back tool definitions: name, optional title, description, inputSchema (JSON Schema), optional outputSchema, and optional annotations.
  • tools/list is paginated. It returns an opaque nextCursor, exactly like resources/list and prompts/list, so a server with hundreds of tools can page them out.
  • Deterministic ordering is a SHOULD. The spec asks servers to return tools in a stable order so clients can cache the list and LLM prompt caches hit more often. If you build a catalog server, do this.
  • Names are unique only within a server. The spec calls out collisions explicitly: two servers can both expose search, so aggregating clients “SHOULD implement a disambiguation strategy such as prefixing tool names with a server identifier.”

That last point is where fleets go wrong. Let’s build the client first, then fix it.

A Client That Lists Tools From a Server

The Python SDK’s Client owns the whole connection lifecycle — entering the async with block launches the server process and negotiates a protocol version; leaving it shuts everything down:

import asyncio
import json

from mcp import Client, StdioServerParameters
from mcp.client.stdio import stdio_client


def server_params(script: str) -> StdioServerParameters:
    """Describe the subprocess that runs the MCP server."""
    return StdioServerParameters(
        command="python" if script.endswith(".py") else "node",
        args=[script],
    )


async def list_all_tools(script: str) -> list[dict]:
    """Connect, page through tools/list, and normalize to registry entries."""
    entries: list[dict] = []
    async with Client(stdio_client(server_params(script))) as client:
        page = await client.list_tools()          # first page
        while True:
            for tool in page.tools:
                entries.append({
                    # Prefix with the server id so two `search` tools never collide.
                    "id": f"{script}::{tool.name}",
                    "name": tool.name,
                    "description": tool.description or "",
                    "input_schema": tool.input_schema,
                })
            if not getattr(page, "next_cursor", None):
                break
            page = await client.list_tools(cursor=page.next_cursor)
    return entries


if __name__ == "__main__":
    tools = asyncio.run(list_all_tools("servers/weather.py"))
    print(json.dumps(tools, indent=2)[:800])

What this buys you: the catalog is derived from the servers themselves, so a tool can never appear in the registry with a description that drifted from the code. Note also that the spec lets the tool set vary by authorization — a server may return only the tools the caller’s scopes permit — which means discovery should run per-credential, not once globally.

The Registry: A Catalog With Ownership

Discovery answers “what exists right now.” A registry answers “what is approved, who owns it, and which version is live.” Keep it as a file in git so it is reviewable, diffable, and promotable through environments:

# registry/tools.yaml
version: 3
updated_at: '2026-11-16'
tools:
  - id: crm::search_contacts
    mcp_server: crm
    name: search_contacts
    version: 2.3.1
    owner: team-crm
    tier: production            # production | staging | sandbox
    approval:
      status: approved
      approved_by: sec-review
      approved_at: '2026-10-28'
      scope: [read-only]
    schemas:
      input_hash: sha256:9f2c…
      output_hash: sha256:1ab7…
    slo:
      p95_ms: 400
      rate_limit_per_min: 120
    agents: [support-triage, sales-copilot]
    tags: [crm, read, search]

  - id: warehouse::execute_sql
    mcp_server: warehouse
    name: execute_sql
    version: 1.0.0
    owner: data-platform
    tier: staging
    approval:
      status: pending
      requested_by: analytics
      risk: high                # writes / destructive
    agents: []
    tags: [sql, write, destructive]

Five fields do most of the work:

  • version + schema hashes. When a server ships search_contacts 2.4 with a new required parameter, the hash change fails contract tests (see post 3 in this series) and forces re-approval. This is the registry’s versioning story: not semver theater, but the model-visible schema is versioned.
  • owner. Every tool has a team that gets paged when it misbehaves. An unowned tool does not ship.
  • tier + approval. Only production + approved entries are ever eligible for loading.
  • agents. Which fleet members may see this tool — this is your per-agent allowlist.
  • tags. Cheap first-pass filtering before embeddings get involved.

Semantic Selection: Load Tools As Needed

Now the context problem. Even an approved registry of 80 tools is too many to put in every prompt. The fix is to embed each tool’s description once, then at request time retrieve only the top-k relevant tools and bind just those:

import math
import os
import re
from collections.abc import Iterable

EMBED_CACHE: dict[str, list[float]] = {}


def embed(text: str) -> list[float]:
    """Embed a string. Swap this for any provider you like."""
    key = re.sub(r"\s+", " ", text.strip().lower())
    if key in EMBED_CACHE:
        return EMBED_CACHE[key]
    from openai import OpenAI  # imported lazily so tests run offline
    client = OpenAI()
    resp = client.embeddings.create(model="text-embedding-3-small", input=key)
    EMBED_CACHE[key] = resp.data[0].embedding
    return EMBED_CACHE[key]


def cosine(a: Iterable[float], b: Iterable[float]) -> float:
    dot = sum(x * y for x, y in zip(a, b))
    na = math.sqrt(sum(x * x for x in a))
    nb = math.sqrt(sum(y * y for y in b))
    return dot / (na * nb) if na and nb else 0.0


def index_registry(tools: list[dict]) -> list[dict]:
    """One vector per tool: name + description + tags is what the model reads,
    so it is also what we search over."""
    out = []
    for t in tools:
        if t["approval"]["status"] != "approved":
            continue
        text = f"{t['name']}: {t['description']} tags: {' '.join(t['tags'])}"
        out.append({**t, "vector": embed(text)})
    return out


def pick_tools(query: str, index: list[dict], k: int = 6,
               min_score: float = 0.30) -> list[dict]:
    """Return the k tools most relevant to this request, above a floor."""
    qv = embed(query)
    scored = sorted(
        ((cosine(qv, t["vector"]), t) for t in index),
        key=lambda pair: pair[0],
        reverse=True,
    )
    return [t for score, t in scored[:k] if score >= min_score]

Two design notes. First, the floor (min_score) matters as much as k: it lets the model correctly have no tools for a chit-chat turn, which is a real and underrated capability. Second, this runs per request, so tool availability can vary by message — attach pick_tools(user_text) results to that one model call instead of mutating global state.

For reference, bind_tools/tools= on every request is exactly how MCP clients work too: the client tutorial fetches list_tools() and passes name/description/input_schema with each model call, then executes every requested call in a loop with a MAX_TOOL_TURNS cap. Your retrieval layer slots in right before that — same shape, smaller list.

Dynamic Loading and the Approval Gate

Wire the pieces into a small dispatcher:

def tools_for_request(query: str, registry: list[dict]) -> list[dict]:
    """Registry -> approval filter -> semantic shortlist -> prompt-ready tools."""
    approved = [t for t in registry
                if t["approval"]["status"] == "approved"
                and t["tier"] == "production"]
    index = index_registry(approved)
    chosen = pick_tools(query, index)

    return [{
        "name": t["id"].replace("::", "__"),   # fleet-wide unique name
        "description": t["description"],
        "input_schema": t["input_schema"],
        "annotations": {"version": t["version"], "owner": t["owner"]},
    } for t in chosen]

The approval gate is intentionally boring and explicit. In practice you want a PR-based flow: a team adds an entry with status: pending and risk: high, CI runs schema contract tests, a human from security signs approved_by, and only then does the entry become loadable. Two protocol-aligned guardrails worth copying from the MCP tools spec:

  1. Human in the loop. The spec is emphatic that applications “SHOULD always be a human in the loop with the ability to deny tool invocations,” with UI that shows which tools are exposed and prompts for confirmation on sensitive operations. Your registry’s tier and scope fields are the data that powers those prompts.
  2. Treat annotations as untrusted. The spec warns clients to consider tool annotations untrusted unless the server is trusted. Same for your registry: verify schema hashes server-side rather than trusting a description field a server sent you.

Putting It All Together

A request for “find the Acme deal owner and draft a follow-up” flows like this:

1. Embed the request.
2. Filter registry: approved + production + in this agent's allowlist  → 41 tools
3. Semantic top-k with floor (k=6, min_score=0.30)                   → 3 tools
   crm::search_contacts  (0.71)
   crm::list_deals        (0.66)
   mail::draft_message    (0.44)
4. Bind those 3 to this model call only (name, description, inputSchema).
5. Model calls crm::list_deals → dispatcher routes to the MCP server,
   executes tools/call, returns the result (and any isError flag).
6. If the model asks for something uncovered, re-run step 1-4 with the
   new request text — tools are re-selected each turn.

Context cost stays flat as the fleet grows from 8 to 800 tools: you pay for six descriptions per turn instead of eight hundred. And when the warehouse team ships a new tool, they ship it as an MCP server plus a registry PR — discovery is automatic, ownership is explicit, and nothing reaches a model before a human approved it.

Conclusion and Next Steps

You replaced a static TOOLS = [...] with a real discovery pipeline: MCP’s tools/list as the source of truth, a git-managed registry carrying version, ownership, and approval state, semantic shortlisting so agents load tools per request, and a human approval gate before anything enters the fleet. Prefixing by server and re-selecting each turn turned out to be the two highest-leverage lines in the whole design.

Homework:

  1. Subscribe to notifications/tools/list_changed (via subscriptions/listen) and invalidate your registry cache when a server’s tool set changes.
  2. Log which tools get selected but never called — those are your description-quality bugs.
  3. Add a previously_failed signal to pick_tools so a tool that errored twice this session stops being shortlisted.
  4. Benchmark it: measure tool-selection accuracy at k=6 versus binding everything, and publish the token delta. The number usually ends the debate.