# 调试指南

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

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

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

## 目录

* [启用调试日志记录](#enable-debug-logging)
* [常见问题](#common-issues)
* [MCP 服务器调试](#mcp-server-debugging)
* [连接问题](#connection-issues)
* [工具执行问题](#tool-execution-issues)
* [特定平台问题](#platform-specific-issues)

## 启用调试日志记录

调试的第一步是启用详细日志记录，以了解底层运行情况。

<div class="ghd-codetabs">
<div class="ghd-codetab" data-lang="typescript" data-label="TypeScript"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">TypeScript</div>

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

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

</div>

<div class="ghd-codetab" data-lang="python" data-label="Python"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Python</div>

```python
from copilot import CopilotClient

client = CopilotClient(log_level="debug")
```

</div>

<div class="ghd-codetab" data-lang="go" data-label="Go"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Go</div>

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

client := copilot.NewClient(&copilot.ClientOptions{
    LogLevel: "debug",
})
```

</div>

<div class="ghd-codetab" data-lang="dotnet" data-label=".NET"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">.NET</div>

<!-- docs-validate: skip -->

```csharp
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>()
});
```

</div>

<div class="ghd-codetab" data-lang="java" data-label="Java"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Java</div>

```java
import com.github.copilot.CopilotClient;
import com.github.copilot.rpc.*;

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

</div>

</div>

### 日志目录

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

<div class="ghd-codetabs">
<div class="ghd-codetab" data-lang="typescript" data-label="TypeScript"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">TypeScript</div>

```typescript
const client = new CopilotClient({
  cliArgs: ["--log-dir", "/path/to/logs"],
});
```

</div>

<div class="ghd-codetab" data-lang="python" data-label="Python"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Python</div>

```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.
```

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

</div>

<div class="ghd-codetab" data-lang="go" data-label="Go"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Go</div>

```golang
client := copilot.NewClient(&copilot.ClientOptions{
    Connection: copilot.StdioConnection{
        Args: []string{"--log-dir", "/path/to/logs"},
    },
})
```

</div>

<div class="ghd-codetab" data-lang="dotnet" data-label=".NET"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">.NET</div>

```csharp
var client = new CopilotClient(new CopilotClientOptions
{
    Connection = RuntimeConnection.ForStdio(args: new[] { "--log-dir", "/path/to/logs" })
});
```

</div>

<div class="ghd-codetab" data-lang="java" data-label="Java"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Java</div>

<!-- docs-validate: skip -->

```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.
```

</div>

</div>

## 常见问题

### “未找到 CLI”/“Copilot：未找到命令”

**原因：** 未安装 Copilot CLI，或者其未包含在 PATH 中。

**Solution:**

1. 安装 CLI： [安装指南](/zh/enterprise-cloud@latest/copilot/how-tos/copilot-cli/set-up-copilot-cli/install-copilot-cli)

2. 验证安装：

   ```bash
   copilot --version
   ```

3. 或指定完整路径：

<div class="ghd-codetabs">
<div class="ghd-codetab" data-lang="javascript" data-label="JavaScript"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">JavaScript</div>

```typescript
const client = new CopilotClient({
  cliPath: "/usr/local/bin/copilot",
});
```

</div>

<div class="ghd-codetab" data-lang="python" data-label="Python"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Python</div>

```python
client = CopilotClient({"cli_path": "/usr/local/bin/copilot"})
```

</div>

<div class="ghd-codetab" data-lang="go" data-label="Go"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Go</div>

```golang
client := copilot.NewClient(&copilot.ClientOptions{
    Connection: copilot.StdioConnection{Path: "/usr/local/bin/copilot"},
})
```

</div>

<div class="ghd-codetab" data-lang="dotnet" data-label=".NET"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">.NET</div>

```csharp
var client = new CopilotClient(new CopilotClientOptions
{
    CliPath = "/usr/local/bin/copilot"
});
```

</div>

<div class="ghd-codetab" data-lang="java" data-label="Java"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Java</div>

```java
var client = new CopilotClient(new CopilotClientOptions()
    .setCliPath("/usr/local/bin/copilot")
);
```

</div>

</div>

### “未进行身份验证”

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

**Solution:**

1. 对 CLI 进行身份验证：

   ```bash
   copilot auth login
   ```

2. 或者以编程方式提供令牌：

<div class="ghd-codetabs">
<div class="ghd-codetab" data-lang="javascript" data-label="JavaScript"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">JavaScript</div>

```typescript
const client = new CopilotClient({
  gitHubToken: process.env.GITHUB_TOKEN,
});
```

</div>

<div class="ghd-codetab" data-lang="python" data-label="Python"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Python</div>

```python
import os
client = CopilotClient({"github_token": os.environ.get("GITHUB_TOKEN")})
```

</div>

<div class="ghd-codetab" data-lang="go" data-label="Go"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Go</div>

```golang
client := copilot.NewClient(&copilot.ClientOptions{
    GitHubToken: os.Getenv("GITHUB_TOKEN"),
})
```

</div>

<div class="ghd-codetab" data-lang="dotnet" data-label=".NET"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">.NET</div>

```csharp
var client = new CopilotClient(new CopilotClientOptions
{
    GitHubToken = Environment.GetEnvironmentVariable("GITHUB_TOKEN")
});
```

</div>

<div class="ghd-codetab" data-lang="java" data-label="Java"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Java</div>

```java
var client = new CopilotClient(new CopilotClientOptions()
    .setGitHubToken(System.getenv("GITHUB_TOKEN"))
);
```

</div>

</div>

### “找不到会话”

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

**Solution:**

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

   ```typescript
   await session.disconnect();
   // Don't use session after this!
   ```

2. 对于恢复会话，请验证会话 ID 是否存在：

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

### “连接被拒绝”/“ECONNREFUSED”

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

**Solution:**

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

   ```bash
   copilot --server --stdio
   ```

2. 如果使用 TCP 模式，请检查端口冲突：

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

## MCP 服务器调试

MCP（模型上下文协议）服务器可能很难调试。 有关全面的 MCP 调试指南，请参阅专用 **[MCP 服务器调试指南](/zh/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/troubleshooting/mcp-debugging)**。

### 快速 MCP 清单

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

### 测试 MCP 服务器

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

```bash
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 服务器调试指南](/zh/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/troubleshooting/mcp-debugging) 。

## 连接问题

### stdio 与 TCP 模式

SDK 支持两种传输模式：

| 模式              | Description             | 用例           |
| --------------- | ----------------------- | ------------ |
| **Stdio** （默认值） | CLI 作为子进程运行，通过管道进行通信    | 本地开发，单一进程    |
| **TCP**         | CLI 单独运行，通过 TCP 套接字进行通信 | 多个客户端，远程 CLI |

**Stdio 模式（默认值）：**

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

**TCP 模式：**

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

**连接到现有服务器：**

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

### 诊断连接失败

1. **检查客户端状态：**

   ```typescript
   console.log("Connection state:", client.getState());
   // Should be "connected" after start()
   ```

2. **监听状态变化：**

   ```typescript
   client.on("stateChange", (state) => {
     console.log("State changed to:", state);
   });
   ```

3. **验证 CLI 进程是否正在运行：**

   ```bash
   # Check for copilot processes
   ps aux | grep copilot
   ```

## 工具执行问题

### 未调用自定义工具

1. **验证工具注册：**

   ```typescript
   const session = await client.createSession({
     tools: [myTool],
   });

   // Check registered tools
   console.log("Registered tools:", session.getTools?.());
   ```

2. **检查工具架构是否为有效的 JSON 架构：**

   ```typescript
   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. **确保处理程序返回有效结果：**

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

### 工具错误未出现

订阅错误事件：

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

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

## 特定于平台的问题

### Windows操作系统

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

   ```csharp
   CliPath = @"C:\Program Files\GitHub\copilot.exe"
   // or
   CliPath = "C:/Program Files/GitHub/copilot.exe"
   ```

2. **PATHEXT 解析：** SDK 会自动处理此问题，但如果问题仍然存在：

   ```csharp
   // Explicitly specify .exe
   Command = "myserver.exe"  // Not just "myserver"
   ```

3. **控制台编码：** 确保使用 UTF-8 编码，以正确处理 JSON：

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

### macOS

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

   ```bash
   xattr -d com.apple.quarantine /path/to/copilot
   ```

2. **GUI 应用中的 PATH 问题：** GUI 应用程序可能无法继承 shell PATH：

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

### Linux

1. **权限问题：**

   ```bash
   chmod +x /path/to/copilot
   ```

2. **缺少库：** 检查所需的共享库：

   ```bash
   ldd /path/to/copilot
   ```

## 获取帮助

如果你仍然卡住了：

1. **收集调试信息：**
   * SDK 版本
   * CLI 版本 （`copilot --version`）
   * 操作系统
   * 调试日志
   * 最小复制代码

2. **搜索现有问题：**[GitHub问题](https://github.com/github/copilot-sdk/issues)

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

## 另见

* [构建你的第一个由 Copilot 提供支持的应用](/zh/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/getting-started)
* [将 MCP 服务器与 GitHub Copilot SDK 配合使用](/zh/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/features/mcp) - MCP 配置和设置
* [MCP 服务器调试指南](/zh/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/troubleshooting/mcp-debugging) - 详细的 MCP 故障排除
* [API 参考](https://github.com/github/copilot-sdk)