UNPKG

youling-task

Version:

基于POMDP的研发任务分解工具,支持MCP协议

126 lines 3.6 kB
/** * MCP stdio传输层实现 * 用于支持通过标准输入/输出与MCP客户端通信 */ import { createInterface } from 'readline'; import logger from '../utils/logger.js'; // JSON-RPC 2.0协议常量 const JSON_RPC_VERSION = '2.0'; /** * Stdio传输层类 */ export class StdioTransport { handler; isReady = false; rl; /** * 构造函数 * @param options 配置选项 */ constructor(options) { this.handler = options.handler; // 创建readline接口,用于从stdin读取数据 this.rl = createInterface({ input: process.stdin, output: process.stdout, terminal: false }); // 监听行输入 this.rl.on('line', this.handleLine.bind(this)); // 监听关闭事件 this.rl.on('close', () => { logger.info('STDIO连接已关闭'); process.exit(0); }); // 向客户端通知服务器已就绪 this.sendReadyStatus(options.serverName, options.version); } /** * 处理接收到的行 * @param line 接收到的行 */ async handleLine(line) { try { // 解析JSON-RPC请求 const request = JSON.parse(line); logger.debug('收到STDIO请求', { request }); // 处理请求 try { const response = await this.handler(request); this.sendResponse(response, request.id); } catch (error) { this.sendErrorResponse(error.code || -32603, error.message || 'Internal error', request?.id, error.data); } } catch (error) { logger.error('解析请求失败', { error: error.message, line }); this.sendErrorResponse(-32700, 'Parse error', null); } } /** * 发送就绪状态 */ sendReadyStatus(serverName, version) { const statusMessage = { jsonrpc: JSON_RPC_VERSION, method: 'server/status', params: { status: 'ready', mode: 'stdio', name: serverName, version: version, protocol: 'MCP (JSON-RPC 2.0)', streaming: true } }; // 输出到stdout console.log(JSON.stringify(statusMessage)); this.isReady = true; logger.info('STDIO模式MCP服务器就绪'); } /** * 发送JSON-RPC响应 * @param result 结果 * @param id 请求ID */ sendResponse(result, id) { const response = { jsonrpc: JSON_RPC_VERSION, result, id }; console.log(JSON.stringify(response)); logger.debug('发送STDIO响应', { id }); } /** * 发送JSON-RPC错误响应 * @param code 错误代码 * @param message 错误消息 * @param id 请求ID * @param data 错误数据 */ sendErrorResponse(code, message, id, data) { const errorResponse = { jsonrpc: JSON_RPC_VERSION, error: { code, message }, id }; if (data !== undefined) { errorResponse.error.data = data; } console.log(JSON.stringify(errorResponse)); logger.debug('发送STDIO错误响应', { code, message, id }); } /** * 关闭传输层 */ close() { this.rl.close(); } } export default StdioTransport; //# sourceMappingURL=stdio-transport.js.map