Skip to main content

调试指南

本指南介绍所有受支持的语言中Copilot SDK 的常见问题和调试技术。

目录

启用调试日志记录

调试的第一步是启用详细日志记录,以便查看底层发生了什么。

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

const client = new CopilotClient({
  logLevel: "debug",  // Options: "none", "error", "warning", "info", "debug", "all"
});
Python
from copilot import CopilotClient

client = CopilotClient(log_level="debug")
Go
package main

import copilot "github.com/github/copilot-sdk/go"

func main() {
    client := copilot.NewClient(&copilot.ClientOptions{
        LogLevel: "debug",
    })
    _ = client
}
import copilot "github.com/github/copilot-sdk/go"

client := copilot.NewClient(&copilot.ClientOptions{
    LogLevel: "debug",
})
.NET
using GitHub.Copilot;
using Microsoft.Extensions.Logging;

// Using ILogger
var loggerFactory = LoggerFactory.Create(builder =>
{
    builder.SetMinimumLevel(LogLevel.Debug);
    builder.AddConsole();
});

var client = new CopilotClient(new CopilotClientOptions
{
    LogLevel = "debug",
    Logger = loggerFactory.CreateLogger<CopilotClient>()
});
Java
import com.github.copilot.sdk.CopilotClient;
import com.github.copilot.sdk.json.*;

var client = new CopilotClient(new CopilotClientOptions()
    .setLogLevel("debug")
);

日志目录

CLI 将日志写入目录。 可以指定自定义位置:

TypeScript
const client = new CopilotClient({
  cliArgs: ["--log-dir", "/path/to/logs"],
});
Python
# The Python SDK does not currently support passing extra CLI arguments.
# Logs are written to the default location or can be configured via
# the CLI when running in server mode.

注意

Python SDK 日志记录配置受到限制。 如需进行高级日志记录,请手动运行命令行工具 --log-dir,并通过 RuntimeConnection.for_uri(...) 连接。

Go
package main

import copilot "github.com/github/copilot-sdk/go"

func main() {
    client := copilot.NewClient(&copilot.ClientOptions{
        Connection: copilot.StdioConnection{
            Args: []string{"--log-dir", "/path/to/logs"},
        },
    })
    _ = client
}
client := copilot.NewClient(&copilot.ClientOptions{
    Connection: copilot.StdioConnection{
        Args: []string{"--log-dir", "/path/to/logs"},
    },
})
.NET
var client = new CopilotClient(new CopilotClientOptions
{
    Connection = RuntimeConnection.ForStdio(args: new[] { "--log-dir", "/path/to/logs" })
});
Java
// The Java SDK does not currently support passing extra CLI arguments.
// For custom log directories, run the CLI manually with --log-dir
// and connect via cliUrl.

常见问题

“未找到 CLI”/“Copilot:未找到命令”

原因: 未安装 Copilot CLI,或者其未包含在 PATH 中。

Solution:

  1. 安装 CLI: 安装指南

  2. 验证安装:

    copilot --version
    
  3. 或指定完整路径:

JavaScript
const client = new CopilotClient({
  cliPath: "/usr/local/bin/copilot",
});
Python
client = CopilotClient({"cli_path": "/usr/local/bin/copilot"})
Go
client := copilot.NewClient(&copilot.ClientOptions{
    Connection: copilot.StdioConnection{Path: "/usr/local/bin/copilot"},
})
.NET
var client = new CopilotClient(new CopilotClientOptions
{
    CliPath = "/usr/local/bin/copilot"
});
Java
var client = new CopilotClient(new CopilotClientOptions()
    .setCliPath("/usr/local/bin/copilot")
);

“未进行身份验证”

Cause: CLI 未使用GitHub进行身份验证。

Solution:

  1. 对 CLI 进行身份验证:

    copilot auth login
    
  2. 或者以编程方式提供令牌:

JavaScript
const client = new CopilotClient({
  gitHubToken: process.env.GITHUB_TOKEN,
});
Python
import os
client = CopilotClient({"github_token": os.environ.get("GITHUB_TOKEN")})
Go
client := copilot.NewClient(&copilot.ClientOptions{
    GithubToken: os.Getenv("GITHUB_TOKEN"),
})
.NET
var client = new CopilotClient(new CopilotClientOptions
{
    GithubToken = Environment.GetEnvironmentVariable("GITHUB_TOKEN")
});
Java
var client = new CopilotClient(new CopilotClientOptions()
    .setGitHubToken(System.getenv("GITHUB_TOKEN"))
);

“找不到会话”

原因: 尝试使用已销毁或不存在的会话。

Solution:

  1. 请确保不要在 disconnect() 之后调用方法。

    await session.disconnect();
    // Don't use session after this!
    
  2. 对于恢复会话,请验证会话 ID 是否存在:

    const sessions = await client.listSessions();
    console.log("Available sessions:", sessions);
    

“连接被拒绝”/“ECONNREFUSED”

原因: CLI 服务器进程崩溃或无法启动。

Solution:

  1. 检查 CLI 是否能独立正常运行:

    copilot --server --stdio
    
  2. 如果使用 TCP 模式,请检查端口冲突:

    const client = new CopilotClient({
      useStdio: false,
      port: 0,  // Use random available port
    });
    

MCP 服务器调试

MCP(模型上下文协议)服务器可能很难调试。 有关全面的 MCP 调试指南,请参阅专用 MCP 服务器调试指南

快速 MCP 清单

  • MCP 服务器可执行文件存在并独立运行
  • 命令路径正确(使用绝对路径)
  • 已启用工具: tools: ["*"]
  • 服务器正确响应 initialize 请求
  • 根据需要设置工作目录 (cwd

测试 MCP 服务器

在与 SDK 集成之前,请验证 MCP 服务器是否正常工作:

echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}' | /path/to/your/mcp-server

有关详细的故障排除,请参阅 MCP 服务器调试指南

连接问题

stdio 与 TCP 模式

SDK 支持两种传输模式:

模式Description用例
Stdio (默认值)CLI 作为子进程运行,通过管道进行通信本地开发,单一进程
TCPCLI 单独运行,通过 TCP 套接字进行通信多个客户端,远程 CLI

Stdio 模式(默认值):

const client = new CopilotClient({
  useStdio: true,  // This is the default
});

TCP 模式:

const client = new CopilotClient({
  useStdio: false,
  port: 8080,  // Or 0 for random port
});

连接到现有服务器:

const client = new CopilotClient({
  cliUrl: "localhost:8080",  // Connect to running server
});

诊断连接失败

  1. 检查客户端状态:

    console.log("Connection state:", client.getState());
    // Should be "connected" after start()
    
  2. 监听状态变化:

    client.on("stateChange", (state) => {
      console.log("State changed to:", state);
    });
    
  3. 验证 CLI 进程是否正在运行:

    # Check for copilot processes
    ps aux | grep copilot
    

工具执行问题

未调用自定义工具

  1. 验证工具注册:

    const session = await client.createSession({
      tools: [myTool],
    });
    
    // Check registered tools
    console.log("Registered tools:", session.getTools?.());
    
  2. 检查工具架构是否为有效的 JSON 架构:

    const myTool = {
      name: "get_weather",
      description: "Get weather for a location",
      parameters: {
        type: "object",
        properties: {
          location: { type: "string", description: "City name" },
        },
        required: ["location"],
      },
      handler: async (args) => {
        return { temperature: 72 };
      },
    };
    
  3. 确保处理程序返回有效结果:

    handler: async (args) => {
      // Must return something JSON-serializable
      return { success: true, data: "result" };
      
      // Don't return undefined or non-serializable objects
    }
    

工具错误未浮现

订阅错误事件:

session.on("tool.execution_error", (event) => {
  console.error("Tool error:", event.data);
});

session.on("error", (event) => {
  console.error("Session error:", event.data);
});

特定于平台的问题

Windows操作系统

  1. 路径分隔符: 使用原始字符串或正斜杠:

    CliPath = @"C:\Program Files\GitHub\copilot.exe"
    // or
    CliPath = "C:/Program Files/GitHub/copilot.exe"
    
  2. PATHEXT 解析: SDK 会自动处理此问题,但如果问题仍然存在:

    // Explicitly specify .exe
    Command = "myserver.exe"  // Not just "myserver"
    
  3. 控制台编码: 确保使用 UTF-8 编码,以正确处理 JSON:

    Console.OutputEncoding = System.Text.Encoding.UTF8;
    

macOS

  1. 守护程序问题: 如果阻止 CLI:

    xattr -d com.apple.quarantine /path/to/copilot
    
  2. GUI 应用中的 PATH 问题: GUI 应用程序可能无法继承 shell PATH:

    const client = new CopilotClient({
      cliPath: "/opt/homebrew/bin/copilot",  // Full path
    });
    

Linux

  1. 权限问题:

    chmod +x /path/to/copilot
    
  2. 缺少库: 检查所需的共享库:

    ldd /path/to/copilot
    

获取帮助

如果你仍然卡住了:

  1. 收集调试信息:

    • SDK 版本
    • CLI 版本 (copilot --version
    • 操作系统
    • 调试日志
    • 最小复制代码
  2. 搜索现有问题:GitHub问题

  3. 使用收集到的信息新建问题

另见