mcpField
C
copilot-sdk

copilot-sdk

github.com/microsoft開発3.2k78 回インストール1 日前に更新
リポジトリ

copilot-sdk について

GitHub Copilot SDKは、4つの言語でGitHub Copilotとプログラムから連携するアプリを開発するためのSDKです。Copilot CLIをラップし、セッション、ストリーミング、カスタムツール、フック、MCPサーバー連携を提供します。

主な機能

  1. 01Node.js、Python、Go、.NETに対応
  2. 02セッションとメッセージの管理
  3. 03ストリーミング応答とイベント
  4. 04カスタムツールとライフサイクルフック
  5. 05MCPサーバーの設定

活用シーン

  1. 01Copilotセッションを利用するアプリの開発
  2. 02画面へのCopilot応答のストリーミング表示
  3. 03Copilotへのアプリ固有ツールの追加
  4. 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-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

アーキテクチャ

SDK は、stdio(デフォルト)または TCP を介した JSON-RPC で Copilot CLI と通信します。CLI はモデル呼び出し、ツール実行、セッション状態、MCP サーバーのライフサイクルを管理します。

Your App → SDK Client → [stdio/TCP] → Copilot CLI → Model Provider
                                          ↕
                                     MCP Servers

トランスポートモード:

モード説明用途
Stdio(デフォルト)パイプ経由で CLI をサブプロセスとして実行ローカル開発、単一プロセス
TCPCLI をネットワークサーバーとして実行複数クライアント、バックエンドサービス

基本パターン:クライアント → セッション → メッセージ

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"ツール呼び出しを許可するかどうか
permissionDecisionReasonstring拒否または確認を求める理由
modifiedArgsobjectツールに渡す変更後の引数
additionalContextstring会話に追加するコンテキスト
suppressOutputboolean会話にツールの出力を表示しない
ツール実行後フック

実行後に結果を変換したり、機密データを秘匿化したり、ツールの動作をログに記録したりできます。

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 です
commandstringはい実行ファイルのパス
argsstring[]はいコマンド引数
envobjectいいえ環境変数
cwdstringいいえ作業ディレクトリ
toolsstring[]いいえすべての場合は ["*"]、なしの場合は []
timeoutnumberいいえタイムアウト(ミリ秒)

リモート HTTP:

フィールド型必須説明
type"http"はいサーバーの種類
urlstringはいサーバーの URL
headersobjectいいえHTTP ヘッダー
toolsstring[]いいえツールのフィルター
timeoutnumberいいえタイムアウト(ミリ秒)
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 に出力する必要があります

認証

認証方法(優先順位順)
  1. 明示的なトークン — コンストラクターの githubToken
  2. HMAC キー — CAPI_HMAC_KEY または COPILOT_HMAC_KEY 環境変数
  3. 直接 API トークン — COPILOT_API_URL とともに使用する GITHUB_COPILOT_API_TOKEN
  4. 環境変数 — COPILOT_GITHUB_TOKEN → GH_TOKEN → GITHUB_TOKEN
  5. 保存済み OAuth — copilot auth login で取得したもの
  6. 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"プロバイダーの種類
baseUrlstring必須。 API エンドポイントの URL
apiKeystringAPI キー(ローカルプロバイダーでは省略可)
bearerTokenstringBearer トークン認証(apiKey より優先)
wireApi"completions" | "responses"API 形式(デフォルト:"completions")
azure.apiVersionstringAzure 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 を停止する前に、アクティブなセッションの処理を完了します

クライアントの設定

オプション型デフォルト説明
cliPathstring自動検出Copilot CLI 実行可能ファイルのパス
cliUrlstring—外部 CLI サーバーの URL
githubTokenstring—認証用の GitHub トークン
useLoggedInUserbooleantrue保存済みの CLI 認証情報を使用します
logLevelstring"none""none" | "error" | "warning" | "info" | "debug"
autoRestartbooleantrueクラッシュ時に CLI を自動再起動します
useStdiobooleantruestdio トランスポートを使用します

セッションの設定

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

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 foundCLI がインストールされていないか、PATH にありませんCLI をインストールするか、cliPath を設定します
Not authenticated有効な認証情報がありませんcopilot auth login を実行するか、githubToken を指定します
Session not founddestroy() の実行後にセッションを使用していますlistSessions() で有効な ID を確認します
Connection refusedCLI プロセスがクラッシュしましたautoRestart: true を有効にし、ポートの競合を確認します
MCP ツールが見つからないサーバーの初期化に失敗したか、ツールが有効になっていませんtools: ["*"] を設定し、サーバーを個別にテストします
接続状態
console.log("State:", client.getState());  // "connected" after start()
client.on("stateChange", (state) => console.log("Changed to:", state));

主要 API の概要

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

References

コメント