Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 | /** * V3 MCP Stdio Transport * * Standard I/O transport for MCP communication: * - Optimized JSON parsing with streaming * - Buffer management for large messages * - Graceful shutdown handling * * Performance Targets: * - Message parsing: <5ms * - Response sending: <2ms */ import { EventEmitter } from 'events'; import * as readline from 'readline'; import { ITransport, TransportType, MCPRequest, MCPResponse, MCPNotification, RequestHandler, NotificationHandler, TransportHealthStatus, ILogger, } from '../types.js'; /** * Stdio Transport Configuration */ export interface StdioTransportConfig { inputStream?: NodeJS.ReadableStream; outputStream?: NodeJS.WritableStream; maxMessageSize?: number; } /** * Stdio Transport Implementation * * Uses readline for efficient line-by-line processing of JSON-RPC messages */ export class StdioTransport extends EventEmitter implements ITransport { public readonly type: TransportType = 'stdio'; private requestHandler?: RequestHandler; private notificationHandler?: NotificationHandler; private rl?: readline.Interface; private running = false; private messageBuffer = ''; // Statistics private messagesReceived = 0; private messagesSent = 0; private errors = 0; private readonly inputStream: NodeJS.ReadableStream; private readonly outputStream: NodeJS.WritableStream; private readonly maxMessageSize: number; constructor( private readonly logger: ILogger, config: StdioTransportConfig = {} ) { super(); this.inputStream = config.inputStream || process.stdin; this.outputStream = config.outputStream || process.stdout; this.maxMessageSize = config.maxMessageSize || 10 * 1024 * 1024; // 10MB default } /** * Start the transport */ async start(): Promise<void> { if (this.running) { throw new Error('Stdio transport already running'); } this.logger.info('Starting stdio transport'); // Create readline interface for efficient line processing this.rl = readline.createInterface({ input: this.inputStream, crlfDelay: Infinity, }); // Handle incoming lines this.rl.on('line', (line) => { this.handleLine(line); }); // Handle close this.rl.on('close', () => { this.handleClose(); }); // Handle errors on input stream this.inputStream.on('error', (error) => { this.handleError(error); }); this.running = true; this.logger.info('Stdio transport started'); } /** * Stop the transport */ async stop(): Promise<void> { if (!this.running) { return; } this.logger.info('Stopping stdio transport'); this.running = false; if (this.rl) { this.rl.close(); this.rl = undefined; } this.logger.info('Stdio transport stopped'); } /** * Register request handler */ onRequest(handler: RequestHandler): void { this.requestHandler = handler; } /** * Register notification handler */ onNotification(handler: NotificationHandler): void { this.notificationHandler = handler; } /** * Get health status */ async getHealthStatus(): Promise<TransportHealthStatus> { return { healthy: this.running, metrics: { messagesReceived: this.messagesReceived, messagesSent: this.messagesSent, errors: this.errors, }, }; } /** * Handle incoming line */ private async handleLine(line: string): Promise<void> { if (!line.trim()) { return; } // Check message size if (line.length > this.maxMessageSize) { this.logger.error('Message exceeds maximum size', { size: line.length, max: this.maxMessageSize, }); this.errors++; return; } try { const message = JSON.parse(line); this.messagesReceived++; // Validate JSON-RPC format if (message.jsonrpc !== '2.0') { this.logger.warn('Invalid JSON-RPC version', { received: message.jsonrpc }); await this.sendError(message.id, -32600, 'Invalid JSON-RPC version'); return; } if (!message.method) { this.logger.warn('Missing method in request'); await this.sendError(message.id, -32600, 'Missing method'); return; } // Determine if this is a request or notification if (message.id !== undefined) { // Request - needs response await this.handleRequest(message as MCPRequest); } else { // Notification - no response needed await this.handleNotification(message as MCPNotification); } } catch (error) { this.errors++; this.logger.error('Failed to parse message', { error, line: line.substring(0, 100) }); await this.sendError(null, -32700, 'Parse error'); } } /** * Handle MCP request */ private async handleRequest(request: MCPRequest): Promise<void> { if (!this.requestHandler) { this.logger.warn('No request handler registered'); await this.sendError(request.id, -32603, 'No request handler'); return; } try { const startTime = performance.now(); const response = await this.requestHandler(request); const duration = performance.now() - startTime; this.logger.debug('Request processed', { method: request.method, duration: `${duration.toFixed(2)}ms`, }); await this.sendResponse(response); } catch (error) { this.logger.error('Request handler error', { method: request.method, error }); await this.sendError( request.id, -32603, error instanceof Error ? error.message : 'Internal error' ); } } /** * Handle MCP notification */ private async handleNotification(notification: MCPNotification): Promise<void> { if (!this.notificationHandler) { this.logger.debug('Notification received but no handler', { method: notification.method }); return; } try { await this.notificationHandler(notification); } catch (error) { this.logger.error('Notification handler error', { method: notification.method, error }); // Notifications don't send error responses } } /** * Send response to stdout */ private async sendResponse(response: MCPResponse): Promise<void> { const json = JSON.stringify(response); await this.write(json); this.messagesSent++; } /** * Send error response */ private async sendError(id: string | number | null, code: number, message: string): Promise<void> { const response: MCPResponse = { jsonrpc: '2.0', id, error: { code, message }, }; await this.sendResponse(response); this.errors++; } /** * Send notification to stdout */ async sendNotification(notification: MCPNotification): Promise<void> { const json = JSON.stringify(notification); await this.write(json); this.messagesSent++; } /** * Write to output stream */ private write(data: string): Promise<void> { return new Promise((resolve, reject) => { this.outputStream.write(data + '\n', (error) => { if (error) { this.errors++; reject(error); } else { resolve(); } }); }); } /** * Handle stream close */ private handleClose(): void { this.logger.info('Stdio stream closed'); this.running = false; this.emit('close'); } /** * Handle stream error */ private handleError(error: Error): void { this.logger.error('Stdio stream error', error); this.errors++; this.emit('error', error); } } /** * Create stdio transport */ export function createStdioTransport( logger: ILogger, config: StdioTransportConfig = {} ): StdioTransport { return new StdioTransport(logger, config); } |