# GitHub Copilot SDK での MCP サーバーの使用

Copilot SDK は MCP サーバー (モデル コンテキスト プロトコル) と統合して、アシスタントの機能を外部ツールで拡張できます。 MCP サーバーは個別のプロセスとして実行され、会話中に呼び出すことができるCopilotツール (関数) を公開します。

<!-- markdownlint-disable GHD046 GHD005 -->

<!-- Suppressed: GHD046 (outdated release terminology), GHD005 (hardcoded data variable) -->

> \[!NOTE]
> これは進化する機能です。 進行中のディスカッションについては [、問題 #36](https://github.com/github/copilot-sdk/issues/36) を参照してください。

## MCP とは

[モデル コンテキスト プロトコル (MCP)](https://modelcontextprotocol.io/) は、AI アシスタントを外部のツールやデータ ソースに接続するためのオープンな標準です。 MCP サーバーは次のことができます。

* コードまたはスクリプトを実行する
* データベースのクエリ
* ファイル システムにアクセスする
* 外部 API を呼び出す
* その他

## サーバーの種類

SDK では、次の 2 種類の MCP サーバーがサポートされています。

| タイプ             | 説明                                 | ユースケース(事例)                    |
| --------------- | ---------------------------------- | ----------------------------- |
| **Local/Stdio** | サブプロセスとして実行され、stdin/stdout 経由で通信する | ローカル ツール、ファイル アクセス、カスタム スクリプト |
| **HTTP/SSE**    | HTTP 経由でアクセスされるリモート サーバー           | 共有サービス、クラウドでホストされるツール         |

## コンフィギュレーション

### Node.js/ TypeScript

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

const client = new CopilotClient();
const session = await client.createSession({
    model: "gpt-5",
    mcpServers: {
        // Local MCP server (stdio)
        "my-local-server": {
            type: "local",
            command: "node",
            args: ["./mcp-server.js"],
            env: { DEBUG: "true" },
            cwd: "./servers",
            tools: ["*"],  // "*" = all tools, [] = none, or list specific tools
            timeout: 30000,
        },
        // Remote MCP server (HTTP)
        "github": {
            type: "http",
            url: "https://api.githubcopilot.com/mcp/",
            headers: { "Authorization": "Bearer ${TOKEN}" },
            tools: ["*"],
        },
    },
});
```

### Python

```python
import asyncio
from copilot import CopilotClient
from copilot.session import PermissionHandler

async def main():
    client = CopilotClient()
    await client.start()

    session = await client.create_session(on_permission_request=PermissionHandler.approve_all, model="gpt-5", mcp_servers={
        # Local MCP server (stdio)
        "my-local-server": {
            "type": "local",
            "command": "python",
            "args": ["./mcp_server.py"],
            "env": {"DEBUG": "true"},
            "cwd": "./servers",
            "tools": ["*"],
            "timeout": 30000,
        },
        # Remote MCP server (HTTP)
        "github": {
            "type": "http",
            "url": "https://api.githubcopilot.com/mcp/",
            "headers": {"Authorization": "Bearer ${TOKEN}"},
            "tools": ["*"],
        },
    })

    response = await session.send_and_wait("List my recent GitHub notifications")
    print(response.data.content)

    await client.stop()

asyncio.run(main())
```

### Go

```golang
package main

import (
    "context"
    "log"
    copilot "github.com/github/copilot-sdk/go"
)

func main() {
    ctx := context.Background()
    client := copilot.NewClient(nil)
    if err := client.Start(ctx); err != nil {
        log.Fatal(err)
    }
    defer client.Stop()

    session, err := client.CreateSession(ctx, &copilot.SessionConfig{
        Model: "gpt-5",
        MCPServers: map[string]copilot.MCPServerConfig{
            "my-local-server": copilot.MCPStdioServerConfig{
                Command: "node",
                Args:    []string{"./mcp-server.js"},
                Tools:   []string{"*"},
            },
        },
    })
    if err != nil {
        log.Fatal(err)
    }
    defer session.Disconnect()

    // Use the session...
}
```

### .NET

```csharp
using GitHub.Copilot;

await using var client = new CopilotClient();
await using var session = await client.CreateSessionAsync(new SessionConfig
{
    Model = "gpt-5",
    McpServers = new Dictionary<string, McpServerConfig>
    {
        ["my-local-server"] = new McpStdioServerConfig
        {
            Command = "node",
            Args = new List<string> { "./mcp-server.js" },
            Tools = new List<string> { "*" },
        },
    },
});
```

## セッションごとに構成されたサーバーを無効にする

`disabledMcpServers`を、セッションで実行してはならない MCP サーバー名に正確に設定します。
この設定のスコープは、個々の作成要求または再開要求です。グローバル MCP 設定またはサーバー構成は変更されません。

```typescript
const session = await client.createSession({
    mcpServers: {
        filesystem: { type: "local", command: "npx", args: ["-y", "@modelcontextprotocol/server-filesystem", "."] },
        github: { type: "http", url: "https://api.githubcopilot.com/mcp/" },
    },
    disabledMcpServers: ["github"],
});
```

| SDK     | 構成プロパティ                          |
| ------- | -------------------------------- |
| Node.js | `disabledMcpServers`             |
| Python  | `disabled_mcp_servers`           |
| Go      | `DisabledMCPServers`             |
| .NET    | `DisabledMcpServers`             |
| Java    | `setDisabledMcpServers(...)`     |
| Rust    | `with_disabled_mcp_servers(...)` |

セッションの作成と **コールド** 再開では、無効になっているサーバーは起動されず、ランタイムは認証を開始しません。 常駐履歴書は、ランタイムが既に生成したサーバーを元に戻すことはできません。 名前は正確に一致します。

## ツールの構成

`tools` フィールドを使用して、MCP サーバーで使用できるツールを制御できます。

### すべてのツールを許可する

`"*"`を使用して、MCP サーバーによって提供されるすべてのツールを有効にします。

```typescript
tools: ["*"]
```

### 特定のツールを許可する

アクセスを制限するツール名の一覧を指定します。

```typescript
tools: ["bash", "edit"]
```

エージェントで使用できるのは、一覧に示されているツールのみです。

### すべてのツールを無効にする

空の配列を使用して、すべてのツールを無効にします。

```typescript
tools: []
```

### Notes

* `tools` フィールドでは、使用できるツールを定義します。
* 個別の `allow` または `disallow` 構成はありません。ツール アクセスは、この一覧を通じて直接制御されます。

## クイック スタート: ファイルシステム MCP サーバー

公式の [`@modelcontextprotocol/server-filesystem`](https://www.npmjs.com/package/@modelcontextprotocol/server-filesystem) MCP サーバーを使用した完全な作業例を次に示します。

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

async function main() {
    const client = new CopilotClient();

    // Create session with filesystem MCP server
    const session = await client.createSession({
        mcpServers: {
            filesystem: {
                type: "local",
                command: "npx",
                args: ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
                tools: ["*"],
            },
        },
    });

    console.log("Session created:", session.sessionId);

    // The model can now use filesystem tools
    const result = await session.sendAndWait({
        prompt: "List the files in the allowed directory",
    });

    console.log("Response:", result?.data?.content);

    await session.disconnect();
    await client.stop();
}

main();
```

**Output:**

```text
Session created: 18b3482b-bcba-40ba-9f02-ad2ac949a59a
Response: The allowed directory is `/tmp`, which contains various files
and subdirectories including temporary system files, log files, and
directories for different applications.
```

> \[!TIP]
> [MCP サーバー ディレクトリから任意の MCP サーバー](https://github.com/modelcontextprotocol/servers)を使用できます。 一般的なオプションには、 `@modelcontextprotocol/server-github`、 `@modelcontextprotocol/server-sqlite`、 `@modelcontextprotocol/server-puppeteer`などがあります。

## 構成オプション

### ローカル/stdio サーバー

| 財産                      | タイプ        | 必須                 | 説明                                      |
| ----------------------- | ---------- | ------------------ | --------------------------------------- |
| `type`                  |            |                    |                                         |
| `"local"` または `"stdio"` | No         | サーバーの種類 (既定値はローカル) |                                         |
| `command`               | `string`   | はい                 | 実行するコマンド                                |
| `args`                  | `string[]` | はい                 | コマンド引数                                  |
| `env`                   | `object`   | No                 | 環境変数                                    |
| `cwd`                   | `string`   | No                 | 作業ディレクトリ                                |
| `tools`                 | `string[]` | No                 | すべてを有効にするツール (`["*"]` すべて有効), (`[]` なし) |
| `timeout`               | `number`   | No                 | タイムアウト (ミリ秒)                            |

### リモート サーバー (HTTP/SSE)

| 財産                   | タイプ        | 必須      | 説明                |
| -------------------- | ---------- | ------- | ----------------- |
| `type`               |            |         |                   |
| `"http"` または `"sse"` | はい         | サーバーの種類 |                   |
| `url`                | `string`   | はい      | サーバー アドレス         |
| `headers`            | `object`   | No      | HTTP ヘッダー (認証用など) |
| `tools`              | `string[]` | No      | 有効にするツール          |
| `timeout`            | `number`   | No      | タイムアウト (ミリ秒)      |

## Troubleshooting

### ツールが表示されない、または呼び出されていない

1. **MCP サーバーが正しく起動されていることを確認する**
   * コマンドと引数が正しいことを確認する
   * 起動時にサーバー プロセスがクラッシュしないことを確認する
   * stderr でエラー出力を探す

2. **ツールの構成を確認する**
   * `tools`が`["*"]`に設定されているか、必要な特定のツールが一覧表示されていることを確認します
   * 空の配列 `[]` は、ツールが有効になっていないこと

3. **リモート サーバーの接続を確認する**
   * URL にアクセスできることを確認する
   * 認証ヘッダーが正しいことを確認する

### 一般的な問題

| Issue                             | ソリューション                       |
| --------------------------------- | ----------------------------- |
| "MCP サーバーが見つかりません"                | コマンド パスが正しく、実行可能であることを確認する    |
| "接続が拒否されました" (HTTP)               | URL を確認し、サーバーが実行されていることを確認します |
| "タイムアウトエラー"                       |                               |
| `timeout`値を増やすか、サーバーのパフォーマンスを確認する |                               |
| ツールは機能しますが、呼び出されません               | プロンプトにツールの機能が明確に必要であることを確認する  |

デバッグの詳細なガイダンスについては、 **[MCP サーバー デバッグ ガイド](/ja/copilot/how-tos/copilot-sdk/troubleshooting/mcp-debugging)** を参照してください。

## 関連するリソース

* [モデル コンテキスト プロトコルの仕様](https://modelcontextprotocol.io/)
* [MCP サーバー ディレクトリ](https://github.com/modelcontextprotocol/servers) - コミュニティ MCP サーバー
* [GitHub MCP サーバー](https://github.com/github/github-mcp-server) - 公式GitHub MCP サーバー
* [初めてのCopilot搭載アプリを構築する](/ja/copilot/how-tos/copilot-sdk/getting-started) - SDK の基本とカスタム ツール
* [デバッグ ガイド](/ja/copilot/how-tos/copilot-sdk/troubleshooting/debugging) - SDK 全体のデバッグ

## こちらも参照ください

* [MCP サーバー デバッグ ガイド](/ja/copilot/how-tos/copilot-sdk/troubleshooting/mcp-debugging) - MCP の詳細なトラブルシューティング
* [問題 9](https://github.com/github/copilot-sdk/issues/9) - 元の MCP ツールの使用に関する質問
* [問題 #36](https://github.com/github/copilot-sdk/issues/36) - MCP ドキュメントの追跡に関する問題