Skip to content

Tool Discovery

When a registry contains dozens or hundreds of tools, sending every tool schema in the initial prompt wastes tokens and degrades LLM performance. ToolDiscoveryTool lets the LLM discover relevant tools on demand via exact name lookup or natural language queries, powered by BM25F (Best Matching 25 with Field weighting) sparse search.

Changelog

New in version: 0.7.0 (#108) Updated in: #114 — enable_tool_search(), include_deferred, schema in search results Updated in: #118 — Renamed to ToolDiscoveryTool / discover_tools, added exact match, get_deferred_summaries()

Overview

flowchart LR
    LLM -- "discover('compress_file')" --> ToolDiscoveryTool
    ToolDiscoveryTool -- "exact match" --> ExactResult["[{name, schema, score: 1.0}]"]
    LLM -- "discover('compress file')" --> ToolDiscoveryTool
    ToolDiscoveryTool -- "BM25F index" --> FuzzyResults["[{name, description, score, ...}]"]

ToolDiscoveryTool supports two modes:

  1. Exact match — if the query matches a registered tool name, the full schema is returned immediately (score 1.0).
  2. Fuzzy search — otherwise, a BM25F multi-field search is performed.

Five fields are indexed per tool with configurable weights:

Field Default Weight Source
name 3.0 Tool name (underscores → spaces)
description 2.0 Tool docstring / description
search_hint 2.0 ToolMetadata.search_hint
tags 1.5 ToolMetadata.tags + custom_tags
params 1.0 Parameter names from JSON schema

Quick Start

The easiest way to enable tool discovery is via enable_tool_discovery(), which registers a discover_tools callable into the registry so LLMs can discover tools autonomously:

from toolregistry import ToolRegistry

registry = ToolRegistry()

@registry.register
def add(a: float, b: float) -> float:
    """Add two numbers together."""
    return a + b

@registry.register
def read_file(path: str) -> str:
    """Read the contents of a file from the filesystem."""
    return open(path).read()

# Enable tool discovery — registers "discover_tools" as a callable tool
registry.enable_tool_discovery()

# LLMs see discover_tools in get_schemas() and can call it to discover tools
schemas = registry.get_schemas(include_deferred=False)

You can also enable it at construction time:

registry = ToolRegistry(tool_discovery=True)

Discovery modes

Discovery follows the deferred set by default. registry.tool_discovery_mode is "auto", which means:

  • registering a tool with ToolMetadata(defer=True) turns discovery on, so discover_tools and call_deferred are registered in the same operation;
  • undoing the last deferral — unregistering the tool, un-deferring it, or disabling it — turns discovery off again.

enable_tool_discovery() and disable_tool_discovery() pin the mode to "on" and "off" instead. An explicit choice survives later registrations: a registry switched on stays on when its last deferred tool disappears, and one switched off stays off when a deferred tool is registered — those tools are then unreachable to a model until discovery is enabled. Choose the behaviour directly with:

registry.set_tool_discovery_mode("auto")   # follow the deferred set (default)
registry.set_tool_discovery_mode("on")     # always on
registry.set_tool_discovery_mode("off")    # always off

Turning discovery off emits an UNREGISTER change event for each of the two tools, so anything that mirrors the registry — the route table behind the MCP server, the OpenAPI document — refreshes what it advertises instead of keeping a tool the registry no longer has.

Standalone Usage

If you prefer to use ToolDiscoveryTool directly without registering it:

from toolregistry import ToolRegistry
from toolregistry.tool_discovery import ToolDiscoveryTool

registry = ToolRegistry()
# ... register tools ...

discoverer = ToolDiscoveryTool(registry)

# Exact match — returns full schema
results = discoverer.discover("read_file")
print(results[0]["schema"])  # full tool definition

# Fuzzy search — BM25 ranking
results = discoverer.discover("read text file")
print(results[0]["name"])   # "read_file"
print(results[0]["score"])  # 1.23 (BM25 score)

Discovery Results

Each result is a dict with these keys:

Key Type Description
name str Tool name (identifier)
description str Tool description
score float BM25 relevance score (1.0 for exact match)
namespace str \| None Tool namespace, if any
deferred bool Whether the tool is marked as deferred
schema dict Full tool schema (always for exact match; only deferred tools in fuzzy mode)

For exact matches, the result always includes the full tool schema regardless of deferred status. For fuzzy search, only deferred tools include their schema so the LLM can call them immediately after discovery.

A tool whose result shape is declared in ToolMetadata(extra={"output_schema": ...}) — the same field the server publishes as MCP outputSchema — also reports it inside the returned schema, beside the input parameters (inside function for OpenAI-style definitions, at the top level for the flat openai-responses, Anthropic and Gemini shapes). Without it a model learns what a deferred tool takes but not what it returns, even though the tool emits structured content.

Only enabled tools are searchable: a tool disabled at the method or namespace level disappears from both discover_tools and get_deferred_summaries(). query must be a non-empty, non-whitespace string and top_k must be at least 1 — the generated schema declares both, and the runtime raises ValueError if they arrive anyway. Matching runs against each tool's name, description, tags, parameter names and search_hint; coverage is strongest for English keywords, and CJK queries are supported through character bigrams.

results = discoverer.discover("email", top_k=3)
for r in results:
    print(f"{r['name']}: {r['score']:.2f} — {r['description']}")
    if r.get("schema"):
        print(f"  Schema: {r['schema']}")

Relevance Floor

Fuzzy results are cut relative to the best hit: any hit scoring below min_score_ratio (default 0.3) of the top score is dropped, so a query with one clear match is not padded with tools that merely share a token. The best hit is always kept; exact-name lookups bypass the floor entirely.

# Stricter (keep only hits within 50% of the best score)
registry.enable_tool_discovery(min_score_ratio=0.5)

# Disable the floor and get the raw top_k list
registry.enable_tool_discovery(min_score_ratio=0.0)

# Same knob on the standalone object
discoverer = ToolDiscoveryTool(registry, min_score_ratio=0.3)

The floor is relative, not absolute: BM25 scores are not comparable across queries (they depend on corpus size, IDF and query length), so a fixed absolute cutoff would drop valid results for short corpora and keep noise for long ones. A query that matches nothing well keeps its near-tied hits rather than returning an empty list, which would leave a model with no next step.

Query Token Filter

A query made of words the corpus uses everywhere is not a search. Tokens appearing in at least max_df_ratio (default 0.5) of the indexed tools are dropped before scoring, so "for" and "a" in "weather forecast for a city" stop matching every description that happens to contain them. If the filter would remove every token, the search falls back to the query's capability tokens — the ones that appear in at least one tool name — and keeps the rarest, so on a homogeneous corpus "file on disk" still matches the four file tools that "file" matches rather than returning nothing. A query made only of boilerplate words ("the a of") has no capability token and returns an empty list rather than near-tied filler.

The filter is corpus-adaptive — document frequency, not an English stopword list — so it works for any language and for domain vocabulary. A term only counts as filler once it appears in at least three indexed tools, so in a small registry a word shared by two of four tools is still searched rather than dropped at the 50% boundary. A single-token query is never filtered: one word is a capability keyword, and discarding it would make that capability unfindable. Disable the filter with max_df_ratio=0:

registry.enable_tool_discovery(max_df_ratio=0.0)

The two stages compose: the token filter removes words that match too broadly, then the score floor drops hits far below the winner.

Progressive Disclosure

The recommended workflow for large registries:

  1. Mark rarely-used tools as deferred with ToolMetadata(defer=True)
  2. Use get_schemas(include_deferred=False) to send only essential tools to the LLM
  3. Inject deferred tool summaries via get_deferred_summaries() into the system prompt
  4. Enable discover_tools so the LLM can look up any tool by name or query
from toolregistry import Tool, ToolMetadata, ToolTag

registry = ToolRegistry(tool_discovery=True)

# Core tools — always visible
@registry.register
def add(a: float, b: float) -> float:
    """Add two numbers."""
    return a + b

# Deferred tools — discoverable on demand
registry.register(
    Tool.from_function(
        compress_file,
        metadata=ToolMetadata(
            defer=True,
            tags={ToolTag.FILE_SYSTEM},
        ),
    )
)

# 1. Non-deferred schemas for LLM tools parameter
schemas = registry.get_schemas(include_deferred=False)

# 2. Deferred summaries for system prompt
summaries = registry.get_deferred_summaries()
# [{"name": "compress_file", "description": "Compress a file into a zip archive.", "namespace": None}]

Deferred Summaries

get_deferred_summaries() returns a lightweight list of deferred tool names with first-sentence descriptions, suitable for system prompt injection:

summaries = registry.get_deferred_summaries()
for s in summaries:
    print(f"- {s['name']}: {s['description']}")

Each summary contains:

Key Type Description
name str Tool name
description str First sentence of the tool description
namespace str \| None Tool namespace, if any

Only enabled deferred tools are included. The description is truncated to the first sentence (text before the first . on the first line).

Invoking Deferred Tools via call_deferred

When tool discovery is enabled, a call_deferred proxy tool is registered alongside discover_tools. It bridges the gap for MCP clients that cache tools/list at initialization and cannot dynamically register newly discovered tools.

The workflow is:

  1. LLM calls discover_tools(query="search") → receives the deferred tool's full schema
  2. LLM calls call_deferred(_target_tool="search", query="hello") → the registry executes the deferred tool through the full pipeline (permissions, execution backend, logging)

call_deferred only accepts deferred tools — calling it with a non-deferred tool raises ValueError.

call_deferred is a proxy, not a permission bypass: the registry resolves the target and runs the call through the same access check as a direct call, using the target's arguments. A policy that denies the target denies the proxy call too, including rules that depend on parameter values. Both the proxy call and the dispatched call appear in the execution log.

Tool names are matched leniently. Both discover_tools and call_deferred resolve a name after collapsing / and - to _ and folding case, so a name rewritten by an MCP client — weather_get_current for the registered weather-get-current — still reaches the right tool. An exact registered spelling always wins over a normalized match. When no tool matches, the error lists the closest registered names so the caller can self-correct in one turn.

Both discover_tools and call_deferred are registered and unregistered together via enable_tool_discovery() / disable_tool_discovery(). Their names are available as constants: TOOL_DISCOVERY_NAME and TOOL_CALL_DEFERRED_NAME from toolregistry.llm.discovery.

Search Hints

Use ToolMetadata.search_hint to add synonyms, related concepts, or domain-specific terms that improve discoverability:

registry.register(
    Tool.from_function(
        read_file,
        metadata=ToolMetadata(
            search_hint="open load text content cat",
        ),
    )
)

The search_hint field is indexed at weight 2.0 (same as description), so these keywords influence ranking just as strongly as the tool's own description.

Custom Field Weights

Override the default BM25F field weights to tune ranking for your use case:

# Via enable_tool_discovery()
registry.enable_tool_discovery(field_weights={
    "name": 5.0,          # Boost exact name matches
    "description": 1.0,
    "tags": 3.0,          # Boost tag-based discovery
    "params": 0.5,
    "search_hint": 2.0,
})

# Or via standalone ToolDiscoveryTool
discoverer = ToolDiscoveryTool(
    registry,
    field_weights={
        "name": 5.0,
        "description": 1.0,
        "tags": 3.0,
        "params": 0.5,
        "search_hint": 2.0,
    },
)

Rebuilding the Index

The index automatically rebuilds whenever tools are registered, unregistered, re-enabled or updated, powered by the ChangeCallback mechanism. This holds both for enable_tool_discovery() and for a ToolDiscoveryTool you construct directly: the discoverer subscribes itself, and the rebuild happens lazily on the next discover() call, so a bulk change costs one rebuild rather than one per event. No manual intervention is needed:

@registry.register
def new_tool(x: int) -> int:
    """A newly added tool."""
    return x * 2

results = discoverer.discover("newly added")
assert results[0]["name"] == "new_tool"

Call discoverer.close() to stop following a registry (idempotent); disable_tool_discovery() does this for you. rebuild_index() remains available to force a rebuild, for example after editing a tool's metadata in place.

Implementation Details

ToolDiscoveryTool uses a vendored copy of zerodep's SparseIndex (v0.2.2) — a pure-Python BM25/BM25F implementation with zero external dependencies. The index lives entirely in memory and is typically negligible in size (100 tools ≈ a few KB).

BM25F parameters:

  • k1 = 1.5 — term frequency saturation
  • b = 0.75 — document length normalization
  • delta = 1.0 — BM25+ floor correction