Skip to content

如何使用 GitHub Copilot SDK 构建自定义 AI 应用程序

通过 GitHub Copilot SDK,开发者可以将 Copilot 的强大能力集成到自己的应用程序中。它通过 JSON-RPC 封装了 Copilot CLI,支持多语言调用、自定义工具定义及 MCP 协议集成,无需从零开发复杂的 AI 交互逻辑。

为什么需要这个技能

当你需要构建一个不仅仅是“聊天窗口”,而是能够与本地系统深度交互的 AI 应用时,简单的 API 调用是不够的。

Copilot SDK 提供了一套完整的生命周期管理方案:从会话维持(Session Management)到实时流式输出(Streaming),再到自定义工具(Custom Tools)的定义。它允许你定义 AI 可以调用的函数,甚至可以通过 MCP(Model Context Protocol)服务器连接现有的外部工具生态,极大地扩展了 AI 的行动能力。

适用场景

  • 构建自定义 AI Agent:创建具有特定角色(如 PR 评审员)且能调用本地 API 的智能体。
  • 开发 IDE 增强插件:在自己的开发工具中嵌入 Copilot 的代码理解和生成能力。
  • 自动化工作流集成:将 Copilot 接入到公司内部的 CI/CD 流程或运维面板中。
  • BYOK 方案实现:通过自定义 Provider,使用自己的 API Key 调用多种大模型。

核心工作流

1. 基础调用模式

所有操作遵循 Client Session Message 的模式。以 Node.js 为例:

typescript
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: "请分析这段代码的复杂度" });
console.log(response?.data.content);

await client.stop();

2. 扩展 AI 能力(自定义工具)

你可以定义 AI 在执行任务时可以调用的工具,使其能获取实时数据或执行具体操作:

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

const getWeather = defineTool("get_weather", {
    description: "获取指定城市的当前天气",
    parameters: {
        type: "object",
        properties: { city: { type: "string", description: "城市名称" } },
        required: ["city"],
    },
    handler: async ({ city }) => ({ city, temperature: "22°C", condition: "晴朗" }),
});

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

3. 高级集成与控制

  • MCP 集成:通过 mcpServers 配置,快速接入本地或远程的 MCP 服务器,复用社区已有的工具集。
  • 权限拦截 (Hooks):使用 onPreToolUse 钩子,在 AI 调用敏感工具(如 shell 命令)前进行权限审计或拦截。
  • 会话持久化:通过指定 sessionId 恢复之前的对话,实现跨重启的任务连续性。

下载和安装

下载 copilot-sdk 中文版 Skill ZIP

解压后将目录放入你的 AI 工具 skills 文件夹,重启工具后即可使用。具体路径参考内附的 USAGE.zh.md

你可能还需要

暂无推荐