AI Coding Agents
Build a Lazy MCP Tool Registry That Keeps the Tools Array Stable
Lazy MCP tool loading gives a model access to a large catalog while presenting only the tools relevant to a task. Use provider-native search when your model and gateway support it, or return tool references from a custom search tool when you need your own ranking on Claude. For a shared interface across providers, keep the tools array fixed and return matching schemas in conversation results.
Choose who owns tool discovery
There are two distinct inventories to manage. The host needs a catalog of what its MCP servers advertise so it can route calls. The model needs enough information to choose a tool and construct valid arguments for the current task. A lazy registry changes which part of that catalog the model sees and when. Decide who should rank the tools and how the model should call them. On Claude, your application can rank the tools while the API exposes their individual schemas. A generic invoker gives you a consistent interface across providers. MCP tools specification
| Route | Initial model surface | What arrives after search | Choose it when |
|---|---|---|---|
| Anthropic native search | Search plus non-deferred tools | Discovered definitions referenced inline by the API | The model and gateway support Anthropic’s native discovery |
| Anthropic custom search | Your search tool plus any other non-deferred tools | The API expands tool references in your search result | You need your own ranking on Claude with individual tool schemas |
| OpenAI native search | Search and tools you expose up front | Relevant tools added to model context | The model supports search and related tools fit namespaces |
| Local registry | search_tools and invoke_tool (names chosen for this example) | Matching schemas in an ordinary conversation result | You control the host and need the same two-tool interface across routes |
| Eager loading | Every enabled definition | Ordinary tool results | The enabled set is small and common tasks already know their tools |
Start by replaying the same task with its small set of known tools. If the agent reliably finds them and the schema burden is modest, there may be no discovery step worth adding. A registry is useful when several tasks share a large catalog but each needs a different corner of it. The ByteCosts schema overhead guide covers how to price the eager baseline, including warm cache reads. Use it to decide whether to prototype discovery. MCP tool definition token cost
Choose built-in or custom search
Anthropic documents two search variants as of November 30, 2026. Use tool_search_tool_bm25_20251119 for natural-language queries and tool_search_tool_regex_20251119 for pattern queries. Include the search tool in the request’s tools array and set defer_loading: true on the definitions you want to load on demand. Keep at least one tool non-deferred, ordinarily the search tool itself. The application still sends full definitions for the deferred tools on each request. Anthropic excludes them from the system-prompt prefix and expands discovered references in the conversation. Keep the search results in history in the form returned by the API. A deferred tool cannot also carry cache_control, so place a tool-level cache breakpoint on a non-deferred tool when you use one. Anthropic tool search documentation
If Anthropic’s MCP connector supplies the tools, configure defer_loading in the mcp_toolset entry’s default_config to defer the set. The docs also describe per-tool configuration under configs. Start by leaving a common operation available and deferring a less frequently used group. Exercise a task that calls the always-available operation and a second task that must discover a deferred one. Trace what the model receives, then check the usage fields on the continuation. Anthropic describes tool search itself as without a separate server-tool charge, with definitions it loads counted as input tokens. Anthropic tool search documentation
If you want to rank tools yourself on Claude, return tool_reference blocks in a standard tool_result from your custom search tool. Every referenced tool needs a definition in the top-level tools array, normally with defer_loading: true. The API expands those references just as it does for built-in search, so the model can call the discovered tools using their individual schemas. Anthropic custom tool search
OpenAI’s function-calling guide lists tool_search support on gpt-5.4 and later as of November 30, 2026. Use namespaces to group related tools by domain, such as billing and support. A function inside a namespace can carry defer_loading: true. Organize each namespace so its purpose distinguishes it from neighboring groups, then try a task with similar function names in both groups. This checks whether the agent searches the right surface and obtains the schema it needs. Verify support for the provider-native search feature on the actual route through your gateway before enabling it for a workflow. OpenAI function calling
Keep the local registry’s tools array fixed
When the route lacks native search or you want a shared invocation interface, keep the model-facing definitions fixed and handle MCP discovery on the host. Build a local index from tools the session is authorized to use. The sample takes that list as input. In a production MCP client, fetch it through tools/list and handle pagination. When a server that declares listChanged sends notifications/tools/list_changed, refresh the catalog under your session policy. The provider-facing tools can keep their original definitions even when the server catalog changes. Decide how existing search results expire before changing which tools an active session may invoke. MCP tools specification
The first block defines the stable pair and a small, standard-library BM25 index. Build postings over terms from each tool’s name and description. When the model sends a query, score matching tools using term frequency, document frequency, and description length. Return the top results with their full argument schemas. The reference ranks exact term matches after case folding and splitting on punctuation and underscores. It breaks ties by tool name and gives back an empty list when no terms match. The score parameters and result limit are choices in this example.
from collections import Counter, defaultdict
from hashlib import sha256
import json
from math import log1p
import re
def terms(text):
return re.findall(r"[^\W_]+", text.casefold())
def json_bytes(value):
return json.dumps(value, sort_keys=True, separators=(",", ":")).encode("utf-8")
def schema(name, description, **properties):
return {
"name": name, "description": description,
"inputSchema": {
"type": "object", "properties": properties,
"required": list(properties), "additionalProperties": False,
},
}
TOOLS = json_bytes([
schema("search_tools", "Find available tools and their argument schemas.",
query={"type": "string"}, k={"type": "integer", "minimum": 1, "maximum": 5}),
schema("invoke_tool", "Call a tool returned by search_tools.",
tool={"type": "string"}, arguments={"type": "object"}),
])
class Registry:
def __init__(self, catalog):
self.schemas = {tool["name"]: json_bytes(tool) for tool in catalog}
if len(self.schemas) != len(catalog):
raise ValueError("duplicate tool names")
self.postings = defaultdict(list)
self.lengths = {}
for name, encoded in self.schemas.items():
tokens = terms(f"{name} {json.loads(encoded)['description']}")
self.lengths[name] = len(tokens)
for term, count in Counter(tokens).items():
self.postings[term].append((name, count))
self.average = sum(self.lengths.values()) / max(1, len(self.schemas))
def search(self, query, k):
if not isinstance(query, str) or type(k) is not int or not 1 <= k <= 5:
raise ValueError("search expects a text query and k from 1 through 5")
scores = defaultdict(float)
size = len(self.schemas)
k1, b = 1.2, 0.75 # Reference implementation parameters.
for term in sorted(set(terms(query))):
posting = self.postings.get(term, ())
idf = log1p((size - len(posting) + 0.5) / (len(posting) + 0.5))
for name, count in posting:
norm = 1 - b + b * self.lengths[name] / self.average
scores[name] += idf * count * (k1 + 1) / (count + k1 * norm)
names = sorted(scores, key=lambda name: (-scores[name], name))[:k]
return [json.loads(self.schemas[name]) for name in names]
Save both blocks in order as registry.py. The request and result envelope below belongs to this example. Translate it into your provider’s ordinary client tool calls and tool results, preserving the call ID. OpenAI and Anthropic have their own message formats. The inner JSON stays data in the conversation, so a discovered tool is invoked by calling invoke_tool with the chosen identifier and argument object. Its result is appended after the invocation. The demo shows the host side and uses local functions with no MCP transport or network calls. OpenAI function calling, Anthropic tool search documentation
class Session:
def __init__(self, registry, handlers):
self.registry = registry
self.handlers = dict(handlers)
if self.handlers.keys() != registry.schemas.keys():
raise ValueError("index the same authorized tools the session can invoke")
self.history = []
self.discovered = set()
def request(self):
return {"tools": json.loads(TOOLS), "conversation": json.loads(json_bytes(self.history))}
def call(self, call_id, name, arguments):
if name == "search_tools":
result = self.registry.search(**arguments)
self.discovered.update(tool["name"] for tool in result)
elif name == "invoke_tool":
if not isinstance(arguments, dict) or arguments.keys() != {"tool", "arguments"}:
raise ValueError("invoke expects a tool and its arguments")
tool, parameters = arguments["tool"], arguments["arguments"]
if not isinstance(tool, str) or not isinstance(parameters, dict):
raise ValueError("invoke expects a tool name and an argument object")
if tool not in self.discovered or tool not in self.handlers:
raise ValueError("tool is unavailable; search first")
handler = self.handlers[tool]
result = handler(**parameters)
else:
raise ValueError("unknown front-door tool")
encoded = json_bytes(result).decode("utf-8")
self.history.extend([
{"kind": "tool_call", "id": call_id, "name": name,
"arguments": json.loads(json_bytes(arguments))},
{"kind": "tool_result", "call_id": call_id, "content": encoded},
])
return result
def lookup_receipt(receipt_id):
if not isinstance(receipt_id, str):
raise ValueError("receipt_id must be text")
return {"receipt_id": receipt_id, "found": receipt_id == "R7"}
def list_currencies():
return ["USD", "EUR"]
def demo_session():
catalog = [
schema("billing_lookup_receipt", "Find a billing receipt by receipt ID.",
receipt_id={"type": "string"}),
schema("billing_list_currencies", "List supported billing currencies."),
]
return Session(Registry(catalog), {
"billing_lookup_receipt": lookup_receipt,
"billing_list_currencies": list_currencies,
})
if __name__ == "__main__":
session = demo_session()
session.call("c1", "search_tools", {"query": "billing receipt", "k": 1})
result = session.call("c2", "invoke_tool", {
"tool": "billing_lookup_receipt", "arguments": {"receipt_id": "R7"},
})
print(json.dumps(result))
print("Tools SHA-256:", sha256(json_bytes(session.request()["tools"])).hexdigest())
In an integration, the invoker should resolve the identifier through the session’s authorized catalog and validate the arguments against the actual current schema before dispatch. An MCP server should still apply its own argument validation and permissions. Treat a search result as descriptive catalog data. A privileged operation still needs the same authorization or confirmation it would need if called eagerly. If two servers advertise the same name, assign distinct host identifiers and retain the server mapping out of the model’s reach. The example rejects duplicate names and indexes only tools its handler map can invoke. MCP tools specification
Walk a task through search and invocation
Run python3 -B registry.py in the directory where you saved the two blocks. The demo searches for “billing receipt,” ranks billing_lookup_receipt first, and returns that tool’s argument schema. It then invokes the tool with receipt ID R7. The fixture returns {"receipt_id": "R7", "found": true}. Write a small test that compares the serialized tools array before search, after search, and after invocation. Check that the conversation after search remains a prefix of the conversation after invocation, and that attempting to invoke an unlisted tool raises an error.
The invariant is limited to the local tools block and the ordering of this example’s conversation records. Your SDK or gateway may serialize definitions differently or insert its own instructions. A stable block preserves what your application controls. Confirm that the final request stays stable at the relevant prefix boundary and read the provider’s usage to see if it reused that prefix. As a second check, run a query that returns no matching schema. The agent should refine the query or stop with an actionable explanation. An unrelated tool that happened to rank first can turn an easy recovery into a misdirected call. Anthropic tool search documentation
Measure the extra turn and retrieval quality
In the local design, the model issues a search, sees the schema in a result, and then decides how to call it. Relative to an eager configuration where it could invoke the tool immediately, that adds a model round trip on a discovery path. Charge that path for the search call’s generated arguments, the continuation with the search result, and whatever carried context the provider bills on those requests. Also count repeat searches and the times the returned schema remains in later history. Compare the full session cost and latency against the eager baseline with its cache warm as well as cold. When a workflow chooses the tool in application code before the first model request, include that route in the comparison if it fits the product. MCP tool definition token cost
In its November 24, 2025 post, Anthropic reported internal MCP evaluation improvements with Tool Search Tool enabled, from 49% to 74% for Opus 4 and from 79.5% to 88.1% for Opus 4.5. The RAG-MCP paper’s authors report 43.13% tool selection accuracy versus their 13.62% baseline on benchmark tasks. The paper used semantic retrieval, and the local example uses lexical BM25. Treat the figures as evidence from those evaluations and test the retrieval method on your catalog. Give your evaluation both obvious queries that share vocabulary with tool descriptions and paraphrases that express the same intent differently. Anthropic’s internal evaluation, RAG-MCP paper
Include a task that discovers a tool and then uses it several times. Keeping the search result in history lets the model refer back to the same argument schema without another lookup. Also include a task that changes domains midway. When the model moves from tracing a receipt to checking a support case, compare the cost of the second search and retained billing schema with the cost of exposing both namespaces from the beginning. Record when a previously discovered tool becomes unavailable so you can distinguish stale results from ranking failures.
Pick a rollout criterion
Create a list of tasks with expected tools and record whether each expected schema appears in the results. Separately check whether the model chooses it, supplies valid arguments, and completes the user’s task. A correct tool may be ranked too low for the selected result limit, and a model may still pick an incorrect tool from a good shortlist. Diagnose those failures independently. If the catalog uses different vocabulary from your users, try adding accurate task terms to the descriptions and replay the failures before changing the retrieval algorithm.
Adopt the lazy registry on a route only after its discovery rate and accepted-task spend compare well with the eager configuration. If the app mostly uses a small set of operations, start with that set direct and test discovery on the long tail. If the main overhead comes from many sequential calls after discovery, measure that problem separately from schema retrieval. MCP tool selection accuracy, Programmatic tool calling versus tool loops, Build an agent cost ledger
Sources
- Tool search tool (Anthropic, accessed 2026-11-30)
- Function calling (OpenAI, accessed 2026-11-30)
- Tools specification (Model Context Protocol, accessed 2026-11-30)
- Introducing advanced tool use (Anthropic, accessed 2026-11-30)
- RAG-MCP (RAG-MCP authors, accessed 2026-11-30)
Interactive report
- The Tool Tax: Connecting a tool server can make the very next request bigger, even if the agent never calls it. Follow the cost of the catalog, the search, and the results that come back.
How this note was produced
Drafted with AI assistance from committed ByteCosts pricing snapshots and deterministic cost formulas. Figures are grounded in the linked sources (last updated 2026-11-30). Read our editorial & automation policy, inspect the methodology, or report a discrepancy.
Build a Lazy MCP Tool Registry That Keeps the Tools Array Stable. ByteCosts. Updated 2026-11-30. https://bytecosts.com/blog/lazy-mcp-tool-registry/