OpenCode SDK Development について
OpenCode SDK を使ったカスタムツールとプラグインの開発ガイドです。セッション、ファイル、イベント、MCP 設定にプログラムからアクセスするクライアント SDK も扱います。
主な機能
- 01スキーマ検証付きカスタムツールの作成
- 02プラグインフックの登録
- 03セッションとファイル API の利用
- 04サーバーイベントの購読
- 05MCP の状態と設定へのアクセス
活用シーン
- 01プロジェクト固有の OpenCode ツールの作成
- 02OpenCode プラグインへのフック追加
- 03セッションとファイル操作の自動化
- 04OpenCode イベントストリームの監視
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 の開発向けに 2 つの主要なパッケージを提供しています。
| パッケージ | 用途 |
|---|---|
@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 を再起動してください
スキーマエラーの場合:
- 必須の引数がすべて指定されていることを確認してください
- 型の制約(string と number など)を確認してください
- オプションのフィールドで
.optional()が使われていることを確認してください
実行エラーの場合:
executeが文字列を返すことを確認してください- 非同期処理が完了することを確認してください
- エラーを処理し、エラーメッセージを文字列で返してください
参考資料
リファレンスファイル
API の詳細なドキュメントについては、次を参照してください。
references/sdk-api.md- SDK クライアント API の完全なリファレンスreferences/plugin-api.md- プラグインのフックと型の完全なリファレンス
サンプルファイル
examples/ に動作するサンプルがあります。
examples/basic-tool.ts- シンプルなツールの実装examples/full-plugin.ts- フックを備えた完全なプラグイン