MCP在网络协议上和http是什么关系? 为什么MCP服务器的服务可以使用Nginx代理?

MCP 与 HTTP 的关系及 Nginx 代理原理

MCP 与 HTTP 的关系

MCP(Model Context Protocol)在网络协议上与 HTTP 既有区别又有联系:

1. 协议层级关系

MCP 不是替代 HTTP 的协议,而是在其之上构建的专门协议:

text

应用层: MCP协议 ← 这是专门为AI交互设计的协议
传输层: WebSocket/SSE/HTTP ← 这些是MCP可以使用的传输机制
网络层: TCP/IP

2. MCP 可以使用多种传输机制

MCP 设计为协议无关,可以通过多种方式传输:

  • WebSocket (最常用)

  • Server-Sent Events (SSE)

  • 标准输入/输出 (本地开发)

  • 自定义传输层

3. 与 HTTP 的关系

  • MCP 消息通常通过 HTTP 升级的 WebSocket 连接传输

  • MCP 可以使用 HTTP 进行初始握手和认证

  • MCP 定义了自己的消息格式和语义,独立于传输层

为什么 MCP 服务器可以使用 Nginx 代理

Nginx 可以代理 MCP 服务的原因在于:

1. WebSocket 代理支持

Nginx 从 1.3.13 版本开始支持 WebSocket 代理,这正是 MCP 常用的传输方式:

nginx

# Nginx WebSocket 代理配置
server {
    listen 443 ssl;
    server_name mcp.example.com;
    
    location /mcp/ {
        proxy_pass http://localhost:8000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_set_header Host $host;
        
        # 保持连接活跃
        proxy_read_timeout 1d;
        proxy_send_timeout 1d;
    }
}

2. HTTP/HTTPS 终止和代理

Nginx 可以作为反向代理处理 SSL 终止、负载均衡和请求路由:

nginx

# 完整的 MCP 代理配置
server {
    listen 80;
    server_name mcp.example.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl;
    server_name mcp.example.com;
    
    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/private.key;
    
    # MCP WebSocket 端点
    location /mcp/ws {
        proxy_pass http://mcp_backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
    
    # MCP SSE 端点 (如果使用Server-Sent Events)
    location /mcp/sse {
        proxy_pass http://mcp_backend;
        proxy_buffering off;
        proxy_cache off;
        proxy_set_header Connection '';
    }
}

upstream mcp_backend {
    server localhost:8000;
    server localhost:8001 backup;
}

3. 协议转换和适配

Nginx 可以处理协议转换,使得 MCP 服务可以通过标准 Web 端口(80/443)访问:

text

客户端 ←[HTTP/WebSocket]→ Nginx ←[原始MCP协议]→ MCP服务器

4. 安全增强

Nginx 为 MCP 服务提供企业级安全功能:

  • SSL/TLS 终止

  • 速率限制

  • 访问控制

  • DDoS 防护

  • 身份验证

MCP 服务器的网络实现示例

下面是一个支持 WebSocket 传输的 MCP 服务器实现:

python

#!/usr/bin/env python3
import asyncio
import json
from mcp.server import Server
from websockets.server import serve

# 创建 MCP 服务器实例
server = Server("math-server")

# 注册加法工具
@server.tool()
async def add(a: float, b: float) -> str:
    """将两个数字相加"""
    result = a + b
    return f"{a} + {b} = {result}"

async def handle_websocket(websocket):
    """处理 WebSocket 连接"""
    # 将 WebSocket 连接转换为 MCP 所需的流接口
    async for message in websocket:
        # 处理 MCP 消息
        response = await server.process_message(json.loads(message))
        if response:
            await websocket.send(json.dumps(response))

async def main():
    # 启动 WebSocket 服务器
    async with serve(handle_websocket, "localhost", 8000):
        print("MCP 服务器运行在 ws://localhost:8000")
        await asyncio.Future()  # 永久运行

if __name__ == "__main__":
    asyncio.run(main())

客户端连接示例

python

#!/usr/bin/env python3
import asyncio
import json
import websockets
from mcp.client import ClientSession

async def main():
    # 通过 WebSocket 连接到 MCP 服务器
    async with websockets.connect("wss://mcp.example.com/mcp/ws") as websocket:
        # 创建读取和写入适配器
        async def read_message():
            return json.loads(await websocket.recv())
            
        async def write_message(message):
            await websocket.send(json.dumps(message))
        
        # 创建 MCP 会话
        session = ClientSession(read_message, write_message)
        
        # 初始化连接
        await session.initialize()
        
        # 列出可用工具
        tools = await session.list_tools()
        print("可用工具:", [t.name for t in tools.tools])
        
        # 调用加法工具
        result = await session.call_tool(
            "add",
            arguments={"a": 5, "b": 3.5}
        )
        
        print("远程加法结果:", result.content[0].text)
        
        await session.close()

if __name__ == "__main__":
    asyncio.run(main())

总结

MCP 与 HTTP 的关系是:

  1. MCP 是应用层协议,可以使用 HTTP/WebSocket 作为传输机制

  2. MCP 不是替代 HTTP,而是在其之上构建的专门协议

  3. MCP 消息可以通过 HTTP 升级的 WebSocket 连接传输

Nginx 可以代理 MCP 服务的原因:

  1. Nginx 支持 WebSocket 代理,这是 MCP 的常用传输方式

  2. Nginx 可以处理协议转换和适配

  3. Nginx 提供安全增强功能,如 SSL 终止和访问控制

  4. Nginx 支持负载均衡和高可用性配置

这种架构使得 MCP 服务能够利用现有的 Web 基础设施,同时保持其专门的协议语义。

MCP 通过 WebSocket 传输的通信流程

Nginx 代理 MCP 服务的配置示例

# Nginx 配置:代理 MCP over WebSocket
server {
    listen 80;
    server_name mcp.example.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl;
    server_name mcp.example.com;
    
    ssl_certificate /etc/ssl/certs/mcp.example.com.crt;
    ssl_certificate_key /etc/ssl/private/mcp.example.com.key;
    
    # MCP WebSocket 端点
    location /mcp/ {
        proxy_pass http://localhost:8000/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        
        # 延长超时时间以适应持久连接
        proxy_read_timeout 1d;
        proxy_send_timeout 1d;
    }
    
    # 健康检查端点
    location /health {
        proxy_pass http://localhost:8000/health;
        proxy_set_header Host $host;
    }
}

MCP 消息格式示例

// MCP 初始化消息
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "initialize",
  "params": {
    "protocolVersion": "2024.11.05",
    "capabilities": {
      "tools": {}
    },
    "clientInfo": {
      "name": "ExampleClient",
      "version": "1.0.0"
    }
  }
}

// MCP 工具调用消息
{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "tools/call",
  "params": {
    "name": "add",
    "arguments": {
      "a": 5,
      "b": 3
    }
  }
}

// MCP 工具响应消息
{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "5 + 3 = 8"
      }
    ]
  }
}

总结

通过上述图表和说明,可以清楚地看到:

  1. 层级关系:MCP 是应用层协议,可以使用多种传输机制(WebSocket、SSE、HTTP)

  2. 依赖关系:MCP over WebSocket 依赖于 HTTP 进行初始握手,然后升级为全双工通信

  3. 代理能力:Nginx 可以代理 MCP 服务是因为它能处理 WebSocket 升级请求和持久连接

  4. 协议特点:MCP 专为 AI 交互设计,而 HTTP/WebSocket 是更通用的通信协议

这种设计使得 MCP 能够利用现有的 Web 基础设施,同时提供专门为 AI 助手优化的交互模式。

Logo

更多推荐