注意
Copilot SDK 目前处于公开预览阶段。功能和可用性可能会更改。
Copilot SDK 可以与 MCP 服务器(模型上下文协议)集成,以通过外部工具扩展助手的功能。MCP 服务器作为独立进程运行,并公开工具(函数),Copilot 可以在对话中调用这些工具。
什么是 MCP?
Model Context Protocol (MCP)是一项用于将 AI 助手连接到外部工具和数据源的开放标准。MCP 服务器可以执行代码或脚本、查询数据库、访问文件系统、调用外部 API 等。
服务器类型
SDK 支持两种类型的 MCP 服务器
| 类型 | 描述 | 使用场景 |
|---|---|---|
| 本地/标准输入输出 | 作为子进程运行,通过 stdin/stdout 进行通信 | 本地工具、文件访问、自定义脚本 |
| HTTP/SSE | 通过 HTTP 访问的远程服务器 | 共享服务、云托管工具 |
配置
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、Go 和 .NET 的示例,请参阅 github/copilot-sdk 仓库。有关 Java,请参阅 github/copilot-sdk-java 仓库。
快速开始:文件系统 MCP 服务器
以下是使用官方 @modelcontextprotocol/server-filesystem MCP 服务器的完整示例
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();
提示
您可以从 MCP 服务器目录 中使用任意 MCP 服务器。常用选项包括 @modelcontextprotocol/server-github、@modelcontextprotocol/server-sqlite 与 @modelcontextprotocol/server-puppeteer。
配置选项
本地/标准输入输出服务器
| 属性 | 类型 | 是否必填 | 描述 |
|---|---|---|---|
type | "local" or "stdio" | 否 | 服务器类型(默认本地) |
command | string | 是 | 要执行的命令 |
参数 | string[] | 是 | 命令参数 |
env | object | 否 | 环境变量 |
cwd | string | 否 | 工作目录 |
tools | string[] | 否 | 要启用的工具(["*"] 表示全部,[] 表示不启用) |
超时 | number | 否 | 毫秒为单位的超时时间 |
远程服务器(HTTP/SSE)
| 属性 | 类型 | 是否必填 | 描述 |
|---|---|---|---|
type | "http" or "sse" | 是 | 服务器类型 |
url | string | 是 | 服务器 URL |
请求头 | object | 否 | HTTP 请求头(例如用于身份验证) |
tools | string[] | 否 | 要启用的工具 |
超时 | number | 否 | 毫秒为单位的超时时间 |
故障排除
工具未显示或未被调用
- 验证 MCP 服务器是否正确启动——检查命令和参数是否正确,并确保服务器进程在启动时没有崩溃。查看 stderr 中的错误输出。
- 检查工具配置——确保
tools被设置为["*"]或列出您需要的特定工具。空数组[]表示未启用任何工具。 - 验证远程服务器的连接性——确保 URL 可访问并检查身份验证请求头是否正确。
常见问题
| 议题 | 解决方案 |
|---|---|
| "未找到 MCP 服务器" | 验证命令路径是否正确且可执行 |
| "连接被拒绝"(HTTP) | 检查 URL 并确保服务器正在运行 |
| "超时" 错误 | 增大 timeout 值或检查服务器性能 |
| 工具可用但未被调用 | 确保您的提示明确要求使用该工具的功能 |
延伸阅读
- 模型上下文协议规范
- MCP 服务器目录——社区 MCP 服务器
- GitHub MCP 服务器——官方 GitHub MCP 服务器