- ツールの実行を制御 する - ツール呼び出しの承認、拒否、または変更
- 変換結果 - 処理前にツールの出力を変更する
- コンテキストの追加 - セッション開始時に追加情報を挿入する
- エラーの処理 - カスタム エラー処理を実装する
- 監査とログ - コンプライアンスのすべての対話を追跡する
使用可能なフック
| フック | Trigger | ユースケース(事例) |
|---|---|---|
| ツール使用前のフック | ツールの実行前 | アクセス許可の制御、引数の検証 |
| ツール使用後フック | ツールの実行後 (成功のみ) | 結果変換、ログ記録 |
| ツール使用後フック | 結果が失敗したツールの実行後 | 再試行のガイダンスを挿入し、エラーをログに記録する |
| ユーザープロンプト送信のフック | ユーザーがメッセージを送信する場合 | プロンプトの変更、フィルター処理 |
| セッションライフサイクルフック | セッションの開始 | コンテキストの追加、セッションの構成 |
| セッションライフサイクルフック | セッションの終了 | クリーンアップ、分析 |
| エラー処理フック | エラーが発生する | カスタム エラー処理 |
簡単スタート
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
from copilot import CopilotClient
from copilot.session import PermissionHandler
async def main():
client = CopilotClient()
await client.start()
async def on_pre_tool_use(input_data, invocation):
print(f"Tool called: {input_data['toolName']}")
return {"permissionDecision": "allow"}
async def on_post_tool_use(input_data, invocation):
print(f"Tool result: {input_data['toolResult']}")
return None
async def on_session_start(input_data, invocation):
return {"additionalContext": "User prefers concise answers."}
session = await client.create_session(on_permission_request=PermissionHandler.approve_all, hooks={
"on_pre_tool_use": on_pre_tool_use,
"on_post_tool_use": on_post_tool_use,
"on_session_start": on_session_start,
})
Go
package main
import (
"context"
"fmt"
copilot "github.com/github/copilot-sdk/go"
)
func main() {
client := copilot.NewClient(nil)
session, _ := client.CreateSession(context.Background(), &copilot.SessionConfig{
Hooks: &copilot.SessionHooks{
OnPreToolUse: func(input copilot.PreToolUseHookInput, inv copilot.HookInvocation) (*copilot.PreToolUseHookOutput, error) {
fmt.Printf("Tool called: %s\n", input.ToolName)
return &copilot.PreToolUseHookOutput{
PermissionDecision: "allow",
}, nil
},
OnPostToolUse: func(input copilot.PostToolUseHookInput, inv copilot.HookInvocation) (*copilot.PostToolUseHookOutput, error) {
fmt.Printf("Tool result: %v\n", input.ToolResult)
return nil, nil
},
OnSessionStart: func(input copilot.SessionStartHookInput, inv copilot.HookInvocation) (*copilot.SessionStartHookOutput, error) {
return &copilot.SessionStartHookOutput{
AdditionalContext: "User prefers concise answers.",
}, nil
},
},
})
_ = session
}
.NET
using GitHub.Copilot;
var client = new CopilotClient();
var session = await client.CreateSessionAsync(new SessionConfig
{
Hooks = new SessionHooks
{
OnPreToolUse = (input, invocation) =>
{
Console.WriteLine($"Tool called: {input.ToolName}");
return Task.FromResult<PreToolUseHookOutput?>(
new PreToolUseHookOutput { PermissionDecision = "allow" }
);
},
OnPostToolUse = (input, invocation) =>
{
Console.WriteLine($"Tool result: {input.ToolResult}");
return Task.FromResult<PostToolUseHookOutput?>(null);
},
OnSessionStart = (input, invocation) =>
{
return Task.FromResult<SessionStartHookOutput?>(
new SessionStartHookOutput { AdditionalContext = "User prefers concise answers." }
);
},
},
});
Java
import com.github.copilot.sdk.*;
import com.github.copilot.sdk.json.*;
import java.util.concurrent.CompletableFuture;
try (var client = new CopilotClient()) {
client.start().get();
var hooks = new SessionHooks()
.setOnPreToolUse((input, invocation) -> {
System.out.println("Tool called: " + input.getToolName());
return CompletableFuture.completedFuture(PreToolUseHookOutput.allow());
})
.setOnPostToolUse((input, invocation) -> {
System.out.println("Tool result: " + input.getToolResult());
return CompletableFuture.completedFuture(null);
})
.setOnSessionStart((input, invocation) -> {
return CompletableFuture.completedFuture(
new SessionStartHookOutput("User prefers concise answers.", null)
);
});
var session = client.createSession(
new SessionConfig()
.setHooks(hooks)
.setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
).get();
}
フック呼び出しコンテキスト
すべてのフックは、現在のセッションに関するコンテキストを持つ invocation パラメーターを受け取ります。
| フィールド | タイプ | Description |
|---|---|---|
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)}`,
};
},
},
});
フックガイド
- ツール使用前のフック - コントロール ツールの実行アクセス許可
- ツール使用後フック - 変換ツールの結果
- ユーザープロンプト送信のフック - ユーザー プロンプトを変更する
- セッションライフサイクルフック - セッションの開始と終了
- エラー処理フック - カスタム エラー処理