|
6 | 6 |
|
7 | 7 | import type {McpContext, TextSnapshotNode} from '../McpContext.js'; |
8 | 8 | import {zod} from '../third_party/index.js'; |
9 | | -import type {ElementHandle} from '../third_party/index.js'; |
| 9 | +import type {ElementHandle, KeyInput} from '../third_party/index.js'; |
| 10 | +import {parseKey} from '../utils/keyboard.js'; |
10 | 11 |
|
11 | 12 | import {ToolCategory} from './categories.js'; |
12 | 13 | import {defineTool} from './ToolDefinition.js'; |
@@ -270,3 +271,39 @@ export const uploadFile = defineTool({ |
270 | 271 | } |
271 | 272 | }, |
272 | 273 | }); |
| 274 | + |
| 275 | +export const pressKey = defineTool({ |
| 276 | + name: 'press_key', |
| 277 | + 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).`, |
| 278 | + annotations: { |
| 279 | + category: ToolCategory.INPUT, |
| 280 | + readOnlyHint: false, |
| 281 | + }, |
| 282 | + schema: { |
| 283 | + key: zod |
| 284 | + .string() |
| 285 | + .describe( |
| 286 | + 'A key or a combination (e.g., "Enter", "Control+A", "Control++", "Control+Shift+R"). Modifiers: Control, Shift, Alt, Meta', |
| 287 | + ), |
| 288 | + }, |
| 289 | + handler: async (request, response, context) => { |
| 290 | + const page = context.getSelectedPage(); |
| 291 | + const tokens = parseKey(request.params.key) as KeyInput[]; |
| 292 | + const [key, ...modifiers] = tokens; |
| 293 | + |
| 294 | + await context.waitForEventsAfterAction(async () => { |
| 295 | + for (let i = modifiers.length - 1; i >= 0; i--) { |
| 296 | + await page.keyboard.down(modifiers[i]); |
| 297 | + } |
| 298 | + await page.keyboard.press(key); |
| 299 | + for (const modifier of modifiers) { |
| 300 | + await page.keyboard.up(modifier); |
| 301 | + } |
| 302 | + }); |
| 303 | + |
| 304 | + response.appendResponseLine( |
| 305 | + `Successfully pressed key: ${request.params.key}`, |
| 306 | + ); |
| 307 | + response.setIncludeSnapshot(true); |
| 308 | + }, |
| 309 | +}); |
0 commit comments