()
| 38 | * sets up signal handlers for graceful shutdown, and starts the server. |
| 39 | */ |
| 40 | export async function startMcpServer(): Promise<void> { |
| 41 | let idleShutdown: McpIdleShutdownController | null = null; |
| 42 | |
| 43 | const lifecycle = createMcpLifecycleCoordinator({ |
| 44 | onShutdown: async ({ reason, error, snapshot, server }) => { |
| 45 | idleShutdown?.stop(); |
| 46 | |
| 47 | const isCrash = reason === 'uncaught-exception' || reason === 'unhandled-rejection'; |
| 48 | const event = isCrash ? 'crash' : 'shutdown'; |
| 49 | |
| 50 | const transportMessages: Record<string, string> = { |
| 51 | 'stdin-end': 'MCP stdin ended; shutting down MCP server', |
| 52 | 'stdin-close': 'MCP stdin closed; shutting down MCP server', |
| 53 | 'stdout-error': 'MCP stdout pipe broke; shutting down MCP server', |
| 54 | 'stderr-error': 'MCP stderr pipe broke; shutting down MCP server', |
| 55 | 'idle-timeout': 'MCP idle timeout reached; shutting down MCP server', |
| 56 | }; |
| 57 | log('info', transportMessages[reason] ?? `MCP shutdown requested: ${reason}`); |
| 58 | |
| 59 | if (!isTransportDisconnectReason(reason)) { |
| 60 | recordMcpLifecycleMetric({ |
| 61 | event, |
| 62 | phase: snapshot.phase, |
| 63 | reason, |
| 64 | uptimeMs: snapshot.uptimeMs, |
| 65 | rssBytes: snapshot.rssBytes, |
| 66 | matchingMcpProcessCount: snapshot.matchingMcpProcessCount, |
| 67 | activeOperationCount: snapshot.activeOperationCount, |
| 68 | watcherRunning: snapshot.watcherRunning, |
| 69 | }); |
| 70 | |
| 71 | for (const anomaly of snapshot.anomalies) { |
| 72 | recordMcpLifecycleAnomalyMetric({ |
| 73 | kind: anomaly, |
| 74 | phase: snapshot.phase, |
| 75 | reason, |
| 76 | }); |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | const result = await runMcpShutdown({ |
| 81 | reason, |
| 82 | error, |
| 83 | snapshot, |
| 84 | server, |
| 85 | }); |
| 86 | |
| 87 | lifecycle.detachProcessHandlers(); |
| 88 | process.exit(result.exitCode); |
| 89 | }, |
| 90 | }); |
| 91 | |
| 92 | lifecycle.attachProcessHandlers(); |
| 93 | |
| 94 | try { |
| 95 | const profiler = createStartupProfiler('start-mcp-server'); |
| 96 | |
| 97 | // MCP mode defaults to info level logging |
no test coverage detected