chrome-devtools-mcp 1.7.0 → 1.9.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 (74) hide show
  1. package/README.md +20 -874
  2. package/build/src/McpContext.js +98 -45
  3. package/build/src/McpPage.js +10 -4
  4. package/build/src/McpResponse.js +22 -4
  5. package/build/src/ToolHandler.js +81 -57
  6. package/build/src/bin/chrome-devtools-mcp-main.js +4 -4
  7. package/build/src/bin/chrome-devtools.js +29 -30
  8. package/build/src/browser.js +8 -17
  9. package/build/src/{PageCollector.js → collectors/PageCollector.js} +7 -7
  10. package/build/src/{ServiceWorkerCollector.js → collectors/ServiceWorkerCollector.js} +1 -1
  11. package/build/src/config/browser-options.js +123 -0
  12. package/build/src/config/category-options.js +80 -0
  13. package/build/src/{bin/chrome-devtools-cli-options.js → config/cli-options.js} +380 -25
  14. package/build/src/{bin/chrome-devtools-mcp-cli-options.js → config/mcp-options.js} +113 -148
  15. package/build/src/daemon/client.js +11 -2
  16. package/build/src/daemon/daemon.js +2 -2
  17. package/build/src/daemon/utils.js +6 -0
  18. package/build/src/devtools/DevtoolsUtils.js +29 -35
  19. package/build/src/formatters/ConsoleFormatter.js +43 -10
  20. package/build/src/formatters/HeapSnapshotFormatter.js +10 -2
  21. package/build/src/formatters/IssueFormatter.js +1 -1
  22. package/build/src/formatters/NetworkFormatter.js +12 -9
  23. package/build/src/index.js +185 -91
  24. package/build/src/{HeapSnapshotManager.js → processors/HeapSnapshotManager.js} +21 -5
  25. package/build/src/{trace-processing/parse.js → processors/PerformanceTrace.js} +1 -1
  26. package/build/src/telemetry/ClearcutLogger.js +18 -5
  27. package/build/src/telemetry/flagUtils.js +4 -3
  28. package/build/src/telemetry/types.js +4 -0
  29. package/build/src/third_party/THIRD_PARTY_NOTICES +8 -65
  30. package/build/src/third_party/bundled-packages.json +4 -4
  31. package/build/src/third_party/devtools-formatter-worker.js +22 -0
  32. package/build/src/third_party/devtools-heap-snapshot-worker.js +296 -42
  33. package/build/src/third_party/index.js +38728 -37176
  34. package/build/src/third_party/issue-descriptions/connectionAllowlistEmbeddingRequirementNotSatisfied.md +26 -0
  35. package/build/src/third_party/issue-descriptions/connectionAllowlistIFrameAttributeLoosensEmbeddingRequirement.md +19 -0
  36. package/build/src/third_party/issue-descriptions/connectionAllowlistInvalidAllowConnectionAllowlistFrom.md +21 -0
  37. package/build/src/third_party/issue-descriptions/federatedAuthRequestAccountsBlockedByConnectionAllowlist.md +1 -0
  38. package/build/src/third_party/issue-descriptions/federatedAuthRequestConfigBlockedByConnectionAllowlist.md +1 -0
  39. package/build/src/third_party/issue-descriptions/federatedAuthRequestIdTokenBlockedByConnectionAllowlist.md +1 -0
  40. package/build/src/third_party/issue-descriptions/federatedAuthRequestWellKnownBlockedByConnectionAllowlist.md +1 -0
  41. package/build/src/tools/ToolDefinition.js +15 -0
  42. package/build/src/tools/categories.js +2 -5
  43. package/build/src/tools/console.js +9 -3
  44. package/build/src/tools/emulation.js +2 -2
  45. package/build/src/tools/extensions.js +7 -5
  46. package/build/src/tools/input.js +26 -16
  47. package/build/src/tools/lighthouse.js +3 -1
  48. package/build/src/tools/memory.js +112 -16
  49. package/build/src/tools/network.js +7 -4
  50. package/build/src/tools/pages.js +34 -23
  51. package/build/src/tools/performance.js +16 -25
  52. package/build/src/tools/pwa.js +128 -0
  53. package/build/src/tools/screencast.js +7 -4
  54. package/build/src/tools/screenshot.js +42 -9
  55. package/build/src/tools/script.js +29 -8
  56. package/build/src/tools/slim/tools.js +43 -35
  57. package/build/src/tools/snapshot.js +5 -3
  58. package/build/src/tools/thirdPartyDeveloper.js +2 -2
  59. package/build/src/tools/tools.js +2 -0
  60. package/build/src/tools/webmcp.js +2 -2
  61. package/build/src/{WaitForHelper.js → utils/WaitForHelper.js} +74 -38
  62. package/build/src/utils/bytes.js +105 -0
  63. package/build/src/utils/logger.js +25 -11
  64. package/build/src/utils/url.js +73 -0
  65. package/build/src/version.js +1 -1
  66. package/package.json +21 -13
  67. package/skills/a11y-debugging/SKILL.md +2 -0
  68. package/skills/chrome-devtools/SKILL.md +5 -4
  69. package/skills/chrome-devtools-cli/SKILL.md +103 -64
  70. package/skills/cookie-debugging/SKILL.md +149 -0
  71. package/skills/debug-optimize-lcp/SKILL.md +9 -9
  72. package/skills/memory-leak-debugging/SKILL.md +6 -2
  73. package/skills/troubleshooting/SKILL.md +1 -0
  74. package/build/src/utils/string.js +0 -37
@@ -4,7 +4,7 @@
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
6
  import { createStackTraceForConsoleMessage, SymbolizedError, } from '../devtools/DevtoolsUtils.js';
7
- import { UncaughtError } from '../PageCollector.js';
7
+ import { UncaughtError } from '../collectors/PageCollector.js';
8
8
  import * as DevTools from '../third_party/index.js';
9
9
  export class ConsoleFormatter {
10
10
  #id;
@@ -14,6 +14,7 @@ export class ConsoleFormatter {
14
14
  #resolvedArgs;
15
15
  #stack;
16
16
  #cause;
17
+ #includeStackInConcise;
17
18
  isIgnored;
18
19
  constructor(params) {
19
20
  this.#id = params.id;
@@ -23,6 +24,7 @@ export class ConsoleFormatter {
23
24
  this.#resolvedArgs = params.resolvedArgs ?? [];
24
25
  this.#stack = params.stack;
25
26
  this.#cause = params.cause;
27
+ this.#includeStackInConcise = params.includeStackInConcise ?? false;
26
28
  this.isIgnored = params.isIgnored;
27
29
  }
28
30
  static async from(msg, options) {
@@ -45,7 +47,7 @@ export class ConsoleFormatter {
45
47
  devTools: options?.devTools,
46
48
  details: msg.details,
47
49
  targetId: msg.targetId,
48
- includeStackAndCause: options?.fetchDetailedData,
50
+ includeStackAndCause: options?.fetchDetailedData || options?.fetchStackTrace,
49
51
  resolvedStackTraceForTesting: options?.resolvedStackTraceForTesting,
50
52
  resolvedCauseForTesting: options?.resolvedCauseForTesting,
51
53
  });
@@ -55,6 +57,7 @@ export class ConsoleFormatter {
55
57
  text: error.message,
56
58
  stack: error.stackTrace,
57
59
  cause: error.cause,
60
+ includeStackInConcise: options.fetchStackTrace,
58
61
  isIgnored,
59
62
  });
60
63
  }
@@ -86,7 +89,8 @@ export class ConsoleFormatter {
86
89
  if (options.resolvedStackTraceForTesting) {
87
90
  stack = options.resolvedStackTraceForTesting;
88
91
  }
89
- else if (options.fetchDetailedData && options.devTools) {
92
+ else if ((options.fetchDetailedData || options.fetchStackTrace) &&
93
+ options.devTools) {
90
94
  try {
91
95
  stack = await createStackTraceForConsoleMessage(options.devTools, msg);
92
96
  }
@@ -101,6 +105,7 @@ export class ConsoleFormatter {
101
105
  argCount: resolvedArgs.length || msg.args().length,
102
106
  resolvedArgs,
103
107
  stack,
108
+ includeStackInConcise: options.fetchStackTrace,
104
109
  isIgnored,
105
110
  });
106
111
  }
@@ -112,6 +117,15 @@ export class ConsoleFormatter {
112
117
  toStringDetailed() {
113
118
  return convertConsoleMessageConciseDetailedToString(this.toJSONDetailed());
114
119
  }
120
+ #getText() {
121
+ if (this.#text) {
122
+ return this.#text;
123
+ }
124
+ if (this.#resolvedArgs.length > 0) {
125
+ return formatArg(this.#resolvedArgs[0], this);
126
+ }
127
+ return '';
128
+ }
115
129
  #getArgs() {
116
130
  if (this.#resolvedArgs.length > 0) {
117
131
  const args = [...this.#resolvedArgs];
@@ -124,12 +138,18 @@ export class ConsoleFormatter {
124
138
  return [];
125
139
  }
126
140
  toJSON() {
127
- return {
141
+ const json = {
128
142
  type: this.#type,
129
- text: this.#text,
143
+ text: this.#getText(),
130
144
  argsCount: this.#argCount,
131
145
  id: this.#id,
132
146
  };
147
+ if (this.#includeStackInConcise && this.#stack) {
148
+ json.stackTrace = formatStackTrace(this.#stack, this.#cause, this, {
149
+ includeNote: false,
150
+ });
151
+ }
152
+ return json;
133
153
  }
134
154
  /**
135
155
  * Groups consecutive messages with the same type, text, and argument count.
@@ -143,7 +163,7 @@ export class ConsoleFormatter {
143
163
  prev.message instanceof ConsoleFormatter &&
144
164
  msg instanceof ConsoleFormatter &&
145
165
  prev.message.#type === msg.#type &&
146
- prev.message.#text === msg.#text &&
166
+ prev.message.#getText() === msg.#getText() &&
147
167
  prev.message.#argCount === msg.#argCount) {
148
168
  prev.count++;
149
169
  }
@@ -157,6 +177,9 @@ export class ConsoleFormatter {
157
177
  type: message.#type,
158
178
  text: message.#text,
159
179
  argCount: message.#argCount,
180
+ stack: message.#stack,
181
+ cause: message.#cause,
182
+ includeStackInConcise: message.#includeStackInConcise,
160
183
  isIgnored: message.isIgnored,
161
184
  }, count)
162
185
  : message);
@@ -165,7 +188,7 @@ export class ConsoleFormatter {
165
188
  return {
166
189
  id: this.#id,
167
190
  type: this.#type,
168
- text: this.#text,
191
+ text: this.#getText(),
169
192
  argsCount: this.#argCount,
170
193
  args: this.#getArgs().map(arg => formatArg(arg, this)),
171
194
  stackTrace: this.#stack
@@ -191,7 +214,15 @@ export class GroupedConsoleFormatter extends ConsoleFormatter {
191
214
  }
192
215
  function convertConsoleMessageConciseToString(msg) {
193
216
  const countSuffix = msg.count && msg.count > 1 ? ` [${msg.count} times]` : '';
194
- return `msgid=${msg.id} [${msg.type}] ${msg.text} (${msg.argsCount} args)${countSuffix}`;
217
+ const messageLine = `msgid=${msg.id} [${msg.type}] ${msg.text} (${msg.argsCount} args)${countSuffix}`;
218
+ if (!msg.stackTrace) {
219
+ return messageLine;
220
+ }
221
+ const indentedStackTrace = msg.stackTrace
222
+ .split('\n')
223
+ .map(line => ` ${line}`)
224
+ .join('\n');
225
+ return `${messageLine}\n${indentedStackTrace}`;
195
226
  }
196
227
  function convertConsoleMessageConciseDetailedToString(msg) {
197
228
  const result = [
@@ -227,14 +258,16 @@ function formatArg(arg, formatter) {
227
258
  return typeof arg === 'object' ? JSON.stringify(arg) : String(arg);
228
259
  }
229
260
  const STACK_TRACE_MAX_LINES = 50;
230
- function formatStackTrace(stackTrace, cause, formatter) {
261
+ function formatStackTrace(stackTrace, cause, formatter, options) {
231
262
  const lines = formatStackTraceInner(stackTrace, cause, formatter);
232
263
  const includedLines = lines.slice(0, STACK_TRACE_MAX_LINES);
233
264
  const reminderCount = lines.length - includedLines.length;
234
265
  return [
235
266
  ...includedLines,
236
267
  reminderCount > 0 ? `... and ${reminderCount} more frames` : '',
237
- 'Note: line and column numbers use 1-based indexing',
268
+ options?.includeNote === false
269
+ ? ''
270
+ : 'Note: line and column numbers use 1-based indexing',
238
271
  ]
239
272
  .filter(line => !!line)
240
273
  .join('\n');
@@ -33,7 +33,7 @@ export class HeapSnapshotFormatter {
33
33
  lines.push('nodeId,nodeName,type,distance,selfSize,retainedSize');
34
34
  }
35
35
  else if (isEdgeLike(firstItem)) {
36
- lines.push('name,type,nodeId,nodeName');
36
+ lines.push('name,type,nodeId,nodeName,selfSize,retainedSize');
37
37
  }
38
38
  }
39
39
  for (const item of items) {
@@ -41,7 +41,7 @@ export class HeapSnapshotFormatter {
41
41
  lines.push(`${item.id},${item.name},${item.type},${item.distance},${formatBytesToKb(item.selfSize)},${formatBytesToKb(item.retainedSize)}`);
42
42
  }
43
43
  else if (isEdgeLike(item)) {
44
- lines.push(`${item.name},${item.type},${item.node.id},${item.node.name}`);
44
+ lines.push(`${item.name},${item.type},${item.node.id},${item.node.name},${formatBytesToKb(item.node.selfSize)},${formatBytesToKb(item.node.retainedSize)}`);
45
45
  }
46
46
  }
47
47
  return lines.join('\n');
@@ -89,6 +89,14 @@ export class HeapSnapshotFormatter {
89
89
  lines.push(`Unattributed Size: ${formatBytesToKb(sizes.noAttributionSize)}`);
90
90
  return lines.join('\n');
91
91
  }
92
+ static formatRetainedByContextSummary(summary) {
93
+ const lines = [];
94
+ lines.push(`Context count: ${summary.contextCount}`);
95
+ lines.push(`Retained by context size: ${formatBytesToKb(summary.retainedByContextSize)} (${summary.retainedByContextCount} objects)`);
96
+ lines.push(`Not retained by context size: ${formatBytesToKb(summary.notRetainedByContextSize)} (${summary.notRetainedByContextCount} objects)`);
97
+ lines.push(`Total size: ${formatBytesToKb(summary.totalSize)}`);
98
+ return lines.join('\n');
99
+ }
92
100
  #getSortedAggregates() {
93
101
  return Object.values(this.#aggregates).sort((a, b) => b.maxRet - a.maxRet);
94
102
  }
@@ -144,7 +144,7 @@ export class IssueFormatter {
144
144
  }
145
145
  }
146
146
  function convertIssueConciseToString(issue) {
147
- return `msgid=${issue.id} [issue] ${issue.title} (count: ${issue.count})`;
147
+ return `msgid=${issue.id} [issue] ${issue.title ?? 'Unknown Issue'} (count: ${issue.count})`;
148
148
  }
149
149
  function convertIssueDetailedToString(issue) {
150
150
  const result = [];
@@ -6,6 +6,7 @@
6
6
  import { isUtf8 } from 'node:buffer';
7
7
  import { DevTools, } from '../third_party/index.js';
8
8
  const BODY_CONTEXT_SIZE_LIMIT = 10000;
9
+ const URL_CONTEXT_SIZE_LIMIT = 255;
9
10
  export class NetworkFormatter {
10
11
  #request;
11
12
  #options;
@@ -38,7 +39,7 @@ export class NetworkFormatter {
38
39
  const requestBodyNotAvailableMessage = '<Request body not available anymore>';
39
40
  if (this.#options.requestFilePath) {
40
41
  if (!this.#options.saveFile) {
41
- throw new Error('saveFile is not provided');
42
+ throw new Error('Unable to save the request body to a file: no saveFile callback was configured.');
42
43
  }
43
44
  if (data) {
44
45
  const result = await this.#options.saveFile(Buffer.from(data), this.#options.requestFilePath, '.network-request');
@@ -65,7 +66,7 @@ export class NetworkFormatter {
65
66
  try {
66
67
  const buffer = await response.buffer();
67
68
  if (!this.#options.saveFile) {
68
- throw new Error('saveFile is not provided');
69
+ throw new Error('Unable to save the response body to a file: no saveFile callback was configured.');
69
70
  }
70
71
  const result = await this.#options.saveFile(buffer, this.#options.responseFilePath, '.network-response');
71
72
  this.#responseBodyFilePath = result.filename;
@@ -86,7 +87,7 @@ export class NetworkFormatter {
86
87
  return convertNetworkRequestConciseToString(this.toJSON());
87
88
  }
88
89
  toStringDetailed() {
89
- return converNetworkRequestDetailedToStringDetailed(this.toJSONDetailed());
90
+ return convertNetworkRequestDetailedToStringDetailed(this.toJSONDetailed());
90
91
  }
91
92
  toJSON() {
92
93
  return {
@@ -178,22 +179,24 @@ function getSizeLimitedString(text, sizeLimit) {
178
179
  return text;
179
180
  }
180
181
  function convertNetworkRequestConciseToString(data) {
181
- // TODO truncate the URL
182
- return `reqid=${data.requestId} ${data.method} ${data.url} [${data.status}]${data.selectedInDevToolsUI ? ` [selected in the DevTools Network panel]` : ''}`;
182
+ // Long URLs (e.g., data: URLs) bloat the concise list output. The full URL
183
+ // remains available via the detailed view and the structured content.
184
+ const url = getSizeLimitedString(data.url, URL_CONTEXT_SIZE_LIMIT);
185
+ return `reqid=${data.requestId} ${data.method} ${url} [${data.status}]${data.selectedInDevToolsUI ? ` [selected in the DevTools Network panel]` : ''}`;
183
186
  }
184
- function formatHeadlers(headers) {
187
+ function formatHeaders(headers) {
185
188
  const response = [];
186
189
  for (const [name, value] of Object.entries(headers)) {
187
190
  response.push(`- ${name}:${value}`);
188
191
  }
189
192
  return response;
190
193
  }
191
- function converNetworkRequestDetailedToStringDetailed(data) {
194
+ function convertNetworkRequestDetailedToStringDetailed(data) {
192
195
  const response = [];
193
196
  response.push(`## Request ${data.url}`);
194
197
  response.push(`Status: ${data.status}`);
195
198
  response.push(`### Request Headers`);
196
- for (const line of formatHeadlers(data.requestHeaders)) {
199
+ for (const line of formatHeaders(data.requestHeaders)) {
197
200
  response.push(line);
198
201
  }
199
202
  if (data.requestBody) {
@@ -206,7 +209,7 @@ function converNetworkRequestDetailedToStringDetailed(data) {
206
209
  }
207
210
  if (data.responseHeaders) {
208
211
  response.push(`### Response Headers`);
209
- for (const line of formatHeadlers(data.responseHeaders)) {
212
+ for (const line of formatHeaders(data.responseHeaders)) {
210
213
  response.push(line);
211
214
  }
212
215
  }
@@ -3,135 +3,224 @@
3
3
  * Copyright 2026 Google LLC
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
+ import path from 'node:path';
7
+ import { pathToFileURL } from 'node:url';
6
8
  import { ensureBrowserConnected, ensureBrowserLaunched } from './browser.js';
7
9
  import { loadIssueDescriptions } from './devtools/issueDescriptions.js';
8
10
  import { McpContext } from './McpContext.js';
9
11
  import { ClearcutLogger } from './telemetry/ClearcutLogger.js';
10
12
  import { FilePersistence } from './telemetry/persistence.js';
11
- import { McpServer, SetLevelRequestSchema, ListRootsResultSchema, RootsListChangedNotificationSchema, } from './third_party/index.js';
13
+ import { McpServer as SdkMcpServer, SetLevelRequestSchema, ListRootsResultSchema, RootsListChangedNotificationSchema, Mutex, puppeteer, } from './third_party/index.js';
12
14
  import { ToolHandler } from './ToolHandler.js';
13
15
  import { createTools } from './tools/tools.js';
14
16
  import { logger } from './utils/logger.js';
15
- import { Mutex } from './third_party/index.js';
16
17
  import { VERSION } from './version.js';
17
- export { buildFlag } from './ToolHandler.js';
18
- export async function createMcpServer(serverArgs, options) {
19
- if (serverArgs.usageStatistics) {
20
- ClearcutLogger.initialize({
21
- persistence: new FilePersistence(),
22
- logFile: serverArgs.logFile,
23
- appVersion: VERSION,
24
- clearcutEndpoint: serverArgs.clearcutEndpoint,
25
- clearcutForceFlushIntervalMs: serverArgs.clearcutForceFlushIntervalMs,
26
- clearcutIncludePidHeader: serverArgs.clearcutIncludePidHeader,
18
+ puppeteer.setFollowSymlinks(false);
19
+ /**
20
+ * Timeout for a `roots/list` that a tool call is waiting on, matching the 5s
21
+ * default used for page operations. `getContext()` awaits it while
22
+ * `ToolHandler` holds the tool mutex, so leaving it unbounded lets a client
23
+ * that negotiates `roots` but does not answer block every tool for the SDK's
24
+ * default of 60s. Background refreshes are not bounded by this, so roots a
25
+ * slow client sends late still land.
26
+ */
27
+ const ROOTS_REQUEST_TIMEOUT = 5_000;
28
+ export class McpServer {
29
+ server;
30
+ #serverArgs;
31
+ #options;
32
+ #context;
33
+ /**
34
+ * Client roots stay valid across browser reconnects and only the client can
35
+ * invalidate them through a `roots/list_changed` notification. CLI-configured
36
+ * roots are read from `#serverArgs` when combining roots.
37
+ */
38
+ #lastClientRoots;
39
+ #toolMutex = new Mutex();
40
+ constructor(serverArgs, options = {}) {
41
+ this.#serverArgs = serverArgs;
42
+ this.#options = options;
43
+ if (this.#serverArgs.usageStatistics) {
44
+ ClearcutLogger.initialize({
45
+ persistence: new FilePersistence(),
46
+ logFile: this.#serverArgs.logFile,
47
+ appVersion: VERSION,
48
+ clearcutEndpoint: this.#serverArgs.clearcutEndpoint,
49
+ clearcutForceFlushIntervalMs: this.#serverArgs.clearcutForceFlushIntervalMs,
50
+ clearcutIncludePidHeader: this.#serverArgs.clearcutIncludePidHeader,
51
+ });
52
+ }
53
+ this.server = new SdkMcpServer({
54
+ name: 'chrome_devtools',
55
+ title: 'Chrome DevTools MCP server',
56
+ version: VERSION,
57
+ }, { capabilities: { logging: {} } });
58
+ this.server.server.setRequestHandler(SetLevelRequestSchema, () => {
59
+ return {};
60
+ });
61
+ this.server.server.oninitialized = () => {
62
+ const clientName = this.server.server.getClientVersion()?.name;
63
+ if (clientName) {
64
+ ClearcutLogger.get()?.setClientName(clientName);
65
+ }
66
+ if (this.server.server.getClientCapabilities()?.roots) {
67
+ void this.#updateRoots();
68
+ this.server.server.setNotificationHandler(RootsListChangedNotificationSchema, () => {
69
+ void this.#updateRoots();
70
+ });
71
+ }
72
+ else if (!this.#serverArgs.allowUnrestrictedPaths &&
73
+ (this.#serverArgs.filesystemRoot ?? []).length === 0) {
74
+ console.warn('[chrome-devtools-mcp] The connecting client did not negotiate the MCP roots ' +
75
+ 'capability. File-writing tools will be restricted to the OS temp directory. ' +
76
+ 'To restore the previous unrestricted behavior, start the server with ' +
77
+ '--allow-unrestricted-paths.');
78
+ }
79
+ };
80
+ }
81
+ async connect(transport) {
82
+ return await this.server.connect(transport);
83
+ }
84
+ /**
85
+ * Closes the MCP connection and disposes internal context/listeners.
86
+ */
87
+ async close() {
88
+ this.#context?.dispose();
89
+ this.#context = undefined;
90
+ await this.server.close();
91
+ }
92
+ [Symbol.dispose]() {
93
+ this.close().catch(() => {
94
+ // TODO: wire up the logger
95
+ });
96
+ }
97
+ async [Symbol.asyncDispose]() {
98
+ await this.close();
99
+ }
100
+ static async from(serverArgs, options = {}) {
101
+ const server = new McpServer(serverArgs, options);
102
+ await server.#init();
103
+ return server;
104
+ }
105
+ async #init() {
106
+ const tools = createTools(this.#serverArgs);
107
+ for (const tool of tools) {
108
+ this.#registerTool(tool);
109
+ }
110
+ await loadIssueDescriptions();
111
+ }
112
+ #combinedRoots() {
113
+ const configuredRoots = (this.#serverArgs.allowUnrestrictedPaths
114
+ ? []
115
+ : (this.#serverArgs.filesystemRoot ?? [])).map(root => {
116
+ const rootPath = path.resolve(String(root));
117
+ return {
118
+ uri: pathToFileURL(rootPath).href,
119
+ name: path.basename(rootPath) || rootPath,
120
+ };
27
121
  });
122
+ if (configuredRoots.length === 0 && this.#lastClientRoots === undefined) {
123
+ return undefined;
124
+ }
125
+ return [...configuredRoots, ...(this.#lastClientRoots ?? [])];
28
126
  }
29
- const server = new McpServer({
30
- name: 'chrome_devtools',
31
- title: 'Chrome DevTools MCP server',
32
- version: VERSION,
33
- }, { capabilities: { logging: {} } });
34
- server.server.setRequestHandler(SetLevelRequestSchema, () => {
35
- return {};
36
- });
37
- const updateRoots = async () => {
38
- if (!server.server.getClientCapabilities()?.roots) {
127
+ /**
128
+ * `timeout` is only passed where a tool call is waiting on the result – the
129
+ * background refreshes below block nobody, so bounding them would just discard
130
+ * roots a slow client was about to send
131
+ */
132
+ async #updateRoots(timeout) {
133
+ if (!this.server.server.getClientCapabilities()?.roots) {
39
134
  return;
40
135
  }
41
136
  try {
42
- const roots = await server.server.request({ method: 'roots/list' }, ListRootsResultSchema);
43
- context?.setRoots(roots.roots);
137
+ const roots = await this.server.server.request({ method: 'roots/list' }, ListRootsResultSchema, timeout === undefined ? undefined : { timeout });
138
+ this.#lastClientRoots = roots.roots;
139
+ this.#context?.setRoots(this.#combinedRoots());
44
140
  }
45
141
  catch (e) {
46
142
  logger?.('Failed to list roots', e);
47
143
  }
48
- };
49
- server.server.oninitialized = () => {
50
- const clientName = server.server.getClientVersion()?.name;
51
- if (clientName) {
52
- ClearcutLogger.get()?.setClientName(clientName);
53
- }
54
- if (server.server.getClientCapabilities()?.roots) {
55
- void updateRoots();
56
- server.server.setNotificationHandler(RootsListChangedNotificationSchema, () => {
57
- void updateRoots();
58
- });
59
- }
60
- else if (!serverArgs.allowUnrestrictedPaths) {
61
- console.warn('[chrome-devtools-mcp] The connecting client did not negotiate the MCP roots ' +
62
- 'capability. File-writing tools will be restricted to the OS temp directory. ' +
63
- 'To restore the previous unrestricted behavior, start the server with ' +
64
- '--allow-unrestricted-paths.');
65
- }
66
- };
67
- let context;
68
- async function getContext() {
69
- const chromeArgs = (serverArgs.chromeArg ?? []).map(String);
70
- const ignoreDefaultChromeArgs = (serverArgs.ignoreDefaultChromeArg ?? []).map(String);
71
- if (serverArgs.proxyServer) {
72
- chromeArgs.push(`--proxy-server=${serverArgs.proxyServer}`);
144
+ }
145
+ async #getContext() {
146
+ const chromeArgs = (this.#serverArgs.chromeArg ?? []).map(String);
147
+ const ignoreDefaultChromeArgs = (this.#serverArgs.ignoreDefaultChromeArg ?? []).map(String);
148
+ if (this.#serverArgs.proxyServer) {
149
+ chromeArgs.push(`--proxy-server=${this.#serverArgs.proxyServer}`);
73
150
  }
74
- const devtools = serverArgs.experimentalDevtools ?? false;
75
- const blocklist = serverArgs.blockedUrlPattern
76
- ? serverArgs.blockedUrlPattern.map(String)
151
+ const devtools = this.#serverArgs.experimentalDevtools ?? false;
152
+ const blocklist = this.#serverArgs.blockedUrlPattern
153
+ ? this.#serverArgs.blockedUrlPattern.map(String)
77
154
  : undefined;
78
- const allowlist = serverArgs.allowedUrlPattern
79
- ? serverArgs.allowedUrlPattern.map(String)
155
+ const allowlist = this.#serverArgs.allowedUrlPattern
156
+ ? this.#serverArgs.allowedUrlPattern.map(String)
80
157
  : undefined;
81
- const browser = serverArgs.browserUrl || serverArgs.wsEndpoint || serverArgs.autoConnect
158
+ const channel = this.#serverArgs.channel;
159
+ const browser = this.#serverArgs.browserUrl ||
160
+ this.#serverArgs.wsEndpoint ||
161
+ this.#serverArgs.autoConnect
82
162
  ? await ensureBrowserConnected({
83
- browserURL: serverArgs.browserUrl,
84
- wsEndpoint: serverArgs.wsEndpoint,
85
- wsHeaders: serverArgs.wsHeaders,
163
+ browserURL: this.#serverArgs.browserUrl,
164
+ wsEndpoint: this.#serverArgs.wsEndpoint,
165
+ wsHeaders: this.#serverArgs.wsHeaders,
86
166
  // Important: only pass channel, if autoConnect is true.
87
- channel: serverArgs.autoConnect
88
- ? serverArgs.channel
89
- : undefined,
90
- userDataDir: serverArgs.userDataDir,
167
+ channel: this.#serverArgs.autoConnect ? channel : undefined,
168
+ userDataDir: this.#serverArgs.userDataDir,
91
169
  devtools,
92
170
  blocklist,
93
171
  allowlist,
94
172
  })
95
173
  : await ensureBrowserLaunched({
96
- headless: serverArgs.headless,
97
- executablePath: serverArgs.executablePath,
98
- channel: serverArgs.channel,
99
- isolated: serverArgs.isolated ?? false,
100
- userDataDir: serverArgs.userDataDir,
101
- logFile: options.logFile,
102
- viewport: serverArgs.viewport,
174
+ headless: this.#serverArgs.headless,
175
+ executablePath: this.#serverArgs.executablePath,
176
+ channel,
177
+ isolated: this.#serverArgs.isolated ?? false,
178
+ userDataDir: this.#serverArgs.userDataDir,
179
+ logFile: this.#options.logFile,
180
+ viewport: this.#serverArgs.viewport,
103
181
  chromeArgs,
104
182
  ignoreDefaultChromeArgs,
105
- acceptInsecureCerts: serverArgs.acceptInsecureCerts,
183
+ acceptInsecureCerts: this.#serverArgs.acceptInsecureCerts,
106
184
  devtools,
107
- enableExtensions: serverArgs.categoryExtensions,
108
- viaCli: serverArgs.viaCli,
185
+ enableExtensions: this.#serverArgs.categoryExtensions,
186
+ viaCli: this.#serverArgs.viaCli,
109
187
  blocklist,
110
188
  allowlist,
111
189
  });
112
- if (context?.browser !== browser) {
113
- context?.dispose();
114
- context = await McpContext.from(browser, logger, {
190
+ if (this.#context?.browser !== browser) {
191
+ this.#context?.dispose();
192
+ this.#context = await McpContext.from(browser, logger, {
115
193
  experimentalDevToolsDebugging: devtools,
116
- experimentalIncludeAllPages: serverArgs.experimentalIncludeAllPages,
117
- performanceCrux: serverArgs.performanceCrux,
194
+ experimentalIncludeAllPages: this.#serverArgs.experimentalIncludeAllPages,
195
+ performanceCrux: this.#serverArgs.performanceCrux,
196
+ sourceMaps: this.#serverArgs.sourceMaps,
118
197
  allowList: allowlist,
119
198
  blocklist: blocklist,
120
- allowUnrestrictedPaths: serverArgs.allowUnrestrictedPaths,
199
+ allowUnrestrictedPaths: this.#serverArgs.allowUnrestrictedPaths,
121
200
  // Surfaces a one-time note in the next response after a reconnect.
122
- reconnected: context !== undefined,
201
+ reconnected: this.#context !== undefined,
202
+ categoryExtensions: this.#serverArgs.categoryExtensions,
123
203
  });
124
- await updateRoots();
204
+ this.#context.setRoots(this.#combinedRoots());
205
+ if (this.#lastClientRoots === undefined) {
206
+ // Nothing listed yet, so this call has to wait – bounded, since it is
207
+ // holding the tool mutex, and a later background refresh still lands
208
+ await this.#updateRoots(ROOTS_REQUEST_TIMEOUT);
209
+ }
210
+ else {
211
+ // Carry the known roots over and refresh out of band, so a reconnect
212
+ // never pays for a client round-trip
213
+ void this.#updateRoots();
214
+ }
125
215
  }
126
- return context;
216
+ return this.#context;
127
217
  }
128
- const toolMutex = new Mutex();
129
- function registerTool(tool) {
130
- const toolHandler = new ToolHandler(tool, serverArgs, getContext, toolMutex);
218
+ #registerTool(tool) {
219
+ const toolHandler = new ToolHandler(tool, this.#serverArgs, () => this.#getContext(), this.#toolMutex);
131
220
  if (!toolHandler.shouldRegister) {
132
221
  return;
133
222
  }
134
- server.registerTool(tool.name, {
223
+ this.server.registerTool(tool.name, {
135
224
  description: tool.description,
136
225
  inputSchema: toolHandler.registeredInputSchema,
137
226
  annotations: tool.annotations,
@@ -139,12 +228,17 @@ export async function createMcpServer(serverArgs, options) {
139
228
  return await toolHandler.handle(params);
140
229
  });
141
230
  }
142
- const tools = createTools(serverArgs);
143
- for (const tool of tools) {
144
- registerTool(tool);
145
- }
146
- await loadIssueDescriptions();
147
- return { server };
231
+ }
232
+ /**
233
+ * Creates and initializes a Chrome DevTools MCP server instance.
234
+ *
235
+ * Maintained as a public API for backwards compatibility because external
236
+ * consumers and integrations rely on `createMcpServer()`. For new code,
237
+ * prefer using `McpServer.from(serverArgs, options)`.
238
+ */
239
+ export async function createMcpServer(serverArgs, options = {}) {
240
+ const server = await McpServer.from(serverArgs, options);
241
+ return { server: server.server };
148
242
  }
149
243
  export const logDisclaimers = (args) => {
150
244
  console.error(`chrome-devtools-mcp exposes content of the browser instance to the MCP clients allowing them to inspect,