Skip to content

Commit bfc94dc

Browse files
committed
feat(tool): add tool_search for dynamic tool discovery
Adds a new tool_search tool that allows the LLM to search for available tools by name or description using regex patterns. This is the first step toward reducing context window usage when many tools are available. Relates to anomalyco#2418
1 parent bbb3120 commit bfc94dc

2 files changed

Lines changed: 47 additions & 0 deletions

File tree

‎packages/opencode/src/tool/registry.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import { Log } from "@/util/log"
2626
import { LspTool } from "./lsp"
2727
import { Truncate } from "./truncation"
2828
import { PlanExitTool, PlanEnterTool } from "./plan"
29+
import { ToolSearchTool } from "./tool-search"
2930

3031
export namespace ToolRegistry {
3132
const log = Log.create({ service: "tool.registry" })
@@ -108,6 +109,7 @@ export namespace ToolRegistry {
108109
WebSearchTool,
109110
CodeSearchTool,
110111
SkillTool,
112+
ToolSearchTool,
111113
...(Flag.OPENCODE_EXPERIMENTAL_LSP_TOOL ? [LspTool] : []),
112114
...(config.experimental?.batch_tool === true ? [BatchTool] : []),
113115
...(Flag.OPENCODE_EXPERIMENTAL_PLAN_MODE && Flag.OPENCODE_CLIENT === "cli" ? [PlanExitTool, PlanEnterTool] : []),
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import z from "zod"
2+
import { Tool } from "./tool"
3+
import { ToolRegistry } from "./registry"
4+
5+
export const ToolSearchTool = Tool.define("tool_search", {
6+
description: `Search for available tools by name or description.
7+
Use this when you need to find a tool for a specific task.
8+
Returns a list of matching tool names that you can then use.`,
9+
parameters: z.object({
10+
query: z.string().describe("Regex pattern to search tool names and descriptions"),
11+
}),
12+
async execute(params, ctx) {
13+
const tools = await ToolRegistry.tools("", ctx.extra?.agent)
14+
const regex = new RegExp(params.query, "i")
15+
16+
const matches: { id: string; description: string }[] = []
17+
for (const tool of tools) {
18+
if (tool.id === "tool_search" || tool.id === "invalid") continue
19+
if (regex.test(tool.id) || regex.test(tool.description)) {
20+
matches.push({
21+
id: tool.id,
22+
description: tool.description.slice(0, 100),
23+
})
24+
}
25+
}
26+
27+
if (matches.length === 0) {
28+
return {
29+
title: "No tools found",
30+
metadata: { matches: 0 },
31+
output: `No tools found matching "${params.query}"`,
32+
}
33+
}
34+
35+
const output = matches
36+
.map((m) => `- ${m.id}: ${m.description}`)
37+
.join("\n")
38+
39+
return {
40+
title: `Found ${matches.length} tools`,
41+
metadata: { matches: matches.length, tools: matches.map((m) => m.id) },
42+
output: `Found ${matches.length} tool(s) matching "${params.query}":\n${output}`,
43+
}
44+
},
45+
})

0 commit comments

Comments
 (0)