|
| 1 | +// Minimal example: start the MCP server (stdio) and send an MCP "initialize" request. |
| 2 | +// |
| 3 | +// This is intentionally tiny and dependency-free so it works anywhere Node works. |
| 4 | +// |
| 5 | +// Usage: |
| 6 | +// node examples/minimal-node-client.mjs |
| 7 | +// |
| 8 | +// It will: |
| 9 | +// 1) spawn `npx chrome-devtools-mcp@latest` |
| 10 | +// 2) send the JSON-RPC initialize message |
| 11 | +// 3) print the server's response |
| 12 | + |
| 13 | +import { spawn } from 'node:child_process'; |
| 14 | + |
| 15 | +const child = spawn( |
| 16 | + 'npx', |
| 17 | + ['--yes', 'chrome-devtools-mcp@latest'], |
| 18 | + { |
| 19 | + stdio: ['pipe', 'pipe', 'pipe'], |
| 20 | + env: { |
| 21 | + ...process.env, |
| 22 | + // Reduce noise in the example output. |
| 23 | + DEBUG: process.env.DEBUG ?? '', |
| 24 | + // Avoid telemetry prompts/noise in some environments. |
| 25 | + CHROME_DEVTOOLS_MCP_NO_USAGE_STATISTICS: 'true', |
| 26 | + }, |
| 27 | + }, |
| 28 | +); |
| 29 | + |
| 30 | +child.stderr.on('data', (d) => process.stderr.write(d)); |
| 31 | + |
| 32 | +let buf = ''; |
| 33 | +child.stdout.on('data', (d) => { |
| 34 | + buf += d.toString('utf8'); |
| 35 | + // MCP stdio transport uses newline-delimited JSON. |
| 36 | + let idx; |
| 37 | + while ((idx = buf.indexOf('\n')) !== -1) { |
| 38 | + const line = buf.slice(0, idx).trim(); |
| 39 | + buf = buf.slice(idx + 1); |
| 40 | + if (!line) continue; |
| 41 | + |
| 42 | + try { |
| 43 | + const msg = JSON.parse(line); |
| 44 | + console.log('←', msg); |
| 45 | + // Exit after we receive initialize response. |
| 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 | +child.on('exit', (code) => { |
| 57 | + if (code !== 0) { |
| 58 | + process.exitCode = code ?? 1; |
| 59 | + } |
| 60 | +}); |
| 61 | + |
| 62 | +const init = { |
| 63 | + jsonrpc: '2.0', |
| 64 | + id: 1, |
| 65 | + method: 'initialize', |
| 66 | + params: { |
| 67 | + protocolVersion: '2024-11-05', |
| 68 | + capabilities: {}, |
| 69 | + clientInfo: { name: 'minimal-node-client', version: '0.0.0' }, |
| 70 | + }, |
| 71 | +}; |
| 72 | + |
| 73 | +child.stdin.write(JSON.stringify(init) + '\n'); |
0 commit comments