-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Expand file tree
/
Copy pathMcpPage.ts
More file actions
697 lines (622 loc) · 20.7 KB
/
Copy pathMcpPage.ts
File metadata and controls
697 lines (622 loc) · 20.7 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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {
createTargetUniverse,
type TargetUniverse,
} from './devtools/DevtoolsUtils.js';
import {logger} from './logger.js';
import {
ConsoleCollector,
NetworkCollector,
type ListenerMap,
type UncaughtError,
} from './PageCollector.js';
import {TextSnapshot} from './TextSnapshot.js';
import type {Locator} from './third_party/index.js';
import {
PredefinedNetworkConditions,
type Dialog,
type ElementHandle,
type Viewport,
type WebMCPTool,
type Protocol,
type Page,
type ConsoleMessage,
type HTTPRequest,
type DevTools,
} from './third_party/index.js';
import {takeSnapshot} from './tools/snapshot.js';
import type {ToolGroups} from './tools/thirdPartyDeveloper.js';
const DEFAULT_TIMEOUT = 5_000;
const NAVIGATION_TIMEOUT = 10_000;
import type {
ContextPage,
DevToolsData,
Response,
} from './tools/ToolDefinition.js';
import type {
EmulationSettings,
GeolocationOptions,
TextSnapshotNode,
} from './types.js';
import {type WithSymbolId, stableIdSymbol} from './utils/id.js';
import {
getNetworkMultiplierFromString,
WaitForHelper,
type WaitForEventsResult,
type DialogAction,
} from './WaitForHelper.js';
/**
* Per-page state wrapper. Consolidates dialog, snapshot, emulation,
* and metadata that were previously scattered across Maps in McpContext.
*
* Internal class consumed only by McpContext. Fields are public for direct
* read/write access. The dialog field is private because it requires an
* event listener lifecycle managed by the constructor/dispose pair.
*/
export class McpPage implements ContextPage {
readonly pptrPage: Page;
readonly id: number;
// Snapshot
textSnapshot: TextSnapshot | null = null;
uniqueBackendNodeIdToMcpId = new Map<string, string>();
extraHandles: ElementHandle[] = [];
// Emulation
emulationSettings: EmulationSettings = {};
// Metadata
isolatedContextName?: string;
devToolsPage?: Page;
#devtoolsUniverse?: TargetUniverse;
// Dialog
#dialog?: Dialog;
#dialogHandler: (dialog: Dialog) => void;
thirdPartyDeveloperTools: ToolGroups = [];
networkCollector: NetworkCollector;
consoleCollector: ConsoleCollector;
#hasNetworkBlockOrAllowlist: boolean;
#locatorClass: typeof Locator;
constructor(
page: Page,
id: number,
options: {
hasNetworkBlockOrAllowlist: boolean;
locatorClass: typeof Locator;
},
) {
this.#hasNetworkBlockOrAllowlist = options.hasNetworkBlockOrAllowlist;
this.#locatorClass = options.locatorClass;
this.pptrPage = page;
this.id = id;
this.#dialogHandler = (dialog: Dialog): void => {
this.#dialog = dialog;
};
page.on('dialog', this.#dialogHandler);
this.networkCollector = new NetworkCollector(page);
this.consoleCollector = new ConsoleCollector(page, collect => {
return {
console: event => {
collect(event);
},
uncaughtError: event => {
collect(event);
},
devtoolsAggregatedIssue: event => {
collect(event);
},
} as ListenerMap;
});
}
async init(): Promise<void> {
if (this.#devtoolsUniverse) {
return;
}
try {
this.#devtoolsUniverse = await createTargetUniverse(this.pptrPage);
} catch (e) {
logger?.('Failed to initialize DevTools universe', e);
}
// We emulate a focused page for all pages to support multi-agent workflows.
void this.pptrPage.emulateFocusedPage(true).catch(error => {
logger?.('Error turning on focused page emulation', error);
});
}
get devtoolsUniverse(): TargetUniverse | undefined {
return this.#devtoolsUniverse;
}
getDialog(): Dialog | undefined {
return this.#dialog;
}
clearDialog(): void {
this.#dialog = undefined;
}
throwIfDialogOpen(): void {
if (this.#dialog) {
throw new Error(
`A dialog is open (${this.#dialog.type()}: ${this.#dialog.message()}).`,
);
}
}
getThirdPartyDeveloperTools(): ToolGroups {
return this.thirdPartyDeveloperTools;
}
getWebMcpTools(): WebMCPTool[] {
return this.pptrPage.webmcp.tools();
}
resolveCdpRequestId(cdpRequestId: string): number | undefined {
if (!cdpRequestId) {
logger?.('no network request');
return;
}
const request = this.networkCollector.find(request => {
// @ts-expect-error id is internal.
return request.id === cdpRequestId;
});
if (!request) {
logger?.('no network request for ' + cdpRequestId);
return;
}
return this.networkCollector.getIdForResource(request);
}
getNetworkRequests(includePreservedRequests?: boolean): HTTPRequest[] {
return this.networkCollector.getData(includePreservedRequests);
}
getConsoleData(
includePreservedMessages?: boolean,
): Array<ConsoleMessage | Error | DevTools.AggregatedIssue | UncaughtError> {
return this.consoleCollector.getData(includePreservedMessages);
}
getConsoleMessageById(
id: number,
): ConsoleMessage | Error | DevTools.AggregatedIssue | UncaughtError {
return this.consoleCollector.getById(id);
}
getNetworkRequestById(reqid: number): HTTPRequest {
return this.networkCollector.getById(reqid);
}
get networkConditions(): string | null {
return this.emulationSettings.networkConditions ?? null;
}
get cpuThrottlingRate(): number {
return this.emulationSettings.cpuThrottlingRate ?? 1;
}
get geolocation(): GeolocationOptions | null {
return this.emulationSettings.geolocation ?? null;
}
get viewport(): Viewport | null {
return this.emulationSettings.viewport ?? null;
}
get userAgent(): string | null {
return this.emulationSettings.userAgent ?? null;
}
get colorScheme(): 'dark' | 'light' | null {
return this.emulationSettings.colorScheme ?? null;
}
// Public for testability: tests spy on this method to verify throttle multipliers.
createWaitForHelper(
cpuMultiplier: number,
networkMultiplier: number,
): WaitForHelper {
return new WaitForHelper(this.pptrPage, cpuMultiplier, networkMultiplier);
}
waitForEventsAfterAction(
action: () => Promise<unknown>,
options?: {
timeout?: number;
waitForStableDom?: boolean;
handleDialog?:
DialogAction | Partial<Record<Protocol.Page.DialogType, DialogAction>>;
},
): Promise<WaitForEventsResult> {
const helper = this.createWaitForHelper(
this.cpuThrottlingRate,
getNetworkMultiplierFromString(this.networkConditions),
);
return helper.waitForEventsAfterAction(action, options);
}
dispose(): void {
this.pptrPage.off('dialog', this.#dialogHandler);
this.networkCollector.dispose();
this.consoleCollector.dispose();
}
async executeThirdPartyDeveloperTool(
toolName: string,
params: Record<string, unknown>,
response: Response,
): Promise<void> {
// Creates array of ElementHandles from the UIDs in the params.
// We do not replace the uids with the ElementsHandles yet, because
// the `evaluate` function only turns them into DOM elements if they
// are passed as non-nested arguments.
const handles: ElementHandle[] = [];
for (const value of Object.values(params)) {
if (
value instanceof Object &&
'uid' in value &&
typeof value.uid === 'string' &&
Object.keys(value).length === 1
) {
handles.push(await this.getElementByUid(value.uid));
}
}
const result = await this.pptrPage.evaluate(
async (name, args, ...elements) => {
// Replace the UIDs with DOM elements.
for (const [key, value] of Object.entries(args)) {
if (
value instanceof Object &&
'uid' in value &&
typeof value.uid === 'string' &&
Object.keys(value).length === 1
) {
args[key] = elements.shift();
}
}
if (!window.__dtmcp?.executeTool) {
throw new Error('No tools found on the page');
}
const toolResult = await window.__dtmcp.executeTool(name, args);
const stashDOMElement = (el: Element) => {
if (!window.__dtmcp) {
window.__dtmcp = {};
}
if (window.__dtmcp.stashedElements === undefined) {
window.__dtmcp.stashedElements = [];
}
window.__dtmcp.stashedElements.push(el);
return {
stashedId: `stashed-${window.__dtmcp.stashedElements.length - 1}`,
};
};
const ancestors: unknown[] = [];
// Recursively walks the tool result:
// - Replaces DOM elements with an ID and stashes the DOM element on the window object
// - Replaces non-plain objects with a string representation of the object
// - Replaces circular references with the string '<Circular reference>'
// - Replaces functions with the string '<Function object>'
const processToolResult = (
data: unknown,
parentEl?: unknown,
): unknown => {
// 1. Handle DOM Elements
if (data instanceof Element) {
return stashDOMElement(data);
}
// 2. Handle Arrays
if (Array.isArray(data)) {
return data.map((item: unknown) =>
processToolResult(item, parentEl),
);
}
// 3. Handle Objects
if (data !== null && typeof data === 'object') {
while (ancestors.length > 0 && ancestors.at(-1) !== parentEl) {
ancestors.pop();
}
if (ancestors.includes(data)) {
return '<Circular reference>';
}
ancestors.push(data);
// If not a plain object, return a string representation of the object
if (Object.getPrototypeOf(data) !== Object.prototype) {
return `<${data.constructor.name} instance>`;
}
const processedObj: Record<string, unknown> = {};
for (const [key, value] of Object.entries(data)) {
processedObj[key] = processToolResult(value, data);
}
return processedObj;
}
// 4. Handle Functions
if (typeof data === 'function') {
return '<Function object>';
}
// 5. Return primitives (strings, numbers, booleans) as-is
return data;
};
return {
result: processToolResult(toolResult),
stashed: window.__dtmcp?.stashedElements?.length ?? 0,
};
},
toolName,
params,
...handles,
);
const elementHandles: ElementHandle[] = [];
for (let i = 0; i < (result.stashed ?? 0); i++) {
const elementHandle = await this.pptrPage.evaluateHandle(index => {
const el = window.__dtmcp?.stashedElements?.[index];
if (!el) {
throw new Error(`Stashed element at index ${index} not found`);
}
return el;
}, i);
elementHandles.push(elementHandle);
}
if (elementHandles.length) {
const oldHandles = [...this.extraHandles];
this.textSnapshot = await TextSnapshot.create(this, {
extraHandles: elementHandles,
});
response.includeSnapshot();
for (const handle of oldHandles) {
await handle
.dispose()
.catch(e => logger?.('Failed to dispose old handle', e));
}
}
const cdpElementIds = await Promise.all(
elementHandles.map(async (elementHandle, index) => {
const backendNodeId = await elementHandle.backendNodeId();
if (!backendNodeId) {
logger?.(
`No backendNodeId for stashed DOM element with index ${index}`,
);
return `stashed-${index}`;
}
const cdpElementId =
this.textSnapshot?.resolveCdpElementId(backendNodeId);
if (!cdpElementId) {
logger?.(
`Could not get cdpElementId for backend node ${backendNodeId}`,
);
return `stashed-${index}`;
}
return cdpElementId;
}),
);
const recursivelyReplaceStashedElements = (node: unknown): unknown => {
if (Array.isArray(node)) {
return node.map(x => recursivelyReplaceStashedElements(x));
}
if (node !== null && typeof node === 'object') {
if (
'stashedId' in node &&
typeof node.stashedId === 'string' &&
node.stashedId.startsWith('stashed-') &&
Object.keys(node).length === 1
) {
const index = parseInt(node.stashedId.split('-')[1]);
return {uid: cdpElementIds[index]};
}
const resultObj: Record<string, unknown> = {};
for (const [key, value] of Object.entries(node)) {
resultObj[key] = recursivelyReplaceStashedElements(value);
}
return resultObj;
}
return node;
};
const resultWithUids = recursivelyReplaceStashedElements(result.result);
response.appendResponseLine(JSON.stringify(resultWithUids, null, 2));
}
async getElementByUid(uid: string): Promise<ElementHandle<Element>> {
if (!this.textSnapshot) {
throw new Error(
`No snapshot found for page ${this.id ?? '?'}. Use ${takeSnapshot.name} to capture one.`,
);
}
const node = this.textSnapshot.idToNode.get(uid);
if (!node) {
throw new Error(`Element uid "${uid}" not found on page ${this.id}.`);
}
return this.#resolveElementHandle(node, uid);
}
async #resolveElementHandle(
node: TextSnapshotNode,
uid: string,
): Promise<ElementHandle<Element>> {
const message = `Element with uid ${uid} no longer exists on the page.`;
try {
const handle = await node.elementHandle();
if (!handle) {
throw new Error(message);
}
return handle;
} catch (error) {
throw new Error(message, {
cause: error,
});
}
}
getAXNodeByUid(uid: string) {
return this.textSnapshot?.idToNode.get(uid);
}
async getDevToolsData(): Promise<DevToolsData> {
try {
logger?.('Getting DevTools UI data');
const devtoolsPage = this.devToolsPage;
if (!devtoolsPage) {
logger?.('No DevTools page detected');
return {};
}
const {cdpRequestId, cdpBackendNodeId} = await devtoolsPage.evaluate(
async () => {
// @ts-expect-error no types
const UI = await import('/bundled/ui/legacy/legacy.js');
// @ts-expect-error no types
const SDK = await import('/bundled/core/sdk/sdk.js');
const request = UI.Context.Context.instance().flavor(
SDK.NetworkRequest.NetworkRequest,
);
const node = UI.Context.Context.instance().flavor(
SDK.DOMModel.DOMNode,
);
return {
cdpRequestId: request?.requestId(),
cdpBackendNodeId: node?.backendNodeId(),
};
},
);
return {cdpBackendNodeId, cdpRequestId};
} catch (err) {
logger?.('error getting devtools data', err);
}
return {};
}
getConsoleMessageStableId(
message: ConsoleMessage | Error | DevTools.AggregatedIssue | UncaughtError,
): number {
return (message as WithSymbolId<typeof message>)[stableIdSymbol] ?? -1;
}
getNetworkRequestStableId(request: HTTPRequest): number {
return (request as WithSymbolId<typeof request>)[stableIdSymbol] ?? -1;
}
async restoreEmulation() {
const currentSetting = this.emulationSettings;
await this.emulate(currentSetting);
}
async emulate(options: {
networkConditions?: string;
cpuThrottlingRate?: number;
geolocation?: GeolocationOptions;
userAgent?: string;
colorScheme?: 'dark' | 'light' | 'auto';
viewport?: Viewport;
extraHttpHeaders?: Record<string, string> | undefined;
}): Promise<void> {
const page = this.pptrPage;
const newSettings: EmulationSettings = {...this.emulationSettings};
// Skip network emulation if blocklist/allowlist is configured, as it conflicts with blocking rules in Puppeteer.
if (this.#hasNetworkBlockOrAllowlist) {
if (options.networkConditions !== undefined) {
throw new Error(
'Network throttling is not supported when network blocking (allowlist/blocklist) is configured.',
);
}
} else if (!options.networkConditions) {
await page.emulateNetworkConditions(null);
delete newSettings.networkConditions;
} else if (options.networkConditions === 'Offline') {
await page.emulateNetworkConditions({
offline: true,
download: 0,
upload: 0,
latency: 0,
});
newSettings.networkConditions = 'Offline';
} else if (options.networkConditions in PredefinedNetworkConditions) {
const networkCondition =
PredefinedNetworkConditions[
options.networkConditions as keyof typeof PredefinedNetworkConditions
];
await page.emulateNetworkConditions(networkCondition);
newSettings.networkConditions = options.networkConditions;
}
const secondarySession = this.devtoolsUniverse?.session;
if (!options.cpuThrottlingRate) {
await page.emulateCPUThrottling(1);
if (secondarySession) {
await secondarySession.send('Emulation.setCPUThrottlingRate', {
rate: 1,
});
}
delete newSettings.cpuThrottlingRate;
} else {
await page.emulateCPUThrottling(options.cpuThrottlingRate);
if (secondarySession) {
await secondarySession.send('Emulation.setCPUThrottlingRate', {
rate: options.cpuThrottlingRate,
});
}
newSettings.cpuThrottlingRate = options.cpuThrottlingRate;
}
if (!options.geolocation) {
await page.setGeolocation({latitude: 0, longitude: 0});
delete newSettings.geolocation;
} else {
await page.setGeolocation(options.geolocation);
newSettings.geolocation = options.geolocation;
}
if (!options.userAgent) {
await page.setUserAgent({userAgent: undefined});
delete newSettings.userAgent;
} else {
await page.setUserAgent({userAgent: options.userAgent});
newSettings.userAgent = options.userAgent;
}
if (!options.colorScheme || options.colorScheme === 'auto') {
await page.emulateMediaFeatures([
{name: 'prefers-color-scheme', value: ''},
]);
delete newSettings.colorScheme;
} else {
await page.emulateMediaFeatures([
{name: 'prefers-color-scheme', value: options.colorScheme},
]);
newSettings.colorScheme = options.colorScheme;
}
if (!options.viewport) {
delete newSettings.viewport;
} else {
const defaults = {
deviceScaleFactor: 1,
isMobile: false,
hasTouch: false,
isLandscape: false,
};
newSettings.viewport = {...defaults, ...options.viewport};
}
if (options.extraHttpHeaders !== undefined) {
await page.setExtraHTTPHeaders(options.extraHttpHeaders);
newSettings.extraHttpHeaders = options.extraHttpHeaders;
if (Object.keys(options.extraHttpHeaders).length === 0) {
delete newSettings.extraHttpHeaders;
}
}
this.emulationSettings = Object.keys(newSettings).length ? newSettings : {};
this.updateTimeouts();
// This should happen after updating the page timeouts.
// Setting the viewport can trigger a reload which we don't want to timeout.
await page.setViewport(newSettings.viewport ?? null);
}
updateTimeouts() {
// For waiters 5sec timeout should be sufficient.
// Increased in case we throttle the CPU
const cpuMultiplier = this.cpuThrottlingRate;
this.pptrPage.setDefaultTimeout(DEFAULT_TIMEOUT * cpuMultiplier);
// 10sec should be enough for the load event to be emitted during
// navigations.
// Increased in case we throttle the network requests or the CPU
const networkMultiplier = getNetworkMultiplierFromString(
this.networkConditions,
);
this.pptrPage.setDefaultNavigationTimeout(
NAVIGATION_TIMEOUT * networkMultiplier * cpuMultiplier,
);
}
waitForTextOnPage(text: string[], timeout?: number): Promise<Element> {
const frames = this.pptrPage.frames();
let locator = this.#locatorClass.race(
frames.flatMap(frame =>
text.flatMap(value => [
frame.locator(`aria/${value}`),
frame.locator(`text/${value}`),
]),
),
);
if (timeout) {
locator = locator.setTimeout(timeout);
}
return locator.wait();
}
/**
* We need to ignore favicon request as they make our test flaky
*/
async setUpNetworkCollectorForTesting() {
this.networkCollector.dispose();
this.networkCollector = new NetworkCollector(this.pptrPage, collect => {
return {
request: req => {
if (req.url().includes('favicon.ico')) {
return;
}
collect(req);
},
} as ListenerMap;
});
}
}