diff --git a/README.md b/README.md index 438024c3e..a0f5d0c1c 100644 --- a/README.md +++ b/README.md @@ -468,8 +468,9 @@ If you run into any issues, checkout our [troubleshooting guide](./docs/troubles - **Network** (2 tools) - [`get_network_request`](docs/tool-reference.md#get_network_request) - [`list_network_requests`](docs/tool-reference.md#list_network_requests) -- **Debugging** (6 tools) +- **Debugging** (7 tools) - [`evaluate_script`](docs/tool-reference.md#evaluate_script) + - [`evaluate_script_file`](docs/tool-reference.md#evaluate_script_file) - [`get_console_message`](docs/tool-reference.md#get_console_message) - [`lighthouse_audit`](docs/tool-reference.md#lighthouse_audit) - [`list_console_messages`](docs/tool-reference.md#list_console_messages) diff --git a/docs/tool-reference.md b/docs/tool-reference.md index 50b4c02c5..42702a05b 100644 --- a/docs/tool-reference.md +++ b/docs/tool-reference.md @@ -1,6 +1,6 @@ -# Chrome DevTools MCP Tool Reference (~6940 cl100k_base tokens) +# Chrome DevTools MCP Tool Reference (~7262 cl100k_base tokens) - **[Input automation](#input-automation)** (9 tools) - [`click`](#click) @@ -30,8 +30,9 @@ - **[Network](#network)** (2 tools) - [`get_network_request`](#get_network_request) - [`list_network_requests`](#list_network_requests) -- **[Debugging](#debugging)** (6 tools) +- **[Debugging](#debugging)** (7 tools) - [`evaluate_script`](#evaluate_script) + - [`evaluate_script_file`](#evaluate_script_file) - [`get_console_message`](#get_console_message) - [`lighthouse_audit`](#lighthouse_audit) - [`list_console_messages`](#list_console_messages) @@ -157,7 +158,7 @@ ### `list_pages` -**Description:** Get a list of pages open in the browser. +**Description:** Get a list of pages open in the browser. **Parameters:** None @@ -323,12 +324,12 @@ so returned values have to be JSON-serializable. **Parameters:** - **function** (string) **(required)**: A JavaScript function declaration to be executed by the tool in the currently selected page. - Example without arguments: `() => { +Example without arguments: `() => { return document.title }` or `async () => { return await fetch("example.com") }`. - Example with arguments: `(el) => { +Example with arguments: `(el) => { return el.innerText; }` @@ -336,6 +337,23 @@ so returned values have to be JSON-serializable. --- +### `evaluate_script_file` + +**Description:** Read a JavaScript file from the local filesystem and evaluate it inside the currently selected page. +The file should contain a JavaScript function declaration (e.g., an arrow function or function expression). +Returns the response as JSON, so returned values have to be JSON-serializable. +This is useful for evaluating large scripts without needing to pass the entire script content as a parameter. + +**Parameters:** + +- **filePath** (string) **(required)**: The absolute path to a JavaScript file containing a function declaration to be executed in the currently selected page. +The file content should be a JavaScript function declaration, for example: +`() => { return document.title; }` or `async () => { return await fetch("example.com"); }` + +- **args** (array) _(optional)_: An optional list of arguments to pass to the function. + +--- + ### `get_console_message` **Description:** Gets a console message by its ID. You can get all messages by calling [`list_console_messages`](#list_console_messages). diff --git a/src/bin/cliDefinitions.ts b/src/bin/cliDefinitions.ts index d32705617..f3ae0f67e 100644 --- a/src/bin/cliDefinitions.ts +++ b/src/bin/cliDefinitions.ts @@ -19,688 +19,665 @@ export type Commands = Record< { description: string; category: string; - args: Record; + args: Record } >; export const commands: Commands = { - click: { - description: 'Clicks on the provided element', - category: 'Input automation', - args: { - uid: { - name: 'uid', - type: 'string', - description: - 'The uid of an element on the page from the page content snapshot', - required: true, - }, - dblClick: { - name: 'dblClick', - type: 'boolean', - description: 'Set to true for double clicks. Default is false.', - required: false, - }, - includeSnapshot: { - name: 'includeSnapshot', - type: 'boolean', - description: - 'Whether to include a snapshot in the response. Default is false.', - required: false, - }, - }, + "click": { + "description": "Clicks on the provided element", + "category": "Input automation", + "args": { + "uid": { + "name": "uid", + "type": "string", + "description": "The uid of an element on the page from the page content snapshot", + "required": true + }, + "dblClick": { + "name": "dblClick", + "type": "boolean", + "description": "Set to true for double clicks. Default is false.", + "required": false + }, + "includeSnapshot": { + "name": "includeSnapshot", + "type": "boolean", + "description": "Whether to include a snapshot in the response. Default is false.", + "required": false + } + } }, - close_page: { - description: - 'Closes the page by its index. The last open page cannot be closed.', - category: 'Navigation automation', - args: { - pageId: { - name: 'pageId', - type: 'number', - description: - 'The ID of the page to close. Call list_pages to list pages.', - required: true, - }, - }, + "close_page": { + "description": "Closes the page by its index. The last open page cannot be closed.", + "category": "Navigation automation", + "args": { + "pageId": { + "name": "pageId", + "type": "number", + "description": "The ID of the page to close. Call list_pages to list pages.", + "required": true + } + } }, - drag: { - description: 'Drag an element onto another element', - category: 'Input automation', - args: { - from_uid: { - name: 'from_uid', - type: 'string', - description: 'The uid of the element to drag', - required: true, - }, - to_uid: { - name: 'to_uid', - type: 'string', - description: 'The uid of the element to drop into', - required: true, - }, - includeSnapshot: { - name: 'includeSnapshot', - type: 'boolean', - description: - 'Whether to include a snapshot in the response. Default is false.', - required: false, - }, - }, + "drag": { + "description": "Drag an element onto another element", + "category": "Input automation", + "args": { + "from_uid": { + "name": "from_uid", + "type": "string", + "description": "The uid of the element to drag", + "required": true + }, + "to_uid": { + "name": "to_uid", + "type": "string", + "description": "The uid of the element to drop into", + "required": true + }, + "includeSnapshot": { + "name": "includeSnapshot", + "type": "boolean", + "description": "Whether to include a snapshot in the response. Default is false.", + "required": false + } + } }, - emulate: { - description: 'Emulates various features on the selected page.', - category: 'Emulation', - args: { - networkConditions: { - name: 'networkConditions', - type: 'string', - description: 'Throttle network. Omit to disable throttling.', - required: false, - enum: ['Offline', 'Slow 3G', 'Fast 3G', 'Slow 4G', 'Fast 4G'], - }, - cpuThrottlingRate: { - name: 'cpuThrottlingRate', - type: 'number', - description: - 'Represents the CPU slowdown factor. Omit or set the rate to 1 to disable throttling', - required: false, - }, - geolocation: { - name: 'geolocation', - type: 'string', - description: - 'Geolocation (`x`) to emulate. Latitude between -90 and 90. Longitude between -180 and 180. Omit clear the geolocation override.', - required: false, - }, - userAgent: { - name: 'userAgent', - type: 'string', - description: - 'User agent to emulate. Set to empty string to clear the user agent override.', - required: false, - }, - colorScheme: { - name: 'colorScheme', - type: 'string', - description: - 'Emulate the dark or the light mode. Set to "auto" to reset to the default.', - required: false, - enum: ['dark', 'light', 'auto'], - }, - viewport: { - name: 'viewport', - type: 'string', - description: - "Emulate device viewports 'xx[,mobile][,touch][,landscape]'. 'touch' and 'mobile' to emulate mobile devices. 'landscape' to emulate landscape mode.", - required: false, - }, - }, + "emulate": { + "description": "Emulates various features on the selected page.", + "category": "Emulation", + "args": { + "networkConditions": { + "name": "networkConditions", + "type": "string", + "description": "Throttle network. Omit to disable throttling.", + "required": false, + "enum": [ + "Offline", + "Slow 3G", + "Fast 3G", + "Slow 4G", + "Fast 4G" + ] + }, + "cpuThrottlingRate": { + "name": "cpuThrottlingRate", + "type": "number", + "description": "Represents the CPU slowdown factor. Omit or set the rate to 1 to disable throttling", + "required": false + }, + "geolocation": { + "name": "geolocation", + "type": "string", + "description": "Geolocation (`x`) to emulate. Latitude between -90 and 90. Longitude between -180 and 180. Omit clear the geolocation override.", + "required": false + }, + "userAgent": { + "name": "userAgent", + "type": "string", + "description": "User agent to emulate. Set to empty string to clear the user agent override.", + "required": false + }, + "colorScheme": { + "name": "colorScheme", + "type": "string", + "description": "Emulate the dark or the light mode. Set to \"auto\" to reset to the default.", + "required": false, + "enum": [ + "dark", + "light", + "auto" + ] + }, + "viewport": { + "name": "viewport", + "type": "string", + "description": "Emulate device viewports 'xx[,mobile][,touch][,landscape]'. 'touch' and 'mobile' to emulate mobile devices. 'landscape' to emulate landscape mode.", + "required": false + } + } }, - evaluate_script: { - description: - 'Evaluate a JavaScript function inside the currently selected page. Returns the response as JSON,\nso returned values have to be JSON-serializable.', - category: 'Debugging', - args: { - function: { - name: 'function', - type: 'string', - description: - 'A JavaScript function declaration to be executed by the tool in the currently selected page.\nExample without arguments: `() => {\n return document.title\n}` or `async () => {\n return await fetch("example.com")\n}`.\nExample with arguments: `(el) => {\n return el.innerText;\n}`\n', - required: true, - }, - args: { - name: 'args', - type: 'array', - description: 'An optional list of arguments to pass to the function.', - required: false, - }, - }, + "evaluate_script": { + "description": "Evaluate a JavaScript function inside the currently selected page. Returns the response as JSON,\nso returned values have to be JSON-serializable.", + "category": "Debugging", + "args": { + "function": { + "name": "function", + "type": "string", + "description": "A JavaScript function declaration to be executed by the tool in the currently selected page.\nExample without arguments: `() => {\n return document.title\n}` or `async () => {\n return await fetch(\"example.com\")\n}`.\nExample with arguments: `(el) => {\n return el.innerText;\n}`\n", + "required": true + }, + "args": { + "name": "args", + "type": "array", + "description": "An optional list of arguments to pass to the function.", + "required": false + } + } }, - fill: { - description: - 'Type text into a input, text area or select an option from a element.", + "category": "Input automation", + "args": { + "uid": { + "name": "uid", + "type": "string", + "description": "The uid of an element on the page from the page content snapshot", + "required": true + }, + "value": { + "name": "value", + "type": "string", + "description": "The value to fill in", + "required": true + }, + "includeSnapshot": { + "name": "includeSnapshot", + "type": "boolean", + "description": "Whether to include a snapshot in the response. Default is false.", + "required": false + } + } }, - get_network_request: { - description: - 'Gets a network request by an optional reqid, if omitted returns the currently selected request in the DevTools Network panel.', - category: 'Network', - args: { - reqid: { - name: 'reqid', - type: 'number', - description: - 'The reqid of the network request. If omitted returns the currently selected request in the DevTools Network panel.', - required: false, - }, - requestFilePath: { - name: 'requestFilePath', - type: 'string', - description: - 'The absolute or relative path to save the request body to. If omitted, the body is returned inline.', - required: false, - }, - responseFilePath: { - name: 'responseFilePath', - type: 'string', - description: - 'The absolute or relative path to save the response body to. If omitted, the body is returned inline.', - required: false, - }, - }, + "get_console_message": { + "description": "Gets a console message by its ID. You can get all messages by calling list_console_messages.", + "category": "Debugging", + "args": { + "msgid": { + "name": "msgid", + "type": "number", + "description": "The msgid of a console message on the page from the listed console messages", + "required": true + } + } }, - handle_dialog: { - description: - 'If a browser dialog was opened, use this command to handle it', - category: 'Input automation', - args: { - action: { - name: 'action', - type: 'string', - description: 'Whether to dismiss or accept the dialog', - required: true, - enum: ['accept', 'dismiss'], - }, - promptText: { - name: 'promptText', - type: 'string', - description: 'Optional prompt text to enter into the dialog.', - required: false, - }, - }, + "get_network_request": { + "description": "Gets a network request by an optional reqid, if omitted returns the currently selected request in the DevTools Network panel.", + "category": "Network", + "args": { + "reqid": { + "name": "reqid", + "type": "number", + "description": "The reqid of the network request. If omitted returns the currently selected request in the DevTools Network panel.", + "required": false + }, + "requestFilePath": { + "name": "requestFilePath", + "type": "string", + "description": "The absolute or relative path to save the request body to. If omitted, the body is returned inline.", + "required": false + }, + "responseFilePath": { + "name": "responseFilePath", + "type": "string", + "description": "The absolute or relative path to save the response body to. If omitted, the body is returned inline.", + "required": false + } + } }, - hover: { - description: 'Hover over the provided element', - category: 'Input automation', - args: { - uid: { - name: 'uid', - type: 'string', - description: - 'The uid of an element on the page from the page content snapshot', - required: true, - }, - includeSnapshot: { - name: 'includeSnapshot', - type: 'boolean', - description: - 'Whether to include a snapshot in the response. Default is false.', - required: false, - }, - }, + "handle_dialog": { + "description": "If a browser dialog was opened, use this command to handle it", + "category": "Input automation", + "args": { + "action": { + "name": "action", + "type": "string", + "description": "Whether to dismiss or accept the dialog", + "required": true, + "enum": [ + "accept", + "dismiss" + ] + }, + "promptText": { + "name": "promptText", + "type": "string", + "description": "Optional prompt text to enter into the dialog.", + "required": false + } + } }, - lighthouse_audit: { - description: - 'Get Lighthouse score and reports for accessibility, SEO and best practices. This excludes performance. For performance audits, run performance_start_trace', - category: 'Debugging', - args: { - mode: { - name: 'mode', - type: 'string', - description: - '"navigation" reloads & audits. "snapshot" analyzes current state.', - required: false, - default: 'navigation', - enum: ['navigation', 'snapshot'], - }, - device: { - name: 'device', - type: 'string', - description: 'Device to emulate.', - required: false, - default: 'desktop', - enum: ['desktop', 'mobile'], - }, - outputDirPath: { - name: 'outputDirPath', - type: 'string', - description: 'Directory for reports. If omitted, uses temporary files.', - required: false, - }, - }, + "hover": { + "description": "Hover over the provided element", + "category": "Input automation", + "args": { + "uid": { + "name": "uid", + "type": "string", + "description": "The uid of an element on the page from the page content snapshot", + "required": true + }, + "includeSnapshot": { + "name": "includeSnapshot", + "type": "boolean", + "description": "Whether to include a snapshot in the response. Default is false.", + "required": false + } + } }, - list_console_messages: { - description: - 'List all console messages for the currently selected page since the last navigation.', - category: 'Debugging', - args: { - pageSize: { - name: 'pageSize', - type: 'integer', - description: - 'Maximum number of messages to return. When omitted, returns all requests.', - required: false, - }, - pageIdx: { - name: 'pageIdx', - type: 'integer', - description: - 'Page number to return (0-based). When omitted, returns the first page.', - required: false, - }, - types: { - name: 'types', - type: 'array', - description: - 'Filter messages to only return messages of the specified resource types. When omitted or empty, returns all messages.', - required: false, - }, - includePreservedMessages: { - name: 'includePreservedMessages', - type: 'boolean', - description: - 'Set to true to return the preserved messages over the last 3 navigations.', - required: false, - default: false, - }, - }, + "lighthouse_audit": { + "description": "Get Lighthouse score and reports for accessibility, SEO and best practices. This excludes performance. For performance audits, run performance_start_trace", + "category": "Debugging", + "args": { + "mode": { + "name": "mode", + "type": "string", + "description": "\"navigation\" reloads & audits. \"snapshot\" analyzes current state.", + "required": false, + "default": "navigation", + "enum": [ + "navigation", + "snapshot" + ] + }, + "device": { + "name": "device", + "type": "string", + "description": "Device to emulate.", + "required": false, + "default": "desktop", + "enum": [ + "desktop", + "mobile" + ] + }, + "outputDirPath": { + "name": "outputDirPath", + "type": "string", + "description": "Directory for reports. If omitted, uses temporary files.", + "required": false + } + } }, - list_network_requests: { - description: - 'List all requests for the currently selected page since the last navigation.', - category: 'Network', - args: { - pageSize: { - name: 'pageSize', - type: 'integer', - description: - 'Maximum number of requests to return. When omitted, returns all requests.', - required: false, - }, - pageIdx: { - name: 'pageIdx', - type: 'integer', - description: - 'Page number to return (0-based). When omitted, returns the first page.', - required: false, - }, - resourceTypes: { - name: 'resourceTypes', - type: 'array', - description: - 'Filter requests to only return requests of the specified resource types. When omitted or empty, returns all requests.', - required: false, - }, - includePreservedRequests: { - name: 'includePreservedRequests', - type: 'boolean', - description: - 'Set to true to return the preserved requests over the last 3 navigations.', - required: false, - default: false, - }, - }, + "list_console_messages": { + "description": "List all console messages for the currently selected page since the last navigation.", + "category": "Debugging", + "args": { + "pageSize": { + "name": "pageSize", + "type": "integer", + "description": "Maximum number of messages to return. When omitted, returns all requests.", + "required": false + }, + "pageIdx": { + "name": "pageIdx", + "type": "integer", + "description": "Page number to return (0-based). When omitted, returns the first page.", + "required": false + }, + "types": { + "name": "types", + "type": "array", + "description": "Filter messages to only return messages of the specified resource types. When omitted or empty, returns all messages.", + "required": false + }, + "includePreservedMessages": { + "name": "includePreservedMessages", + "type": "boolean", + "description": "Set to true to return the preserved messages over the last 3 navigations.", + "required": false, + "default": false + } + } }, - list_pages: { - description: 'Get a list of pages open in the browser.', - category: 'Navigation automation', - args: {}, + "list_network_requests": { + "description": "List all requests for the currently selected page since the last navigation.", + "category": "Network", + "args": { + "pageSize": { + "name": "pageSize", + "type": "integer", + "description": "Maximum number of requests to return. When omitted, returns all requests.", + "required": false + }, + "pageIdx": { + "name": "pageIdx", + "type": "integer", + "description": "Page number to return (0-based). When omitted, returns the first page.", + "required": false + }, + "resourceTypes": { + "name": "resourceTypes", + "type": "array", + "description": "Filter requests to only return requests of the specified resource types. When omitted or empty, returns all requests.", + "required": false + }, + "includePreservedRequests": { + "name": "includePreservedRequests", + "type": "boolean", + "description": "Set to true to return the preserved requests over the last 3 navigations.", + "required": false, + "default": false + } + } }, - navigate_page: { - description: - 'Go to a URL, or back, forward, or reload. Use project URL if not specified otherwise.', - category: 'Navigation automation', - args: { - type: { - name: 'type', - type: 'string', - description: - 'Navigate the page by URL, back or forward in history, or reload.', - required: false, - enum: ['url', 'back', 'forward', 'reload'], - }, - url: { - name: 'url', - type: 'string', - description: 'Target URL (only type=url)', - required: false, - }, - ignoreCache: { - name: 'ignoreCache', - type: 'boolean', - description: 'Whether to ignore cache on reload.', - required: false, - }, - handleBeforeUnload: { - name: 'handleBeforeUnload', - type: 'string', - description: - 'Whether to auto accept or beforeunload dialogs triggered by this navigation. Default is accept.', - required: false, - enum: ['accept', 'decline'], - }, - initScript: { - name: 'initScript', - type: 'string', - description: - 'A JavaScript script to be executed on each new document before any other scripts for the next navigation.', - required: false, - }, - timeout: { - name: 'timeout', - type: 'integer', - description: - 'Maximum wait time in milliseconds. If set to 0, the default timeout will be used.', - required: false, - }, - }, + "list_pages": { + "description": "Get a list of pages open in the browser.", + "category": "Navigation automation", + "args": {} }, - new_page: { - description: - 'Open a new tab and load a URL. Use project URL if not specified otherwise.', - category: 'Navigation automation', - args: { - url: { - name: 'url', - type: 'string', - description: 'URL to load in a new page.', - required: true, - }, - background: { - name: 'background', - type: 'boolean', - description: - 'Whether to open the page in the background without bringing it to the front. Default is false (foreground).', - required: false, - }, - isolatedContext: { - name: 'isolatedContext', - type: 'string', - description: - 'If specified, the page is created in an isolated browser context with the given name. Pages in the same browser context share cookies and storage. Pages in different browser contexts are fully isolated.', - required: false, - }, - timeout: { - name: 'timeout', - type: 'integer', - description: - 'Maximum wait time in milliseconds. If set to 0, the default timeout will be used.', - required: false, - }, - }, + "navigate_page": { + "description": "Go to a URL, or back, forward, or reload. Use project URL if not specified otherwise.", + "category": "Navigation automation", + "args": { + "type": { + "name": "type", + "type": "string", + "description": "Navigate the page by URL, back or forward in history, or reload.", + "required": false, + "enum": [ + "url", + "back", + "forward", + "reload" + ] + }, + "url": { + "name": "url", + "type": "string", + "description": "Target URL (only type=url)", + "required": false + }, + "ignoreCache": { + "name": "ignoreCache", + "type": "boolean", + "description": "Whether to ignore cache on reload.", + "required": false + }, + "handleBeforeUnload": { + "name": "handleBeforeUnload", + "type": "string", + "description": "Whether to auto accept or beforeunload dialogs triggered by this navigation. Default is accept.", + "required": false, + "enum": [ + "accept", + "decline" + ] + }, + "initScript": { + "name": "initScript", + "type": "string", + "description": "A JavaScript script to be executed on each new document before any other scripts for the next navigation.", + "required": false + }, + "timeout": { + "name": "timeout", + "type": "integer", + "description": "Maximum wait time in milliseconds. If set to 0, the default timeout will be used.", + "required": false + } + } }, - performance_analyze_insight: { - description: - 'Provides more detailed information on a specific Performance Insight of an insight set that was highlighted in the results of a trace recording.', - category: 'Performance', - args: { - insightSetId: { - name: 'insightSetId', - type: 'string', - description: - 'The id for the specific insight set. Only use the ids given in the "Available insight sets" list.', - required: true, - }, - insightName: { - name: 'insightName', - type: 'string', - description: - 'The name of the Insight you want more information on. For example: "DocumentLatency" or "LCPBreakdown"', - required: true, - }, - }, + "new_page": { + "description": "Open a new tab and load a URL. Use project URL if not specified otherwise.", + "category": "Navigation automation", + "args": { + "url": { + "name": "url", + "type": "string", + "description": "URL to load in a new page.", + "required": true + }, + "background": { + "name": "background", + "type": "boolean", + "description": "Whether to open the page in the background without bringing it to the front. Default is false (foreground).", + "required": false + }, + "isolatedContext": { + "name": "isolatedContext", + "type": "string", + "description": "If specified, the page is created in an isolated browser context with the given name. Pages in the same browser context share cookies and storage. Pages in different browser contexts are fully isolated.", + "required": false + }, + "timeout": { + "name": "timeout", + "type": "integer", + "description": "Maximum wait time in milliseconds. If set to 0, the default timeout will be used.", + "required": false + } + } }, - performance_start_trace: { - 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.', - category: 'Performance', - args: { - reload: { - name: 'reload', - type: 'boolean', - description: - '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.', - required: false, - default: true, - }, - autoStop: { - name: 'autoStop', - type: 'boolean', - description: - 'Determines if the trace recording should be automatically stopped.', - required: false, - default: true, - }, - filePath: { - name: 'filePath', - type: 'string', - description: - '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).', - required: false, - }, - }, + "performance_analyze_insight": { + "description": "Provides more detailed information on a specific Performance Insight of an insight set that was highlighted in the results of a trace recording.", + "category": "Performance", + "args": { + "insightSetId": { + "name": "insightSetId", + "type": "string", + "description": "The id for the specific insight set. Only use the ids given in the \"Available insight sets\" list.", + "required": true + }, + "insightName": { + "name": "insightName", + "type": "string", + "description": "The name of the Insight you want more information on. For example: \"DocumentLatency\" or \"LCPBreakdown\"", + "required": true + } + } }, - performance_stop_trace: { - description: - 'Stop the active performance trace recording on the selected webpage.', - category: 'Performance', - args: { - filePath: { - name: 'filePath', - type: 'string', - description: - '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).', - required: false, - }, - }, + "performance_start_trace": { + "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.", + "category": "Performance", + "args": { + "reload": { + "name": "reload", + "type": "boolean", + "description": "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.", + "required": false, + "default": true + }, + "autoStop": { + "name": "autoStop", + "type": "boolean", + "description": "Determines if the trace recording should be automatically stopped.", + "required": false, + "default": true + }, + "filePath": { + "name": "filePath", + "type": "string", + "description": "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).", + "required": false + } + } }, - press_key: { - description: - 'Press a key or key combination. Use this when other input methods like fill() cannot be used (e.g., keyboard shortcuts, navigation keys, or special key combinations).', - category: 'Input automation', - args: { - key: { - name: 'key', - type: 'string', - description: - 'A key or a combination (e.g., "Enter", "Control+A", "Control++", "Control+Shift+R"). Modifiers: Control, Shift, Alt, Meta', - required: true, - }, - includeSnapshot: { - name: 'includeSnapshot', - type: 'boolean', - description: - 'Whether to include a snapshot in the response. Default is false.', - required: false, - }, - }, + "performance_stop_trace": { + "description": "Stop the active performance trace recording on the selected webpage.", + "category": "Performance", + "args": { + "filePath": { + "name": "filePath", + "type": "string", + "description": "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).", + "required": false + } + } }, - resize_page: { - description: - "Resizes the selected page's window so that the page has specified dimension", - category: 'Emulation', - args: { - width: { - name: 'width', - type: 'number', - description: 'Page width', - required: true, - }, - height: { - name: 'height', - type: 'number', - description: 'Page height', - required: true, - }, - }, + "press_key": { + "description": "Press a key or key combination. Use this when other input methods like fill() cannot be used (e.g., keyboard shortcuts, navigation keys, or special key combinations).", + "category": "Input automation", + "args": { + "key": { + "name": "key", + "type": "string", + "description": "A key or a combination (e.g., \"Enter\", \"Control+A\", \"Control++\", \"Control+Shift+R\"). Modifiers: Control, Shift, Alt, Meta", + "required": true + }, + "includeSnapshot": { + "name": "includeSnapshot", + "type": "boolean", + "description": "Whether to include a snapshot in the response. Default is false.", + "required": false + } + } }, - select_page: { - description: 'Select a page as a context for future tool calls.', - category: 'Navigation automation', - args: { - pageId: { - name: 'pageId', - type: 'number', - description: - 'The ID of the page to select. Call list_pages to get available pages.', - required: true, - }, - bringToFront: { - name: 'bringToFront', - type: 'boolean', - description: 'Whether to focus the page and bring it to the top.', - required: false, - }, - }, + "resize_page": { + "description": "Resizes the selected page's window so that the page has specified dimension", + "category": "Emulation", + "args": { + "width": { + "name": "width", + "type": "number", + "description": "Page width", + "required": true + }, + "height": { + "name": "height", + "type": "number", + "description": "Page height", + "required": true + } + } }, - take_memory_snapshot: { - description: - 'Capture a memory heapsnapshot of the currently selected page to memory leak debugging', - category: 'Performance', - args: { - filePath: { - name: 'filePath', - type: 'string', - description: - 'A path to a .heapsnapshot file to save the heapsnapshot to.', - required: true, - }, - }, + "select_page": { + "description": "Select a page as a context for future tool calls.", + "category": "Navigation automation", + "args": { + "pageId": { + "name": "pageId", + "type": "number", + "description": "The ID of the page to select. Call list_pages to get available pages.", + "required": true + }, + "bringToFront": { + "name": "bringToFront", + "type": "boolean", + "description": "Whether to focus the page and bring it to the top.", + "required": false + } + } }, - take_screenshot: { - description: 'Take a screenshot of the page or element.', - category: 'Debugging', - args: { - format: { - name: 'format', - type: 'string', - description: - 'Type of format to save the screenshot as. Default is "png"', - required: false, - default: 'png', - enum: ['png', 'jpeg', 'webp'], - }, - quality: { - name: 'quality', - type: 'number', - description: - 'Compression quality for JPEG and WebP formats (0-100). Higher values mean better quality but larger file sizes. Ignored for PNG format.', - required: false, - }, - uid: { - name: 'uid', - type: 'string', - description: - 'The uid of an element on the page from the page content snapshot. If omitted takes a pages screenshot.', - required: false, - }, - fullPage: { - name: 'fullPage', - type: 'boolean', - description: - 'If set to true takes a screenshot of the full page instead of the currently visible viewport. Incompatible with uid.', - required: false, - }, - filePath: { - name: 'filePath', - type: 'string', - description: - 'The absolute path, or a path relative to the current working directory, to save the screenshot to instead of attaching it to the response.', - required: false, - }, - }, + "take_memory_snapshot": { + "description": "Capture a memory heapsnapshot of the currently selected page to memory leak debugging", + "category": "Performance", + "args": { + "filePath": { + "name": "filePath", + "type": "string", + "description": "A path to a .heapsnapshot file to save the heapsnapshot to.", + "required": true + } + } }, - take_snapshot: { - description: - 'Take a text snapshot of the currently selected page based on the a11y tree. The snapshot lists page elements along with a unique\nidentifier (uid). Always use the latest snapshot. Prefer taking a snapshot over taking a screenshot. The snapshot indicates the element selected\nin the DevTools Elements panel (if any).', - category: 'Debugging', - args: { - verbose: { - name: 'verbose', - type: 'boolean', - description: - 'Whether to include all possible information available in the full a11y tree. Default is false.', - required: false, - }, - filePath: { - name: 'filePath', - type: 'string', - description: - 'The absolute path, or a path relative to the current working directory, to save the snapshot to instead of attaching it to the response.', - required: false, - }, - }, + "take_screenshot": { + "description": "Take a screenshot of the page or element.", + "category": "Debugging", + "args": { + "format": { + "name": "format", + "type": "string", + "description": "Type of format to save the screenshot as. Default is \"png\"", + "required": false, + "default": "png", + "enum": [ + "png", + "jpeg", + "webp" + ] + }, + "quality": { + "name": "quality", + "type": "number", + "description": "Compression quality for JPEG and WebP formats (0-100). Higher values mean better quality but larger file sizes. Ignored for PNG format.", + "required": false + }, + "uid": { + "name": "uid", + "type": "string", + "description": "The uid of an element on the page from the page content snapshot. If omitted takes a pages screenshot.", + "required": false + }, + "fullPage": { + "name": "fullPage", + "type": "boolean", + "description": "If set to true takes a screenshot of the full page instead of the currently visible viewport. Incompatible with uid.", + "required": false + }, + "filePath": { + "name": "filePath", + "type": "string", + "description": "The absolute path, or a path relative to the current working directory, to save the screenshot to instead of attaching it to the response.", + "required": false + } + } }, - type_text: { - description: 'Type text using keyboard into a previously focused input', - category: 'Input automation', - args: { - text: { - name: 'text', - type: 'string', - description: 'The text to type', - required: true, - }, - submitKey: { - name: 'submitKey', - type: 'string', - description: - 'Optional key to press after typing. E.g., "Enter", "Tab", "Escape"', - required: false, - }, - }, + "take_snapshot": { + "description": "Take a text snapshot of the currently selected page based on the a11y tree. The snapshot lists page elements along with a unique\nidentifier (uid). Always use the latest snapshot. Prefer taking a snapshot over taking a screenshot. The snapshot indicates the element selected\nin the DevTools Elements panel (if any).", + "category": "Debugging", + "args": { + "verbose": { + "name": "verbose", + "type": "boolean", + "description": "Whether to include all possible information available in the full a11y tree. Default is false.", + "required": false + }, + "filePath": { + "name": "filePath", + "type": "string", + "description": "The absolute path, or a path relative to the current working directory, to save the snapshot to instead of attaching it to the response.", + "required": false + } + } }, - upload_file: { - description: 'Upload a file through a provided element.', - category: 'Input automation', - args: { - uid: { - name: 'uid', - type: 'string', - description: - 'The uid of the file input element or an element that will open file chooser on the page from the page content snapshot', - required: true, - }, - filePath: { - name: 'filePath', - type: 'string', - description: 'The local path of the file to upload', - required: true, - }, - includeSnapshot: { - name: 'includeSnapshot', - type: 'boolean', - description: - 'Whether to include a snapshot in the response. Default is false.', - required: false, - }, - }, + "type_text": { + "description": "Type text using keyboard into a previously focused input", + "category": "Input automation", + "args": { + "text": { + "name": "text", + "type": "string", + "description": "The text to type", + "required": true + }, + "submitKey": { + "name": "submitKey", + "type": "string", + "description": "Optional key to press after typing. E.g., \"Enter\", \"Tab\", \"Escape\"", + "required": false + } + } }, + "upload_file": { + "description": "Upload a file through a provided element.", + "category": "Input automation", + "args": { + "uid": { + "name": "uid", + "type": "string", + "description": "The uid of the file input element or an element that will open file chooser on the page from the page content snapshot", + "required": true + }, + "filePath": { + "name": "filePath", + "type": "string", + "description": "The local path of the file to upload", + "required": true + }, + "includeSnapshot": { + "name": "includeSnapshot", + "type": "boolean", + "description": "Whether to include a snapshot in the response. Default is false.", + "required": false + } + } + } } as const; diff --git a/src/tools/script.ts b/src/tools/script.ts index e3ff14d7d..8f11ffa3f 100644 --- a/src/tools/script.ts +++ b/src/tools/script.ts @@ -4,6 +4,9 @@ * SPDX-License-Identifier: Apache-2.0 */ +import fs from 'node:fs/promises'; +import path from 'node:path'; + import {zod} from '../third_party/index.js'; import type {Frame, JSHandle, Page, WebWorker} from '../third_party/index.js'; import type {ExtensionServiceWorker} from '../types.js'; @@ -105,6 +108,79 @@ Example with arguments: \`(el) => { }; }); +export const evaluateScriptFile = defineTool(cliArgs => { + return { + name: 'evaluate_script_file', + description: `Read a JavaScript file from the local filesystem and evaluate it inside the currently selected page. +The file should contain a JavaScript function declaration (e.g., an arrow function or function expression). +Returns the response as JSON, so returned values have to be JSON-serializable. +This is useful for evaluating large scripts without needing to pass the entire script content as a parameter.`, + annotations: { + category: ToolCategory.DEBUGGING, + readOnlyHint: false, + }, + schema: { + filePath: zod.string().describe( + `The absolute path to a JavaScript file containing a function declaration to be executed in the currently selected page. +The file content should be a JavaScript function declaration, for example: +\`() => { return document.title; }\` or \`async () => { return await fetch("example.com"); }\` +`, + ), + args: zod + .array( + zod + .string() + .describe( + 'The uid of an element on the page from the page content snapshot', + ), + ) + .optional() + .describe(`An optional list of arguments to pass to the function.`), + ...(cliArgs?.experimentalPageIdRouting ? pageIdSchema : {}), + }, + handler: async (request, response, context) => { + const {args: uidArgs, filePath, pageId} = request.params; + + const resolvedPath = path.isAbsolute(filePath) + ? filePath + : path.resolve(filePath); + + let fnString: string; + try { + fnString = await fs.readFile(resolvedPath, 'utf-8'); + } catch (err) { + throw new Error( + `Could not read script file: ${resolvedPath}`, + {cause: err}, + ); + } + + fnString = fnString.trim(); + + const mcpPage = cliArgs?.experimentalPageIdRouting + ? context.getPageById(pageId) + : context.getSelectedMcpPage(); + const page = mcpPage.pptrPage; + + const args: Array> = []; + try { + const frames = new Set(); + for (const uid of uidArgs ?? []) { + const handle = await mcpPage.getElementByUid(uid); + frames.add(handle.frame); + args.push(handle); + } + + const evaluatable = await getPageOrFrame(page, frames); + + await performEvaluation(evaluatable, fnString, args, response, context); + } finally { + void Promise.allSettled(args.map(arg => arg.dispose())); + } + }, + }; +}); + const performEvaluation = async ( evaluatable: Evaluatable, fnString: string, diff --git a/tests/tools/fixtures/test-script-async.js b/tests/tools/fixtures/test-script-async.js new file mode 100644 index 000000000..4922e070a --- /dev/null +++ b/tests/tools/fixtures/test-script-async.js @@ -0,0 +1,4 @@ +async () => { + await new Promise(res => setTimeout(res, 0)); + return 'async-works'; +} diff --git a/tests/tools/fixtures/test-script-with-args.js b/tests/tools/fixtures/test-script-with-args.js new file mode 100644 index 000000000..6eaecb66a --- /dev/null +++ b/tests/tools/fixtures/test-script-with-args.js @@ -0,0 +1,3 @@ +(el) => { + return el.id; +} diff --git a/tests/tools/fixtures/test-script.js b/tests/tools/fixtures/test-script.js new file mode 100644 index 000000000..fed12f672 --- /dev/null +++ b/tests/tools/fixtures/test-script.js @@ -0,0 +1,3 @@ +() => { + return document.title; +} diff --git a/tests/tools/script.test.ts b/tests/tools/script.test.ts index 772ebc076..079099671 100644 --- a/tests/tools/script.test.ts +++ b/tests/tools/script.test.ts @@ -10,10 +10,15 @@ import {describe, it} from 'node:test'; import type {ParsedArguments} from '../../src/bin/chrome-devtools-mcp-cli-options.js'; import {installExtension} from '../../src/tools/extensions.js'; -import {evaluateScript} from '../../src/tools/script.js'; +import {evaluateScript, evaluateScriptFile} from '../../src/tools/script.js'; import {serverHooks} from '../server.js'; import {extractExtensionId, html, withMcpContext} from '../utils.js'; +const FIXTURE_DIR = path.join( + import.meta.dirname, + '../../../tests/tools/fixtures', +); + const EXTENSION_PATH = path.join( import.meta.dirname, '../../../tests/tools/fixtures/extension-sw', @@ -301,4 +306,85 @@ describe('script', () => { ); }); }); + + describe('evaluate_script_file', () => { + it('evaluates a script file', async () => { + await withMcpContext(async (response, context) => { + const page = await context.newPage(); + await page.pptrPage.setContent(` + + Test Page + + `); + + await evaluateScriptFile().handler( + { + params: { + filePath: path.join(FIXTURE_DIR, 'test-script.js'), + }, + }, + response, + context, + ); + const lineEvaluation = response.responseLines.at(2)!; + assert.strictEqual(JSON.parse(lineEvaluation), 'Test Page'); + }); + }); + + it('evaluates an async script file', async () => { + await withMcpContext(async (response, context) => { + await evaluateScriptFile().handler( + { + params: { + filePath: path.join(FIXTURE_DIR, 'test-script-async.js'), + }, + }, + response, + context, + ); + const lineEvaluation = response.responseLines.at(2)!; + assert.strictEqual(JSON.parse(lineEvaluation), 'async-works'); + }); + }); + + it('evaluates a script file with element arguments', async () => { + await withMcpContext(async (response, context) => { + const page = context.getSelectedPptrPage(); + await page.setContent(html``); + await context.createTextSnapshot(context.getSelectedMcpPage()); + + await evaluateScriptFile().handler( + { + params: { + filePath: path.join(FIXTURE_DIR, 'test-script-with-args.js'), + args: ['1_1'], + }, + }, + response, + context, + ); + const lineEvaluation = response.responseLines.at(2)!; + assert.strictEqual(JSON.parse(lineEvaluation), 'test'); + }); + }); + + it('throws error for non-existent file', async () => { + await withMcpContext(async (response, context) => { + await assert.rejects( + evaluateScriptFile().handler( + { + params: { + filePath: '/non/existent/file.js', + }, + }, + response, + context, + ), + { + message: 'Could not read script file: /non/existent/file.js', + }, + ); + }); + }); + }); });