# xiaozhi-mcp-bridge **Repository Path**: wtlogin/xiaozhi-mcp-bridge ## Basic Information - **Project Name**: xiaozhi-mcp-bridge - **Description**: 小智AI的mcp服务接入,这个 Python 桥接器可以将本地运行的多个 MCP 服务连接到小智AI的 WebSocket 接入点 wss://api.xiaozhi.me/mcp/?token=xxxx。 - **Primary Language**: Python - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 1 - **Created**: 2026-02-07 - **Last Updated**: 2026-02-07 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 小智AI MCP 桥接器使用指南 ## 概述 这个Python客户端可以将本地的MCP服务连接到小智AI (xiaozhi.me),让你在小智AI中使用各种MCP工具。 ## 快速开始 ### 1. 环境准备 ```bash # 创建项目目录 mkdir xiaozhi-mcp-client cd xiaozhi-mcp-client # 创建虚拟环境 (推荐) python -m venv venv source venv/bin/activate # Linux/Mac # 或 Windows: # venv\Scripts\activate # 安装依赖 pip install websockets ``` ### 2. 安装MCP服务 ```bash # 安装Node.js (如果还没有) # 然后安装MCP服务 npm install -g @mcp/calculator npm install -g @mcp/filesystem npm install -g @mcp/git npm install -g @mcp/weather npm install -g @mcp/time ``` ### 3. 获取小智AI Token 1. 访问 https://xiaozhi.me 2. 登录你的账户 3. 在设置中找到MCP相关配置 4. 获取你的token ### 4. 运行客户端 ```bash # 将上面的Python代码保存为 mcp_client.py python mcp_client.py --token YOUR_XIAOZHI_TOKEN # 启用调试日志 python mcp_client.py --token YOUR_XIAOZHI_TOKEN --debug ``` ## 配置更多MCP服务 ### 修改服务配置 编辑 `mcp_client.py` 文件中的 `services_config` 列表: ```python services_config = [ ("calculator", ["npx", "@mcp/calculator"]), ("filesystem", ["npx", "@mcp/filesystem"]), ("git", ["npx", "@mcp/git"]), ("weather", ["npx", "@mcp/weather"]), ("time", ["npx", "@mcp/time"]), # 添加更多服务 ("notion", ["npx", "@mcp/notion"]), ("slack", ["npx", "@mcp/slack"]), ("github", ["npx", "@mcp/github"]), ] ``` ### 支持的MCP服务 以下是一些常用的MCP服务,你可以从 https://mcp.so 找到更多: #### 开发工具 - `@mcp/git` - Git版本控制 - `@mcp/github` - GitHub集成 - `@mcp/gitlab` - GitLab集成 - `@mcp/docker` - Docker容器管理 #### 文件和数据 - `@mcp/filesystem` - 文件系统操作 - `@mcp/sqlite` - SQLite数据库 - `@mcp/postgres` - PostgreSQL数据库 - `@mcp/mysql` - MySQL数据库 #### 生产力工具 - `@mcp/notion` - Notion笔记 - `@mcp/slack` - Slack消息 - `@mcp/gmail` - Gmail邮件 - `@mcp/calendar` - 日历管理 - `@mcp/jira` - Jira项目管理 #### 网络和API - `@mcp/browser` - 浏览器自动化 - `@mcp/http` - HTTP请求 - `@mcp/rest-api` - REST API调用 #### 实用工具 - `@mcp/calculator` - 计算器 - `@mcp/weather` - 天气查询 - `@mcp/time` - 时间工具 - `@mcp/crypto` - 加密工具 - `@mcp/qrcode` - 二维码生成 ## 高级配置 ### 创建配置文件 创建 `config.json` 配置文件: ```json { "xiaozhi_token": "your_token_here", "services": [ { "name": "calculator", "command": ["npx", "@mcp/calculator"], "enabled": true }, { "name": "filesystem", "command": ["npx", "@mcp/filesystem"], "enabled": true, "config": { "allowed_paths": ["/home/user/documents"] } }, { "name": "git", "command": ["npx", "@mcp/git"], "enabled": false } ], "logging": { "level": "INFO", "file": "mcp_client.log" } } ``` ### 修改客户端支持配置文件 ```python import json def load_config(config_file="config.json"): try: with open(config_file, 'r', encoding='utf-8') as f: return json.load(f) except FileNotFoundError: return None # 在main函数中使用 config = load_config() if config: client = MCPClient(config['xiaozhi_token']) for service in config['services']: if service.get('enabled', True): await client.add_service(service['name'], service['command']) ``` ## 部署选项 ### 1. 使用 systemd (Linux) 创建服务文件 `/etc/systemd/system/xiaozhi-mcp.service`: ```ini [Unit] Description=XiaoZhi MCP Client After=network.target [Service] Type=simple User=your_username WorkingDirectory=/path/to/your/project Environment=PATH=/usr/bin:/usr/local/bin ExecStart=/path/to/venv/bin/python mcp_client.py --token YOUR_TOKEN Restart=always RestartSec=10 [Install] WantedBy=multi-user.target ``` 启动服务: ```bash sudo systemctl daemon-reload sudo systemctl enable xiaozhi-mcp sudo systemctl start xiaozhi-mcp ``` ### 2. 使用 Docker 创建 `Dockerfile`: ```dockerfile FROM python:3.11-slim # 安装Node.js (用于MCP服务) RUN apt-get update && \ apt-get install -y nodejs npm && \ rm -rf /var/lib/apt/lists/* WORKDIR /app # 安装Python依赖 COPY requirements.txt . RUN pip install -r requirements.txt # 安装MCP服务 RUN npm install -g @mcp/calculator @mcp/filesystem @mcp/git @mcp/weather @mcp/time # 复制代码 COPY mcp_client.py . # 运行 CMD ["python", "mcp_client.py", "--token", "$XIAOZHI_TOKEN"] ``` 构建和运行: ```bash docker build -t xiaozhi-mcp-client . docker run -e XIAOZHI_TOKEN=your_token xiaozhi-mcp-client ``` ### 3. 使用 Docker Compose 创建 `docker-compose.yml`: ```yaml version: '3.8' services: xiaozhi-mcp: build: . environment: - XIAOZHI_TOKEN=${XIAOZHI_TOKEN} restart: unless-stopped volumes: - ./config.json:/app/config.json:ro logging: driver: "json-file" options: max-size: "10m" max-file: "3" ``` ## 故障排除 ### 1. 连接问题 ```bash # 检查网络连接 ping api.xiaozhi.me # 检查WebSocket连接 curl -i -N -H "Connection: Upgrade" \ -H "Upgrade: websocket" \ -H "Sec-WebSocket-Key: test" \ -H "Sec-WebSocket-Version: 13" \ https://api.xiaozhi.me/mcp/?token=YOUR_TOKEN ``` ### 2. MCP服务问题 ```bash # 手动测试MCP服务 npx @mcp/calculator # 检查服务是否正确安装 npm list -g @mcp/calculator ``` ### 3. 常见错误 **Token无效**: - 检查token是否正确 - 确认token没有过期 - 重新获取token **服务启动失败**: - 检查Node.js和npm是否正确安装 - 确认MCP服务包已安装 - 查看详细错误日志 **WebSocket连接断开**: - 客户端会自动重连 - 检查网络稳定性 - 确认小智AI服务状态 ### 4. 调试技巧 ```python # 启用详细日志 python mcp_client.py --token YOUR_TOKEN --debug # 查看特定服务的输出 # 在代码中添加: logger.debug(f"Service {service_name} output: {response_line}") ``` ## 扩展功能 ### 1. 添加自定义工具 ```python async def add_custom_tool(self, tool_name: str, tool_func): """添加自定义工具""" self.all_tools[tool_name] = { 'name': tool_name, 'description': '自定义工具', 'service_name': 'custom', 'func': tool_func } ``` ### 2. 工具调用统计 ```python from collections import defaultdict import time class MCPClient: def __init__(self, xiaozhi_token: str): # ... 其他初始化代码 self.tool_usage_stats = defaultdict(int) self.tool_response_times = defaultdict(list) async def call_tool(self, tool_name: str, arguments: Dict = None) -> Dict: start_time = time.time() try: result = await super().call_tool(tool_name, arguments) self.tool_usage_stats[tool_name] += 1 response_time = time.time() - start_time self.tool_response_times[tool_name].append(response_time) return result except Exception as e: logger.error(f"Tool {tool_name} failed after {time.time() - start_time:.2f}s: {e}") raise ``` ### 3. 健康检查 ```python async def health_check(self): """检查所有服务的健康状态""" healthy_services = [] for name, service in self.services.items(): if service.process and service.process.poll() is None: healthy_services.append(name) else: logger.warning(f"Service {name} is not healthy") return { 'healthy_services': healthy_services, 'total_services': len(self.services), 'total_tools': len(self.all_tools) } ``` 这个Python客户端提供了完整的解决方案来连接本地MCP服务到小智AI。你可以根据需要添加更多服务和功能!