メモ
Copilot SDK は現在 テクニカル プレビューです。 機能と可用性は変更される場合があります。
フックを使用すると、会話ライフサイクルの重要なポイントで Copilot SDK セッションの動作をインターセプトしてカスタマイズできます。 フックを使用して以下を行います。
-
**ツールの実行を制御**する - ツール呼び出しの承認、拒否、または変更 -
**変換結果** - 処理前にツールの出力を変更する -
**コンテキストの追加** - セッションの開始時に追加情報を挿入する -
**エラーの処理** - カスタム エラー処理を実装する -
**監査とログ** - コンプライアンスのすべての対話を追跡する
使用可能なフック
| フック | Trigger | 利用シーン |
|---|---|---|
onPreToolUse | ツールの実行前 | アクセス許可の制御、引数の検証 |
onPostToolUse | ツールの実行後 | 結果変換、ログ記録 |
onUserPromptSubmitted | ユーザーがメッセージを送信する場合 | プロンプトの変更、フィルター処理 |
onSessionStart | セッションの開始 | コンテキストの追加、セッションの構成 |
onSessionEnd | セッションの終了 | クリーンアップ、分析 |
onErrorOccurred | エラーが発生する | カスタム エラー処理 |
簡単スタート
次の例では、Node.js/TypeScript でセッションを作成するときにフックを登録する方法を示します。
import { CopilotClient } from "@github/copilot-sdk";
const client = new CopilotClient();
const session = await client.createSession({
hooks: {
onPreToolUse: async (input) => {
console.log(`Tool called: ${input.toolName}`);
// Allow all tools
return { permissionDecision: "allow" };
},
onPostToolUse: async (input) => {
console.log(
`Tool result: ${JSON.stringify(input.toolResult)}`
);
return null; // No modifications
},
onSessionStart: async (input) => {
return {
additionalContext:
"User prefers concise answers.",
};
},
},
});
Python、Go、.NET の例については、 github/copilot-sdk リポジトリを参照してください。
フック呼び出しコンテキスト
すべてのフックは、現在のセッションに関するコンテキストを持つ invocation パラメーターを受け取ります。
| フィールド | タイプ | 説明 |
|---|---|---|
sessionId | 文字列 | 現在のセッションの ID |
これにより、フックで状態を維持したり、セッション固有のロジックを実行したりできます。
一般的なパターン
すべてのツール呼び出しのログ記録
const session = await client.createSession({
hooks: {
onPreToolUse: async (input) => {
console.log(
`[${new Date().toISOString()}] Tool: `
+ `${input.toolName}, `
+ `Args: ${JSON.stringify(input.toolArgs)}`
);
return { permissionDecision: "allow" };
},
onPostToolUse: async (input) => {
console.log(
`[${new Date().toISOString()}] `
+ `Result: ${JSON.stringify(input.toolResult)}`
);
return null;
},
},
});
危険なツールのブロック
const BLOCKED_TOOLS = ["shell", "bash", "exec"];
const session = await client.createSession({
hooks: {
onPreToolUse: async (input) => {
if (BLOCKED_TOOLS.includes(input.toolName)) {
return {
permissionDecision: "deny",
permissionDecisionReason:
"Shell access is not permitted",
};
}
return { permissionDecision: "allow" };
},
},
});
ユーザー コンテキストの追加
const session = await client.createSession({
hooks: {
onSessionStart: async () => {
const userPrefs = await loadUserPreferences();
return {
additionalContext:
`User preferences: `
+ `${JSON.stringify(userPrefs)}`,
};
},
},
});
次のステップ
-
[AUTOTITLE](/copilot/how-tos/copilot-sdk/use-hooks/pre-tool-use) -
[AUTOTITLE](/copilot/how-tos/copilot-sdk/use-hooks/post-tool-use) -
[AUTOTITLE](/copilot/how-tos/copilot-sdk/use-hooks/user-prompt-submitted) -
[AUTOTITLE](/copilot/how-tos/copilot-sdk/use-hooks/session-lifecycle) -
[AUTOTITLE](/copilot/how-tos/copilot-sdk/use-hooks/error-handling)