Skip to main content
Glama
README.md
# MCP Hub

聚合多个 MCP 服务器,统一暴露为一个标准 MCP 接口,供其他 Agent(如 Claude Code、Cursor 等)集成。

## 功能特性

- **多 MCP 聚合**:连接多个下游 MCP 服务器,将所有工具统一暴露
- **工具命名空间**:自动前缀隔离,`server_id_tool_name` 格式
- **双传输支持**:同时支持 stdio 和 HTTP (Streamable HTTP) 两种传输方式
- **热管理**:注册/启用/禁用下游服务器后**自动热重载**,无需重启网关
- **管理 API**:RESTful HTTP API 管理所有下游服务器
- **SQLite 持久化**:服务器配置持久存储,零外部依赖
- **自省工具**:内置 `gateway__list_servers` 和 `gateway__list_all_tools`

## 安装

### 前提条件

- Python >= 3.10
- Node.js >= 16(如需运行 npm MCP 包)

### 安装步骤

```bash
# 克隆或进入项目目录
cd mcp_demo

# 安装(开发模式)
pip install -e .
```

### 依赖

```
fastmcp >= 2.0      # MCP 框架
pydantic >= 2.0     # 数据模型校验
typer               # CLI 命令行
uvicorn             # HTTP 服务器
starlette           # HTTP 管理 API
aiosqlite           # SQLite 存储
httpx               # HTTP 客户端
```

## 快速开始

### 1. 注册下游 MCP 服务器

```bash
# 注册本地 Python MCP 服务器
mcp-gateway register \
  --server-id math \
  --display-name "Math Server" \
  --command python \
  --args "examples/downstream_servers/math_server.py"

# 注册天气服务器
mcp-gateway register \
  --server-id weather \
  --display-name "Weather Server" \
  --command python \
  --args "examples/downstream_servers/weather_server.py"

# 注册 bing-search(Windows 需要 cmd /c 包装)
mcp-gateway register \
  --server-id bing \
  --display-name "Bing Search" \
  --command cmd \
  --args "/c,npx,-y,bing-cn-mcp"

# 注册 HTTP 类型的 MCP 服务器
mcp-gateway register \
  --server-id remote-api \
  --display-name "Remote API" \
  --transport http \
  --url "https://api.example.com/mcp"
```

### 2. 查看已注册的服务器

```bash
# 基本列表
mcp-gateway list

# 显示连接状态和工具
mcp-gateway list --status --tools

# JSON 格式输出
mcp-gateway list --json
```

### 3. 启动网关

```bash
# stdio 模式(供 Claude Code 等 Agent 以子进程方式集成)
mcp-gateway serve

# HTTP 模式(供远程 Agent 连接)
mcp-gateway serve --transport http --port 8000

# 完整参数
mcp-gateway serve \
  --transport http \
  --host 0.0.0.0 \
  --port 8000 \
  --path /mcp \
  --management-port 9000 \
  --store gateway.db
```

## CLI 命令参考

| 命令 | 说明 |
|---|---|
| `mcp-gateway serve` | 启动网关服务器 |
| `mcp-gateway register` | 注册新的下游 MCP 服务器(自动通知运行中网关热重载) |
| `mcp-gateway list` | 列出所有已注册的服务器 |
| `mcp-gateway enable <id>` | 启用服务器(自动通知运行中网关热重载) |
| `mcp-gateway disable <id>` | 禁用服务器(自动通知运行中网关热重载) |
| `mcp-gateway remove <id>` | 永久移除服务器(自动通知运行中网关热重载) |
| `mcp-gateway health <id>` | 检查服务器健康状态 |
| `mcp-gateway reload` | 手动重载配置提示 |
| `mcp-gateway export-config` | 导出服务器配置 |
| `mcp-gateway import-config <file>` | 从 JSON 文件导入配置(自动通知运行中网关热重载) |

### `serve` 参数

| 参数 | 默认值 | 说明 |
|---|---|---|
| `--transport`, `-t` | `stdio` | 传输类型:`stdio` 或 `http` |
| `--host` | `127.0.0.1` | HTTP 监听地址 |
| `--port`, `-p` | `8000` | HTTP 端口 |
| `--path` | `/mcp` | MCP 协议的 HTTP 路径 |
| `--management-port` | `9000` | 管理 API 端口 |
| `--no-management` | — | 禁用管理 API |
| `--store` | `gateway_config.db` | SQLite 数据库路径 |
| `--name` | `MCP Gateway` | 网关名称 |
| `--log-level` | `INFO` | 日志级别 |

### `register` 参数

| 参数 | 说明 |
|---|---|
| `--server-id` | 唯一服务器标识(必填) |
| `--display-name` | 可读名称 |
| `--transport` | `stdio`(默认)或 `http` |
| `--command` | stdio 模式的启动命令 |
| `--args` | 逗号分隔的命令参数 |
| `--url` | HTTP 模式的服务器 URL |
| `--management-port` | 管理 API 端口,用于自动热重载(默认 9000) |
| `--no-auto-discover` | 注册后不立即连接 |
| `--tags` | 逗号分隔的标签 |
| `--store` | 存储路径 |

> **注意**:`register`、`enable`、`disable`、`remove`、`import-config` 命令执行后会自动通知运行中的网关热重载(通过管理 API)。如果网关未运行,重载请求会静默失败,不影响命令执行。

## HTTP 管理 API

管理 API 运行在独立端口(默认 9000)。

### 端点列表

```
GET    /api/v1/servers                      列出所有服务器
POST   /api/v1/servers                      注册新服务器
GET    /api/v1/servers/{server_id}          获取服务器详情
PUT    /api/v1/servers/{server_id}          更新服务器配置
DELETE /api/v1/servers/{server_id}          删除服务器
POST   /api/v1/servers/{server_id}/enable   启用服务器
POST   /api/v1/servers/{server_id}/disable  禁用服务器
GET    /api/v1/servers/{server_id}/health   健康检查
GET    /api/v1/tools                        查看所有聚合工具
GET    /api/v1/gateway/status               网关状态概览
POST   /api/v1/gateway/reload               热重载配置
GET    /api/v1/gateway/export               导出配置
POST   /api/v1/gateway/import               导入配置
```

### 使用示例

```bash
# 注册服务器
curl -X POST http://localhost:9000/api/v1/servers \
  -H "Content-Type: application/json" \
  -d '{
    "server_id": "weather",
    "display_name": "Weather Service",
    "transport": "stdio",
    "stdio_config": {"command": "python", "args": ["weather_server.py"]}
  }'

# 查看所有服务器
curl http://localhost:9000/api/v1/servers

# 查看聚合工具
curl http://localhost:9000/api/v1/tools

# 查看网关状态
curl http://localhost:9000/api/v1/gateway/status

# 启用/禁用
curl -X POST http://localhost:9000/api/v1/servers/weather/enable
curl -X POST http://localhost:9000/api/v1/servers/weather/disable

# 热重载
curl -X POST http://localhost:9000/api/v1/gateway/reload
```

## 供其他 Agent 集成

### Claude Code 集成

在项目根目录创建 `.mcp.json`:

```json
{
  "mcpServers": {
    "gateway": {
      "command": "python",
      "args": ["-m", "mcp_gateway", "serve", "--transport", "stdio"]
    }
  }
}
```

或使用全局 CLI 命令:

```bash
claude mcp add gateway -s project -- python -m mcp_gateway serve --transport stdio
```

### 自定义 Agent 集成

```python
# 通过 stdio
from fastmcp import Client
from fastmcp.client.transports import StdioTransport

async with Client(StdioTransport(
    command="python",
    args=["-m", "mcp_gateway", "serve", "--transport", "stdio"],
)) as client:
    # 列出所有工具(含命名空间前缀)
    tools = await client.list_tools()
    for tool in tools:
        print(tool.name)  # 如: math__add, weather__get_forecast

    # 调用代理工具
    result = await client.call_tool("math__add", {"a": 3, "b": 5})
    print(result)
```

```python
# 通过 HTTP
from fastmcp import Client

async with Client("http://localhost:8000/mcp") as client:
    tools = await client.list_tools()
    result = await client.call_tool("weather__get_current", {"city": "Beijing"})
    print(result)
```

### 远程 Agent 集成

作为标准 MCP HTTP 服务器,任何支持 MCP Streamable HTTP 协议的 Agent 都可以连接:

```json
{
  "mcpServers": {
    "gateway": {
      "type": "http",
      "url": "http://gateway-host:8000/mcp"
    }
  }
}
```

## 工具命名规则

所有下游服务器的工具自动添加 `server_id_` 前缀:

| 下游服务器 | 原始工具名 | 网关中的名称 |
|---|---|---|
| math | `add` | `math_add` |
| math | `multiply` | `math_multiply` |
| weather | `get_forecast` | `weather_get_forecast` |
| bing | `bing_search` | `bing_bing_search` |
| bing | `crawl_webpage` | `bing_crawl_webpage` |

网关自省工具使用双下划线 `gateway__` 前缀(不被 mount 改写):

| 工具名 | 功能 |
|---|---|
| `gateway__list_servers` | 列出所有服务器及连接状态 |
| `gateway__list_all_tools` | 列出所有聚合的工具 |

## 项目架构

```
外部 Agent (Claude Code / Cursor / 其他)
         │
    ┌────┴────┐
   stdio     HTTP (streamable-http)
    └────┬────┘
         ▼
  ┌──────────────────┐
  │  GatewayServer    │  ← 统一的 FastMCP 实例
  │  (FastMCP)        │
  └────┬────┬─────────┘
       │    │
  ┌────▼─┐ ┌▼────────────┐
  │Proxy  │ │Management   │
  │Manager│ │API          │
  └──┬──┬─┘ └─────────────┘
     │  │
 ┌───▼┐ ┌▼────┐
 │MCP A│ │MCP B│  ...
 └────┘ └─────┘
```

## 配置导入/导出

```bash
# 导出当前配置
mcp-gateway export-config --output servers.json

# 从 JSON 文件导入
mcp-gateway import-config servers.json

# 示例配置文件格式 (examples/config.yaml)
```

示例配置 (`examples/config.yaml`):

```json
{
  "mcpServers": {
    "math": {
      "command": "python",
      "args": ["examples/downstream_servers/math_server.py"]
    },
    "weather": {
      "command": "python",
      "args": ["examples/downstream_servers/weather_server.py"]
    },
    "bing-search": {
      "command": "cmd",
      "args": ["/c", "npx", "-y", "bing-cn-mcp"]
    }
  }
}
```

## 注意事项

1. **Windows stdio**:Windows 下注册 npm 类 MCP 需使用 `cmd` 命令:`--command cmd --args "/c,npx,-y,<package-name>"`
2. **网络环境**:HTTP 类型的下游服务器需要可访问的网络连接
3. **端口冲突**:默认 MCP 端口 8000,管理端口 9000,确保未被占用
4. **无 unmount**:FastMCP 暂不支持运行时 unmount,禁用/删除服务器后建议重启网关获得干净状态
5. **单机设计**:SQLite 适合单机部署,如需集群可通过 `AbstractStore` 接口扩展 PostgreSQL 等