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
@@ -58,74 +58,95 @@ var __disposeResources = (this && this.__disposeResources) || (function (Suppres
58
58
  import { McpResponse } from './McpResponse.js';
59
59
  import { SlimMcpResponse } from './SlimMcpResponse.js';
60
60
  import { ClearcutLogger } from './telemetry/ClearcutLogger.js';
61
- import { zod } from './third_party/index.js';
61
+ import { ProtocolError, ProtocolErrorCode, zod, } from './third_party/index.js';
62
62
  import { labels } from './tools/categories.js';
63
63
  import { categoryToFlagName } from './config/category-options.js';
64
+ import { isAvailableInMode, isBrowserlessTool, isPageScopedTool, isSlimTool, } from './tools/ToolDefinition.js';
65
+ import { getErrorMessage } from './utils/errorHandling.js';
64
66
  import { logger } from './utils/logger.js';
65
67
  import { fileURLToPath, pathToFileURL } from 'node:url';
66
- import { isLocalhost } from './utils/url.js';
68
+ import { isDeepStrictEqual } from 'node:util';
69
+ import { isLocalBrowserEndpoint } from './utils/url.js';
70
+ /**
71
+ * Upper bound on how long a tool call may wait to acquire the browser
72
+ * (connect/launch and McpContext initialization). A connect attempt on a
73
+ * half-open socket can hang without ever failing; this bound turns that into
74
+ * a clear error and abandons the attempt so the next call starts fresh.
75
+ *
76
+ * This does not bound the tool's own work. A slow but valid call (a long
77
+ * `wait_for` timeout, an `evaluate_script` awaiting a slow promise, a
78
+ * Lighthouse audit) must finish on its own terms without the browser being
79
+ * closed underneath it. A transport that dies mid-call is detected by the
80
+ * WebSocket keep-alive configured in BrowserManager#connect(), which rejects
81
+ * the in-flight CDP calls and fires `disconnected`.
82
+ */
83
+ export const TOOL_CALL_TIMEOUT_MS = 60_000;
84
+ class ToolCallTimeoutError extends Error {
85
+ }
67
86
  function buildDisabledMessage(toolName, flag, categoryLabel) {
68
87
  const reason = categoryLabel
69
88
  ? `is in category ${categoryLabel} which`
70
89
  : `requires ${flag.startsWith('--experimental') ? 'experimental feature' : 'flag'} ${flag} and`;
71
90
  return `Tool ${toolName} ${reason} is currently disabled. Enable it by running chrome-devtools start ${flag}=true. For more information check the README.`;
72
91
  }
73
- function getToolStatusInfo(tool, serverArgs) {
92
+ function getDisabledReason(tool, serverArgs) {
93
+ if (!isAvailableInMode(tool, serverArgs)) {
94
+ return isSlimTool(tool)
95
+ ? `Tool ${tool.name} is only available with --slim.`
96
+ : `Tool ${tool.name} is not available with --slim.`;
97
+ }
74
98
  const category = tool.annotations.category;
75
99
  if (category) {
76
100
  const flag = categoryToFlagName(category);
77
101
  if (!serverArgs[flag]) {
78
- return {
79
- disabled: true,
80
- reason: buildDisabledMessage(tool.name, `--${flag}`, labels[category]),
81
- };
102
+ return buildDisabledMessage(tool.name, `--${flag}`, labels[category]);
82
103
  }
83
104
  }
84
105
  for (const condition of tool.annotations.conditions || []) {
85
106
  if (!serverArgs[condition]) {
86
- return {
87
- disabled: true,
88
- reason: buildDisabledMessage(tool.name, `--${condition}`),
89
- };
107
+ return buildDisabledMessage(tool.name, `--${condition}`);
90
108
  }
91
109
  }
92
- return { disabled: false };
93
- }
94
- function isPageScopedTool(tool) {
95
- return 'pageScoped' in tool && tool.pageScoped === true;
110
+ return undefined;
96
111
  }
97
- function formatArgumentNames(names) {
98
- return names.map(name => `"${name}"`).join(', ');
99
- }
100
- function buildUnknownArgumentsMessage(toolName, unknownArgumentNames, expectedArgumentNames) {
101
- const unknownLabel = unknownArgumentNames.length === 1 ? 'argument' : 'arguments';
102
- const expectedArguments = expectedArgumentNames.length
103
- ? `Expected arguments: ${formatArgumentNames(expectedArgumentNames)}.`
104
- : 'This tool does not accept any arguments.';
105
- const correction = unknownArgumentNames.length === 1 ? 'Remove it' : 'Remove them';
106
- return `Unknown ${unknownLabel} for tool "${toolName}": ${formatArgumentNames(unknownArgumentNames)}. ${expectedArguments} ${correction} and retry.`;
107
- }
108
- async function validateAndResolvePathOrUrl(filePathOrUrl, context) {
112
+ async function validateAndResolvePathOrUrl(filePathOrUrl, context, allowUrl) {
113
+ if (filePathOrUrl.trim().length === 0) {
114
+ return undefined;
115
+ }
116
+ let url;
109
117
  try {
110
- const url = new URL(filePathOrUrl);
118
+ url = new URL(filePathOrUrl);
119
+ }
120
+ catch {
121
+ // Not a URL; fall through and validate it as a regular file path.
122
+ }
123
+ if (url) {
111
124
  if (url.protocol === 'file:') {
112
125
  return pathToFileURL(await context.validatePath(fileURLToPath(url))).href;
113
126
  }
114
- else if (['http:', 'https:', 'ws:', 'wss:'].includes(url.protocol)) {
115
- return filePathOrUrl;
127
+ if (['http:', 'https:', 'ws:', 'wss:'].includes(url.protocol)) {
128
+ // Only pass a remote URL through unchanged for parameters whose sink
129
+ // actually fetches the URL or hands it to the browser (allowUrl). For a
130
+ // filesystem-path parameter, a value that merely looks like an http/ws
131
+ // URL must still be rejected outright: `new URL()` accepts
132
+ // `http://x/../../etc/passwd`, and the downstream filesystem API (e.g.
133
+ // Puppeteer's uploadFile) path.resolve()s that non-absolute string into
134
+ // an absolute host path, which would bypass validatePath (workspace
135
+ // roots and the temp-dir fallback) if it fell through to it unchanged.
136
+ if (allowUrl) {
137
+ return filePathOrUrl;
138
+ }
139
+ throw new Error('This parameter expects a file path, not a URL.');
116
140
  }
117
141
  }
118
- catch {
119
- // Suppress parsing errors for regular file paths.
120
- }
121
142
  return await context.validatePath(filePathOrUrl);
122
143
  }
123
- function isLocalBrowser(context) {
124
- if (context.browser.process()) {
144
+ function isLocalBrowser(browser) {
145
+ if (browser.process()) {
125
146
  return true;
126
147
  }
127
- const wsEndpoint = context.browser.wsEndpoint();
128
- if (wsEndpoint && isLocalhost(wsEndpoint)) {
148
+ const wsEndpoint = browser.wsEndpoint();
149
+ if (wsEndpoint && isLocalBrowserEndpoint(wsEndpoint)) {
129
150
  return true;
130
151
  }
131
152
  return false;
@@ -142,19 +163,26 @@ function shouldValidateFile(option, isLocal) {
142
163
  }
143
164
  return false;
144
165
  }
145
- async function validateToolFiles(tool, params, context) {
146
- const isLocal = isLocalBrowser(context);
166
+ /**
167
+ * `isLocal` tells whether files are accessed on the machine the server runs on,
168
+ * which is always the case for browserless tools.
169
+ */
170
+ async function validateToolFiles(tool, params, context, isLocal) {
147
171
  for (const [key, option] of Object.entries(tool.verifyFilesSchema)) {
148
172
  if (shouldValidateFile(option, isLocal)) {
173
+ const allowUrl = option !== true && option.allowUrl === true;
149
174
  const val = params[key];
150
175
  if (typeof val === 'string') {
151
- params[key] = await validateAndResolvePathOrUrl(val, context);
176
+ params[key] = await validateAndResolvePathOrUrl(val, context, allowUrl);
152
177
  }
153
178
  else if (Array.isArray(val)) {
154
179
  const updated = [];
155
180
  for (const item of val) {
156
181
  if (typeof item === 'string') {
157
- updated.push(await validateAndResolvePathOrUrl(item, context));
182
+ const resolved = await validateAndResolvePathOrUrl(item, context, allowUrl);
183
+ if (resolved !== undefined) {
184
+ updated.push(resolved);
185
+ }
158
186
  }
159
187
  else {
160
188
  throw new Error('Unexpected non-string value as a file path or URL');
@@ -165,111 +193,240 @@ async function validateToolFiles(tool, params, context) {
165
193
  }
166
194
  }
167
195
  }
196
+ function toInputJsonSchema(schema) {
197
+ return zod.toJSONSchema(schema, { io: 'input', unrepresentable: 'any' });
198
+ }
199
+ function formatValidationError(toolName, error) {
200
+ const details = error.issues
201
+ .map(issue => `${issue.path.length > 0 ? `${issue.path.join('.')}: ` : ''}${issue.message}`)
202
+ .join(', ');
203
+ return `Input validation error: Invalid arguments for tool ${toolName}: ${details}`;
204
+ }
205
+ function errorResult(text) {
206
+ return {
207
+ content: [{ type: 'text', text }],
208
+ isError: true,
209
+ };
210
+ }
211
+ /**
212
+ * The page id a page tool call targets, or `undefined` when the call targets
213
+ * the selected page. `args` can be the raw or the parsed arguments.
214
+ */
215
+ function routedPageId(tool, serverArgs, args) {
216
+ if (!serverArgs.pageIdRouting || isSlimTool(tool)) {
217
+ return undefined;
218
+ }
219
+ const { pageId } = args;
220
+ return typeof pageId === 'number' && Number.isInteger(pageId)
221
+ ? pageId
222
+ : undefined;
223
+ }
168
224
  export class ToolHandler {
169
- tool;
170
- serverArgs;
171
225
  getContext;
172
- toolMutex;
173
- inputSchema;
174
- registeredInputSchema;
175
- disabled;
176
- disabledReason;
177
- constructor(tool, serverArgs, getContext, toolMutex) {
178
- this.tool = tool;
179
- this.serverArgs = serverArgs;
226
+ abandonPendingBrowserAttemptOnTimeout;
227
+ #tool;
228
+ #config;
229
+ #registeredInputSchema;
230
+ #disabled = false;
231
+ #disabledReason;
232
+ constructor(tool, config, getContext, abandonPendingBrowserAttemptOnTimeout) {
180
233
  this.getContext = getContext;
181
- this.toolMutex = toolMutex;
182
- const { disabled, reason } = getToolStatusInfo(tool, serverArgs);
183
- this.disabledReason = reason;
184
- this.disabled = disabled && !serverArgs.viaCli;
185
- this.inputSchema = tool.schema;
186
- this.registeredInputSchema = zod.object(this.inputSchema).loose();
234
+ this.abandonPendingBrowserAttemptOnTimeout = abandonPendingBrowserAttemptOnTimeout;
235
+ this.#tool = tool;
236
+ this.#config = config;
237
+ this.#registeredInputSchema = zod.object(tool.schema).strict();
238
+ this.#updateStatus(tool);
239
+ }
240
+ get registeredInputSchema() {
241
+ return this.#registeredInputSchema;
242
+ }
243
+ /**
244
+ * Whether the tool is hidden from the client.
245
+ */
246
+ get disabled() {
247
+ return this.#disabled;
248
+ }
249
+ #updateStatus(tool) {
250
+ const serverArgs = this.#config.resolved;
251
+ this.#disabledReason = getDisabledReason(tool, serverArgs);
252
+ this.#disabled =
253
+ Boolean(this.#disabledReason) &&
254
+ (!isAvailableInMode(tool, serverArgs) || !serverArgs.viaCli);
187
255
  }
188
- unknownArgumentNames(params) {
189
- return Object.keys(params).filter(key => !Object.hasOwn(this.inputSchema, key));
256
+ /**
257
+ * Replaces the tool definition and re-evaluates its status against the
258
+ * current server config. Callers must pause the task runner, so calls that
259
+ * are already waiting run with the new state. Returns true if the tool
260
+ * listing visible to the client changed.
261
+ */
262
+ update(tool) {
263
+ const previousTool = this.#tool;
264
+ const previousDisabled = this.#disabled;
265
+ const previousInputSchema = this.#registeredInputSchema;
266
+ const nextInputSchema = zod.object(tool.schema).strict();
267
+ this.#tool = tool;
268
+ this.#registeredInputSchema = nextInputSchema;
269
+ this.#updateStatus(tool);
270
+ if (previousDisabled !== this.#disabled) {
271
+ return true;
272
+ }
273
+ if (this.#disabled) {
274
+ return false;
275
+ }
276
+ return (previousTool.description !== tool.description ||
277
+ !isDeepStrictEqual(previousTool.annotations, tool.annotations) ||
278
+ !isDeepStrictEqual(toInputJsonSchema(previousInputSchema), toInputJsonSchema(nextInputSchema)));
279
+ }
280
+ /**
281
+ * Races a promise against TOOL_CALL_TIMEOUT_MS, calling onTimeout() if the
282
+ * timer wins. The loser of the race is left running — there is no way to
283
+ * cancel a pending connect/launch — but since nothing is left awaiting it,
284
+ * it cannot block subsequent tool calls.
285
+ */
286
+ async #raceWithTimeout(promise, onTimeout) {
287
+ const timeoutError = new ToolCallTimeoutError(`Tool "${this.#tool.name}" timed out after ${TOOL_CALL_TIMEOUT_MS}ms waiting for the browser connection to be established. The connection attempt will be retried automatically on the next tool call.`);
288
+ let timer;
289
+ const timeout = new Promise((_, reject) => {
290
+ timer = setTimeout(() => reject(timeoutError), TOOL_CALL_TIMEOUT_MS);
291
+ timer.unref?.();
292
+ });
293
+ try {
294
+ return await Promise.race([promise, timeout]);
295
+ }
296
+ catch (err) {
297
+ if (err === timeoutError) {
298
+ onTimeout();
299
+ }
300
+ throw err;
301
+ }
302
+ finally {
303
+ clearTimeout(timer);
304
+ }
190
305
  }
191
- handle = async (params) => {
306
+ #dataFormat(serverArgs) {
307
+ // --experimentalDataFormat takes precedence over the legacy
308
+ // --experimentalToonFormat.
309
+ return (serverArgs.experimentalDataFormat ??
310
+ (serverArgs.experimentalToonFormat ? 'toon' : 'default'));
311
+ }
312
+ /**
313
+ * Browserless tools never establish a browser connection, so they also never
314
+ * wait for one under TOOL_CALL_TIMEOUT_MS.
315
+ */
316
+ async #runBrowserlessTool(tool, params, response, context) {
317
+ try {
318
+ await validateToolFiles(tool, params, context, true);
319
+ await tool.handler({ params }, response, context);
320
+ }
321
+ catch (err) {
322
+ response.setError(err);
323
+ }
324
+ return await response.handle(context, this.#dataFormat(this.#config.resolved));
325
+ }
326
+ async #runBrowserTool(tool, params, response, context, onTelemetryData) {
327
+ // ensureBrowser() has no cancellation mechanism, so this timeout only
328
+ // stops us from waiting — the attempt itself keeps running abandoned.
329
+ // abandonPendingBrowserAttemptOnTimeout() tells BrowserManager to
330
+ // discard that attempt if it succeeds later instead of handing it to a
331
+ // subsequent caller — see BrowserManager#abandonPendingAttempt()'s doc
332
+ // comment for the full mechanism.
333
+ const browser = await this.#raceWithTimeout(context.ensureBrowser(), () => this.abandonPendingBrowserAttemptOnTimeout());
334
+ logger?.(`${tool.name} browser: resolved`);
335
+ if (context.consumeReconnectNotice()) {
336
+ response.setReconnectNotice();
337
+ }
338
+ let page;
339
+ try {
340
+ await validateToolFiles(tool, params, context, isLocalBrowser(browser));
341
+ if (isPageScopedTool(tool)) {
342
+ const pageId = routedPageId(tool, this.#config.resolved, params);
343
+ page =
344
+ pageId !== undefined
345
+ ? context.getPageById(pageId)
346
+ : context.getSelectedMcpPage();
347
+ await page?.init({ emulateFocus: true });
348
+ response.setPage(page);
349
+ if (tool.blockedByDialog) {
350
+ page.throwIfDialogOpen();
351
+ }
352
+ await tool.handler({
353
+ params,
354
+ page,
355
+ }, response, context);
356
+ }
357
+ else {
358
+ await tool.handler({
359
+ params,
360
+ }, response, context);
361
+ }
362
+ }
363
+ catch (err) {
364
+ response.setError(err);
365
+ }
366
+ onTelemetryData(await context.getDevToolsData(page), context.getSelectedMcpPageUrl(page));
367
+ return await response.handle(context, this.#dataFormat(this.#config.resolved));
368
+ }
369
+ /**
370
+ * The queue the call runs on. `'none'` tools run outside the runner.
371
+ * `'page'` tools run on the queue of the page named by `rawArgs.pageId`
372
+ * when page id routing applies; every other call runs on the context
373
+ * queue.
374
+ */
375
+ #queueFor(context, rawArgs) {
376
+ const tool = this.#tool;
377
+ switch (tool.concurrency) {
378
+ case 'none':
379
+ return undefined;
380
+ case 'page': {
381
+ const pageId = routedPageId(tool, this.#config.resolved, rawArgs);
382
+ return pageId !== undefined
383
+ ? context.pageTaskQueue(pageId)
384
+ : context.taskQueue;
385
+ }
386
+ default:
387
+ return context.taskQueue;
388
+ }
389
+ }
390
+ handle = async (rawArgs = {}, options) => {
192
391
  const env_1 = { stack: [], error: void 0, hasError: false };
193
392
  try {
194
- const _guard = __addDisposableResource(env_1, await this.toolMutex.acquire(), false);
195
- if (this.disabledReason) {
196
- return {
197
- content: [
198
- {
199
- type: 'text',
200
- text: this.disabledReason,
201
- },
202
- ],
203
- isError: true,
204
- };
393
+ const context = await this.getContext();
394
+ let queueGuard;
395
+ try {
396
+ queueGuard = await this.#queueFor(context, rawArgs)?.scheduleTask();
205
397
  }
206
- const unknownArgumentNames = this.unknownArgumentNames(params);
207
- if (unknownArgumentNames.length) {
208
- return {
209
- content: [
210
- {
211
- type: 'text',
212
- text: buildUnknownArgumentsMessage(this.tool.name, unknownArgumentNames, Object.keys(this.inputSchema)),
213
- },
214
- ],
215
- isError: true,
216
- };
398
+ catch (err) {
399
+ // The queue was disposed while the call waited, e.g. the page closed.
400
+ return errorResult(getErrorMessage(err));
401
+ }
402
+ const guard = __addDisposableResource(env_1, queueGuard, false);
403
+ if (options?.viaMcp && this.#disabled) {
404
+ throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Tool ${this.#tool.name} disabled`);
217
405
  }
406
+ if (this.#disabledReason) {
407
+ return errorResult(this.#disabledReason);
408
+ }
409
+ const tool = this.#tool;
410
+ const parseResult = this.#registeredInputSchema.safeParse(rawArgs);
411
+ if (!parseResult.success) {
412
+ return errorResult(formatValidationError(tool.name, parseResult.error));
413
+ }
414
+ const params = parseResult.data;
218
415
  const startTime = Date.now();
219
416
  let success = false;
220
417
  let devToolsData;
221
418
  let pageUrl;
222
419
  try {
223
- logger?.(`${this.tool.name} request: ${JSON.stringify(params, null, ' ')}`);
224
- const context = await this.getContext();
225
- logger?.(`${this.tool.name} context: resolved`);
226
- const response = this.serverArgs.slim
227
- ? new SlimMcpResponse(this.serverArgs)
228
- : new McpResponse(this.serverArgs);
229
- response.setRedactNetworkHeaders(this.serverArgs.redactNetworkHeaders);
230
- if (context.consumeReconnectNotice()) {
231
- response.setReconnectNotice();
232
- }
233
- let page;
234
- try {
235
- await validateToolFiles(this.tool, params, context);
236
- if (isPageScopedTool(this.tool)) {
237
- const pageId = typeof params.pageId === 'number' ? params.pageId : undefined;
238
- page =
239
- this.serverArgs.pageIdRouting &&
240
- pageId !== undefined &&
241
- !this.serverArgs.slim
242
- ? context.getPageById(pageId)
243
- : context.getSelectedMcpPage();
244
- response.setPage(page);
245
- if (this.tool.blockedByDialog) {
246
- page.throwIfDialogOpen();
247
- }
248
- await this.tool.handler({
249
- params,
250
- page,
251
- }, response, context);
252
- }
253
- else {
254
- await this.tool.handler({
255
- params,
256
- }, response, context);
257
- }
258
- }
259
- catch (err) {
260
- response.setError(err);
261
- }
262
- devToolsData = await context.getDevToolsData(page);
263
- pageUrl = context.getSelectedMcpPageUrl(page);
264
- // Resolve data format: --experimentalDataFormat takes precedence, fall back to legacy --experimentalToonFormat
265
- let dataFormat = 'default';
266
- if (this.serverArgs.experimentalDataFormat) {
267
- dataFormat = this.serverArgs.experimentalDataFormat;
268
- }
269
- else if (this.serverArgs.experimentalToonFormat) {
270
- dataFormat = 'toon';
271
- }
272
- const { content, structuredContent } = await response.handle(context, dataFormat);
420
+ logger?.(`${tool.name} request: ${JSON.stringify(params, null, ' ')}`);
421
+ const response = isSlimTool(tool)
422
+ ? new SlimMcpResponse(this.#config)
423
+ : new McpResponse(this.#config);
424
+ const { content, structuredContent } = isBrowserlessTool(tool)
425
+ ? await this.#runBrowserlessTool(tool, params, response, context)
426
+ : await this.#runBrowserTool(tool, params, response, context, (data, url) => {
427
+ devToolsData = data;
428
+ pageUrl = url;
429
+ });
273
430
  const result = {
274
431
  content,
275
432
  };
@@ -277,32 +434,34 @@ export class ToolHandler {
277
434
  result.isError = true;
278
435
  }
279
436
  success = true;
280
- if (this.serverArgs.experimentalStructuredContent) {
437
+ if (this.#config.resolved.experimentalStructuredContent) {
281
438
  result.structuredContent = structuredContent;
282
439
  }
283
440
  return result;
284
441
  }
285
442
  catch (err) {
286
- logger?.(`${this.tool.name} error:`, err, err?.stack);
443
+ logger?.(`${tool.name} error:`, err, err?.stack);
287
444
  let errorText = err && 'message' in err ? err.message : String(err);
288
- if ('cause' in err && err.cause) {
289
- errorText += `\nCause: ${err.cause.message}`;
445
+ let cause = err && typeof err === 'object' && 'cause' in err
446
+ ? err.cause
447
+ : undefined;
448
+ const seenCauses = new Set([err]);
449
+ while (cause &&
450
+ typeof cause === 'object' &&
451
+ !seenCauses.has(cause) &&
452
+ 'message' in cause &&
453
+ typeof cause.message === 'string') {
454
+ seenCauses.add(cause);
455
+ errorText += `\nCause: ${cause.message}`;
456
+ cause = 'cause' in cause ? cause.cause : undefined;
290
457
  }
291
- return {
292
- content: [
293
- {
294
- type: 'text',
295
- text: errorText,
296
- },
297
- ],
298
- isError: true,
299
- };
458
+ return errorResult(errorText);
300
459
  }
301
460
  finally {
302
461
  void ClearcutLogger.get()?.logToolInvocation({
303
- toolName: this.tool.name,
462
+ toolName: tool.name,
304
463
  params,
305
- schema: this.inputSchema,
464
+ schema: tool.schema,
306
465
  success,
307
466
  latencyMs: Date.now() - startTime,
308
467
  devToolsData,
@@ -6,27 +6,30 @@
6
6
  import '../utils/polyfill.js';
7
7
  import process from 'node:process';
8
8
  import { BrowserManager } from '../BrowserManager.js';
9
- import { McpServer, logDisclaimers } from '../index.js';
9
+ import { McpServer } from '../index.js';
10
10
  import { ClearcutLogger } from '../telemetry/ClearcutLogger.js';
11
11
  import { computeFlagUsage } from '../telemetry/flagUtils.js';
12
12
  import { StdioServerTransport } from '../third_party/index.js';
13
13
  import { checkForUpdates } from '../utils/check-for-updates.js';
14
+ import { logDisclaimers } from '../utils/disclaimers.js';
14
15
  import { logger, saveLogsToFile } from '../utils/logger.js';
16
+ import { setupUnhandledRejectionHandler } from '../utils/errorHandling.js';
15
17
  import { VERSION } from '../version.js';
16
- import { mcpOptions, parseArguments } from '../config/mcp-options.js';
18
+ import { mcpOptions } from '../config/mcp-options.js';
19
+ import { ConfigParser } from '../config/ConfigParser.js';
17
20
  await checkForUpdates('Run `npm install chrome-devtools-mcp@latest` to update.');
18
- export const args = parseArguments(VERSION);
21
+ const configParser = new ConfigParser(VERSION);
22
+ const serverConfig = configParser.parseConfig();
23
+ const args = serverConfig.resolved;
19
24
  const logFile = args.logFile ? saveLogsToFile(args.logFile) : undefined;
20
- if (process.env['CHROME_DEVTOOLS_MCP_CRASH_ON_UNCAUGHT'] !== 'true') {
21
- process.on('unhandledRejection', (reason, promise) => {
22
- logger?.('Unhandled promise rejection', promise, reason);
23
- });
24
- }
25
+ setupUnhandledRejectionHandler(() => {
26
+ process.exit(1);
27
+ });
25
28
  logger?.(`Starting Chrome DevTools MCP Server v${VERSION}`);
26
- const browserManager = new BrowserManager(args, {
29
+ const browserManager = new BrowserManager(serverConfig, {
27
30
  logFile,
28
31
  });
29
- const serverPromise = McpServer.from(args, {
32
+ const serverPromise = McpServer.from(serverConfig, {
30
33
  browserManager,
31
34
  });
32
35
  // Shutdown on stdin EOF (stdio MCP convention — the client closes the
@@ -4,8 +4,8 @@
4
4
  * Copyright 2025 Google LLC
5
5
  * SPDX-License-Identifier: Apache-2.0
6
6
  */
7
- process.title = 'chrome-devtools-mcp';
8
7
  import { version } from 'node:process';
8
+ process.title = 'chrome-devtools-mcp';
9
9
  const [major, minor] = version.substring(1).split('.').map(Number);
10
10
  if (major === 20 && minor < 19) {
11
11
  console.error(`ERROR: \`chrome-devtools-mcp\` does not support Node ${process.version}. Please upgrade to Node 20.19.0 LTS or a newer LTS.`);