# 本地调试测试指南
## 1. 环境准备
### 安装Go
确保已安装Go 1.21或更高版本:
```bash
go version
```
如果没有安装,请访问 https://golang.org/dl/ 下载安装。
### 安装项目依赖
```bash
cd yapi-mcp-server
go mod download
go mod tidy
```
## 2. 基本运行测试
### 方式1: 直接运行
```bash
go run .
```
程序会通过stdin/stdout进行MCP协议通信,等待JSON-RPC消息。
### 方式2: 构建后运行
```bash
# 构建
go build -o bin/yapi-mcp-server .
# 运行
./bin/yapi-mcp-server
```
## 3. 测试MCP协议消息
### 测试1: 初始化请求
创建一个测试文件 `test_init.json`:
```json
{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {},
"clientInfo": {
"name": "test-client",
"version": "1.0.0"
}
}
}
```
运行测试:
```bash
cat test_init.json | go run .
```
### 测试2: 列出可用工具
创建 `test_list_tools.json`:
```json
{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/list"
}
```
运行测试:
```bash
cat test_list_tools.json | go run .
```
### 测试3: 调用工具获取接口信息
创建 `test_get_interface.json`:
```json
{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "get_yapi_interface",
"arguments": {
"url": "http://your-yapi-instance.com/project/123/interface/api/456"
}
}
}
```
运行测试(需要先设置环境变量):
```bash
export YAPI_BASE_URL="http://your-yapi-instance.com"
export YAPI_TOKEN="your-token" # 可选
cat test_get_interface.json | go run .
```
## 4. 使用测试脚本
### 创建测试脚本
创建 `test.sh`:
```bash
#!/bin/bash
# 设置环境变量
export YAPI_BASE_URL="${YAPI_BASE_URL:-http://localhost}"
export YAPI_TOKEN="${YAPI_TOKEN:-}"
echo "=== 测试1: 初始化 ==="
echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}' | go run .
echo ""
echo "=== 测试2: 列出工具 ==="
echo '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' | go run .
echo ""
echo "=== 测试3: 调用工具 ==="
echo '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"get_yapi_interface","arguments":{"url":"http://yapi.example.com/project/123/interface/api/456"}}}' | go run .
```
运行测试脚本:
```bash
chmod +x test.sh
./test.sh
```
## 5. 使用Go测试框架
### 创建单元测试文件
创建 `main_test.go`:
```go
package main
import (
"encoding/json"
"os"
"strings"
"testing"
)
func TestHandleListTools(t *testing.T) {
server := &MCPServer{}
response := server.handleListTools()
if response["tools"] == nil {
t.Error("tools字段不存在")
}
tools := response["tools"].([]map[string]interface{})
if len(tools) == 0 {
t.Error("工具列表为空")
}
}
func TestHandleCallTool(t *testing.T) {
// 设置测试环境变量
os.Setenv("YAPI_BASE_URL", "http://test.example.com")
os.Setenv("YAPI_TOKEN", "test-token")
defer os.Unsetenv("YAPI_BASE_URL")
defer os.Unsetenv("YAPI_TOKEN")
server := &MCPServer{}
request := map[string]interface{}{
"params": map[string]interface{}{
"name": "get_yapi_interface",
"arguments": map[string]interface{}{
"url": "http://test.example.com/project/123/interface/api/456",
},
},
}
response := server.handleCallTool(request)
if response["error"] != nil {
t.Logf("错误响应(可能是预期的): %v", response["error"])
}
}
```
运行测试:
```bash
go test -v
```
## 6. 交互式调试
### 使用printf调试
在代码中添加调试输出:
```go
func (s *MCPServer) handleRequest(request map[string]interface{}) map[string]interface{} {
method, ok := request["method"].(string)
log.Printf("收到请求: method=%s", method) // 添加这行
// ... 其他代码
}
```
### 使用Go调试器
使用Delve调试器:
```bash
# 安装Delve
go install github.com/go-delve/delve/cmd/dlv@latest
# 使用Delve调试
dlv debug .
```
在调试器中:
- 设置断点: `break main.handleRequest`
- 运行: `continue`
- 查看变量: `print method`
- 单步执行: `next` 或 `step`
## 7. 测试YApi解析器
创建 `yapi_parser_test.go`:
```go
package main
import (
"testing"
)
func TestParseURL(t *testing.T) {
parser := NewYApiParser("", "")
tests := []struct {
url string
expected string
}{
{
"http://yapi.example.com/project/123/interface/api/456",
"123",
},
{
"http://yapi.example.com/project/789",
"789",
},
}
for _, tt := range tests {
info := parser.ParseURL(tt.url)
if info.ProjectID != tt.expected {
t.Errorf("ParseURL(%s) = %s, 期望 %s", tt.url, info.ProjectID, tt.expected)
}
}
}
```
运行测试:
```bash
go test -v -run TestParseURL
```
## 8. 模拟MCP客户端测试
创建 `test_client.go`:
```go
package main
import (
"encoding/json"
"fmt"
"os"
)
func main() {
server := &MCPServer{
stdin: os.Stdin,
stdout: os.Stdout,
}
// 测试消息
testMessages := []string{
`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{}}}`,
`{"jsonrpc":"2.0","id":2,"method":"tools/list"}`,
`{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"get_yapi_interface","arguments":{"url":"http://test.com/project/123/interface/api/456"}}}`,
}
for _, msg := range testMessages {
var request map[string]interface{}
json.Unmarshal([]byte(msg), &request)
response := server.handleRequest(request)
response["jsonrpc"] = "2.0"
response["id"] = request["id"]
output, _ := json.MarshalIndent(response, "", " ")
fmt.Println(string(output))
fmt.Println("---")
}
}
```
运行:
```bash
go run test_client.go
```
## 9. 使用curl测试(如果支持HTTP)
如果将来添加HTTP支持,可以使用curl测试:
```bash
curl -X POST http://localhost:8080/mcp \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
```
## 10. 常见问题排查
### 问题1: 程序立即退出
**原因**: MCP服务器通过stdio通信,如果没有输入会立即退出。
**解决**: 使用管道输入测试消息,或通过MCP客户端连接。
### 问题2: JSON解析错误
**原因**: 输入的JSON格式不正确。
**解决**: 检查JSON格式,使用 `jq` 验证:
```bash
echo '{"test":"value"}' | jq .
```
### 问题3: 环境变量未生效
**原因**: 环境变量未正确设置。
**解决**:
```bash
# 检查环境变量
echo $YAPI_BASE_URL
echo $YAPI_TOKEN
# 设置环境变量
export YAPI_BASE_URL="http://your-yapi.com"
export YAPI_TOKEN="your-token"
```
## 11. 性能测试
使用压力测试工具:
```bash
# 创建大量测试消息
for i in {1..100}; do
echo '{"jsonrpc":"2.0","id":'$i',"method":"tools/list"}' >> test_bulk.json
done
# 测试性能
time cat test_bulk.json | go run .
```
## 12. 日志调试
添加详细日志:
```go
import (
"log"
"os"
)
func init() {
log.SetOutput(os.Stderr) // 错误输出到stderr,不影响stdout的MCP通信
log.SetFlags(log.LstdFlags | log.Lshortfile)
}
```
在关键位置添加日志:
```go
log.Printf("收到请求: %+v", request)
log.Printf("解析URL: %s -> %+v", url, urlInfo)
```
## 快速测试命令总结
```bash
# 1. 基本测试
echo '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | go run .
# 2. 带环境变量的测试
YAPI_BASE_URL="http://test.com" echo '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_yapi_interface","arguments":{"url":"http://test.com/project/123/interface/api/456"}}}' | go run .
# 3. 运行单元测试
go test -v
# 4. 构建并测试
go build -o bin/yapi-mcp-server . && echo '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | ./bin/yapi-mcp-server
```