Your Mastra agents can now load tools on demand with ToolSearchProcessor for sharper tool selection and reduced token usage and cost.
The processor exposes two built-in tools:
search_tools: Finds matching tools by keyword against toolidanddescription.load_tool: Loads a tool into the agent's active tool set.
By default, agents load tools eagerly, exposing every registered tool to the model on every turn. As tool sets grow, token usage increases and tool selection accuracy drops. Now with a ToolSearchProcessor, tools load on demand: the agent searches for tools and only loads what it needs, keeping tool selection sharp and token usage low.
When the agent needs a tool, it calls search_tools, finds matches, then uses load_tool to load it. Subsequent turns can call the loaded tool directly. Loaded tools stay in thread state for a configurable TTL (default 1 hour) before they're cleaned up. There's a small latency cost for the first lookup of each tool, but following turns run with reduced token usage.
Get started
Install the latest Mastra core package:
npm install @mastra/core@mastra/core@1.58.0 or later, added in PR #12290.Create a ToolSearchProcessor and attach it to an agent.
Configure the search settings: topK caps search results and minScore sets a minimum relevance threshold. ttl controls how long loaded tools stay in thread state before cleanup.
Attach the processor to an agent:
import { Agent } from "@mastra/core/agent";
import { ToolSearchProcessor } from "@mastra/core/processors";
import { allTools } from "../tools";
const toolSearch = new ToolSearchProcessor({
tools: allTools,
search: { topK: 5, minScore: 0 },
ttl: 3_600_000 // 1 hour
});
export const agentOnDemand = new Agent({
id: "agent-on-demand",
name: "Agent (on-demand)",
instructions: /* ... */,
model: "anthropic/claude-opus-4-7",
inputProcessors: [toolSearch]
});ToolSearchProcessor adds search_tools and load_tool to the agent's tool set. It runs before the LLM call to find and inject the required tools. On subsequent turns, it re-injects any previously loaded tools.
For more information and full configuration options, see:
