copilot-sdk
GitHub Copilotとプログラムレベルで連携するアプリケーションを構築できます。このSDKはCopilot CLIをJSON-RPCでラップし、セッション管理、カスタムツール、フック、MCPサーバー統合、ストリーミング機能をNode.js、Python、Go、.NETで提供します。
description の原文を見る
Build applications that programmatically interact with GitHub Copilot. The SDK wraps the Copilot CLI via JSON-RPC, providing session management, custom tools, hooks, MCP server integration, and streaming across Node.js, Python, Go, and .NET.
SKILL.md 本文
GitHub Copilot SDK
GitHub Copilotとプログラムで連携するアプリケーションを構築します。このSDKはJSON-RPCを介してCopilot CLIをラップし、セッション管理、カスタムツール、フック、MCPサーバー統合、ストリーミングをNode.js、Python、Go、.NETで提供します。
前提条件
- 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 |
コアパターン:Client → Session → Message
すべての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を設定し、デルタイベントにサブスクライブすることで、リアルタイムに出力できます。
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()
session.on(handle_event)
await session.send_and_wait({"prompt": "Tell me a joke"})
イベントサブスクリプション
| メソッド | 説明 |
|---|---|
on(handler) | すべてのイベントにサブスクライブ、アンサブスクライブ関数を返す |
on(eventType, handler) | 特定のイベントタイプにサブスクライブ(Node.jsのみ) |
カスタムツール
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
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],
});
フック
セッションのライフサイクルの主要なポイントで動作をインターセプトし、カスタマイズします。
| フック | トリガー | ユースケース |
|---|---|---|
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" };
},
},
});
ツール前実行出力
| フィールド | 型 | 説明 |
|---|---|---|
permissionDecision | "allow" | "deny" | "ask" | ツール呼び出しを許可するかどうか |
permissionDecisionReason | string | deny/askの理由説明 |
modifiedArgs | object | 渡す引数の変更版 |
additionalContext | string | 会話の追加コンテキスト |
suppressOutput | boolean | 会話からツール出力を隠す |
MCPサーバー統合
MCPサーバーに接続して、事前構築されたツール機能を利用します。
リモートHTTPサーバー
const session = await client.createSession({
mcpServers: {
github: { type: "http", url: "https://api.githubcopilot.com/mcp/" },
},
});
ローカルStdioサーバー
const session = await client.createSession({
mcpServers: {
filesystem: {
type: "local",
command: "npx",
args: ["-y", "@modelcontextprotocol/server-filesystem", "/allowed/path"],
tools: ["*"],
},
},
});
MCPコンフィグフィールド
| フィールド | 型 | 説明 |
|---|---|---|
type | "local" | "http" | サーバートランスポートタイプ |
command | string | 実行ファイルパス(ローカル) |
args | string[] | コマンド引数(ローカル) |
url | string | サーバーURL(http) |
tools | string[] | ["*"]または特定のツール名 |
env | object | 環境変数 |
cwd | string | 作業ディレクトリ(ローカル) |
timeout | number | タイムアウト(ミリ秒) |
認証
メソッド(優先順序)
- 明示的トークン — コンストラクタの
githubToken - 環境変数 —
COPILOT_GITHUB_TOKEN→GH_TOKEN→GITHUB_TOKEN - 保存されたOAuth —
copilot auth loginから - GitHub CLI —
gh auth認証情報
プログラムによるトークン
const client = new CopilotClient({ githubToken: process.env.GITHUB_TOKEN });
BYOK(独自キーをお持ちください)
独自のAPIキーを使用 — Copilotサブスクリプションは不要です。
const session = await client.createSession({
model: "gpt-5.2-codex",
provider: {
type: "openai",
baseUrl: "https://your-resource.openai.azure.com/openai/v1/",
wireApi: "responses",
apiKey: process.env.FOUNDRY_API_KEY,
},
});
| プロバイダー | 型 | 注記 |
|---|---|---|
| OpenAI | "openai" | OpenAI APIおよび互換エンドポイント |
| Azure OpenAI | "azure" | ネイティブAzureエンドポイント(/openai/v1を含めない) |
| Azure AI Foundry | "openai" | OpenAI互換Foundryエンドポイント |
| Anthropic | "anthropic" | Claudeモデル |
| Ollama | "openai" | ローカルモデル、APIキー不要 |
ワイヤーAPI: GPT-5シリーズには"responses"を、その他には"completions"(デフォルト)を使用します。
セッション永続化
独自のセッションIDを提供することで、再起動をまたいでセッションを再開できます。
// 明示的IDで作成
const session = await client.createSession({
sessionId: "user-123-task-456",
model: "gpt-4.1",
});
// 後で再開
const resumed = await client.resumeSession("user-123-task-456");
await resumed.sendAndWait({ prompt: "What did we discuss?" });
セッション管理:
const sessions = await client.listSessions(); // すべて一覧表示
await client.deleteSession("user-123-task-456"); // 削除
await session.destroy(); // アクティブを破棄
BYOKセッション: 再開時にproviderコンフィグを再度提供する必要があります(キーは永続化されません)。
無限セッション
コンテキスト制限を超える可能性がある長時間実行のワークフロー用:
const session = await client.createSession({
infiniteSessions: {
enabled: true,
backgroundCompactionThreshold: 0.80,
bufferExhaustionThreshold: 0.95,
},
});
カスタムエージェント
特化した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"],
});
パーミッション&入力ハンドラー
ツールパーミッションとユーザー入力リクエストをプログラムで処理します:
const session = await client.createSession({
onPermissionRequest: async (request) => {
// gitコマンドのみ自動承認
if (request.kind === "shell") {
return { approved: request.command.startsWith("git") };
}
return { approved: true };
},
onUserInputRequest: async (request) => {
// ask_userツール呼び出しを処理
return { response: "yes" };
},
});
外部CLIサーバー
プロセスの自動管理の代わりに、別途実行中のCLIに接続します:
copilot --headless --port 4321
const client = new CopilotClient({ cliUrl: "localhost:4321" });
クライアントコンフィグレーション
| オプション | 型 | 説明 |
|---|---|---|
cliPath | string | Copilot CLIの実行ファイルへのパス |
cliUrl | string | 外部CLIサーバーのURL |
githubToken | string | 認証用GitHubトークン |
useLoggedInUser | boolean | 保存されたCLI認証情報を使用(デフォルト:true) |
logLevel | string | "none" | "error" | "warning" | "info" | "debug" |
autoRestart | boolean | CLIクラッシュ時に自動再起動(デフォルト:true) |
useStdio | boolean | stdioトランスポートを使用(デフォルト:true) |
セッションコンフィグレーション
| オプション | 型 | 説明 |
|---|---|---|
model | string | 使用するモデル(例:"gpt-4.1") |
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 | 作業ディレクトリ |
デバッグ
デバッグログを有効にして問題をトラブルシューティングします:
const client = new CopilotClient({ logLevel: "debug" });
一般的な問題:
CLI not found→ CLIをインストールするかcliPathを設定Not authenticated→copilot auth loginを実行するかgithubTokenを提供Session not found→destroy()後にセッションを使用しないConnection refused→ CLIプロセスを確認、autoRestartを有効化
主要API概要
| 言語 | クライアント | セッション作成 | 送信 | 停止 |
|---|---|---|---|---|
| Node.js | new CopilotClient() | client.createSession() | session.sendAndWait() | client.stop() |
| Python | CopilotClient() | client.create_session() | session.send_and_wait() | client.stop() |
| Go | copilot.NewClient(nil) | client.CreateSession() | session.SendAndWait() | client.Stop() |
| .NET | new CopilotClient() | client.CreateSessionAsync() | session.SendAndWaitAsync() | client.DisposeAsync() |
参考資料
いつ使うのか
このスキルは概要に記載されたワークフロー、またはアクションを実行する場合に適用できます。
ライセンス: MIT(寛容ライセンスのため全文を引用しています) · 原本リポジトリ
詳細情報
- 作者
- ngTwg
- ライセンス
- MIT
- 最終更新
- 2026/4/4
Source: https://github.com/ngTwg/Branding-Focused-Skills / ライセンス: MIT