Skip to main content

Filter tools

Documentation for v0.0.1. Additional guides and API reference coverage are being expanded.
Ranking and filtering examples do not prove provider compatibility or grant execution permission. await router.filterTools(options) returns scored, ordered tool descriptors so your application can shortlist relevant tools. It never dispatches a tool or grants permission to call one. Source discovery may connect to MCP servers, and an explicitly selected provider-backed ranker may make model requests.

Choose a ranking approach

These are alternatives, not automatically chained stages. Choosing an LLM ranker does not first run lexical or embedding ranking. A limit of five caps the returned shortlist, not the number of tools sent to the ranker. Narrow the sources and eligibility policy before ranking to reduce exposure and work.

Which ranker wins?

  1. Per-call model: 'alias' selects exactly models.alias.ranking on this router.
  2. Otherwise, per-call ranker overrides the router’s configured ranker.
  3. Otherwise, the router’s configured ranker is used, or lexical ranking if none is configured.
model and ranker are mutually exclusive on a filterTools() call. ranker takes an adapter, not a raw language model. A model alias is a host-defined name, not a provider model ID. For a nonblank prompt, an unknown alias rejects with model_not_found; an entry without .ranking rejects with model_capability_unavailable. There is no silent fallback to another ranker. The router’s top-level model default and policy.modelBindings select routing for execution; they do not choose the filter ranker. policy.modelAccess, when configured, also governs ranking access. See model bindings and access.

Start with lexical filtering

This complete example uses two synthetic raw MCP definitions. It needs only the core package: no provider, credentials, server connection or tool handler. The policy allows these demo definitions into retrieval for a reader but denies execution.
In production, context must come from your authenticated server, not model text or an untrusted request field. Replace the demo name checks with your own trusted eligibility policy. The required revision callback returns a constant only because these example policies are fixed; advance your production policy revision when rules or grants change. No policy means no eligible results; ranking is not a way around policy. For real MCP inventories, use the trusted MCP-server array and policy instead of these raw definitions. Lexical scoring sends no prompt or catalogue to a model, but server discovery can still perform network I/O.

Semantic ranking with an embedding provider

createSemanticRanker() is an embedding adapter, not an LLM scoring adapter. It embeds the prompt and a canonical projection of each eligible tool’s name, description, input schema and output schema, normalizes the vectors, and compares cosine similarity. The host must supply an EmbeddingProvider whose embed({ texts, signal, deadline }) returns a promise of vectors: one per input text, in the same order, each with exactly dimensions finite numbers and a nonzero norm. It must respect cancellation and the absolute monotonic deadline (performance.now() time origin). The helper does not download an embedding model or implement your provider’s transport. This reusable function takes the host’s actual embedding implementation and configuration. The caller must already approve every supplied raw definition for retrieval; the allow-all eligibility below is limited to that explicit input set. It denies execution.
  • identity contains nonempty provider, model and version strings identifying the actual embedding implementation. Keep them accurate when changing models or versions.
  • dimensions must match the returned vectors and fit the router’s limits.embeddingDimensions (default 4,096; configurable up to 8,192).
  • egress is { kind: 'in_process' } for in-process embeddings, or { kind: 'http', url, allowRemote } for HTTP. Non-loopback endpoints require HTTPS and allowRemote: true; URLs cannot contain credentials, query strings or fragments. HTTP is allowed only for loopback endpoints.
  • Egress is a declaration, not a network sandbox. The trusted callback owns the actual requests, credentials and destination restrictions. Never label a remote provider as in-process.
  • batchSize defaults to 32 texts, with a maximum of 64. It is not the result limit. The router can cache descriptor embeddings; the prompt is embedded on each invocation.
The example’s 0.3 threshold is illustrative, not a recommended universal relevance cutoff. Evaluate it with your model and tool catalogue. This composition does not claim live embedding-provider compatibility.

LLM relevance scoring with a model alias

createModelRanker() asks a language model for a score from 0 to 1 for every supplied candidate. It validates the complete score output; it does not generate embeddings, choose call arguments or execute a tool. Use the compatible optional AI SDK dependencies. The model parameter below must be a ConfiguredLanguageModel produced by createBoundedModel(), not a raw provider model or a string. The shared model configuration shows how to construct one with a host-owned fetch, approved endpoint and server-side credentials. Do not invoke this function until provider exposure and spending are authorized. The adapter also checks every eligible tool’s input schema before sending a model request. Its restricted schema profile requires explicit object properties, additionalProperties: false, and required listing every property (including required: [] for an empty object). Arrays require items; scalar types are string, number, integer, boolean or null, with supported enum, string-length and numeric-bound constraints. References, unions and other unsupported keywords reject with unsupported_schema. Do not silently rewrite a real tool’s schema to fit this profile; choose a compatible tool set or another ranker. As with the semantic example, tools must be an explicitly approved retrieval set of raw definitions. This router denies execution and restricts model access to its configured alias. Raw/unbound sources work with this global allowlist, but non-lexical ranking rejects them if any server/tool-scoped model-access rules are configured: raw definitions cannot prove those bindings, even if eligibility filters some out.
Here model: 'relevance' selects models.relevance.ranking. To pass the same adapter directly, use ranker: llmRanker instead of the per-call model field, while retaining any required model-access configuration. With an applicable allowlist, a direct or default ranker must be the same adapter object registered under exactly one permitted alias. Registering that object under multiple aliases makes direct selection ambiguous; select the permitted alias explicitly instead. To make it the default, set the router configuration’s ranker property to llmRanker. The adapter defaults to batchSize: 32 and maxRequests: 8, also bounded by the router’s ranking limits. Large candidate sets can fail with resource_limit; lowering the returned limit does not reduce the input batches. Model ranking may expose the prompt, tool descriptions and schemas to the configured provider. Scores are relevance judgments, not calibrated probabilities or permission decisions.

Bring your own ranker

A custom Ranker implements rank(request) and returns an array (or a promise of an array) of candidate descriptors with a finite score in [-1, 1]. Preserve every descriptor field, return each tool at most once, and never invent tool IDs. Return all qualifying candidates; the router validates, sorts and applies the result limit. This deliberately simple exact-name adapter is model-free. Pass it as ranker: exactNameRanker in a filter call or in the router configuration; it is not a semantic search implementation.
The request includes prompt, eligible tools, signal, an absolute monotonic deadline, an optional explicit threshold, and data-only embedding/ranking limits. It does not provide request context, authorization callbacks or transport secrets. Your callback still owns its I/O and must respect cancellation and deadlines; router bounds are not a sandbox for arbitrary host code. A custom ranker is subject to configured model-access rules even if its implementation happens to be model-free.

All filter options

These are the complete FilterToolsOptions fields for 0.0.1. Only prompt is required. Omit unused optional properties rather than supplying undefined.

Source selection

ToolSource is a raw MCPTool, a FilterToolDescriptor (bound or unbound), or a trusted ServerConfig. Endpoints, commands and credentials must come from the host, never model output.
  • If both tools and servers are omitted, the operation uses the router’s known local registrations and connected-server inventories.
  • If either field is supplied, only the explicit union is selected. A server configuration contributes that server’s inventory; a descriptor contributes only that tool, not all tools on its server.
  • tools: [] alone or servers: [] alone selects nothing. An empty field does not cancel a nonempty companion field: tools: [] with nonempty servers still selects those servers.
  • Duplicate compatible server configurations are deduplicated; conflicting configurations are rejected rather than silently overridden.
  • Policy eligibility is applied before exposing candidates to a ranker. An empty shortlist can mean no eligible tools, no matches or no scores above the threshold; it does not necessarily mean discovery failed.

Threshold defaults and score meaning

An explicit threshold is passed to the ranker and enforced again by the router on returned scores before the limit. It does not restore candidates a custom adapter has already omitted. Scores from different ranking approaches are not interchangeable; tune cutoffs on your own workload rather than treating a score as confidence or authorization.

Results and next steps

The return type is Promise<RankedTool[]>: each result preserves its descriptor fields and adds score. Results are ordered by descending score with deterministic tie-breaking, and may contain fewer than limit entries or be empty. Raw definitions remain unbound, even after ranking. They cannot be executed simply because they scored well. For a current bound result you intend to reuse as an execute source, first check that it exists and remove the output-only score (const { score, ...boundDescriptor } = selected[0];). A fresh authorization check still happens at execution; no score proves arguments are valid or a call is allowed. Malformed options can reject with RouterConfigError; discovery, policy, resource, cancellation or provider failures can reject with RouterOperationError instead of returning an empty array. See results and errors. Own each router’s lifetime and close it in finally. To perform one governed action, scope an execute. For local filtering latency, read Benchmarks. It explains the qualified p95 24.893034 ms result against the p95 ≤ 50 ms target, the 1,000-tool workload and hosted-VM venue exception, and why this is not an AI-response or network-latency claim.