Skip to main content
Glama
hr98w

MCP Server Proxy

by hr98w
README.md
# MCP Server Proxy

一个强大的代理服务器,可以聚合多个 MCP (Model Context Protocol) 服务器,让 LLM 客户端通过单一连接访问来自多个后端服务器的工具、资源和提示模板。

## ✨ 核心特性

- **🔗 多服务器聚合**: 同时连接多个 MCP 服务器(已测试 25+ 工具)
- **🚀 多传输协议支持**:
  - **代理对外**: stdio、HTTP (SSE)、Streamable HTTP
  - **后端连接**: stdio、HTTP (SSE)、Streamable HTTP 混合连接
- **🏷️ 命名空间管理**: 通过可配置命名空间避免命名冲突
- **📡 实时通知转发**: 转发后端服务器的通知到客户端
- **🔥 热重载配置**: 配置文件变更自动生效,无需重启服务
- **🌐 Web管理界面**: 现代化的Web界面管理MCP服务器配置
- **✅ 协议完全兼容**: 完全兼容 MCP 规范和 SDK v1.17.5
- **🔧 会话管理**: HTTP 传输的高级会话处理
- **🛡️ 健壮错误处理**: 完善的错误处理和连接管理
- **📊 全面日志记录**: 可配置级别的详细日志

## 🏗️ 架构设计

### 基础架构
```
LLM Client (Cursor/Claude Desktop)
    ↓ (JSON-RPC 2.0 via stdio/HTTP/Streamable)
MCP Server Proxy (多传输协议支持)
    ↓ (Multiple connections via stdio/HTTP/Streamable)
Backend MCP Servers (Everything, Memory, SSE, Streamable HTTP, etc.)
```

### 多传输协议架构
```
┌─────────────────┐    ┌──────────────────────────────────┐
│   LLM Client    │    │        MCP Server Proxy          │
│                 │    │                                  │
│ ┌─────────────┐ │    │ ┌─────────────┐ ┌──────────────┐ │
│ │ stdio       │◄┼────┼►│ stdio       │ │ BackendMgr   │ │
│ │ HTTP (SSE)  │◄┼────┼►│ HTTP (SSE)  │ │ CapabilityAgg│ │
│ │ Streamable  │◄┼────┼►│ Streamable  │ │ RequestRouter│ │
│ └─────────────┘ │    │ └─────────────┘ │ NotifyMgr    │ │
└─────────────────┘    │                 └──────────────┘ │
                       └──────────────────────────────────┘
                                    │
                       ┌────────────┼────────────┐
                       ▼            ▼            ▼
              ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
              │Everything   │ │Simple SSE   │ │Streamable   │
              │Server       │ │Server       │ │HTTP Server  │
              │(stdio)      │ │(HTTP)       │ │(Streamable) │
              └─────────────┘ └─────────────┘ └─────────────┘
```

代理服务器对客户端表现为单一的 MCP 服务器,同时管理与多个后端服务器的连接。

## 🚀 快速开始

### 环境要求

- Node.js >= 18.0.0
- npm >= 8.0.0
- 操作系统: macOS, Linux, Windows

### 1. 项目构建

#### 1.1 安装依赖
```bash
cd mcp-proxy
npm install
```

#### 1.2 构建项目
```bash
npm run build
```

构建完成后,编译后的文件将位于 `dist/` 目录中。

### 2. 启动后端测试MCP服务器

#### 2.1 启动 SSE Server (端口 3004)
```bash
# 在新的终端窗口中执行
node examples/server-sse.js
```

服务器将在 `http://localhost:3004/sse` 启动,提供 2 个工具。

#### 2.2 启动 Streamable HTTP Server (端口 3005)
```bash
# 在新的终端窗口中执行
node examples/server-streamable-http.js
```

服务器将在 `http://localhost:3005/mcp` 启动,提供 3 个工具。

#### 2.3 Everything Server (通过 stdio)
Everything Server 通过 stdio 协议启动,无需单独启动,将由 Proxy 自动管理。

### 3. 启动 Admin 管理页面

```bash
# 在新的终端窗口中执行
npm run dev:admin examples/config.json
```

管理界面将在 http://localhost:3001 启动。

### 4. 启动 Proxy Server

#### 4.1 基本启动 (支持热重载)
```bash
# 使用默认配置启动
node dist/index.js examples/config.json
```

#### 4.2 开发模式启动
```bash
# 开发模式,支持自动重启
npm run dev examples/config.json
```

#### 4.3 启用调试日志
```bash
# 启用详细调试日志
LOG_LEVEL=DEBUG node dist/index.js examples/config.json
```

#### 4.4 使用 MCP Inspector 测试
```bash
# 使用inspector启动
npx @modelcontextprotocol/inspector node dist/index.js examples/config.json
```

### 5. 配置Cursor连接

#### 5.1 创建 Cursor MCP 配置
编辑或创建 `~/.cursor/mcp.json` 文件:

```json
{
  "mcpServers": {
    "mcp-proxy": {
      "command": "node",
      "args": ["/path-to-mcp-proxy/mcp-proxy/dist/index.js", "/path-to-mcp-proxy/mcp-proxy/examples/config.json"],
      "env": {
        "LOG_LEVEL": "INFO"
      }
    }
  }
}
```

#### 5.2 重启 Cursor
完全关闭并重新启动 Cursor 以加载新的 MCP 配置。

### 6. 完整启动序列

按以下顺序启动所有组件:

```bash
# 终端 1: 构建项目
npm run build

# 终端 2: 启动 SSE Server
node examples/server-sse.js

# 终端 3: 启动 Streamable Server
node examples/server-streamable-http.js

# 终端 4: 启动管理界面
npm run dev:admin examples/config.json

# 终端 5: 启动 Proxy Server
LOG_LEVEL=DEBUG node dist/index.js examples/config.json

# 终端 6: 测试功能
npx @modelcontextprotocol/inspector node dist/index.js examples/config.json
```

### 7. 验证功能

#### 7.1 使用 MCP Inspector 测试
Inspector 将显示:
- 聚合的工具列表 (预期: 16 个工具)
- 资源列表 (预期: 10 个资源)
- 提示模板列表 (预期: 3 个提示模板)

#### 7.2 验证命名空间
工具名称应该带有命名空间前缀:
- `everything.*` - Everything Server 的工具 (11个)
- `sse.*` - SSE Server 的工具 (2个)
- `stream.*` - Streamable Server 的工具 (3个)

#### 7.3 测试热重载功能
编辑 `examples/config.json`,例如禁用一个服务器,保存后观察:
- Proxy 日志显示服务器被动态移除
- 工具数量实时变化
- Cursor 中的工具列表自动更新

### 8. 常见问题排查

#### 8.1 端口冲突
如果遇到端口占用问题:
```bash
# 查找占用端口的进程
lsof -ti:3004 | xargs kill -9
lsof -ti:3005 | xargs kill -9
```

#### 8.2 Cursor 连接问题
1. 检查 MCP 配置文件路径是否正确
2. 确保 Proxy 服务器正在运行
3. 查看 Cursor 的 MCP 日志 (`Cmd+Shift+U` → "MCP Logs")

### 环境变量

- `LOG_LEVEL`: 日志级别 (DEBUG, INFO, WARN, ERROR)
- `ADMIN_PORT`: 管理界面端口 (默认: 3001)

## Configuration

Create a configuration file (JSON format) to define your backend servers:

```json
{
  "serverInfo": {
    "name": "mcp-server-proxy",
    "version": "1.0.0"
  },
  "servers": [
    {
      "id": "everything",
      "name": "Everything Server",
      "command": "npx",
      "args": ["@modelcontextprotocol/server-everything"],
      "transport": "stdio",
      "namespace": "everything",
      "enabled": true
    },
    {
      "id": "simple-sse",
      "name": "Simple SSE Server",
      "transport": "http",
      "url": "http://localhost:3004/sse",
      "namespace": "sse",
      "enabled": true
    },
    {
      "id": "streamable-http",
      "name": "Streamable HTTP Server",
      "transport": "streamable",
      "url": "http://localhost:3005/mcp",
      "namespace": "stream",
      "enabled": true
    }
  ]
}
```

### Configuration Options

#### 通用配置
- `id`: 服务器唯一标识符
- `name`: 人类可读的服务器名称
- `transport`: 传输协议类型 ("stdio", "http", "streamable")
- `namespace`: 工具/资源/提示模板的命名空间前缀
- `enabled`: 是否启用该服务器

#### stdio 传输配置
- `command`: 启动服务器的命令
- `args`: 命令参数 (可选)
- `env`: 环境变量 (可选)

#### HTTP/Streamable 传输配置
- `url`: 服务器的 HTTP URL
  - HTTP SSE: `http://localhost:3004/sse`
  - Streamable HTTP: `http://localhost:3005/mcp`

## 🔥 热重载功能

MCP Proxy支持配置文件热重载,无需重启即可应用配置变更:

### 工作原理
1. **文件监听**: 自动监听配置文件变化
2. **智能差异检测**: 只更新发生变化的服务器
3. **动态管理**: 新增/删除/修改服务器配置
4. **MCP通知**: 自动通知客户端能力变化

### 使用方法
```bash
# 启动支持热重载的代理
node dist/index.js examples/config.json

# 修改配置文件,变更会自动生效
# 查看日志确认重载成功
```

### 支持的变更类型
- ✅ 添加新服务器
- ✅ 删除现有服务器
- ✅ 修改服务器配置
- ✅ 启用/禁用服务器

## 🌐 Web管理界面

现代化的Web界面管理MCP服务器配置:

### 功能特性
- **服务器列表**: 查看所有配置的MCP服务器
- **实时状态**: 显示服务器连接状态和能力统计
- **添加服务器**: 通过表单添加新的MCP服务器
- **编辑配置**: 修改现有服务器配置
- **一键操作**: 启用/禁用/删除服务器
- **实时更新**: 配置变更立即生效

### 访问方式
1. 启动管理服务器: `npm run dev:admin examples/config.json`
2. 打开浏览器访问: http://localhost:3001
3. 通过界面管理服务器配置

详细使用指南请参考 [ADMIN_GUIDE.md](./ADMIN_GUIDE.md)

## 🏷️ 命名空间

代理支持命名空间以避免服务器间的冲突:

- 无命名空间: `list_files`, `query_database`
- 有命名空间: `everything.list_files`, `sse.simple_tool`

实际项目中的命名空间示例:
- `everything.*` - Everything Server 的工具 (11个)
- `sse.*` - SSE Server 的工具 (2个)
- `stream.*` - Streamable Server 的工具 (3个)

## 🧪 测试验证

### 使用 MCP Inspector 测试

```bash
# 测试代理服务器
npx @modelcontextprotocol/inspector node dist/index.js examples/config.json
```

Inspector 将显示:
- **16个工具**: 来自3个不同服务器的聚合工具
- **10个资源**: 文件系统资源访问
- **3个提示模板**: 代码生成、文档编写等

### 验证成功标志

当所有组件正常运行时,你应该看到:

1. **Proxy 日志显示**:
   - "Starting MCP Server Proxy..."
   - "Connected to server: everything"
   - "Connected to server: stream"
   - "Aggregated capabilities: 16 tools, 10 resources, 3 prompts"

2. **MCP Inspector 显示**:
   - 16 个工具 (everything.*, sse.*, stream.*)
   - 10 个资源
   - 3 个提示模板

3. **管理界面显示**:
   - 服务器状态为 "Connected"
   - 实时能力统计正确

## API

The proxy implements the full MCP specification:

### Lifecycle
- `initialize` - Initialize connection and negotiate capabilities
- `initialized` - Confirm initialization complete

### Tools
- `tools/list` - List all available tools from all servers
- `tools/call` - Execute a tool (routed to appropriate server)

### Resources  
- `resources/list` - List all available resources from all servers
- `resources/read` - Read a resource (routed to appropriate server)

### Prompts
- `prompts/list` - List all available prompts from all servers
- `prompts/get` - Get a prompt (routed to appropriate server)

### Notifications
- `notifications/tools/list_changed` - Tools list changed
- `notifications/resources/list_changed` - Resources list changed  
- `notifications/prompts/list_changed` - Prompts list changed

## Development

### 项目结构

```
src/
├── proxy/           # 主代理服务器
├── managers/        # 组件管理器
│   ├── BackendManager.ts      # 后端服务器连接管理
│   ├── CapabilityAggregator.ts # 能力聚合
│   ├── RequestRouter.ts       # 请求路由
│   └── NotificationManager.ts # 通知处理
├── admin/           # Web管理界面
│   ├── server.ts              # 管理服务器
│   └── public/                # 前端资源
│       ├── index.html         # 管理界面
│       └── app.js             # 前端逻辑
├── types/           # TypeScript类型定义
├── utils/           # 工具函数
└── config/          # 配置管理
```

### Building

```bash
npm run build
```

### Linting

```bash
npm run lint
```

### 开发和测试

#### 构建项目
```bash
npm run build
```

#### 开发模式
```bash
# 启动开发模式(支持自动重启)
npm run dev examples/config.json

# 启动管理界面开发模式
npm run dev:admin examples/config.json
```

#### 集成测试

1. **完整功能测试**:
```bash
# 启动所有测试服务器
node examples/server-sse.js &
node examples/server-streamable-http.js &

# 启动代理服务器
LOG_LEVEL=DEBUG node dist/index.js examples/config.json
```

2. **使用 MCP Inspector 测试**:
```bash
npx @modelcontextprotocol/inspector node dist/index.js examples/config.json
```

这将:
- 在本地端口启动 MCP Inspector
- 将代理服务器作为子进程启动
- 打开Web界面进行交互式测试
- 验证16个工具的聚合结果

Web界面功能:
- 查看聚合的工具、资源和提示模板
- 使用自定义参数测试工具执行
- 监控实时 JSON-RPC 通信
- 调试协议消息和错误
- 检查服务器能力和元数据

#### 验证清单

- ✅ 代理服务器无错误启动
- ✅ 配置文件正确加载
- ✅ MCP Inspector 成功连接
- ✅ 协议握手完成 (initialize/initialized)
- ✅ 工具/资源/提示模板正确聚合 (16个工具)
- ✅ 命名空间前缀正常工作 (everything.*, sse.*, stream.*)
- ✅ 请求路由功能正常
- ✅ 错误处理健壮
- ✅ 通知正确转发
- ✅ 热重载功能正常
- ✅ Web管理界面可访问

## License

MIT License - see LICENSE file for details.

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request

## 🔧 故障排除

### 常见问题

1. **端口冲突**
   ```bash
   # 查找占用端口的进程
   lsof -ti:3004 | xargs kill -9  # SSE Server
   lsof -ti:3005 | xargs kill -9  # Streamable Server
   lsof -ti:3001 | xargs kill -9  # Admin界面
   ```

2. **后端服务器启动失败**
   - 检查配置文件中的命令和参数
   - 验证服务器可执行文件是否可用
   - 检查环境变量设置

3. **工具未显示**
   - 验证服务器已连接(检查日志)
   - 检查命名空间配置
   - 确保服务器支持工具能力
   - 验证服务器的 `enabled` 状态

4. **Cursor 连接问题**
   - 检查 MCP 配置文件路径是否正确
   - 确保 Proxy 服务器正在运行
   - 查看 Cursor 的 MCP 日志 (`Cmd+Shift+U` → "MCP Logs")
   - 完全重启 Cursor

5. **权限错误**
   - 检查文件系统权限
   - 验证环境变量设置正确
   ```bash
   chmod +x dist/index.js
   ```

### 调试模式

启用详细调试日志:

```bash
LOG_LEVEL=DEBUG node dist/index.js examples/config.json
```

这将显示详细信息:
- 服务器连接状态
- 能力加载过程
- 请求路由详情
- 通知处理过程
- 热重载操作