From 46ba05d90b912b8bc4533e7a7323daa5a6fdb9bd Mon Sep 17 00:00:00 2001 From: aberemia24 Date: Tue, 30 Sep 2025 11:25:13 +0300 Subject: [PATCH 1/3] feat(screenshot): add WebP format support with quality parameter Add WebP format to screenshot tool, providing superior compression compared to JPEG. Also fixes bug where saveTemporaryFile always saved files with .png extension regardless of format. --- docs/tool-reference.md | 4 ++-- src/McpContext.ts | 15 +++++++++------ src/tools/ToolDefinition.ts | 2 +- src/tools/screenshot.ts | 4 ++-- 4 files changed, 14 insertions(+), 11 deletions(-) diff --git a/docs/tool-reference.md b/docs/tool-reference.md index 1b39e869..1f51dffb 100644 --- a/docs/tool-reference.md +++ b/docs/tool-reference.md @@ -306,9 +306,9 @@ so returned values have to JSON-serializable. **Parameters:** -- **format** (enum: "png", "jpeg") _(optional)_: Type of format to save the screenshot as. Default is "png" +- **format** (enum: "png", "jpeg", "webp") _(optional)_: Type of format to save the screenshot as. Default is "png" - **fullPage** (boolean) _(optional)_: If set to true takes a screenshot of the full page instead of the currently visible viewport. Incompatible with uid. -- **quality** (number) _(optional)_: Compression quality for JPEG format (0-100). Higher values mean better quality but larger file sizes. Ignored for PNG format. +- **quality** (number) _(optional)_: Compression quality for JPEG and WebP formats (0-100). Higher values mean better quality but larger file sizes. Ignored for PNG format. - **uid** (string) _(optional)_: The uid of an element on the page from the page content snapshot. If omitted takes a pages screenshot. --- diff --git a/src/McpContext.ts b/src/McpContext.ts index 71308676..50c636c3 100644 --- a/src/McpContext.ts +++ b/src/McpContext.ts @@ -338,17 +338,20 @@ export class McpContext implements Context { async saveTemporaryFile( data: Uint8Array, - mimeType: 'image/png' | 'image/jpeg', + mimeType: 'image/png' | 'image/jpeg' | 'image/webp', ): Promise<{filename: string}> { try { const dir = await fs.mkdtemp( path.join(os.tmpdir(), 'chrome-devtools-mcp-'), ); - const filename = path.join( - dir, - mimeType == 'image/png' ? `screenshot.png` : 'screenshot.jpg', - ); - await fs.writeFile(path.join(dir, `screenshot.png`), data); + const ext = + mimeType === 'image/png' + ? 'png' + : mimeType === 'image/jpeg' + ? 'jpg' + : 'webp'; + const filename = path.join(dir, `screenshot.${ext}`); + await fs.writeFile(filename, data); return {filename}; } catch (err) { this.logger(err); diff --git a/src/tools/ToolDefinition.ts b/src/tools/ToolDefinition.ts index a0741f4c..c617e8db 100644 --- a/src/tools/ToolDefinition.ts +++ b/src/tools/ToolDefinition.ts @@ -72,7 +72,7 @@ export type Context = Readonly<{ setCpuThrottlingRate(rate: number): void; saveTemporaryFile( data: Uint8Array, - mimeType: 'image/png' | 'image/jpeg', + mimeType: 'image/png' | 'image/jpeg' | 'image/webp', ): Promise<{filename: string}>; waitForEventsAfterAction(action: () => Promise): Promise; }>; diff --git a/src/tools/screenshot.ts b/src/tools/screenshot.ts index ae1f98bf..b413d36a 100644 --- a/src/tools/screenshot.ts +++ b/src/tools/screenshot.ts @@ -19,7 +19,7 @@ export const screenshot = defineTool({ }, schema: { format: z - .enum(['png', 'jpeg']) + .enum(['png', 'jpeg', 'webp']) .default('png') .describe('Type of format to save the screenshot as. Default is "png"'), quality: z @@ -28,7 +28,7 @@ export const screenshot = defineTool({ .max(100) .optional() .describe( - 'Compression quality for JPEG format (0-100). Higher values mean better quality but larger file sizes. Ignored for PNG format.', + 'Compression quality for JPEG and WebP formats (0-100). Higher values mean better quality but larger file sizes. Ignored for PNG format.', ), uid: z .string() From 1be0fb1c673a6c1faf297a3a60aafbbafcb9ada0 Mon Sep 17 00:00:00 2001 From: aberemia24 Date: Wed, 1 Oct 2025 19:04:28 +0300 Subject: [PATCH 2/3] feat: add press_key tool for keyboard input Add press_key tool that supports single keys and key combinations with modifiers. Features: - Single key press (e.g., "Enter", "Escape", "Tab") - Key combinations with modifiers (e.g., "Control+A", "Control+Shift+T") - Edge case handling (e.g., "Control++" for plus key with modifier) Implementation: - Added splitKeyCombo() helper function to parse key combinations - Handles modifier keys: Control, Shift, Alt, Meta - Presses modifiers in order, releases in reverse order - Includes comprehensive tests for all scenarios - Updated documentation with 27 tools (was 26) --- README.md | 3 +- docs/tool-reference.md | 13 +++- src/tools/input.ts | 66 +++++++++++++++++ tests/tools/input.test.ts | 147 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 227 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 469ef252..098d7c95 100644 --- a/README.md +++ b/README.md @@ -204,13 +204,14 @@ If you run into any issues, checkout our [troubleshooting guide](./docs/troubles -- **Input automation** (7 tools) +- **Input automation** (8 tools) - [`click`](docs/tool-reference.md#click) - [`drag`](docs/tool-reference.md#drag) - [`fill`](docs/tool-reference.md#fill) - [`fill_form`](docs/tool-reference.md#fill_form) - [`handle_dialog`](docs/tool-reference.md#handle_dialog) - [`hover`](docs/tool-reference.md#hover) + - [`press_key`](docs/tool-reference.md#press_key) - [`upload_file`](docs/tool-reference.md#upload_file) - **Navigation automation** (7 tools) - [`close_page`](docs/tool-reference.md#close_page) diff --git a/docs/tool-reference.md b/docs/tool-reference.md index c4c4bc9e..27a31b0c 100644 --- a/docs/tool-reference.md +++ b/docs/tool-reference.md @@ -2,13 +2,14 @@ # Chrome DevTools MCP Tool Reference -- **[Input automation](#input-automation)** (7 tools) +- **[Input automation](#input-automation)** (8 tools) - [`click`](#click) - [`drag`](#drag) - [`fill`](#fill) - [`fill_form`](#fill_form) - [`handle_dialog`](#handle_dialog) - [`hover`](#hover) + - [`press_key`](#press_key) - [`upload_file`](#upload_file) - **[Navigation automation](#navigation-automation)** (7 tools) - [`close_page`](#close_page) @@ -101,6 +102,16 @@ --- +### `press_key` + +**Description:** Press a key or key combination on the keyboard. Supports modifier keys and combinations. + +**Parameters:** + +- **key** (string) **(required)**: Key to press. Can be a single key (e.g., "Enter", "Escape", "a") or a combination with modifiers (e.g., "Control+A", "Control+Shift+T", "Control++"). Modifier keys: Control, Shift, Alt, Meta. + +--- + ### `upload_file` **Description:** Upload a file through a provided element. diff --git a/src/tools/input.ts b/src/tools/input.ts index eda04e80..0893200f 100644 --- a/src/tools/input.ts +++ b/src/tools/input.ts @@ -216,3 +216,69 @@ export const uploadFile = defineTool({ } }, }); + +/** + * Split a key combination string into individual keys. + * Handles combinations like "Control+A" and special cases like "Control++". + * Based on Playwright's implementation. + */ +function splitKeyCombo(keyString: string): string[] { + const keys: string[] = []; + let building = ''; + for (const char of keyString) { + if (char === '+' && building) { + // Only split if there's text before + + keys.push(building); + building = ''; + } else { + building += char; + } + } + keys.push(building); + return keys; +} + +export const pressKey = defineTool({ + name: 'press_key', + description: `Press a key or key combination on the keyboard. Supports modifier keys and combinations.`, + annotations: { + category: ToolCategories.INPUT_AUTOMATION, + readOnlyHint: false, + }, + schema: { + key: z + .string() + .describe( + 'Key to press. Can be a single key (e.g., "Enter", "Escape", "a") or a combination with modifiers (e.g., "Control+A", "Control+Shift+T", "Control++"). Modifier keys: Control, Shift, Alt, Meta.', + ), + }, + handler: async (request, response, context) => { + const page = context.getSelectedPage(); + const tokens = splitKeyCombo(request.params.key); + const key = tokens[tokens.length - 1]; + const modifiers = tokens.slice(0, -1); + + await context.waitForEventsAfterAction(async () => { + // Press down modifiers + for (const modifier of modifiers) { + // @ts-expect-error - Puppeteer KeyInput type is too restrictive for dynamic input + await page.keyboard.down(modifier); + } + + // Press the key + // @ts-expect-error - Puppeteer KeyInput type is too restrictive for dynamic input + await page.keyboard.press(key); + + // Release modifiers in reverse order + for (let i = modifiers.length - 1; i >= 0; i--) { + // @ts-expect-error - Puppeteer KeyInput type is too restrictive for dynamic input + await page.keyboard.up(modifiers[i]); + } + }); + + response.appendResponseLine( + `Successfully pressed key: ${request.params.key}`, + ); + response.setIncludeSnapshot(true); + }, +}); diff --git a/tests/tools/input.test.ts b/tests/tools/input.test.ts index 8329192f..5af2ce6f 100644 --- a/tests/tools/input.test.ts +++ b/tests/tools/input.test.ts @@ -15,6 +15,7 @@ import { drag, fillForm, uploadFile, + pressKey, } from '../../src/tools/input.js'; import {serverHooks} from '../server.js'; import {html, withBrowser} from '../utils.js'; @@ -402,4 +403,150 @@ describe('input', () => { }); }); }); + + describe('pressKey', () => { + it('presses a simple key', async () => { + await withBrowser(async (response, context) => { + const page = context.getSelectedPage(); + await page.setContent(` + +
+`); + await context.createTextSnapshot(); + await page.focus('#test-input'); + await pressKey.handler( + { + params: { + key: 'Enter', + }, + }, + response, + context, + ); + assert.strictEqual( + response.responseLines[0], + 'Successfully pressed key: Enter', + ); + assert.ok(response.includeSnapshot); + const result = await page.$eval( + '#result', + el => (el as HTMLElement).innerText, + ); + assert.strictEqual(result, 'Enter'); + }); + }); + + it('presses a key combination', async () => { + await withBrowser(async (response, context) => { + const page = context.getSelectedPage(); + await page.setContent(` + +`); + await context.createTextSnapshot(); + await pressKey.handler( + { + params: { + key: 'Control+A', + }, + }, + response, + context, + ); + assert.strictEqual( + response.responseLines[0], + 'Successfully pressed key: Control+A', + ); + assert.ok(response.includeSnapshot); + // Verify text is selected by getting selection + const selected = await page.evaluate(() => { + const input = document.getElementById( + 'test-input', + ) as HTMLTextAreaElement; + return ( + input.selectionStart === 0 && + input.selectionEnd === input.value.length + ); + }); + assert.ok(selected, 'Text should be selected'); + }); + }); + + it('presses plus key with modifier (Control++)', async () => { + await withBrowser(async (response, context) => { + const page = context.getSelectedPage(); + await page.setContent(` +
+`); + await context.createTextSnapshot(); + await pressKey.handler( + { + params: { + key: 'Control++', + }, + }, + response, + context, + ); + assert.strictEqual( + response.responseLines[0], + 'Successfully pressed key: Control++', + ); + assert.ok(response.includeSnapshot); + const result = await page.$eval( + '#result', + el => (el as HTMLElement).innerText, + ); + assert.strictEqual(result, 'ctrl-plus'); + }); + }); + + it('presses multiple modifiers', async () => { + await withBrowser(async (response, context) => { + const page = context.getSelectedPage(); + await page.setContent(` +
+`); + await context.createTextSnapshot(); + await pressKey.handler( + { + params: { + key: 'Control+Shift+T', + }, + }, + response, + context, + ); + assert.strictEqual( + response.responseLines[0], + 'Successfully pressed key: Control+Shift+T', + ); + assert.ok(response.includeSnapshot); + const result = await page.$eval( + '#result', + el => (el as HTMLElement).innerText, + ); + assert.strictEqual(result, 'ctrl-shift-t'); + }); + }); + }); }); From 2fda49999abe8114fcb261c7baa23de5e9d71946 Mon Sep 17 00:00:00 2001 From: aberemia24 Date: Sat, 11 Oct 2025 02:31:08 +0300 Subject: [PATCH 3/3] refactor: move keyboard utilities to third_party with proper attribution - Move splitKeyCombo to src/third_party/playwright/keyboard.ts - Add Playwright LICENSE and README with source attribution - Replace @ts-expect-error with proper KeyInput type casts - Update press_key description to clarify when to use vs fill() - Standardize input tool schema descriptions using uidSchema --- src/third_party/playwright/LICENSE | 202 +++++++++++++++++++++++++ src/third_party/playwright/README.md | 24 +++ src/third_party/playwright/keyboard.ts | 45 ++++++ src/tools/input.ts | 86 +++-------- 4 files changed, 291 insertions(+), 66 deletions(-) create mode 100644 src/third_party/playwright/LICENSE create mode 100644 src/third_party/playwright/README.md create mode 100644 src/third_party/playwright/keyboard.ts diff --git a/src/third_party/playwright/LICENSE b/src/third_party/playwright/LICENSE new file mode 100644 index 00000000..df112373 --- /dev/null +++ b/src/third_party/playwright/LICENSE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Portions Copyright (c) Microsoft Corporation. + Portions Copyright 2017 Google Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/src/third_party/playwright/README.md b/src/third_party/playwright/README.md new file mode 100644 index 00000000..90a35a38 --- /dev/null +++ b/src/third_party/playwright/README.md @@ -0,0 +1,24 @@ +# Playwright Keyboard Utilities + +**Name:** Playwright +**Short Name:** playwright +**URL:** https://github.com/microsoft/playwright +**Version:** Based on Playwright's keyboard utilities +**License:** Apache-2.0 +**License File:** LICENSE +**Security Critical:** no + +## Description + +This directory contains keyboard input utilities adapted from Microsoft's Playwright project. The code handles splitting keyboard combination strings (e.g., "Control+A", "Control++") for use with Puppeteer's keyboard API. + +## Source + +The `splitKeyCombo` function is based on Playwright's key combination parsing logic. + +**Original Source:** https://github.com/microsoft/playwright + +## Attribution + +Copyright (c) Microsoft Corporation +Licensed under the Apache License, Version 2.0 diff --git a/src/third_party/playwright/keyboard.ts b/src/third_party/playwright/keyboard.ts new file mode 100644 index 00000000..3ee10c4b --- /dev/null +++ b/src/third_party/playwright/keyboard.ts @@ -0,0 +1,45 @@ +/** + * Copyright (c) Microsoft Corporation. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Adapted from Playwright for use with Puppeteer's keyboard API. + * Source: https://github.com/microsoft/playwright + */ + +/** + * Split a key combination string into individual keys. + * Handles combinations like "Control+A" and special cases like "Control++". + * + * @param keyString - The key combination to split (e.g., "Control+Shift+A", "Control++") + * @returns Array of individual key strings [modifiers..., key] + * + * @example + * splitKeyCombo("Control+A") // ["Control", "A"] + * splitKeyCombo("Control++") // ["Control", "+"] + * splitKeyCombo("Enter") // ["Enter"] + */ +export function splitKeyCombo(keyString: string): string[] { + const keys: string[] = []; + let building = ''; + for (const char of keyString) { + if (char === '+' && building) { + // Only split if there's text before + + keys.push(building); + building = ''; + } else { + building += char; + } + } + keys.push(building); + return keys; +} diff --git a/src/tools/input.ts b/src/tools/input.ts index 0893200f..94f1baf9 100644 --- a/src/tools/input.ts +++ b/src/tools/input.ts @@ -4,11 +4,12 @@ * SPDX-License-Identifier: Apache-2.0 */ -import type {ElementHandle} from 'puppeteer-core'; +import type {ElementHandle, KeyInput} from 'puppeteer-core'; import z from 'zod'; +import {splitKeyCombo} from '../third_party/playwright/keyboard.js'; import {ToolCategories} from './categories.js'; -import {defineTool} from './ToolDefinition.js'; +import {defineTool, uidSchema} from './ToolDefinition.js'; export const click = defineTool({ name: 'click', @@ -18,15 +19,8 @@ export const click = defineTool({ readOnlyHint: false, }, schema: { - uid: z - .string() - .describe( - 'The uid of an element on the page from the page content snapshot', - ), - dblClick: z - .boolean() - .optional() - .describe('Set to true for double clicks. Default is false.'), + uid: uidSchema, + dblClick: z.boolean().optional().describe('Double click (default: false)'), }, handler: async (request, response, context) => { const uid = request.params.uid; @@ -57,11 +51,7 @@ export const hover = defineTool({ readOnlyHint: false, }, schema: { - uid: z - .string() - .describe( - 'The uid of an element on the page from the page content snapshot', - ), + uid: uidSchema, }, handler: async (request, response, context) => { const uid = request.params.uid; @@ -80,18 +70,14 @@ export const hover = defineTool({ export const fill = defineTool({ name: 'fill', - description: `Type text into a input, text area or select an option from a element`, annotations: { category: ToolCategories.INPUT_AUTOMATION, readOnlyHint: false, }, schema: { - uid: z - .string() - .describe( - 'The uid of an element on the page from the page content snapshot', - ), - value: z.string().describe('The value to fill in'), + uid: uidSchema, + value: z.string().describe('Value to fill'), }, handler: async (request, response, context) => { const handle = await context.getElementByUid(request.params.uid); @@ -115,8 +101,8 @@ export const drag = defineTool({ readOnlyHint: false, }, schema: { - from_uid: z.string().describe('The uid of the element to drag'), - to_uid: z.string().describe('The uid of the element to drop into'), + from_uid: z.string().describe('Element uid to drag'), + to_uid: z.string().describe('Element uid to drop into'), }, handler: async (request, response, context) => { const fromHandle = await context.getElementByUid(request.params.from_uid); @@ -147,11 +133,11 @@ export const fillForm = defineTool({ elements: z .array( z.object({ - uid: z.string().describe('The uid of the element to fill out'), - value: z.string().describe('Value for the element'), + uid: z.string().describe('Element uid'), + value: z.string().describe('Value'), }), ) - .describe('Elements from snapshot to fill out.'), + .describe('Elements to fill'), }, handler: async (request, response, context) => { for (const element of request.params.elements) { @@ -177,12 +163,8 @@ export const uploadFile = defineTool({ readOnlyHint: false, }, schema: { - uid: z - .string() - .describe( - 'The uid of the file input element or an element that will open file chooser on the page from the page content snapshot', - ), - filePath: z.string().describe('The local path of the file to upload'), + uid: z.string().describe('File input element uid or element that opens file chooser'), + filePath: z.string().describe('Local file path'), }, handler: async (request, response, context) => { const {uid, filePath} = request.params; @@ -217,61 +199,33 @@ export const uploadFile = defineTool({ }, }); -/** - * Split a key combination string into individual keys. - * Handles combinations like "Control+A" and special cases like "Control++". - * Based on Playwright's implementation. - */ -function splitKeyCombo(keyString: string): string[] { - const keys: string[] = []; - let building = ''; - for (const char of keyString) { - if (char === '+' && building) { - // Only split if there's text before + - keys.push(building); - building = ''; - } else { - building += char; - } - } - keys.push(building); - return keys; -} - export const pressKey = defineTool({ name: 'press_key', - description: `Press a key or key combination on the keyboard. Supports modifier keys and combinations.`, + 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).`, annotations: { category: ToolCategories.INPUT_AUTOMATION, readOnlyHint: false, }, schema: { - key: z - .string() - .describe( - 'Key to press. Can be a single key (e.g., "Enter", "Escape", "a") or a combination with modifiers (e.g., "Control+A", "Control+Shift+T", "Control++"). Modifier keys: Control, Shift, Alt, Meta.', - ), + key: z.string().describe('Key or combination (e.g., "Enter", "Control+A", "Control++"). Modifiers: Control, Shift, Alt, Meta'), }, handler: async (request, response, context) => { const page = context.getSelectedPage(); const tokens = splitKeyCombo(request.params.key); - const key = tokens[tokens.length - 1]; - const modifiers = tokens.slice(0, -1); + const key = tokens[tokens.length - 1] as KeyInput; + const modifiers = tokens.slice(0, -1) as KeyInput[]; await context.waitForEventsAfterAction(async () => { // Press down modifiers for (const modifier of modifiers) { - // @ts-expect-error - Puppeteer KeyInput type is too restrictive for dynamic input await page.keyboard.down(modifier); } // Press the key - // @ts-expect-error - Puppeteer KeyInput type is too restrictive for dynamic input await page.keyboard.press(key); // Release modifiers in reverse order for (let i = modifiers.length - 1; i >= 0; i--) { - // @ts-expect-error - Puppeteer KeyInput type is too restrictive for dynamic input await page.keyboard.up(modifiers[i]); } });