chrome-devtools-mcp 1.10.1 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.md +72 -20
  2. package/build/src/BrowserManager.js +155 -27
  3. package/build/src/McpContext.js +598 -200
  4. package/build/src/McpPage.js +513 -131
  5. package/build/src/McpResponse.js +291 -116
  6. package/build/src/McpWorker.js +66 -0
  7. package/build/src/SlimMcpResponse.js +5 -1
  8. package/build/src/TextSnapshot.js +40 -20
  9. package/build/src/ToolHandler.js +306 -147
  10. package/build/src/bin/chrome-devtools-mcp-main.js +13 -10
  11. package/build/src/bin/chrome-devtools-mcp.js +1 -1
  12. package/build/src/bin/chrome-devtools.js +34 -44
  13. package/build/src/collectors/PageCollector.js +13 -9
  14. package/build/src/collectors/ServiceWorkerCollector.js +20 -13
  15. package/build/src/collectors/constants.js +7 -0
  16. package/build/src/config/ConfigLocator.js +70 -0
  17. package/build/src/config/ConfigParser.js +159 -0
  18. package/build/src/config/ConfigWatcher.js +94 -0
  19. package/build/src/config/ServerConfig.js +251 -0
  20. package/build/src/config/browser-options.js +15 -17
  21. package/build/src/config/category-options.js +15 -30
  22. package/build/src/config/cli-commands.js +165 -5
  23. package/build/src/config/cli-options.js +441 -58
  24. package/build/src/config/mcp-options.js +212 -264
  25. package/build/src/config/puppeteer-options.js +67 -0
  26. package/build/src/config/tool-options.js +60 -0
  27. package/build/src/daemon/client.js +84 -44
  28. package/build/src/daemon/daemon.js +59 -45
  29. package/build/src/daemon/utils.js +46 -12
  30. package/build/src/devtools/DevToolsCommentBridge.js +71 -11
  31. package/build/src/devtools/DevtoolsUtils.js +52 -15
  32. package/build/src/devtools/McpHostBindingAdapter.js +0 -1
  33. package/build/src/formatters/CommentFormatter.js +4 -13
  34. package/build/src/formatters/ConsoleFormatter.js +29 -2
  35. package/build/src/formatters/CssFormatter.js +3 -2
  36. package/build/src/formatters/HeapSnapshotFormatter.js +111 -57
  37. package/build/src/formatters/IssueFormatter.js +33 -32
  38. package/build/src/formatters/NetworkFormatter.js +62 -22
  39. package/build/src/formatters/RemoteObjectFormatter.js +231 -0
  40. package/build/src/formatters/SnapshotFormatter.js +44 -7
  41. package/build/src/index.js +285 -88
  42. package/build/src/processors/ChunkedTraceParser.js +11 -11
  43. package/build/src/processors/HeapSnapshotManager.js +455 -156
  44. package/build/src/processors/PerformanceTrace.js +9 -9
  45. package/build/src/telemetry/ClearcutLogger.js +1 -1
  46. package/build/src/telemetry/transformation.js +7 -11
  47. package/build/src/telemetry/watchdog/main.js +1 -1
  48. package/build/src/third_party/THIRD_PARTY_NOTICES +399 -689
  49. package/build/src/third_party/bundled-packages.json +7 -8
  50. package/build/src/third_party/cli.js +9239 -0
  51. package/build/src/third_party/devtools-formatter-worker.js +4299 -2517
  52. package/build/src/third_party/devtools-heap-snapshot-worker.js +1298 -22
  53. package/build/src/third_party/index.js +132003 -146852
  54. package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantRead.md +0 -1
  55. package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantReadOptOut.md +5 -0
  56. package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantSet.md +0 -1
  57. package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantSetOptOut.md +5 -0
  58. package/build/src/third_party/issue-descriptions/deprecation.md +1 -1
  59. package/build/src/third_party/issue-descriptions/genericGeolocationPromptWithoutUserGesture.md +5 -0
  60. package/build/src/third_party/issue-descriptions/sriValidationFailedIntegrityMismatch.md +2 -0
  61. package/build/src/third_party/lighthouse-devtools-mcp-bundle.js +54576 -52174
  62. package/build/src/tools/ToolDefinition.js +102 -12
  63. package/build/src/tools/comments.js +62 -4
  64. package/build/src/tools/console.js +6 -4
  65. package/build/src/tools/css.js +5 -2
  66. package/build/src/tools/emulation.js +22 -8
  67. package/build/src/tools/extensions.js +5 -0
  68. package/build/src/tools/input.js +29 -9
  69. package/build/src/tools/lighthouse.js +136 -12
  70. package/build/src/tools/memory.js +166 -59
  71. package/build/src/tools/network.js +5 -4
  72. package/build/src/tools/pages.js +52 -7
  73. package/build/src/tools/performance.js +28 -7
  74. package/build/src/tools/pwa.js +7 -0
  75. package/build/src/tools/screencast.js +74 -33
  76. package/build/src/tools/screenshot.js +52 -21
  77. package/build/src/tools/script.js +125 -40
  78. package/build/src/tools/slim/tools.js +27 -13
  79. package/build/src/tools/snapshot.js +13 -3
  80. package/build/src/tools/thirdPartyDeveloper.js +9 -5
  81. package/build/src/tools/tools.js +35 -22
  82. package/build/src/tools/webmcp.js +11 -6
  83. package/build/src/types.js +11 -0
  84. package/build/src/utils/TaskRunner.js +136 -0
  85. package/build/src/utils/WaitForHelper.js +15 -2
  86. package/build/src/utils/bytes.js +2 -12
  87. package/build/src/utils/check-for-updates.js +2 -2
  88. package/build/src/utils/disclaimers.js +27 -0
  89. package/build/src/utils/errorHandling.js +20 -0
  90. package/build/src/utils/keyboard.js +14 -2
  91. package/build/src/utils/logger.js +84 -5
  92. package/build/src/utils/resourceType.js +27 -0
  93. package/build/src/utils/text.js +44 -0
  94. package/build/src/utils/timeout.js +14 -0
  95. package/build/src/utils/url.js +140 -3
  96. package/build/src/version.js +1 -1
  97. package/package.json +16 -11
  98. package/skills/a11y-debugging/SKILL.md +7 -12
  99. package/skills/chrome-devtools/SKILL.md +2 -2
  100. package/skills/chrome-devtools-cli/SKILL.md +18 -15
  101. package/skills/cookie-debugging/SKILL.md +8 -5
  102. package/skills/debug-optimize-lcp/SKILL.md +1 -1
  103. package/skills/troubleshooting/SKILL.md +5 -6
@@ -0,0 +1,67 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ import { validateUrlPatterns } from '../utils/url.js';
7
+ /**
8
+ * Options that are applied through Puppeteer when launching or connecting to
9
+ * the browser.
10
+ */
11
+ export const puppeteerOptions = {
12
+ viewport: {
13
+ type: 'string',
14
+ describe: 'Initial viewport size for the Chrome instances started by the server. For example, `1280x720`. In headless mode, max size is 3840x2160px.',
15
+ coerce: (arg) => {
16
+ if (arg === undefined) {
17
+ return;
18
+ }
19
+ const [width, height] = arg.split('x').map(Number);
20
+ if (!Number.isInteger(width) ||
21
+ !Number.isInteger(height) ||
22
+ width <= 0 ||
23
+ height <= 0) {
24
+ throw new Error('Invalid viewport. Expected format is `1280x720` with positive integer width and height.');
25
+ }
26
+ return {
27
+ width,
28
+ height,
29
+ };
30
+ },
31
+ },
32
+ acceptInsecureCerts: {
33
+ type: 'boolean',
34
+ default: false,
35
+ description: `If enabled, ignores errors relative to self-signed and expired certificates. Use with caution.`,
36
+ },
37
+ blockedUrlPattern: {
38
+ type: 'array',
39
+ string: true,
40
+ reloadable: true,
41
+ describe: "Restricts browser's network access by blocking specified URL patterns (uses https://urlpattern.spec.whatwg.org/). Silently detaches from targets with blocked URLs upon connection, and blocks runtime requests (including navigations and subresources); targets already open when patterns are updated via --watchConfig remain attached. Accepts an array of patterns. A pattern that uses a regexp group, a named group (`:name`), or a partial IPv4 wildcard (for example `(127\\.\\d+\\.\\d+\\.\\d+)`, `*://127.0.0.1::port/*`, or `*://127.0.0.*/*`) is rejected, because it is not enforced on redirects or subresources; use an exact value or a `*` wildcard instead. Patterns follow URL Pattern defaults: an omitted port matches only the scheme's default port (for example, `https://internal.corp/*` does not match `https://internal.corp:8443/`; use `https://internal.corp:*/*` to match any port), and the hostname must match exactly (a trailing-dot host such as `internal.corp.` is a different hostname).",
42
+ coerce: (arg) => {
43
+ if (arg === undefined || arg.length === 0) {
44
+ return undefined;
45
+ }
46
+ validateUrlPatterns(arg, '--blockedUrlPattern');
47
+ return arg;
48
+ },
49
+ },
50
+ allowedUrlPattern: {
51
+ type: 'array',
52
+ string: true,
53
+ reloadable: true,
54
+ describe: "Restricts browser's network access by allowing only specified URL patterns (uses https://urlpattern.spec.whatwg.org/). Requires Chrome 149+. Silently detaches from targets with unallowed URLs upon connection, and blocks runtime requests (including navigations and subresources); targets already open when patterns are updated via --watchConfig remain attached. Accepts an array of patterns. A pattern that uses a regexp group, a named group (`:name`), or a partial IPv4 wildcard (for example `(127\\.\\d+\\.\\d+\\.\\d+)`, `*://127.0.0.1::port/*`, or `*://127.0.0.*/*`) is rejected, because it is not enforced on redirects or subresources; use an exact value or a `*` wildcard instead. Patterns follow URL Pattern defaults: an omitted port matches only the scheme's default port (for example, `https://internal.corp/*` does not match `https://internal.corp:8443/`; use `https://internal.corp:*/*` to match any port), and the hostname must match exactly (a trailing-dot host such as `internal.corp.` is a different hostname).",
55
+ coerce: (arg) => {
56
+ if (arg === undefined) {
57
+ return undefined;
58
+ }
59
+ if (arg.length === 0) {
60
+ throw new Error('Invalid --allowedUrlPattern: at least one pattern is required.');
61
+ }
62
+ validateUrlPatterns(arg, '--allowedUrlPattern');
63
+ return arg;
64
+ },
65
+ },
66
+ };
67
+ //# sourceMappingURL=puppeteer-options.js.map
@@ -0,0 +1,60 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ /**
7
+ * Options that change the default behavior of tools.
8
+ */
9
+ export const toolOptions = {
10
+ screenshotFormat: {
11
+ type: 'string',
12
+ default: 'png',
13
+ description: 'Override the default output format used by take_screenshot when the caller does not specify one. JPEG and WebP are ~3-5x smaller than PNG, which reduces transfer and storage size. To reduce context size use --screenshotMaxWidth / --screenshotMaxHeight, since image tokens scale with dimensions rather than encoded bytes. Unset preserves the existing default ("png").',
14
+ choices: ['jpeg', 'png', 'webp'],
15
+ reloadable: true,
16
+ },
17
+ screenshotQuality: {
18
+ type: 'number',
19
+ description: 'Override the default compression quality (0-100) used by take_screenshot for JPEG and WebP when the caller does not specify one. Lower values mean smaller files. Ignored for PNG. Unset preserves the Puppeteer default.',
20
+ reloadable: true,
21
+ coerce: (value) => {
22
+ if (value === undefined) {
23
+ return;
24
+ }
25
+ if (!Number.isInteger(value) || value < 0 || value > 100) {
26
+ throw new Error(`Invalid screenshotQuality ${value}. Expected an integer between 0 and 100.`);
27
+ }
28
+ return value;
29
+ },
30
+ },
31
+ screenshotMaxWidth: {
32
+ type: 'number',
33
+ description: 'Maximum width in pixels for screenshots. If the captured image is wider, it is downscaled (preserving aspect ratio) before being returned. Reduces context size in AI conversations. Unset means no resize.',
34
+ reloadable: true,
35
+ coerce: (value) => {
36
+ if (value === undefined) {
37
+ return;
38
+ }
39
+ if (!Number.isInteger(value) || value <= 0) {
40
+ throw new Error(`Invalid screenshotMaxWidth ${value}. Expected a positive integer.`);
41
+ }
42
+ return value;
43
+ },
44
+ },
45
+ screenshotMaxHeight: {
46
+ type: 'number',
47
+ description: 'Maximum height in pixels for screenshots. If the captured image is taller, it is downscaled (preserving aspect ratio) before being returned. Can be combined with --screenshot-max-width; the smaller scale factor wins. Unset means no resize.',
48
+ reloadable: true,
49
+ coerce: (value) => {
50
+ if (value === undefined) {
51
+ return;
52
+ }
53
+ if (!Number.isInteger(value) || value <= 0) {
54
+ throw new Error(`Invalid screenshotMaxHeight ${value}. Expected a positive integer.`);
55
+ }
56
+ return value;
57
+ },
58
+ },
59
+ };
60
+ //# sourceMappingURL=tool-options.js.map
@@ -6,55 +6,51 @@
6
6
  import { spawn } from 'node:child_process';
7
7
  import fs from 'node:fs';
8
8
  import net from 'node:net';
9
- import { PipeTransport } from '../third_party/index.js';
9
+ import path from 'node:path';
10
+ import { PipeTransport } from '../third_party/cli.js';
10
11
  import { getTempFilePath } from '../utils/files.js';
11
- import { logger, puppeteerLogger } from '../utils/logger.js';
12
- import { DAEMON_SCRIPT_PATH, getSocketPath, getPidFilePath, isDaemonRunning, } from './utils.js';
12
+ import { logger, puppeteerLogger, redactDaemonArgsForLogging, } from '../utils/logger.js';
13
+ import { DAEMON_SCRIPT_PATH, getDaemonPid, getSocketPath, getPidFilePath, isDaemonRunning, } from './utils.js';
13
14
  const FILE_TIMEOUT = 10_000;
14
15
  const READY_CHECK_INTERVAL = 100;
15
16
  const READY_CHECK_COMMAND_TIMEOUT = 1_000;
16
- /**
17
- * Waits for a file to be created and populated (removed = false) or removed (removed = true).
18
- */
19
- function waitForFile(filePath, removed = false) {
20
- return new Promise((resolve, reject) => {
21
- const check = () => {
22
- const exists = fs.existsSync(filePath);
23
- if (removed) {
24
- return !exists;
25
- }
26
- if (!exists) {
27
- return false;
28
- }
29
- try {
30
- return fs.statSync(filePath).size > 0;
31
- }
32
- catch {
33
- return false;
34
- }
35
- };
36
- if (check()) {
37
- resolve();
38
- return;
39
- }
40
- const timer = setTimeout(() => {
41
- fs.unwatchFile(filePath);
42
- reject(new Error(`Timeout: file ${filePath} ${removed ? 'not removed' : 'not found'} within ${FILE_TIMEOUT}ms`));
43
- }, FILE_TIMEOUT);
44
- fs.watchFile(filePath, { interval: 500 }, () => {
45
- if (check()) {
46
- clearTimeout(timer);
47
- fs.unwatchFile(filePath);
48
- resolve();
49
- }
50
- });
51
- });
52
- }
53
17
  function delay(ms) {
54
18
  return new Promise(resolve => {
55
19
  setTimeout(resolve, ms);
56
20
  });
57
21
  }
22
+ async function waitFor(check, timeoutMessage) {
23
+ const deadline = Date.now() + FILE_TIMEOUT;
24
+ while (Date.now() < deadline) {
25
+ if (check()) {
26
+ return;
27
+ }
28
+ const timeLeft = deadline - Date.now();
29
+ if (timeLeft > 0) {
30
+ await delay(Math.min(READY_CHECK_INTERVAL, timeLeft));
31
+ }
32
+ }
33
+ if (check()) {
34
+ return;
35
+ }
36
+ throw new Error(timeoutMessage);
37
+ }
38
+ /**
39
+ * Waits for a file to be created and populated.
40
+ */
41
+ async function waitForFile(filePath) {
42
+ await waitFor(() => {
43
+ if (!fs.existsSync(filePath)) {
44
+ return false;
45
+ }
46
+ try {
47
+ return fs.statSync(filePath).size > 0;
48
+ }
49
+ catch {
50
+ return false;
51
+ }
52
+ }, `Timeout: file ${filePath} not found within ${FILE_TIMEOUT}ms`);
53
+ }
58
54
  async function waitForDaemonReady(sessionId) {
59
55
  const deadline = Date.now() + FILE_TIMEOUT;
60
56
  let lastError;
@@ -84,9 +80,16 @@ export async function startDaemon(mcpArgs = [], sessionId) {
84
80
  }
85
81
  const pidFilePath = getPidFilePath(sessionId);
86
82
  if (fs.existsSync(pidFilePath)) {
83
+ if (process.platform !== 'win32') {
84
+ const pidDir = path.dirname(pidFilePath);
85
+ if (fs.lstatSync(pidDir).isSymbolicLink() ||
86
+ fs.lstatSync(pidFilePath).isSymbolicLink()) {
87
+ throw new Error(`Refusing to remove daemon PID file through a symbolic link: ${pidFilePath}`);
88
+ }
89
+ }
87
90
  fs.unlinkSync(pidFilePath);
88
91
  }
89
- logger?.('Starting daemon...', ...mcpArgs);
92
+ logger?.('Starting daemon...', ...redactDaemonArgsForLogging(mcpArgs));
90
93
  const child = spawn(process.execPath, [DAEMON_SCRIPT_PATH, ...mcpArgs], {
91
94
  detached: true,
92
95
  stdio: 'ignore',
@@ -111,7 +114,7 @@ export async function sendCommand(command, sessionId, timeout = SEND_COMMAND_TIM
111
114
  const socket = net.createConnection({
112
115
  path: socketPath,
113
116
  });
114
- return new Promise((resolve, reject) => {
117
+ return await new Promise((resolve, reject) => {
115
118
  const timer = setTimeout(() => {
116
119
  socket.destroy();
117
120
  reject(new Error('Timeout waiting for daemon response'));
@@ -120,6 +123,7 @@ export async function sendCommand(command, sessionId, timeout = SEND_COMMAND_TIM
120
123
  transport.onmessage = async (message) => {
121
124
  clearTimeout(timer);
122
125
  logger?.('onmessage', message);
126
+ socket.end();
123
127
  resolve(JSON.parse(message));
124
128
  };
125
129
  socket.on('error', error => {
@@ -141,9 +145,45 @@ export async function stopDaemon(sessionId) {
141
145
  logger?.('Daemon is not running');
142
146
  return;
143
147
  }
148
+ const pid = getDaemonPid(sessionId);
144
149
  const pidFilePath = getPidFilePath(sessionId);
145
- await sendCommand({ method: 'stop' }, sessionId);
146
- await waitForFile(pidFilePath, /*removed=*/ true);
150
+ try {
151
+ await sendCommand({ method: 'stop' }, sessionId);
152
+ }
153
+ catch (error) {
154
+ logger?.('Failed to stop daemon via socket, sending SIGTERM:', error);
155
+ if (pid) {
156
+ try {
157
+ process.kill(pid, 'SIGTERM');
158
+ }
159
+ catch {
160
+ // Ignore if process already exited.
161
+ }
162
+ }
163
+ }
164
+ try {
165
+ await waitFor(() => !isDaemonRunning(sessionId), `Timeout: daemon (pid ${pid}) did not exit within ${FILE_TIMEOUT}ms`);
166
+ fs.rmSync(pidFilePath, { force: true });
167
+ }
168
+ catch (error) {
169
+ if (pid) {
170
+ try {
171
+ process.kill(pid, 'SIGKILL');
172
+ }
173
+ catch {
174
+ // Ignore if process already exited.
175
+ }
176
+ }
177
+ try {
178
+ fs.unlinkSync(pidFilePath);
179
+ }
180
+ catch {
181
+ // Ignore if file already removed.
182
+ }
183
+ if (isDaemonRunning(sessionId)) {
184
+ throw error;
185
+ }
186
+ }
147
187
  }
148
188
  export async function verifyDaemonVersion(sessionId, cliVersion) {
149
189
  if (!isDaemonRunning(sessionId)) {
@@ -4,15 +4,23 @@
4
4
  * Copyright 2026 Google LLC
5
5
  * SPDX-License-Identifier: Apache-2.0
6
6
  */
7
+ import '../utils/polyfill.js';
7
8
  import fs, { constants, openSync, writeSync, closeSync } from 'node:fs';
8
9
  import { createServer } from 'node:net';
9
10
  import os from 'node:os';
10
11
  import path from 'node:path';
11
12
  import process from 'node:process';
12
- import { Client, PipeTransport, StdioClientTransport, } from '../third_party/index.js';
13
- import { logger, puppeteerLogger } from '../utils/logger.js';
13
+ import { BrowserManager } from '../BrowserManager.js';
14
+ import { mcpOptions } from '../config/mcp-options.js';
15
+ import { ConfigParser } from '../config/ConfigParser.js';
16
+ import { McpServer } from '../index.js';
17
+ import { ClearcutLogger } from '../telemetry/ClearcutLogger.js';
18
+ import { computeFlagUsage } from '../telemetry/flagUtils.js';
19
+ import { PipeTransport } from '../third_party/index.js';
20
+ import { logger, puppeteerLogger, saveLogsToFile } from '../utils/logger.js';
21
+ import { setupUnhandledRejectionHandler } from '../utils/errorHandling.js';
14
22
  import { VERSION } from '../version.js';
15
- import { DAEMON_CLIENT_NAME, getPidFilePath, getSocketPath, INDEX_SCRIPT_PATH, IS_WINDOWS, isDaemonRunning, assertValidSessionId, } from './utils.js';
23
+ import { DAEMON_CLIENT_NAME, getPidFilePath, getSocketPath, IS_WINDOWS, isDaemonRunning, assertValidSessionId, } from './utils.js';
16
24
  const sessionId = process.env.CHROME_DEVTOOLS_MCP_SESSION_ID || '';
17
25
  assertValidSessionId(sessionId);
18
26
  logger?.(`Daemon sessionId: ${sessionId}`);
@@ -28,13 +36,18 @@ try {
28
36
  if (os.platform() !== 'win32') {
29
37
  // POSIX specific checks
30
38
  try {
31
- const stats = fs.statSync(pidDir);
32
- // 1. Check Ownership: Ensure the directory is owned by the current user.
39
+ const stats = fs.lstatSync(pidDir);
40
+ // 1. Reject symlinked runtime directories before checking ownership.
41
+ if (stats.isSymbolicLink()) {
42
+ console.error(`[MCP Daemon] Critical error: PID directory ${pidDir} must not be a symbolic link. Possible tampering.`);
43
+ process.exit(1);
44
+ }
45
+ // 2. Check Ownership: Ensure the directory is owned by the current user.
33
46
  if (stats.uid !== currentUserUid) {
34
47
  console.error(`[MCP Daemon] Critical error: PID directory ${pidDir} is not owned by the current user (Expected: ${currentUserUid}, Found: ${stats.uid}). Possible tampering.`);
35
48
  process.exit(1);
36
49
  }
37
- // 2. Check Permissions: Ensure the directory is not group or world-writable.
50
+ // 3. Check Permissions: Ensure the directory is not group or world-writable.
38
51
  // Mode is a number, e.g., 0o700. We check if bits for group/world write are set.
39
52
  const mode = stats.mode;
40
53
  if (mode & constants.S_IWGRP || mode & constants.S_IWOTH) {
@@ -85,43 +98,43 @@ logger?.(`Writing ${process.pid.toString()} to ${pidFilePath}`);
85
98
  const socketPath = getSocketPath(sessionId);
86
99
  const startDate = new Date();
87
100
  const mcpServerArgs = process.argv.slice(2);
88
- let mcpClient = null;
89
- let mcpTransport = null;
101
+ let mcpServer = null;
90
102
  let server = null;
91
- async function setupMCPClient() {
92
- console.log('Setting up MCP client connection...');
93
- // Create stdio transport for chrome-devtools-mcp
94
- mcpTransport = new StdioClientTransport({
95
- command: process.execPath,
96
- args: [INDEX_SCRIPT_PATH, ...mcpServerArgs],
97
- env: process.env,
103
+ async function setupMCPServer() {
104
+ logger?.(`Starting Chrome DevTools MCP Server v${VERSION}`);
105
+ const configParser = new ConfigParser(VERSION);
106
+ const serverConfig = configParser.parseConfig();
107
+ const args = serverConfig.resolved;
108
+ const logFile = args.logFile ? saveLogsToFile(args.logFile) : undefined;
109
+ const browserManager = new BrowserManager(serverConfig, {
110
+ logFile,
98
111
  });
99
- mcpClient = new Client({
100
- name: DAEMON_CLIENT_NAME,
101
- version: VERSION,
102
- }, {
103
- capabilities: {},
112
+ mcpServer = await McpServer.from(serverConfig, {
113
+ browserManager,
114
+ logFile,
104
115
  });
105
- await mcpClient.connect(mcpTransport);
106
- console.log('MCP client connected');
116
+ if (args.watchConfig) {
117
+ mcpServer.watchConfig();
118
+ }
119
+ ClearcutLogger.get()?.setClientName(DAEMON_CLIENT_NAME);
120
+ void ClearcutLogger.get()?.logDailyActiveIfNeeded();
121
+ void ClearcutLogger.get()?.logServerStart(computeFlagUsage(args, mcpOptions));
107
122
  }
108
123
  async function handleRequest(msg) {
109
124
  try {
110
125
  if (msg.method === 'invoke_tool') {
111
- if (!mcpClient) {
112
- throw new Error('MCP client not initialized');
126
+ await started;
127
+ if (!mcpServer) {
128
+ throw new Error('MCP server not initialized');
113
129
  }
114
130
  const { tool, args } = msg;
115
- const result = (await mcpClient.callTool({
116
- name: tool,
117
- arguments: args || {},
118
- }));
131
+ const result = await mcpServer.callTool(tool, args);
119
132
  return {
120
133
  success: true,
121
134
  result: JSON.stringify(result),
122
135
  };
123
136
  }
124
- else if (msg.method === 'stop') {
137
+ if (msg.method === 'stop') {
125
138
  // Ensure we are not interrupting in-progress starting.
126
139
  await started;
127
140
  // Trigger cleanup asynchronously.
@@ -133,7 +146,7 @@ async function handleRequest(msg) {
133
146
  message: 'stopping',
134
147
  };
135
148
  }
136
- else if (msg.method === 'status') {
149
+ if (msg.method === 'status') {
137
150
  await started;
138
151
  const statusResult = {
139
152
  pid: process.pid,
@@ -192,8 +205,7 @@ async function startSocketServer() {
192
205
  }, async () => {
193
206
  console.log(`Daemon server listening on ${socketPath}`);
194
207
  try {
195
- // Setup MCP client
196
- await setupMCPClient();
208
+ await setupMCPServer();
197
209
  resolve();
198
210
  }
199
211
  catch (err) {
@@ -206,23 +218,23 @@ async function startSocketServer() {
206
218
  });
207
219
  });
208
220
  }
221
+ let isCleaningUp = false;
209
222
  async function cleanup(exitCode = 0) {
210
- console.log('Cleaning up daemon...');
211
- try {
212
- await mcpClient?.close();
213
- }
214
- catch (error) {
215
- logger?.('Error closing MCP client:', error);
223
+ if (isCleaningUp) {
224
+ return;
216
225
  }
226
+ isCleaningUp = true;
227
+ console.log('Cleaning up daemon...');
217
228
  try {
218
- await mcpTransport?.close();
229
+ await mcpServer?.close();
219
230
  }
220
231
  catch (error) {
221
- logger?.('Error closing MCP transport:', error);
232
+ logger?.('Error closing MCP server:', error);
222
233
  }
223
- if (server) {
234
+ const activeServer = server;
235
+ if (activeServer) {
224
236
  await new Promise(resolve => {
225
- server.close(() => resolve());
237
+ activeServer.close(() => resolve());
226
238
  });
227
239
  }
228
240
  if (!IS_WINDOWS) {
@@ -234,9 +246,12 @@ async function cleanup(exitCode = 0) {
234
246
  }
235
247
  }
236
248
  logger?.(`unlinking ${pidFilePath}`);
237
- if (fs.existsSync(pidFilePath)) {
249
+ try {
238
250
  fs.unlinkSync(pidFilePath);
239
251
  }
252
+ catch {
253
+ // ignore errors
254
+ }
240
255
  process.exit(exitCode);
241
256
  }
242
257
  // Handle shutdown signals
@@ -254,8 +269,7 @@ process.on('uncaughtException', error => {
254
269
  logger?.('Uncaught exception:', error);
255
270
  void cleanup(1);
256
271
  });
257
- process.on('unhandledRejection', error => {
258
- logger?.('Unhandled rejection:', error);
272
+ setupUnhandledRejectionHandler(() => {
259
273
  void cleanup(1);
260
274
  });
261
275
  // Start the server
@@ -3,13 +3,13 @@
3
3
  * Copyright 2026 Google LLC
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
+ import childProcess from 'node:child_process';
6
7
  import fs from 'node:fs';
7
8
  import os from 'node:os';
8
9
  import path from 'node:path';
9
10
  import process from 'node:process';
10
11
  import { logger } from '../utils/logger.js';
11
12
  export const DAEMON_SCRIPT_PATH = path.join(import.meta.dirname, 'daemon.js');
12
- export const INDEX_SCRIPT_PATH = path.join(import.meta.dirname, '..', 'bin', 'chrome-devtools-mcp.js');
13
13
  const APP_NAME = 'chrome-devtools-mcp';
14
14
  export const DAEMON_CLIENT_NAME = 'chrome-devtools-cli-daemon';
15
15
  export function assertValidSessionId(sessionId) {
@@ -23,7 +23,6 @@ export function assertValidSessionId(sessionId) {
23
23
  // Using these paths due to strict limits on the POSIX socket path length.
24
24
  export function getSocketPath(sessionId) {
25
25
  assertValidSessionId(sessionId);
26
- const uid = os.userInfo().uid;
27
26
  const username = os.userInfo().username;
28
27
  const suffix = sessionId ? `-${sessionId}` : '';
29
28
  const appName = APP_NAME + suffix;
@@ -33,14 +32,7 @@ export function getSocketPath(sessionId) {
33
32
  // Append username to prevent cross-user named pipe squatting
34
33
  return path.join('\\\\.\\pipe', `${appName}-${username}`, 'server.sock');
35
34
  }
36
- // 1. Try XDG_RUNTIME_DIR (Linux standard, sometimes macOS)
37
- if (process.env.XDG_RUNTIME_DIR) {
38
- return path.join(process.env.XDG_RUNTIME_DIR, appName, 'server.sock');
39
- }
40
- // 2. macOS/Unix Fallback: Use /tmp/
41
- // We use /tmp/ because it is much shorter than ~/Library/Application Support/
42
- // and keeps us well under the 104-character limit.
43
- return path.join('/tmp', `${appName}-${uid}.sock`);
35
+ return path.join(getRuntimeHome(sessionId), 'server.sock');
44
36
  }
45
37
  export function getRuntimeHome(sessionId) {
46
38
  assertValidSessionId(sessionId);
@@ -86,16 +78,57 @@ export function getDaemonPid(sessionId) {
86
78
  return null;
87
79
  }
88
80
  }
81
+ const verifiedDaemonPids = new Map();
82
+ function getProcessCommandLine(pid) {
83
+ if (process.platform === 'linux' && fs.existsSync('/proc')) {
84
+ return fs
85
+ .readFileSync(`/proc/${pid}/cmdline`, 'utf-8')
86
+ .replaceAll('\0', ' ');
87
+ }
88
+ if (IS_WINDOWS) {
89
+ return childProcess.execFileSync('powershell.exe', [
90
+ '-NoProfile',
91
+ '-NonInteractive',
92
+ '-Command',
93
+ `(Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}").CommandLine`,
94
+ ], {
95
+ encoding: 'utf-8',
96
+ stdio: ['ignore', 'pipe', 'ignore'],
97
+ windowsHide: true,
98
+ });
99
+ }
100
+ return childProcess.execFileSync('ps', ['-p', String(pid), '-o', 'command='], {
101
+ encoding: 'utf-8',
102
+ stdio: ['ignore', 'pipe', 'ignore'],
103
+ });
104
+ }
105
+ function isDaemonProcess(pid) {
106
+ const cached = verifiedDaemonPids.get(pid);
107
+ if (cached !== undefined) {
108
+ return cached;
109
+ }
110
+ try {
111
+ const commandLine = getProcessCommandLine(pid).trim();
112
+ const isDaemon = commandLine === '' || /[\\/]daemon[\\/]daemon\.js/.test(commandLine);
113
+ verifiedDaemonPids.set(pid, isDaemon);
114
+ return isDaemon;
115
+ }
116
+ catch {
117
+ verifiedDaemonPids.set(pid, true);
118
+ return true;
119
+ }
120
+ }
89
121
  export function isDaemonRunning(sessionId) {
90
122
  assertValidSessionId(sessionId);
91
123
  const pid = getDaemonPid(sessionId);
92
124
  if (pid) {
93
125
  try {
94
126
  process.kill(pid, 0); // Throws if process doesn't exist
95
- return true;
127
+ return isDaemonProcess(pid);
96
128
  }
97
129
  catch {
98
130
  // Process is dead, stale PID file. Proceed with startup.
131
+ verifiedDaemonPids.delete(pid);
99
132
  }
100
133
  }
101
134
  return false;
@@ -128,7 +161,8 @@ export function serializeArgs(options, argv) {
128
161
  }
129
162
  }
130
163
  else {
131
- args.push(`--${kebabKey}=${String(value)}`);
164
+ const serializedValue = typeof value === 'object' ? JSON.stringify(value) : String(value);
165
+ args.push(`--${kebabKey}=${serializedValue}`);
132
166
  }
133
167
  }
134
168
  return args;