#!/usr/bin/env python3 """ 小智设备连接测试客户端 连接到 xiaozhi-server,模拟设备握手,触发 MCP 工具初始化 """ import asyncio import json import uuid import websockets import sys XIAOZHI_WS = "ws://localhost:8000/xiaozhi/v1/" DEVICE_ID = str(uuid.uuid4()) TOPIC = str(uuid.uuid4()) async def main(): print(f"连接 xiaozhi-server: {XIAOZHI_WS}") print(f"Device ID: {DEVICE_ID}") async with websockets.connect(XIAOZHI_WS, ping_interval=None) as ws: # 发送设备 hello hello = { "type": "hello", "deviceId": DEVICE_ID, "deviceName": "测试设备", "clientType": "py-websocket-test", "protocolVersion": "1.0.0", "featureSet": {"mcp": True}, } await ws.send(json.dumps(hello)) print(f"发送 hello: {hello}") # 接收消息(最多等 30 秒) for i in range(20): try: msg = await asyncio.wait_for(ws.recv(), timeout=5.0) data = json.loads(msg) msg_type = data.get("type", "unknown") print(f"收到 [{msg_type}]: {json.dumps(data, ensure_ascii=False)[:200]}") if msg_type == "welcome": print("\n✅ 连接成功!") if "tools" in data: print(f"MCP 工具列表: {[t.get('name') for t in data.get('tools', [])]}") if "mcpTools" in data: print(f"MCP 工具: {data.get('mcpTools')}") break except asyncio.TimeoutError: print(f" ... 等待中 ({i+1}/20)") continue print("\n测试完成,5秒后关闭...") await asyncio.sleep(5) if __name__ == "__main__": try: asyncio.run(main()) except KeyboardInterrupt: print("\n已退出") except Exception as e: print(f"错误: {e}") sys.exit(1)