opera-devtools-mcp 0.6.1 → 0.8.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 (96) hide show
  1. package/README.md +1 -1
  2. package/build/src/McpContext.js +78 -41
  3. package/build/src/McpPage.js +5 -1
  4. package/build/src/ToolHandler.js +54 -76
  5. package/build/src/bin/chrome-devtools-mcp-main.js +4 -4
  6. package/build/src/bin/chrome-devtools.js +56 -124
  7. package/build/src/bin/opera-browser-cli.js +102 -0
  8. package/build/src/bin/opera-devtools-cli-options.js +1 -1
  9. package/build/src/bin/opera-devtools-mcp-cli-options.js +1 -1
  10. package/build/src/bin/opera-devtools-mcp.js +20 -1
  11. package/build/src/browser.js +23 -25
  12. package/build/src/config/browser-options.js +126 -0
  13. package/build/src/config/category-options.js +81 -0
  14. package/build/src/{bin/chrome-devtools-cli-options.js → config/cli-options.js} +368 -26
  15. package/build/src/{bin/chrome-devtools-mcp-cli-options.js → config/mcp-options.js} +143 -164
  16. package/build/src/daemon/client.js +55 -40
  17. package/build/src/daemon/daemon.js +62 -39
  18. package/build/src/daemon/utils.js +6 -0
  19. package/build/src/devtools/DevtoolsUtils.js +27 -21
  20. package/build/src/formatters/NetworkFormatter.js +5 -2
  21. package/build/src/index.js +166 -100
  22. package/build/src/opera/branding.js +4 -2
  23. package/build/src/opera/browserActivity.js +62 -0
  24. package/build/src/opera/browserCleanup.js +123 -0
  25. package/build/src/opera/browserErrors.js +66 -0
  26. package/build/src/opera/browserFlags.js +184 -38
  27. package/build/src/opera/browserTarget.js +513 -0
  28. package/build/src/opera/cdpErrors.js +391 -0
  29. package/build/src/opera/cliCommands.js +378 -0
  30. package/build/src/opera/cliOutput.js +284 -0
  31. package/build/src/opera/compactSnapshot.js +525 -0
  32. package/build/src/opera/config.js +166 -0
  33. package/build/src/opera/daemonLifecycle.js +257 -0
  34. package/build/src/opera/daemonLog.js +103 -0
  35. package/build/src/opera/daemonPidFile.js +83 -0
  36. package/build/src/opera/daemonShutdown.js +66 -0
  37. package/build/src/opera/daemonSocket.js +87 -0
  38. package/build/src/opera/daemonStreaming.js +130 -0
  39. package/build/src/opera/daemonToolCall.js +26 -0
  40. package/build/src/opera/detect.js +114 -0
  41. package/build/src/opera/doctor.js +317 -0
  42. package/build/src/opera/envConfig.js +229 -0
  43. package/build/src/opera/launcherNotice.js +116 -0
  44. package/build/src/opera/legacyBridgeCleanup.js +297 -0
  45. package/build/src/opera/logs.js +133 -0
  46. package/build/src/opera/mcpServerSupervisor.js +128 -0
  47. package/build/src/opera/migrationShared.js +164 -0
  48. package/build/src/opera/operaPages.js +56 -0
  49. package/build/src/opera/pageIdRouting.js +35 -0
  50. package/build/src/opera/pageRecovery.js +53 -0
  51. package/build/src/opera/profile.js +270 -0
  52. package/build/src/opera/refArgs.js +36 -0
  53. package/build/src/opera/serviceWorkerRetry.js +46 -4
  54. package/build/src/opera/setup.js +290 -0
  55. package/build/src/opera/skills/SKILL.md +160 -0
  56. package/build/src/opera/streamingTools.js +73 -0
  57. package/build/src/opera/suggestions.js +67 -0
  58. package/build/src/opera/toolHandlerHooks.js +25 -1
  59. package/build/src/opera/tools/opera.js +107 -38
  60. package/build/src/opera/urlResolver.js +69 -0
  61. package/build/src/opera/webStorageWarning.js +92 -0
  62. package/build/src/processors/HeapSnapshotManager.js +12 -0
  63. package/build/src/telemetry/ClearcutLogger.js +19 -6
  64. package/build/src/telemetry/transformation.js +4 -0
  65. package/build/src/telemetry/types.js +4 -0
  66. package/build/src/third_party/THIRD_PARTY_NOTICES +5 -5
  67. package/build/src/third_party/bundled-packages.json +3 -3
  68. package/build/src/third_party/devtools-formatter-worker.js +23 -0
  69. package/build/src/third_party/devtools-heap-snapshot-worker.js +101 -20
  70. package/build/src/third_party/index.js +15460 -14256
  71. package/build/src/third_party/issue-descriptions/federatedAuthRequestAccountsBlockedByConnectionAllowlist.md +1 -0
  72. package/build/src/third_party/issue-descriptions/federatedAuthRequestConfigBlockedByConnectionAllowlist.md +1 -0
  73. package/build/src/third_party/issue-descriptions/federatedAuthRequestIdTokenBlockedByConnectionAllowlist.md +1 -0
  74. package/build/src/third_party/issue-descriptions/federatedAuthRequestWellKnownBlockedByConnectionAllowlist.md +1 -0
  75. package/build/src/tools/ToolDefinition.js +15 -0
  76. package/build/src/tools/categories.js +0 -6
  77. package/build/src/tools/comments.js +90 -0
  78. package/build/src/tools/console.js +1 -1
  79. package/build/src/tools/emulation.js +1 -1
  80. package/build/src/tools/extensions.js +1 -1
  81. package/build/src/tools/memory.js +60 -6
  82. package/build/src/tools/network.js +2 -2
  83. package/build/src/tools/pages.js +26 -15
  84. package/build/src/tools/performance.js +4 -3
  85. package/build/src/tools/screencast.js +3 -2
  86. package/build/src/tools/screenshot.js +39 -8
  87. package/build/src/tools/script.js +17 -4
  88. package/build/src/tools/slim/tools.js +41 -33
  89. package/build/src/tools/snapshot.js +1 -1
  90. package/build/src/tools/tools.js +2 -0
  91. package/build/src/utils/WaitForHelper.js +12 -1
  92. package/build/src/utils/bytes.js +105 -0
  93. package/build/src/utils/url.js +79 -0
  94. package/build/src/version.js +1 -1
  95. package/package.json +29 -8
  96. package/build/src/bin/opera-devtools.js +0 -10
@@ -5,110 +5,17 @@
5
5
  *
6
6
  * Modified by Opera Software AS.
7
7
  */
8
- import { CACHE_DIR_NAME, ENV_NO_USAGE_STATISTICS, MCP_BIN_NAME, PACKAGE_NAME, REPO_URL, } from '../opera/branding.js';
8
+ import { ENV_NO_USAGE_STATISTICS, PACKAGE_NAME, REPO_URL, } from '../opera/branding.js';
9
9
  import { PERFORMANCE_CRUX_DEFAULT, PERFORMANCE_CRUX_DESCRIPTION, USAGE_STATISTICS_DEFAULT, USAGE_STATISTICS_DESCRIPTION, } from '../opera/policy.js';
10
10
  import { yargs, hideBin } from '../third_party/index.js';
11
- export const cliOptions = {
12
- autoConnect: {
13
- type: 'boolean',
14
- description: 'If specified, automatically connects to a browser (Chrome 144+) running locally from the user data directory identified by the channel param (default channel is stable). Requires the remote debugging server to be started in the Chrome instance via chrome://inspect/#remote-debugging.',
15
- conflicts: ['isolated', 'executablePath'],
16
- default: false,
17
- coerce: (value) => {
18
- if (!value) {
19
- return;
20
- }
21
- return value;
22
- },
23
- },
24
- browserUrl: {
25
- type: 'string',
26
- description: `Connect to a running, debuggable Chrome instance (e.g. \`http://127.0.0.1:9222\`). For more details see: ${REPO_URL}#connecting-to-a-running-chrome-instance.`,
27
- alias: 'u',
28
- conflicts: ['wsEndpoint'],
29
- coerce: (url) => {
30
- if (!url) {
31
- return;
32
- }
33
- try {
34
- new URL(url);
35
- }
36
- catch {
37
- throw new Error(`Provided browserUrl ${url} is not valid URL.`);
38
- }
39
- return url;
40
- },
41
- },
42
- wsEndpoint: {
43
- type: 'string',
44
- description: 'WebSocket endpoint to connect to a running Chrome instance (e.g., ws://127.0.0.1:9222/devtools/browser/<id>). Alternative to --browserUrl.',
45
- alias: 'w',
46
- conflicts: ['browserUrl'],
47
- coerce: (url) => {
48
- if (!url) {
49
- return;
50
- }
51
- try {
52
- const parsed = new URL(url);
53
- if (parsed.protocol !== 'ws:' && parsed.protocol !== 'wss:') {
54
- throw new Error(`Provided wsEndpoint ${url} must use ws:// or wss:// protocol.`);
55
- }
56
- return url;
57
- }
58
- catch (error) {
59
- if (error.message.includes('ws://')) {
60
- throw error;
61
- }
62
- throw new Error(`Provided wsEndpoint ${url} is not valid URL.`);
63
- }
64
- },
65
- },
66
- wsHeaders: {
67
- type: 'string',
68
- description: 'Custom headers for WebSocket connection in JSON format (e.g., \'{"Authorization":"Bearer token"}\'). Only works with --wsEndpoint.',
69
- implies: 'wsEndpoint',
70
- coerce: (val) => {
71
- if (!val) {
72
- return;
73
- }
74
- try {
75
- const parsed = JSON.parse(val);
76
- if (typeof parsed !== 'object' || Array.isArray(parsed)) {
77
- throw new Error('Headers must be a JSON object');
78
- }
79
- return parsed;
80
- }
81
- catch (error) {
82
- throw new Error(`Invalid JSON for wsHeaders: ${error.message}`);
83
- }
84
- },
85
- },
86
- headless: {
87
- type: 'boolean',
88
- description: 'Whether to run in headless (no UI) mode.',
89
- default: false,
90
- },
91
- executablePath: {
92
- type: 'string',
93
- description: 'Path to custom Chrome executable.',
94
- conflicts: ['browserUrl', 'wsEndpoint'],
95
- alias: 'e',
96
- },
97
- isolated: {
98
- type: 'boolean',
99
- description: 'If specified, creates a temporary user-data-dir that is automatically cleaned up after the browser is closed. Defaults to false.',
100
- },
101
- userDataDir: {
102
- type: 'string',
103
- description: `Path to the user data directory for Chrome. Default is $HOME/.cache/${CACHE_DIR_NAME}/chrome-profile$CHANNEL_SUFFIX_IF_NON_STABLE`,
104
- conflicts: ['browserUrl', 'wsEndpoint', 'isolated'],
105
- },
106
- channel: {
107
- type: 'string',
108
- description: 'Specify a different Chrome channel that should be used. The default is the stable channel version.',
109
- choices: ['canary', 'dev', 'beta', 'stable'],
110
- conflicts: ['browserUrl', 'wsEndpoint', 'executablePath'],
111
- },
11
+ import os from 'node:os';
12
+ import { readFileSync } from 'node:fs';
13
+ export const DEFAULT_FILESYSTEM_ROOT = [os.tmpdir()];
14
+ import { getCategoryOptions } from './category-options.js';
15
+ import { getBrowserOptions } from './browser-options.js';
16
+ export const mcpOptions = {
17
+ ...getCategoryOptions(),
18
+ ...getBrowserOptions(),
112
19
  logFile: {
113
20
  type: 'string',
114
21
  describe: 'Path to a file to write debug logs to. Set the env variable `DEBUG` to `*` to enable verbose logs. Useful for submitting bug reports.',
@@ -130,17 +37,20 @@ export const cliOptions = {
130
37
  };
131
38
  },
132
39
  },
133
- proxyServer: {
134
- type: 'string',
135
- description: `Proxy server configuration for Chrome passed as --proxy-server when launching the browser. See https://www.chromium.org/developers/design-documents/network-settings/ for details.`,
136
- },
137
40
  acceptInsecureCerts: {
138
41
  type: 'boolean',
139
42
  description: `If enabled, ignores errors relative to self-signed and expired certificates. Use with caution.`,
140
43
  },
141
- experimentalPageIdRouting: {
44
+ pageIdRouting: {
142
45
  type: 'boolean',
143
- describe: 'Whether to expose pageId on page-scoped tools and route requests by page ID (useful for concurrent agent sessions).',
46
+ describe: 'Require pageId on page-scoped tools and route requests by page ID (useful for concurrent agent sessions). Use --no-page-id-routing to disable.',
47
+ default: true,
48
+ },
49
+ devtoolsComments: {
50
+ type: 'boolean',
51
+ describe: 'Whether to enable DevTools comments tools. Internal WIP feature.',
52
+ hidden: true,
53
+ default: false,
144
54
  },
145
55
  experimentalDevtools: {
146
56
  type: 'boolean',
@@ -152,11 +62,13 @@ export const cliOptions = {
152
62
  },
153
63
  memoryDebugging: {
154
64
  type: 'boolean',
65
+ default: false,
155
66
  describe: 'Whether to enable memory debugging tools.',
156
67
  alias: 'experimentalMemory',
157
68
  },
158
69
  experimentalStructuredContent: {
159
70
  type: 'boolean',
71
+ default: false,
160
72
  describe: 'Whether to output structured formatted content.',
161
73
  },
162
74
  experimentalToonFormat: {
@@ -188,13 +100,19 @@ export const cliOptions = {
188
100
  describe: 'Path to ffmpeg executable for screencast recording.',
189
101
  implies: 'experimentalScreencast',
190
102
  },
191
- categoryExperimentalWebmcp: {
192
- type: 'boolean',
193
- describe: 'Set to true to enable debugging WebMCP tools. Requires Chrome 150+ with the following flag: `--enable-features=WebMCP`',
194
- },
195
- chromeArg: {
196
- type: 'array',
197
- describe: `Additional arguments for Chrome. Only applies when Chrome is launched by ${MCP_BIN_NAME}.`,
103
+ experimentalScreencastFps: {
104
+ type: 'number',
105
+ describe: 'Frames per second to use for screencast recording. Lower values can reduce memory pressure on pages that produce frames faster than ffmpeg can encode them.',
106
+ implies: 'experimentalScreencast',
107
+ coerce: (value) => {
108
+ if (value === undefined) {
109
+ return;
110
+ }
111
+ if (!Number.isInteger(value) || value <= 0) {
112
+ throw new Error(`Invalid experimentalScreencastFps ${value}. Expected a positive integer.`);
113
+ }
114
+ return value;
115
+ },
198
116
  },
199
117
  blockedUrlPattern: {
200
118
  type: 'array',
@@ -206,42 +124,6 @@ export const cliOptions = {
206
124
  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). Accepts an array of patterns.",
207
125
  conflicts: ['blockedUrlPattern'],
208
126
  },
209
- ignoreDefaultChromeArg: {
210
- type: 'array',
211
- describe: `Explicitly disable default arguments for Chrome. Only applies when Chrome is launched by ${MCP_BIN_NAME}.`,
212
- },
213
- categoryEmulation: {
214
- type: 'boolean',
215
- default: true,
216
- describe: 'Set to false to exclude tools related to emulation.',
217
- },
218
- categoryPerformance: {
219
- type: 'boolean',
220
- default: true,
221
- describe: 'Set to false to exclude tools related to performance.',
222
- },
223
- categoryNetwork: {
224
- type: 'boolean',
225
- default: true,
226
- describe: 'Set to false to exclude tools related to network.',
227
- },
228
- categoryExtensions: {
229
- type: 'boolean',
230
- hidden: false,
231
- default: false,
232
- describe: 'Set to true to include tools related to extensions. Note: This feature is currently only supported with a pipe connection. autoConnect, browserUrl, and wsEndpoint are not supported with this feature until 149 will be released.',
233
- },
234
- categoryExperimentalThirdParty: {
235
- type: 'boolean',
236
- default: false,
237
- describe: 'Set to true to enable third-party developer tools exposed by the inspected page itself',
238
- },
239
- categoryPwa: {
240
- type: 'boolean',
241
- hidden: false,
242
- conflicts: ['autoConnect', 'browserUrl', 'wsEndpoint'],
243
- describe: 'Set to true to include tools for automating Progressive Web Apps (install, launch, uninstall, and OS state). This feature is only supported with a pipe connection; autoConnect, browserUrl, and wsEndpoint are not supported.',
244
- },
245
127
  performanceCrux: {
246
128
  type: 'boolean',
247
129
  default: PERFORMANCE_CRUX_DEFAULT,
@@ -252,6 +134,16 @@ export const cliOptions = {
252
134
  default: USAGE_STATISTICS_DEFAULT,
253
135
  describe: USAGE_STATISTICS_DESCRIPTION,
254
136
  },
137
+ javascriptEvaluation: {
138
+ type: 'boolean',
139
+ default: true,
140
+ describe: 'Set to false to disable JavaScript execution. When disabled, evaluation tools (evaluate_script and slim evaluate) are disabled, the initScript parameter in navigate_page is turned off, and navigating to javascript:, data:, or vbscript: URLs is disallowed.',
141
+ },
142
+ sourceMaps: {
143
+ type: 'boolean',
144
+ default: true,
145
+ describe: 'Whether to enable source maps in DevTools. Use --no-source-maps to disable.',
146
+ },
255
147
  clearcutEndpoint: {
256
148
  type: 'string',
257
149
  hidden: true,
@@ -269,7 +161,7 @@ export const cliOptions = {
269
161
  },
270
162
  screenshotFormat: {
271
163
  type: 'string',
272
- 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 helps reduce context size in AI conversations. Unset preserves the existing default ("png").',
164
+ 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").',
273
165
  choices: ['jpeg', 'png', 'webp'],
274
166
  },
275
167
  screenshotQuality: {
@@ -328,30 +220,78 @@ export const cliOptions = {
328
220
  allowUnrestrictedPaths: {
329
221
  type: 'boolean',
330
222
  default: false,
223
+ deprecated: 'Use --workspace=/ instead.',
331
224
  describe: 'If set, disables the default path restriction that applies when the MCP client does not negotiate ' +
332
225
  'the roots capability. By default, file-writing tools are restricted to the OS temp directory when ' +
333
226
  'no roots are configured. Use this only when connecting a trusted local client that does not implement ' +
334
227
  'MCP roots and requires access to paths outside the temp directory.',
335
228
  },
229
+ filesystemRoot: {
230
+ type: 'array',
231
+ alias: 'workspace',
232
+ default: DEFAULT_FILESYSTEM_ROOT,
233
+ defaultDescription: 'OS temp directory',
234
+ describe: 'A directory that filesystem tools are allowed to access. May be specified more than once.',
235
+ },
236
+ config: {
237
+ type: 'string',
238
+ describe: 'Path to JSON configuration file.',
239
+ },
336
240
  };
241
+ export function getMcpOptionsForViaCli() {
242
+ if (!('default' in mcpOptions.headless)) {
243
+ throw new Error('headless cli option unexpectedly does not have a default');
244
+ }
245
+ if (!('default' in mcpOptions.experimentalStructuredContent)) {
246
+ throw new Error('experimentalStructuredContent cli option unexpectedly does not have a default');
247
+ }
248
+ if ('default' in mcpOptions.isolated) {
249
+ throw new Error('isolated cli option unexpectedly has a default');
250
+ }
251
+ return {
252
+ ...mcpOptions,
253
+ headless: {
254
+ ...mcpOptions.headless,
255
+ default: true,
256
+ },
257
+ memoryDebugging: {
258
+ ...mcpOptions.memoryDebugging,
259
+ default: true,
260
+ },
261
+ categoryExtensions: {
262
+ ...mcpOptions.categoryExtensions,
263
+ default: true,
264
+ },
265
+ experimentalStructuredContent: {
266
+ ...mcpOptions.experimentalStructuredContent,
267
+ default: true,
268
+ },
269
+ isolated: {
270
+ ...mcpOptions.isolated,
271
+ description: 'If specified, creates a temporary user-data-dir that is automatically cleaned up after the browser is closed. Defaults to true unless userDataDir is provided.',
272
+ },
273
+ };
274
+ }
337
275
  /**
338
276
  * Exported only for testing to not trigger process exit.
339
277
  */
340
278
  export function parser(version, argv = process.argv, env = process.env) {
341
- // Preserve yargs' mixed camel/kebab-case expansion under strict validation.
342
- const kebabCaseAliases = {};
343
- for (const option of Object.keys(cliOptions)) {
344
- const alias = option.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
345
- if (alias !== option) {
346
- kebabCaseAliases[option] = alias;
347
- }
348
- }
279
+ const isViaCli = argv.includes('--viaCli') || argv.includes('--via-cli');
280
+ const options = isViaCli ? getMcpOptionsForViaCli() : mcpOptions;
349
281
  const yargsInstance = yargs(hideBin(argv))
350
282
  .scriptName(`npx ${PACKAGE_NAME}@latest`)
351
- .options(cliOptions)
352
- .alias(kebabCaseAliases)
353
- .strictOptions()
283
+ .parserConfiguration({
284
+ 'strip-aliased': true,
285
+ 'strip-dashed': true,
286
+ })
287
+ .options(options)
288
+ .showHelpOnFail(false, 'Specify --help for available options')
354
289
  .middleware(args => {
290
+ if (isViaCli && args.filesystemRoot === DEFAULT_FILESYSTEM_ROOT) {
291
+ const cliFilesystemArgs = args;
292
+ cliFilesystemArgs.allowUnrestrictedPaths = true;
293
+ cliFilesystemArgs.filesystemRoot = undefined;
294
+ }
355
295
  // We can't set default in the options else
356
296
  // Yargs will complain
357
297
  if (!args.channel &&
@@ -364,6 +304,16 @@ export function parser(version, argv = process.argv, env = process.env) {
364
304
  console.error(`turning off usage statistics. process.env['CI'] || process.env['${ENV_NO_USAGE_STATISTICS}'] is set.`);
365
305
  args.usageStatistics = false;
366
306
  }
307
+ const cliOptionsAllowedArgs = [
308
+ ...Object.keys(options),
309
+ // Yargs populated with positional args
310
+ '_',
311
+ '$0',
312
+ ];
313
+ const unknownArgs = Object.keys(args).filter(arg => !cliOptionsAllowedArgs.includes(arg));
314
+ if (unknownArgs.length > 0) {
315
+ console.error(`Unknown arguments: ${unknownArgs.map(arg => `--${arg}`)}`);
316
+ }
367
317
  })
368
318
  .example([
369
319
  [
@@ -422,12 +372,41 @@ export function parser(version, argv = process.argv, env = process.env) {
422
372
  '$0 --no-performance-crux',
423
373
  'Disable CrUX (field data) integration in performance tools.',
424
374
  ],
375
+ ['$0 --no-source-maps', 'Disable source maps in DevTools.'],
376
+ [
377
+ '$0 --no-javascript-evaluation',
378
+ 'Disable JavaScript execution (disables evaluation tools, initScript in navigate_page, and navigating to javascript:, data:, or vbscript: URLs).',
379
+ ],
425
380
  [
426
381
  '$0 --slim',
427
382
  'Only 3 tools: navigation, JavaScript execution and screenshot',
428
383
  ],
429
384
  ]);
430
385
  return yargsInstance
386
+ .config('config', 'Path to JSON configuration file', configPath => {
387
+ try {
388
+ const parsed = JSON.parse(readFileSync(configPath, 'utf-8'));
389
+ if (typeof parsed !== 'object' ||
390
+ parsed === null ||
391
+ Array.isArray(parsed)) {
392
+ throw new Error('Config must be a JSON object');
393
+ }
394
+ return yargs()
395
+ .parserConfiguration({
396
+ 'strip-aliased': true,
397
+ 'camel-case-expansion': false,
398
+ })
399
+ .options(options)
400
+ .config(parsed)
401
+ .strict()
402
+ .fail(false)
403
+ .exitProcess(false)
404
+ .parseSync([]);
405
+ }
406
+ catch (err) {
407
+ throw new Error(`Invalid JSON config file: ${err.message}`);
408
+ }
409
+ })
431
410
  .wrap(Math.min(120, yargsInstance.terminalWidth()))
432
411
  .help()
433
412
  .version(version);
@@ -435,4 +414,4 @@ export function parser(version, argv = process.argv, env = process.env) {
435
414
  export function parseArguments(version, argv = process.argv, env = process.env) {
436
415
  return parser(version, argv, env).parseSync();
437
416
  }
438
- //# sourceMappingURL=chrome-devtools-mcp-cli-options.js.map
417
+ //# sourceMappingURL=mcp-options.js.map
@@ -6,9 +6,11 @@
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 { ensureCleanStart, readExitReason } from '../opera/daemonLifecycle.js';
10
+ import { nameSpawnFailure, openDaemonLog } from '../opera/daemonLog.js';
11
+ import { requestOverSocket } from '../opera/daemonStreaming.js';
10
12
  import { getTempFilePath } from '../utils/files.js';
11
- import { logger, puppeteerLogger } from '../utils/logger.js';
13
+ import { logger } from '../utils/logger.js';
12
14
  import { DAEMON_SCRIPT_PATH, getSocketPath, getPidFilePath, isDaemonRunning, } from './utils.js';
13
15
  const FILE_TIMEOUT = 10_000;
14
16
  const READY_CHECK_INTERVAL = 100;
@@ -77,64 +79,68 @@ async function waitForDaemonReady(sessionId) {
77
79
  throw new Error(`Timeout: daemon not ready within ${FILE_TIMEOUT}ms`, lastError === undefined ? undefined : { cause: lastError });
78
80
  }
79
81
  export async function startDaemon(mcpArgs = [], sessionId) {
80
- if (isDaemonRunning(sessionId)) {
82
+ // Not `isDaemonRunning`: that reads the pid file, and a daemon whose pid file
83
+ // is gone (or whose socket a racing starter unlinked) is invisible to it.
84
+ // `ensureCleanStart` probes the socket and reaps whatever the last daemon left
85
+ // behind, so the daemon we are about to fork is the only one in the session.
86
+ if (await ensureCleanStart(sessionId)) {
81
87
  logger?.('Daemon is already running');
82
88
  await waitForDaemonReady(sessionId);
83
89
  return;
84
90
  }
91
+ logger?.('Starting daemon...', ...mcpArgs);
85
92
  const pidFilePath = getPidFilePath(sessionId);
86
- if (fs.existsSync(pidFilePath)) {
87
- fs.unlinkSync(pidFilePath);
93
+ const logFd = openDaemonLog(sessionId);
94
+ let child;
95
+ try {
96
+ child = spawn(process.execPath, [DAEMON_SCRIPT_PATH, ...mcpArgs], {
97
+ detached: true,
98
+ // Not 'ignore' unless there was nothing to open: the daemon is detached
99
+ // with no terminal, so discarding its output leaves a daemon that dies
100
+ // silently unexplainable. The file is what the mid-command failure below
101
+ // points the user at.
102
+ stdio: logFd === 'ignore' ? 'ignore' : ['ignore', logFd, logFd],
103
+ env: { ...process.env, CHROME_DEVTOOLS_MCP_SESSION_ID: sessionId },
104
+ cwd: process.cwd(),
105
+ windowsHide: true,
106
+ });
107
+ }
108
+ finally {
109
+ // The child holds its own descriptor; the parent's copy would outlive it.
110
+ if (logFd !== 'ignore') {
111
+ fs.closeSync(logFd);
112
+ }
88
113
  }
89
- logger?.('Starting daemon...', ...mcpArgs);
90
- const child = spawn(process.execPath, [DAEMON_SCRIPT_PATH, ...mcpArgs], {
91
- detached: true,
92
- stdio: 'ignore',
93
- env: { ...process.env, CHROME_DEVTOOLS_MCP_SESSION_ID: sessionId },
94
- cwd: process.cwd(),
95
- windowsHide: true,
96
- });
97
114
  child.unref();
98
- await waitForFile(pidFilePath);
115
+ // The pid file and the spawn's own failure, whichever comes first. See
116
+ // `opera/daemonLog.ts` for why a failed spawn must not surface as a timeout.
117
+ await Promise.race([
118
+ waitForFile(pidFilePath),
119
+ nameSpawnFailure(child, sessionId),
120
+ ]);
99
121
  await waitForDaemonReady(sessionId);
100
122
  }
101
123
  const SEND_COMMAND_TIMEOUT = 60_000; // ms
102
124
  /**
103
125
  * `sendCommand` opens a socket connection sends a single command and disconnects.
126
+ *
127
+ * The frame protocol — including `onLog`, which opts the request into the
128
+ * streaming variant and hands each chunk over as it arrives — lives in
129
+ * `opera/daemonStreaming.ts`'s `requestOverSocket`.
104
130
  */
105
- export async function sendCommand(command, sessionId, timeout = SEND_COMMAND_TIMEOUT) {
131
+ export async function sendCommand(command, sessionId, timeout = SEND_COMMAND_TIMEOUT, onLog) {
106
132
  // Before connecting and sending, verify the daemon is still alive.
107
133
  if (!isDaemonRunning(sessionId)) {
108
- throw new Error('Daemon is not running.');
134
+ // A daemon that tore itself down leaves a reason behind; surfacing it is
135
+ // the difference between "Daemon is not running." and knowing why.
136
+ const reason = readExitReason(sessionId);
137
+ throw new Error(reason ? `Daemon is not running: ${reason}` : 'Daemon is not running.');
109
138
  }
110
139
  const socketPath = getSocketPath(sessionId);
111
140
  const socket = net.createConnection({
112
141
  path: socketPath,
113
142
  });
114
- return new Promise((resolve, reject) => {
115
- const timer = setTimeout(() => {
116
- socket.destroy();
117
- reject(new Error('Timeout waiting for daemon response'));
118
- }, timeout);
119
- const transport = new PipeTransport(socket, socket, puppeteerLogger);
120
- transport.onmessage = async (message) => {
121
- clearTimeout(timer);
122
- logger?.('onmessage', message);
123
- resolve(JSON.parse(message));
124
- };
125
- socket.on('error', error => {
126
- clearTimeout(timer);
127
- logger?.('Socket error:', error);
128
- reject(error);
129
- });
130
- socket.on('close', () => {
131
- clearTimeout(timer);
132
- logger?.('Socket closed:');
133
- reject(new Error('Socket closed'));
134
- });
135
- logger?.('Sending message', command);
136
- transport.send(JSON.stringify(command));
137
- });
143
+ return requestOverSocket({ socket, command, sessionId, timeout, onLog });
138
144
  }
139
145
  export async function stopDaemon(sessionId) {
140
146
  if (!isDaemonRunning(sessionId)) {
@@ -165,6 +171,15 @@ export async function verifyDaemonVersion(sessionId, cliVersion) {
165
171
  }
166
172
  export async function handleResponse(response, format) {
167
173
  if (response.isError) {
174
+ if (format === 'md') {
175
+ const chunks = [];
176
+ for (const content of response.content) {
177
+ if (content.type === 'text') {
178
+ chunks.push(content.text);
179
+ }
180
+ }
181
+ return chunks.join(' ');
182
+ }
168
183
  return JSON.stringify(response.content);
169
184
  }
170
185
  const chunks = [];