|
| 1 | +// Example: connect to a Chrome instance that was started with a remote debugging port. |
| 2 | +// |
| 3 | +// 1) Start Chrome manually with remote debugging enabled, e.g.: |
| 4 | +// macOS: |
| 5 | +// /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222 |
| 6 | +// Linux: |
| 7 | +// google-chrome --remote-debugging-port=9222 |
| 8 | +// |
| 9 | +// 2) Run this script: |
| 10 | +// node examples/remote-debugging-9222.mjs |
| 11 | +// |
| 12 | +// This spawns the MCP server and connects it to http://127.0.0.1:9222 via --browserUrl. |
| 13 | +// |
| 14 | +// Note: This is intentionally a small template you can adapt for your own MCP client. |
| 15 | + |
| 16 | +import { spawn } from 'node:child_process'; |
| 17 | + |
| 18 | +const DEBUG_URL = process.env.CHROME_DEBUG_URL ?? 'http://127.0.0.1:9222'; |
| 19 | + |
| 20 | +const child = spawn( |
| 21 | + 'npx', |
| 22 | + ['--yes', 'chrome-devtools-mcp@latest', '--browserUrl', DEBUG_URL], |
| 23 | + { |
| 24 | + stdio: ['pipe', 'pipe', 'pipe'], |
| 25 | + env: { |
| 26 | + ...process.env, |
| 27 | + CHROME_DEVTOOLS_MCP_NO_USAGE_STATISTICS: 'true', |
| 28 | + }, |
| 29 | + }, |
| 30 | +); |
| 31 | + |
| 32 | +child.stderr.on('data', (d) => process.stderr.write(d)); |
| 33 | + |
| 34 | +let buf = ''; |
| 35 | +child.stdout.on('data', (d) => { |
| 36 | + buf += d.toString('utf8'); |
| 37 | + let idx; |
| 38 | + while ((idx = buf.indexOf('\n')) !== -1) { |
| 39 | + const line = buf.slice(0, idx).trim(); |
| 40 | + buf = buf.slice(idx + 1); |
| 41 | + if (!line) continue; |
| 42 | + try { |
| 43 | + const msg = JSON.parse(line); |
| 44 | + console.log('←', msg); |
| 45 | + // Exit after initialize. |
| 46 | + if (msg.id === 1) { |
| 47 | + child.kill(); |
| 48 | + process.exit(0); |
| 49 | + } |
| 50 | + } catch { |
| 51 | + // ignore non-JSON lines |
| 52 | + } |
| 53 | + } |
| 54 | +}); |
| 55 | + |
| 56 | +const init = { |
| 57 | + jsonrpc: '2.0', |
| 58 | + id: 1, |
| 59 | + method: 'initialize', |
| 60 | + params: { |
| 61 | + protocolVersion: '2024-11-05', |
| 62 | + capabilities: {}, |
| 63 | + clientInfo: { name: 'remote-debugging-9222', version: '0.0.0' }, |
| 64 | + }, |
| 65 | +}; |
| 66 | + |
| 67 | +child.stdin.write(JSON.stringify(init) + '\n'); |
0 commit comments