-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathinput.ts
More file actions
678 lines (637 loc) · 20.1 KB
/
Copy pathinput.ts
File metadata and controls
678 lines (637 loc) · 20.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {logger} from '../logger.js';
import type {McpContext} from '../McpContext.js';
import {zod} from '../third_party/index.js';
import type {ElementHandle, KeyInput} from '../third_party/index.js';
import type {TextSnapshotNode} from '../types.js';
import {parseKey} from '../utils/keyboard.js';
import type {WaitForEventsResult} from '../WaitForHelper.js';
import {ToolCategory} from './categories.js';
import type {ContextPage} from './ToolDefinition.js';
import {definePageTool} from './ToolDefinition.js';
const dblClickSchema = zod
.boolean()
.optional()
.describe('Set to true for double clicks. Default is false.');
const includeSnapshotSchema = zod
.boolean()
.optional()
.describe('Whether to include a snapshot in the response. Default is false.');
const submitKeySchema = zod
.string()
.optional()
.describe(
'Optional key to press after typing. E.g., "Enter", "Tab", "Escape"',
);
const dragOffsetXSchema = zod
.number()
.optional()
.describe(
'Optional x offset in CSS pixels from the target element bounding rect top-left corner. Cannot be combined with to_fraction_x.',
);
const dragOffsetYSchema = zod
.number()
.optional()
.describe(
'Optional y offset in CSS pixels from the target element bounding rect top-left corner. Cannot be combined with to_fraction_y.',
);
const dragFractionXSchema = zod
.number()
.min(0)
.max(1)
.optional()
.describe(
'Optional x fraction within the target element bounding rect. 0 is the left edge and 1 is the right edge. Cannot be combined with to_offset_x.',
);
const dragFractionYSchema = zod
.number()
.min(0)
.max(1)
.optional()
.describe(
'Optional y fraction within the target element bounding rect. 0 is the top edge and 1 is the bottom edge. Cannot be combined with to_offset_y.',
);
const CUSTOM_DRAG_DELAY_MS = 150;
interface DragCustomDropParams {
to_offset_x?: number;
to_offset_y?: number;
to_fraction_x?: number;
to_fraction_y?: number;
}
function hasCustomDropPoint(params: DragCustomDropParams): boolean {
return (
params.to_offset_x !== undefined ||
params.to_offset_y !== undefined ||
params.to_fraction_x !== undefined ||
params.to_fraction_y !== undefined
);
}
function assertValidCustomDropPoint(params: DragCustomDropParams): void {
if (params.to_offset_x !== undefined && params.to_fraction_x !== undefined) {
throw new Error(
'Specify only one of to_offset_x or to_fraction_x for drag().',
);
}
if (params.to_offset_y !== undefined && params.to_fraction_y !== undefined) {
throw new Error(
'Specify only one of to_offset_y or to_fraction_y for drag().',
);
}
}
function resolveDropAxisCoordinate(
origin: number,
size: number,
offset?: number,
fraction?: number,
): number {
if (offset !== undefined) {
return origin + offset;
}
if (fraction !== undefined) {
return origin + size * fraction;
}
return origin + size / 2;
}
async function resolveCustomDropPoint(
handle: ElementHandle<Element>,
params: DragCustomDropParams,
): Promise<{x: number; y: number}> {
const box = await handle.boundingBox();
if (!box) {
throw new Error('Failed to compute the drag drop target bounding box.');
}
return {
x: resolveDropAxisCoordinate(
box.x,
box.width,
params.to_offset_x,
params.to_fraction_x,
),
y: resolveDropAxisCoordinate(
box.y,
box.height,
params.to_offset_y,
params.to_fraction_y,
),
};
}
function handleActionError(error: unknown, uid: string) {
logger('failed to act using a locator', error);
throw new Error(
`Failed to interact with the element with uid ${uid}. The element did not become interactive within the configured timeout.`,
{
cause: error,
},
);
}
async function selectNativeSelectOption(handle: ElementHandle<Element>) {
const selectHandle = await handle.evaluateHandle(node => {
if (!(node instanceof HTMLOptionElement)) {
return null;
}
const select = node.closest('select');
if (!select || select.multiple || select.disabled || node.disabled) {
return null;
}
const parentElement = node.parentElement;
if (
parentElement instanceof HTMLOptGroupElement &&
parentElement.disabled
) {
return null;
}
return select;
});
try {
const select = selectHandle.asElement() as ElementHandle<Element> | null;
if (!select) {
return false;
}
const valueHandle = await handle.getProperty('value');
try {
const value = await valueHandle.jsonValue();
if (typeof value !== 'string') {
return false;
}
await select.asLocator().fill(value);
} finally {
void valueHandle.dispose();
}
return true;
} finally {
void selectHandle.dispose();
}
}
export const click = definePageTool({
name: 'click',
description: `Clicks on the provided element`,
annotations: {
category: ToolCategory.INPUT,
readOnlyHint: false,
},
schema: {
uid: zod
.string()
.describe(
'The uid of an element on the page from the page content snapshot',
),
dblClick: dblClickSchema,
includeSnapshot: includeSnapshotSchema,
},
blockedByDialog: true,
verifyFilesSchema: [],
handler: async (request, response) => {
const uid = request.params.uid;
const handle = await request.page.getElementByUid(uid);
const aXNode = request.page.getAXNodeByUid(uid);
const shouldSelectNativeOption =
!request.params.dblClick && aXNode?.role === 'option';
try {
const result = await request.page.waitForEventsAfterAction(async () => {
if (
shouldSelectNativeOption &&
(await selectNativeSelectOption(handle))
) {
return;
}
await handle.asLocator().click({
count: request.params.dblClick ? 2 : 1,
});
});
response.appendResponseLine(
request.params.dblClick
? `Successfully double clicked on the element`
: `Successfully clicked on the element`,
);
response.attachWaitForResult(result);
if (request.params.includeSnapshot) {
response.includeSnapshot();
}
} catch (error) {
handleActionError(error, uid);
} finally {
void handle.dispose();
}
},
});
export const clickAt = definePageTool({
name: 'click_at',
description: `Clicks at the provided coordinates`,
annotations: {
category: ToolCategory.INPUT,
readOnlyHint: false,
conditions: ['experimentalVision'],
},
schema: {
x: zod.number().describe('The x coordinate'),
y: zod.number().describe('The y coordinate'),
dblClick: dblClickSchema,
includeSnapshot: includeSnapshotSchema,
},
blockedByDialog: true,
verifyFilesSchema: [],
handler: async (request, response) => {
const page = request.page;
const result = await page.waitForEventsAfterAction(async () => {
await page.pptrPage.mouse.click(request.params.x, request.params.y, {
count: request.params.dblClick ? 2 : 1,
});
});
response.appendResponseLine(
request.params.dblClick
? `Successfully double clicked at the coordinates`
: `Successfully clicked at the coordinates`,
);
response.attachWaitForResult(result);
if (request.params.includeSnapshot) {
response.includeSnapshot();
}
},
});
export const hover = definePageTool({
name: 'hover',
description: `Hover over the provided element`,
annotations: {
category: ToolCategory.INPUT,
readOnlyHint: false,
},
schema: {
uid: zod
.string()
.describe(
'The uid of an element on the page from the page content snapshot',
),
includeSnapshot: includeSnapshotSchema,
},
blockedByDialog: true,
verifyFilesSchema: [],
handler: async (request, response) => {
const uid = request.params.uid;
const handle = await request.page.getElementByUid(uid);
try {
const result = await request.page.waitForEventsAfterAction(async () => {
await handle.asLocator().hover();
});
response.appendResponseLine(`Successfully hovered over the element`);
response.attachWaitForResult(result);
if (request.params.includeSnapshot) {
response.includeSnapshot();
}
} catch (error) {
handleActionError(error, uid);
} finally {
void handle.dispose();
}
},
});
// The AXNode for an option doesn't contain its `value`. We set text content of the option as value.
// If the form is a combobox, we need to find the correct option by its text value.
// To do that, loop through the children while checking which child's text matches the requested value (requested value is actually the text content).
// When the correct option is found, use the element handle to get the real value.
async function selectOption(
handle: ElementHandle,
aXNode: TextSnapshotNode,
value: string,
) {
let optionFound = false;
for (const child of aXNode.children) {
if (child.role === 'option' && child.name === value && child.value) {
optionFound = true;
const childHandle = await child.elementHandle();
if (childHandle) {
try {
const childValueHandle = await childHandle.getProperty('value');
try {
const childValue = await childValueHandle.jsonValue();
if (childValue) {
await handle.asLocator().fill(childValue.toString());
}
} finally {
void childValueHandle.dispose();
}
break;
} finally {
void childHandle.dispose();
}
}
}
}
if (!optionFound) {
throw new Error(`Could not find option with text "${value}"`);
}
}
function hasOptionChildren(aXNode: TextSnapshotNode) {
return aXNode.children.some(child => child.role === 'option');
}
async function fillFormElement(
uid: string,
value: string,
context: McpContext,
page: ContextPage,
) {
const handle = await page.getElementByUid(uid);
try {
const aXNode = context.getAXNodeByUid(uid);
// We assume that combobox needs to be handled as select if it has
// role='combobox' and option children.
if (aXNode && aXNode.role === 'combobox' && hasOptionChildren(aXNode)) {
await selectOption(handle, aXNode, value);
} else {
const isToggle = await handle.evaluate(el => {
if (el instanceof HTMLInputElement) {
return el.type === 'checkbox' || el.type === 'radio';
}
const role = el.getAttribute('role');
return role === 'checkbox' || role === 'radio' || role === 'switch';
});
if (isToggle) {
if (['true', 'false'].includes(value)) {
await handle.asLocator().fill(value === 'true');
} else {
throw new Error(
`Checkboxes, radio boxes and toggles require "true" or "false" value, but ${value} was used`,
);
}
} else {
// Increase timeout for longer input values.
const timeoutPerChar = 10; // ms
const fillTimeout =
page.pptrPage.getDefaultTimeout() + value.length * timeoutPerChar;
await handle.asLocator().setTimeout(fillTimeout).fill(value);
}
}
} catch (error) {
handleActionError(error, uid);
} finally {
void handle.dispose();
}
}
export const fill = definePageTool({
name: 'fill',
description: `Type text into an input, text area or select an option from a <select> element.`,
annotations: {
category: ToolCategory.INPUT,
readOnlyHint: false,
},
schema: {
uid: zod
.string()
.describe(
'The uid of an element on the page from the page content snapshot',
),
value: zod
.string()
.describe(
'The value to fill in. "true" or "false" for checkboxes and toggles, "true" for radio buttons.',
),
includeSnapshot: includeSnapshotSchema,
},
blockedByDialog: true,
verifyFilesSchema: [],
handler: async (request, response, context) => {
const page = request.page;
const result = await page.waitForEventsAfterAction(async () => {
await fillFormElement(
request.params.uid,
request.params.value,
context as McpContext,
page,
);
});
response.appendResponseLine(`Successfully filled out the element`);
response.attachWaitForResult(result);
if (request.params.includeSnapshot) {
response.includeSnapshot();
}
},
});
export const typeText = definePageTool({
name: 'type_text',
description: `Type text using keyboard into a previously focused input`,
annotations: {
category: ToolCategory.INPUT,
readOnlyHint: false,
},
schema: {
text: zod.string().describe('The text to type'),
submitKey: submitKeySchema,
},
blockedByDialog: true,
verifyFilesSchema: [],
handler: async (request, response) => {
const page = request.page;
const result = await page.waitForEventsAfterAction(async () => {
await page.pptrPage.keyboard.type(request.params.text);
if (request.params.submitKey) {
await page.pptrPage.keyboard.press(
request.params.submitKey as KeyInput,
);
}
});
response.appendResponseLine(
`Typed text "${request.params.text}${request.params.submitKey ? ` + ${request.params.submitKey}` : ''}"`,
);
response.attachWaitForResult(result);
},
});
export const drag = definePageTool({
name: 'drag',
description: `Drag an element onto another element`,
annotations: {
category: ToolCategory.INPUT,
readOnlyHint: false,
},
schema: {
from_uid: zod.string().describe('The uid of the element to drag'),
to_uid: zod.string().describe('The uid of the element to drop into'),
to_offset_x: dragOffsetXSchema,
to_offset_y: dragOffsetYSchema,
to_fraction_x: dragFractionXSchema,
to_fraction_y: dragFractionYSchema,
includeSnapshot: includeSnapshotSchema,
},
blockedByDialog: true,
verifyFilesSchema: [],
handler: async (request, response) => {
const fromHandle = await request.page.getElementByUid(
request.params.from_uid,
);
const toHandle = await request.page.getElementByUid(request.params.to_uid);
const customDropParams: DragCustomDropParams = {
to_offset_x: request.params.to_offset_x,
to_offset_y: request.params.to_offset_y,
to_fraction_x: request.params.to_fraction_x,
to_fraction_y: request.params.to_fraction_y,
};
try {
const result = await request.page.waitForEventsAfterAction(async () => {
if (!hasCustomDropPoint(customDropParams)) {
await fromHandle.drag(toHandle);
await new Promise(resolve => setTimeout(resolve, 50));
await toHandle.drop(fromHandle);
return;
}
assertValidCustomDropPoint(customDropParams);
await fromHandle.scrollIntoView();
await toHandle.scrollIntoView();
const targetPoint = await resolveCustomDropPoint(
toHandle,
customDropParams,
);
const mouse = request.page.pptrPage.mouse;
await fromHandle.hover();
await mouse.down();
await mouse.move(targetPoint.x, targetPoint.y);
await new Promise(resolve => setTimeout(resolve, CUSTOM_DRAG_DELAY_MS));
await mouse.up();
});
response.appendResponseLine(`Successfully dragged an element`);
response.attachWaitForResult(result);
if (request.params.includeSnapshot) {
response.includeSnapshot();
}
} finally {
void fromHandle.dispose();
void toHandle.dispose();
}
},
});
export const fillForm = definePageTool({
name: 'fill_form',
description: `Fill out multiple form elements (inputs, selects, checkboxes, radios) at once. ALWAYS prefer this tool over multiple individual 'fill' or 'click' calls when interacting with forms. It is significantly faster, more reliable, and reduces turn count. Example: Fill username, password, and check "Remember Me" in one call.`,
annotations: {
category: ToolCategory.INPUT,
readOnlyHint: false,
},
schema: {
elements: zod
.array(
// eslint-disable-next-line @local/enforce-zod-schema
zod.object({
uid: zod.string().describe('The uid of the element to fill out'),
value: zod
.string()
.describe(
'Value for the element. "true" or "false" for checkboxes and toggles, "true" for radio buttons.',
),
}),
)
.describe('Elements from snapshot to fill out.'),
includeSnapshot: includeSnapshotSchema,
},
blockedByDialog: true,
verifyFilesSchema: [],
handler: async (request, response, context) => {
const page = request.page;
let lastResult: WaitForEventsResult = {};
for (const element of request.params.elements) {
lastResult = await page.waitForEventsAfterAction(async () => {
await fillFormElement(
element.uid,
element.value,
context as McpContext,
page,
);
});
}
response.appendResponseLine(`Successfully filled out the form`);
response.attachWaitForResult(lastResult);
if (request.params.includeSnapshot) {
response.includeSnapshot();
}
},
});
export const uploadFile = definePageTool({
name: 'upload_file',
description: 'Upload a file through a provided element.',
annotations: {
category: ToolCategory.INPUT,
readOnlyHint: false,
},
schema: {
uid: zod
.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: zod.string().describe('The local path of the file to upload'),
includeSnapshot: includeSnapshotSchema,
},
blockedByDialog: true,
verifyFilesSchema: ['filePath'],
handler: async (request, response, _context) => {
const {uid, filePath} = request.params;
const handle = (await request.page.getElementByUid(
uid,
)) as ElementHandle<HTMLInputElement>;
try {
try {
await handle.uploadFile(filePath);
} catch {
// Some sites use a proxy element to trigger file upload instead of
// a type=file element. In this case, we want to default to
// Page.waitForFileChooser() and upload the file this way.
try {
const [fileChooser] = await Promise.all([
request.page.pptrPage.waitForFileChooser({timeout: 3000}),
handle.asLocator().click(),
]);
await fileChooser.accept([filePath]);
} catch {
throw new Error(
`Failed to upload file. The element could not accept the file directly, and clicking it did not trigger a file chooser.`,
);
}
}
if (request.params.includeSnapshot) {
response.includeSnapshot();
}
response.appendResponseLine(`File uploaded from ${filePath}.`);
} finally {
void handle.dispose();
}
},
});
export const pressKey = definePageTool({
name: '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).`,
annotations: {
category: ToolCategory.INPUT,
readOnlyHint: false,
},
schema: {
key: zod
.string()
.describe(
'A key or a combination (e.g., "Enter", "Control+A", "Control++", "Control+Shift+R"). Modifiers: Control, Shift, Alt, Meta',
),
includeSnapshot: includeSnapshotSchema,
},
blockedByDialog: true,
verifyFilesSchema: [],
handler: async (request, response) => {
const page = request.page;
const tokens = parseKey(request.params.key);
const [key, ...modifiers] = tokens;
const result = await page.waitForEventsAfterAction(async () => {
for (const modifier of modifiers) {
await page.pptrPage.keyboard.down(modifier);
}
await page.pptrPage.keyboard.press(key);
for (const modifier of modifiers.toReversed()) {
await page.pptrPage.keyboard.up(modifier);
}
});
response.appendResponseLine(
`Successfully pressed key: ${request.params.key}`,
);
response.attachWaitForResult(result);
if (request.params.includeSnapshot) {
response.includeSnapshot();
}
},
});