跳转到内容

自定义工具

在 OpenCode 中创建 LLM 可调用的自定义工具。

自定义工具是由你编写、在对话过程中可被 LLM 主动调用的函数。它们与 OpenCode 的内置工具(如 readwritebash 等)一起工作。


创建一个工具

工具以 TypeScriptJavaScript 文件的形式定义。但工具实现内部可以调用任意语言的脚本——TS/JS 只负责“工具定义”这一层。


放置位置

你可以在以下位置定义工具:

  • 项目本地:放在项目目录下的 .opencode/tool/ 中;
  • 全局:放在 ~/.config/opencode/tool/ 中,对所有项目生效。

结构

推荐使用 tool() 辅助函数来创建工具,它提供类型安全和参数校验。

.opencode/tool/database.ts
import { tool } from "@opencode-ai/plugin"
export default tool({
description: "Query the project database",
args: {
query: tool.schema.string().describe("SQL query to execute"),
},
async execute(args) {
// 在这里实现你的数据库逻辑
return `Executed query: ${args.query}`
},
})

文件名会成为工具名。上面的例子会得到一个名为 database 的工具。


一个文件中导出多个工具

你也可以在同一个文件中导出多个工具。每个导出都会成为一个单独的工具,其名称为 <filename>_<exportname>

.opencode/tool/math.ts
import { tool } from "@opencode-ai/plugin"
export const add = tool({
description: "Add two numbers",
args: {
a: tool.schema.number().describe("First number"),
b: tool.schema.number().describe("Second number"),
},
async execute(args) {
return args.a + args.b
},
})
export const multiply = tool({
description: "Multiply two numbers",
args: {
a: tool.schema.number().describe("First number"),
b: tool.schema.number().describe("Second number"),
},
async execute(args) {
return args.a * args.b
},
})

上面的文件会生成两个工具:math_addmath_multiply


参数(Arguments)

可以使用 tool.schema(本质上是 Zod)来定义参数类型:

args: {
query: tool.schema.string().describe("SQL query to execute")
}

你也可以直接引入 Zod,并返回一个普通对象:

import { z } from "zod"
export default {
description: "Tool description",
args: {
param: z.string().describe("Parameter description"),
},
async execute(args, context) {
// 工具实现
return "result"
},
}

上下文(Context)

工具在执行时会收到当前会话的一些上下文信息:

.opencode/tool/project.ts
import { tool } from "@opencode-ai/plugin"
export default tool({
description: "Get project information",
args: {},
async execute(args, context) {
// 访问上下文信息
const { agent, sessionID, messageID } = context
return `Agent: ${agent}, Session: ${sessionID}, Message: ${messageID}`
},
})

示例

用 Python 写一个工具

工具的实际逻辑可以使用任意语言来实现。下面是一个用 Python 实现“两个数相加”的示例。

首先,编写 Python 脚本:

.opencode/tool/add.py
import sys
a = int(sys.argv[1])
b = int(sys.argv[2])
print(a + b)

然后,创建对应的工具定义来调用它:

.opencode/tool/python-add.ts
import { tool } from "@opencode-ai/plugin"
export default tool({
description: "Add two numbers using Python",
args: {
a: tool.schema.number().describe("First number"),
b: tool.schema.number().describe("Second number"),
},
async execute(args) {
const result = await Bun.$`python3 .opencode/tool/add.py ${args.a} ${args.b}`.text()
return result.trim()
},
})

这里我们使用了 Bun.$ 工具来运行 Python 脚本。