# 将 MCP 服务器与 GitHub Copilot SDK 配合使用

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 支持两种类型的 MCP 服务器：

| 类型              | Description                  | 用例              |
| --------------- | ---------------------------- | --------------- |
| **Local/Stdio** | 作为子进程运行，通过 stdin/stdout 进行通信 | 本地工具、文件访问、自定义脚本 |
| **HTTP/SSE**    | 通过 HTTP 访问的远程服务器             | 共享服务、云托管工具      |

## Configuration

### 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 服务器

| 财产                    | 类型         | 必选           | Description                      |
| --------------------- | ---------- | ------------ | -------------------------------- |
| `type`                |            |              |                                  |
| `"local"` 或 `"stdio"` | 否          | 服务器类型（默认为本地） |                                  |
| `command`             | `string`   | Yes          | 要执行的命令                           |
| `args`                | `string[]` | Yes          | 命令参数                             |
| `env`                 | `object`   | 否            | 环境变量                             |
| `cwd`                 | `string`   | 否            | 工作目录                             |
| `tools`               | `string[]` | 否            | 要启用的工具（`["*"]` 表示全部启用，`[]` 都不启用） |
| `timeout`             | `number`   | 否            | 超时（以毫秒为单位）                       |

### 远程服务器 （HTTP/SSE）

| 财产                 | 类型         | 必选    | Description        |
| ------------------ | ---------- | ----- | ------------------ |
| `type`             |            |       |                    |
| `"http"` 或 `"sse"` | Yes        | 服务器类型 |                    |
| `url`              | `string`   | Yes   | 服务器 URL            |
| `headers`          | `object`   | 否     | HTTP 标头（例如，用于身份验证） |
| `tools`            | `string[]` | 否     | 要启用的工具             |
| `timeout`          | `number`   | 否     | 超时（以毫秒为单位）         |

## 故障排除

### 工具未显示或未被调用

1. **验证 MCP 服务器是否正确启动**
   * 检查命令和参数是否正确
   * 确保服务器进程在启动时不会崩溃
   * 在 stderr 中查找错误输出

2. **检查工具配置**
   * 确保 `tools` 已设置为 `["*"]` 或列出所需的特定工具
   * 空数组 `[]` 意味着未启用任何工具

3. **验证远程服务器的连接性**
   * 确保 URL 可访问
   * 检查身份验证标头是否正确

### 常见问题

| Issue           | 解决方案                   |
| --------------- | ---------------------- |
| “找不到 MCP 服务器”   | 验证命令路径是否正确且可执行         |
| “连接被拒绝”（HTTP）   | 检查 URL 并确保服务器正在运行      |
| “超时”错误          | 增加`timeout`的值，或检查服务器性能 |
| 工具虽然在正常运行但没有被调用 | 请确保提示明确指明工具的功能         |

有关详细的调试指南，请参阅 **[MCP 服务器调试指南](/zh/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 提供支持的应用](/zh/copilot/how-tos/copilot-sdk/getting-started) - SDK 基础知识和自定义工具
* [调试指南](/zh/copilot/how-tos/copilot-sdk/troubleshooting/debugging) - SDK 范围的调试

## 另见

* [MCP 服务器调试指南](/zh/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 文档跟踪问题