Skip to main content

初めてのCopilot搭載アプリを構築する

このチュートリアルでは、Copilot SDK を使用してコマンド ライン アシスタントを構築します。 基本から始めて、ストリーミング応答を追加し、その後カスタム ツールを追加して、Copilot にコードを呼び出す機能を与えます。

ビルドする内容:

You: What's the weather like in Seattle?
Copilot: Let me check the weather for Seattle...
         Currently 62°F and cloudy with a chance of rain.
         Typical Seattle weather!

You: How about Tokyo?
Copilot: In Tokyo it's 75°F and sunny. Great day to be outside!

Prerequisites

開始する前に、以下の項目があることを確認します:

  • GitHub Copilot CLI インストールおよび認証 (インストール ガイド)
  • お好みの言語ランタイム:
    • Node.js 20+ または Python 3.11 以降または Go 1.24 以上または> Rust 1.94 以上または Java 17 以上または .NET 8.0 以降

CLI が動作していることを確認します。

copilot --version

手順 1: SDK をインストールする

コード言語 navigation

TypeScript

まず、新しいディレクトリを作成し、プロジェクトを初期化します。

mkdir copilot-demo && cd copilot-demo
npm init -y --init-type module

次に、SDK と TypeScript ランナーをインストールします。

npm install @github/copilot-sdk tsx

手順 2: 最初のメッセージを送信する

新しいファイルを作成し、次のコードを追加します。 これは、SDK (約 5 行のコード) を使用する最も簡単な方法です。

コード言語 navigation

TypeScript

index.tsを作成します。

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();
process.exit(0);

次のコマンドを実行します。

npx tsx index.ts

次のように表示されます:

4

おめでとうございます! Copilot を活用したアプリを初めて構築しました。

手順 3: ストリーミング応答を追加する

現時点では、何かを表示する前に、完全な応答を待ちます。 生成された応答をストリーミングして対話型にしましょう。

コード言語 navigation

TypeScript

index.tsを更新してください。

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

const client = new CopilotClient();
const session = await client.createSession({
    model: "gpt-4.1",
    streaming: true,
});

// Listen for response chunks
session.on("assistant.message_delta", (event) => {
    process.stdout.write(event.data.deltaContent);
});
session.on("session.idle", () => {
    console.log(); // New line when done
});

await session.sendAndWait({ prompt: "Tell me a short joke" });

await client.stop();
process.exit(0);

コードをもう一度実行します。 応答が単語ごとに表示されます。

イベント サブスクリプションメソッド

SDK には、セッション イベントをサブスクライブするためのメソッドが用意されています。

MethodDescription
on(handler)すべてのイベントをサブスクライブする。unsubscribe 関数を返します
on(eventType, handler)特定のイベントの種類 (Node.js/TypeScript のみ) をサブスクライブします。unsubscribe 関数を返します
subscribe()すべてのイベントを購読する (Rust); event_type で絞り込む

コード言語 navigation

TypeScript
// Subscribe to all events
const unsubscribeAll = session.on((event) => {
    console.log("Event:", event.type);
});

// Subscribe to specific event type
const unsubscribeIdle = session.on("session.idle", (event) => {
    console.log("Session is idle");
});

// Later, to unsubscribe:
unsubscribeAll();
unsubscribeIdle();

手順 4: カスタム ツールを追加する

では、ここからが本題です。 Copilotカスタム ツールを定義してコードを呼び出す機能を提供しましょう。 簡単な気象検索ツールを作成します。

コード言語 navigation

TypeScript

index.tsを更新してください。

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

// Define a tool that Copilot can call
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 (args: { city: string }) => {
        const { city } = args;
        // In a real app, you'd call a weather API here
        const conditions = ["sunny", "cloudy", "rainy", "partly cloudy"];
        const temp = Math.floor(Math.random() * 30) + 50;
        const condition = conditions[Math.floor(Math.random() * conditions.length)];
        return { city, temperature: `${temp}°F`, condition };
    },
});

const client = new CopilotClient();
const session = await client.createSession({
    model: "gpt-4.1",
    streaming: true,
    tools: [getWeather],
});

session.on("assistant.message_delta", (event) => {
    process.stdout.write(event.data.deltaContent);
});

session.on("session.idle", () => {
    console.log(); // New line when done
});

await session.sendAndWait({
    prompt: "What's the weather like in Seattle and Tokyo?",
});

await client.stop();
process.exit(0);

それを実行すると、Copilot がツールを呼び出して天気データを取得し、その結果を返すことがわかります。

手順 5: 対話型アシスタントを構築する

すべてを便利な対話型アシスタントにまとめてみましょう。

コード言語 navigation

TypeScript
import { CopilotClient, defineTool } from "@github/copilot-sdk";
import * as readline from "readline";

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 }) => {
        const conditions = ["sunny", "cloudy", "rainy", "partly cloudy"];
        const temp = Math.floor(Math.random() * 30) + 50;
        const condition = conditions[Math.floor(Math.random() * conditions.length)];
        return { city, temperature: `${temp}°F`, condition };
    },
});

const client = new CopilotClient();
const session = await client.createSession({
    model: "gpt-4.1",
    streaming: true,
    tools: [getWeather],
});

session.on("assistant.message_delta", (event) => {
    process.stdout.write(event.data.deltaContent);
});

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});

console.log("🌤️  Weather Assistant (type 'exit' to quit)");
console.log("   Try: 'What's the weather in Paris?'\n");

const prompt = () => {
    rl.question("You: ", async (input) => {
        if (input.toLowerCase() === "exit") {
            await client.stop();
            rl.close();
            return;
        }

        process.stdout.write("Assistant: ");
        await session.sendAndWait({ prompt: input });
        console.log("\n");
        prompt();
    });
};

prompt();

次のコマンドを使用して実行します。

npx tsx weather-assistant.ts

セッションの例:

🌤️  Weather Assistant (type 'exit' to quit)
   Try: 'What's the weather in Paris?' or 'Compare weather in NYC and LA'

You: What's the weather in Seattle?
Assistant: Let me check the weather for Seattle...
It's currently 62°F and cloudy in Seattle.

You: How about Tokyo and London?
Assistant: I'll check both cities for you:
- Tokyo: 75°F and sunny
- London: 58°F and rainy

You: exit

Copilot呼び出し可能なカスタム ツールを使用してアシスタントを構築しました。

ツールのしくみ

ツールを定義するということは、Copilot に次のことを伝えていることになります:

  1. ツールの機能 (説明)
  2. 必要なパラメーター (スキーマ)
  3. 実行するコード (ハンドラー)

Copilotは、ユーザーの質問に基づいてツールを呼び出すタイミングを決定します。 その場合:

  1. Copilot はパラメーターを使用してツール呼び出し要求を送信します
  2. SDK によってハンドラー関数が実行されます
  3. 結果はCopilotに送り返されます
  4. Copilotは結果を応答に組み込みます

次は何ですか?

基本を理解したところで、さらに便利な機能をご紹介します:

MCP サーバーに接続する

MCP (モデル コンテキスト プロトコル) サーバーには、事前構築済みのツールが用意されています。 GitHubの MCP サーバーに接続して、リポジトリ、問題、プル要求にCopilotアクセスできるようにします。

const session = await client.createSession({
    mcpServers: {
        github: {
            type: "http",
            url: "https://api.githubcopilot.com/mcp/",
        },
    },
});

📖 ** Using MCP servers with the GitHub Copilot SDK** - ローカル サーバーとリモート サーバー、すべての構成オプション、トラブルシューティングについて説明します。

カスタム エージェントを作成する

特定のタスクに特化した 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.",
    }],
});

ヒント

セッション構成で agent: "pr-reviewer" を設定して、最初からこのエージェントを事前に選択することもできます。 詳細については、 カスタム エージェントとサブエージェント オーケストレーション を参照してください。

システム メッセージをカスタマイズする

指示を追加することで、AI の動作と個性を制御します。

const session = await client.createSession({
    systemMessage: {
        content: "You are a helpful assistant for our engineering team. Always be concise.",
    },
});

より詳細な制御を行うには、 mode: "customize" を使用して、残りの部分を維持しながら、システム プロンプトの個々のセクションをオーバーライドします。

const session = await client.createSession({
    systemMessage: {
        mode: "customize",
        sections: {
            tone: { action: "replace", content: "Respond in a warm, professional tone. Be thorough in explanations." },
            code_change_rules: { action: "remove" },
            guidelines: { action: "append", content: "\n* Always cite data sources" },
        },
        content: "Focus on financial analysis and reporting.",
    },
});

使用可能なセクション ID: identitytonetool_efficiencyenvironment_contextcode_change_rulesguidelinessafetytool_instructionscustom_instructionsruntime_instructionslast_instructions

各オーバーライドでは、 replaceremoveappendprependの 4 つのアクションがサポートされます。 不明なセクション ID は適切に処理されます。コンテンツは追加の命令に追加され、警告が出力されます。不明なセクションの remove は無視されます。

TypeScript</c0 の例については、言語固有の SDK READM を参照してください> PythonGoRustJava、および C#

外部 CLI サーバーへの接続

既定では、COPILOT CLI プロセス ライフサイクルが SDK によって自動的に管理され、必要に応じて CLI が開始および停止されます。 ただし、サーバー モードで CLI を個別に実行し、SDK に接続することもできます。 これは、次の場合に役立ちます。

  • デバッグ: SDK の再起動の間に CLI を実行したままにしてログを検査する
  • リソース共有: 複数の SDK クライアントが同じ CLI サーバーに接続できる
  • 開発: カスタム設定または別の環境で CLI を実行する

サーバー モードでの CLI の実行

--headless フラグを使用してサーバー モードで CLI を起動し、必要に応じてポートを指定します。

copilot --headless --port 4321

ポートを指定しない場合、CLI はランダムに使用可能なポートを選択します。

既定では、ヘッドレス サーバーはループバック (127.0.0.1) からの接続のみを受け入れるため、SDK は同じコンピューター上で実行する必要があります。 他のホスト (コンテナーまたは別のサーバーで CLI を実行する場合など) からの接続を受け入れるには、 --hostを使用して非ループバック アドレスにバインドします。

# Listen on all interfaces
copilot --headless --host 0.0.0.0 --port 4321

警告

非ループバック アドレスでヘッドレス サーバーを公開すると、そのアドレスにルーティングできるすべてのユーザーがヘッドレス サーバーに到達できるようになります。 ネットワーク制御 (ファイアウォール、プライベート ネットワーク、リバース プロキシ) と、環境に適した認証と組み合わせてください。

外部サーバーへの SDK の接続

CLI がサーバー モードで実行されたら、"cli url" オプションを使用してそれに接続するように SDK クライアントを構成します。

コード言語 navigation

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

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

// Use the client normally
const session = await client.createSession({ onPermissionRequest: approveAll });
// ...

メモ:cli_url / cliUrl/Go のUriConnectionが提供されている場合、または Rust がTransport::Externalを使用している場合、SDK は CLI プロセスを生成または管理しません。指定された URL にある既存のサーバーにのみ接続されます。

テレメトリと可観測性

Copilot SDK では、分散トレースの OpenTelemetry がサポートされています。 CLI プロセスからのトレース エクスポートと、SDK と CLI 間の telemetryの自動伝達を有効にする構成をクライアントに提供します。

テレメトリの有効化

クライアントの作成時に telemetry (または Telemetry) 構成を渡します。 これはオプトインです。個別の "有効" フラグは必要ありません。

コード言語 navigation

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

const client = new CopilotClient({
  telemetry: {
    otlpEndpoint: "http://localhost:4318",
  },
});

オプションのピア依存関係: @opentelemetry/api

TelemetryConfig オプション

オプションNode.jsPythonGoRustJava.NETDescription
OTLP エンドポイントotlpEndpointotlp_endpointOTLPEndpointotlp_endpointotlpEndpointOtlpEndpointOTLP HTTP エンドポイント URL
ファイルパスfilePathfile_pathFilePathfile_pathfilePathFilePathJSON 行トレース出力のファイル パス
エクスポーターの種類exporterTypeexporter_typeExporterTypeexporter_typeexporterTypeExporterType
"otlp-http" または "file"
求人者名sourceNamesource_nameSourceNamesource_namesourceNameSourceName計装範囲名
コンテンツをキャプチャするcaptureContentcapture_contentCaptureContentcapture_contentcaptureContentCaptureContentメッセージの内容をキャプチャするかどうか

ファイルのエクスポート

OTLP エンドポイントの代わりにローカル ファイルにトレースを書き込むには、

const client = new CopilotClient({
  telemetry: {
    filePath: "./traces.jsonl",
    exporterType: "file",
  },
});

トレース コンテキストの伝達

トレース コンテキストは自動的に伝達されます。手動によるインストルメンテーションは必要ありません。

  • SDK → CLI: 現在のスパン/アクティビティの traceparent ヘッダーと tracestate ヘッダーは、session.createsession.resume、および session.send RPC 呼び出しに含まれます。
  • CLI → SDK: CLI がツール ハンドラーを呼び出すと、CLI のスパンからのトレース コンテキストが伝達され、ツール コードが正しい親スパンで実行されます。

📖 ** Copilot SDK 用の OpenTelemetry インストルメンテーション** - TelemetryConfig オプション、トレース コンテキスト伝達、および言語ごとの依存関係。

詳細情報

それをやりました! GitHub Copilot SDK の主要な概念を学習しました。

  • ✅ クライアントとセッションの作成
  • ✅ メッセージの送信と応答の受信
  • ✅ リアルタイム出力のためのストリーミング
  • ✅ Copilot が呼び出せるカスタム ツールを定義する

今、素晴らしい何かを構築に行く! 🚀