自定义工具 (Custom Tools)
创建 LLM 可以在 OpenCode 中调用的工具
自定义工具是您创建的函数,LLM 可以在对话中调用它们。它们与
read、write 和 bash 等内置工具并列运行。基本结构
工具使用 TypeScript 或 JavaScript 定义,但定义内部可以调用任何语言编写的脚本。
- 位置:
.opencode/tool/(项目级) 或~/.config/opencode/tool/(全局) - 工具名称: 文件名即为工具名
代码示例 (TypeScript)
import { tool } from "@opencode-ai/plugin"
export default tool({
description: "查询项目数据库",
args: {
query: tool.schema.string().describe("要执行的 SQL 查询"),
},
async execute(args) {
// 数据库逻辑
return `执行了查询: ${args.query}`
},
})
使用其他语言 (如 Python)
您可以编写 Python 脚本,然后通过工具定义来调用它。
- Python 脚本 (
add.py)
import sys
print(int(sys.argv[1]) + int(sys.argv[2]))
- 工具定义 (
python-add.ts)
import { tool } from "@opencode-ai/plugin"
export default tool({
description: "使用 Python 加法",
args: { a: tool.schema.number(), b: tool.schema.number() },
async execute(args) {
const result = await Bun.$`python3 .opencode/tool/add.py ${args.a} ${args.b}`.text()
return result.trim()
},
})
参数与上下文
- 参数: 使用
tool.schema(基于 Zod) 定义参数类型和描述 - 上下文: 工具执行时会接收
context,包含agent、sessionID和messageID等信息