[智能体-52]:MCP代码示例
一套完整、可运行、带超详细注释的MCP 代码示例,包含:
- MCP Server(服务端)
- MCP Client(客户端)
- 基于JSON-RPC 2.0
- 实现最核心功能:tools/list、tools/call
- 全部中文注释
完全贴合你说的:MCP = 结构化 Web 服务 + 大模型可识别接口
一、MCP Server 代码(Python)
功能:提供一个查询天气的 MCP 标准工具
python
运行
# -*- coding: utf-8 -*- """ MCP Server 示例 作用:对外提供标准化的 MCP 工具(Tools) 遵循:JSON-RPC 2.0 + MCP 应用层协议 """ import json from flask import Flask, request, jsonify app = Flask(__name__) # ====================== 1. MCP 服务端能力定义(核心) ====================== # MCP 标准:必须暴露支持哪些工具,大模型/Agent 会先读取这个列表 MCP_SERVER_CAPABILITIES = { "tools": [ { "name": "get_weather", # 工具名(标准英文) "description": "查询城市天气", # 描述:大模型能看懂这个工具干嘛 "inputSchema": { # 入参结构:大模型自动生成参数 "type": "object", "properties": { "city": { "type": "string", "description": "要查询的城市名称" } }, "required": ["city"] # 必填参数 } } ] } # ====================== 2. 工具实现(业务逻辑) ====================== def get_weather(city: str) -> dict: """实际的工具功能:查询天气""" return { "city": city, "temperature": "25℃", "weather": "晴天", "wind": "微风" } # ====================== 3. MCP 标准路由(JSON-RPC 2.0) ====================== @app.route("/mcp", methods=["POST"]) def mcp_server(): """ MCP 统一入口 所有 MCP Client 都请求这里 遵循 JSON-RPC 2.0 规范 """ # 1. 获取客户端发来的 JSON-RPC 请求 req_data = request.get_json() # 2. 解析 JSON-RPC 基础字段(必须:jsonrpc, id, method) jsonrpc = req_data.get("jsonrpc") req_id = req_data.get("id") method = req_data.get("method") params = req_data.get("params", {}) # ------------------------------ # MCP 标准方法 1:获取工具列表 # ------------------------------ if method == "tools/list": return jsonify({ "jsonrpc": "2.0", "id": req_id, "result": MCP_SERVER_CAPABILITIES }) # ------------------------------ # MCP 标准方法 2:调用工具(核心) # ------------------------------ elif method == "tools/call": tool_name = params.get("name") arguments = params.get("arguments", {}) # 调用我们实现的工具 if tool_name == "get_weather": result = get_weather(**arguments) return jsonify({ "jsonrpc": "2.0", "id": req_id, "result": { "content": [ {"type": "text", "text": json.dumps(result, ensure_ascii=False)} ] } }) # ------------------------------ # 方法不存在(JSON-RPC 标准错误) # ------------------------------ return jsonify({ "jsonrpc": "2.0", "id": req_id, "error": { "code": -32601, "message": f"Method {method} not found" } }) if __name__ == "__main__": print("✅ MCP Server 启动成功:http://127.0.0.1:5000/mcp") app.run(port=5000, debug=True)二、MCP Client 代码(Python)
功能:调用 MCP Server,模拟 AI Agent 调用外部工具
python
运行
# -*- coding: utf-8 -*- """ MCP Client 示例 作用:模拟 AI Agent / 大模型 调用 MCP 服务 遵循 JSON-RPC 2.0 + MCP 协议 """ import json import requests # MCP Server 地址 MCP_SERVER_URL = "http://127.0.0.1:5000/mcp" def rpc_request(method, params=None, req_id=1): """ 封装 JSON-RPC 2.0 请求 :param method: MCP 方法名(tools/list, tools/call) :param params: 参数 :param req_id: 请求ID(用于匹配请求响应) """ return { "jsonrpc": "2.0", # JSON-RPC 版本固定 "id": req_id, # 唯一ID "method": method, # MCP 标准方法 "params": params or {} } # ====================== 1. 第一步:获取 MCP 工具列表 ====================== print("=" * 50) print("📌 步骤1:Client 获取 Server 工具列表") resp = requests.post(MCP_SERVER_URL, json=rpc_request("tools/list")) tools_data = resp.json() print("工具列表:", json.dumps(tools_data, ensure_ascii=False, indent=2)) # ====================== 2. 第二步:调用 MCP 工具(查询天气) ====================== print("\n" + "=" * 50) print("📌 步骤2:Client 调用 MCP 工具:get_weather") call_params = { "name": "get_weather", "arguments": {"city": "北京"} } resp = requests.post(MCP_SERVER_URL, json=rpc_request("tools/call", call_params)) result = resp.json() print("调用结果:", json.dumps(result, ensure_ascii=False, indent=2))三、运行结果(一看就懂 MCP 机制)
1. 获取工具列表(Agent / 模型先读这个)
json
{ "jsonrpc": "2.0", "id": 1, "result": { "tools": [ { "name": "get_weather", "description": "查询城市天气", "inputSchema": { "type": "object", "properties": { "city": { "type": "string", "description": "要查询的城市名称" } }, "required": ["city"] } } ] } }2. 调用工具返回
json
{ "jsonrpc": "2.0", "id": 1, "result": { "content": [ { "type": "text", "text": "{\"city\":\"北京\",\"temperature\":\"25℃\",\"weather\":\"晴天\",\"wind\":\"微风\"}" } ] } }四、这段代码告诉你 MCP 的本质
- MCP Server = 标准化 Web 服务
- 接口 = JSON-RPC 2.0
- 内容 =大模型能看懂的结构化工具
- 工具名
- 描述
- 入参格式
- 调用 = 统一格式 tools/call
完全符合你说的:MCP 是一个结构化、标准化、可被大模型识别的 Web 服务接口。
