mcpField
O
OpenCode SDK Development

OpenCode SDK Development

github.com/hhopkins95开发036 次安装44 周前更新
代码仓库

关于 OpenCode SDK Development

介绍如何使用 OpenCode SDK 开发自定义工具和插件,也涵盖用于编程访问会话、文件、事件及 MCP 配置的客户端 SDK。

主要功能

  1. 01创建带模式验证的自定义工具
  2. 02注册插件钩子
  3. 03使用会话与文件 API
  4. 04订阅服务端事件
  5. 05访问 MCP 状态与配置

适用场景

  1. 01构建项目专用的 OpenCode 工具
  2. 02为 OpenCode 插件添加钩子
  3. 03自动执行会话和文件操作
  4. 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.ts
basic-tool.ts
references/
sdk-api.md
plugin-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.sessionlist、create、get、delete、prompt、messages、fork、share
client.projectlist、current
client.filelist、read、status
client.findtext、files、symbols
client.toolids、list
client.eventsubscribe(SSE 流式传输)
client.mcpstatus、add
client.tuiappendPrompt、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。

最佳实践

  1. 清晰的描述:为工具和参数编写简洁、以行动为导向的描述
  2. 架构验证:使用 Zod 架构在处理前验证所有输入
  3. 错误处理:以字符串形式返回有意义的错误消息
  4. 中止信号:对于长时间运行的操作,检查 context.abort
  5. 类型安全:使用 TypeScript 从架构中完整推断类型
  6. 最少依赖:保持工具轻量且专注

常见模式

跨语言工具
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