故障排除手冊.md•7.71 kB
# MCP Server 故障排除手冊
## 🔍 診斷工具
### 基本檢查清單
- [ ] Node.js 版本 >= 18.0.0
- [ ] npm 依賴已安裝
- [ ] TypeScript 已成功編譯
- [ ] 服務器可以獨立啟動
- [ ] Claude Desktop 配置正確
- [ ] 路徑使用正確的分隔符
### 快速診斷命令
```bash
# 檢查環境
node --version && npm --version
# 檢查依賴
npm list @modelcontextprotocol/sdk
# 測試編譯
npx tsc --noEmit
# 測試服務器
echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}}' | node dist/index.js
```
## ❌ 常見錯誤解決方案
### 1. 安裝問題
#### 錯誤:`npm install` 失敗
```
Error: Cannot resolve dependency
```
**解決方案**:
```bash
# 清除緩存
npm cache clean --force
# 刪除 node_modules
rm -rf node_modules package-lock.json
# 重新安裝
npm install
```
#### 錯誤:版本不兼容
```
Error: Node.js version not supported
```
**解決方案**:
```bash
# 升級 Node.js 到 18+ 版本
# 使用 nvm (推薦)
nvm install 20
nvm use 20
# 或直接從官網下載安裝
```
### 2. 編譯問題
#### 錯誤:TypeScript 編譯失敗
```
error TS2307: Cannot find module '@modelcontextprotocol/sdk'
```
**解決方案**:
```bash
# 確認依賴已安裝
npm install @modelcontextprotocol/sdk
# 重新編譯
npx tsc --build --clean
npx tsc
```
#### 錯誤:模組解析問題
```
Error: Cannot find module './tools/fileTools.js'
```
**解決方案**:
```typescript
// 確保導入路徑包含 .js 擴展名
import { fileTools } from './tools/fileTools.js';
```
### 3. 服務器運行問題
#### 錯誤:服務器啟動後立即退出
```bash
# 添加錯誤處理日誌
node dist/index.js 2>&1 | tee server.log
```
**常見原因**:
1. 未捕獲的異常
2. 模組導入失敗
3. 權限問題
**解決方案**:
```javascript
// 在 index.js 開頭添加
process.on('uncaughtException', (error) => {
console.error('Uncaught Exception:', error);
process.exit(1);
});
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
process.exit(1);
});
```
#### 錯誤:工具調用失敗
```
Error: Unknown tool: calculate
```
**檢查清單**:
1. 工具是否正確註冊
2. 工具名稱拼寫是否正確
3. 工具模組是否正確導入
### 4. Claude Desktop 集成問題
#### 問題:Claude Desktop 看不到 MCP 工具
**檢查步驟**:
1. **確認配置文件位置**:
```bash
# Windows
echo %APPDATA%\Claude\claude_desktop_config.json
# macOS
echo ~/Library/Application\ Support/Claude/claude_desktop_config.json
```
2. **驗證 JSON 格式**:
```bash
# 使用 jq 驗證 JSON
cat claude_desktop_config.json | jq .
```
3. **檢查路徑格式**:
```json
// Windows - 使用雙反斜線或正斜線
"args": ["D:\\path\\to\\dist\\index.js"]
// 或
"args": ["D:/path/to/dist/index.js"]
```
4. **確認文件權限**:
```bash
# 檢查文件是否可執行
ls -la dist/index.js
# Windows 下檢查
icacls dist\index.js
```
#### 問題:工具執行超時或失敗
**診斷步驟**:
1. **測試服務器獨立運行**:
```bash
node dist/index.js
# 手動輸入測試請求
```
2. **檢查日誌**:
- Claude Desktop 日誌:`%APPDATA%\Claude\logs\`
- 服務器錯誤輸出:檢查 stderr
3. **簡化測試**:
```json
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "get_current_time",
"arguments": {}
}
}
```
### 5. 網絡和權限問題
#### 錯誤:文件訪問被拒絕
```
Error: EACCES: permission denied
```
**解決方案**:
```bash
# 檢查目錄權限
ls -la /path/to/directory
# 修改權限 (小心使用)
chmod 755 /path/to/directory
```
#### 錯誤:網絡請求失敗
```
Error: fetch failed
```
**檢查清單**:
- 網絡連接是否正常
- 防火牆設置
- 代理配置
- SSL 證書問題
### 6. 內存和性能問題
#### 問題:內存使用過高
**監控命令**:
```bash
# 監控 Node.js 進程
top -p $(pgrep -f "node.*index.js")
# 或使用 htop
htop -p $(pgrep -f "node.*index.js")
```
**優化措施**:
```javascript
// 限制內存使用
node --max-old-space-size=512 dist/index.js
// 添加內存監控
setInterval(() => {
const used = process.memoryUsage();
console.error('Memory usage:', {
rss: Math.round(used.rss / 1024 / 1024) + ' MB',
heapTotal: Math.round(used.heapTotal / 1024 / 1024) + ' MB',
heapUsed: Math.round(used.heapUsed / 1024 / 1024) + ' MB'
});
}, 30000); // 每 30 秒檢查一次
```
## 🔧 調試工具
### 1. 詳細日誌
```javascript
// 在 index.ts 中添加詳細日誌
class MCPServer {
constructor() {
console.error('🚀 MCP Server initializing...');
this.server = new Server(
// ... 配置
);
console.error('✅ Server instance created');
}
private setupToolHandlers() {
console.error('🔧 Setting up tool handlers...');
this.server.setRequestHandler(ListToolsRequestSchema, async () => {
console.error('📋 Tools list requested');
const tools = [/* ... */];
console.error(`📋 Returning ${tools.length} tools`);
return { tools };
});
}
}
```
### 2. 請求/響應日誌
```javascript
this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
console.error('🔨 Tool call:', {
name: request.params.name,
args: request.params.arguments
});
try {
const result = await this.handleTool(request.params);
console.error('✅ Tool success:', { name: request.params.name });
return result;
} catch (error) {
console.error('❌ Tool error:', {
name: request.params.name,
error: error.message
});
throw error;
}
});
```
### 3. 性能監控
```javascript
class PerformanceMonitor {
private startTime = Date.now();
recordToolCall(toolName: string, duration: number, success: boolean) {
console.error('📊 Performance:', {
tool: toolName,
duration: `${duration}ms`,
success,
timestamp: new Date().toISOString()
});
}
}
```
## 🆘 緊急恢復
### 完全重置
如果一切都不工作,執行完全重置:
```bash
# 1. 清理項目
rm -rf node_modules dist package-lock.json
# 2. 重新安裝
npm install
# 3. 重新編譯
npm run build
# 4. 測試基本功能
echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}' | node dist/index.js
# 5. 如果還是不工作,檢查 Node.js 版本
node --version
```
### 最小化配置測試
創建最簡單的測試配置:
```json
{
"mcpServers": {
"test-server": {
"command": "node",
"args": ["D:/full/path/to/dist/index.js"]
}
}
}
```
### 逐步排除
1. **只測試服務器啟動**
2. **只測試工具列表**
3. **只測試一個簡單工具**
4. **逐步添加複雜功能**
## 📞 獲取幫助
### 收集診斷信息
```bash
# 創建診斷報告
cat > diagnostic-info.txt << EOF
Node.js Version: $(node --version)
NPM Version: $(npm --version)
OS: $(uname -a || systeminfo | head -5)
MCP SDK Version: $(npm list @modelcontextprotocol/sdk --depth=0)
Build Status: $(npx tsc --noEmit && echo "OK" || echo "FAILED")
Server Test: $(echo '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | timeout 5 node dist/index.js && echo "OK" || echo "FAILED")
EOF
```
### 日誌收集
```bash
# 運行服務器並收集所有輸出
node dist/index.js 2>&1 | tee full-server.log
# 同時監控系統資源
top -b -n 1 > system-info.log
```
---
**🔍 記住:大多數問題都可以通過仔細檢查路徑、權限和日誌來解決!**