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
@@ -29,7 +29,7 @@ const FILTERABLE_RESOURCE_TYPES = [
29
29
  ];
30
30
  export const listNetworkRequests = definePageTool({
31
31
  name: 'list_network_requests',
32
- description: `Lists the most recent requests for the currently selected page since the last navigation.`,
32
+ description: `Lists the most recent requests for the target page since the last navigation.`,
33
33
  annotations: {
34
34
  category: ToolCategory.NETWORK,
35
35
  readOnlyHint: true,
@@ -58,7 +58,7 @@ export const listNetworkRequests = definePageTool({
58
58
  .describe('Set to true to return the preserved requests over the last 3 navigations.'),
59
59
  },
60
60
  blockedByDialog: false,
61
- verifyFilesSchema: [],
61
+ verifyFilesSchema: {},
62
62
  handler: async (request, response) => {
63
63
  const data = await request.page.getDevToolsData();
64
64
  response.attachDevToolsData(data);
@@ -76,7 +76,7 @@ export const listNetworkRequests = definePageTool({
76
76
  });
77
77
  export const getNetworkRequest = definePageTool({
78
78
  name: 'get_network_request',
79
- description: `Gets a network request by an optional reqid, if omitted returns the currently selected request in the DevTools Network panel.`,
79
+ description: `Gets a network request by an optional reqid, if omitted returns the currently selected request in the DevTools Network panel. Useful for inspecting request headers (including 'Cookie') and response headers (including 'Set-Cookie' and directives).`,
80
80
  annotations: {
81
81
  category: ToolCategory.NETWORK,
82
82
  readOnlyHint: false,
@@ -96,7 +96,10 @@ export const getNetworkRequest = definePageTool({
96
96
  .describe('The absolute or relative path to a .network-response file to save the response body to. If omitted, the body is returned inline.'),
97
97
  },
98
98
  blockedByDialog: true,
99
- verifyFilesSchema: ['requestFilePath', 'responseFilePath'],
99
+ verifyFilesSchema: {
100
+ requestFilePath: true,
101
+ responseFilePath: true,
102
+ },
100
103
  handler: async (request, response) => {
101
104
  if (request.params.reqid) {
102
105
  response.attachNetworkRequest(request.params.reqid, {
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { zod } from '../third_party/index.js';
7
7
  import { logger } from '../utils/logger.js';
8
+ import { validateUrl } from '../utils/url.js';
8
9
  import { ToolCategory } from './categories.js';
9
10
  import { CLOSE_PAGE_ERROR, definePageTool, defineTool, timeoutSchema, } from './ToolDefinition.js';
10
11
  export const listPages = defineTool(args => {
@@ -17,7 +18,7 @@ export const listPages = defineTool(args => {
17
18
  },
18
19
  schema: {},
19
20
  blockedByDialog: false,
20
- verifyFilesSchema: [],
21
+ verifyFilesSchema: {},
21
22
  handler: async (_request, response) => {
22
23
  response.setIncludePages(true);
23
24
  response.setListThirdPartyDeveloperTools();
@@ -42,7 +43,7 @@ export const selectPage = defineTool({
42
43
  .describe('Whether to focus the page and bring it to the top.'),
43
44
  },
44
45
  blockedByDialog: false,
45
- verifyFilesSchema: [],
46
+ verifyFilesSchema: {},
46
47
  handler: async (request, response, context) => {
47
48
  const page = context.getPageById(request.params.pageId);
48
49
  context.selectPage(page);
@@ -67,7 +68,7 @@ export const closePage = defineTool({
67
68
  .describe('The ID of the page to close. Call list_pages to list pages.'),
68
69
  },
69
70
  blockedByDialog: false,
70
- verifyFilesSchema: [],
71
+ verifyFilesSchema: {},
71
72
  handler: async (request, response, context) => {
72
73
  try {
73
74
  await context.closePage(request.params.pageId);
@@ -84,7 +85,7 @@ export const closePage = defineTool({
84
85
  response.setListThirdPartyDeveloperTools();
85
86
  },
86
87
  });
87
- export const newPage = defineTool(() => {
88
+ export const newPage = defineTool(args => {
88
89
  return {
89
90
  name: 'new_page',
90
91
  description: `Open a new tab and load a URL. Use project URL if not specified otherwise.`,
@@ -103,12 +104,16 @@ export const newPage = defineTool(() => {
103
104
  .optional()
104
105
  .describe('If specified, the page is created in an isolated browser context with the given name. ' +
105
106
  'Pages in the same browser context share cookies and storage. ' +
106
- 'Pages in different browser contexts are fully isolated.'),
107
+ 'Pages in different browser contexts are fully isolated (useful for clean-slate testing of cookies and authentication).'),
107
108
  ...timeoutSchema,
108
109
  },
109
110
  blockedByDialog: false,
110
- verifyFilesSchema: [],
111
+ verifyFilesSchema: {},
111
112
  handler: async (request, response, context) => {
113
+ validateUrl(request.params.url, {
114
+ javascriptEvaluation: args?.javascriptEvaluation,
115
+ categoryExtensions: args?.categoryExtensions,
116
+ });
112
117
  const page = await context.newPage(request.params.background, request.params.isolatedContext);
113
118
  await page.waitForEventsAfterAction(async () => {
114
119
  await page.pptrPage.goto(request.params.url, {
@@ -120,7 +125,7 @@ export const newPage = defineTool(() => {
120
125
  },
121
126
  };
122
127
  });
123
- export const navigatePage = definePageTool(() => {
128
+ export const navigatePage = definePageTool(args => {
124
129
  return {
125
130
  name: 'navigate_page',
126
131
  description: `Go to a URL, or back, forward, or reload. Use project URL if not specified otherwise.`,
@@ -142,14 +147,18 @@ export const navigatePage = definePageTool(() => {
142
147
  .enum(['accept', 'dismiss'])
143
148
  .optional()
144
149
  .describe('Whether to auto accept or beforeunload dialogs triggered by this navigation. Default is accept.'),
145
- initScript: zod
146
- .string()
147
- .optional()
148
- .describe('A JavaScript script to be executed on each new document before any other scripts for the next navigation.'),
150
+ ...(args?.javascriptEvaluation !== false
151
+ ? {
152
+ initScript: zod
153
+ .string()
154
+ .optional()
155
+ .describe('A JavaScript script to be executed on each new document before any other scripts for the next navigation.'),
156
+ }
157
+ : {}),
149
158
  ...timeoutSchema,
150
159
  },
151
160
  blockedByDialog: false,
152
- verifyFilesSchema: [],
161
+ verifyFilesSchema: {},
153
162
  handler: async (request, response) => {
154
163
  const page = request.page;
155
164
  const options = {
@@ -161,6 +170,12 @@ export const navigatePage = definePageTool(() => {
161
170
  if (!request.params.type) {
162
171
  request.params.type = 'url';
163
172
  }
173
+ if (request.params.url) {
174
+ validateUrl(request.params.url, {
175
+ javascriptEvaluation: args?.javascriptEvaluation,
176
+ categoryExtensions: args?.categoryExtensions,
177
+ });
178
+ }
164
179
  let initScriptId;
165
180
  if (request.params.initScript) {
166
181
  const { identifier } = await page.pptrPage.evaluateOnNewDocument(request.params.initScript);
@@ -239,7 +254,7 @@ export const navigatePage = definePageTool(() => {
239
254
  });
240
255
  export const resizePage = definePageTool({
241
256
  name: 'resize_page',
242
- description: `Resizes the selected page's window so that the page has specified dimension`,
257
+ description: `Resizes the page's window so that the page has specified dimension`,
243
258
  annotations: {
244
259
  category: ToolCategory.EMULATION,
245
260
  readOnlyHint: false,
@@ -249,7 +264,7 @@ export const resizePage = definePageTool({
249
264
  height: zod.number().describe('Page height'),
250
265
  },
251
266
  blockedByDialog: false,
252
- verifyFilesSchema: [],
267
+ verifyFilesSchema: {},
253
268
  handler: async (request, response) => {
254
269
  const page = request.page;
255
270
  try {
@@ -292,7 +307,7 @@ export const handleDialog = definePageTool({
292
307
  .describe('Optional prompt text to enter into the dialog.'),
293
308
  },
294
309
  blockedByDialog: false,
295
- verifyFilesSchema: [],
310
+ verifyFilesSchema: {},
296
311
  handler: async (request, response) => {
297
312
  const page = request.page;
298
313
  const dialog = page.getDialog();
@@ -335,15 +350,11 @@ export const getTabId = definePageTool({
335
350
  readOnlyHint: true,
336
351
  conditions: ['experimentalInteropTools'],
337
352
  },
338
- schema: {
339
- pageId: zod
340
- .number()
341
- .describe(`The ID of the page to get the tab ID for. Call ${listPages().name} to get available pages.`),
342
- },
353
+ schema: {},
343
354
  blockedByDialog: false,
344
- verifyFilesSchema: [],
345
- handler: async (request, response, context) => {
346
- const page = context.getPageById(request.params.pageId);
355
+ verifyFilesSchema: {},
356
+ handler: async (request, response) => {
357
+ const page = request.page;
347
358
  const tabId = page.pptrPage._tabId;
348
359
  response.setTabId(tabId);
349
360
  response.appendResponseLine(`Tab ID: ${tabId}`);
@@ -5,7 +5,7 @@
5
5
  */
6
6
  import zlib from 'node:zlib';
7
7
  import { zod, DevTools } from '../third_party/index.js';
8
- import { parseRawTraceBuffer, traceResultIsSuccess, } from '../trace-processing/parse.js';
8
+ import { parseRawTraceBuffer, traceResultIsSuccess, } from '../processors/PerformanceTrace.js';
9
9
  import { logger } from '../utils/logger.js';
10
10
  import { ToolCategory } from './categories.js';
11
11
  import { definePageTool } from './ToolDefinition.js';
@@ -15,7 +15,7 @@ const filePathSchema = zod
15
15
  .describe('The absolute file path, or a file path relative to the current working directory, to save the raw trace data. For example, trace.json.gz (compressed) or trace.json (uncompressed).');
16
16
  export const startTrace = definePageTool({
17
17
  name: 'performance_start_trace',
18
- description: `Start a performance trace on the selected webpage. Use to find frontend performance issues, Core Web Vitals (LCP, INP, CLS), and improve page load speed.`,
18
+ description: `Start a performance trace on the target webpage. Use to find frontend performance issues, Core Web Vitals (LCP, INP, CLS), and improve page load speed.`,
19
19
  annotations: {
20
20
  category: ToolCategory.PERFORMANCE,
21
21
  readOnlyHint: false,
@@ -24,7 +24,7 @@ export const startTrace = definePageTool({
24
24
  reload: zod
25
25
  .boolean()
26
26
  .default(true)
27
- .describe('Determines if, once tracing has started, the current selected page should be automatically reloaded. Navigate the page to the right URL using the navigate_page tool BEFORE starting the trace if reload or autoStop is set to true.'),
27
+ .describe('Determines if, once tracing has started, the target page should be automatically reloaded. Navigate the page to the right URL using the navigate_page tool BEFORE starting the trace if reload or autoStop is set to true.'),
28
28
  autoStop: zod
29
29
  .boolean()
30
30
  .default(true)
@@ -32,7 +32,9 @@ export const startTrace = definePageTool({
32
32
  filePath: filePathSchema,
33
33
  },
34
34
  blockedByDialog: true,
35
- verifyFilesSchema: ['filePath'],
35
+ verifyFilesSchema: {
36
+ filePath: true,
37
+ },
36
38
  handler: async (request, response, context) => {
37
39
  if (context.isRunningPerformanceTrace()) {
38
40
  response.appendResponseLine('Error: a performance trace is already running. Use performance_stop_trace to stop it. Only one trace can be running at any given time.');
@@ -49,29 +51,16 @@ export const startTrace = definePageTool({
49
51
  waitUntil: 'load',
50
52
  });
51
53
  }
52
- // Keep in sync with the categories arrays in:
53
- // https://source.chromium.org/chromium/chromium/src/+/main:third_party/devtools-frontend/src/front_end/panels/timeline/TimelineController.ts
54
- // https://github.com/GoogleChrome/lighthouse/blob/master/lighthouse-core/gather/gatherers/trace.js
55
54
  const categories = [
56
55
  '-*',
57
- 'blink.console',
58
- 'blink.user_timing',
59
- 'devtools.timeline',
60
- 'disabled-by-default-devtools.screenshot',
61
- 'disabled-by-default-devtools.timeline',
62
- 'disabled-by-default-devtools.timeline.invalidationTracking',
63
- 'disabled-by-default-devtools.timeline.frame',
64
- 'disabled-by-default-devtools.timeline.stack',
65
- 'disabled-by-default-v8.cpu_profiler',
66
- 'disabled-by-default-v8.cpu_profiler.hires',
67
- 'latencyInfo',
68
- 'loading',
69
- 'disabled-by-default-lighthouse',
70
- 'v8.execute',
71
- 'v8',
56
+ ...DevTools.TracingDefaultCategories,
57
+ // These categories are optional in DevTools, but enabled by default in the DevTools UI, so we enable them here too.
58
+ ...DevTools.TracingOptionalCategories.JsSampling,
59
+ ...DevTools.TracingOptionalCategories.Screenshot,
72
60
  ];
73
61
  await page.pptrPage.tracing.start({
74
62
  categories,
63
+ bufferSize: 1200 * 1000,
75
64
  });
76
65
  if (request.params.reload) {
77
66
  await page.pptrPage.goto(pageUrlForTracing, {
@@ -108,7 +97,7 @@ export const startTrace = definePageTool({
108
97
  });
109
98
  export const stopTrace = definePageTool({
110
99
  name: 'performance_stop_trace',
111
- description: 'Stop the active performance trace recording on the selected webpage.',
100
+ description: 'Stop the active performance trace recording on the target webpage.',
112
101
  annotations: {
113
102
  category: ToolCategory.PERFORMANCE,
114
103
  readOnlyHint: false,
@@ -117,7 +106,9 @@ export const stopTrace = definePageTool({
117
106
  filePath: filePathSchema,
118
107
  },
119
108
  blockedByDialog: true,
120
- verifyFilesSchema: ['filePath'],
109
+ verifyFilesSchema: {
110
+ filePath: true,
111
+ },
121
112
  handler: async (request, response, context) => {
122
113
  if (!context.isRunningPerformanceTrace()) {
123
114
  return;
@@ -142,7 +133,7 @@ export const analyzeInsight = definePageTool({
142
133
  .describe('The name of the Insight you want more information on. For example: "DocumentLatency" or "LCPBreakdown"'),
143
134
  },
144
135
  blockedByDialog: false,
145
- verifyFilesSchema: [],
136
+ verifyFilesSchema: {},
146
137
  handler: async (request, response, context) => {
147
138
  const lastRecording = context.recordedTraces().at(-1);
148
139
  if (!lastRecording) {
@@ -0,0 +1,128 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ import { zod } from '../third_party/index.js';
7
+ import { ToolCategory } from './categories.js';
8
+ import { defineTool } from './ToolDefinition.js';
9
+ const manifestIdSchema = zod
10
+ .string()
11
+ .describe('The manifest ID of the web app: the resolved `id` member of its manifest. ' +
12
+ 'If `id` is omitted, it defaults to the resolved `start_url` ' +
13
+ '(e.g. "https://example.com/"). See https://w3c.github.io/manifest/#id-member.');
14
+ const displayModeSchema = zod
15
+ .enum(['standalone', 'browser'])
16
+ .optional()
17
+ .describe('Optional user display mode preference applied after install. ' +
18
+ '"standalone" opens the app in its own window; "browser" opens it as a ' +
19
+ 'tab. Installs via the PWA CDP domain default to "browser" because they ' +
20
+ 'do not simulate the install dialog, so pass "standalone" to get an ' +
21
+ 'app-window experience.');
22
+ export const installPwa = defineTool({
23
+ name: 'install_pwa',
24
+ description: 'Installs a Progressive Web App (PWA) identified by its manifest ID. ' +
25
+ 'This installs through the PWA CDP domain without a user gesture or install ' +
26
+ 'dialog. DevTools installs default to browser display mode.',
27
+ annotations: {
28
+ category: ToolCategory.PWA,
29
+ readOnlyHint: false,
30
+ },
31
+ schema: {
32
+ manifestId: manifestIdSchema,
33
+ installUrlOrBundleUrl: zod
34
+ .string()
35
+ .describe('The location of the app or bundle. For a normal site this is the page ' +
36
+ 'URL; for an Isolated Web App it can be a file:// or http(s):// ' +
37
+ 'signed web bundle.'),
38
+ displayMode: displayModeSchema,
39
+ },
40
+ blockedByDialog: false,
41
+ // We do not validate file paths for remote browser instances
42
+ // because they are on the remote host and not accessed by the MCP server.
43
+ verifyFilesSchema: {
44
+ installUrlOrBundleUrl: {
45
+ local: true,
46
+ remote: false,
47
+ },
48
+ },
49
+ handler: async (request, response, context) => {
50
+ const { manifestId, installUrlOrBundleUrl, displayMode } = request.params;
51
+ await context.installPWA({
52
+ manifestId,
53
+ installUrlOrBundleUrl,
54
+ displayMode,
55
+ });
56
+ response.appendResponseLine(`Installed PWA with manifest ID: ${manifestId}`);
57
+ if (displayMode) {
58
+ response.appendResponseLine(`Display mode set to: ${displayMode}`);
59
+ }
60
+ },
61
+ });
62
+ export const uninstallPwa = defineTool({
63
+ name: 'uninstall_pwa',
64
+ description: 'Uninstalls a Progressive Web App identified by its manifest ID and ' +
65
+ 'closes any open app windows.',
66
+ annotations: {
67
+ category: ToolCategory.PWA,
68
+ readOnlyHint: false,
69
+ },
70
+ schema: {
71
+ manifestId: manifestIdSchema,
72
+ },
73
+ blockedByDialog: false,
74
+ verifyFilesSchema: {},
75
+ handler: async (request, response, context) => {
76
+ const { manifestId } = request.params;
77
+ await context.uninstallPWA({ manifestId });
78
+ response.appendResponseLine(`Uninstalled PWA with manifest ID: ${manifestId}`);
79
+ response.setIncludePages(true);
80
+ },
81
+ });
82
+ export const launchPwa = defineTool({
83
+ name: 'launch_pwa',
84
+ description: 'Launches an installed Progressive Web App using its saved display mode. ' +
85
+ 'Optionally opens a specific URL within the same app instead of the default ' +
86
+ 'start URL.',
87
+ annotations: {
88
+ category: ToolCategory.PWA,
89
+ readOnlyHint: false,
90
+ },
91
+ schema: {
92
+ manifestId: manifestIdSchema,
93
+ url: zod
94
+ .string()
95
+ .optional()
96
+ .describe('Optional URL within the app to open instead of the default start URL.'),
97
+ },
98
+ blockedByDialog: false,
99
+ verifyFilesSchema: {},
100
+ handler: async (request, response, context) => {
101
+ const { manifestId, url } = request.params;
102
+ const page = await context.launchPWA({ manifestId, url });
103
+ response.appendResponseLine(`Launched PWA with manifest ID: ${manifestId} (${page.url()})`);
104
+ response.setIncludePages(true);
105
+ },
106
+ });
107
+ export const getOsAppState = defineTool({
108
+ name: 'get_os_app_state',
109
+ description: 'Returns the OS integration state (badge count and registered file ' +
110
+ 'handlers) for an installed web app, identified by its manifest ID.',
111
+ annotations: {
112
+ category: ToolCategory.PWA,
113
+ readOnlyHint: true,
114
+ },
115
+ schema: {
116
+ manifestId: manifestIdSchema,
117
+ },
118
+ blockedByDialog: false,
119
+ verifyFilesSchema: {},
120
+ handler: async (request, response, context) => {
121
+ const { manifestId } = request.params;
122
+ const state = await context.getPWAState({ manifestId });
123
+ response.appendResponseLine(`OS app state for manifest ID: ${manifestId}`);
124
+ response.appendResponseLine(`Badge count: ${state.badgeCount}`);
125
+ response.appendResponseLine(`File handlers: ${JSON.stringify(state.fileHandlers)}`);
126
+ },
127
+ });
128
+ //# sourceMappingURL=pwa.js.map
@@ -16,7 +16,7 @@ async function generateTempFilePath() {
16
16
  const supportedExtensions = ['.webm', '.mp4'];
17
17
  export const startScreencast = definePageTool(args => ({
18
18
  name: 'screencast_start',
19
- description: `Starts recording a screencast (video) of the selected page in specified format.`,
19
+ description: `Starts recording a screencast (video) of the target page in specified format.`,
20
20
  annotations: {
21
21
  category: ToolCategory.DEBUGGING,
22
22
  readOnlyHint: false,
@@ -29,7 +29,9 @@ export const startScreencast = definePageTool(args => ({
29
29
  .describe(`Output file path (${supportedExtensions.join(',')} are supported). Uses mkdtemp to generate a unique path if not provided.`),
30
30
  },
31
31
  blockedByDialog: false,
32
- verifyFilesSchema: ['filePath'],
32
+ verifyFilesSchema: {
33
+ filePath: true,
34
+ },
33
35
  handler: async (request, response, context) => {
34
36
  if (context.getScreenRecorder() !== null) {
35
37
  response.appendResponseLine('Error: a screencast recording is already in progress. Use screencast_stop to stop it before starting a new one.');
@@ -60,6 +62,7 @@ export const startScreencast = definePageTool(args => ({
60
62
  path: resolvedPath,
61
63
  format: format,
62
64
  ffmpegPath: args?.experimentalFfmpegPath,
65
+ fps: args?.experimentalScreencastFps,
63
66
  });
64
67
  }
65
68
  catch (err) {
@@ -89,7 +92,7 @@ export const startScreencast = definePageTool(args => ({
89
92
  }));
90
93
  export const stopScreencast = definePageTool({
91
94
  name: 'screencast_stop',
92
- description: 'Stops the active screencast recording on the selected page.',
95
+ description: 'Stops the active screencast recording on the target page.',
93
96
  annotations: {
94
97
  category: ToolCategory.DEBUGGING,
95
98
  readOnlyHint: false,
@@ -97,7 +100,7 @@ export const stopScreencast = definePageTool({
97
100
  },
98
101
  schema: {},
99
102
  blockedByDialog: false,
100
- verifyFilesSchema: [],
103
+ verifyFilesSchema: {},
101
104
  handler: async (_request, response, context) => {
102
105
  const data = context.getScreenRecorder();
103
106
  if (!data) {
@@ -60,22 +60,41 @@ import { ToolCategory } from './categories.js';
60
60
  import { definePageTool } from './ToolDefinition.js';
61
61
  async function getSourceBox(page, element, fullPage) {
62
62
  if (element) {
63
- const box = await element.boundingBox();
64
- return box ?? undefined;
63
+ const viewport = page.viewport();
64
+ const [box, devicePixelRatio] = await Promise.all([
65
+ element.boundingBox(),
66
+ viewport
67
+ ? (viewport.deviceScaleFactor ?? 1)
68
+ : page.evaluate(() => window.devicePixelRatio),
69
+ ]);
70
+ return box ? { ...box, devicePixelRatio } : undefined;
65
71
  }
66
72
  if (fullPage) {
67
73
  const dims = await page.evaluate(() => ({
68
74
  width: Math.max(document.documentElement.scrollWidth, document.body?.scrollWidth ?? 0),
69
75
  height: Math.max(document.documentElement.scrollHeight, document.body?.scrollHeight ?? 0),
76
+ devicePixelRatio: window.devicePixelRatio,
70
77
  }));
71
78
  if (dims.width <= 0 || dims.height <= 0) {
72
79
  return undefined;
73
80
  }
74
- return { x: 0, y: 0, width: dims.width, height: dims.height };
81
+ return {
82
+ x: 0,
83
+ y: 0,
84
+ width: dims.width,
85
+ height: dims.height,
86
+ devicePixelRatio: dims.devicePixelRatio,
87
+ };
75
88
  }
76
89
  const viewport = page.viewport();
77
90
  if (viewport) {
78
- return { x: 0, y: 0, width: viewport.width, height: viewport.height };
91
+ return {
92
+ x: 0,
93
+ y: 0,
94
+ width: viewport.width,
95
+ height: viewport.height,
96
+ devicePixelRatio: viewport.deviceScaleFactor ?? 1,
97
+ };
79
98
  }
80
99
  // The browser is launched and connected with `defaultViewport: null`, so
81
100
  // `page.viewport()` stays null until something emulates one. Fall back to the
@@ -83,21 +102,33 @@ async function getSourceBox(page, element, fullPage) {
83
102
  const dims = await page.evaluate(() => ({
84
103
  width: window.innerWidth,
85
104
  height: window.innerHeight,
105
+ devicePixelRatio: window.devicePixelRatio,
86
106
  }));
87
107
  if (dims.width <= 0 || dims.height <= 0) {
88
108
  return undefined;
89
109
  }
90
- return { x: 0, y: 0, width: dims.width, height: dims.height };
110
+ return {
111
+ x: 0,
112
+ y: 0,
113
+ width: dims.width,
114
+ height: dims.height,
115
+ devicePixelRatio: dims.devicePixelRatio,
116
+ };
91
117
  }
92
118
  function computeDownscaleClip(box, maxWidth, maxHeight) {
93
- const widthScale = maxWidth !== undefined ? Math.min(1, maxWidth / box.width) : 1;
94
- const heightScale = maxHeight !== undefined ? Math.min(1, maxHeight / box.height) : 1;
119
+ const widthScale = maxWidth !== undefined
120
+ ? Math.min(1, maxWidth / (box.width * box.devicePixelRatio))
121
+ : 1;
122
+ const heightScale = maxHeight !== undefined
123
+ ? Math.min(1, maxHeight / (box.height * box.devicePixelRatio))
124
+ : 1;
95
125
  const scale = Math.min(widthScale, heightScale);
96
126
  if (scale >= 1) {
97
127
  return undefined;
98
128
  }
99
129
  // Skip degenerate sub-pixel results.
100
- if (Math.round(box.width * scale) < 1 || Math.round(box.height * scale) < 1) {
130
+ if (Math.round(box.width * box.devicePixelRatio * scale) < 1 ||
131
+ Math.round(box.height * box.devicePixelRatio * scale) < 1) {
101
132
  return undefined;
102
133
  }
103
134
  return {
@@ -144,7 +175,9 @@ export const screenshot = definePageTool(args => {
144
175
  .describe('The absolute path, or a path relative to the current working directory, to save the screenshot to instead of attaching it to the response.'),
145
176
  },
146
177
  blockedByDialog: true,
147
- verifyFilesSchema: ['filePath'],
178
+ verifyFilesSchema: {
179
+ filePath: true,
180
+ },
148
181
  handler: async (request, response, context) => {
149
182
  const env_1 = { stack: [], error: void 0, hasError: false };
150
183
  try {
@@ -61,14 +61,24 @@ import { defineTool, pageIdSchema } from './ToolDefinition.js';
61
61
  export const evaluateScript = defineTool(cliArgs => {
62
62
  return {
63
63
  name: 'evaluate_script',
64
- description: `Evaluate a JavaScript function inside the currently selected page${cliArgs?.categoryExtensions ? ' or service worker' : ''}. Returns the response as JSON, so returned values have to be JSON-serializable.`,
64
+ description: `Evaluate a JavaScript function inside the target page${cliArgs?.categoryExtensions ? ' or service worker' : ''}. Returns the response as JSON, so returned values have to be JSON-serializable.`,
65
65
  annotations: {
66
66
  category: ToolCategory.DEBUGGING,
67
67
  readOnlyHint: false,
68
+ conditions: ['javascriptEvaluation'],
68
69
  },
69
70
  schema: {
70
- ...(cliArgs?.experimentalPageIdRouting ? pageIdSchema : {}),
71
- function: zod.string().describe(`A JavaScript function declaration to be executed by the tool in the currently selected page.
71
+ ...(cliArgs?.pageIdRouting
72
+ ? cliArgs.categoryExtensions
73
+ ? {
74
+ pageId: zod
75
+ .number()
76
+ .optional()
77
+ .describe('Targets a specific page by ID. Required when not evaluating in a service worker.'),
78
+ }
79
+ : pageIdSchema
80
+ : {}),
81
+ function: zod.string().describe(`A JavaScript function declaration to be executed by the tool in the target page.
72
82
  Example without arguments: \`() => document.title\` or \`async () => await fetch("example.com")\`.
73
83
  Example with arguments: \`(el) => el.innerText\`
74
84
  `),
@@ -86,6 +96,10 @@ Example with arguments: \`(el) => el.innerText\`
86
96
  .string()
87
97
  .optional()
88
98
  .describe('Handle dialogs while execution. "accept", "dismiss", or string for response of window.prompt. Defaults to accept.'),
99
+ waitForStableDom: zod
100
+ .boolean()
101
+ .optional()
102
+ .describe('Whether to wait for the DOM to settle. Pass false if the script only reads data. Defaults to true.'),
89
103
  ...(cliArgs?.categoryExtensions
90
104
  ? {
91
105
  serviceWorkerId: zod
@@ -96,11 +110,13 @@ Example with arguments: \`(el) => el.innerText\`
96
110
  : {}),
97
111
  },
98
112
  blockedByDialog: true,
99
- verifyFilesSchema: ['filePath'],
113
+ verifyFilesSchema: {
114
+ filePath: true,
115
+ },
100
116
  handler: async (request, response, context) => {
101
117
  const env_1 = { stack: [], error: void 0, hasError: false };
102
118
  try {
103
- const { serviceWorkerId, args: uidArgs, function: fnString, pageId, dialogAction, filePath, } = request.params;
119
+ const { serviceWorkerId, args: uidArgs, function: fnString, pageId, dialogAction, filePath, waitForStableDom, } = request.params;
104
120
  if (cliArgs?.categoryExtensions && serviceWorkerId) {
105
121
  if (uidArgs && uidArgs.length > 0) {
106
122
  throw new Error('args (element uids) cannot be used when evaluating in a service worker.');
@@ -116,14 +132,19 @@ Example with arguments: \`(el) => el.innerText\`
116
132
  filePath,
117
133
  context,
118
134
  });
119
- }, { handleDialog: dialogAction ?? 'accept' });
135
+ },
136
+ // Service workers cannot interact with the DOM, so never wait for it.
137
+ { handleDialog: dialogAction ?? 'accept', waitForStableDom: false });
120
138
  if (result.dialogHandled) {
121
139
  context.getSelectedMcpPage().clearDialog();
122
140
  }
123
141
  response.attachWaitForResult(result);
124
142
  return;
125
143
  }
126
- const mcpPage = cliArgs?.experimentalPageIdRouting
144
+ if (cliArgs?.categoryExtensions && cliArgs?.pageIdRouting && !pageId) {
145
+ throw new Error('specify either a pageId or a serviceWorkerId.');
146
+ }
147
+ const mcpPage = cliArgs?.pageIdRouting && request.params.pageId
127
148
  ? context.getPageById(request.params.pageId)
128
149
  : context.getSelectedMcpPage();
129
150
  const page = mcpPage.pptrPage;
@@ -142,7 +163,7 @@ Example with arguments: \`(el) => el.innerText\`
142
163
  filePath,
143
164
  context,
144
165
  });
145
- }, { handleDialog: dialogAction ?? 'accept' });
166
+ }, { handleDialog: dialogAction ?? 'accept', waitForStableDom });
146
167
  response.attachWaitForResult(result);
147
168
  }
148
169
  catch (e_1) {