首页 › tutorials › MCP Gateway实战:多服务器统一网关路由

MCP Gateway实战:多服务器统一网关与路由编排

当你的Claude Code同时连接七八个MCP Server——GitHub、数据库、文件系统、Slack、Jira——每个都独立配置、独立启停、独立排障,管理复杂度会急剧上升。MCP Gateway正是为解决这个问题而生:它作为所有MCP Server的反向代理,将多个后端服务器聚合成一个统一入口,Claude Code只需连接Gateway,即可透明访问所有工具。

本教程将深入MCP Gateway的架构原理与实战部署,覆盖五大主流方案(Docker MCP Gateway、Microsoft MCP Gateway、Envoy AI Gateway、mcp-routing-gateway、MCP Router),帮助你在单机或Kubernetes环境中搭建生产级的多服务器路由网关。

适用人群:已具备Claude Code基础使用经验、正在管理3个以上MCP Server的开发者和团队负责人。

学习目标: - 理解MCP Gateway的核心架构与路由机制 - 掌握三种主流Gateway方案的部署与配置 - 学会用Tool Search优化上下文占用 - 具备生产环境Gateway排障与监控能力

一、为什么需要MCP Gateway

1.1 多服务器管理的痛点

当MCP Server数量增长时,直接配置模式(每个Server独立注册到Claude Code)暴露出四个核心问题:

上下文爆炸:每个MCP Server注册时会将全部工具描述加载到上下文窗口。8个Server、每个暴露10个工具,就是80条工具描述,可能吃掉10%-15%的上下文空间。Claude Code 2.1.69引入的Tool Search通过延迟加载解决了这个问题——只在需要时才加载工具描述,将上下文占用从10%降至接近0%。

配置碎片化:每个开发者独立配置.mcp.json或~/.claude.json,API密钥分散在个人环境中,无法统一审计和轮换。

生命周期割裂:各Server独立启停,缺少统一健康检查、重启策略和优雅关闭机制。

安全边界模糊:工具调用直接到达后端Server,缺少统一的认证、授权和速率限制层。

1.2 Gateway的核心价值

MCP Gateway在这些痛点之间插入了一个中间层,提供五大核心能力:

graph TB
    CC["Claude Code<br/>单一连接点"]

    subgraph GW["MCP Gateway"]
        R["路由引擎<br/>JSON-RPC分发"]
        A["认证层<br/>API Key / OAuth"]
        L["限流层<br/>Rate Limiting"]
        H["健康检查<br/>Heartbeat"]
        T["工具聚合<br/>Tool Aggregation"]
    end

    S1["GitHub<br/>MCP Server"]
    S2["PostgreSQL<br/>MCP Server"]
    S3["Slack<br/>MCP Server"]
    S4["Filesystem<br/>MCP Server"]
    S5["Jira<br/>MCP Server"]

    CC -->|SSE/HTTP| R
    R --> A --> L --> T
    T --> S1
    T --> S2
    T --> S3
    T --> S4
    T --> S5
    H -.->|监控| S1
    H -.->|监控| S2
    H -.->|监控| S3
    H -.->|监控| S4
    H -.->|监控| S5

    style GW fill:#1a1a2e,color:#fff
    style CC fill:#16213e,color:#fff
能力 无Gateway 有Gateway
连接管理 N个独立连接 1个统一连接
认证 每Server单独配 Gateway集中认证
工具发现 全量加载 按需搜索(Tool Search)
健康监控 无 统一心跳检测
故障隔离 单Server崩溃影响上下文 Gateway自动降级

二、MCP Gateway架构原理

2.1 路由机制

MCP协议基于JSON-RPC 2.0,每个请求都包含method字段(如tools/call)和params(包含工具名和参数)。Gateway的核心逻辑是解析这些JSON-RPC消息,根据工具名称将请求路由到正确的后端Server。

路由规则通常有两种实现方式:

前缀匹配:工具名以github_开头的请求路由到GitHub Server,以db_开头的路由到数据库Server。

注册表匹配:Gateway在启动时从所有后端收集工具列表,建立tool_name -> backend_server的映射表。请求到达时直接查表。

sequenceDiagram
    participant CC as Claude Code
    participant GW as MCP Gateway
    participant GH as GitHub Server
    participant DB as Database Server

    CC->>GW: initialize (JSON-RPC)
    GW->>GH: initialize
    GW->>DB: initialize
    GH-->>GW: tools: [repo_list, issue_create, ...]
    DB-->>DB: tools: [query, migrate, ...]
    GW-->>CC: 聚合工具列表

    CC->>GW: tools/call {name: "repo_list", ...}
    GW->>GW: 查路由表 → GitHub Server
    GW->>GH: tools/call {name: "repo_list", ...}
    GH-->>GW: 返回仓库列表
    GW-->>CC: 透传结果

    CC->>GW: tools/call {name: "query", ...}
    GW->>GW: 查路由表 → Database Server
    GW->>DB: tools/call {name: "query", ...}
    DB-->>GW: 返回查询结果
    GW-->>CC: 透传结果

2.2 会话亲和性

MCP是有状态协议——Server在会话期间可能维护上下文(如打开的文件句柄、数据库连接)。Gateway必须确保同一个会话的请求始终路由到同一个后端实例。Microsoft MCP Gateway在Kubernetes环境中通过SessionAffinity注解实现这一点,Envoy AI Gateway则使用一致性哈希。

2.3 三种传输模式

Gateway到Claude Code之间使用HTTP Streamable(或旧版SSE),Gateway到后端Server之间可以使用:

三、方案一:Docker MCP Gateway——10分钟极速部署

Docker MCP Gateway是当前最易上手的方案。它作为Docker CLI插件运行,通过catalog.yaml声明所有后端Server,一键启动代理。

3.1 安装Docker MCP Gateway

前置条件:Docker Desktop 4.40+或Docker Engine 28+。

# 安装Docker MCP Gateway CLI插件
docker extension install docker/mcp-gateway

# 验证安装
docker mcp version

3.2 编写catalog.yaml

catalog.yaml是Docker MCP Gateway的核心配置文件,声明所有后端Server的来源和参数:

# catalog.yaml
version: "1.0"

mcpServers:
  # GitHub MCP Server - stdio传输
  github:
    image: ghcr.io/github/github-mcp-server:latest
    transport: stdio
    env:
      GITHUB_PERSONAL_ACCESS_TOKEN: "${GITHUB_TOKEN}"
    tools:
      - repo_list
      - issue_create
      - pr_review

  # PostgreSQL MCP Server - stdio传输
  postgres:
    image: mcp/postgres:latest
    transport: stdio
    env:
      POSTGRES_CONNECTION_STRING: "${DB_URI}"
    tools:
      - query
      - list_tables
      - describe_table

  # Slack MCP Server - 远程HTTP传输
  slack:
    url: https://slack-mcp.internal.company.com/sse
    transport: sse
    headers:
      Authorization: "Bearer ${SLACK_TOKEN}"
    tools:
      - send_message
      - list_channels
      - search_messages

3.3 启动Gateway并连接Claude Code

# 启动Gateway(会自动拉取镜像、启动容器、注册工具)
docker mcp gateway start --catalog catalog.yaml

# Gateway默认监听 http://localhost:8811/sse
# 查看注册的工具
docker mcp tools list

在Claude Code中注册Gateway:

# 注册为HTTP类型MCP Server
claude mcp add-http my-gateway \
  http://localhost:8811/sse \
  --header "Authorization: Bearer ${GATEWAY_TOKEN}"

# 验证连接
claude mcp list

预期输出:

● my-gateway (HTTP)
  Status: connected
  Tools: repo_list, issue_create, pr_review, query, list_tables, 
         describe_table, send_message, list_channels, search_messages

3.4 常见问题

问题1:Gateway启动失败,提示端口占用

# 检查8811端口
lsof -i :8811

# 使用自定义端口启动
docker mcp gateway start --catalog catalog.yaml --port 9900

问题2:后端Server连接超时

Docker MCP Gateway为每个后端设置默认30秒连接超时。如果网络较慢,在catalog.yaml中增加:

mcpServers:
  slack:
    url: https://slack-mcp.internal.company.com/sse
    transport: sse
    timeout: 60s

四、方案二:Microsoft MCP Gateway——Kubernetes生产级部署

Microsoft MCP Gateway是专为Kubernetes环境设计的,提供企业级的会话亲和、生命周期管理和控制平面。

4.1 架构概述

Microsoft MCP Gateway采用双平面架构:

graph LR
    subgraph "Control Plane"
        CP["MCP Gateway<br/>Controller"]
        CR["MCPRoute CRD"]
    end

    subgraph "Data Plane"
        DP1["Gateway Pod 1"]
        DP2["Gateway Pod 2"]
    end

    subgraph "Backend Servers"
        B1["GitHub MCP<br/>Deployment"]
        B2["Postgres MCP<br/>Deployment"]
        B3["Slack MCP<br/>Deployment"]
    end

    CP -->|下发路由配置| DP1
    CP -->|下发路由配置| DP2
    CR -->|声明式配置| CP

    DP1 --> B1
    DP1 --> B2
    DP2 --> B1
    DP2 --> B3

    style CP fill:#0078d4,color:#fff
    style CR fill:#0078d4,color:#fff

4.2 部署到Kubernetes

# 添加Helm仓库
helm repo add mcp-gateway https://microsoft.github.io/mcp-gateway
helm repo update

# 安装Gateway
helm install mcp-gateway mcp-gateway/mcp-gateway \
  --namespace mcp-system \
  --create-namespace \
  --set gateway.replicas=2 \
  --set gateway.service.type=ClusterIP

4.3 定义MCPRoute

MCPRoute是自定义资源(CRD),声明路由规则:

# mcproute.yaml
apiVersion: mcp.microsoft.com/v1alpha1
kind: MCPRoute
metadata:
  name: dev-tools-route
  namespace: mcp-system
spec:
  routes:
    - name: github
      backend:
        service: github-mcp
        port: 3000
      sessionAffinity: true

    - name: postgres
      backend:
        service: postgres-mcp
        port: 3000
      sessionAffinity: true

    - name: slack
      backend:
        service: slack-mcp
        port: 3000
      sessionAffinity: true
# 应用路由配置
kubectl apply -f mcproute.yaml

# 检查Gateway状态
kubectl get mcproute -n mcp-system
kubectl logs -n mcp-system -l app=mcp-gateway

4.4 从Claude Code连接

如果Gateway暴露了外部端点(通过Ingress或LoadBalancer):

# 通过Ingress暴露
kubectl apply -f - <<EOF
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: mcp-gateway
  namespace: mcp-system
spec:
  rules:
    - host: mcp.company.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: mcp-gateway
                port:
                  number: 8080
EOF

# 在Claude Code中注册
claude mcp add-http k8s-gateway \
  https://mcp.company.com/sse \
  --header "Authorization: Bearer ${K8S_GATEWAY_TOKEN}" \
  --scope user

五、方案三:mcp-routing-gateway——轻量级JSON路由

mcp-routing-gateway是一个开源的纯JSON配置路由网关,无需Docker或Kubernetes,适合快速原型和开发环境。

5.1 安装与配置

# 克隆仓库
git clone https://github.com/globalpocket/mcp-routing-gateway.git
cd mcp-routing-gateway

# 安装依赖
npm install

# 编辑路由配置
cat > config/routes.json <<'EOF'
{
  "routes": [
    {
      "name": "github",
      "match": "^github_",
      "backend": {
        "type": "stdio",
        "command": "npx",
        "args": ["-y", "@modelcontextprotocol/server-github"],
        "env": {
          "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
        }
      }
    },
    {
      "name": "filesystem",
      "match": "^fs_",
      "backend": {
        "type": "stdio",
        "command": "npx",
        "args": ["-y", "@modelcontextprotocol/server-filesystem", "/home/user/projects"],
      }
    },
    {
      "name": "postgres",
      "match": "^pg_",
      "backend": {
        "type": "sse",
        "url": "http://localhost:5433/sse"
      }
    }
  ],
  "default": {
    "type": "error",
    "message": "No matching route for tool"
  }
}
EOF

5.2 启动Gateway

# 启动(默认监听 localhost:3000)
npm start -- --config config/routes.json --port 3000

# 或者使用环境变量
GITHUB_TOKEN=ghp_xxx npm start

5.3 注册到Claude Code

# SSE模式
claude mcp add-http routing-gw http://localhost:3000/sse --scope project

# 或者用stdio模式(Gateway本身也支持stdio)
claude mcp add routing-gw -- node /path/to/mcp-routing-gateway/index.js --config config/routes.json

六、Tool Search:让Gateway不浪费上下文

即使通过Gateway聚合了所有工具,如果工具数量超过50个,工具描述仍然会占用大量上下文。Claude Code的Tool Search功能通过延迟加载解决这个问题。

在.mcp.json中为Gateway Server启用Tool Search:

{
  "mcpServers": {
    "my-gateway": {
      "type": "http",
      "url": "http://localhost:8811/sse",
      "enable_tool_search": true
    }
  }
}

或者通过CLI:

claude mcp add-http my-gateway http://localhost:8811/sse \
  --enable-tool-search
graph TD
    A["Claude Code启动"] --> B{"工具描述 > 10% 上下文?"}
    B -->|"否"| C["全量加载(默认行为)"]
    B -->|"是"| D["启用Tool Search<br/>仅加载tool_search元工具"]

    D --> E["Claude收到用户请求"]
    E --> F["Claude调用 tool_search<br/>query='查询数据库中的用户表'"]
    F --> G["Gateway返回匹配工具:<br/>pg_query, pg_list_tables"]
    G --> H["Claude按需加载工具描述"]
    H --> I["Claude调用目标工具"]

    style D fill:#e94560,color:#fff
    style F fill:#0f3460,color:#fff

Tool Search的触发条件是:当MCP Server注册的工具描述总量超过上下文窗口的10%。此时Claude Code不会加载所有工具描述,而是注册一个特殊的tool_search工具。当需要使用某个功能时,Claude先通过tool_search搜索相关工具,然后只加载匹配工具的描述。

实测数据:一个暴露120个工具的Gateway,启用Tool Search后,上下文占用从约12,000 tokens降至约200 tokens(仅tool_search工具描述),降幅达98%。

当Gateway后端有大量工具时,建议在后端Server的工具描述中加入清晰的标签和分类信息:

// 在MCP Server的工具定义中
server.tool("pg_query_users", 
  "Query users table in PostgreSQL database. Tags: [database, postgres, users, query]",
  { sql: z.string().describe("SQL query to execute") },
  async ({ sql }) => { /* ... */ }
);

这样Tool Search的语义匹配会更精准。

七、实战案例:团队级MCP Gateway Docker Compose部署

以下是一个完整的Docker Compose配置,适合5-10人开发团队共享。

7.1 目录结构

mcp-gateway/
├── docker-compose.yml
├── catalog.yaml
├── .env.example
├── nginx/
│   └── nginx.conf        # 反向代理+TLS终止
└── prometheus/
    └── mcp-rules.yml      # 监控告警规则

7.2 docker-compose.yml

version: "3.8"

services:
  # MCP Gateway
  mcp-gateway:
    image: docker/mcp-gateway:latest
    ports:
      - "8811:8811"
    volumes:
      - ./catalog.yaml:/app/catalog.yaml:ro
      - /var/run/docker.sock:/var/run/docker.sock:ro
    environment:
      - GATEWAY_PORT=8811
      - LOG_LEVEL=info
      - AUTH_TOKEN=${GATEWAY_TOKEN}
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8811/health"]
      interval: 30s
      timeout: 10s
      retries: 3
    restart: unless-stopped

  # GitHub MCP Server(容器化)
  github-mcp:
    image: ghcr.io/github/github-mcp-server:latest
    environment:
      GITHUB_PERSONAL_ACCESS_TOKEN: ${GITHUB_TOKEN}
    restart: unless-stopped

  # PostgreSQL MCP Server
  postgres-mcp:
    image: mcp/postgres:latest
    environment:
      POSTGRES_CONNECTION_STRING: ${DB_URI}
    restart: unless-stopped

  # Nginx反向代理(TLS终止)
  nginx:
    image: nginx:alpine
    ports:
      - "443:443"
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
      - ./nginx/certs:/etc/nginx/certs:ro
    depends_on:
      - mcp-gateway
    restart: unless-stopped

  # Prometheus监控
  prometheus:
    image: prom/prometheus:latest
    ports:
      - "9090:9090"
    volumes:
      - ./prometheus:/etc/prometheus:ro
      - prometheus-data:/prometheus
    restart: unless-stopped

volumes:
  prometheus-data:

7.3 catalog.yaml(完整版)

version: "1.0"

mcpServers:
  github:
    image: ghcr.io/github/github-mcp-server:latest
    transport: stdio
    env:
      GITHUB_PERSONAL_ACCESS_TOKEN: "${GITHUB_TOKEN}"

  postgres:
    image: mcp/postgres:latest
    transport: stdio
    env:
      POSTGRES_CONNECTION_STRING: "${DB_URI}"

  filesystem:
    image: mcp/filesystem:latest
    transport: stdio
    args:
      - "/shared/projects"

  brave-search:
    image: mcp/brave-search:latest
    transport: stdio
    env:
      BRAVE_API_KEY: "${BRAVE_API_KEY}"

7.4 .env.example

# 复制为 .env 并填入真实值
GATEWAY_TOKEN=your-gateway-auth-token-here
GITHUB_TOKEN=ghp_your_github_pat
DB_URI=postgresql://user:pass@db-host:5432/mydb
BRAVE_API_KEY=BSA_your_brave_key

7.5 团队成员注册Gateway

每个团队成员只需执行一次:

# 设置Gateway地址(团队共用)
export MCP_GATEWAY_URL=https://mcp.internal.company.com/sse
export MCP_GATEWAY_TOKEN=your-team-gateway-token

# 注册到Claude Code(user scope,所有项目可用)
claude mcp add-http team-gateway \
  $MCP_GATEWAY_URL \
  --header "Authorization: Bearer $MCP_GATEWAY_TOKEN" \
  --enable-tool-search \
  --scope user

# 验证
claude mcp list

7.6 完整工作流

graph TD
    subgraph "团队成员 A"
        CC1["Claude Code"]
    end

    subgraph "团队成员 B"
        CC2["Claude Code"]
    end

    subgraph "团队成员 C"
        CC3["Claude Code"]
    end

    subgraph "共享基础设施"
        NGINX["Nginx<br/>TLS终止"]
        GW["Docker MCP Gateway<br/>:8811"]
        PROM["Prometheus<br/>:9090"]

        GH["GitHub MCP"]
        PG["Postgres MCP"]
        FS["Filesystem MCP"]
        BS["Brave Search MCP"]
    end

    CC1 -->|HTTPS| NGINX
    CC2 -->|HTTPS| NGINX
    CC3 -->|HTTPS| NGINX
    NGINX -->|HTTP| GW

    GW --> GH
    GW --> PG
    GW --> FS
    GW --> BS

    GW -.->|metrics| PROM

    style NGINX fill:#009639,color:#fff
    style GW fill:#1a1a2e,color:#fff
    style PROM fill:#e6522c,color:#fff

八、Gateway排障实战

8.1 五大常见故障与修复

故障1:MCP server disconnected

# 查看Gateway日志
docker mcp gateway logs

# 常见原因:后端Server崩溃
# 检查各后端容器状态
docker ps --filter "name=mcp"

# 重启单个后端
docker restart mcp-gateway-github-mcp-1

# 重启整个Gateway
docker mcp gateway restart

故障2:工具列表为空

# 检查Gateway是否成功连接后端
docker mcp tools list --verbose

# 如果后端需要环境变量但未传入
# 检查.env文件
cat .env | grep -v '^#' | grep -v '^$'

# 重新加载catalog
docker mcp gateway reload --catalog catalog.yaml

故障3:工具调用超时

# 查看Gateway超时配置
docker mcp gateway config show | grep timeout

# 在catalog.yaml中增加超时
# 某些数据库查询可能需要更长时间
mcpServers:
  postgres:
    timeout: 120s  # 从默认30s增加到120s

故障4:认证失败(401/403)

# 验证Gateway Token
curl -H "Authorization: Bearer $MCP_GATEWAY_TOKEN" \
  http://localhost:8811/health

# 检查Claude Code配置
claude mcp get team-gateway
# 确认header中的token与Gateway端配置一致

故障5:Tool Search不生效

Tool Search要求MCP Server支持tools/search方法或completions能力。如果Gateway后端的某些Server不支持,Tool Search可能对它们降级为全量加载。

# 检查哪些Server支持Tool Search
claude mcp list --verbose
# 输出中会显示每个Server的tool search状态

8.2 调试模式

临时启用详细日志以定位问题:

# Docker MCP Gateway
docker mcp gateway start --catalog catalog.yaml --log-level debug

# mcp-routing-gateway
DEBUG=mcp:* npm start -- --config config/routes.json

8.3 监控指标

生产环境建议监控以下指标:

指标 说明 告警阈值
mcp_request_duration_seconds 请求延迟P99 > 5s
mcp_backend_errors_total 后端错误率 > 1%/min
mcp_active_sessions 活跃会话数 接近上限
mcp_tools_registered 已注册工具数 突然变为0
mcp_gateway_health Gateway健康状态 非1

九、三大方案对比与选型

graph LR
    START["选择Gateway方案"] --> Q1{"部署环境?"}

    Q1 -->|"单机/开发"| Q2{"需要容器化?"}
    Q1 -->|"Kubernetes"| MS["Microsoft MCP<br/>Gateway"]
    Q1 -->|"需要API网关能力"| EN["Envoy AI Gateway"]

    Q2 -->|"是"| DK["Docker MCP<br/>Gateway"]
    Q2 -->|"否"| Q3{"工具数量?"}

    Q3 -->|"< 20"| MR["mcp-routing-<br/>gateway"]
    Q3 -->|"> 20"| DK

    style START fill:#533483,color:#fff
    style MS fill:#0078d4,color:#fff
    style EN fill:#e6522c,color:#fff
    style DK fill:#2496ed,color:#fff
    style MR fill:#339af0,color:#fff
维度 Docker MCP Gateway Microsoft MCP Gateway mcp-routing-gateway Envoy AI Gateway
部署复杂度 低(docker compose up) 高(K8s + Helm) 低(npm start) 中(Envoy + 配置)
适用规模 1-20人团队 企业级 个人/小团队 企业级
会话亲和 基础支持 K8s原生支持 无 一致性哈希
认证集成 Bearer Token K8s RBAC + OAuth 无 Envoy Filter
监控 基础日志 Prometheus 基础日志 Envoy Admin + Prometheus
热更新 gateway reload CRD滚动更新 JSON热加载 xDS动态配置
维护方 Docker Inc. Microsoft 社区 Envoy社区

选型建议: - 个人开发者/小团队:先用mcp-routing-gateway快速验证,有容器化需求后迁移到Docker MCP Gateway - 中型团队(5-20人):Docker MCP Gateway + Nginx TLS终止 + Prometheus监控 - 大型组织(20+人):Microsoft MCP Gateway on Kubernetes + Envoy AI Gateway作为前端API网关

十、高级模式:Gateway组合编排

在复杂场景中,多个Gateway可以组合使用。例如:

10.1 分层Gateway架构

Claude Code
    ↓
Envoy AI Gateway(API管理、限流、TLS终止)
    ↓
Docker MCP Gateway(工具聚合、路由)
    ↓
各个MCP Server

Envoy AI Gateway作为最前端,处理所有API管理职责(限流、认证、审计日志),然后将请求转发给Docker MCP Gateway做工具路由。这种分层架构让每一层职责清晰。

10.2 多区域Gateway联邦

在跨国团队中,可以在每个区域部署一个Gateway,通过中央Gateway联邦实现跨区域工具访问:

# 区域Gateway配置(us-west-2)
mcpServers:
  local-postgres:
    url: http://postgres-mcp.us-west-2.internal:3000/sse
  local-filesystem:
    url: http://fs-mcp.us-west-2.internal:3000/sse

  # 通过联邦访问其他区域的工具
  eu-github:
    type: federated
    gateway: https://mcp-gateway.eu-central-1.company.com/sse
    route: github

十一、Gateway配置最佳实践

11.1 配置作用域策略

Claude Code支持三种MCP配置作用域:

作用域 命令参数 存储位置 适用场景
local --scope local(默认) ~/.claude.json(项目路径下) 个人实验
project --scope project .mcp.json(项目根目录) 团队共享
user --scope user ~/.claude.json(全局) 个人所有项目通用

团队使用Gateway时的推荐策略:

# Gateway地址 → user scope(所有项目共用一个Gateway)
claude mcp add-http team-gateway https://mcp.company.com/sse \
  --scope user --enable-tool-search

# 项目特定Server → project scope(提交到Git)
# .mcp.json
{
  "mcpServers": {
    "local-storybook": {
      "type": "http",
      "url": "http://localhost:6006/sse"
    }
  }
}

11.2 环境变量安全

永远不要在catalog.yaml或.mcp.json中硬编码API密钥。使用环境变量引用:

# 正确做法
mcpServers:
  github:
    env:
      GITHUB_PERSONAL_ACCESS_TOKEN: "${GITHUB_TOKEN}"  # 从.env读取

# 错误做法
mcpServers:
  github:
    env:
      GITHUB_PERSONAL_ACCESS_TOKEN: "ghp_abc123def456"  # 绝对禁止

.mcp.json中同样遵循:

{
  "mcpServers": {
    "team-gateway": {
      "type": "http",
      "url": "https://mcp.company.com/sse",
      "headers": {
        "Authorization": "Bearer ${GATEWAY_TOKEN}"
      }
    }
  }
}

确保.env文件在.gitignore中:

echo ".env" >> .gitignore

11.3 优雅关闭

Gateway关闭时应等待进行中的工具调用完成,而非立即断开连接:

# Docker MCP Gateway支持优雅关闭
docker mcp gateway stop --grace-period 30s

# Kubernetes环境中,设置terminationGracePeriodSeconds
# 在Deployment中:
spec:
  terminationGracePeriodSeconds: 60

十二、从零到生产的迁移路径

graph TD
    P1["Phase 1: 评估<br/>清点当前MCP Server数量<br/>测量上下文占用"]
    --> P2["Phase 2: 选型<br/>根据团队规模和基础设施<br/>选择Gateway方案"]

    P2 --> P3["Phase 3: 开发环境<br/>部署Gateway<br/>迁移1-2个Server验证"]

    P3 --> P4["Phase 4: 全量迁移<br/>所有Server迁移到Gateway<br/>启用Tool Search"]

    P4 --> P5["Phase 5: 生产加固<br/>添加认证/限流/监控<br/>编写运维手册"]

    P5 --> P6["Phase 6: 持续优化<br/>根据监控数据调优<br/>评估多区域部署"]

    style P1 fill:#2d3436,color:#fff
    style P3 fill:#00b894,color:#fff
    style P5 fill:#e17055,color:#fff

Phase 1关键命令:

# 查看当前所有MCP Server
claude mcp list

# 统计工具总数
claude mcp list --json | jq '[.[].tools | length] | add'
# 如果输出 > 30,强烈建议引入Gateway

Phase 3验证清单: - [ ] Gateway可以成功启动并连接所有后端 - [ ] Claude Code通过Gateway调用工具延迟 < 200ms - [ ] 工具列表与直连模式一致 - [ ] 日志中无异常报错 - [ ] Tool Search正常工作(如已启用)

Phase 5加固清单: - [ ] TLS加密(HTTPS连接) - [ ] 认证(Bearer Token或OAuth) - [ ] 速率限制(防止工具调用风暴) - [ ] 健康检查(自动摘除故障后端) - [ ] Prometheus监控(延迟、错误率、会话数) - [ ] 日志聚合(ELK或Loki) - [ ] 备份恢复方案(catalog.yaml版本控制)

延伸阅读

训练营适用性评估

评估维度 说明
适合训练营类型 中高级AI工程训练营、DevOps训练营、企业AI平台培训
前置基础 Claude Code基础使用、Docker基础、MCP协议概念
预计教学时长 4-6小时(含动手实验)
实验环境要求 Docker Desktop、3个以上MCP Server、可选K8s集群
难度评级 中高级(3/5星)

参考来源

  1. Docker MCP Gateway官方文档 — Docker MCP Gateway配置、catalog.yaml格式与部署指南
  2. Microsoft MCP Gateway — Kubernetes原生MCP反向代理,支持会话亲和和CRD路由声明
  3. Envoy AI Gateway MCP支持 — Envoy企业级API网关的MCP协议集成方案
  4. Claude Code MCP Tool Search详解 — Tool Search延迟加载机制,上下文占用降低95%
  5. globalpocket/mcp-routing-gateway — 轻量级JSON配置路由网关,纯JSON路由规则

[!tip] 51学通信知识星球 星主:爱卫生(微信:gprshome201101)——公众号「51学通信」创办者,19 年通信行业运维与讲师经验,著有《GPRS网络信令实例详解》《EPC原理与实践》《5G核心网原理与实践》三本纸质书(各大电商平台有售)。 星球定位:深耕 5G 核心网、IMS、NFV/AI、云原生等 ICT 领域,主打运维岗位与信令分析。 当前规模:5200 篇主题 / 990 个回答,198 元/年。 加入福利:加入星球后请加爱卫生微信,拉您进知识星球年度陪伴与答疑群——不限量回复您的各种问题,另有群内分享。 AI 加持:51学通信知识星球已作为 skill 接入 WorkBuddy,使用 deepseek-4-flash 在海量星球帖子中精准找贴、找视频、找 FAQ 和案例,做总结、找文档和 PPT 等场景全覆盖。

51学通信知识星球海报-扫码加入