// 测试 SSE 连接到 MCP 服务器 import { v4 as uuidv4 } from 'uuid'; async function testSSEConnection() { console.log('🧪 测试 SSE 连接...'); try { // 1. 测试健康检查 const healthResponse = await fetch('http://127.0.0.1:3100/health'); console.log('✅ 健康检查:', healthResponse.status, healthResponse.statusText); // 2. 测试 SSE 连接 console.log('📡 尝试连接 SSE...'); const sseUrl = 'http://127.0.0.1:3100/mcp/sse'; const eventSource = new EventSource(sseUrl); eventSource.onopen = () => { console.log('✅ SSE 连接成功'); // 发送初始化请求 sendMCPRequest('initialize', { protocolVersion: "2024-11-05", capabilities: { roots: { listChanged: true }, sampling: {} }, clientInfo: { name: "xiaozhi-client-sse", version: "1.0.0" } }); }; eventSource.onmessage = (event) => { console.log('📨 收到 SSE 消息:', event.data); try { const message = JSON.parse(event.data); console.log('解析的消息:', message); } catch (error) { console.error('消息解析失败:', error); } }; eventSource.onerror = (error) => { console.error('❌ SSE 连接错误:', error); }; // 发送 MCP 请求的函数 async function sendMCPRequest(method, params) { const request = { jsonrpc: '2.0', id: uuidv4(), method, params }; console.log(`📤 发送 MCP 请求 (${method}):`, request); try { const response = await fetch('http://127.0.0.1:3100/mcp', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'text/event-stream, application/json', 'Cache-Control': 'no-cache' }, body: JSON.stringify(request) }); console.log(`🔧 请求响应 (${method}):`, response.status, response.statusText); if (response.ok) { const contentType = response.headers.get('content-type'); if (contentType && contentType.includes('application/json')) { const result = await response.json(); console.log(`✅ 直接响应 (${method}):`, result); } else { console.log(`📡 等待 SSE 响应 (${method})`); } } else { const error = await response.text(); console.log(`❌ 请求失败 (${method}):`, error); } } catch (error) { console.error(`❌ 请求异常 (${method}):`, error); } } // 5秒后测试工具列表 setTimeout(() => { sendMCPRequest('tools/list', {}); }, 2000); // 10秒后关闭连接 setTimeout(() => { console.log('🔌 关闭 SSE 连接'); eventSource.close(); }, 10000); } catch (error) { console.error('❌ 测试失败:', error); } } testSSEConnection();