From 45b2e52d0dd0042634a99ab09e3cfe1e8f72f3b8 Mon Sep 17 00:00:00 2001 From: 1-6 Date: Sat, 17 Oct 2026 20:06:19 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=9C=AC=E6=9C=BA=E8=AE=BE=E5=A4=87?= =?UTF-8?q?=E5=B7=A5=E5=85=B7=E6=8E=A5=E5=8F=A3=EF=BC=88=E9=BB=98=E8=AE=A4?= =?UTF-8?q?=E5=85=B3=E9=97=AD=EF=BC=89=EF=BC=8C=E8=AE=A9=E5=90=8C=E6=9C=BA?= =?UTF-8?q?=E5=A4=96=E9=83=A8=E7=A8=8B=E5=BA=8F=E5=88=97=E5=87=BA=E5=B9=B6?= =?UTF-8?q?=E8=B0=83=E7=94=A8=E5=B7=B2=E8=BF=9E=E6=8E=A5=E8=AE=BE=E5=A4=87?= =?UTF-8?q?=E7=9A=84=20MCP=20=E5=B7=A5=E5=85=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 core/api/device_tool_handler.py:GET /xiaozhi/device/tools、POST /xiaozhi/device/call - 只接受 127.0.0.1/::1 请求;配置 server.device_tool_api 默认 false - websocket_server 登记/注销在线连接,供接口查找设备 Co-Authored-By: Claude Opus 5.5 --- main/xiaozhi-server/config.yaml | 3 + .../core/api/device_tool_handler.py | 111 ++++++++++++++++++ main/xiaozhi-server/core/http_server.py | 11 ++ main/xiaozhi-server/core/websocket_server.py | 3 + 4 files changed, 128 insertions(+) create mode 100644 main/xiaozhi-server/core/api/device_tool_handler.py diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml index 17329459a..9e6f186fe 100644 --- a/main/xiaozhi-server/config.yaml +++ b/main/xiaozhi-server/config.yaml @@ -27,6 +27,9 @@ server: vision_explain: http://你的ip或者域名:端口号/mcp/vision/explain # OTA返回信息时区偏移量 timezone_offset: +8 + # 本机设备工具接口:允许同一台机器上的外部程序列出并调用已连接设备上报的 MCP 工具 + # 只接受 127.0.0.1 的请求;设备需已建立 WebSocket 会话(唤醒或按键开始对话后) + device_tool_api: false # 认证配置 auth: # 是否启用认证 diff --git a/main/xiaozhi-server/core/api/device_tool_handler.py b/main/xiaozhi-server/core/api/device_tool_handler.py new file mode 100644 index 000000000..a920681ad --- /dev/null +++ b/main/xiaozhi-server/core/api/device_tool_handler.py @@ -0,0 +1,111 @@ +"""本机设备工具接口:让同一台机器上的外部程序(自动化脚本、其他智能体)调用已连接设备上报的 MCP 工具。 + +默认关闭,需在配置里打开 server.device_tool_api: true;只接受来自 127.0.0.1 / ::1 的请求。 + + GET /xiaozhi/device/tools 列出当前已连接的设备、其上报的工具名、工具列表是否就绪 + POST /xiaozhi/device/call {"tool": 工具名, "arguments": {...}, "device_id": 可省(仅一台在线时), "timeout": 秒} + +注意:设备只有在建立 WebSocket 会话后才会出现在列表中(例如唤醒或按键开始对话之后)。 +""" + +import json +import time + +from aiohttp import web + +from config.logger import setup_logging +from core.api.base_handler import BaseHandler + +TAG = __name__ + +# 当前在线的 ConnectionHandler;device_id 在握手后才设置,所以查询时再读取 +_active_connections = set() + + +def register_connection(handler): + _active_connections.add(handler) + + +def unregister_connection(handler): + _active_connections.discard(handler) + + +def _online(): + return { + h.device_id: h + for h in list(_active_connections) + if getattr(h, "device_id", None) + } + + +class DeviceToolHandler(BaseHandler): + def __init__(self, config: dict): + super().__init__(config) + self.logger = setup_logging() + + @staticmethod + def _is_local(request) -> bool: + return request.remote in ("127.0.0.1", "::1") + + def _json(self, data, status=200): + response = web.json_response(data, status=status, dumps=lambda o: json.dumps(o, ensure_ascii=False)) + self._add_cors_headers(response) + return response + + async def handle_list(self, request): + if not self._is_local(request): + return self._json({"error": "only local requests are allowed"}, status=403) + result = [] + for device_id, handler in _online().items(): + client = getattr(handler, "mcp_client", None) + ready = bool(client) and await client.is_ready() + result.append( + { + "device_id": device_id, + "tools": sorted(client.tools) if client else [], + "ready": ready, + } + ) + return self._json(result) + + async def handle_call(self, request): + if not self._is_local(request): + return self._json({"error": "only local requests are allowed"}, status=403) + try: + body = await request.json() + except Exception: + return self._json({"error": "request body must be JSON"}, status=400) + + online = _online() + device_id = body.get("device_id") or (next(iter(online)) if len(online) == 1 else None) + handler = online.get(device_id) + if not handler: + message = "device not connected" if not online else "more than one device online, device_id is required" + return self._json({"error": message, "online": list(online)}, status=404) + + client = getattr(handler, "mcp_client", None) + if not client or not await client.is_ready(): + return self._json({"error": "device tool list is not ready yet"}, status=503) + + from core.providers.tools.device_mcp.mcp_handler import call_mcp_tool + + started = time.time() + try: + result = await call_mcp_tool( + handler, + client, + body.get("tool", ""), + json.dumps(body.get("arguments", {}), ensure_ascii=False), + timeout=int(body.get("timeout", 15)), + ) + except Exception as e: + self.logger.bind(tag=TAG).warning(f"本机设备工具调用失败: {e}") + return self._json({"error": f"{type(e).__name__}: {e}", "device_id": device_id}, status=502) + return self._json( + { + "device_id": device_id, + "tool": body.get("tool"), + "result": result, + "seconds": round(time.time() - started, 2), + } + ) diff --git a/main/xiaozhi-server/core/http_server.py b/main/xiaozhi-server/core/http_server.py index feb96f3b7..d88fae497 100644 --- a/main/xiaozhi-server/core/http_server.py +++ b/main/xiaozhi-server/core/http_server.py @@ -3,6 +3,7 @@ from aiohttp import web from config.logger import setup_logging from core.api.ota_handler import OTAHandler from core.api.vision_handler import VisionHandler +from core.api.device_tool_handler import DeviceToolHandler TAG = __name__ @@ -13,6 +14,7 @@ class SimpleHttpServer: self.logger = setup_logging() self.ota_handler = OTAHandler(config) self.vision_handler = VisionHandler(config) + self.device_tool_handler = DeviceToolHandler(config) def _get_websocket_url(self, local_ip: str, port: int) -> str: """获取websocket地址 @@ -75,6 +77,15 @@ class SimpleHttpServer: ] ) + # 本机设备工具接口(默认关闭,只接受本机请求) + if server_config.get("device_tool_api", False): + app.add_routes( + [ + web.get("/xiaozhi/device/tools", self.device_tool_handler.handle_list), + web.post("/xiaozhi/device/call", self.device_tool_handler.handle_call), + ] + ) + # 运行服务 runner = web.AppRunner(app) await runner.setup() diff --git a/main/xiaozhi-server/core/websocket_server.py b/main/xiaozhi-server/core/websocket_server.py index c1cb4a541..e45c26748 100644 --- a/main/xiaozhi-server/core/websocket_server.py +++ b/main/xiaozhi-server/core/websocket_server.py @@ -31,6 +31,7 @@ _setup_websockets_logger() from core.connection import ConnectionHandler +from core.api.device_tool_handler import register_connection, unregister_connection from config.config_loader import get_config_from_api_async from core.auth import AuthManager, AuthenticationError from core.utils.modules_initialize import initialize_modules @@ -127,11 +128,13 @@ class WebSocketServer: self._intent, self, # 传入server实例 ) + register_connection(handler) try: await handler.handle_connection(websocket) except Exception as e: self.logger.bind(tag=TAG).error(f"处理连接时出错: {e}") finally: + unregister_connection(handler) # 强制关闭连接(如果还没有关闭的话) try: # 安全地检查WebSocket状态并关闭