copilot-sdk について
GitHub Copilot SDKは、4つの言語でGitHub Copilotとプログラムから連携するアプリを開発するためのSDKです。Copilot CLIをラップし、セッション、ストリーミング、カスタムツール、フック、MCPサーバー連携を提供します。
主な機能
- 01Node.js、Python、Go、.NETに対応
- 02セッションとメッセージの管理
- 03ストリーミング応答とイベント
- 04カスタムツールとライフサイクルフック
- 05MCPサーバーの設定
活用シーン
- 01Copilotセッションを利用するアプリの開発
- 02画面へのCopilot応答のストリーミング表示
- 03Copilotへのアプリ固有ツールの追加
- 04ローカルまたはリモートMCPサーバーへの接続
MCP 対応
SDKでは、Copilotセッション用にローカルstdioとリモートHTTPのMCPサーバーを設定できます。ヘッダー、環境変数、タイムアウト、ツールの絞り込みも指定できます。
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ microsoft/ skills --skill copilot-sdkインストール後、Claude Code で/copilot-sdkを入力して読み込まれたか確認します。
詳細
GitHub Copilot SDK
GitHub Copilot とプログラムからやり取りするアプリケーションを構築できます。この SDK は JSON-RPC を介して Copilot CLI をラップし、Node.js、Python、Go、.NET におけるセッション管理、カスタムツール、フック、MCP サーバー統合、ストリーミングを提供します。
前提条件
- GitHub Copilot CLI がインストールされ、認証済みであること(
copilot --version) - GitHub Copilot サブスクリプション(Individual、Business、または Enterprise)— BYOK の場合は不要です
- ランタイム: Node.js 18+ / Python 3.8+ / Go 1.21+ / .NET 8.0+
インストール
| 言語 | パッケージ | インストール |
|---|---|---|
| Node.js | @github/copilot-sdk | npm install @github/copilot-sdk |
| Python | github-copilot-sdk | pip install github-copilot-sdk |
| Go | github.com/github/copilot-sdk/go | go get github.com/github/copilot-sdk/go |
| .NET | GitHub.Copilot.SDK | dotnet add package GitHub.Copilot.SDK |
アーキテクチャ
SDK は、stdio(デフォルト)または TCP を介した JSON-RPC で Copilot CLI と通信します。CLI はモデル呼び出し、ツール実行、セッション状態、MCP サーバーのライフサイクルを管理します。
Your App → SDK Client → [stdio/TCP] → Copilot CLI → Model Provider
↕
MCP Servers
トランスポートモード:
| モード | 説明 | 用途 |
|---|---|---|
| Stdio(デフォルト) | パイプ経由で CLI をサブプロセスとして実行 | ローカル開発、単一プロセス |
| TCP | CLI をネットワークサーバーとして実行 | 複数クライアント、バックエンドサービス |
基本パターン:クライアント → セッション → メッセージ
SDK の使い方はすべて、クライアントの作成、セッションの作成、メッセージの送信という流れに従います。
Node.js / TypeScript
import { CopilotClient } from "@github/copilot-sdk";
const client = new CopilotClient();
const session = await client.createSession({ model: "gpt-4.1" });
const response = await session.sendAndWait({ prompt: "What is 2 + 2?" });
console.log(response?.data.content);
await client.stop();
Python
import asyncio
from copilot import CopilotClient
async def main():
client = CopilotClient()
await client.start()
session = await client.create_session({"model": "gpt-4.1"})
response = await session.send_and_wait({"prompt": "What is 2 + 2?"})
print(response.data.content)
await client.stop()
asyncio.run(main())
Go
client := copilot.NewClient(nil)
if err := client.Start(ctx); err != nil { log.Fatal(err) }
defer client.Stop()
session, _ := client.CreateSession(ctx, &copilot.SessionConfig{Model: "gpt-4.1"})
response, _ := session.SendAndWait(ctx, copilot.MessageOptions{Prompt: "What is 2 + 2?"})
fmt.Println(*response.Data.Content)
.NET
await using var client = new CopilotClient();
await using var session = await client.CreateSessionAsync(new SessionConfig { Model = "gpt-4.1" });
var response = await session.SendAndWaitAsync(new MessageOptions { Prompt = "What is 2 + 2?" });
Console.WriteLine(response?.Data.Content);
ストリーミング応答
streaming: true を設定し、デルタイベントを購読すると、リアルタイムで出力を受け取れます。
Node.js
const session = await client.createSession({ model: "gpt-4.1", streaming: true });
session.on("assistant.message_delta", (event) => {
process.stdout.write(event.data.deltaContent);
});
session.on("session.idle", () => console.log());
await session.sendAndWait({ prompt: "Tell me a joke" });
Python
from copilot.generated.session_events import SessionEventType
session = await client.create_session({"model": "gpt-4.1", "streaming": True})
def handle_event(event):
if event.type == SessionEventType.ASSISTANT_MESSAGE_DELTA:
sys.stdout.write(event.data.delta_content)
sys.stdout.flush()
if event.type == SessionEventType.SESSION_IDLE:
print()
session.on(handle_event)
await session.send_and_wait({"prompt": "Tell me a joke"})
イベントの購読
| メソッド | 説明 |
|---|---|
on(handler) | すべてのイベントを購読します。購読解除関数を返します |
on(eventType, handler) | 指定したイベントタイプを購読します(Node.js のみ) |
購読解除するには、返された関数を呼び出します。.NET では、返された破棄可能オブジェクトに対して .Dispose() を呼び出します。
カスタムツール
Copilot が呼び出して機能を拡張できるツールを定義します。
Node.js
import { CopilotClient, defineTool } from "@github/copilot-sdk";
const getWeather = defineTool("get_weather", {
description: "Get the current weather for a city",
parameters: {
type: "object",
properties: { city: { type: "string", description: "The city name" } },
required: ["city"],
},
handler: async ({ city }) => ({ city, temperature: "72°F", condition: "sunny" }),
});
const session = await client.createSession({
model: "gpt-4.1",
tools: [getWeather],
});
Python
from copilot.tools import define_tool
from pydantic import BaseModel, Field
class GetWeatherParams(BaseModel):
city: str = Field(description="The city name")
@define_tool(description="Get the current weather for a city")
async def get_weather(params: GetWeatherParams) -> dict:
return {"city": params.city, "temperature": "72°F", "condition": "sunny"}
session = await client.create_session({"model": "gpt-4.1", "tools": [get_weather]})
Go
type WeatherParams struct {
City string `json:"city" jsonschema:"The city name"`
}
getWeather := copilot.DefineTool("get_weather", "Get weather for a city",
func(params WeatherParams, inv copilot.ToolInvocation) (WeatherResult, error) {
return WeatherResult{City: params.City, Temperature: "72°F"}, nil
},
)
session, _ := client.CreateSession(ctx, &copilot.SessionConfig{
Model: "gpt-4.1",
Tools: []copilot.Tool{getWeather},
})
.NET
using Microsoft.Extensions.AI;
using System.ComponentModel;
var getWeather = AIFunctionFactory.Create(
([Description("The city name")] string city) => new { city, temperature = "72°F" },
"get_weather", "Get the current weather for a city");
await using var session = await client.CreateSessionAsync(new SessionConfig {
Model = "gpt-4.1", Tools = [getWeather],
});
ツールの要件
- ハンドラーは JSON にシリアライズ可能なデータを返す必要があります(
undefinedは不可) - パラメーターは JSON Schema 形式に準拠する必要があります
- ツールの説明には、使用すべき状況を明確に記載してください
フック
ライフサイクルの重要な時点でセッションの動作を傍受し、カスタマイズします。
| フック | トリガー | 用途 |
|---|---|---|
onPreToolUse | ツール実行前 | 権限制御、引数の変更 |
onPostToolUse | ツール実行後 | 結果の変換、ログ記録、秘匿化 |
onUserPromptSubmitted | ユーザーがメッセージを送信 | プロンプトの変更、フィルタリング、コンテキストの注入 |
onSessionStart | セッション開始時(新規または再開) | コンテキストの追加、セッションの設定 |
onSessionEnd | セッション終了時 | クリーンアップ、分析、メトリクス |
onErrorOccurred | エラー発生時 | カスタムエラー処理、再試行ロジック、監視 |
ツール実行前フック
ツールの実行前に、ツールの権限を制御したり、引数を変更したり、コンテキストを注入したりできます。
const session = await client.createSession({
hooks: {
onPreToolUse: async (input) => {
if (["shell", "bash"].includes(input.toolName)) {
return { permissionDecision: "deny", permissionDecisionReason: "Shell access not permitted" };
}
return { permissionDecision: "allow" };
},
},
});
入力フィールド: timestamp、cwd、toolName、toolArgs
出力フィールド:
| フィールド | 型 | 説明 |
|---|---|---|
permissionDecision | "allow" | "deny" | "ask" | ツール呼び出しを許可するかどうか |
permissionDecisionReason | string | 拒否または確認を求める理由 |
modifiedArgs | object | ツールに渡す変更後の引数 |
additionalContext | string | 会話に追加するコンテキスト |
suppressOutput | boolean | 会話にツールの出力を表示しない |
ツール実行後フック
実行後に結果を変換したり、機密データを秘匿化したり、ツールの動作をログに記録したりできます。
hooks: {
onPostToolUse: async (input) => {
// Redact sensitive data from results
if (typeof input.toolResult === "string") {
let redacted = input.toolResult;
for (const pattern of SENSITIVE_PATTERNS) {
redacted = redacted.replace(pattern, "[REDACTED]");
}
if (redacted !== input.toolResult) {
return { modifiedResult: redacted };
}
}
return null; // Pass through unchanged
},
}
出力フィールド: modifiedResult、additionalContext、suppressOutput
ユーザープロンプト送信時のフック
処理前にユーザープロンプトを変更または拡張します。プロンプトテンプレート、コンテキストの注入、入力の検証に役立ちます。
hooks: {
onUserPromptSubmitted: async (input) => {
return {
modifiedPrompt: `[User from engineering team] ${input.prompt}`,
additionalContext: "Follow company coding standards.",
};
},
}
出力フィールド: modifiedPrompt、additionalContext、suppressOutput
セッションのライフサイクルフック
hooks: {
onSessionStart: async (input, invocation) => {
// input.source: "startup" | "resume" | "new"
console.log(`Session ${invocation.sessionId} started (${input.source})`);
return { additionalContext: "Project uses TypeScript and React." };
},
onSessionEnd: async (input, invocation) => {
// input.reason: "complete" | "error" | "abort" | "timeout" | "user_exit"
await recordMetrics({ sessionId: invocation.sessionId, reason: input.reason });
return null;
},
}
エラー処理フック
hooks: {
onErrorOccurred: async (input) => {
// input.errorContext: "model_call" | "tool_execution" | "system" | "user_input"
// input.recoverable: boolean
if (input.errorContext === "model_call" && input.error.includes("rate")) {
return { errorHandling: "retry", retryCount: 3, userNotification: "Rate limited. Retrying..." };
}
return null; // Default error handling
},
}
出力フィールド: suppressOutput、errorHandling("retry" | "skip" | "abort")、retryCount、userNotification
Python フックの例
async def on_pre_tool_use(input_data, invocation):
if input_data["toolName"] in ["shell", "bash"]:
return {"permissionDecision": "deny", "permissionDecisionReason": "Not permitted"}
return {"permissionDecision": "allow"}
session = await client.create_session({
"hooks": {"on_pre_tool_use": on_pre_tool_use}
})
Go フックの例
session, _ := client.CreateSession(ctx, &copilot.SessionConfig{
Hooks: &copilot.SessionHooks{
OnPreToolUse: func(input copilot.PreToolUseHookInput, inv copilot.HookInvocation) (*copilot.PreToolUseHookOutput, error) {
return &copilot.PreToolUseHookOutput{PermissionDecision: "allow"}, nil
},
},
})
MCP サーバーの統合
MCP(Model Context Protocol)サーバーに接続して、事前構築済みのツール機能を利用できます。
ローカル Stdio サーバー
const session = await client.createSession({
mcpServers: {
filesystem: {
type: "local",
command: "npx",
args: ["-y", "@modelcontextprotocol/server-filesystem", "/allowed/path"],
tools: ["*"],
env: { DEBUG: "true" },
cwd: "./servers",
timeout: 30000,
},
},
});
リモート HTTP サーバー
const session = await client.createSession({
mcpServers: {
github: {
type: "http",
url: "https://api.githubcopilot.com/mcp/",
headers: { Authorization: "Bearer ${TOKEN}" },
tools: ["*"],
},
},
});
MCP 設定フィールド
ローカル/Stdio:
| フィールド | 型 | 必須 | 説明 |
|---|---|---|---|
type | "local" | いいえ | デフォルトは local です |
command | string | はい | 実行ファイルのパス |
args | string[] | はい | コマンド引数 |
env | object | いいえ | 環境変数 |
cwd | string | いいえ | 作業ディレクトリ |
tools | string[] | いいえ | すべての場合は ["*"]、なしの場合は [] |
timeout | number | いいえ | タイムアウト(ミリ秒) |
リモート HTTP:
| フィールド | 型 | 必須 | 説明 |
|---|---|---|---|
type | "http" | はい | サーバーの種類 |
url | string | はい | サーバーの URL |
headers | object | いいえ | HTTP ヘッダー |
tools | string[] | いいえ | ツールのフィルター |
timeout | number | いいえ | タイムアウト(ミリ秒) |
MCP のデバッグ
統合する前に、MCP サーバーを個別にテストします。
echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}' | /path/to/your/mcp-server
対話型のデバッグには、MCP Inspector を使用します。
npx @modelcontextprotocol/inspector /path/to/your/mcp-server
よくある MCP の問題:
- ツールが表示されない →
tools: ["*"]を設定し、サーバーがtools/listに応答することを確認します - サーバーが起動しない → コマンドには絶対パスを使用し、
cwdを確認します - stdout への出力混入 → デバッグ出力は stdout ではなく stderr に出力する必要があります
認証
認証方法(優先順位順)
- 明示的なトークン — コンストラクターの
githubToken - HMAC キー —
CAPI_HMAC_KEYまたはCOPILOT_HMAC_KEY環境変数 - 直接 API トークン —
COPILOT_API_URLとともに使用するGITHUB_COPILOT_API_TOKEN - 環境変数 —
COPILOT_GITHUB_TOKEN→GH_TOKEN→GITHUB_TOKEN - 保存済み OAuth —
copilot auth loginで取得したもの - GitHub CLI —
gh authの認証情報
プログラムによるトークン設定
const client = new CopilotClient({ githubToken: process.env.GITHUB_TOKEN });
OAuth GitHub App
ユーザーが GitHub でサインインするマルチユーザーアプリ向け:
const client = new CopilotClient({
githubToken: userAccessToken, // gho_ or ghu_ token from OAuth flow
useLoggedInUser: false, // Don't use stored CLI credentials
});
サポートされるトークンの種類: gho_(OAuth)、ghu_(GitHub App)、github_pat_(細粒度 PAT)。
サポート対象外: ghp_(従来型 PAT — 非推奨)。
自動ログインの無効化
SDK が保存済みの認証情報を使用しないようにします。
const client = new CopilotClient({ useLoggedInUser: false });
BYOK(独自のキーを使用)
独自の API キーを使用できます。Copilot のサブスクリプションは不要です。CLI はエージェントのランタイムとしてのみ機能します。
プロバイダーの設定
OpenAI:
provider: { type: "openai", baseUrl: "https://api.openai.com/v1", apiKey: process.env.OPENAI_API_KEY }
Azure AI Foundry(OpenAI 互換):
provider: {
type: "openai",
baseUrl: "https://your-resource.openai.azure.com/openai/v1/",
apiKey: process.env.FOUNDRY_API_KEY,
wireApi: "responses", // Use "responses" for GPT-5 series, "completions" for others
}
Azure OpenAI(ネイティブエンドポイント):
provider: {
type: "azure",
baseUrl: "https://my-resource.openai.azure.com", // Just the host — no /openai/v1
apiKey: process.env.AZURE_OPENAI_KEY,
azure: { apiVersion: "2024-10-21" },
}
Anthropic:
provider: { type: "anthropic", baseUrl: "https://api.anthropic.com", apiKey: process.env.ANTHROPIC_API_KEY }
Ollama(ローカル):
provider: { type: "openai", baseUrl: "http://localhost:11434/v1" }
プロバイダー設定のリファレンス
| フィールド | 型 | 説明 |
|---|---|---|
type | "openai" | "azure" | "anthropic" | プロバイダーの種類 |
baseUrl | string | 必須。 API エンドポイントの URL |
apiKey | string | API キー(ローカルプロバイダーでは省略可) |
bearerToken | string | Bearer トークン認証(apiKey より優先) |
wireApi | "completions" | "responses" | API 形式(デフォルト:"completions") |
azure.apiVersion | string | Azure API のバージョン(デフォルト:"2024-10-21") |
BYOK による Azure Managed Identity
DefaultAzureCredential を使用して、Azure デプロイメント用の短期間有効な Bearer トークンを取得します。
from azure.identity import DefaultAzureCredential
from copilot import CopilotClient, ProviderConfig, SessionConfig
credential = DefaultAzureCredential()
token = credential.get_token("https://cognitiveservices.azure.com/.default").token
session = await client.create_session(SessionConfig(
model="gpt-4.1",
provider=ProviderConfig(
type="openai",
base_url=f"{foundry_url}/openai/v1/",
bearer_token=token,
wire_api="responses",
),
))
注: Bearer トークンの有効期限は約 1 時間です。長時間実行するアプリでは、新しいセッションを開始する前にトークンを更新してください。SDK はトークンを自動更新しません。
BYOK の制限事項
- 静的な認証情報のみ — Entra ID、OIDC、マネージド ID のネイティブサポートはありません
- 自動更新なし — トークンの有効期限が切れた場合、新しいセッションを作成する必要があります
- キーは永続化されません — セッション再開時に
provider設定を再度指定する必要があります - モデルの利用可否 — プロバイダーが提供するモデルに限られます
セッションの永続化
独自のセッション ID を指定すると、再起動後にセッションを再開できます。
// Create with explicit ID
const session = await client.createSession({
sessionId: "user-123-task-456",
model: "gpt-4.1",
});
// Resume later (even from a different client instance)
const resumed = await client.resumeSession("user-123-task-456");
await resumed.sendAndWait({ prompt: "What did we discuss?" });
セッション管理
const sessions = await client.listSessions(); // List all
const lastId = await client.getLastSessionId(); // Get most recent
await client.deleteSession("user-123-task-456"); // Delete from storage
await session.destroy(); // Destroy active session
再開時のオプション
セッションの再開時には、model、systemMessage、availableTools、excludedTools、provider(BYOK では必須)、reasoningEffort、streaming、mcpServers、customAgents、skillDirectories、infiniteSessions を再設定できます。
セッション ID のベストプラクティス
| パターン | 例 | 用途 |
|---|---|---|
user-{userId}-{taskId} | user-alice-pr-review-42 | マルチユーザーアプリ |
tenant-{tenantId}-{workflow} | tenant-acme-onboarding | マルチテナント SaaS |
{userId}-{taskType}-{timestamp} | alice-deploy-1706932800 | 時間に基づくクリーンアップ |
永続化される内容
セッションの状態は ~/.copilot/session-state/{sessionId}/ に保存されます。
| データ | 永続化されるか | メモ |
|---|---|---|
| 会話履歴 | ✅ はい | メッセージスレッド全体 |
| ツール呼び出しの結果 | ✅ はい | コンテキスト用にキャッシュされます |
| エージェントの計画状態 | ✅ はい | plan.md ファイル |
| セッションの成果物 | ✅ はい | files/ ディレクトリ内 |
| プロバイダー/API キー | ❌ いいえ | 再開時に再度指定する必要があります |
| メモリー内のツール状態 | ❌ いいえ | ツールはステートレスになるよう設計してください |
無限セッション
コンテキストの制限を超える可能性のある長時間実行のワークフローでは、自動圧縮を有効にします。
const session = await client.createSession({
infiniteSessions: {
enabled: true,
backgroundCompactionThreshold: 0.80, // Start background compaction at 80%
bufferExhaustionThreshold: 0.95, // Block and compact at 95%
},
});
しきい値はコンテキスト使用率(0.0~1.0)であり、絶対的なトークン数ではありません。
カスタムエージェント
専門的な AI のペルソナを定義します。
const session = await client.createSession({
customAgents: [{
name: "pr-reviewer",
displayName: "PR Reviewer",
description: "Reviews pull requests for best practices",
prompt: "You are an expert code reviewer. Focus on security, performance, and maintainability.",
}],
});
システムメッセージ
AI の動作と性格を制御します。
const session = await client.createSession({
systemMessage: { content: "You are a helpful assistant. Always be concise." },
});
スキルの統合
スキルディレクトリを読み込み、Copilot の機能を拡張します。
const session = await client.createSession({
skillDirectories: ["./skills/code-review", "./skills/documentation"],
disabledSkills: ["experimental-feature"],
});
スキルはカスタムエージェントや MCP サーバーと組み合わせることができます。
const session = await client.createSession({
skillDirectories: ["./skills/security"],
customAgents: [{ name: "auditor", prompt: "Focus on OWASP Top 10." }],
mcpServers: { postgres: { type: "local", command: "npx", args: ["-y", "@modelcontextprotocol/server-postgres"], tools: ["*"] } },
});
権限と入力ハンドラー
ツールの権限やユーザー入力リクエストをプログラムで処理します。SDK は デフォルト拒否 の権限モデルを採用しており、ハンドラーを指定しない限り、すべての権限リクエストが拒否されます。
const session = await client.createSession({
onPermissionRequest: async (request) => {
if (request.kind === "shell") {
return { approved: request.command.startsWith("git") };
}
return { approved: true };
},
onUserInputRequest: async (request) => {
return { response: "yes" };
},
});
トークン使用量の追跡
CLI の /usage を使う代わりに、使用量イベントをサブスクライブします。
session.on("assistant.usage", (event) => {
console.log("Tokens:", { input: event.data.inputTokens, output: event.data.outputTokens });
});
デプロイパターン
ローカル CLI(デフォルト)
SDK が CLI をサブプロセスとして自動起動します。最も簡単なセットアップで、設定は不要です。
const client = new CopilotClient(); // Auto-manages CLI process
外部 CLI サーバー(バックエンドサービス)
CLI をヘッドレスモードで実行し、TCP 経由で SDK に接続します。
copilot --headless --port 4321
const client = new CopilotClient({ cliUrl: "localhost:4321" });
複数クライアントのサポート: 複数の SDK クライアントで 1 つの CLI サーバーを共有できます。
同梱 CLI(デスクトップアプリ)
CLI バイナリをアプリに同梱します。
const client = new CopilotClient({ cliPath: path.join(__dirname, "vendor", "copilot") });
Docker Compose
services:
copilot-cli:
image: ghcr.io/github/copilot-cli:latest
command: ["--headless", "--port", "4321"]
environment:
- COPILOT_GITHUB_TOKEN=${COPILOT_GITHUB_TOKEN}
volumes:
- session-data:/root/.copilot/session-state
api:
build: .
environment:
- CLI_URL=copilot-cli:4321
depends_on: [copilot-cli]
volumes:
session-data:
セッション分離パターン
| パターン | 分離 | リソース | 最適な用途 |
|---|---|---|---|
| ユーザーごとの CLI | 完全 | 高 | マルチテナント SaaS、コンプライアンス |
| 共有 CLI +セッション ID | 論理的 | 低 | 内部ツール |
| セッションの共有 | なし | 低 | チームでの共同作業(ロックが必要) |
本番環境チェックリスト
- セッションのクリーンアップ:期限切れのセッションを定期的に削除します
- ヘルスチェック:CLI サーバーに ping を送信し、応答がない場合は再起動します
- 永続ストレージ:コンテナー用に
~/.copilot/session-state/をマウントします - シークレット管理:トークンには Vault/K8s Secrets を使用します
- セッションロック:共有セッションへのアクセスには Redis などを使用します
- グレースフルシャットダウン:CLI を停止する前に、アクティブなセッションの処理を完了します
クライアントの設定
| オプション | 型 | デフォルト | 説明 |
|---|---|---|---|
cliPath | string | 自動検出 | Copilot CLI 実行可能ファイルのパス |
cliUrl | string | — | 外部 CLI サーバーの URL |
githubToken | string | — | 認証用の GitHub トークン |
useLoggedInUser | boolean | true | 保存済みの CLI 認証情報を使用します |
logLevel | string | "none" | "none" | "error" | "warning" | "info" | "debug" |
autoRestart | boolean | true | クラッシュ時に CLI を自動再起動します |
useStdio | boolean | true | stdio トランスポートを使用します |
セッションの設定
| オプション | 型 | 説明 |
|---|---|---|
model | string | 使用するモデル(例:"gpt-4.1"、"claude-sonnet-4") |
sessionId | string | 再開可能なセッション用のカスタム ID |
streaming | boolean | ストリーミング応答を有効にします |
tools | Tool[] | カスタムツール |
mcpServers | object | MCP サーバーの設定 |
hooks | object | セッションフック |
provider | object | BYOK プロバイダーの設定 |
customAgents | object[] | カスタムエージェントの定義 |
systemMessage | object | システムメッセージの上書き |
skillDirectories | string[] | スキルを読み込むディレクトリ |
disabledSkills | string[] | 無効にするスキル |
reasoningEffort | string | 推論の努力レベル |
availableTools | string[] | 使用可能なツールを制限します |
excludedTools | string[] | 特定のツールを除外します |
infiniteSessions | object | 自動圧縮の設定 |
workingDirectory | string | 作業ディレクトリ |
SDK と CLI の機能比較
✅ SDK で利用可能
セッション管理、メッセージ送信(send/sendAndWait/abort)、メッセージ履歴(getMessages)、カスタムツール、ツールの権限フック、MCP サーバー(ローカル+HTTP)、ストリーミング、モデル選択、BYOK プロバイダー、カスタムエージェント、システムメッセージ、スキル、無限セッション、権限ハンドラー、40 種類以上のイベント。
❌ CLI 専用の機能
セッションのエクスポート(--share)、スラッシュコマンド、対話型 UI、ターミナルへのレンダリング、YOLO モード、ログイン/ログアウトのフロー、/compact(代わりに infiniteSessions を使用)、/usage(代わりに usage イベントを使用)、/review、/delegate。
回避策:
- セッションのエクスポート →
session.on()とsession.getMessages()を使ってイベントを手動で収集します - 権限の制御 →
--allow-all-pathsの代わりにonPermissionRequestハンドラーを使用します - コンテキストの圧縮 →
/compactの代わりにinfiniteSessionsの設定を使用します
デバッグ
デバッグログを有効にします:
const client = new CopilotClient({ logLevel: "debug" });
カスタムログディレクトリ:
const client = new CopilotClient({ cliArgs: ["--log-dir", "/path/to/logs"] });
よくある問題
| 問題 | 原因 | 解決策 |
|---|---|---|
CLI not found | CLI がインストールされていないか、PATH にありません | CLI をインストールするか、cliPath を設定します |
Not authenticated | 有効な認証情報がありません | copilot auth login を実行するか、githubToken を指定します |
Session not found | destroy() の実行後にセッションを使用しています | listSessions() で有効な ID を確認します |
Connection refused | CLI プロセスがクラッシュしました | autoRestart: true を有効にし、ポートの競合を確認します |
| MCP ツールが見つからない | サーバーの初期化に失敗したか、ツールが有効になっていません | tools: ["*"] を設定し、サーバーを個別にテストします |
接続状態
console.log("State:", client.getState()); // "connected" after start()
client.on("stateChange", (state) => console.log("Changed to:", state));
主要 API の概要
| 言語 | クライアント | セッションの作成 | 送信 | 再開 | 停止 |
|---|---|---|---|---|---|
| Node.js | new CopilotClient() | client.createSession() | session.sendAndWait() | client.resumeSession() | client.stop() |
| Python | CopilotClient() | client.create_session() | session.send_and_wait() | client.resume_session() | client.stop() |
| Go | copilot.NewClient(nil) | client.CreateSession() | session.SendAndWait() | client.ResumeSession() | client.Stop() |
| .NET | new CopilotClient() | client.CreateSessionAsync() | session.SendAndWaitAsync() | client.ResumeSessionAsync() | client.DisposeAsync() |