关于 OpenCode SDK Development
介绍如何使用 OpenCode SDK 开发自定义工具和插件,也涵盖用于编程访问会话、文件、事件及 MCP 配置的客户端 SDK。
主要功能
- 01创建带模式验证的自定义工具
- 02注册插件钩子
- 03使用会话与文件 API
- 04订阅服务端事件
- 05访问 MCP 状态与配置
适用场景
- 01构建项目专用的 OpenCode 工具
- 02为 OpenCode 插件添加钩子
- 03自动执行会话和文件操作
- 04监控 OpenCode 事件流
MCP 相关
指南介绍 SDK 的 `client.mcp` 方法,用于检查 MCP 状态和添加 MCP 服务,也讲解了 OpenCode 自定义工具与插件的开发。
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ hhopkins95/ ai-systems --skill opencode-sdk-development安装后在 Claude Code 中输入/opencode-sdk-development确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
examples/full-plugin.tsbasic-tool.tsreferences/sdk-api.mdplugin-api.md详细介绍
OpenCode SDK 开发
使用 OpenCode SDK 创建自定义工具和插件的指南。
概览
OpenCode 提供两个主要软件包用于 SDK 开发:
| 软件包 | 用途 |
|---|---|
@opencode-ai/sdk | 用于与 OpenCode 服务交互的客户端 SDK(会话、消息、文件) |
@opencode-ai/plugin | 用于通过架构验证创建自定义工具的插件系统 |
快速入门:自定义工具
自定义工具可以扩展 OpenCode 的功能。工具是会从以下位置自动发现的 TypeScript/JavaScript 文件:
- 本地:项目目录中的
.opencode/tool/ - 全局:
~/.config/opencode/tool/
文件名会成为工具名称。
基本工具结构
import { tool } from "@opencode-ai/plugin"
export default tool({
description: "Brief description of what the tool does",
args: {
paramName: tool.schema.string().describe("Parameter description")
},
async execute(args, context) {
// context provides: sessionID, messageID, agent, abort
return "Result string returned to the AI"
}
})
架构定义
使用 tool.schema(基于 Zod)验证参数:
args: {
// String with description
query: tool.schema.string().describe("Search query"),
// Optional string
path: tool.schema.string().optional().describe("File path"),
// Number with constraints
limit: tool.schema.number().min(1).max(100).default(10).describe("Max results"),
// Enum/literal union
format: tool.schema.enum(["json", "text"]).describe("Output format"),
// Boolean
recursive: tool.schema.boolean().default(false).describe("Search recursively")
}
工具上下文
execute 函数会接收一个上下文对象:
type ToolContext = {
sessionID: string // Current session ID
messageID: string // Current message ID
agent: string // Current agent identifier
abort: AbortSignal // Signal for cancellation
}
示例:文件搜索工具
import { tool } from "@opencode-ai/plugin"
import { $ } from "bun"
export default tool({
description: "Search for files matching a pattern",
args: {
pattern: tool.schema.string().describe("Glob pattern to match"),
directory: tool.schema.string().default(".").describe("Directory to search")
},
async execute({ pattern, directory }) {
const result = await $`find ${directory} -name "${pattern}"`.text()
return result || "No files found"
}
})
插件开发
插件通过事件、身份验证和工具修改相关钩子,提供更全面的集成能力。
插件结构
import type { Plugin } from "@opencode-ai/plugin"
const plugin: Plugin = async (input) => {
const { client, project, directory, worktree, $ } = input
return {
// Custom tools
tool: {
myTool: tool({ /* definition */ })
},
// Event hooks
event: async ({ event }) => { /* handle events */ },
// Configuration hooks
config: async (config) => { /* modify config */ },
// Message hooks
"chat.message": async (input, output) => { /* modify messages */ },
// Tool execution hooks
"tool.execute.before": async (input, output) => { /* pre-processing */ },
"tool.execute.after": async (input, output) => { /* post-processing */ }
}
}
export default plugin
可用钩子
| 钩子 | 用途 |
|---|---|
event | 处理来自服务的实时事件 |
config | 加载时修改配置 |
tool | 注册自定义工具 |
auth | 自定义身份验证提供方 |
chat.message | 发送前修改消息 |
chat.params | 修改 LLM 参数(temperature、topP) |
permission.ask | 处理权限请求 |
tool.execute.before | 预处理工具参数 |
tool.execute.after | 后处理工具输出 |
SDK 客户端用法
SDK 客户端提供对 OpenCode 功能的编程访问。
初始化
import { createOpencode, createOpencodeClient } from "@opencode-ai/sdk"
// Create both client and server
const { client, server } = await createOpencode({
hostname: "127.0.0.1",
port: 4096,
timeout: 5000
})
// Or just the client
const client = createOpencodeClient({
baseUrl: "http://127.0.0.1:4096"
})
客户端 API 类别
| 类别 | 方法 |
|---|---|
client.session | list、create、get、delete、prompt、messages、fork、share |
client.project | list、current |
client.file | list、read、status |
client.find | text、files、symbols |
client.tool | ids、list |
client.event | subscribe(SSE 流式传输) |
client.mcp | status、add |
client.tui | appendPrompt、submitPrompt、showToast |
会话管理
// List sessions
const { data: sessions } = await client.session.list()
// Create session
const { data: session } = await client.session.create()
// Send prompt
const { data: response } = await client.session.prompt({
path: { id: sessionId },
body: {
parts: [{ type: "text", text: "Your message here" }]
}
})
// Get messages
const { data: messages } = await client.session.messages({
path: { id: sessionId }
})
事件流式传输
const result = await client.event.subscribe()
for await (const event of result.events) {
console.log("Event:", event.type, event.data)
}
安装
# Install SDK
npm install @opencode-ai/sdk
# Install plugin package (for tools)
npm install @opencode-ai/plugin
需要 TypeScript >= 4.9。
工具文件位置
| 位置 | 范围 |
|---|---|
.opencode/tool/*.ts | 项目专用工具 |
~/.config/opencode/tool/*.ts | 适用于所有项目的全局工具 |
多个导出会创建多个工具:filename_exportname。
最佳实践
- 清晰的描述:为工具和参数编写简洁、以行动为导向的描述
- 架构验证:使用 Zod 架构在处理前验证所有输入
- 错误处理:以字符串形式返回有意义的错误消息
- 中止信号:对于长时间运行的操作,检查
context.abort - 类型安全:使用 TypeScript 从架构中完整推断类型
- 最少依赖:保持工具轻量且专注
常见模式
跨语言工具
import { tool } from "@opencode-ai/plugin"
import { $ } from "bun"
export default tool({
description: "Run Python analysis script",
args: {
file: tool.schema.string().describe("File to analyze")
},
async execute({ file }) {
return await $`python3 analyze.py ${file}`.text()
}
})
带上下文的工具
import { tool } from "@opencode-ai/plugin"
export default tool({
description: "Get current session info",
args: {},
async execute(args, context) {
return JSON.stringify({
session: context.sessionID,
message: context.messageID,
agent: context.agent
}, null, 2)
}
})
故障排除
工具未显示:
- 确认文件位于
.opencode/tool/或~/.config/opencode/tool/ - 检查文件是否导出了有效的工具定义
- 重启 OpenCode 以重新加载工具
架构错误:
- 确保提供了所有必需参数
- 检查类型约束(字符串与数字)
- 确认可选字段使用
.optional()
执行错误:
- 检查
execute是否返回字符串 - 确认异步操作已完成
- 处理错误并以字符串形式返回错误消息
更多资源
参考文件
详细 API 文档:
references/sdk-api.md- 完整的 SDK 客户端 API 参考references/plugin-api.md- 完整的插件钩子和类型
示例文件
examples/ 中的可运行示例:
examples/basic-tool.ts- 简单的工具实现examples/full-plugin.ts- 带钩子的完整插件
External Documentation
评论
支持 Markdown