From d7f3b3caf52e16b08e33d19bbc254761b888d863 Mon Sep 17 00:00:00 2001 From: myifeng Date: Wed, 28 May 2025 18:32:15 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8E=A5=E6=94=B6=E5=B9=B6=E6=89=93=E5=8D=B0MC?= =?UTF-8?q?P=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../xiaozhi-server/core/handle/helloHandle.py | 21 ++++++++++++++++ main/xiaozhi-server/core/handle/textHandle.py | 25 +++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/main/xiaozhi-server/core/handle/helloHandle.py b/main/xiaozhi-server/core/handle/helloHandle.py index 5dfc6b62..ac97c566 100644 --- a/main/xiaozhi-server/core/handle/helloHandle.py +++ b/main/xiaozhi-server/core/handle/helloHandle.py @@ -35,6 +35,27 @@ async def handleHelloMessage(conn, msg_json): if features: conn.logger.bind(tag=TAG).info(f"客户端特性: {features}") conn.features = features + if features.get("mcp"): + conn.logger.bind(tag=TAG).info("客户端支持MCP") + # 发送初始化 + await conn.websocket.send(json.dumps({ + "type": "mcp", + "payload": { + "jsonrpc": "2.0", + "method": "notifications/initialized" + } + })) + # 发送mcp消息,获取tools列表 + await conn.websocket.send(json.dumps( { + "type": "mcp", + "payload": { + "jsonrpc": "2.0", + "method": "tools/list", + "id": 10001, + "params": { + } + } + })) await conn.websocket.send(json.dumps(conn.welcome_msg)) diff --git a/main/xiaozhi-server/core/handle/textHandle.py b/main/xiaozhi-server/core/handle/textHandle.py index 33596b50..06964105 100644 --- a/main/xiaozhi-server/core/handle/textHandle.py +++ b/main/xiaozhi-server/core/handle/textHandle.py @@ -74,6 +74,31 @@ async def handleTextMessage(conn, message): asyncio.create_task(handleIotStatus(conn, msg_json["states"])) elif msg_json["type"] == "mcp": conn.logger.bind(tag=TAG).info(f"收到mcp消息:{message}") + if "payload" in msg_json: + payload = msg_json["payload"] + id = payload.get("id", None) + if id is None: + conn.logger.bind(tag=TAG).error("MCP消息缺少ID") + return + # result: 包含工具列表和上下文 + # TODO: 处理MCP消息时,进行不同的处理 + if "jsonrpc" not in payload or payload["jsonrpc"] != "2.0": + conn.logger.bind(tag=TAG).error("MCP消息缺少jsonrpc版本") + return + if "result" in payload: + result = payload["result"] + if "tools" in result: + # 初始化处理工具列表 + tools = result["tools"] + conn.features["mcp"] = True + # 设置工具列表到连接对象,方便后续使用 + conn.features["mcp_tools"] = tools + conn.logger.bind(tag=TAG).info(f"收到MCP工具列表:{tools}") + elif "context" in result: + # 处理上下文,上下文根据id进行管理,上报的id对应Server下发时的id + context = result["context"] + conn.logger.bind(tag=TAG).info(f"收到MCP上下文:{context}, ID: {id}") + elif msg_json["type"] == "server": # 记录日志时过滤敏感信息 conn.logger.bind(tag=TAG).info(