-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathscript.ts
More file actions
185 lines (167 loc) · 5.34 KB
/
script.ts
File metadata and controls
185 lines (167 loc) · 5.34 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
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {zod} from '../third_party/index.js';
import type {Frame, JSHandle, Page, WebWorker} from '../third_party/index.js';
import type {ExtensionServiceWorker} from '../types.js';
import {ToolCategory} from './categories.js';
import type {Context, Response} from './ToolDefinition.js';
import {defineTool, pageIdSchema} from './ToolDefinition.js';
export type Evaluatable = Page | Frame | WebWorker;
export const evaluateScript = defineTool(cliArgs => {
return {
name: 'evaluate_script',
description: `Evaluate a JavaScript function inside the currently selected page. Returns the response as JSON,
so returned values have to be JSON-serializable.`,
annotations: {
category: ToolCategory.DEBUGGING,
readOnlyHint: false,
},
schema: {
function: zod.string().describe(
`A JavaScript function declaration to be executed by the tool in the currently selected page.
Example without arguments: \`() => {
return document.title
}\` or \`async () => {
return await fetch("example.com")
}\`.
Example with arguments: \`(el) => {
return el.innerText;
}\`
`,
),
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 : {}),
...(cliArgs?.categoryExtensions
? {
serviceWorkerId: zod
.string()
.optional()
.describe(
`An optional service worker id to evaluate the script in.`,
),
}
: {}),
},
handler: async (request, response, context) => {
const {
serviceWorkerId,
args: uidArgs,
function: fnString,
pageId,
} = request.params;
if (cliArgs?.categoryExtensions && serviceWorkerId) {
if (uidArgs && uidArgs.length > 0) {
throw new Error(
'args (element uids) cannot be used when evaluating in a service worker.',
);
}
if (pageId) {
throw new Error('specify either a pageId or a serviceWorkerId.');
}
const worker = await getWebWorker(context, serviceWorkerId);
const selectedPage = context.getSelectedMcpPage();
const result = await selectedPage.waitForEventsAfterAction(async () => {
await performEvaluation(worker, fnString, [], response);
});
if (result.navigated) {
response.appendResponseLine(
`Page navigated to ${selectedPage.pptrPage.url()}.`,
);
}
return;
}
const mcpPage = cliArgs?.experimentalPageIdRouting
? context.getPageById(request.params.pageId)
: context.getSelectedMcpPage();
const page: Page = mcpPage.pptrPage;
const args: Array<JSHandle<unknown>> = [];
try {
const frames = new Set<Frame>();
for (const uid of uidArgs ?? []) {
const handle = await mcpPage.getElementByUid(uid);
frames.add(handle.frame);
args.push(handle);
}
const evaluatable = await getPageOrFrame(page, frames);
const result = await mcpPage.waitForEventsAfterAction(async () => {
await performEvaluation(evaluatable, fnString, args, response);
});
if (result.navigated) {
response.appendResponseLine(`Page navigated to ${page.url()}.`);
}
} finally {
void Promise.allSettled(args.map(arg => arg.dispose()));
}
},
};
});
const performEvaluation = async (
evaluatable: Evaluatable,
fnString: string,
args: Array<JSHandle<unknown>>,
response: Response,
) => {
const fn = await evaluatable.evaluateHandle(`(${fnString})`);
try {
const result = await evaluatable.evaluate(
async (fn, ...args) => {
// @ts-expect-error no types for function fn
return JSON.stringify(await fn(...args));
},
fn,
...args,
);
response.appendResponseLine('Script ran on page and returned:');
response.appendResponseLine('```json');
response.appendResponseLine(`${result}`);
response.appendResponseLine('```');
} finally {
void fn.dispose();
}
};
const getPageOrFrame = async (
page: Page,
frames: Set<Frame>,
): Promise<Page | Frame> => {
let pageOrFrame: Page | Frame;
// We can't evaluate the element handle across frames
if (frames.size > 1) {
throw new Error(
"Elements from different frames can't be evaluated together.",
);
} else {
pageOrFrame = [...frames.values()][0] ?? page;
}
return pageOrFrame;
};
const getWebWorker = async (
context: Context,
serviceWorkerId: string,
): Promise<WebWorker> => {
const serviceWorkers = context.getExtensionServiceWorkers();
const serviceWorker = serviceWorkers.find(
(sw: ExtensionServiceWorker) =>
context.getExtensionServiceWorkerId(sw) === serviceWorkerId,
);
if (serviceWorker && serviceWorker.target) {
const worker = await serviceWorker.target.worker();
if (!worker) {
throw new Error('Service worker target not found.');
}
return worker;
} else {
throw new Error('Service worker not found.');
}
};