|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +/** |
| 4 | + * @license |
| 5 | + * Copyright 2026 Google LLC |
| 6 | + * SPDX-License-Identifier: Apache-2.0 |
| 7 | + */ |
| 8 | + |
| 9 | +import fs from 'node:fs/promises'; |
| 10 | +import {createServer, type Server} from 'node:net'; |
| 11 | +import process from 'node:process'; |
| 12 | + |
| 13 | +import {Client} from '@modelcontextprotocol/sdk/client/index.js'; |
| 14 | +import {StdioClientTransport} from '@modelcontextprotocol/sdk/client/stdio.js'; |
| 15 | + |
| 16 | +import {logger} from '../logger.js'; |
| 17 | +import {PipeTransport} from '../third_party/index.js'; |
| 18 | + |
| 19 | +import { |
| 20 | + getSocketPath, |
| 21 | + handlePidFile, |
| 22 | + INDEX_SCRIPT_PATH, |
| 23 | + IS_WINDOWS, |
| 24 | +} from './utils.js'; |
| 25 | + |
| 26 | +const pidFile = handlePidFile(); |
| 27 | +const socketPath = getSocketPath(); |
| 28 | + |
| 29 | +let mcpClient: Client | null = null; |
| 30 | +let mcpTransport: StdioClientTransport | null = null; |
| 31 | +let server: Server | null = null; |
| 32 | + |
| 33 | +async function setupMCPClient() { |
| 34 | + console.log('Setting up MCP client connection...'); |
| 35 | + |
| 36 | + const args = process.argv.slice(2); |
| 37 | + // Create stdio transport for chrome-devtools-mcp |
| 38 | + mcpTransport = new StdioClientTransport({ |
| 39 | + command: process.execPath, |
| 40 | + args: [INDEX_SCRIPT_PATH, ...args], |
| 41 | + env: process.env as Record<string, string>, |
| 42 | + }); |
| 43 | + mcpClient = new Client( |
| 44 | + { |
| 45 | + name: 'chrome-devtools-cli-daemon', |
| 46 | + // TODO: handle client version (optional). |
| 47 | + version: '0.1.0', |
| 48 | + }, |
| 49 | + { |
| 50 | + capabilities: {}, |
| 51 | + }, |
| 52 | + ); |
| 53 | + await mcpClient.connect(mcpTransport); |
| 54 | + |
| 55 | + console.log('MCP client connected'); |
| 56 | +} |
| 57 | + |
| 58 | +interface McpContent { |
| 59 | + type: string; |
| 60 | + text?: string; |
| 61 | +} |
| 62 | + |
| 63 | +interface McpResult { |
| 64 | + content?: McpContent[] | string; |
| 65 | + text?: string; |
| 66 | +} |
| 67 | + |
| 68 | +type DaemonMessage = |
| 69 | + | { |
| 70 | + method: 'stop'; |
| 71 | + } |
| 72 | + | { |
| 73 | + method: 'invoke_tool'; |
| 74 | + tool: string; |
| 75 | + args?: Record<string, unknown>; |
| 76 | + }; |
| 77 | + |
| 78 | +async function handleRequest(msg: DaemonMessage) { |
| 79 | + try { |
| 80 | + if (msg.method === 'invoke_tool') { |
| 81 | + if (!mcpClient) { |
| 82 | + throw new Error('MCP client not initialized'); |
| 83 | + } |
| 84 | + const {tool, args} = msg; |
| 85 | + |
| 86 | + const result = (await mcpClient.callTool({ |
| 87 | + name: tool, |
| 88 | + arguments: args || {}, |
| 89 | + })) as McpResult | McpContent[]; |
| 90 | + |
| 91 | + return { |
| 92 | + success: true, |
| 93 | + result: JSON.stringify(result), |
| 94 | + }; |
| 95 | + } else if (msg.method === 'stop') { |
| 96 | + // Trigger cleanup asynchronously |
| 97 | + setImmediate(() => { |
| 98 | + void cleanup(); |
| 99 | + }); |
| 100 | + return { |
| 101 | + success: true, |
| 102 | + message: 'stopping', |
| 103 | + }; |
| 104 | + } else { |
| 105 | + return { |
| 106 | + success: false, |
| 107 | + error: `Unknown method: ${JSON.stringify(msg, null, 2)}`, |
| 108 | + }; |
| 109 | + } |
| 110 | + } catch (error: unknown) { |
| 111 | + const errorMessage = error instanceof Error ? error.message : String(error); |
| 112 | + return { |
| 113 | + success: false, |
| 114 | + error: errorMessage, |
| 115 | + }; |
| 116 | + } |
| 117 | +} |
| 118 | + |
| 119 | +async function startSocketServer() { |
| 120 | + // Remove existing socket file if it exists (only on non-Windows) |
| 121 | + if (!IS_WINDOWS) { |
| 122 | + try { |
| 123 | + await fs.unlink(socketPath); |
| 124 | + } catch { |
| 125 | + // ignore errors. |
| 126 | + } |
| 127 | + } |
| 128 | + |
| 129 | + return await new Promise<void>((resolve, reject) => { |
| 130 | + server = createServer(socket => { |
| 131 | + const transport = new PipeTransport(socket, socket); |
| 132 | + transport.onmessage = async (message: string) => { |
| 133 | + logger('onmessage', message); |
| 134 | + const response = await handleRequest(JSON.parse(message)); |
| 135 | + transport.send(JSON.stringify(response)); |
| 136 | + socket.end(); |
| 137 | + }; |
| 138 | + socket.on('error', error => { |
| 139 | + logger('Socket error:', error); |
| 140 | + }); |
| 141 | + }); |
| 142 | + |
| 143 | + server.listen( |
| 144 | + { |
| 145 | + path: socketPath, |
| 146 | + readableAll: false, |
| 147 | + writableAll: false, |
| 148 | + }, |
| 149 | + async () => { |
| 150 | + console.log(`Daemon server listening on ${socketPath}`); |
| 151 | + |
| 152 | + try { |
| 153 | + // Setup MCP client |
| 154 | + await setupMCPClient(); |
| 155 | + resolve(); |
| 156 | + } catch (err) { |
| 157 | + reject(err); |
| 158 | + } |
| 159 | + }, |
| 160 | + ); |
| 161 | + |
| 162 | + server.on('error', error => { |
| 163 | + logger('Server error:', error); |
| 164 | + reject(error); |
| 165 | + }); |
| 166 | + }); |
| 167 | +} |
| 168 | + |
| 169 | +async function cleanup() { |
| 170 | + console.log('Cleaning up daemon...'); |
| 171 | + |
| 172 | + try { |
| 173 | + await mcpClient?.close(); |
| 174 | + } catch (error) { |
| 175 | + logger('Error closing MCP client:', error); |
| 176 | + } |
| 177 | + try { |
| 178 | + await mcpTransport?.close(); |
| 179 | + } catch (error) { |
| 180 | + logger('Error closing MCP transport:', error); |
| 181 | + } |
| 182 | + server?.close(() => { |
| 183 | + if (!IS_WINDOWS) { |
| 184 | + void fs.unlink(socketPath).catch(() => undefined); |
| 185 | + } |
| 186 | + }); |
| 187 | + await fs.unlink(pidFile).catch(() => undefined); |
| 188 | + process.exit(0); |
| 189 | +} |
| 190 | + |
| 191 | +// Handle shutdown signals |
| 192 | +process.on('SIGTERM', () => { |
| 193 | + void cleanup(); |
| 194 | +}); |
| 195 | +process.on('SIGINT', () => { |
| 196 | + void cleanup(); |
| 197 | +}); |
| 198 | +process.on('SIGHUP', () => { |
| 199 | + void cleanup(); |
| 200 | +}); |
| 201 | + |
| 202 | +// Handle uncaught errors |
| 203 | +process.on('uncaughtException', error => { |
| 204 | + logger('Uncaught exception:', error); |
| 205 | +}); |
| 206 | +process.on('unhandledRejection', error => { |
| 207 | + logger('Unhandled rejection:', error); |
| 208 | +}); |
| 209 | + |
| 210 | +// Start the server |
| 211 | +startSocketServer().catch(error => { |
| 212 | + logger('Failed to start daemon server:', error); |
| 213 | + process.exit(1); |
| 214 | +}); |
0 commit comments