You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Docker的动态可扩展MCP Server基础设施构建及跨容器工具注册方案问询

基于Docker的动态可扩展MCP Server基础设施构建及跨容器工具注册方案问询

看起来你已经理清了整体架构方向——用Docker/K8s拆分MCP Server和工具实现动态扩展,同时用Git Actions做CI/CD,这个思路非常棒!核心痛点其实是从进程内本地注册到跨容器远程注册的模式转变,我来给你拆解具体的实现方案:

1. 重构MCP Server:新增远程工具注册API

原来的@mcp.tool()是进程内直接绑定Server实例,现在要把注册逻辑改成HTTP API驱动,让工具容器能主动向Server注册自己的元信息。

修改mcp_server.py,添加注册接口

from fastapi import FastAPI
from fastmcp import FastMCP

# 初始化FastAPI和FastMCP
app = FastAPI(title="MCP Server", version="1.0.0")
mcp = FastMCP(name="MCP Server", version="1.0.0")

# 存储已注册工具的元信息(生产环境建议用Redis等持久化存储)
registered_tools = {}

# 工具注册接口
@app.post("/api/tools/register")
async def register_tool(tool_info: dict):
    # 校验工具信息(比如必填的名称、描述、调用地址、参数 schema)
    required_fields = ["name", "description", "invoke_url", "input_schema", "output_schema"]
    if not all(field in tool_info for field in required_fields):
        return {"status": "failed", "message": "Missing required fields"}
    
    registered_tools[tool_info["name"]] = tool_info
    print(f"Registered tool: {tool_info['name']}")
    return {"status": "success"}

# 处理工具调用的转发逻辑(当Server收到工具调用请求时,转发到对应的工具容器)
@app.post("/api/tools/invoke/{tool_name}")
async def invoke_tool(tool_name: str, params: dict):
    if tool_name not in registered_tools:
        return {"status": "failed", "message": "Tool not found"}
    
    tool = registered_tools[tool_name]
    # 转发请求到工具容器的调用接口
    import httpx
    async with httpx.AsyncClient() as client:
        response = await client.post(tool["invoke_url"], json=params)
        return response.json()

# 保留原FastMCP的核心逻辑(如果需要兼容旧的本地工具)

2. 改造工具容器:独立服务+启动时自动注册

每个工具不再依赖Server的mcp实例,而是做成独立的HTTP服务,启动时主动向MCP Server发送注册请求。

改造add.py为独立服务

from fastapi import FastAPI
import httpx
import asyncio

app = FastAPI(title="Add Tool", version="1.0.0")

# 工具核心逻辑
@app.post("/api/run")
async def add(a: int, b: int) -> int:
    """Add two numbers"""
    return a + b

# 健康检查接口(供Server做心跳检测)
@app.get("/health")
async def health_check():
    return {"status": "healthy"}

# 启动时向MCP Server注册
async def register_with_server():
    # 通过Docker/K8s的服务名访问Server(避免硬写IP)
    server_url = "http://mcp-server:8000" 
    tool_info = {
        "name": "add",
        "description": "Add two numbers",
        "invoke_url": "http://add-tool:8000/api/run",  # 工具自身的访问地址
        "input_schema": {"a": "int", "b": "int"},
        "output_schema": "int"
    }
    try:
        async with httpx.AsyncClient() as client:
            response = await client.post(f"{server_url}/api/tools/register", json=tool_info)
            if response.status_code == 200:
                print("Add tool registered successfully!")
            else:
                print(f"Registration failed: {response.text}")
    except Exception as e:
        print(f"Failed to connect to MCP Server: {str(e)}")

# FastAPI启动钩子,触发注册
@app.on_event("startup")
async def startup_event():
    await register_with_server()

3. Docker网络与编排配置

确保Server和工具容器在同一个自定义网络内,这样可以通过服务名互相访问(不用依赖动态IP)。

示例docker-compose.yml

version: '3.8'
networks:
  mcp-network:
    driver: bridge

services:
  mcp-server:
    build: ./mcp-server
    ports:
      - "8000:8000"
    networks:
      - mcp-network
    restart: always

  add-tool:
    build: ./tools/add
    networks:
      - mcp-network
    depends_on:
      - mcp-server
    restart: always

4. K8s扩展与Git Actions CI/CD

K8s部署要点

  • 为MCP Server和每个工具创建单独的Deployment和Service(ClusterIP类型,供集群内部访问)
  • 工具容器的环境变量中配置MCP Server的Service地址(比如MCP_SERVER_URL=http://mcp-server-service.default.svc.cluster.local)
  • 可以用HPA(水平Pod自动扩缩容)根据工具的负载自动调整实例数

Git Actions示例(工具镜像构建与部署)

name: Build & Deploy MCP Tool
on:
  push:
    branches: [mcp_tool_branch]

jobs:
  build-deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - name: Build Docker Image
        run: docker build -t your-registry/add-tool:${{ github.sha }} .
      
      - name: Push to Registry
        run: |
          echo "${{ secrets.DOCKER_PASSWORD }}" | docker login your-registry -u "${{ secrets.DOCKER_USERNAME }}" --password-stdin
          docker push your-registry/add-tool:${{ github.sha }}
      
      - name: Update K8s Deployment
        run: |
          kubectl config set-context --current --namespace=mcp
          kubectl set image deployment/add-tool add-tool=your-registry/add-tool:${{ github.sha }}

5. 容错与稳定性优化

  • 心跳检测:MCP Server定期调用工具的/health接口,移除长时间无响应的工具
  • 重新注册:工具容器重启后自动触发注册逻辑,确保Server能及时感知
  • 注册信息持久化:生产环境把registered_tools存储到Redis或数据库,避免Server重启后丢失注册信息

这样改造后,每个工具都是独立的可扩展单元,和MCP Server完全解耦,完美适配Docker/K8s的微服务架构,也能通过Git Actions实现自动化部署。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 10:08:02