@mcp-b/chrome-devtools-mcp 2.3.0 → 2.3.1-beta.20260528050333

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 (67) hide show
  1. package/package.json +1 -1
  2. package/build/src/DevToolsConnectionAdapter.js +0 -70
  3. package/build/src/DevtoolsUtils.js +0 -290
  4. package/build/src/McpContext.js +0 -687
  5. package/build/src/McpPage.js +0 -95
  6. package/build/src/McpResponse.js +0 -588
  7. package/build/src/Mutex.js +0 -37
  8. package/build/src/PageCollector.js +0 -308
  9. package/build/src/SlimMcpResponse.js +0 -18
  10. package/build/src/WaitForHelper.js +0 -135
  11. package/build/src/bin/chrome-devtools-cli-options.js +0 -651
  12. package/build/src/bin/chrome-devtools-mcp-cli-options.js +0 -317
  13. package/build/src/bin/chrome-devtools-mcp-main.js +0 -35
  14. package/build/src/bin/chrome-devtools-mcp.js +0 -21
  15. package/build/src/bin/chrome-devtools.js +0 -185
  16. package/build/src/bin/cliDefinitions.js +0 -615
  17. package/build/src/browser.js +0 -198
  18. package/build/src/daemon/client.js +0 -152
  19. package/build/src/daemon/daemon.js +0 -206
  20. package/build/src/daemon/types.js +0 -6
  21. package/build/src/daemon/utils.js +0 -108
  22. package/build/src/formatters/ConsoleFormatter.js +0 -234
  23. package/build/src/formatters/IssueFormatter.js +0 -192
  24. package/build/src/formatters/NetworkFormatter.js +0 -215
  25. package/build/src/formatters/SnapshotFormatter.js +0 -131
  26. package/build/src/index.js +0 -202
  27. package/build/src/issue-descriptions.js +0 -39
  28. package/build/src/logger.js +0 -36
  29. package/build/src/polyfill.js +0 -7
  30. package/build/src/telemetry/ClearcutLogger.js +0 -102
  31. package/build/src/telemetry/WatchdogClient.js +0 -60
  32. package/build/src/telemetry/flagUtils.js +0 -45
  33. package/build/src/telemetry/metricUtils.js +0 -14
  34. package/build/src/telemetry/persistence.js +0 -53
  35. package/build/src/telemetry/types.js +0 -33
  36. package/build/src/telemetry/watchdog/ClearcutSender.js +0 -203
  37. package/build/src/telemetry/watchdog/main.js +0 -127
  38. package/build/src/third_party/devtools-formatter-worker.js +0 -7
  39. package/build/src/third_party/index.js +0 -26
  40. package/build/src/third_party/lighthouse-devtools-mcp-bundle.js +0 -54183
  41. package/build/src/tools/ToolDefinition.js +0 -72
  42. package/build/src/tools/categories.js +0 -24
  43. package/build/src/tools/console.js +0 -85
  44. package/build/src/tools/emulation.js +0 -55
  45. package/build/src/tools/extensions.js +0 -96
  46. package/build/src/tools/input.js +0 -368
  47. package/build/src/tools/lighthouse.js +0 -123
  48. package/build/src/tools/memory.js +0 -28
  49. package/build/src/tools/network.js +0 -120
  50. package/build/src/tools/pages.js +0 -319
  51. package/build/src/tools/performance.js +0 -190
  52. package/build/src/tools/screencast.js +0 -79
  53. package/build/src/tools/screenshot.js +0 -84
  54. package/build/src/tools/script.js +0 -119
  55. package/build/src/tools/slim/tools.js +0 -81
  56. package/build/src/tools/snapshot.js +0 -56
  57. package/build/src/tools/tools.js +0 -52
  58. package/build/src/tools/webmcp.js +0 -416
  59. package/build/src/trace-processing/parse.js +0 -84
  60. package/build/src/types.js +0 -6
  61. package/build/src/utils/ExtensionRegistry.js +0 -35
  62. package/build/src/utils/files.js +0 -19
  63. package/build/src/utils/keyboard.js +0 -296
  64. package/build/src/utils/pagination.js +0 -49
  65. package/build/src/utils/string.js +0 -36
  66. package/build/src/utils/types.js +0 -6
  67. package/build/src/version.js +0 -9
@@ -1,319 +0,0 @@
1
- /**
2
- * @license
3
- * Copyright 2025 Google LLC
4
- * SPDX-License-Identifier: Apache-2.0
5
- */
6
- import { logger } from '../logger.js';
7
- import { zod } from '../third_party/index.js';
8
- import { ToolCategory } from './categories.js';
9
- import { CLOSE_PAGE_ERROR, definePageTool, defineTool, timeoutSchema } from './ToolDefinition.js';
10
- export const listPages = definePageTool((args) => {
11
- return {
12
- name: 'list_pages',
13
- description: `Get a list of pages ${args?.categoryExtensions ? 'including extension service workers' : ''} open in the browser.`,
14
- annotations: {
15
- category: ToolCategory.NAVIGATION,
16
- readOnlyHint: true,
17
- },
18
- schema: {},
19
- handler: async (_request, response) => {
20
- response.setIncludePages(true);
21
- },
22
- };
23
- });
24
- export const selectPage = defineTool({
25
- name: 'select_page',
26
- description: `Select a page as a context for future tool calls.`,
27
- annotations: {
28
- category: ToolCategory.NAVIGATION,
29
- readOnlyHint: true,
30
- },
31
- schema: {
32
- pageId: zod
33
- .number()
34
- .describe(`The ID of the page to select. Call ${listPages().name} to get available pages.`),
35
- bringToFront: zod
36
- .boolean()
37
- .optional()
38
- .describe('Whether to focus the page and bring it to the top.'),
39
- },
40
- handler: async (request, response, context) => {
41
- const page = context.getPageById(request.params.pageId);
42
- context.selectPage(page);
43
- response.setIncludePages(true);
44
- if (request.params.bringToFront) {
45
- await page.pptrPage.bringToFront();
46
- }
47
- },
48
- });
49
- export const closePage = defineTool({
50
- name: 'close_page',
51
- description: `Closes the page by its index. The last open page cannot be closed.`,
52
- annotations: {
53
- category: ToolCategory.NAVIGATION,
54
- readOnlyHint: false,
55
- },
56
- schema: {
57
- pageId: zod.number().describe('The ID of the page to close. Call list_pages to list pages.'),
58
- },
59
- handler: async (request, response, context) => {
60
- try {
61
- await context.closePage(request.params.pageId);
62
- }
63
- catch (err) {
64
- if (err.message === CLOSE_PAGE_ERROR) {
65
- response.appendResponseLine(err.message);
66
- }
67
- else {
68
- throw err;
69
- }
70
- }
71
- response.setIncludePages(true);
72
- },
73
- });
74
- export const newPage = defineTool({
75
- name: 'new_page',
76
- description: `Open a new tab and load a URL. Use project URL if not specified otherwise.`,
77
- annotations: {
78
- category: ToolCategory.NAVIGATION,
79
- readOnlyHint: false,
80
- },
81
- schema: {
82
- url: zod.string().describe('URL to load in a new page.'),
83
- background: zod
84
- .boolean()
85
- .optional()
86
- .describe('Whether to open the page in the background without bringing it to the front. Default is false (foreground).'),
87
- isolatedContext: zod
88
- .string()
89
- .optional()
90
- .describe('If specified, the page is created in an isolated browser context with the given name. ' +
91
- 'Pages in the same browser context share cookies and storage. ' +
92
- 'Pages in different browser contexts are fully isolated.'),
93
- ...timeoutSchema,
94
- },
95
- handler: async (request, response, context) => {
96
- const page = await context.newPage(request.params.background, request.params.isolatedContext);
97
- await context.waitForEventsAfterAction(async () => {
98
- await page.pptrPage.goto(request.params.url, {
99
- timeout: request.params.timeout,
100
- });
101
- }, { timeout: request.params.timeout });
102
- response.setIncludePages(true);
103
- },
104
- });
105
- export const navigatePage = definePageTool({
106
- name: 'navigate_page',
107
- description: `Go to a URL, or back, forward, or reload. Use project URL if not specified otherwise.`,
108
- annotations: {
109
- category: ToolCategory.NAVIGATION,
110
- readOnlyHint: false,
111
- },
112
- schema: {
113
- type: zod
114
- .enum(['url', 'back', 'forward', 'reload'])
115
- .optional()
116
- .describe('Navigate the page by URL, back or forward in history, or reload.'),
117
- url: zod.string().optional().describe('Target URL (only type=url)'),
118
- ignoreCache: zod.boolean().optional().describe('Whether to ignore cache on reload.'),
119
- handleBeforeUnload: zod
120
- .enum(['accept', 'decline'])
121
- .optional()
122
- .describe('Whether to auto accept or beforeunload dialogs triggered by this navigation. Default is accept.'),
123
- initScript: zod
124
- .string()
125
- .optional()
126
- .describe('A JavaScript script to be executed on each new document before any other scripts for the next navigation.'),
127
- ...timeoutSchema,
128
- },
129
- handler: async (request, response, context) => {
130
- const page = request.page;
131
- const options = {
132
- timeout: request.params.timeout,
133
- };
134
- if (!request.params.type && !request.params.url) {
135
- throw new Error('Either URL or a type is required.');
136
- }
137
- if (!request.params.type) {
138
- request.params.type = 'url';
139
- }
140
- const handleBeforeUnload = request.params.handleBeforeUnload ?? 'accept';
141
- const dialogHandler = (dialog) => {
142
- if (dialog.type() === 'beforeunload') {
143
- if (handleBeforeUnload === 'accept') {
144
- response.appendResponseLine(`Accepted a beforeunload dialog.`);
145
- void dialog.accept();
146
- }
147
- else {
148
- response.appendResponseLine(`Declined a beforeunload dialog.`);
149
- void dialog.dismiss();
150
- }
151
- // We are not going to report the dialog like regular dialogs.
152
- page.clearDialog();
153
- }
154
- };
155
- let initScriptId;
156
- if (request.params.initScript) {
157
- const { identifier } = await page.pptrPage.evaluateOnNewDocument(request.params.initScript);
158
- initScriptId = identifier;
159
- }
160
- page.pptrPage.on('dialog', dialogHandler);
161
- try {
162
- await context.waitForEventsAfterAction(async () => {
163
- switch (request.params.type) {
164
- case 'url':
165
- if (!request.params.url) {
166
- throw new Error('A URL is required for navigation of type=url.');
167
- }
168
- try {
169
- await page.pptrPage.goto(request.params.url, options);
170
- response.appendResponseLine(`Successfully navigated to ${request.params.url}.`);
171
- }
172
- catch (error) {
173
- response.appendResponseLine(`Unable to navigate in the selected page: ${error.message}.`);
174
- }
175
- break;
176
- case 'back':
177
- try {
178
- await page.pptrPage.goBack(options);
179
- response.appendResponseLine(`Successfully navigated back to ${page.pptrPage.url()}.`);
180
- }
181
- catch (error) {
182
- response.appendResponseLine(`Unable to navigate back in the selected page: ${error.message}.`);
183
- }
184
- break;
185
- case 'forward':
186
- try {
187
- await page.pptrPage.goForward(options);
188
- response.appendResponseLine(`Successfully navigated forward to ${page.pptrPage.url()}.`);
189
- }
190
- catch (error) {
191
- response.appendResponseLine(`Unable to navigate forward in the selected page: ${error.message}.`);
192
- }
193
- break;
194
- case 'reload':
195
- try {
196
- await page.pptrPage.reload({
197
- ...options,
198
- ignoreCache: request.params.ignoreCache,
199
- });
200
- response.appendResponseLine(`Successfully reloaded the page.`);
201
- }
202
- catch (error) {
203
- response.appendResponseLine(`Unable to reload the selected page: ${error.message}.`);
204
- }
205
- break;
206
- }
207
- }, { timeout: request.params.timeout });
208
- }
209
- finally {
210
- page.pptrPage.off('dialog', dialogHandler);
211
- if (initScriptId) {
212
- await page.pptrPage.removeScriptToEvaluateOnNewDocument(initScriptId).catch((error) => {
213
- logger(`Failed to remove init script`, error);
214
- });
215
- }
216
- }
217
- response.setIncludePages(true);
218
- },
219
- });
220
- export const resizePage = definePageTool({
221
- name: 'resize_page',
222
- description: `Resizes the selected page's window so that the page has specified dimension`,
223
- annotations: {
224
- category: ToolCategory.EMULATION,
225
- readOnlyHint: false,
226
- },
227
- schema: {
228
- width: zod.number().describe('Page width'),
229
- height: zod.number().describe('Page height'),
230
- },
231
- handler: async (request, response, _context) => {
232
- const page = request.page;
233
- try {
234
- const browser = page.pptrPage.browser();
235
- const windowId = await page.pptrPage.windowId();
236
- const bounds = await browser.getWindowBounds(windowId);
237
- if (bounds.windowState === 'fullscreen') {
238
- // Have to call this twice on Ubuntu when the window is in fullscreen mode.
239
- await browser.setWindowBounds(windowId, { windowState: 'normal' });
240
- await browser.setWindowBounds(windowId, { windowState: 'normal' });
241
- }
242
- else if (bounds.windowState !== 'normal') {
243
- await browser.setWindowBounds(windowId, { windowState: 'normal' });
244
- }
245
- }
246
- catch {
247
- // Window APIs are not supported on all platforms
248
- }
249
- await page.pptrPage.resize({
250
- contentWidth: request.params.width,
251
- contentHeight: request.params.height,
252
- });
253
- response.setIncludePages(true);
254
- },
255
- });
256
- export const handleDialog = definePageTool({
257
- name: 'handle_dialog',
258
- description: `If a browser dialog was opened, use this command to handle it`,
259
- annotations: {
260
- category: ToolCategory.INPUT,
261
- readOnlyHint: false,
262
- },
263
- schema: {
264
- action: zod.enum(['accept', 'dismiss']).describe('Whether to dismiss or accept the dialog'),
265
- promptText: zod.string().optional().describe('Optional prompt text to enter into the dialog.'),
266
- },
267
- handler: async (request, response, _context) => {
268
- const page = request.page;
269
- const dialog = page.getDialog();
270
- if (!dialog) {
271
- throw new Error('No open dialog found');
272
- }
273
- switch (request.params.action) {
274
- case 'accept': {
275
- try {
276
- await dialog.accept(request.params.promptText);
277
- }
278
- catch (err) {
279
- // Likely already handled by the user outside of MCP.
280
- logger(err);
281
- }
282
- response.appendResponseLine('Successfully accepted the dialog');
283
- break;
284
- }
285
- case 'dismiss': {
286
- try {
287
- await dialog.dismiss();
288
- }
289
- catch (err) {
290
- // Likely already handled.
291
- logger(err);
292
- }
293
- response.appendResponseLine('Successfully dismissed the dialog');
294
- break;
295
- }
296
- }
297
- page.clearDialog();
298
- response.setIncludePages(true);
299
- },
300
- });
301
- export const getTabId = definePageTool({
302
- name: 'get_tab_id',
303
- description: `Get the tab ID of the page`,
304
- annotations: {
305
- category: ToolCategory.NAVIGATION,
306
- readOnlyHint: true,
307
- conditions: ['experimentalInteropTools'],
308
- },
309
- schema: {
310
- pageId: zod
311
- .number()
312
- .describe(`The ID of the page to get the tab ID for. Call ${listPages().name} to get available pages.`),
313
- },
314
- handler: async (request, response, context) => {
315
- const page = context.getPageById(request.params.pageId);
316
- const tabId = page.pptrPage._tabId;
317
- response.setTabId(tabId);
318
- },
319
- });
@@ -1,190 +0,0 @@
1
- /**
2
- * @license
3
- * Copyright 2025 Google LLC
4
- * SPDX-License-Identifier: Apache-2.0
5
- */
6
- import zlib from 'node:zlib';
7
- import { logger } from '../logger.js';
8
- import { zod, DevTools } from '../third_party/index.js';
9
- import { parseRawTraceBuffer, traceResultIsSuccess } from '../trace-processing/parse.js';
10
- import { ToolCategory } from './categories.js';
11
- import { definePageTool } from './ToolDefinition.js';
12
- const filePathSchema = zod
13
- .string()
14
- .optional()
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
- export const startTrace = definePageTool({
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.`,
19
- annotations: {
20
- category: ToolCategory.PERFORMANCE,
21
- readOnlyHint: false,
22
- },
23
- schema: {
24
- reload: zod
25
- .boolean()
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.'),
28
- autoStop: zod
29
- .boolean()
30
- .default(true)
31
- .describe('Determines if the trace recording should be automatically stopped.'),
32
- filePath: filePathSchema,
33
- },
34
- handler: async (request, response, context) => {
35
- if (context.isRunningPerformanceTrace()) {
36
- 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.');
37
- return;
38
- }
39
- context.setIsRunningPerformanceTrace(true);
40
- const page = request.page;
41
- const pageUrlForTracing = page.pptrPage.url();
42
- if (request.params.reload) {
43
- // Before starting the recording, navigate to about:blank to clear out any state.
44
- await page.pptrPage.goto('about:blank', {
45
- waitUntil: ['networkidle0'],
46
- });
47
- }
48
- // Keep in sync with the categories arrays in:
49
- // https://source.chromium.org/chromium/chromium/src/+/main:third_party/devtools-frontend/src/front_end/panels/timeline/TimelineController.ts
50
- // https://github.com/GoogleChrome/lighthouse/blob/master/lighthouse-core/gather/gatherers/trace.js
51
- const categories = [
52
- '-*',
53
- 'blink.console',
54
- 'blink.user_timing',
55
- 'devtools.timeline',
56
- 'disabled-by-default-devtools.screenshot',
57
- 'disabled-by-default-devtools.timeline',
58
- 'disabled-by-default-devtools.timeline.invalidationTracking',
59
- 'disabled-by-default-devtools.timeline.frame',
60
- 'disabled-by-default-devtools.timeline.stack',
61
- 'disabled-by-default-v8.cpu_profiler',
62
- 'disabled-by-default-v8.cpu_profiler.hires',
63
- 'latencyInfo',
64
- 'loading',
65
- 'disabled-by-default-lighthouse',
66
- 'v8.execute',
67
- 'v8',
68
- ];
69
- await page.pptrPage.tracing.start({
70
- categories,
71
- });
72
- if (request.params.reload) {
73
- await page.pptrPage.goto(pageUrlForTracing, {
74
- waitUntil: ['load'],
75
- });
76
- }
77
- if (request.params.autoStop) {
78
- await new Promise((resolve) => setTimeout(resolve, 5_000));
79
- await stopTracingAndAppendOutput(page.pptrPage, response, context, request.params.filePath);
80
- }
81
- else {
82
- response.appendResponseLine(`The performance trace is being recorded. Use performance_stop_trace to stop it.`);
83
- }
84
- },
85
- });
86
- export const stopTrace = definePageTool({
87
- name: 'performance_stop_trace',
88
- description: 'Stop the active performance trace recording on the selected webpage.',
89
- annotations: {
90
- category: ToolCategory.PERFORMANCE,
91
- readOnlyHint: false,
92
- },
93
- schema: {
94
- filePath: filePathSchema,
95
- },
96
- handler: async (request, response, context) => {
97
- if (!context.isRunningPerformanceTrace()) {
98
- return;
99
- }
100
- const page = request.page;
101
- await stopTracingAndAppendOutput(page.pptrPage, response, context, request.params.filePath);
102
- },
103
- });
104
- export const analyzeInsight = definePageTool({
105
- name: 'performance_analyze_insight',
106
- description: 'Provides more detailed information on a specific Performance Insight of an insight set that was highlighted in the results of a trace recording.',
107
- annotations: {
108
- category: ToolCategory.PERFORMANCE,
109
- readOnlyHint: true,
110
- },
111
- schema: {
112
- insightSetId: zod
113
- .string()
114
- .describe('The id for the specific insight set. Only use the ids given in the "Available insight sets" list.'),
115
- insightName: zod
116
- .string()
117
- .describe('The name of the Insight you want more information on. For example: "DocumentLatency" or "LCPBreakdown"'),
118
- },
119
- handler: async (request, response, context) => {
120
- const lastRecording = context.recordedTraces().at(-1);
121
- if (!lastRecording) {
122
- response.appendResponseLine('No recorded traces found. Record a performance trace so you have Insights to analyze.');
123
- return;
124
- }
125
- response.attachTraceInsight(lastRecording, request.params.insightSetId, request.params.insightName);
126
- },
127
- });
128
- async function stopTracingAndAppendOutput(page, response, context, filePath) {
129
- try {
130
- const traceEventsBuffer = await page.tracing.stop();
131
- if (filePath && traceEventsBuffer) {
132
- let dataToWrite = traceEventsBuffer;
133
- if (filePath.endsWith('.gz')) {
134
- dataToWrite = await new Promise((resolve, reject) => {
135
- zlib.gzip(traceEventsBuffer, (error, result) => {
136
- if (error) {
137
- reject(error);
138
- }
139
- else {
140
- resolve(result);
141
- }
142
- });
143
- });
144
- }
145
- const file = await context.saveFile(dataToWrite, filePath);
146
- response.appendResponseLine(`The raw trace data was saved to ${file.filename}.`);
147
- }
148
- const result = await parseRawTraceBuffer(traceEventsBuffer);
149
- response.appendResponseLine('The performance trace has been stopped.');
150
- if (traceResultIsSuccess(result)) {
151
- if (context.isCruxEnabled()) {
152
- await populateCruxData(result);
153
- }
154
- context.storeTraceRecording(result);
155
- response.attachTraceSummary(result);
156
- }
157
- else {
158
- throw new Error(`There was an unexpected error parsing the trace: ${result.error}`);
159
- }
160
- }
161
- finally {
162
- context.setIsRunningPerformanceTrace(false);
163
- }
164
- }
165
- /** We tell CrUXManager to fetch data so it's available when DevTools.PerformanceTraceFormatter is invoked */
166
- async function populateCruxData(result) {
167
- logger('populateCruxData called');
168
- const cruxManager = DevTools.CrUXManager.instance();
169
- // go/jtfbx. Yes, we're aware this API key is public. ;)
170
- cruxManager.setEndpointForTesting('https://chromeuxreport.googleapis.com/v1/records:queryRecord?key=AIzaSyBn5gimNjhiEyA_euicSKko6IlD3HdgUfk');
171
- const cruxSetting = DevTools.Common.Settings.Settings.instance().createSetting('field-data', {
172
- enabled: true,
173
- });
174
- cruxSetting.set({ enabled: true });
175
- // Gather URLs to fetch CrUX data for
176
- const urls = [...(result.parsedTrace.insights?.values() ?? [])].map((c) => c.url.toString());
177
- urls.push(result.parsedTrace.data.Meta.mainFrameURL);
178
- const urlSet = new Set(urls);
179
- if (urlSet.size === 0) {
180
- logger('No URLs found for CrUX data');
181
- return;
182
- }
183
- logger(`Fetching CrUX data for ${urlSet.size} URLs: ${Array.from(urlSet).join(', ')}`);
184
- const cruxData = await Promise.all(Array.from(urlSet).map(async (url) => {
185
- const data = await cruxManager.getFieldDataForPage(url);
186
- logger(`CrUX data for ${url}: ${data ? 'found' : 'not found'}`);
187
- return data;
188
- }));
189
- result.parsedTrace.metadata.cruxFieldData = cruxData;
190
- }
@@ -1,79 +0,0 @@
1
- /**
2
- * @license
3
- * Copyright 2026 Google LLC
4
- * SPDX-License-Identifier: Apache-2.0
5
- */
6
- import fs from 'node:fs/promises';
7
- import os from 'node:os';
8
- import path from 'node:path';
9
- import { zod } from '../third_party/index.js';
10
- import { ToolCategory } from './categories.js';
11
- import { definePageTool } from './ToolDefinition.js';
12
- async function generateTempFilePath() {
13
- const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'chrome-devtools-mcp-'));
14
- return path.join(dir, `screencast.mp4`);
15
- }
16
- export const startScreencast = definePageTool({
17
- name: 'screencast_start',
18
- description: 'Starts recording a screencast (video) of the selected page in mp4 format.',
19
- annotations: {
20
- category: ToolCategory.DEBUGGING,
21
- readOnlyHint: false,
22
- conditions: ['screencast'],
23
- },
24
- schema: {
25
- path: zod
26
- .string()
27
- .optional()
28
- .describe('Output path. Uses mkdtemp to generate a unique path if not provided.'),
29
- },
30
- handler: async (request, response, context) => {
31
- if (context.getScreenRecorder() !== null) {
32
- response.appendResponseLine('Error: a screencast recording is already in progress. Use screencast_stop to stop it before starting a new one.');
33
- return;
34
- }
35
- const filePath = request.params.path ?? (await generateTempFilePath());
36
- const resolvedPath = path.resolve(filePath);
37
- const page = request.page;
38
- let recorder;
39
- try {
40
- recorder = await page.pptrPage.screencast({
41
- path: resolvedPath,
42
- format: 'mp4',
43
- });
44
- }
45
- catch (err) {
46
- const message = err instanceof Error ? err.message : String(err);
47
- if (message.includes('ENOENT') && message.includes('ffmpeg')) {
48
- throw new Error('ffmpeg is required for screencast recording but was not found. ' +
49
- 'Install ffmpeg (https://ffmpeg.org/) and ensure it is available in your PATH.');
50
- }
51
- throw err;
52
- }
53
- context.setScreenRecorder({ recorder, filePath: resolvedPath });
54
- response.appendResponseLine(`Screencast recording started. The recording will be saved to ${resolvedPath}. Use ${stopScreencast.name} to stop recording.`);
55
- },
56
- });
57
- export const stopScreencast = definePageTool({
58
- name: 'screencast_stop',
59
- description: 'Stops the active screencast recording on the selected page.',
60
- annotations: {
61
- category: ToolCategory.DEBUGGING,
62
- readOnlyHint: false,
63
- conditions: ['screencast'],
64
- },
65
- schema: {},
66
- handler: async (_request, response, context) => {
67
- const data = context.getScreenRecorder();
68
- if (!data) {
69
- return;
70
- }
71
- try {
72
- await data.recorder.stop();
73
- response.appendResponseLine(`The screencast recording has been stopped and saved to ${data.filePath}.`);
74
- }
75
- finally {
76
- context.setScreenRecorder(null);
77
- }
78
- },
79
- });
@@ -1,84 +0,0 @@
1
- /**
2
- * @license
3
- * Copyright 2025 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 { definePageTool } from './ToolDefinition.js';
9
- export const screenshot = definePageTool({
10
- name: 'take_screenshot',
11
- description: `Take a screenshot of the page or element.`,
12
- annotations: {
13
- category: ToolCategory.DEBUGGING,
14
- // Not read-only due to filePath param.
15
- readOnlyHint: false,
16
- },
17
- schema: {
18
- format: zod
19
- .enum(['png', 'jpeg', 'webp'])
20
- .default('png')
21
- .describe('Type of format to save the screenshot as. Default is "png"'),
22
- quality: zod
23
- .number()
24
- .min(0)
25
- .max(100)
26
- .optional()
27
- .describe('Compression quality for JPEG and WebP formats (0-100). Higher values mean better quality but larger file sizes. Ignored for PNG format.'),
28
- uid: zod
29
- .string()
30
- .optional()
31
- .describe('The uid of an element on the page from the page content snapshot. If omitted takes a pages screenshot.'),
32
- fullPage: zod
33
- .boolean()
34
- .optional()
35
- .describe('If set to true takes a screenshot of the full page instead of the currently visible viewport. Incompatible with uid.'),
36
- filePath: zod
37
- .string()
38
- .optional()
39
- .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.'),
40
- },
41
- handler: async (request, response, context) => {
42
- if (request.params.uid && request.params.fullPage) {
43
- throw new Error('Providing both "uid" and "fullPage" is not allowed.');
44
- }
45
- let pageOrHandle;
46
- if (request.params.uid) {
47
- pageOrHandle = await request.page.getElementByUid(request.params.uid);
48
- }
49
- else {
50
- pageOrHandle = request.page.pptrPage;
51
- }
52
- const format = request.params.format;
53
- const quality = format === 'png' ? undefined : request.params.quality;
54
- const screenshot = await pageOrHandle.screenshot({
55
- type: format,
56
- fullPage: request.params.fullPage,
57
- quality,
58
- optimizeForSpeed: true, // Bonus: optimize encoding for speed
59
- });
60
- if (request.params.uid) {
61
- response.appendResponseLine(`Took a screenshot of node with uid "${request.params.uid}".`);
62
- }
63
- else if (request.params.fullPage) {
64
- response.appendResponseLine('Took a screenshot of the full current page.');
65
- }
66
- else {
67
- response.appendResponseLine("Took a screenshot of the current page's viewport.");
68
- }
69
- if (request.params.filePath) {
70
- const file = await context.saveFile(screenshot, request.params.filePath);
71
- response.appendResponseLine(`Saved screenshot to ${file.filename}.`);
72
- }
73
- else if (screenshot.length >= 2_000_000) {
74
- const { filepath } = await context.saveTemporaryFile(screenshot, `screenshot.${request.params.format}`);
75
- response.appendResponseLine(`Saved screenshot to ${filepath}.`);
76
- }
77
- else {
78
- response.attachImage({
79
- mimeType: `image/${request.params.format}`,
80
- data: Buffer.from(screenshot).toString('base64'),
81
- });
82
- }
83
- },
84
- });