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. 05MCP の状態と設定へのアクセス

活用シーン

  1. 01プロジェクト固有の OpenCode ツールの作成
  2. 02OpenCode プラグインへのフック追加
  3. 03セッションとファイル操作の自動化
  4. 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.ts
basic-tool.ts
references/
sdk-api.md
plugin-api.md

詳細

OpenCode SDK の開発

OpenCode SDK を使用してカスタムツールやプラグインを作成するためのガイドです。

概要

OpenCode では、SDK の開発向けに 2 つの主要なパッケージを提供しています。

パッケージ用途
@opencode-ai/sdkOpenCode サーバー(セッション、メッセージ、ファイル)と連携するクライアント 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.paramsLLM パラメーター(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 を再起動してください

スキーマエラーの場合:

  • 必須の引数がすべて指定されていることを確認してください
  • 型の制約(string と number など)を確認してください
  • オプションのフィールドで .optional() が使われていることを確認してください

実行エラーの場合:

  • execute が文字列を返すことを確認してください
  • 非同期処理が完了することを確認してください
  • エラーを処理し、エラーメッセージを文字列で返してください

参考資料

リファレンスファイル

API の詳細なドキュメントについては、次を参照してください。

  • references/sdk-api.md - SDK クライアント API の完全なリファレンス
  • references/plugin-api.md - プラグインのフックと型の完全なリファレンス
サンプルファイル

examples/ に動作するサンプルがあります。

  • examples/basic-tool.ts - シンプルなツールの実装
  • examples/full-plugin.ts - フックを備えた完全なプラグイン
External Documentation

コメント