MCP生产部署实战:从开发到上线的完整指南

1. 客户端配置详解

1.1 mcp.json 标准格式

json 复制代码
{
  "version": "1.0",
  "mcpServers": {
    "my_ai_tools": {
      "command": "python",
      "args": ["/path/to/server.py"],
      "env": {
        "OPENAI_API_KEY": "sk-xxx",
        "DB_URL": "mysql://user:pass@localhost/db"
      },
      "description": "AI工具集(数据库/天气API)"
    }
  }
}

关键字段说明:

  • command:启动命令(如python、uvicorn等)
  • args:命令行参数(支持相对路径)
  • env:环境变量(敏感信息建议通过外部注入)
  • description:客户端展示的服务描述

1.2 配置位置

  • 全局配置 :~/.config/mcp/config.json
  • 项目级配置 :./.mcp/mcp.json
  • IDE特定配置 :如Cursor会在工作区查找.vscode/mcp.json

1.3 环境变量管理

bash 复制代码
# 推荐使用.env文件(需配合python-dotenv)
echo "DB_PASSWORD=123456" > .env

然后在代码中加载:

python 复制代码
from dotenv import load_dotenv
load_dotenv()

2. 部署模式对比

2.1 STDIO模式(开发环境首选)

json 复制代码
{
  "command": "python",
  "args": ["server.py"]
}
  • 优点 :
    • 零延迟通信
    • 调试方便(日志直接输出)
  • 限制 :
    • 必须与客户端同机部署
    • 无跨进程隔离

2.2 SSE模式(生产环境必选)

json 复制代码
{
  "command": "uvicorn",
  "args": ["server:app", "--port", "8000"]
}

需要FastAPI封装:

python 复制代码
# server.py
from fastapi import FastAPI
from fastmcp import FastMCP

app = FastAPI()
mcp = FastMCP("ProductionTools")

@app.post("/mcp")
async def handle_mcp():
    return await mcp.handle_request()

# 注册工具...

3. 生产环境部署实战

3.1 使用Gunicorn+Uvicorn

bash 复制代码
gunicorn -w 4 -k uvicorn.workers.UvicornWorker server:app

对应mcp.json:

json 复制代码
{
  "command": "curl",
  "args": ["http://localhost:8000/mcp"]
}

3.2 容器化部署(Docker)

dockerfile 复制代码
FROM python:3.10
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
CMD ["gunicorn", "-w", "4", "-k", "uvicorn.workers.UvicornWorker", "server:app"]

3.3 健康检查配置

python 复制代码
@app.get("/health")
def health_check():
    return {"status": "ok"}

4. 安全加固方案

4.1 认证鉴权

python 复制代码
from fastapi.security import HTTPBearer
security = HTTPBearer()

@app.post("/mcp")
async def handle_mcp(token: str = Depends(security)):
    if token != os.getenv("API_TOKEN"):
        raise HTTPException(status_code=403)
    return await mcp.handle_request()

4.2 限流保护

python 复制代码
from fastapi.middleware import Middleware
from slowapi import Limiter
from slowapi.util import get_remote_address

limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter

@app.post("/mcp")
@limiter.limit("10/minute")
async def handle_mcp():
    return await mcp.handle_request()

5. 监控与日志

5.1 Prometheus监控

python 复制代码
from prometheus_fastapi_instrumentator import Instrumentator
Instrumentator().instrument(app).expose(app)

5.2 结构化日志

python 复制代码
import logging
import json_logging

json_logging.init_fastapi(enable_json=True)
logger = logging.getLogger("mcp-server")

附录:部署检查清单

  1. 测试STDIO和SSE两种模式
  2. 配置环境变量加密方案
  3. 设置健康检查端点
  4. 实现基础认证鉴权
  5. 配置日志和监控系统
  6. 压力测试(推荐使用locust)
相关推荐
ZhengEnCi1 小时前
vLLM是什么:PagedAttention 让大模型推理快 2-4 倍,还能撑起更长思维链
人工智能·性能优化·llm
DigitalOcean6 小时前
WorkBuddy 接入自定义模型教程:配置 GPT、Claude 等大模型
llm·agent
用户8813034824078 小时前
给 MCP Server 加调用链日志和大输出落盘:一个装饰器搞定,附 3 个实测踩坑(Python SDK v2)
mcp
iiiiii118 小时前
大模型批量生成中的左填充 (left padding)与右填充 (right padding):从生成正确性到 GRPO 的混合策略
人工智能·机器学习·语言模型·大模型·llm·attention·注意力
TickDB9 小时前
美股历史数据下载:用 Codex 取数,Python 导出 CSV
python·websocket·mcp·行情数据 api
Eloudy10 小时前
从 huggingFace 下载大模型命令备忘
llm·gpu·rdma
lucas_AI10 小时前
不用一行恶意代码,就能教坏你的 AI Agent:SkillPoison 只用了 15 条『成功经验』
llm
lucas_AI10 小时前
把图转成文字再答题,为什么反而错得更狠?图森破了:答案就吊在那一条边上
llm
lucas_AI11 小时前
DeepMind 发布 Genie 4:世界模型会「出声」了,一句话实时改写世界
人工智能·llm
lucas_AI12 小时前
为什么大模型总敢一本正经地胡说?研究者关掉了它脑内的 8 个「自信开关」
人工智能·llm