Agent Skills by ALSEL
汎用LLM・AI開発⭐ リポ 4品質スコア 71/100

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-sdknpm install @github/copilot-sdk
Pythongithub-copilot-sdkpip install github-copilot-sdk
Gogithub.com/github/copilot-sdk/gogo get github.com/github/copilot-sdk/go
.NETGitHub.Copilot.SDKdotnet 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"ツール呼び出しを許可するかどうか
permissionDecisionReasonstringdeny/askの理由説明
modifiedArgsobject渡す引数の変更版
additionalContextstring会話の追加コンテキスト
suppressOutputboolean会話からツール出力を隠す

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"サーバートランスポートタイプ
commandstring実行ファイルパス(ローカル)
argsstring[]コマンド引数(ローカル)
urlstringサーバーURL(http)
toolsstring[]["*"]または特定のツール名
envobject環境変数
cwdstring作業ディレクトリ(ローカル)
timeoutnumberタイムアウト(ミリ秒)

認証

メソッド(優先順序)

  1. 明示的トークン — コンストラクタのgithubToken
  2. 環境変数COPILOT_GITHUB_TOKENGH_TOKENGITHUB_TOKEN
  3. 保存されたOAuthcopilot auth loginから
  4. GitHub CLIgh 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" });

クライアントコンフィグレーション

オプション説明
cliPathstringCopilot CLIの実行ファイルへのパス
cliUrlstring外部CLIサーバーのURL
githubTokenstring認証用GitHubトークン
useLoggedInUserboolean保存されたCLI認証情報を使用(デフォルト:true)
logLevelstring"none" | "error" | "warning" | "info" | "debug"
autoRestartbooleanCLIクラッシュ時に自動再起動(デフォルト:true)
useStdiobooleanstdioトランスポートを使用(デフォルト:true)

セッションコンフィグレーション

オプション説明
modelstring使用するモデル(例:"gpt-4.1"
sessionIdstring再開可能なセッションのカスタムID
streamingbooleanストリーミングレスポンスを有効化
toolsTool[]カスタムツール
mcpServersobjectMCPサーバーコンフィグ
hooksobjectセッションフック
providerobjectBYOKプロバイダーコンフィグ
customAgentsobject[]カスタムエージェント定義
systemMessageobjectシステムメッセージオーバーライド
skillDirectoriesstring[]スキルを読み込むディレクトリ
disabledSkillsstring[]無効化するスキル
reasoningEffortstring推論努力レベル
availableToolsstring[]利用可能なツールを制限
excludedToolsstring[]除外する特定のツール
infiniteSessionsobject自動圧縮コンフィグ
workingDirectorystring作業ディレクトリ

デバッグ

デバッグログを有効にして問題をトラブルシューティングします:

const client = new CopilotClient({ logLevel: "debug" });

一般的な問題:

  • CLI not found → CLIをインストールするかcliPathを設定
  • Not authenticatedcopilot auth loginを実行するかgithubTokenを提供
  • Session not founddestroy()後にセッションを使用しない
  • Connection refused → CLIプロセスを確認、autoRestartを有効化

主要API概要

言語クライアントセッション作成送信停止
Node.jsnew CopilotClient()client.createSession()session.sendAndWait()client.stop()
PythonCopilotClient()client.create_session()session.send_and_wait()client.stop()
Gocopilot.NewClient(nil)client.CreateSession()session.SendAndWait()client.Stop()
.NETnew CopilotClient()client.CreateSessionAsync()session.SendAndWaitAsync()client.DisposeAsync()

参考資料

いつ使うのか

このスキルは概要に記載されたワークフロー、またはアクションを実行する場合に適用できます。

ライセンス: MIT(寛容ライセンスのため全文を引用しています) · 原本リポジトリ

詳細情報

作者
ngTwg
リポジトリ
ngTwg/Branding-Focused-Skills
ライセンス
MIT
最終更新
2026/4/4

Source: https://github.com/ngTwg/Branding-Focused-Skills / ライセンス: MIT

本サイトは GitHub 上で公開されているオープンソースの SKILL.md ファイルをクロール・インデックス化したものです。 各スキルの著作権は原作者に帰属します。掲載に問題がある場合は info@alsel.co.jp または /takedown フォームよりご連絡ください。
原作者: ngTwg · ngTwg/Branding-Focused-Skills · ライセンス: MIT