-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathpages.ts
More file actions
373 lines (348 loc) · 10.7 KB
/
pages.ts
File metadata and controls
373 lines (348 loc) · 10.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
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {logger} from '../logger.js';
import type {Dialog} from '../third_party/index.js';
import {zod} from '../third_party/index.js';
import {ToolCategory} from './categories.js';
import {CLOSE_PAGE_ERROR, defineTool, timeoutSchema} from './ToolDefinition.js';
export const listPages = defineTool({
name: 'list_pages',
description: `Get a list of pages open in the browser.`,
annotations: {
category: ToolCategory.NAVIGATION,
readOnlyHint: true,
},
schema: {},
handler: async (_request, response) => {
response.setIncludePages(true);
},
});
export const selectPage = defineTool({
name: 'select_page',
description: `Select a page as a context for future tool calls.`,
annotations: {
category: ToolCategory.NAVIGATION,
readOnlyHint: true,
},
schema: {
pageId: zod
.number()
.describe(
`The ID of the page to select. Call ${listPages.name} to get available pages.`,
),
bringToFront: zod
.boolean()
.optional()
.describe('Whether to focus the page and bring it to the top.'),
},
handler: async (request, response, context) => {
const page = context.getPageById(request.params.pageId);
context.selectPage(page);
response.setIncludePages(true);
if (request.params.bringToFront) {
await page.bringToFront();
}
},
});
export const closePage = defineTool({
name: 'close_page',
description: `Closes the page by its index. The last open page cannot be closed.`,
annotations: {
category: ToolCategory.NAVIGATION,
readOnlyHint: false,
},
schema: {
pageId: zod
.number()
.describe('The ID of the page to close. Call list_pages to list pages.'),
},
handler: async (request, response, context) => {
try {
await context.closePage(request.params.pageId);
} catch (err) {
if (err.message === CLOSE_PAGE_ERROR) {
response.appendResponseLine(err.message);
} else {
throw err;
}
}
response.setIncludePages(true);
},
});
export const newPage = defineTool({
name: 'new_page',
description: `Creates a new page`,
annotations: {
category: ToolCategory.NAVIGATION,
readOnlyHint: false,
},
schema: {
url: zod.string().describe('URL to load in a new page.'),
background: zod
.boolean()
.optional()
.describe(
'Whether to open the page in the background without bringing it to the front. Default is false (foreground).',
),
...timeoutSchema,
},
handler: async (request, response, context) => {
const page = await context.newPage(request.params.background);
await context.waitForEventsAfterAction(
async () => {
await page.goto(request.params.url, {
timeout: request.params.timeout,
});
},
{timeout: request.params.timeout},
);
response.setIncludePages(true);
},
});
export const navigatePage = defineTool({
name: 'navigate_page',
description: `Navigates the currently selected page to a URL.`,
annotations: {
category: ToolCategory.NAVIGATION,
readOnlyHint: false,
},
schema: {
type: zod
.enum(['url', 'back', 'forward', 'reload'])
.optional()
.describe(
'Navigate the page by URL, back or forward in history, or reload.',
),
url: zod.string().optional().describe('Target URL (only type=url)'),
ignoreCache: zod
.boolean()
.optional()
.describe('Whether to ignore cache on reload.'),
handleBeforeUnload: zod
.enum(['accept', 'decline'])
.optional()
.describe(
'Whether to auto accept or beforeunload dialogs triggered by this navigation. Default is accept.',
),
initScript: zod
.string()
.optional()
.describe(
'A JavaScript script to be executed on each new document before any other scripts for the next navigation.',
),
...timeoutSchema,
},
handler: async (request, response, context) => {
const page = context.getSelectedPage();
const options = {
timeout: request.params.timeout,
};
if (!request.params.type && !request.params.url) {
throw new Error('Either URL or a type is required.');
}
if (!request.params.type) {
request.params.type = 'url';
}
const handleBeforeUnload = request.params.handleBeforeUnload ?? 'accept';
const dialogHandler = (dialog: Dialog) => {
if (dialog.type() === 'beforeunload') {
if (handleBeforeUnload === 'accept') {
response.appendResponseLine(`Accepted a beforeunload dialog.`);
void dialog.accept();
} else {
response.appendResponseLine(`Declined a beforeunload dialog.`);
void dialog.dismiss();
}
// We are not going to report the dialog like regular dialogs.
context.clearDialog();
}
};
let initScriptId: string | undefined;
if (request.params.initScript) {
const {identifier} = await page.evaluateOnNewDocument(
request.params.initScript,
);
initScriptId = identifier;
}
page.on('dialog', dialogHandler);
try {
await context.waitForEventsAfterAction(
async () => {
switch (request.params.type) {
case 'url':
if (!request.params.url) {
throw new Error(
'A URL is required for navigation of type=url.',
);
}
try {
await page.goto(request.params.url, options);
response.appendResponseLine(
`Successfully navigated to ${request.params.url}.`,
);
} catch (error) {
response.appendResponseLine(
`Unable to navigate in the selected page: ${error.message}.`,
);
}
break;
case 'back':
try {
await page.goBack(options);
response.appendResponseLine(
`Successfully navigated back to ${page.url()}.`,
);
} catch (error) {
response.appendResponseLine(
`Unable to navigate back in the selected page: ${error.message}.`,
);
}
break;
case 'forward':
try {
await page.goForward(options);
response.appendResponseLine(
`Successfully navigated forward to ${page.url()}.`,
);
} catch (error) {
response.appendResponseLine(
`Unable to navigate forward in the selected page: ${error.message}.`,
);
}
break;
case 'reload':
try {
await page.reload({
...options,
ignoreCache: request.params.ignoreCache,
});
response.appendResponseLine(`Successfully reloaded the page.`);
} catch (error) {
response.appendResponseLine(
`Unable to reload the selected page: ${error.message}.`,
);
}
break;
}
},
{timeout: request.params.timeout},
);
} finally {
page.off('dialog', dialogHandler);
if (initScriptId) {
await page
.removeScriptToEvaluateOnNewDocument(initScriptId)
.catch(error => {
logger(`Failed to remove init script`, error);
});
}
}
response.setIncludePages(true);
},
});
export const resizePage = defineTool({
name: 'resize_page',
description: `Resizes the selected page's window so that the page has specified dimension`,
annotations: {
category: ToolCategory.EMULATION,
readOnlyHint: false,
},
schema: {
width: zod.number().describe('Page width'),
height: zod.number().describe('Page height'),
},
handler: async (request, response, context) => {
const page = context.getSelectedPage();
try {
const browser = page.browser();
const windowId = await page.windowId();
const bounds = await browser.getWindowBounds(windowId);
if (bounds.windowState === 'fullscreen') {
// Have to call this twice on Ubuntu when the window is in fullscreen mode.
await browser.setWindowBounds(windowId, {windowState: 'normal'});
await browser.setWindowBounds(windowId, {windowState: 'normal'});
} else if (bounds.windowState !== 'normal') {
await browser.setWindowBounds(windowId, {windowState: 'normal'});
}
} catch {
// Window APIs are not supported on all platforms
}
await page.resize({
contentWidth: request.params.width,
contentHeight: request.params.height,
});
response.setIncludePages(true);
},
});
export const handleDialog = defineTool({
name: 'handle_dialog',
description: `If a browser dialog was opened, use this command to handle it`,
annotations: {
category: ToolCategory.INPUT,
readOnlyHint: false,
},
schema: {
action: zod
.enum(['accept', 'dismiss'])
.describe('Whether to dismiss or accept the dialog'),
promptText: zod
.string()
.optional()
.describe('Optional prompt text to enter into the dialog.'),
},
handler: async (request, response, context) => {
const dialog = context.getDialog();
if (!dialog) {
throw new Error('No open dialog found');
}
switch (request.params.action) {
case 'accept': {
try {
await dialog.accept(request.params.promptText);
} catch (err) {
// Likely already handled by the user outside of MCP.
logger(err);
}
response.appendResponseLine('Successfully accepted the dialog');
break;
}
case 'dismiss': {
try {
await dialog.dismiss();
} catch (err) {
// Likely already handled.
logger(err);
}
response.appendResponseLine('Successfully dismissed the dialog');
break;
}
}
context.clearDialog();
response.setIncludePages(true);
},
});
export const getTabId = defineTool({
name: 'get_tab_id',
description: `Get the tab ID of the page`,
annotations: {
category: ToolCategory.NAVIGATION,
readOnlyHint: true,
conditions: ['experimentalInteropTools'],
},
schema: {
pageId: zod
.number()
.describe(
`The ID of the page to get the tab ID for. Call ${listPages.name} to get available pages.`,
),
},
handler: async (request, response, context) => {
const page = context.getPageById(request.params.pageId);
// @ts-expect-error _tabId is internal.
const tabId = page._tabId;
response.setTabId(tabId);
},
});