概要
OpenClaw の拡張システムにより、開発者は AI エージェントにカスタム機能を追加できます。拡張機能は新しいツールの登録、システムプロンプトスニペットの注入、特定イベントの処理、さらにはツールパイプラインの動作変更が可能です。本記事では、OpenClaw 拡張機能のゼロからの開発、テスト、デプロイまでをガイドします。
拡張機能の読み込み方法
OpenClaw は2つの拡張機能読み込み方法をサポートしています:
プログラム的な読み込み
コードを通じて直接拡張機能を登録します。OpenClaw との深い統合シナリオに適しています:
const { OpenClaw } = require('openclaw');
const app = new OpenClaw();
app.registerExtension({
name: 'my-extension',
version: '1.0.0',
description: 'My custom extension',
setup: async (context) => {
// 拡張機能の初期化ロジック
}
});
ディスクパスからの読み込み
拡張機能を指定ディレクトリに配置すると、OpenClaw が起動時に自動的に検出して読み込みます:
extensions:
path: /data/openclaw/extensions
autoLoad: true
allowedExtensions:
- my-extension
- another-extension
拡張機能のディレクトリ構造:
/data/openclaw/extensions/
my-extension/
index.js
package.json
manifest.yaml
拡張機能の構造
manifest.yaml
すべての拡張機能にはマニフェストファイルが必要で、拡張機能のメタデータと機能を宣言します:
name: my-extension
version: 1.0.0
description: This is a sample extension
author: Developer Name
minOpenClawVersion: 2.0.0
capabilities:
tools: true
prompts: true
events: true
permissions:
network: false
filesystem:
read: ["/data/openclaw/workspace"]
write: ["/tmp/openclaw/my-extension"]
config:
apiEndpoint:
type: string
required: true
description: API endpoint address
maxRetries:
type: number
default: 3
description: Maximum number of retries
エントリファイル
拡張機能のエントリファイルは拡張コンテキストオブジェクトを受け取る setup 関数をエクスポートします:
module.exports = {
setup: async (ctx) => {
// ツールの登録
ctx.registerTool({
name: 'my_custom_tool',
description: 'Description of the custom tool functionality',
parameters: {
type: 'object',
properties: {
query: { type: 'string', description: 'Query content' }
},
required: ['query']
},
execute: async (params, toolCtx) => {
const result = await doSomething(params.query);
return { content: result };
}
});
// プロンプトの注入
ctx.registerPrompt({
position: 'tools',
content: 'When the user needs a certain feature, please use the my_custom_tool tool.'
});
// イベントのリッスン
ctx.on('session:start', async (session) => {
console.log(`New session started: ${session.id}`);
});
}
};
ツール登録の詳細
ツール定義
ツールを登録する際は、JSON Schema 仕様に準拠したパラメータ定義を提供する必要があります。これらの定義は7段階ツールパイプラインの Schema 検証ステージでチェックされ、準拠しない定義は拒否されます。
Execute 関数
ツールの execute 関数は2つのパラメータを受け取ります:
- params:ユーザーから渡されたツールパラメータ。Schema に対して検証済み
- toolCtx:以下を含むツールコンテキスト:
session:現在のセッションオブジェクトchannel:現在のチャンネル情報user:現在のユーザー情報abortSignal:中断シグナル(パイプライン第7段階から)config:拡張機能の設定
戻り値の形式
ツールの execute 関数はオブジェクトを返す必要があります。一般的な形式:
// テキスト結果
return { content: 'Operation completed successfully' };
// 構造化データ
return { content: JSON.stringify(data), metadata: { type: 'json' } };
// エラー結果
return { error: 'Operation failed: specific reason' };
// 添付ファイル付きの結果
return {
content: 'Image generated',
attachments: [{ path: '/tmp/output.png', type: 'image/png' }]
};
プロンプト注入
拡張機能はシステムプロンプト内の異なる位置にコンテンツを注入できます:
ctx.registerPrompt({
position: 'system', // システムレベルプロンプト
content: 'You have the ability to...',
priority: 10 // 優先度。数値が大きいほど先に表示
});
ctx.registerPrompt({
position: 'tools', // ツール使用ガイダンス
content: 'When using xxx tool, please note...'
});
これらのプロンプトスニペットは buildAgentSystemPrompt() によって収集され、最終的なシステムプロンプトに統合されます。
イベントシステム
OpenClaw のイベントシステムにより、拡張機能はさまざまなシステムイベントに応答できます:
session:start— 新しいセッション開始session:end— セッション終了message:receive— 新しいメッセージ受信message:send— メッセージ送信tool:before— ツール実行前tool:after— ツール実行後tool:error— ツール実行エラー
ctx.on('tool:before', async (event) => {
console.log(`About to execute tool: ${event.toolName}`);
// パラメータの変更や実行のキャンセルが可能
});
拡張機能間通信
複数の拡張機能は共有コンテキストを通じて通信できます:
// 拡張機能 A がデータを公開
ctx.shared.set('weather:current', weatherData);
// 拡張機能 B がデータを読み取り
const weather = ctx.shared.get('weather:current');
テスト
ユニットテスト
OpenClaw は隔離された環境で拡張機能をテストするためのテストツールキットを提供しています:
const { createTestContext } = require('openclaw/testing');
describe('my-extension', () => {
it('should execute tool correctly', async () => {
const ctx = createTestContext();
await extension.setup(ctx);
const result = await ctx.executeTool('my_custom_tool', {
query: 'test'
});
expect(result.content).toBeDefined();
});
});
統合テスト
OpenClaw の開発モードを使用してサービスを起動し、拡張機能を読み込み、実際の会話を通じて機能をテストします。
セッション永続化
拡張機能が生成したデータは OpenClaw のセッション永続化メカニズム(JSONL 形式)を使用して保存できます。セッションデータがコンパクションを受ける際、拡張機能は session:compact イベントを通じてコンパクションプロセスに参加し、どのデータを保持するかを決定できます。
公開と共有
完成した拡張機能はパッケージ化して OpenClaw Skill Marketplace に公開でき、他のユーザーがインストールして使用できます。公開前には基本的なセキュリティレビューと機能検証が必要です。
ベストプラクティス
- 最小権限:拡張機能が実際に必要な権限のみを宣言する
- グレースフルエラーハンドリング:すべての非同期操作にエラーハンドリングを含める
- 中断シグナルの尊重:長時間実行される操作は定期的に
abortSignalをチェックする - 徹底したドキュメント:ツールに明確な説明とパラメータの解説を書く
- バージョン互換性:マニフェストに最小 OpenClaw バージョン要件を宣言する
まとめ
OpenClaw の拡張システムは強力で柔軟なカスタマイズ機能を提供します。新しいツールの追加、動作の変更、外部サービスとの統合のいずれも、拡張機能によりモジュール式に実現できます。拡張機能開発をマスターすることが、OpenClaw をあらゆるシナリオに適応させる鍵です。