MCP 应用程序流程
以下是从接收 HTTP 请求到运行 MCP 方法的详细应用程序流程:
1. 请求输入 (main.py)
HTTP Request → FastAPI Application → /mcp Endpoint- HTTP请求到达终端
/mcp - FastAPI 引导到函数
handle_mcp_request在main.py
# main.py
@app.post("/mcp")
async def handle_mcp_request(request: MCPRequest):
"""Endpoint principale MCP over HTTP"""
return await MCPRoutes.handle_mcp_request(request.dict())2. 路由管理 (mcp_routes.py)
MCPRoutes.handle_mcp_request() → Gestione Metodo → Chiamata a MCPMethods- 请求已转发至
MCPRoutes.handle_mcp_request() - 从请求中提取方法(例如:“tools/call”)
- 根据方法,调用相应的函数
MCPMethods
# routes/mcp_routes.py
if method == "tools/call":
params = request_data.get("params", {})
response = MCPMethods.handle_tools_call(msg_id, params)3. 运行工具 (mcp_methods.py)
MCPMethods.handle_tools_call() → Esecuzione Tool Specifico → Rispostahandle_tools_call接收参数并确定要运行哪个工具- 调用特定的工具函数(例如:
_format_text)
# modules/mcp_methods.py
@staticmethod
def handle_tools_call(msg_id: int, params: Dict[str, Any]) -> Dict[str, Any]:
tool_name = params.get("name")
arguments = params.get("arguments", {})
# Esegue il tool specifico
result = MCPMethods.execute_tool(tool_name, arguments)
# Costruisce la risposta JSON-RPC
return {
"jsonrpc": "2.0",
"id": msg_id,
"result": result
}
@staticmethod
def execute_tool(tool_name: str, arguments: Dict[str, Any]) -> str:
if tool_name == "format_text":
return MCPMethods._format_text(arguments)
# ... altri tools ...4. 运行特定工具(例如:format_text)
@staticmethod
def _format_text(arguments: Dict[str, Any]) -> str:
text = arguments.get("text", "")
style = arguments.get("style", "uppercase")
styles = {
"uppercase": text.upper(),
"lowercase": text.lower(),
"title": text.title(),
"capitalize": text.capitalize()
}
if style in styles:
return f"Formatted text ({style}): {styles[style]}"
else:
return f"Error: Unknown style '{style}'. Available: {list(styles.keys())}"5. 回复
流量通过层次返回:
- 该工具将结果返回到
execute_tool execute_tool返回到handle_tools_callhandle_tools_call将结果打包为 JSON-RPC 格式- 回复将返回给客户端
6. 错误管理
每个级别都会处理自己的错误:
- FastAPI 处理验证错误
- MCPRoutes 处理不支持的方法
- MCPMethods 处理特定工具错误
流程图
sequenceDiagram
participant Client
participant FastAPI
participant MCPRoutes
participant MCPMethods
Client->>+FastAPI: POST /mcp
FastAPI->>+MCPRoutes: handle_mcp_request()
alt Metodo supportato
MCPRoutes->>+MCPMethods: handle_tools_call()
MCPMethods->>MCPMethods: execute_tool()
MCPMethods->>MCPMethods: _format_text() o altro tool
MCPMethods-->>MCPRoutes: Risultato
else Metodo non supportato
MCPRoutes-->>-FastAPI: Errore 400
end
MCPRoutes-->>-FastAPI: Risposta JSON-RPC
FastAPI-->>-Client: HTTP 200 + Risposta______________________________________________________________________
这种流程确保了明确的责任分离,并使应用程序易于维护和使用新工具进行扩展。
