-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcdp_server.py
More file actions
1594 lines (1302 loc) · 54.4 KB
/
Copy pathcdp_server.py
File metadata and controls
1594 lines (1302 loc) · 54.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 python3
"""
SeleniumBase Pure CDP Mode MCP Server
======================================
Exposes SeleniumBase's Pure CDP Mode (sync API, `seleniumbase.sb_cdp.Chrome`)
as MCP tools. Pure CDP Mode drives the browser entirely over the Chrome
DevTools Protocol (no WebDriver), which is SeleniumBase's stealthiest mode
and includes captcha-solving support.
Reference:
github.com/seleniumbase/SeleniumBase/blob/master/help_docs/cdp_mode_methods.md
Model: One persistent `sb_cdp.Chrome` session per server process.
Call start_browser once; drive it with the other tools; then close_browser.
Design notes:
Tools follow a consistent CSS-selector-or-text matching convention:
selector arguments accept a CSS selector or visible text (for example,
a:contains("Sign in")). Related SeleniumBase capabilities are consolidated
into parameterized tools using action, mode, state, or check parameters.
This keeps the toolset compact and predictable while giving an MCP client
access to the underlying browser-automation capabilities without
having to choose between multiple near-identical tools.
Tool-selection philosophy:
- Use get_page_info for browser/page metadata such as URL, title, origin,
and navigation history.
- Use get_content for reading visible text or HTML.
- Use find_elements for discovering and inspecting multiple matching
elements as structured data.
- Use check_state for an immediate, non-waiting state check.
- Use wait_for when the agent needs to wait for a condition to become true.
- Use assert_condition when the agent needs to verify an expected condition
and treat failure as an assertion error.
- Use click/type_text/select_option/hover_with_action/focus_on for
interactions and element positioning.
"""
from __future__ import annotations
import atexit
import sys
from functools import wraps
from typing import Any, Literal
from mcp.server import MCPServer
from seleniumbase import sb_cdp
mcp = MCPServer("seleniumbase-cdp")
_sb: sb_cdp.CDPMethods | None = None
def _get_sb() -> sb_cdp.CDPMethods:
"""Return the active browser session or raise a useful lifecycle error."""
if _sb is None:
raise RuntimeError("No browser session. Call start_browser first.")
return _sb
def handle_sb_errors(func):
"""Convert SeleniumBase/runtime exceptions into descriptive MCP results.
Browser automation failures are returned as readable error strings so
an MCP client/LLM can inspect the error and decide whether to retry,
change a selector, wait for a condition, navigate elsewhere, or take
another corrective action.
"""
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
error_type = e.__class__.__name__
error_msg = str(e).strip()
return f"Error in {func.__name__}: {error_type} - {error_msg}"
return wrapper
# ---------------------------------------------------------------------------
# Session lifecycle
# ---------------------------------------------------------------------------
@mcp.tool()
def start_browser(
url: str | None = None,
headless: bool | None = None,
use_chromium: bool = False,
browser_executable_path: str | None = None,
incognito: bool = False,
guest: bool = False,
ad_block: bool = False,
proxy: str | None = None,
) -> str:
"""Launch a persistent SeleniumBase Pure CDP Mode browser session.
This must be called before browser interaction tools such as navigate,
get_content, click, type_text, or find_elements. The same browser
session remains active across subsequent MCP tool calls until
close_browser is called or the server process exits.
Pure CDP Mode communicates directly with the browser through the Chrome
DevTools Protocol rather than WebDriver. This provides SeleniumBase's
CDP-based browser automation capabilities without using WebDriver as the
browser-control layer.
Args:
url: Optional URL to open immediately after the browser launches.
If omitted, the browser starts without navigating to a requested
page.
headless: Controls whether the browser runs without a visible window.
If True, always run headless. If False, always run headed.
If omitted (None), the default depends on the operating system:
Linux defaults to headless because MCP/server environments
commonly do not have a graphical desktop, while Windows and macOS
default to headed so that a visible browser window is available.
Use True or False to explicitly override the OS-specific default
on any operating system.
use_chromium: Use Chromium instead of Google Chrome. This is useful
when Google Chrome is not installed. SeleniumBase can manage the
Chromium browser when this option is enabled.
browser_executable_path: Explicit filesystem path to the browser
executable when it is not installed in a standard location.
Do not combine this with use_chromium=True.
incognito: Launch Chrome/Chromium in incognito mode.
guest: Launch Chrome/Chromium in guest mode. Do not combine this with
incognito=True.
ad_block: Enable SeleniumBase's basic ad-blocking functionality.
proxy: Optional proxy server. Examples include
"SERVER:PORT" or "USER:PASS@SERVER:PORT".
Returns:
A confirmation message when the browser starts successfully, including
the effective headless setting, or a descriptive error when browser
startup fails.
Lifecycle:
Call start_browser once at the beginning of a browser automation
workflow. Reusing the existing session preserves cookies, tabs,
navigation history, localStorage/sessionStorage, and other browser
state between tool calls. Call close_browser when finished.
Environment requirements:
The MCP runtime must have a compatible Chrome or Chromium browser
available. If the browser executable cannot be discovered, use
use_chromium=True or provide browser_executable_path explicitly.
On Linux, the default is headless=True so the browser can run in
typical server/container environments without a graphical desktop.
Set headless=False when a graphical display is available and a visible
browser is desired. On Windows and macOS, the default is
headless=False. Set headless=True when running without a desktop or
when a visible browser window is not desired.
"""
global _sb
if _sb is not None:
return (
"A browser session is already running. "
"Call close_browser first."
)
if incognito and guest:
return "Error: incognito and guest cannot both be enabled."
if use_chromium and browser_executable_path:
return (
"Error: use_chromium and browser_executable_path "
"cannot both be used at the same time."
)
# OS-specific default:
# - Linux: headless by default for server/container compatibility.
# - Windows/macOS: headed by default for interactive desktop use.
# - Explicit True/False always overrides the OS default.
if headless is None:
effective_headless = sys.platform.startswith("linux")
else:
effective_headless = headless
kwargs: dict[str, Any] = {"headless": effective_headless}
if use_chromium:
kwargs["use_chromium"] = True
if browser_executable_path:
kwargs["browser_executable_path"] = browser_executable_path
if incognito:
kwargs["incognito"] = True
if guest:
kwargs["guest"] = True
if ad_block:
kwargs["ad_block"] = True
if proxy:
kwargs["proxy"] = proxy
try:
_sb = sb_cdp.Chrome(url, **kwargs)
return (
f"Started Pure CDP Mode browser "
f"(url={url!r}, headless={effective_headless}, "
f"use_chromium={use_chromium})"
)
except Exception as e:
if _sb is not None:
try:
_sb.quit()
except Exception:
pass
_sb = None
return (
f"Error starting browser: "
f"{e.__class__.__name__} - {str(e).strip()}"
)
@mcp.tool()
def close_browser() -> str:
"""Close the active browser session and release browser resources.
Call this when the browser automation workflow is finished. Closing the
session ends the persistent browser state, including its open tabs,
cookies, navigation history, and page state. If browser automation is
needed afterward, start a new session with start_browser.
This operation is safe to call when no browser session is active.
"""
global _sb
if _sb is None:
return "No browser session was running."
try:
_sb.quit()
except Exception:
pass
_sb = None
return "Browser closed."
# ---------------------------------------------------------------------------
# Page information
# ---------------------------------------------------------------------------
@mcp.tool()
@handle_sb_errors
def get_page_info() -> dict | str:
"""Get current browser session and page metadata.
Use this as the primary tool for determining where the browser currently
is after navigation, clicks, form submissions, redirects, reloads, or
tab switches.
This is a READ-ONLY metadata operation. It does not inspect arbitrary
page content, find elements, check visibility, wait for conditions, or
assert expected values.
Returns:
A dictionary containing:
- running: True when a browser session is active.
- url: The complete current page URL, including path and query string.
- title: The current document title.
- origin: The current page origin (scheme, host, and port).
- user_agent: The browser's current User-Agent string.
- history: The browser navigation history for the current session.
Tool selection:
- Need URL, title, origin, User-Agent, or navigation history ->
use get_page_info.
- Need visible page text or HTML -> use get_content.
- Need information about matching elements -> use find_elements.
- Need an immediate state check -> use check_state.
- Need to wait for a condition -> use wait_for.
- Need to verify an expected condition -> use assert_condition.
Unlike a dedicated browser-status tool, get_page_info is the single
source of browser/page metadata. If no browser session is active, it
returns {"running": False} instead of attempting to access a page.
This operation does not navigate, reload, click, type, or otherwise
modify the current page.
"""
if _sb is None:
return {"running": False}
try:
return {
"running": True,
"url": _sb.get_current_url(),
"title": _sb.get_title(),
"origin": _sb.get_origin(),
"user_agent": _sb.get_user_agent(),
"history": _sb.get_navigation_history(),
}
except Exception as e:
return {
"running": False,
"error": f"{e.__class__.__name__}: {str(e).strip()}",
}
# ---------------------------------------------------------------------------
# Navigation
# ---------------------------------------------------------------------------
@mcp.tool()
@handle_sb_errors
def navigate(url: str) -> str:
"""Navigate the current browser tab to a URL.
Use this when the browser needs to visit a new URL rather than move
through its existing back/forward history.
If the URL does not include a protocol such as "https://", SeleniumBase
automatically prefixes "https://" before navigation. For example,
"seleniumbase.io" becomes "https://seleniumbase.io".
Navigation waits for the initial HTML document to be loaded before
returning. The visited page becomes part of the browser's navigation
history.
Args:
url: Destination URL. May be a complete URL such as
"https://example.com" or a hostname such as "example.com".
Returns:
A confirmation containing the requested URL.
Tool selection:
- Go to a new URL -> use navigate.
- Return to the previous page -> use navigate_history(action="back").
- Go forward in history -> use navigate_history(action="forward").
- Refresh the current page -> use navigate_history(action="reload").
"""
_get_sb().get(url)
return f"Navigated to {url}"
@mcp.tool()
@handle_sb_errors
def navigate_history(
action: Literal["back", "forward", "reload"] = "back",
) -> str:
"""Navigate through the current browser history or reload the page.
Use this tool only for navigation relative to the current browser
history. Use navigate when going to an arbitrary URL.
Args:
action:
- "back": Navigate to the previous history entry. Has no useful
effect when there is no previous history entry.
- "forward": Navigate to the next history entry. Has no useful
effect when there is no forward history entry.
- "reload": Reload the current page while ignoring the browser
cache so page resources are fetched again.
Returns:
A confirmation message describing the operation performed.
Notes:
These operations can trigger page loads, redirects, and other
navigation events. Use get_page_info afterward when you need to
verify the resulting URL or title.
Tool selection:
- Arbitrary destination URL -> use navigate.
- Previous/next browser history entry -> use this tool.
- Refresh current page -> use this tool with action="reload".
"""
sb = _get_sb()
if action == "back":
sb.go_back()
return "Navigated back."
if action == "forward":
sb.go_forward()
return "Navigated forward."
if action == "reload":
sb.reload(ignore_cache=True)
return "Page reloaded."
return (
f"Error: unknown action '{action}'. "
"Use 'back', 'forward', or 'reload'."
)
# ---------------------------------------------------------------------------
# Finding & reading
# ---------------------------------------------------------------------------
@mcp.tool()
@handle_sb_errors
def find_elements(
selector: str,
timeout: int | float | None = 7,
include_html: bool = False,
) -> dict | str:
"""Find matching elements and return structured element information.
Use this tool when you need to discover how many elements match a
selector, inspect their text/tag names, or inspect the HTML of multiple
matches.
This tool resolves element handles immediately into ordinary JSON-like
dictionaries. It does not return live SeleniumBase element objects.
Args:
selector: CSS selector, or a SeleniumBase selector that can match
visible text. Examples include "button", ".login-link", or
'a:contains("Sign in")'.
timeout: Maximum number of seconds to wait for matching elements.
Defaults to 7 seconds.
include_html: If True, include each matching element's outer HTML.
If False, return only tag name and text.
Returns:
A dictionary containing:
- count: Number of matching elements found.
- matches: A list of element dictionaries containing tag_name and
text, plus html when include_html=True.
Tool selection:
- Need structured information about matching elements ->
use find_elements.
- Need the visible text/HTML of a page or a single element ->
use get_content.
- Need to click one of several matches -> use click with nth.
- Need to know whether an element is present/visible ->
use check_state.
Note:
Element handles cannot be persisted across MCP calls. If you find
elements and then need to act on one, resolve it again with the
appropriate interaction tool.
"""
sb = _get_sb()
els = sb.find_all(selector, timeout=timeout)
if include_html:
return {
"count": len(els),
"matches": [
{
"tag_name": e.tag_name,
"text": e.text,
"html": e.get_html(),
}
for e in els
],
}
return {
"count": len(els),
"matches": [
{
"tag_name": e.tag_name,
"text": e.text,
}
for e in els
],
}
@mcp.tool()
@handle_sb_errors
def get_content(
selector: str | None = None,
output_format: Literal["text", "html", "urls"] = "text",
include_shadow_dom: bool = True,
) -> str | list[str]:
"""Read visible text, HTML, or discovered URLs from the current page.
Use this tool when you need actual page content or URL information rather
than page metadata.
Args:
selector: Optional CSS selector or SeleniumBase text-matching selector
identifying the element whose content should be read. For
output_format="text" or "html", the selector scopes the returned
content to that element. For output_format="urls", the selector
scopes URL discovery to URLs within that element. When omitted,
the operation applies to the whole page.
output_format:
- "text": Return visible text from the page or selected element.
- "html": Return HTML from the page or selected element.
- "urls": Return all discovered linked/resource URLs on the page
or within the selected element. URLs associated with elements
such as anchors, links, images, scripts, and metadata may be
included. SeleniumBase returns full URLs with their URL
prefixes.
include_shadow_dom: When output_format="html" and selector is omitted,
include any shadow-root HTML present in the page. This option has
no effect for "text" or "urls", or when a selector is specified.
Returns:
For output_format="text", a string containing visible text.
For output_format="html", a string containing HTML.
For output_format="urls", a list of URL strings. This is useful for
crawling, link discovery, resource inspection, and finding candidate
URLs before navigating to them.
Tool selection:
- Need URL, title, origin, User-Agent, or navigation history ->
use get_page_info.
- Need visible text -> use output_format="text".
- Need page or element HTML -> use output_format="html".
- Need URLs from the page or an element -> use output_format="urls".
- Need structured information about matching elements ->
use find_elements.
- Need to check whether an element is present or visible ->
use check_state.
- Need to wait for content to appear -> use wait_for.
"""
sb = _get_sb()
if output_format == "urls":
return sb.get_all_urls(selector=selector)
if selector is None:
if output_format == "html":
return sb.get_page_source(
include_shadow_dom=include_shadow_dom
)
return sb.get_text("body")
if output_format == "html":
return sb.get_element_html(selector)
return sb.get_text(selector)
@mcp.tool()
@handle_sb_errors
def get_attributes(
selector: str,
attribute: str | None = None,
) -> Any:
"""Read HTML attributes from a matching element.
Use this tool when you need the value of one or more HTML attributes
such as href, src, value, class, id, name, type, aria-label, or data-*.
Args:
selector: CSS selector or SeleniumBase text-matching selector for
the target element.
attribute: Specific HTML attribute to retrieve. When omitted, return
all HTML attributes of the element as a dictionary.
Returns:
The requested attribute value, or a dictionary containing all
HTML attributes of the element when attribute is omitted.
Tool selection:
- Need one or more HTML attribute values from a specific element ->
use this tool.
- Need to discover multiple matching elements or inspect their text ->
use 'find_elements'.
- Need visible text or HTML content -> use 'get_content'.
- Need to check presence or visibility -> use 'check_state'.
This is a read-only operation and does not modify the element.
"""
sb = _get_sb()
if attribute:
return sb.get_element_attribute(selector, attribute)
return sb.get_element_attributes(selector)
@mcp.tool()
@handle_sb_errors
def check_state(
check: Literal["present", "visible", "count", "text_visible"] = "visible",
selector: str = "body",
text: str | None = None,
) -> Any:
"""Immediately inspect the current state of an element or page.
Use this tool when you need an observation of the current state and do
NOT want to wait for a condition. For waiting behavior, use wait_for.
For an expectation that should fail as an assertion, use assert_condition.
Args:
check:
- "present": Return whether at least one matching element exists.
- "visible": Return whether the matching element is visible.
- "count": Return the number of matching elements. This check may
wait up to 1 second for a match.
- "text_visible": Return whether the specified text is visible
within the selected element. Requires text.
selector: CSS selector or SeleniumBase selector for the element.
Defaults to "body".
text: Text to check when check="text_visible".
Returns:
A boolean for present/visible/text_visible, or an integer count for
count. Missing elements do not cause an exception for these checks.
Tool selection:
- Immediate yes/no/count observation -> use check_state.
- Wait until a state becomes true/false -> use wait_for.
- Verify an expected condition and fail when it is not met ->
use assert_condition.
Note:
Except for count's short lookup, this tool does not wait for elements
to appear. Use wait_for when page timing matters.
"""
sb = _get_sb()
if check == "present":
return sb.is_element_present(selector)
if check == "visible":
return sb.is_element_visible(selector)
if check == "count":
return len(sb.find_elements(selector, timeout=1))
if check == "text_visible":
if text is None:
return (
"Error: The 'text_visible' check requires value for 'text'."
)
return sb.is_text_visible(text, selector)
return (
f"Error: unknown check '{check}'. "
"Use 'present', 'visible', 'count', or 'text_visible'."
)
# ---------------------------------------------------------------------------
# Interacting with elements
# ---------------------------------------------------------------------------
@mcp.tool()
@handle_sb_errors
def click(
selector: str,
nth: int | None = None,
all_matches: bool = False,
only_if_visible: bool = False,
parent_selector: str | None = None,
timeout: int | float | None = 7,
scroll: bool = True,
) -> str:
"""Click one or more elements matching a selector.
This is the primary element-clicking tool. The selector may be a CSS
selector or SeleniumBase text-matching selector such as
'a:contains("Sign in")'.
Args:
selector: Target CSS selector or text-matching selector.
nth: Click only the Nth matching element, using 1-based indexing.
Takes priority over all_matches.
all_matches: Click every currently visible matching element, in order.
Ignored when nth is provided.
only_if_visible: Attempt the click only when the target is already
visible. Does not wait for the element to become visible.
parent_selector: Restrict the nested lookup to a parent element.
Useful for elements inside iframes or nested containers when
supported by SeleniumBase.
timeout: Seconds to wait for a basic click when no specialized mode
is selected. Defaults to 7 seconds.
scroll: Scroll the target into view before clicking.
Tool selection:
- Click one matching element -> basic click.
- Click a specific matching occurrence -> set nth.
- Click every visible match -> set all_matches=True.
- Click only when already visible -> set only_if_visible=True.
- Click an element nested inside another element -> set
parent_selector.
"""
sb = _get_sb()
if nth is not None:
if nth < 1:
return "Error: nth must be >= 1."
sb.click_nth_element(selector, nth, scroll=scroll)
return f"Clicked match #{nth} of {selector}"
if all_matches:
sb.click_visible_elements(selector)
return f"Clicked all visible matches of {selector}"
if only_if_visible:
sb.click_if_visible(selector)
return f"click (only_if_visible) ran for {selector}"
if parent_selector:
sb.nested_click(parent_selector, selector)
return f"Clicked {selector} inside {parent_selector}"
sb.click(selector, timeout=timeout, scroll=scroll)
return f"Clicked {selector}"
@mcp.tool()
@handle_sb_errors
def hover_with_action(
selector1: str,
selector2: str | None = None,
action: Literal[
"none",
"click",
"drag_and_drop",
] = "none",
) -> str:
"""Hover over an element, optionally click another element, or drag-&-drop.
Use this tool for hover interactions, hover-triggered menus, and
drag-and-drop operations.
Args:
selector1:
The primary element selector.
For action="none", this is the element to hover over.
For action="click", this is the element to hover over before
clicking selector2.
For action="drag_and_drop", this is the draggable source element.
selector2:
The secondary element selector.
Required for action="click", where it identifies the element
revealed or targeted after hovering selector1.
Required for action="drag_and_drop", where it identifies the
destination/drop target.
Not used for action="none".
action:
- "none": Hover over selector1 only.
- "click": Hover over selector1, then click selector2.
- "drag_and_drop": Drag selector1 and drop it onto selector2.
Returns:
A confirmation describing the performed operation.
Tool selection:
- Simple hover -> action="none".
- Hover over one element and then click another -> action="click".
- Drag one element onto another -> action="drag_and_drop".
Notes:
For action="click", selector1 is the hover target and selector2 is
the click target.
For action="drag_and_drop", selector1 is the source and selector2
is the destination.
"""
sb = _get_sb()
if action == "none":
sb.hover_element(selector1)
return f"Hovered {selector1}"
if action == "click":
if selector2 is None:
return "Error: action='click' requires selector2."
sb.hover_and_click(selector1, selector2)
return f"Hovered {selector1} and clicked {selector2}"
if action == "drag_and_drop":
if selector2 is None:
return "Error: action='drag_and_drop' requires selector2."
sb.drag_and_drop(selector1, selector2)
return f"Dragged {selector1} onto {selector2}"
return (
f"Error: unknown action '{action}'. "
"Use 'none', 'click', or 'drag_and_drop'."
)
@mcp.tool()
@handle_sb_errors
def type_text(
selector: str,
text: str = "",
mode: Literal[
"fill_input",
"append",
"fast_type",
"set_value",
"clear_only",
] = "fill_input",
timeout: int | float | None = 7,
) -> str:
"""Fill, append, fast-type, directly set, or clear a form control.
Use this tool for input elements, textareas, and contenteditable elements.
Args:
selector: CSS selector or SeleniumBase selector identifying the
input, textarea, or contenteditable element.
text: Text to enter or set. Not used when mode="clear_only".
mode:
- "fill_input": Clear the field and then type text normally.
- "append": Keep the existing value and add text as keystrokes.
- "fast_type": Clear the field and type text without pauses.
- "set_value": Set the value directly and immediately. This can
be useful for fast form filling but does not simulate normal
key events. It can also be used to handle input sliders,
e.g. 'input[type="range"]'.
- "clear_only": Empty the text field; text is ignored.
timeout: Maximum seconds to wait for the target element.
Tool selection:
- Normal text entry to replace existing text -> mode="fill_input".
- Add text without clearing the field first -> mode="append".
- Fast typing to replace existing text -> mode="fast_type".
- Directly set a value (e.g. input slider) -> mode="set_value".
- Empty a field of all text -> mode="clear_only".
"""
sb = _get_sb()
if mode == "fill_input":
sb.type(selector, text, timeout=timeout)
elif mode == "append":
sb.send_keys(selector, text, timeout=timeout)
elif mode == "fast_type":
sb.fast_type(selector, text, timeout=timeout)
elif mode == "set_value":
sb.set_value(selector, text, timeout=timeout)
elif mode == "clear_only":
sb.clear_input(selector, timeout=timeout)
else:
return (
f"Error: unknown mode '{mode}'. "
"Use 'fill_input', 'append', 'fast_type', "
"'set_value', or 'clear_only'."
)
return f"type_text(mode={mode!r}) done for {selector}"
@mcp.tool()
@handle_sb_errors
def select_option(
dropdown_selector: str,
value: str | int,
by: Literal["text", "value", "index"] = "text",
) -> str:
"""Select an option from an HTML <select> dropdown.
Args:
dropdown_selector: CSS selector identifying the <select> element.
value: The option's visible text, its HTML value attribute, or its
0-based index, depending on by.
by:
- "text": Match the option's visible text.
- "value": Match the option's HTML value attribute.
- "index": Match the option's 0-based position. Both integer and
numeric-string values are accepted.
Raises:
An error when the dropdown or requested option cannot be found.
This tool is for native <select> elements. For custom JavaScript
dropdowns made from div/button/list elements, use click or other
element-interaction tools instead.
"""
sb = _get_sb()
if by == "text":
sb.select_option_by_text(dropdown_selector, str(value))
elif by == "value":
sb.select_option_by_value(dropdown_selector, str(value))
elif by == "index":
sb.select_option_by_index(dropdown_selector, int(value))
else:
return f"Error: unknown by='{by}'. Use 'text', 'value', or 'index'."
return f"Selected ({by}={value!r}) in {dropdown_selector}"
@mcp.tool()
@handle_sb_errors
def focus_on(
selector: str,
action: Literal[
"scroll_to_element",
"focus",
"highlight",
] = "scroll_to_element",
) -> str:
"""Scroll to, focus, or highlight an element.
Use this tool when an element needs to be brought into view, focused for
keyboard interaction, or highlighted for debugging/demonstration.
This tool does NOT click, type into, select from, hover over, or otherwise
activate the element.
Args:
selector: CSS selector or SeleniumBase selector identifying the target.
action:
- "scroll_to_element": Scroll the page until the element is in
the current viewport. This is the default action.
- "focus": Move keyboard focus to the element.
- "highlight": Temporarily highlight the element for debugging or
demonstration. This can affect timing and may reduce stealth.
Tool selection:
- Bring an element into view -> use focus_on with the default action.
- Focus an element -> use focus_on(action="focus").
- Highlight element for debugging -> use focus_on(action="highlight").
- Click -> use click.
- Type text into a text field -> use type_text.
- Hover -> use hover_with_action.
"""
sb = _get_sb()
if action == "scroll_to_element":
sb.scroll_into_view(selector)
elif action == "focus":
sb.find_element(selector).focus()
elif action == "highlight":
sb.highlight(selector)
else:
return (
f"Error: unknown action '{action}'. "
"Use 'scroll_to_element', 'focus', or 'highlight'."
)
return f"{action} done for {selector}"
# ---------------------------------------------------------------------------
# Waiting & assertions
# ---------------------------------------------------------------------------
@mcp.tool()
@handle_sb_errors
def wait_for(
state: Literal[
"present",
"visible",
"not_visible",
"absent",
] = "visible",
selector: str | None = None,
text: str | None = None,
timeout: int | float | None = 7,
) -> str:
"""Wait until an element or text reaches a requested state.
Use this tool when the page is dynamic and an automation step must wait
for a condition before continuing.
Unlike check_state, this tool intentionally waits. Unlike assert_condition,
its purpose is synchronization rather than validating a test expectation.
Args:
state:
- "present": Wait until the matching element exists.
- "visible": Wait until the matching element is visible.
- "not_visible": Wait until the matching element is not visible.
- "absent": Wait until the matching element no longer exists.
Ignored when text is provided.
selector: CSS selector or SeleniumBase selector for the element.
Required unless text is supplied.
text: If supplied, wait for this text to appear within selector
(or within "body" when selector is omitted).
timeout: Maximum seconds to wait. Defaults to 7 seconds.
Returns:
A confirmation when the requested condition is reached.
Tool selection:
- Check current state immediately -> use check_state.
- Wait for a state/content transition -> use wait_for.
- Verify an expected value/condition -> use assert_condition.
"""
sb = _get_sb()
if selector is None and text is None:
return "Error: `selector` and `text` cannot both be None."