Thanks to visit codestin.com
Credit goes to docs.github.com

Skip to main content

バックエンド サービス用の Copilot SDK の設定

API、Web バックエンド、マイクロサービス、バックグラウンド ワーカーなどのサーバー側アプリケーションで GitHub Copilot SDK を実行します。

この機能を使用できるユーザーについて

GitHub Copilot SDK は、すべての Copilot プランで使用できます。

メモ

          Copilot SDK は現在 テクニカル プレビューです。 機能と可用性は変更される場合があります。

CLI は、バックエンド コードがネットワーク経由で接続するヘッドレス サーバーとして実行されます。

          **次の場合に最適です。** Web アプリ バックエンド、API サービス、内部ツール、CI/CD 統合、任意のサーバー側ワークロード。

どのように機能するのか

SDK が CLI 子プロセスを生成する代わりに、 ヘッドレス サーバー モードで CLI を個別に実行します。 バックエンドは、 cliUrl オプションを使用して TCP 経由で接続します。 ヘッドレス サーバー アーキテクチャの詳細な図と、それが既定の自動マネージド CLI とどのように比較されるかについては、 github/copilot-sdkrepository を参照してください。

主な特性:

  • CLI は永続的なサーバー プロセスとして実行され、要求ごとに生成されません。
  • SDK は TCP 経由で接続します。CLI とアプリは異なるコンテナーで実行できます。
  • 複数の SDK クライアントで 1 つの CLI サーバーを共有できます。
  • 任意の認証方法 (GitHub トークン、環境変数、BYOK) で動作します。

手順 1: ヘッドレス モードで CLI を起動する

CLI をバックグラウンド サーバーとして実行します。

# Start with a specific port
copilot --headless --port 4321

# Or let it pick a random port (prints the URL)
copilot --headless
# Output: Listening on http://localhost:52431

運用環境の場合は、システム サービスまたはコンテナーで実行します。

# Docker
docker run -d --name copilot-cli \
    -p 4321:4321 \
    -e COPILOT_GITHUB_TOKEN="$TOKEN" \
    ghcr.io/github/copilot-cli:latest \
    --headless --port 4321
# systemd
[Service]
ExecStart=/usr/local/bin/copilot --headless --port 4321
Environment=COPILOT_GITHUB_TOKEN=YOUR-GITHUB-TOKEN
Restart=always

手順 2: SDK を接続する

Node.js/ TypeScript

import { CopilotClient } from "@github/copilot-sdk";

const client = new CopilotClient({
    cliUrl: "localhost:4321",
});

const session = await client.createSession({
    sessionId: `user-${userId}-${Date.now()}`,
    model: "gpt-4.1",
});

const response = await session.sendAndWait({ prompt: req.body.message });
res.json({ content: response?.data.content });

Python

from copilot import CopilotClient

client = CopilotClient({
    "cli_url": "localhost:4321",
})
await client.start()

session = await client.create_session({
    "session_id": f"user-{user_id}-{int(time.time())}",
    "model": "gpt-4.1",
})

response = await session.send_and_wait({"prompt": message})

Go

client := copilot.NewClient(&copilot.ClientOptions{
    CLIUrl: "localhost:4321",
})
client.Start(ctx)
defer client.Stop()

session, _ := client.CreateSession(ctx, &copilot.SessionConfig{
    SessionID: fmt.Sprintf("user-%s-%d", userID, time.Now().Unix()),
    Model:     "gpt-4.1",
})

response, _ := session.SendAndWait(ctx, copilot.MessageOptions{Prompt: message})

.NET

var client = new CopilotClient(new CopilotClientOptions
{
    CliUrl = "localhost:4321",
    UseStdio = false,
});

await using var session = await client.CreateSessionAsync(new SessionConfig
{
    SessionId = $"user-{userId}-{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}",
    Model = "gpt-4.1",
});

var response = await session.SendAndWaitAsync(
    new MessageOptions { Prompt = message });

バックエンド サービスの認証

環境変数トークン

最も簡単な方法は、CLI サーバーでトークンを設定することです。

# All requests use this token
export COPILOT_GITHUB_TOKEN="YOUR-SERVICE-ACCOUNT-TOKEN"
copilot --headless --port 4321
          `YOUR-SERVICE-ACCOUNT-TOKEN`を、サービス アカウントのGitHubpersonal access tokenまたは OAuth トークンに置き換えます。

ユーザーごとのトークン (OAuth)

セッションの作成時に個々のユーザー トークンを渡す:

// Your API receives user tokens from your auth layer
app.post("/chat", authMiddleware, async (req, res) => {
    const client = new CopilotClient({
        cliUrl: "localhost:4321",
        githubToken: req.user.githubToken,
        useLoggedInUser: false,
    });

    const session = await client.createSession({
        sessionId: `user-${req.user.id}-chat`,
        model: "gpt-4.1",
    });

    const response = await session.sendAndWait({
        prompt: req.body.message,
    });

    res.json({ content: response?.data.content });
});

BYOK ( GitHub 認証なし)

モデル プロバイダーに独自の API キーを使用します。

const client = new CopilotClient({
    cliUrl: "localhost:4321",
});

const session = await client.createSession({
    model: "gpt-4.1",
    provider: {
        type: "openai",
        baseUrl: "https://api.openai.com/v1",
        apiKey: process.env.OPENAI_API_KEY,
    },
});

一般的なバックエンド パターン

Express を使用した Web API

import express from "express";
import { CopilotClient } from "@github/copilot-sdk";

const app = express();
app.use(express.json());

// Single shared CLI connection
const client = new CopilotClient({
    cliUrl: process.env.CLI_URL || "localhost:4321",
});

app.post("/api/chat", async (req, res) => {
    const { sessionId, message } = req.body;

    // Create or resume session
    let session;
    try {
        session = await client.resumeSession(sessionId);
    } catch {
        session = await client.createSession({
            sessionId,
            model: "gpt-4.1",
        });
    }

    const response = await session.sendAndWait({ prompt: message });
    res.json({
        sessionId,
        content: response?.data.content,
    });
});

app.listen(3000);

バックグラウンド ワーカー

import { CopilotClient } from "@github/copilot-sdk";

const client = new CopilotClient({
    cliUrl: process.env.CLI_URL || "localhost:4321",
});

// Process jobs from a queue
async function processJob(job: Job) {
    const session = await client.createSession({
        sessionId: `job-${job.id}`,
        model: "gpt-4.1",
    });

    const response = await session.sendAndWait({
        prompt: job.prompt,
    });

    await saveResult(job.id, response?.data.content);
    await session.disconnect(); // Clean up after job completes
}

Docker Compose のデプロイ

version: "3.8"

services:
  copilot-cli:
    image: ghcr.io/github/copilot-cli:latest
    command: ["--headless", "--port", "4321"]
    environment:
      - COPILOT_GITHUB_TOKEN=${COPILOT_GITHUB_TOKEN}
    ports:
      - "4321:4321"
    restart: always
    volumes:
      - session-data:/root/.copilot/session-state

  api:
    build: .
    environment:
      - CLI_URL=copilot-cli:4321
    depends_on:
      - copilot-cli
    ports:
      - "3000:3000"

volumes:
  session-data:

健康診断

CLI サーバーの正常性を監視します。

// Periodic health check
async function checkCLIHealth(): Promise<boolean> {
    try {
        const status = await client.getStatus();
        return status !== undefined;
    } catch {
        return false;
    }
}

セッションのクリーンアップ

バックエンド サービスは、リソース リークを回避するために、セッションを積極的にクリーンアップする必要があります。

// Clean up expired sessions periodically
async function cleanupSessions(maxAgeMs: number) {
    const sessions = await client.listSessions();
    const now = Date.now();

    for (const session of sessions) {
        const age = now - new Date(session.createdAt).getTime();
        if (age > maxAgeMs) {
            await client.deleteSession(session.sessionId);
        }
    }
}

// Run every hour
setInterval(() => cleanupSessions(24 * 60 * 60 * 1000), 60 * 60 * 1000);

制限事項

制限事項詳細情報
単一 CLI サーバー = 単一障害点本番環境でのデプロイについて、高可用性パターンを検討してください。
SDK と CLI の間に組み込みの認証がないネットワーク パス (同じホスト、VPC など) をセキュリティで保護します。
ローカル ディスク上のセッション状態コンテナーの再起動用に永続ストレージをマウントします。
30 分間の無操作タイムアウトアクティビティのないセッションは自動的にクリーンアップされます。

次のステップ

  • インストールと最初のメッセージについては、 Copilot SDK のはじめに を参照してください。
  • 再起動の間のセッションの再開については、 リポジトリのgithub/copilot-sdkを参照してください。
  • ユーザー認証の追加については、 リポジトリの github/copilot-sdk を参照してください。