# 디버깅 가이드

이 가이드에서는 지원되는 모든 언어에서 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 로깅 구성이 제한됩니다. 고급 로깅을 위해 CLI를 `--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 설치: [설치 가이드](/ko/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 서버 디버깅 가이드](/ko/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 서버 디버깅 가이드](/ko/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. **콘솔 인코딩:** 적절한 JSON 처리를 위해 UTF-8을 확인합니다.

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

### macOS

1. **게이트키퍼 문제:** CLI가 차단된 경우:

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

2. **GUI 앱의 PATH 문제:** GUI 애플리케이션은 셸 PATH를 상속할 수 없습니다.

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

### 리눅스

1. **권한 문제:**

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

2. **누락된 라이브러리:** 필요한 공유 라이브러리를 확인합니다.

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

## 도움 받기

여전히 막혀 있다면:

1. **디버그 정보 수집:**
   * SDK 버전
   * CLI 버전(`copilot --version`)
   * 운영 체제
   * 디버그 로그
   * 최소 복제 코드

2. **기존 이슈 검색:**[GitHub Issues](https://github.com/github/copilot-sdk/issues)

3. 수집된 정보**로 새 문제 열기**

## 참고하십시오

* [첫 번째 Copilot 기반 앱 빌드](/ko/copilot/how-tos/copilot-sdk/getting-started)
* [GitHub Copilot SDK에서 MCP 서버 사용](/ko/copilot/how-tos/copilot-sdk/features/mcp) - MCP 구성 및 설정
* [MCP 서버 디버깅 가이드](/ko/copilot/how-tos/copilot-sdk/troubleshooting/mcp-debugging) - 자세한 MCP 문제 해결
* [API 참조](https://github.com/github/copilot-sdk)