-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathserver.js
More file actions
executable file
·1136 lines (1077 loc) · 38.4 KB
/
server.js
File metadata and controls
executable file
·1136 lines (1077 loc) · 38.4 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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import pkg from 'selenium-webdriver';
const { Builder, By, Key, until, Actions, error } = pkg;
import { Options as ChromeOptions } from 'selenium-webdriver/chrome.js';
import { Options as FirefoxOptions } from 'selenium-webdriver/firefox.js';
import { Options as EdgeOptions } from 'selenium-webdriver/edge.js';
import { Options as SafariOptions } from 'selenium-webdriver/safari.js';
// BiDi imports — loaded dynamically to avoid hard failures if not available
let LogInspector, Network;
try {
LogInspector = (await import('selenium-webdriver/bidi/logInspector.js')).default;
const networkModule = await import('selenium-webdriver/bidi/network.js');
Network = networkModule.Network;
} catch (_) {
// BiDi modules not available in this selenium-webdriver version
LogInspector = null;
Network = null;
}
// Create an MCP server
const server = new McpServer({
name: "MCP Selenium",
version: "1.0.0"
});
// Server state
const state = {
drivers: new Map(),
currentSession: null,
bidi: new Map()
};
// Helper functions
const getDriver = () => {
const driver = state.drivers.get(state.currentSession);
if (!driver) {
throw new Error('No active browser session');
}
return driver;
};
const getLocator = (by, value) => {
switch (by.toLowerCase()) {
case 'id': return By.id(value);
case 'css': return By.css(value);
case 'xpath': return By.xpath(value);
case 'name': return By.name(value);
case 'tag': return By.tagName(value);
case 'class': return By.className(value);
default: throw new Error(`Unsupported locator strategy: ${by}`);
}
};
// BiDi helpers
const newBidiState = () => ({
available: false,
consoleLogs: [],
pageErrors: [],
networkLogs: []
});
async function setupBidi(driver, sessionId) {
const bidi = newBidiState();
const logInspector = await LogInspector(driver);
await logInspector.onConsoleEntry((entry) => {
try {
bidi.consoleLogs.push({
level: entry.level, text: entry.text, timestamp: entry.timestamp,
type: entry.type, method: entry.method, args: entry.args
});
} catch (_) { /* ignore malformed entry */ }
});
await logInspector.onJavascriptLog((entry) => {
try {
bidi.pageErrors.push({
level: entry.level, text: entry.text, timestamp: entry.timestamp,
type: entry.type, stackTrace: entry.stackTrace
});
} catch (_) { /* ignore malformed entry */ }
});
const network = await Network(driver);
await network.responseCompleted((event) => {
try {
bidi.networkLogs.push({
type: 'response', url: event.request?.url, status: event.response?.status,
method: event.request?.method, mimeType: event.response?.mimeType, timestamp: Date.now()
});
} catch (_) { /* ignore malformed event */ }
});
await network.fetchError((event) => {
try {
bidi.networkLogs.push({
type: 'error', url: event.request?.url, method: event.request?.method,
errorText: event.errorText, timestamp: Date.now()
});
} catch (_) { /* ignore malformed event */ }
});
bidi.available = true;
state.bidi.set(sessionId, bidi);
}
function registerBidiTool(name, description, logKey, emptyMessage, unavailableMessage) {
server.tool(
name,
description,
{ clear: z.boolean().optional().describe("Clear after returning (default: false)") },
async ({ clear = false }) => {
try {
getDriver();
const bidi = state.bidi.get(state.currentSession);
if (!bidi?.available) {
return { content: [{ type: 'text', text: unavailableMessage }] };
}
const logs = bidi[logKey];
const result = logs.length === 0 ? emptyMessage : JSON.stringify(logs, null, 2);
if (clear) bidi[logKey] = [];
return { content: [{ type: 'text', text: result }] };
} catch (e) {
return { content: [{ type: 'text', text: `Error: ${e.message}` }], isError: true };
}
}
);
}
// Common schemas
const browserOptionsSchema = z.object({
headless: z.boolean().optional().describe("Run browser in headless mode"),
arguments: z.array(z.string()).optional().describe("Additional browser arguments")
}).optional();
const locatorSchema = {
by: z.enum(["id", "css", "xpath", "name", "tag", "class"]).describe("Locator strategy to find element"),
value: z.string().describe("Value for the locator strategy"),
timeout: z.number().optional().describe("Maximum time to wait for element in milliseconds")
};
// Browser Management Tools
server.tool(
"start_browser",
"launches browser",
{
browser: z.enum(["chrome", "firefox", "edge", "safari"]).describe("Browser to launch (chrome, firefox, edge, or safari)"),
options: browserOptionsSchema
},
async ({ browser, options = {} }) => {
try {
let builder = new Builder();
let driver;
let warnings = [];
// Enable BiDi websocket if the modules are available
if (LogInspector && Network) {
// 'ignore' prevents BiDi from auto-dismissing alert/confirm/prompt dialogs,
// allowing accept_alert, dismiss_alert, and get_alert_text to work as expected.
builder = builder.withCapabilities({ 'webSocketUrl': true, 'unhandledPromptBehavior': 'ignore' });
}
switch (browser) {
case 'chrome': {
const chromeOptions = new ChromeOptions();
if (options.headless) {
chromeOptions.addArguments('--headless=new');
}
if (options.arguments) {
options.arguments.forEach(arg => chromeOptions.addArguments(arg));
}
driver = await builder
.forBrowser('chrome')
.setChromeOptions(chromeOptions)
.build();
break;
}
case 'edge': {
const edgeOptions = new EdgeOptions();
if (options.headless) {
edgeOptions.addArguments('--headless=new');
}
if (options.arguments) {
options.arguments.forEach(arg => edgeOptions.addArguments(arg));
}
driver = await builder
.forBrowser('edge')
.setEdgeOptions(edgeOptions)
.build();
break;
}
case 'firefox': {
const firefoxOptions = new FirefoxOptions();
if (options.headless) {
firefoxOptions.addArguments('--headless');
}
if (options.arguments) {
options.arguments.forEach(arg => firefoxOptions.addArguments(arg));
}
driver = await builder
.forBrowser('firefox')
.setFirefoxOptions(firefoxOptions)
.build();
break;
}
case 'safari': {
const safariOptions = new SafariOptions();
if (options.headless) {
warnings.push('Safari does not support headless mode — launching with visible window.');
}
if (options.arguments?.length) {
warnings.push('Safari does not support custom arguments — ignoring.');
}
driver = await builder
.forBrowser('safari')
.setSafariOptions(safariOptions)
.build();
break;
}
default: {
throw new Error(`Unsupported browser: ${browser}`);
}
}
const sessionId = `${browser}_${Date.now()}`;
state.drivers.set(sessionId, driver);
state.currentSession = sessionId;
// Attempt to enable BiDi for real-time log capture
if (LogInspector && Network) {
try {
await setupBidi(driver, sessionId);
} catch (_) {
// BiDi not supported by this browser/driver — continue without it
}
}
let message = `Browser started with session_id: ${sessionId}`;
if (state.bidi.get(sessionId)?.available) {
message += ' (BiDi enabled: console logs, JS errors, and network activity are being captured)';
}
if (warnings.length > 0) {
message += `\nWarnings: ${warnings.join(' ')}`;
}
return {
content: [{ type: 'text', text: message }]
};
} catch (e) {
return {
content: [{ type: 'text', text: `Error starting browser: ${e.message}` }],
isError: true
};
}
}
);
server.tool(
"navigate",
"navigates to a URL",
{
url: z.string().describe("URL to navigate to")
},
async ({ url }) => {
try {
const driver = getDriver();
await driver.get(url);
return {
content: [{ type: 'text', text: `Navigated to ${url}` }]
};
} catch (e) {
return {
content: [{ type: 'text', text: `Error navigating: ${e.message}` }],
isError: true
};
}
}
);
// Element Interaction Tools
server.tool(
"find_element",
"finds an element",
{
...locatorSchema
},
async ({ by, value, timeout = 10000 }) => {
try {
const driver = getDriver();
const locator = getLocator(by, value);
await driver.wait(until.elementLocated(locator), timeout);
return {
content: [{ type: 'text', text: 'Element found' }]
};
} catch (e) {
return {
content: [{ type: 'text', text: `Error finding element: ${e.message}` }],
isError: true
};
}
}
);
server.tool(
"click_element",
"clicks an element",
{
...locatorSchema
},
async ({ by, value, timeout = 10000 }) => {
try {
const driver = getDriver();
const locator = getLocator(by, value);
const element = await driver.wait(until.elementLocated(locator), timeout);
await element.click();
return {
content: [{ type: 'text', text: 'Element clicked' }]
};
} catch (e) {
return {
content: [{ type: 'text', text: `Error clicking element: ${e.message}` }],
isError: true
};
}
}
);
server.tool(
"send_keys",
"sends keys to an element, aka typing",
{
...locatorSchema,
text: z.string().describe("Text to enter into the element")
},
async ({ by, value, text, timeout = 10000 }) => {
try {
const driver = getDriver();
const locator = getLocator(by, value);
const element = await driver.wait(until.elementLocated(locator), timeout);
await element.clear();
await element.sendKeys(text);
return {
content: [{ type: 'text', text: `Text "${text}" entered into element` }]
};
} catch (e) {
return {
content: [{ type: 'text', text: `Error entering text: ${e.message}` }],
isError: true
};
}
}
);
server.tool(
"get_element_text",
"gets the text() of an element",
{
...locatorSchema
},
async ({ by, value, timeout = 10000 }) => {
try {
const driver = getDriver();
const locator = getLocator(by, value);
const element = await driver.wait(until.elementLocated(locator), timeout);
const text = await element.getText();
return {
content: [{ type: 'text', text }]
};
} catch (e) {
return {
content: [{ type: 'text', text: `Error getting element text: ${e.message}` }],
isError: true
};
}
}
);
server.tool(
"hover",
"moves the mouse to hover over an element",
{
...locatorSchema
},
async ({ by, value, timeout = 10000 }) => {
try {
const driver = getDriver();
const locator = getLocator(by, value);
const element = await driver.wait(until.elementLocated(locator), timeout);
const actions = driver.actions({ bridge: true });
await actions.move({ origin: element }).perform();
return {
content: [{ type: 'text', text: 'Hovered over element' }]
};
} catch (e) {
return {
content: [{ type: 'text', text: `Error hovering over element: ${e.message}` }],
isError: true
};
}
}
);
server.tool(
"drag_and_drop",
"drags an element and drops it onto another element",
{
...locatorSchema,
targetBy: z.enum(["id", "css", "xpath", "name", "tag", "class"]).describe("Locator strategy to find target element"),
targetValue: z.string().describe("Value for the target locator strategy")
},
async ({ by, value, targetBy, targetValue, timeout = 10000 }) => {
try {
const driver = getDriver();
const sourceLocator = getLocator(by, value);
const targetLocator = getLocator(targetBy, targetValue);
const sourceElement = await driver.wait(until.elementLocated(sourceLocator), timeout);
const targetElement = await driver.wait(until.elementLocated(targetLocator), timeout);
const actions = driver.actions({ bridge: true });
await actions.dragAndDrop(sourceElement, targetElement).perform();
return {
content: [{ type: 'text', text: 'Drag and drop completed' }]
};
} catch (e) {
return {
content: [{ type: 'text', text: `Error performing drag and drop: ${e.message}` }],
isError: true
};
}
}
);
server.tool(
"double_click",
"performs a double click on an element",
{
...locatorSchema
},
async ({ by, value, timeout = 10000 }) => {
try {
const driver = getDriver();
const locator = getLocator(by, value);
const element = await driver.wait(until.elementLocated(locator), timeout);
const actions = driver.actions({ bridge: true });
await actions.doubleClick(element).perform();
return {
content: [{ type: 'text', text: 'Double click performed' }]
};
} catch (e) {
return {
content: [{ type: 'text', text: `Error performing double click: ${e.message}` }],
isError: true
};
}
}
);
server.tool(
"right_click",
"performs a right click (context click) on an element",
{
...locatorSchema
},
async ({ by, value, timeout = 10000 }) => {
try {
const driver = getDriver();
const locator = getLocator(by, value);
const element = await driver.wait(until.elementLocated(locator), timeout);
const actions = driver.actions({ bridge: true });
await actions.contextClick(element).perform();
return {
content: [{ type: 'text', text: 'Right click performed' }]
};
} catch (e) {
return {
content: [{ type: 'text', text: `Error performing right click: ${e.message}` }],
isError: true
};
}
}
);
server.tool(
"press_key",
"simulates pressing a keyboard key",
{
key: z.string().describe("Key to press (e.g., 'Enter', 'Tab', 'a', etc.)")
},
async ({ key }) => {
try {
const driver = getDriver();
// Map named keys to Selenium Key constants (case-insensitive).
// Single characters are passed through as-is.
const resolvedKey = key.length === 1
? key
: Key[key.toUpperCase().replace(/ /g, '_')] ?? null;
if (resolvedKey === null) {
return {
content: [{ type: 'text', text: `Error pressing key: Unknown key name '${key}'. Use a single character or a named key like 'Enter', 'Tab', 'Escape', etc.` }],
isError: true
};
}
const actions = driver.actions({ bridge: true });
await actions.keyDown(resolvedKey).keyUp(resolvedKey).perform();
return {
content: [{ type: 'text', text: `Key '${key}' pressed` }]
};
} catch (e) {
return {
content: [{ type: 'text', text: `Error pressing key: ${e.message}` }],
isError: true
};
}
}
);
server.tool(
"upload_file",
"uploads a file using a file input element",
{
...locatorSchema,
filePath: z.string().describe("Absolute path to the file to upload")
},
async ({ by, value, filePath, timeout = 10000 }) => {
try {
const driver = getDriver();
const locator = getLocator(by, value);
const element = await driver.wait(until.elementLocated(locator), timeout);
await element.sendKeys(filePath);
return {
content: [{ type: 'text', text: 'File upload initiated' }]
};
} catch (e) {
return {
content: [{ type: 'text', text: `Error uploading file: ${e.message}` }],
isError: true
};
}
}
);
server.tool(
"take_screenshot",
"captures a screenshot of the current page",
{
outputPath: z.string().optional().describe("Optional path where to save the screenshot. If not provided, returns an image/png content block.")
},
async ({ outputPath }) => {
try {
const driver = getDriver();
const screenshot = await driver.takeScreenshot();
if (outputPath) {
const fs = await import('fs');
await fs.promises.writeFile(outputPath, screenshot, 'base64');
return {
content: [{ type: 'text', text: `Screenshot saved to ${outputPath}` }]
};
} else {
return {
content: [
{ type: 'image', data: screenshot, mimeType: 'image/png' }
]
};
}
} catch (e) {
return {
content: [{ type: 'text', text: `Error taking screenshot: ${e.message}` }],
isError: true
};
}
}
);
server.tool(
"close_session",
"closes the current browser session",
{},
async () => {
try {
const driver = getDriver();
const sessionId = state.currentSession;
try {
await driver.quit();
} finally {
state.drivers.delete(sessionId);
state.bidi.delete(sessionId);
state.currentSession = null;
}
return {
content: [{ type: 'text', text: `Browser session ${sessionId} closed` }]
};
} catch (e) {
return {
content: [{ type: 'text', text: `Error closing session: ${e.message}` }],
isError: true
};
}
}
);
// Element Utility Tools
server.tool(
"clear_element",
"clears the content of an input or textarea element",
{
...locatorSchema
},
async ({ by, value, timeout = 10000 }) => {
try {
const driver = getDriver();
const locator = getLocator(by, value);
const element = await driver.wait(until.elementLocated(locator), timeout);
await element.clear();
return {
content: [{ type: 'text', text: 'Element cleared' }]
};
} catch (e) {
return {
content: [{ type: 'text', text: `Error clearing element: ${e.message}` }],
isError: true
};
}
}
);
server.tool(
"get_element_attribute",
"gets the value of an attribute on an element",
{
...locatorSchema,
attribute: z.string().describe("Name of the attribute to get (e.g., 'href', 'value', 'class')")
},
async ({ by, value, attribute, timeout = 10000 }) => {
try {
const driver = getDriver();
const locator = getLocator(by, value);
const element = await driver.wait(until.elementLocated(locator), timeout);
const attrValue = await element.getAttribute(attribute);
return {
content: [{ type: 'text', text: attrValue !== null ? attrValue : '' }]
};
} catch (e) {
return {
content: [{ type: 'text', text: `Error getting attribute: ${e.message}` }],
isError: true
};
}
}
);
server.tool(
"scroll_to_element",
"scrolls the page until an element is visible",
{
...locatorSchema
},
async ({ by, value, timeout = 10000 }) => {
try {
const driver = getDriver();
const locator = getLocator(by, value);
const element = await driver.wait(until.elementLocated(locator), timeout);
await driver.executeScript("arguments[0].scrollIntoView({block: 'center'});", element);
return {
content: [{ type: 'text', text: 'Scrolled to element' }]
};
} catch (e) {
return {
content: [{ type: 'text', text: `Error scrolling to element: ${e.message}` }],
isError: true
};
}
}
);
server.tool(
"execute_script",
"executes JavaScript in the browser and returns the result",
{
script: z.string().describe("JavaScript code to execute in the browser"),
args: z.array(z.any()).optional().describe("Optional arguments to pass to the script (accessible via arguments[0], arguments[1], etc.)")
},
async ({ script, args = [] }) => {
try {
const driver = getDriver();
const result = await driver.executeScript(script, ...args);
const text = result === undefined || result === null
? 'Script executed (no return value)'
: typeof result === 'object' ? JSON.stringify(result, null, 2) : String(result);
return {
content: [{ type: 'text', text }]
};
} catch (e) {
return {
content: [{ type: 'text', text: `Error executing script: ${e.message}` }],
isError: true
};
}
}
);
// Window/Tab Management Tools
server.tool(
"switch_to_window",
"switches to a specific browser window or tab by handle",
{
handle: z.string().describe("Window handle to switch to")
},
async ({ handle }) => {
try {
const driver = getDriver();
await driver.switchTo().window(handle);
return {
content: [{ type: 'text', text: `Switched to window: ${handle}` }]
};
} catch (e) {
return {
content: [{ type: 'text', text: `Error switching window: ${e.message}` }],
isError: true
};
}
}
);
server.tool(
"get_window_handles",
"returns all window/tab handles for the current session",
{},
async () => {
try {
const driver = getDriver();
const handles = await driver.getAllWindowHandles();
const current = await driver.getWindowHandle();
return {
content: [{ type: 'text', text: JSON.stringify({ current, all: handles }, null, 2) }]
};
} catch (e) {
return {
content: [{ type: 'text', text: `Error getting window handles: ${e.message}` }],
isError: true
};
}
}
);
server.tool(
"switch_to_latest_window",
"switches to the most recently opened window or tab",
{},
async () => {
try {
const driver = getDriver();
const handles = await driver.getAllWindowHandles();
if (handles.length === 0) {
throw new Error('No windows available');
}
const latest = handles[handles.length - 1];
await driver.switchTo().window(latest);
return {
content: [{ type: 'text', text: `Switched to latest window: ${latest}` }]
};
} catch (e) {
return {
content: [{ type: 'text', text: `Error switching to latest window: ${e.message}` }],
isError: true
};
}
}
);
server.tool(
"close_current_window",
"closes the current window/tab and switches back to the first remaining window",
{},
async () => {
try {
const driver = getDriver();
await driver.close();
const handles = await driver.getAllWindowHandles();
if (handles.length > 0) {
await driver.switchTo().window(handles[0]);
return {
content: [{ type: 'text', text: `Window closed. Switched to: ${handles[0]}` }]
};
}
// Last window closed — quit the driver and clean up the session
const sessionId = state.currentSession;
try {
await driver.quit();
} catch (quitError) {
console.error(`Error quitting driver for session ${sessionId}:`, quitError);
}
state.drivers.delete(sessionId);
state.bidi.delete(sessionId);
state.currentSession = null;
return {
content: [{ type: 'text', text: 'Last window closed. Session ended.' }]
};
} catch (e) {
return {
content: [{ type: 'text', text: `Error closing window: ${e.message}` }],
isError: true
};
}
}
);
// Frame Management Tools
server.tool(
"switch_to_frame",
"switches focus to an iframe or frame within the page. Provide either by/value to locate by element, or index to switch by position.",
{
by: z.enum(["id", "css", "xpath", "name", "tag", "class"]).optional().describe("Locator strategy to find frame element"),
value: z.string().optional().describe("Value for the locator strategy"),
index: z.number().optional().describe("Frame index (0-based) to switch to by position"),
timeout: z.number().optional().describe("Maximum time to wait for frame in milliseconds")
},
async ({ by, value, index, timeout = 10000 }) => {
try {
const driver = getDriver();
if (index !== undefined) {
await driver.switchTo().frame(index);
} else if (by && value) {
const locator = getLocator(by, value);
const element = await driver.wait(until.elementLocated(locator), timeout);
await driver.switchTo().frame(element);
} else {
throw new Error('Provide either by/value to locate frame by element, or index to switch by position');
}
return {
content: [{ type: 'text', text: `Switched to frame` }]
};
} catch (e) {
return {
content: [{ type: 'text', text: `Error switching to frame: ${e.message}` }],
isError: true
};
}
}
);
server.tool(
"switch_to_default_content",
"switches focus back to the main page from an iframe",
{},
async () => {
try {
const driver = getDriver();
await driver.switchTo().defaultContent();
return {
content: [{ type: 'text', text: 'Switched to default content' }]
};
} catch (e) {
return {
content: [{ type: 'text', text: `Error switching to default content: ${e.message}` }],
isError: true
};
}
}
);
// Alert/Dialog Tools
server.tool(
"accept_alert",
"accepts (clicks OK) on a browser alert, confirm, or prompt dialog",
{
timeout: z.number().optional().describe("Maximum time to wait for alert in milliseconds")
},
async ({ timeout = 5000 }) => {
try {
const driver = getDriver();
await driver.wait(until.alertIsPresent(), timeout);
const alert = await driver.switchTo().alert();
await alert.accept();
return {
content: [{ type: 'text', text: 'Alert accepted' }]
};
} catch (e) {
return {
content: [{ type: 'text', text: `Error accepting alert: ${e.message}` }],
isError: true
};
}
}
);
server.tool(
"dismiss_alert",
"dismisses (clicks Cancel) on a browser alert, confirm, or prompt dialog",
{
timeout: z.number().optional().describe("Maximum time to wait for alert in milliseconds")
},
async ({ timeout = 5000 }) => {
try {
const driver = getDriver();
await driver.wait(until.alertIsPresent(), timeout);
const alert = await driver.switchTo().alert();
await alert.dismiss();
return {
content: [{ type: 'text', text: 'Alert dismissed' }]
};
} catch (e) {
return {
content: [{ type: 'text', text: `Error dismissing alert: ${e.message}` }],
isError: true
};
}
}
);
server.tool(
"get_alert_text",
"gets the text content of a browser alert, confirm, or prompt dialog",
{
timeout: z.number().optional().describe("Maximum time to wait for alert in milliseconds")
},
async ({ timeout = 5000 }) => {
try {
const driver = getDriver();
await driver.wait(until.alertIsPresent(), timeout);
const alert = await driver.switchTo().alert();
const text = await alert.getText();
return {
content: [{ type: 'text', text }]
};
} catch (e) {
return {
content: [{ type: 'text', text: `Error getting alert text: ${e.message}` }],
isError: true
};
}
}
);
server.tool(
"send_alert_text",
"types text into a browser prompt dialog and accepts it",
{
text: z.string().describe("Text to enter into the prompt"),
timeout: z.number().optional().describe("Maximum time to wait for alert in milliseconds")
},
async ({ text, timeout = 5000 }) => {
try {
const driver = getDriver();
await driver.wait(until.alertIsPresent(), timeout);
const alert = await driver.switchTo().alert();
await alert.sendKeys(text);
await alert.accept();
return {
content: [{ type: 'text', text: `Text "${text}" sent to prompt and accepted` }]
};
} catch (e) {
return {
content: [{ type: 'text', text: `Error sending text to alert: ${e.message}` }],
isError: true
};
}
}
);
// Cookie Management Tools
server.tool(
"add_cookie",
"adds a cookie to the current browser session. The browser must be on a page from the cookie's domain before setting it.",
{
name: z.string().describe("Name of the cookie"),
value: z.string().describe("Value of the cookie"),
domain: z.string().optional().describe("Domain the cookie is visible to"),
path: z.string().optional().describe("Path the cookie is visible to"),
secure: z.boolean().optional().describe("Whether the cookie is a secure cookie"),
httpOnly: z.boolean().optional().describe("Whether the cookie is HTTP only"),
expiry: z.number().optional().describe("Expiry date of the cookie as a Unix timestamp (seconds since epoch)")
},
async ({ name, value, domain, path, secure, httpOnly, expiry }) => {
try {
const driver = getDriver();
const cookie = { name, value };
if (domain !== undefined) cookie.domain = domain;
if (path !== undefined) cookie.path = path;
if (secure !== undefined) cookie.secure = secure;
if (httpOnly !== undefined) cookie.httpOnly = httpOnly;
if (expiry !== undefined) cookie.expiry = expiry;
await driver.manage().addCookie(cookie);
return {
content: [{ type: 'text', text: `Cookie "${name}" added` }]
};
} catch (e) {
return {
content: [{ type: 'text', text: `Error adding cookie: ${e.message}` }],
isError: true
};
}
}
);
server.tool(
"get_cookies",
"retrieves cookies from the current browser session. Returns all cookies or a specific cookie by name.",