|
| 1 | +// ToolSearch tool — deferred-tool loading. Lets the agent discover and |
| 2 | +// "expand" tools that aren't loaded by default (large MCP toolkits, computer- |
| 3 | +// use tools, etc.) without bloating the system prompt with their full schema. |
| 4 | +// |
| 5 | +// Spec: docs/DEVELOPMENT_PLAN.md §3.15.6 |
| 6 | +// |
| 7 | +// Wire-up: |
| 8 | +// · ToolRegistry tracks a `deferred` map of name → { description, expand() }. |
| 9 | +// · Agent loop exposes ONLY the deferred-tool names (not schemas) until |
| 10 | +// ToolSearch is called with `select:Name1,Name2,...`. |
| 11 | +// · The tool returns the schemas and asks the registry to register them. |
| 12 | + |
| 13 | +import type { ToolContext, ToolHandler, ToolResult } from '../types.js'; |
| 14 | + |
| 15 | +export interface DeferredToolEntry { |
| 16 | + name: string; |
| 17 | + description: string; |
| 18 | + /** Lazily produce the full ToolHandler when the tool is "expanded". */ |
| 19 | + expand: () => Promise<ToolHandler> | ToolHandler; |
| 20 | +} |
| 21 | + |
| 22 | +export interface DeferredToolStore { |
| 23 | + /** Returns all deferred entries (for keyword search). */ |
| 24 | + list(): DeferredToolEntry[]; |
| 25 | + /** Expand and register an entry; idempotent on already-registered names. */ |
| 26 | + expand(name: string): Promise<ToolHandler | undefined>; |
| 27 | +} |
| 28 | + |
| 29 | +interface SearchInput { |
| 30 | + query: string; |
| 31 | + max_results?: number; |
| 32 | +} |
| 33 | + |
| 34 | +const DEFAULT_MAX_RESULTS = 5; |
| 35 | + |
| 36 | +export function makeToolSearchTool(store: DeferredToolStore): ToolHandler { |
| 37 | + return { |
| 38 | + name: 'ToolSearch', |
| 39 | + definition: { |
| 40 | + name: 'ToolSearch', |
| 41 | + description: |
| 42 | + 'Find and load deferred tools by name or keyword. Use "select:Name1,Name2" to load tools by exact name; otherwise the query is matched as a fuzzy keyword search against tool names and descriptions. Once loaded, the tools become callable in subsequent turns.', |
| 43 | + inputSchema: { |
| 44 | + type: 'object', |
| 45 | + properties: { |
| 46 | + query: { |
| 47 | + type: 'string', |
| 48 | + description: |
| 49 | + 'Either "select:<csv of tool names>" or a free-text query matching name+description.', |
| 50 | + }, |
| 51 | + max_results: { |
| 52 | + type: 'number', |
| 53 | + description: 'Cap on results for keyword queries (default 5).', |
| 54 | + }, |
| 55 | + }, |
| 56 | + required: ['query'], |
| 57 | + }, |
| 58 | + }, |
| 59 | + async execute(rawInput: Record<string, unknown>, _ctx: ToolContext): Promise<ToolResult> { |
| 60 | + const input = rawInput as unknown as SearchInput; |
| 61 | + if (!input?.query || typeof input.query !== 'string') { |
| 62 | + return { content: 'Error: query is required (string).', isError: true }; |
| 63 | + } |
| 64 | + const max = Math.max(1, input.max_results ?? DEFAULT_MAX_RESULTS); |
| 65 | + |
| 66 | + if (input.query.startsWith('select:')) { |
| 67 | + const names = input.query |
| 68 | + .slice('select:'.length) |
| 69 | + .split(',') |
| 70 | + .map((s) => s.trim()) |
| 71 | + .filter(Boolean); |
| 72 | + const loaded: string[] = []; |
| 73 | + const missing: string[] = []; |
| 74 | + for (const n of names) { |
| 75 | + const h = await store.expand(n); |
| 76 | + if (h) loaded.push(h.name); |
| 77 | + else missing.push(n); |
| 78 | + } |
| 79 | + const lines: string[] = []; |
| 80 | + if (loaded.length > 0) lines.push(`Loaded: ${loaded.join(', ')}`); |
| 81 | + if (missing.length > 0) lines.push(`Not found: ${missing.join(', ')}`); |
| 82 | + if (lines.length === 0) lines.push('No tools loaded.'); |
| 83 | + return { content: lines.join('\n'), data: { loaded, missing } }; |
| 84 | + } |
| 85 | + |
| 86 | + // Keyword search — rank by token overlap of name + description |
| 87 | + const tokens = input.query |
| 88 | + .toLowerCase() |
| 89 | + .split(/\s+/) |
| 90 | + .filter((t) => t.length > 0); |
| 91 | + const ranked = store |
| 92 | + .list() |
| 93 | + .map((e) => ({ entry: e, score: score(e, tokens) })) |
| 94 | + .filter((r) => r.score > 0) |
| 95 | + .sort((a, b) => b.score - a.score) |
| 96 | + .slice(0, max); |
| 97 | + if (ranked.length === 0) { |
| 98 | + return { content: `No deferred tools matched "${input.query}".`, data: { hits: [] } }; |
| 99 | + } |
| 100 | + const lines = ranked.map( |
| 101 | + (r) => `${r.entry.name} — ${r.entry.description.slice(0, 120)}`, |
| 102 | + ); |
| 103 | + lines.push(''); |
| 104 | + lines.push(`Use \`select:${ranked.map((r) => r.entry.name).join(',')}\` to load.`); |
| 105 | + return { |
| 106 | + content: lines.join('\n'), |
| 107 | + data: { hits: ranked.map((r) => ({ name: r.entry.name, score: r.score })) }, |
| 108 | + }; |
| 109 | + }, |
| 110 | + }; |
| 111 | +} |
| 112 | + |
| 113 | +function score(entry: DeferredToolEntry, tokens: string[]): number { |
| 114 | + if (tokens.length === 0) return 0; |
| 115 | + const text = `${entry.name} ${entry.description}`.toLowerCase(); |
| 116 | + let s = 0; |
| 117 | + for (const t of tokens) { |
| 118 | + if (entry.name.toLowerCase() === t) s += 100; |
| 119 | + else if (entry.name.toLowerCase().includes(t)) s += 10; |
| 120 | + if (text.includes(t)) s += 1; |
| 121 | + } |
| 122 | + return s; |
| 123 | +} |
| 124 | + |
| 125 | +/** |
| 126 | + * Default DeferredToolStore backed by a ToolRegistry. Builds an internal map |
| 127 | + * of name → entry on construction; expand() calls registry.register(). |
| 128 | + */ |
| 129 | +export class RegistryDeferredStore implements DeferredToolStore { |
| 130 | + private readonly entries = new Map<string, DeferredToolEntry>(); |
| 131 | + constructor( |
| 132 | + private readonly registry: { register: (h: ToolHandler) => void; get: (name: string) => ToolHandler | undefined }, |
| 133 | + entries: DeferredToolEntry[], |
| 134 | + ) { |
| 135 | + for (const e of entries) this.entries.set(e.name, e); |
| 136 | + } |
| 137 | + list(): DeferredToolEntry[] { |
| 138 | + return [...this.entries.values()]; |
| 139 | + } |
| 140 | + async expand(name: string): Promise<ToolHandler | undefined> { |
| 141 | + const existing = this.registry.get(name); |
| 142 | + if (existing) return existing; |
| 143 | + const entry = this.entries.get(name); |
| 144 | + if (!entry) return undefined; |
| 145 | + const handler = await entry.expand(); |
| 146 | + this.registry.register(handler); |
| 147 | + return handler; |
| 148 | + } |
| 149 | +} |
0 commit comments