stealthmcp 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
stealth_browser.py ADDED
@@ -0,0 +1,4626 @@
1
+ #!/usr/bin/env -S uv run --script
2
+ # /// script
3
+ # requires-python = ">=3.11"
4
+ # dependencies = [
5
+ # "adblock==0.6.0",
6
+ # "mcp==1.30.0",
7
+ # "patchright==1.64.4",
8
+ # ]
9
+ # ///
10
+ """FastMCP server providing browser automation tools over CDP / stealth Chromium using patchright."""
11
+
12
+ __version__ = "0.1.0"
13
+
14
+ import argparse
15
+ import asyncio
16
+ import base64
17
+ import collections
18
+ import contextlib
19
+ import datetime
20
+ import fcntl
21
+ import functools
22
+ import hashlib
23
+ import io
24
+ import json
25
+ import logging
26
+ import os
27
+ import random
28
+ import re
29
+ import shutil
30
+ import signal
31
+ import struct
32
+ import subprocess
33
+ import sys
34
+ import tempfile
35
+ import time
36
+ import urllib.request
37
+ import zipfile
38
+ from collections import deque
39
+ from typing import Any, Optional, Union
40
+ from urllib.parse import urlparse
41
+ from adblock import Engine, FilterSet
42
+ from mcp.server.fastmcp import FastMCP
43
+ from patchright.async_api import Browser, BrowserContext, Page, async_playwright
44
+
45
+ try:
46
+ from pydantic import ConfigDict
47
+ import mcp.server.fastmcp.utilities.func_metadata as _fm
48
+
49
+ class _StrictArgModel(_fm.ArgModelBase):
50
+ model_config = ConfigDict(extra="forbid", arbitrary_types_allowed=True)
51
+
52
+ _fm.ArgModelBase = _StrictArgModel
53
+ except Exception:
54
+ pass
55
+
56
+ @contextlib.asynccontextmanager
57
+ async def _lifespan(_app):
58
+ loop = asyncio.get_running_loop()
59
+
60
+ def _on_task_exc(_loop, context):
61
+ try:
62
+ session._unhandled_task_exceptions["n"] += 1
63
+ except Exception:
64
+ pass
65
+ logging.error("UNHANDLED task exception: %r", context.get("exception"))
66
+
67
+ loop.set_exception_handler(_on_task_exc)
68
+ try:
69
+ session._unhandled_task_exceptions = {"n": 0}
70
+ except Exception:
71
+ pass
72
+ yield
73
+
74
+ STEALTH_BROWSER_CHEATSHEET = (
75
+ "Stay headless by default. Use wait_for_human() for interactive login/2FA/CAPTCHA (switches headed & polls); only call set_headless(headless=False) when asked.\n"
76
+ "Use this cheat-sheet instead of reading individual tool schemas; prefer snapshot(filter=...)/extract()/batch() over evaluate_js(). tab=-1 targets active tab (or index / stable 'tN').\n"
77
+ "Always call wait_for_human() (not set_headless churn) whenever a flow hits login/2FA/CAPTCHA/MFA.\n"
78
+ "- status() | new_tab(url='about:blank', block_media=None) | switch_tab(tab=0) | close_tab(tab=-1)\n"
79
+ " For tab URLs/titles: call status() — it lists every open tab's title and URL in one call; do NOT evaluate_js location.href/document.title.\n"
80
+ "- navigate(url, block_media=None, new_tab=False, tab=-1, timeout_ms=30000, wait_until='domcontentloaded')\n"
81
+ "- wait_for(selector='', text='', url_contains='', state='visible', timeout_ms=15000, tab=-1)\n"
82
+ "- wait_for_human(reason='...', url_contains='', url_not_contains='', selector='', timeout_s=180, poll_interval_s=1.5, notify=True, tab=-1)\n"
83
+ "- snapshot(selector='body', max_elements=80, tab=-1, include_shadow=True, include_iframes=True, include_hrefs=False, filter='', viewport_only=False, max_length=8000)\n"
84
+ "- get_content(selector='body', max_length=4000, interactive_only=False, clean=True, tab=-1, offset=0, filter='')\n"
85
+ "- extract(container_selector, fields={k:'text:.sel'|'@attr .sel'|'html:.sel'}, limit=20, include_shadow=True, include_iframes=True, tab=-1, max_length=8000)\n"
86
+ "- click(selector='', ref='', text='', force=False, tab=-1, timeout_ms=5000)\n"
87
+ "- type(selector='', text='', clear_first=True, press_enter=False, tab=-1, timeout_ms=5000, ref='')\n"
88
+ "- press_key(key, tab=-1) | scroll(direction='down', amount=600, tab=-1) | screenshot(save_path='', tab=-1, full_page=False, selector='', ref='', annotate=False)\n"
89
+ "- batch(actions=[{action:'click'|'fill'|'type'|'select'|'press'|'wait_for'|'sleep'|'evaluate', selector, ref, text, value, key, state, ms, force, expression, main_world, timeout_ms}], tab=-1)\n"
90
+ "- evaluate_js(expression='', tab=-1, timeout_ms=15000, script='', max_length=8000, main_world=False)\n"
91
+ "- fetch(url, method='GET', headers=None, body=None, response_type='auto', tab=-1, timeout_ms=15000, save_path='', max_length=8000)\n"
92
+ "- state(framework='auto', selector='', tab=-1, max_length=8000) | set_media(enable_media=True, tab=-1) | set_animations(enabled=False, persist=True)\n"
93
+ "- downloads(limit=20, include_dir=False) | network_requests(url_filter='', resource_type='', content_type='', status_min=0, limit=30, clear=False, tab=-1, max_length=8000) | console_logs(level='', limit=50, clear=False, tab=-1, max_length=8000)\n"
94
+ "- keep_alive(enable=True, tab=-1, min_seconds=45, max_seconds=90, ping_url=None, click_selector=None) | set_headless(headless=True, force=False) | restart_browser(headless=None, url=None) | close_browser(force_kill=True)"
95
+ )
96
+
97
+ mcp = FastMCP(
98
+ "stealth-browser",
99
+ instructions=STEALTH_BROWSER_CHEATSHEET,
100
+ lifespan=_lifespan,
101
+ )
102
+ mcp._mcp_server.version = __version__
103
+
104
+
105
+ @mcp.resource("instructions://cheatsheet")
106
+ def stealth_browser_cheatsheet() -> str:
107
+ """Curated cheat-sheet for stealth-browser tools (use instead of reading raw schema JSON)."""
108
+ return STEALTH_BROWSER_CHEATSHEET
109
+
110
+
111
+ # Persist cheat-sheet to a well-known path so clients that ignore MCP instructions can read it in one call.
112
+ _CHEATSHEET_FILE = os.path.expanduser("~/.cache/stealth-browser/cheatsheet.txt")
113
+ try:
114
+ os.makedirs(os.path.dirname(_CHEATSHEET_FILE), exist_ok=True)
115
+ with open(_CHEATSHEET_FILE, "w", encoding="utf-8") as _f:
116
+ _f.write(STEALTH_BROWSER_CHEATSHEET)
117
+ except Exception:
118
+ pass
119
+
120
+ CDP_PORT = int(os.environ.get("STEALTH_BROWSER_CDP_PORT", os.environ.get("CDP_PORT", "9222")))
121
+ CDP_URL = f"http://127.0.0.1:{CDP_PORT}"
122
+ PROFILE_DIR = os.path.expanduser(os.environ.get("STEALTH_BROWSER_PROFILE_DIR", "~/.agent-chromium-profile"))
123
+ DOWNLOADS_DIR = os.path.expanduser(os.environ.get("STEALTH_BROWSER_DOWNLOADS_DIR", "~/Downloads"))
124
+ IDLE_TIMEOUT_SECONDS = int(os.environ.get("STEALTH_BROWSER_IDLE_TIMEOUT", "300"))
125
+ CDP_CONNECT_TIMEOUT_S = 5.0
126
+ CDP_OP_TIMEOUT_S = 5.0
127
+ GET_CONTEXT_TIMEOUT_S = 30.0
128
+ PAGE_TITLE_TIMEOUT_S = 5.0
129
+ PAGE_CLOSE_TIMEOUT_S = 5.0
130
+ BROWSER_CLOSE_TIMEOUT_S = 5.0
131
+ PLAYWRIGHT_START_TIMEOUT_S = 15.0
132
+ PLAYWRIGHT_STOP_TIMEOUT_S = 5.0
133
+ NEW_PAGE_TIMEOUT_S = 10.0
134
+ RESTART_BROWSER_TIMEOUT_S = 30.0
135
+ GOTO_OUTER_BUFFER_S = 5.0
136
+ DIALOG_ACTION_TIMEOUT_S = 3.0
137
+ MAX_DIALOG_HISTORY = 50
138
+
139
+ TOOL_TOTAL_TIMEOUT_S = 60.0
140
+
141
+
142
+ def _with_tool_deadline(fn):
143
+ @functools.wraps(fn)
144
+ async def wrapper(*args, **kwargs):
145
+ try:
146
+ return await asyncio.wait_for(fn(*args, **kwargs), timeout=TOOL_TOTAL_TIMEOUT_S)
147
+ except asyncio.TimeoutError:
148
+ try:
149
+ probe_ok = await asyncio.wait_for(asyncio.to_thread(session._probe_cdp_ready), timeout=2.0)
150
+ except Exception:
151
+ probe_ok = False
152
+ if not probe_ok:
153
+ try:
154
+ await asyncio.wait_for(session.close(), timeout=5.0)
155
+ except Exception:
156
+ pass
157
+ try:
158
+ await asyncio.wait_for(asyncio.to_thread(_force_kill_browser_processes), timeout=10.0)
159
+ except Exception:
160
+ pass
161
+ return (
162
+ f"Error {fn.__name__}: exceeded {int(TOOL_TOTAL_TIMEOUT_S)}s total; "
163
+ f"CDP transport wedged — browser force-restarted, retry the call."
164
+ )
165
+ return (
166
+ f"Error {fn.__name__}: exceeded {int(TOOL_TOTAL_TIMEOUT_S)}s total; "
167
+ f"browser still reachable — safe to retry; call restart_browser only if calls keep stalling."
168
+ )
169
+ return wrapper
170
+ HEADLESS = os.environ.get("STEALTH_BROWSER_HEADLESS", "true").lower() in ("1", "true", "yes")
171
+ CHROMIUM_APP_BIN = "/Applications/Chromium.app/Contents/MacOS/Chromium"
172
+ DEFAULT_BROWSER_EXECUTABLE = CHROMIUM_APP_BIN if os.path.exists(CHROMIUM_APP_BIN) else None
173
+ BROWSER_EXECUTABLE = os.environ.get("STEALTH_BROWSER_EXECUTABLE", DEFAULT_BROWSER_EXECUTABLE)
174
+ APPLE_PASSWORDS_EXT_ID = "pejdijmoenmkgeppbflobdenhhabjlaj"
175
+ APPLE_PASSWORDS_EXT_DIR = os.path.expanduser(
176
+ os.environ.get("STEALTH_BROWSER_EXTENSIONS_DIR", "~/.local/share/stealth-browser/extensions")
177
+ )
178
+ APPLE_PASSWORDS_CRX_URL = (
179
+ "https://clients2.google.com/service/update2/crx?response=redirect"
180
+ "&prodversion={prodversion}&acceptformat=crx2,crx3&x=id%3D{ext_id}%26uc"
181
+ )
182
+ APPLE_PASSWORDS_CRX_PRODVERSION = os.environ.get("STEALTH_BROWSER_CRX_PRODVERSION", "140.0.0.0")
183
+ _ID_ALPHABET = "abcdefghijklmnop"
184
+ _apple_passwords_ext_cache: Optional[str] = None
185
+
186
+
187
+ def _extension_id_from_key(key_b64: str) -> str:
188
+ """Derive the Chromium extension ID from a manifest `key` (SHA-256 of DER key, mapped 0-f -> a-p)."""
189
+ digest = hashlib.sha256(base64.b64decode(key_b64)).hexdigest()[:32]
190
+ return "".join(_ID_ALPHABET[int(chunk, 16)] for chunk in digest)
191
+
192
+
193
+ def _read_extension_id(ext_dir: str) -> Optional[str]:
194
+ """Return the extension ID declared by an unpacked extension, or None if unreadable."""
195
+ try:
196
+ with open(os.path.join(ext_dir, "manifest.json"), "r", encoding="utf-8") as f:
197
+ key = json.load(f).get("key")
198
+ return _extension_id_from_key(key) if key else None
199
+ except Exception:
200
+ return None
201
+
202
+
203
+ def _cached_apple_passwords_ext() -> Optional[str]:
204
+ """Return an already-extracted, identity-verified copy from the tool-owned extension cache."""
205
+ ext_root = os.path.join(APPLE_PASSWORDS_EXT_DIR, "apple-passwords")
206
+ if not os.path.isdir(ext_root):
207
+ return None
208
+ for entry in sorted(os.listdir(ext_root), reverse=True):
209
+ candidate = os.path.join(ext_root, entry)
210
+ if os.path.isfile(os.path.join(candidate, "manifest.json")) and _read_extension_id(candidate) == APPLE_PASSWORDS_EXT_ID:
211
+ return candidate
212
+ return None
213
+
214
+
215
+ def _read_varint(data: bytes, offset: int) -> tuple:
216
+ result = 0
217
+ shift = 0
218
+ while True:
219
+ byte = data[offset]
220
+ offset += 1
221
+ result |= (byte & 0x7F) << shift
222
+ if not byte & 0x80:
223
+ return result, offset
224
+ shift += 7
225
+
226
+
227
+ def _iter_protobuf_fields(data: bytes):
228
+ """Yield (field_number, value) for a minimal protobuf message; only wire types 0/1/2/5."""
229
+ offset = 0
230
+ while offset < len(data):
231
+ tag, offset = _read_varint(data, offset)
232
+ field, wire = tag >> 3, tag & 7
233
+ if wire == 0:
234
+ value, offset = _read_varint(data, offset)
235
+ elif wire == 2:
236
+ length, offset = _read_varint(data, offset)
237
+ value, offset = data[offset:offset + length], offset + length
238
+ elif wire == 5:
239
+ value, offset = data[offset:offset + 4], offset + 4
240
+ elif wire == 1:
241
+ value, offset = data[offset:offset + 8], offset + 8
242
+ else:
243
+ raise ValueError(f"unsupported protobuf wire type {wire}")
244
+ if not isinstance(value, bytes):
245
+ continue
246
+ yield field, value
247
+
248
+
249
+ def _crx_id_from_pubkey(pubkey: bytes) -> str:
250
+ digest = hashlib.sha256(pubkey).digest()[:16]
251
+ return "".join(_ID_ALPHABET[nibble] for byte in digest for nibble in (byte >> 4, byte & 0xF))
252
+
253
+
254
+ def _rsa_sha256_verify(pubkey_der: bytes, message: bytes, signature: bytes) -> bool:
255
+ """Verify an RSASSA-PKCS1-v1_5 SHA-256 signature via the openssl CLI (no extra Python deps)."""
256
+ with tempfile.TemporaryDirectory() as tmp:
257
+ pub_path = os.path.join(tmp, "pub.der")
258
+ sig_path = os.path.join(tmp, "sig.bin")
259
+ msg_path = os.path.join(tmp, "msg.bin")
260
+ for path, blob in ((pub_path, pubkey_der), (sig_path, signature), (msg_path, message)):
261
+ with open(path, "wb") as f:
262
+ f.write(blob)
263
+ proc = subprocess.run(
264
+ ["openssl", "dgst", "-sha256", "-keyform", "DER", "-verify", pub_path, "-signature", sig_path, msg_path],
265
+ capture_output=True,
266
+ text=True,
267
+ )
268
+ return proc.returncode == 0 and "Verified OK" in proc.stdout
269
+
270
+
271
+ def _verify_crx(data: bytes, expected_id: str) -> Optional[bytes]:
272
+ """Parse a CRX3 container, verify its publisher-key signature, and return the zip payload.
273
+
274
+ Per Chromium's crx3.proto, each sha256_with_rsa proof (field 2) signs
275
+ "CRX3 SignedData\\0" + LE32(signed_header_data size) + signed_header_data (field 10000)
276
+ + the zip archive. The publisher proof's public key must derive the expected ID.
277
+ """
278
+ if data[:4] != b"Cr24":
279
+ raise ValueError("not a CRX container")
280
+ version = struct.unpack("<I", data[4:8])[0]
281
+ if version != 3:
282
+ raise ValueError(f"unsupported CRX version {version} (expected 3)")
283
+ header_size = struct.unpack("<I", data[8:12])[0]
284
+ header = data[12:12 + header_size]
285
+ payload = data[12 + header_size:]
286
+
287
+ signed_header_data = None
288
+ proofs = []
289
+ for field, value in _iter_protobuf_fields(header):
290
+ if field == 2:
291
+ proofs.append(value)
292
+ elif field == 10000:
293
+ signed_header_data = value
294
+ if signed_header_data is None:
295
+ raise ValueError("CRX header is missing signed_header_data")
296
+
297
+ message = (
298
+ b"CRX3 SignedData\x00"
299
+ + struct.pack("<I", len(signed_header_data))
300
+ + signed_header_data
301
+ + payload
302
+ )
303
+ for proof in proofs:
304
+ pubkey = sig = None
305
+ for sub_field, value in _iter_protobuf_fields(proof):
306
+ if sub_field == 1:
307
+ pubkey = value
308
+ elif sub_field == 2:
309
+ sig = value
310
+ if not pubkey or not sig:
311
+ return None
312
+ if _crx_id_from_pubkey(pubkey) != expected_id:
313
+ continue # not the publisher key we pin; keep looking
314
+ if not _rsa_sha256_verify(pubkey, message, sig):
315
+ return None
316
+ return payload
317
+ raise ValueError("no publisher signature for the expected extension ID in CRX header")
318
+
319
+
320
+ def _download_apple_passwords_crx() -> Optional[bytes]:
321
+ url = APPLE_PASSWORDS_CRX_URL.format(
322
+ prodversion=APPLE_PASSWORDS_CRX_PRODVERSION, ext_id=APPLE_PASSWORDS_EXT_ID
323
+ )
324
+ try:
325
+ req = urllib.request.Request(url, headers={"User-Agent": f"Chromium/{APPLE_PASSWORDS_CRX_PRODVERSION}"})
326
+ with urllib.request.urlopen(req, timeout=15) as resp:
327
+ return resp.read()
328
+ except Exception as exc:
329
+ print(f"stealth-browser: Apple Passwords CRX download failed: {exc}", file=sys.stderr)
330
+ return None
331
+
332
+
333
+ def _install_apple_passwords_ext() -> Optional[str]:
334
+ """Fetch, identity-check, and unpack the Apple Passwords extension into the tool-owned cache dir."""
335
+ global _apple_passwords_ext_cache
336
+ cached = _cached_apple_passwords_ext()
337
+ if cached:
338
+ _apple_passwords_ext_cache = cached
339
+ return cached
340
+
341
+ data = _download_apple_passwords_crx()
342
+ if not data:
343
+ return None
344
+ try:
345
+ payload = _verify_crx(data, APPLE_PASSWORDS_EXT_ID)
346
+ except Exception as exc:
347
+ print(f"stealth-browser: Apple Passwords CRX rejected: {exc}", file=sys.stderr)
348
+ return None
349
+
350
+ ext_root = os.path.join(APPLE_PASSWORDS_EXT_DIR, "apple-passwords")
351
+ os.makedirs(ext_root, exist_ok=True)
352
+ staging = tempfile.mkdtemp(prefix=".staging-", dir=ext_root)
353
+ try:
354
+ with zipfile.ZipFile(io.BytesIO(payload)) as archive:
355
+ archive.extractall(staging)
356
+ if _read_extension_id(staging) != APPLE_PASSWORDS_EXT_ID:
357
+ print("stealth-browser: Apple Passwords CRX failed identity check; ignoring", file=sys.stderr)
358
+ return None
359
+ with open(os.path.join(staging, "manifest.json"), "r", encoding="utf-8") as f:
360
+ version = json.load(f).get("version") or "unknown"
361
+ target = os.path.join(ext_root, version)
362
+ if os.path.exists(target):
363
+ shutil.rmtree(target, ignore_errors=True)
364
+ os.replace(staging, target)
365
+ _apple_passwords_ext_cache = target
366
+ return target
367
+ except Exception as exc:
368
+ print(f"stealth-browser: Apple Passwords install failed: {exc}", file=sys.stderr)
369
+ return None
370
+ finally:
371
+ if os.path.isdir(staging):
372
+ shutil.rmtree(staging, ignore_errors=True)
373
+
374
+ MEDIA_RESOURCE_TYPES = {"image", "media", "font"}
375
+ MEDIA_FILE_EXTENSIONS = (
376
+ ".png", ".jpg", ".jpeg", ".webp", ".gif", ".svg",
377
+ ".mp4", ".webm", ".ogg", ".woff", ".woff2", ".ttf", ".otf"
378
+ )
379
+
380
+ CACHE_DIR = os.path.expanduser("~/.cache/stealth-browser")
381
+ CACHE_FILE = os.path.join(CACHE_DIR, "easyprivacy.txt")
382
+ CACHE_BIN_FILE = os.path.join(CACHE_DIR, "easyprivacy.bin")
383
+ STATE_FILE = os.path.join(CACHE_DIR, f"state-{CDP_PORT}.json")
384
+ EASYPRIVACY_URL = "https://easylist.to/easylist/easyprivacy.txt"
385
+
386
+
387
+ def _load_persisted_headless() -> bool:
388
+ """Return persisted headless preference if STEALTH_BROWSER_HEADLESS is not explicitly set."""
389
+ if "STEALTH_BROWSER_HEADLESS" in os.environ:
390
+ return HEADLESS
391
+ try:
392
+ if os.path.exists(STATE_FILE):
393
+ with open(STATE_FILE, "r", encoding="utf-8") as f:
394
+ data = json.load(f)
395
+ if isinstance(data.get("headless"), bool):
396
+ return data["headless"]
397
+ except Exception:
398
+ pass
399
+ return HEADLESS
400
+
401
+
402
+ def _save_persisted_headless(headless: Optional[bool]) -> None:
403
+ """Persist headless mode for crash recovery, or remove state file when None."""
404
+ try:
405
+ if headless is None:
406
+ if os.path.exists(STATE_FILE):
407
+ os.unlink(STATE_FILE)
408
+ return
409
+ os.makedirs(CACHE_DIR, exist_ok=True)
410
+ with open(STATE_FILE, "w", encoding="utf-8") as f:
411
+ json.dump({"headless": bool(headless)}, f)
412
+ except Exception:
413
+ pass
414
+
415
+
416
+ ANIMATIONS_STATE_FILE = os.path.join(CACHE_DIR, f"animations-{CDP_PORT}.json")
417
+ _ANIMATIONS_STYLE_ATTR = "data-anim-pref"
418
+ _ANIMATIONS_KILL_CSS = (
419
+ "*, *::before, *::after { animation-duration: 0s !important; animation-delay: 0s !important; "
420
+ "transition-duration: 0.001s !important; transition-delay: 0s !important; scroll-behavior: auto !important; }"
421
+ )
422
+ _ANIMATIONS_INJECT_JS = """(css) => {
423
+ let style = document.querySelector('style[' + %(attr)s + ']');
424
+ if (!style) {
425
+ style = document.createElement('style');
426
+ style.setAttribute(%(attr)s, '1');
427
+ (document.head || document.documentElement).appendChild(style);
428
+ }
429
+ style.textContent = css;
430
+ }""" % {"attr": json.dumps(_ANIMATIONS_STYLE_ATTR)}
431
+ _ANIMATIONS_INIT_SCRIPT = """(() => {
432
+ const css = %(css)s;
433
+ const inject = () => {
434
+ if (!document.documentElement) return;
435
+ const style = document.createElement('style');
436
+ style.setAttribute(%(attr)s, 'init');
437
+ style.textContent = css;
438
+ (document.head || document.documentElement).appendChild(style);
439
+ };
440
+ if (document.documentElement) inject();
441
+ else document.addEventListener('DOMContentLoaded', inject, { once: true });
442
+ })();""" % {"css": json.dumps(_ANIMATIONS_KILL_CSS), "attr": json.dumps(_ANIMATIONS_STYLE_ATTR)}
443
+
444
+
445
+ def _load_persisted_animations() -> Optional[bool]:
446
+ """Return persisted animation-freeze preference, or None when never set."""
447
+ try:
448
+ if os.path.exists(ANIMATIONS_STATE_FILE):
449
+ with open(ANIMATIONS_STATE_FILE, "r", encoding="utf-8") as f:
450
+ data = json.load(f)
451
+ if isinstance(data.get("animations"), bool):
452
+ return data["animations"]
453
+ except Exception:
454
+ pass
455
+ return None
456
+
457
+
458
+ def _save_persisted_animations(enabled: Optional[bool]) -> None:
459
+ """Persist animation-freeze state for crash recovery, or remove state file when None."""
460
+ try:
461
+ if enabled is None:
462
+ if os.path.exists(ANIMATIONS_STATE_FILE):
463
+ os.unlink(ANIMATIONS_STATE_FILE)
464
+ return
465
+ os.makedirs(CACHE_DIR, exist_ok=True)
466
+ with open(ANIMATIONS_STATE_FILE, "w", encoding="utf-8") as f:
467
+ json.dump({"animations": bool(enabled)}, f)
468
+ except Exception:
469
+ pass
470
+
471
+
472
+ _adblock_engine: Optional[Engine] = None
473
+ _adblock_initialized: bool = False
474
+ _adblock_load_task: Optional[asyncio.Task] = None
475
+
476
+
477
+ def _acquire_file_lock(lock_file, timeout_s: float = 15.0) -> None:
478
+ deadline = time.monotonic() + timeout_s
479
+ while True:
480
+ try:
481
+ fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
482
+ return
483
+ except BlockingIOError:
484
+ if time.monotonic() >= deadline:
485
+ raise TimeoutError(f"Timed out acquiring file lock after {timeout_s}s")
486
+ time.sleep(0.05)
487
+
488
+
489
+ def _resolve_apple_passwords_ext_locked() -> Optional[str]:
490
+ os.makedirs(CACHE_DIR, exist_ok=True)
491
+ with open(os.path.join(CACHE_DIR, "apple-passwords-ext.lock"), "w", encoding="utf-8") as lock_file:
492
+ _acquire_file_lock(lock_file, timeout_s=15.0)
493
+ try:
494
+ return _install_apple_passwords_ext()
495
+ finally:
496
+ fcntl.flock(lock_file, fcntl.LOCK_UN)
497
+
498
+
499
+ def _load_or_build_engine() -> Optional[Engine]:
500
+ """Load cached binary engine or compile EasyPrivacy into Brave's adblock-rust engine."""
501
+ os.makedirs(CACHE_DIR, exist_ok=True)
502
+
503
+ if os.path.exists(CACHE_BIN_FILE):
504
+ try:
505
+ if (time.time() - os.path.getmtime(CACHE_BIN_FILE)) < (7 * 86400):
506
+ engine = Engine(filter_set=FilterSet())
507
+ engine.deserialize_from_file(CACHE_BIN_FILE)
508
+ return engine
509
+ except Exception:
510
+ pass
511
+
512
+ content = None
513
+ if os.path.exists(CACHE_FILE):
514
+ try:
515
+ if (time.time() - os.path.getmtime(CACHE_FILE)) < (7 * 86400):
516
+ with open(CACHE_FILE, "r", encoding="utf-8") as f:
517
+ content = f.read()
518
+ except Exception:
519
+ content = None
520
+
521
+ if not content:
522
+ try:
523
+ req = urllib.request.Request(EASYPRIVACY_URL, headers={"User-Agent": "Mozilla/5.0"})
524
+ with urllib.request.urlopen(req, timeout=5) as resp:
525
+ content = resp.read().decode("utf-8", errors="ignore")
526
+ with open(CACHE_FILE, "w", encoding="utf-8") as f:
527
+ f.write(content)
528
+ except Exception:
529
+ if os.path.exists(CACHE_FILE):
530
+ try:
531
+ with open(CACHE_FILE, "r", encoding="utf-8") as f:
532
+ content = f.read()
533
+ except Exception:
534
+ content = None
535
+
536
+ if content:
537
+ try:
538
+ filters = FilterSet()
539
+ filters.add_filter_list(content)
540
+ engine = Engine(filter_set=filters)
541
+ try:
542
+ engine.serialize_to_file(CACHE_BIN_FILE)
543
+ except Exception:
544
+ pass
545
+ return engine
546
+ except Exception:
547
+ pass
548
+ return None
549
+
550
+
551
+ async def _warm_adblock_engine() -> Optional[Engine]:
552
+ global _adblock_engine, _adblock_initialized, _adblock_load_task
553
+ if _adblock_initialized:
554
+ return _adblock_engine
555
+ try:
556
+ _adblock_engine = await asyncio.to_thread(_load_or_build_engine)
557
+ except asyncio.CancelledError:
558
+ raise
559
+ except Exception:
560
+ _adblock_engine = None
561
+ _adblock_initialized = True
562
+ else:
563
+ _adblock_initialized = True
564
+ finally:
565
+ _adblock_load_task = None
566
+ return _adblock_engine
567
+
568
+
569
+ def _schedule_adblock_warmup() -> Optional[asyncio.Task]:
570
+ global _adblock_load_task
571
+ if _adblock_initialized:
572
+ return None
573
+ if _adblock_load_task is not None and not _adblock_load_task.done():
574
+ return _adblock_load_task
575
+ try:
576
+ loop = asyncio.get_running_loop()
577
+ except RuntimeError:
578
+ return None
579
+ _adblock_load_task = loop.create_task(_warm_adblock_engine())
580
+ return _adblock_load_task
581
+
582
+
583
+ def get_adblock_engine() -> Optional[Engine]:
584
+ global _adblock_engine, _adblock_initialized
585
+ if _adblock_initialized:
586
+ return _adblock_engine
587
+ if _schedule_adblock_warmup() is not None:
588
+ return _adblock_engine
589
+ _adblock_initialized = True
590
+ _adblock_engine = _load_or_build_engine()
591
+ return _adblock_engine
592
+
593
+
594
+ async def _network_route_handler(route, request):
595
+ """Intercepts network requests: evaluates trackers against EasyPrivacy and blocks media when enabled."""
596
+ handled = False
597
+ try:
598
+ frame = None
599
+ try:
600
+ frame = request.frame
601
+ except Exception:
602
+ frame = None
603
+
604
+ if frame is None:
605
+ handled = True
606
+ await route.continue_()
607
+ return
608
+
609
+ url = request.url
610
+ try:
611
+ frame_url = frame.url or ""
612
+ except Exception:
613
+ frame_url = ""
614
+ res_type = request.resource_type or "other"
615
+
616
+ if res_type == "document":
617
+ is_main_frame = True
618
+ try:
619
+ is_main_frame = frame.parent_frame is None
620
+ except Exception:
621
+ is_main_frame = True
622
+ uncommitted = (not frame_url.strip()) or frame_url.strip().lower() == "about:blank"
623
+ if is_main_frame or uncommitted:
624
+ handled = True
625
+ await route.continue_()
626
+ return
627
+
628
+ engine = get_adblock_engine()
629
+ if engine is not None:
630
+ try:
631
+ if engine.check_network_urls(url, frame_url, res_type).matched:
632
+ handled = True
633
+ await route.abort()
634
+ return
635
+ except Exception:
636
+ pass
637
+
638
+ try:
639
+ page = frame.page
640
+ except Exception:
641
+ page = None
642
+ if page and getattr(page, "_media_blocked", False):
643
+ if res_type in MEDIA_RESOURCE_TYPES:
644
+ handled = True
645
+ await route.abort()
646
+ return
647
+ url_clean = url.split("?")[0].lower()
648
+ if url_clean.endswith(MEDIA_FILE_EXTENSIONS):
649
+ handled = True
650
+ await route.abort()
651
+ return
652
+
653
+ handled = True
654
+ await route.continue_()
655
+ except Exception:
656
+ if not handled:
657
+ try:
658
+ await route.continue_()
659
+ except Exception:
660
+ pass
661
+
662
+
663
+ class BrowserSessionManager:
664
+ """Manages dedicated stealth Chromium browser or CDP connection for AI agents."""
665
+
666
+ def __init__(self, cdp_url: str):
667
+ self.cdp_url = cdp_url
668
+ self.headless: bool = _load_persisted_headless()
669
+ self.animations: Optional[bool] = _load_persisted_animations()
670
+ self._playwright = None
671
+ self._browser: Optional[Browser] = None
672
+ self._context: Optional[BrowserContext] = None
673
+ self._active_page: Optional[Page] = None
674
+ self._idle_task: Optional[asyncio.Task] = None
675
+ self._page_to_id: dict[Page, str] = {}
676
+ self._id_to_page: dict[str, Page] = {}
677
+ self._next_tab_seq: int = 1
678
+
679
+ def _touch_activity(self):
680
+ if self._idle_task is not None and not self._idle_task.done():
681
+ self._idle_task.cancel()
682
+ try:
683
+ loop = asyncio.get_running_loop()
684
+ self._idle_task = loop.create_task(self._idle_watchdog())
685
+ except RuntimeError:
686
+ pass
687
+
688
+ async def _idle_watchdog(self):
689
+ try:
690
+ await asyncio.sleep(IDLE_TIMEOUT_SECONDS)
691
+ # Do not auto-stop if keep-alive workers are active
692
+ if "keep_alive_mgr" in globals() and keep_alive_mgr.has_active():
693
+ self._touch_activity()
694
+ return
695
+ # Auto-stop the driver on idle if attached via CDP or if no persistent context is open
696
+ if self._browser is not None or self._context is None:
697
+ await self.close()
698
+ except asyncio.CancelledError:
699
+ pass
700
+
701
+ async def close(self):
702
+ """Cleanly stop the patchright node driver and release browser handles."""
703
+ if "keep_alive_mgr" in globals():
704
+ try:
705
+ await asyncio.wait_for(keep_alive_mgr.stop_all(), timeout=CDP_OP_TIMEOUT_S)
706
+ except Exception:
707
+ pass
708
+ if (
709
+ self._idle_task is not None
710
+ and not self._idle_task.done()
711
+ and asyncio.current_task() is not self._idle_task
712
+ ):
713
+ self._idle_task.cancel()
714
+ self._idle_task = None
715
+ self._context = None
716
+ self._browser = None
717
+ self._active_page = None
718
+ self._page_to_id.clear()
719
+ self._id_to_page.clear()
720
+ if self._playwright is not None:
721
+ try:
722
+ await asyncio.wait_for(self._playwright.stop(), timeout=PLAYWRIGHT_STOP_TIMEOUT_S)
723
+ except Exception:
724
+ pass
725
+ finally:
726
+ self.close_sync()
727
+
728
+ def close_sync(self):
729
+ """Synchronously terminate the patchright node driver subprocess if still alive."""
730
+ if self._playwright is None:
731
+ return
732
+ try:
733
+ proc = getattr(self._playwright._impl_obj._connection._transport, "_proc", None)
734
+ if proc is not None and getattr(proc, "pid", None):
735
+ os.kill(proc.pid, signal.SIGTERM)
736
+ except Exception:
737
+ pass
738
+ self._playwright = None
739
+
740
+ def _detect_cdp_headless(self) -> Optional[bool]:
741
+ """Detect whether the Chromium instance listening on CDP_PORT is running headless."""
742
+ version_detected: Optional[bool] = None
743
+ try:
744
+ with urllib.request.urlopen(f"{self.cdp_url}/json/version", timeout=0.5) as resp:
745
+ data = json.loads(resp.read().decode("utf-8", errors="ignore"))
746
+ ua = data.get("User-Agent", "")
747
+ browser_str = data.get("Browser", "")
748
+ if ua or browser_str:
749
+ version_detected = "HeadlessChrome" in ua or "HeadlessChrome" in browser_str
750
+ if version_detected:
751
+ return True
752
+ except Exception:
753
+ pass
754
+ try:
755
+ pid_res = subprocess.run(
756
+ ["lsof", "-nP", f"-iTCP:{CDP_PORT}", "-sTCP:LISTEN", "-t"],
757
+ capture_output=True,
758
+ text=True,
759
+ timeout=1.5,
760
+ )
761
+ pids = [p.strip() for p in pid_res.stdout.splitlines() if p.strip()]
762
+ if pids:
763
+ ps_res = subprocess.run(
764
+ ["ps", "-ww", "-o", "args=", "-p", pids[0]],
765
+ capture_output=True,
766
+ text=True,
767
+ timeout=1.5,
768
+ )
769
+ args = ps_res.stdout.strip()
770
+ if args:
771
+ return "--headless" in args
772
+ except Exception:
773
+ pass
774
+ return version_detected
775
+
776
+ async def _connect_cdp(self) -> Optional[BrowserContext]:
777
+ """Attach to an already-running Chromium CDP endpoint and sync headless state."""
778
+ try:
779
+ self._browser = await asyncio.wait_for(
780
+ self._playwright.chromium.connect_over_cdp(
781
+ self.cdp_url,
782
+ timeout=1500,
783
+ ),
784
+ timeout=CDP_CONNECT_TIMEOUT_S,
785
+ )
786
+ try:
787
+ detected_headless = await asyncio.wait_for(
788
+ asyncio.to_thread(self._detect_cdp_headless),
789
+ timeout=CDP_OP_TIMEOUT_S,
790
+ )
791
+ except Exception:
792
+ detected_headless = None
793
+ if detected_headless is not None:
794
+ self.headless = detected_headless
795
+ if self._browser.contexts:
796
+ self._context = self._browser.contexts[0]
797
+ await self._ensure_interceptor(self._context)
798
+ return self._context
799
+ except Exception:
800
+ self._browser = None
801
+ return None
802
+
803
+ def _probe_cdp_ready(self) -> bool:
804
+ try:
805
+ with urllib.request.urlopen(f"{self.cdp_url}/json/version", timeout=0.3) as resp:
806
+ return resp.status == 200
807
+ except Exception:
808
+ return False
809
+
810
+ async def _launch_detached_chromium(self) -> None:
811
+ """Launch standalone Chromium detached from the MCP server process so it survives restarts."""
812
+ os.makedirs(PROFILE_DIR, exist_ok=True)
813
+
814
+ nm_hosts_dir = os.path.join(PROFILE_DIR, "NativeMessagingHosts")
815
+ os.makedirs(nm_hosts_dir, exist_ok=True)
816
+ nm_manifest = os.path.join(nm_hosts_dir, "com.apple.passwordmanager.json")
817
+ system_manifest = "/Library/Google/Chrome/NativeMessagingHosts/com.apple.passwordmanager.json"
818
+ if not os.path.exists(nm_manifest) and os.path.exists(system_manifest):
819
+ shutil.copy2(system_manifest, nm_manifest)
820
+
821
+ executable = BROWSER_EXECUTABLE or self._playwright.chromium.executable_path
822
+ browser_args = [
823
+ f"--remote-debugging-port={CDP_PORT}",
824
+ f"--user-data-dir={PROFILE_DIR}",
825
+ "--test-type",
826
+ "--no-first-run",
827
+ "--no-default-browser-check",
828
+ "--disable-search-engine-choice-screen",
829
+ "--disable-sync",
830
+ "--disable-background-networking",
831
+ "--disable-background-timer-throttling",
832
+ "--disable-backgrounding-occluded-windows",
833
+ "--disable-renderer-backgrounding",
834
+ "--disable-prompt-on-repost",
835
+ "--use-mock-keychain",
836
+ "--disable-blink-features=AutomationControlled",
837
+ ]
838
+ if self.headless:
839
+ browser_args.append("--headless=new")
840
+ apple_passwords_ext = _apple_passwords_ext_cache
841
+ if not apple_passwords_ext:
842
+ try:
843
+ apple_passwords_ext = await asyncio.wait_for(
844
+ asyncio.to_thread(_resolve_apple_passwords_ext_locked),
845
+ timeout=20.0,
846
+ )
847
+ except Exception as exc:
848
+ print(f"stealth-browser: Apple Passwords setup skipped: {exc}", file=sys.stderr)
849
+ apple_passwords_ext = None
850
+ if apple_passwords_ext:
851
+ browser_args.extend([
852
+ f"--disable-extensions-except={apple_passwords_ext}",
853
+ f"--load-extension={apple_passwords_ext}",
854
+ ])
855
+
856
+ proc = subprocess.Popen(
857
+ [executable, *browser_args],
858
+ stdin=subprocess.DEVNULL,
859
+ stdout=subprocess.DEVNULL,
860
+ stderr=subprocess.DEVNULL,
861
+ start_new_session=True,
862
+ )
863
+
864
+ deadline = time.monotonic() + 5.0
865
+ while time.monotonic() < deadline:
866
+ if proc.poll() is not None:
867
+ raise RuntimeError(f"Detached Chromium exited early with code {proc.returncode}")
868
+ if await asyncio.to_thread(self._probe_cdp_ready):
869
+ return
870
+ await asyncio.sleep(0.05)
871
+ raise TimeoutError(f"Timed out waiting for Chromium CDP endpoint at {self.cdp_url}")
872
+
873
+ async def get_context(self) -> BrowserContext:
874
+ self._touch_activity()
875
+ if self._playwright is None:
876
+ self._playwright = await asyncio.wait_for(
877
+ async_playwright().start(),
878
+ timeout=PLAYWRIGHT_START_TIMEOUT_S,
879
+ )
880
+
881
+ if self._context is not None:
882
+ try:
883
+ if self._browser is not None and not self._browser.is_connected():
884
+ self._browser = None
885
+ self._context = None
886
+ elif hasattr(self._context, "is_closed") and self._context.is_closed():
887
+ self._context = None
888
+ else:
889
+ _ = self._context.pages
890
+ return self._context
891
+ except Exception:
892
+ self._context = None
893
+ self._browser = None
894
+
895
+ ctx = await self._connect_cdp()
896
+ if ctx is not None:
897
+ return ctx
898
+
899
+ os.makedirs(CACHE_DIR, exist_ok=True)
900
+ lock_path = os.path.join(CACHE_DIR, f"launch-{CDP_PORT}.lock")
901
+ with open(lock_path, "w", encoding="utf-8") as lock_file:
902
+ await asyncio.to_thread(_acquire_file_lock, lock_file, 15.0)
903
+ try:
904
+ ctx = await self._connect_cdp()
905
+ if ctx is not None:
906
+ return ctx
907
+ await self._launch_detached_chromium()
908
+ ctx = await self._connect_cdp()
909
+ if ctx is not None:
910
+ return ctx
911
+ finally:
912
+ fcntl.flock(lock_file, fcntl.LOCK_UN)
913
+
914
+ raise RuntimeError(f"Failed to connect to Chromium CDP endpoint at {self.cdp_url}")
915
+
916
+ async def _configure_native_downloads(self, context: BrowserContext, page: Optional[Page] = None):
917
+ """Override Playwright's allowAndName download interception with native Chromium downloads."""
918
+ if getattr(context, "_downloads_configured", False):
919
+ return
920
+ os.makedirs(DOWNLOADS_DIR, exist_ok=True)
921
+ cdp = None
922
+ try:
923
+ if self._browser is not None:
924
+ cdp = await asyncio.wait_for(
925
+ self._browser.new_browser_cdp_session(),
926
+ timeout=CDP_OP_TIMEOUT_S,
927
+ )
928
+ else:
929
+ target_page = page or (context.pages[0] if context.pages else None)
930
+ if target_page is None or target_page.is_closed():
931
+ return
932
+ cdp = await asyncio.wait_for(
933
+ context.new_cdp_session(target_page),
934
+ timeout=CDP_OP_TIMEOUT_S,
935
+ )
936
+ await asyncio.wait_for(
937
+ cdp.send(
938
+ "Browser.setDownloadBehavior",
939
+ {
940
+ "behavior": "allow",
941
+ "downloadPath": DOWNLOADS_DIR,
942
+ },
943
+ ),
944
+ timeout=CDP_OP_TIMEOUT_S,
945
+ )
946
+ setattr(context, "_downloads_configured", True)
947
+ except Exception:
948
+ pass
949
+ finally:
950
+ if cdp is not None:
951
+ try:
952
+ await asyncio.wait_for(cdp.detach(), timeout=CDP_OP_TIMEOUT_S)
953
+ except Exception:
954
+ pass
955
+
956
+ async def _ensure_interceptor(self, context: BrowserContext):
957
+ _schedule_adblock_warmup()
958
+ await self._configure_native_downloads(context)
959
+ await self._ensure_animation_init_script(context)
960
+ if getattr(context, "_interceptor_attached", False):
961
+ return
962
+ setattr(context, "_interceptor_attached", True)
963
+ try:
964
+ await asyncio.wait_for(context.route("**/*", _network_route_handler), timeout=CDP_OP_TIMEOUT_S)
965
+ except Exception:
966
+ pass
967
+
968
+ async def _ensure_animation_init_script(self, context: BrowserContext) -> None:
969
+ """Install the kill-stylesheet init script on a context when animations are frozen."""
970
+ if self.animations is not False or context is None or getattr(context, "_animations_init_script", False):
971
+ return
972
+ setattr(context, "_animations_init_script", True)
973
+ try:
974
+ await asyncio.wait_for(context.add_init_script(_ANIMATIONS_INIT_SCRIPT), timeout=CDP_OP_TIMEOUT_S)
975
+ except Exception:
976
+ pass
977
+
978
+ def _register_page_listeners(self, page: Page):
979
+ """Attach lifecycle and dialog event listeners to keep cached state clean and prevent modal hangs."""
980
+ if getattr(page, "_agent_listeners_attached", False):
981
+ return
982
+ setattr(page, "_agent_listeners_attached", True)
983
+ dialogs = getattr(page, "_dialog_history", None)
984
+ if dialogs is None:
985
+ dialogs = deque(maxlen=MAX_DIALOG_HISTORY)
986
+ setattr(page, "_dialog_history", dialogs)
987
+
988
+ def _on_closed_or_crashed(_=None):
989
+ if self._active_page is page:
990
+ self._active_page = None
991
+
992
+ async def _on_dialog(dialog):
993
+ dialog_type = str(getattr(dialog, "type", "unknown") or "unknown").lower()
994
+ message = str(getattr(dialog, "message", "") or "")
995
+ try:
996
+ dialog_url = page.url or ""
997
+ except Exception:
998
+ dialog_url = ""
999
+ dialogs.append({
1000
+ "type": dialog_type,
1001
+ "message": message,
1002
+ "url": dialog_url,
1003
+ "timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat(),
1004
+ })
1005
+ try:
1006
+ if dialog_type == "beforeunload":
1007
+ await asyncio.wait_for(dialog.accept(), timeout=DIALOG_ACTION_TIMEOUT_S)
1008
+ else:
1009
+ await asyncio.wait_for(dialog.dismiss(), timeout=DIALOG_ACTION_TIMEOUT_S)
1010
+ except Exception:
1011
+ pass
1012
+
1013
+ page.on("close", _on_closed_or_crashed)
1014
+ page.on("crash", _on_closed_or_crashed)
1015
+ page.on("dialog", _on_dialog)
1016
+ download_tracker.attach(page)
1017
+ telemetry_tracker.attach(page)
1018
+
1019
+ def _unregister_page(self, page: Page) -> None:
1020
+ tab_id = self._page_to_id.pop(page, None)
1021
+ if tab_id is not None and self._id_to_page.get(tab_id) is page:
1022
+ self._id_to_page.pop(tab_id, None)
1023
+
1024
+ def _prune_closed_tabs(self) -> None:
1025
+ for page in list(self._page_to_id):
1026
+ try:
1027
+ closed = page.is_closed()
1028
+ except Exception:
1029
+ closed = True
1030
+ if closed:
1031
+ self._unregister_page(page)
1032
+
1033
+ def get_tab_id(self, page: Page) -> str:
1034
+ existing = self._page_to_id.get(page)
1035
+ if existing is not None:
1036
+ return existing
1037
+ tab_id = f"t{self._next_tab_seq}"
1038
+ self._next_tab_seq += 1
1039
+ self._page_to_id[page] = tab_id
1040
+ self._id_to_page[tab_id] = page
1041
+ if not getattr(page, "_tab_id_close_attached", False):
1042
+ setattr(page, "_tab_id_close_attached", True)
1043
+ page.on("close", lambda _=None, p=page: self._unregister_page(p))
1044
+ return tab_id
1045
+
1046
+ def set_active_page(self, page: Page):
1047
+ self._active_page = page
1048
+ if page is not None and not page.is_closed():
1049
+ self._register_page_listeners(page)
1050
+ self.get_tab_id(page)
1051
+
1052
+ async def get_pages(self) -> list[Page]:
1053
+ context = await asyncio.wait_for(self.get_context(), timeout=GET_CONTEXT_TIMEOUT_S)
1054
+ self._prune_closed_tabs()
1055
+ open_pages = []
1056
+ for p in context.pages:
1057
+ try:
1058
+ if not p.is_closed():
1059
+ self._register_page_listeners(p)
1060
+ _attach_page_trackers(p)
1061
+ self.get_tab_id(p)
1062
+ open_pages.append(p)
1063
+ except Exception:
1064
+ continue
1065
+ return open_pages
1066
+
1067
+ async def get_active_page(self) -> Page:
1068
+ self._touch_activity()
1069
+ if (
1070
+ self._active_page is not None
1071
+ and not self._active_page.is_closed()
1072
+ and (self._browser is None or self._browser.is_connected())
1073
+ ):
1074
+ return self._active_page
1075
+
1076
+ try:
1077
+ context = await asyncio.wait_for(self.get_context(), timeout=GET_CONTEXT_TIMEOUT_S)
1078
+ pages = await self.get_pages()
1079
+ blank_pages = [p for p in pages if p.url in ("about:blank", "chrome://newtab/", "")]
1080
+ if blank_pages:
1081
+ page = blank_pages[0]
1082
+ elif pages:
1083
+ page = pages[-1]
1084
+ else:
1085
+ page = await asyncio.wait_for(context.new_page(), timeout=NEW_PAGE_TIMEOUT_S)
1086
+
1087
+ await _apply_animations_to_page(page)
1088
+ self.set_active_page(page)
1089
+ return page
1090
+ except Exception as exc:
1091
+ if "closed" in str(exc).lower():
1092
+ await self.close()
1093
+ context = await asyncio.wait_for(self.get_context(), timeout=GET_CONTEXT_TIMEOUT_S)
1094
+ pages = await self.get_pages()
1095
+ blank_pages = [p for p in pages if p.url in ("about:blank", "chrome://newtab/", "")]
1096
+ if blank_pages:
1097
+ page = blank_pages[0]
1098
+ elif pages:
1099
+ page = pages[-1]
1100
+ else:
1101
+ page = await asyncio.wait_for(context.new_page(), timeout=NEW_PAGE_TIMEOUT_S)
1102
+ await _apply_animations_to_page(page)
1103
+ self.set_active_page(page)
1104
+ return page
1105
+ raise
1106
+
1107
+ async def resolve_page(self, tab: Union[int, str] = -1) -> Page:
1108
+ self._touch_activity()
1109
+ if isinstance(tab, str):
1110
+ tab_str = tab.strip()
1111
+ if tab_str.lower().startswith("t"):
1112
+ tab_key = tab_str.lower()
1113
+ self._prune_closed_tabs()
1114
+ page = self._id_to_page.get(tab_key)
1115
+ if page is not None:
1116
+ try:
1117
+ is_closed = page.is_closed()
1118
+ except Exception:
1119
+ is_closed = True
1120
+ if is_closed:
1121
+ self._unregister_page(page)
1122
+ page = None
1123
+ if page is not None and self._browser is not None and not self._browser.is_connected():
1124
+ self._unregister_page(page)
1125
+ page = None
1126
+ if page is not None and self._context is not None:
1127
+ ctx_pages = getattr(self._context, "pages", None)
1128
+ if isinstance(ctx_pages, (list, tuple)) and page not in ctx_pages:
1129
+ self._unregister_page(page)
1130
+ page = None
1131
+ if page is None:
1132
+ raise ValueError(f"Tab '{tab}' not found or was closed")
1133
+ return page
1134
+ try:
1135
+ tab = int(tab_str)
1136
+ except ValueError as exc:
1137
+ raise ValueError(f"Invalid tab identifier '{tab}'. Expected an integer index or tab ID like 't1'.") from exc
1138
+
1139
+ if tab < 0:
1140
+ if (
1141
+ self._active_page is not None
1142
+ and not self._active_page.is_closed()
1143
+ and (self._browser is None or self._browser.is_connected())
1144
+ ):
1145
+ _attach_page_trackers(self._active_page)
1146
+ self.get_tab_id(self._active_page)
1147
+ return self._active_page
1148
+ return await self.get_active_page()
1149
+
1150
+ pages = await self.get_pages()
1151
+ if tab >= len(pages):
1152
+ raise ValueError(f"Invalid tab index {tab}. Total open tabs: {len(pages)}")
1153
+ return pages[tab]
1154
+
1155
+
1156
+ session = BrowserSessionManager(CDP_URL)
1157
+
1158
+
1159
+ async def _apply_animations_to_page(page: Page) -> None:
1160
+ """Apply the live reduced-motion emulation and freeze stylesheet to one page when a preference is set."""
1161
+ enabled = session.animations
1162
+ if enabled is None or page is None:
1163
+ return
1164
+ try:
1165
+ if page.is_closed():
1166
+ return
1167
+ except Exception:
1168
+ return
1169
+ motion = "no-preference" if enabled else "reduce"
1170
+ if getattr(page, "_animations_motion", None) != motion:
1171
+ try:
1172
+ await asyncio.wait_for(page.emulate_media(reduced_motion=motion), timeout=CDP_OP_TIMEOUT_S)
1173
+ setattr(page, "_animations_motion", motion)
1174
+ except Exception:
1175
+ pass
1176
+ if not enabled:
1177
+ try:
1178
+ await asyncio.wait_for(page.evaluate(_ANIMATIONS_INJECT_JS, _ANIMATIONS_KILL_CSS), timeout=CDP_OP_TIMEOUT_S)
1179
+ except Exception:
1180
+ pass
1181
+ if not getattr(page, "_animations_nav_hook", False):
1182
+ setattr(page, "_animations_nav_hook", True)
1183
+ page.on("domcontentloaded", lambda _=None, p=page: _schedule_animations_on_page(p))
1184
+
1185
+
1186
+ def _schedule_animations_on_page(page: Page) -> None:
1187
+ """Schedule the per-page animation hook from sync page-listener code paths."""
1188
+ if session.animations is None or page is None:
1189
+ return
1190
+ try:
1191
+ asyncio.get_running_loop().create_task(_apply_animations_to_page(page))
1192
+ except RuntimeError:
1193
+ pass
1194
+
1195
+
1196
+ class KeepAliveManager:
1197
+ """Manages background jittered keep-alive workers to prevent web session timeouts."""
1198
+
1199
+ def __init__(self):
1200
+ self._tasks: dict[Page, asyncio.Task] = {}
1201
+ self._configs: dict[Page, dict] = {}
1202
+
1203
+ def has_active(self) -> bool:
1204
+ self._cleanup_dead_tasks()
1205
+ return bool(self._tasks)
1206
+
1207
+ def _cleanup_dead_tasks(self):
1208
+ dead = [p for p, t in self._tasks.items() if p.is_closed() or t.done()]
1209
+ for p in dead:
1210
+ self._tasks.pop(p, None)
1211
+ self._configs.pop(p, None)
1212
+
1213
+ def is_active(self, page: Page) -> bool:
1214
+ task = self._tasks.get(page)
1215
+ return task is not None and not task.done() and not page.is_closed()
1216
+
1217
+ def get_config(self, page: Page) -> Optional[dict]:
1218
+ return self._configs.get(page)
1219
+
1220
+ async def stop(self, page: Page):
1221
+ task = self._tasks.pop(page, None)
1222
+ self._configs.pop(page, None)
1223
+ if task is not None and not task.done():
1224
+ task.cancel()
1225
+ try:
1226
+ await task
1227
+ except asyncio.CancelledError:
1228
+ pass
1229
+
1230
+ async def stop_all(self):
1231
+ tasks = list(self._tasks.values())
1232
+ self._tasks.clear()
1233
+ self._configs.clear()
1234
+ for t in tasks:
1235
+ if not t.done():
1236
+ t.cancel()
1237
+ if tasks:
1238
+ await asyncio.gather(*tasks, return_exceptions=True)
1239
+
1240
+ async def start(
1241
+ self,
1242
+ page: Page,
1243
+ min_seconds: int = 45,
1244
+ max_seconds: int = 90,
1245
+ ping_url: Optional[str] = None,
1246
+ click_selector: Optional[str] = None,
1247
+ ):
1248
+ await self.stop(page)
1249
+ self._configs[page] = {
1250
+ "min_seconds": min_seconds,
1251
+ "max_seconds": max_seconds,
1252
+ "ping_url": ping_url,
1253
+ "click_selector": click_selector,
1254
+ "started_at": datetime.datetime.now().isoformat(),
1255
+ "last_ping": None,
1256
+ }
1257
+
1258
+ async def _worker():
1259
+ try:
1260
+ while not page.is_closed():
1261
+ delay = random.uniform(float(min_seconds), float(max_seconds))
1262
+ await asyncio.sleep(delay)
1263
+ if page.is_closed():
1264
+ break
1265
+
1266
+ session._touch_activity()
1267
+
1268
+ keep_working_js = """() => {
1269
+ const buttons = Array.from(document.querySelectorAll('button, a, [role="button"]'));
1270
+ const keepWorking = buttons.find(b => {
1271
+ const t = (b.innerText || '').toLowerCase();
1272
+ return t.includes('keep working') || t.includes('continue session') || t.includes('stay signed in') || t.includes('extend session');
1273
+ });
1274
+ if (!keepWorking) return null;
1275
+ const r = keepWorking.getBoundingClientRect();
1276
+ return { x: r.x + r.width / 2, y: r.y + r.height / 2, text: (keepWorking.innerText || '').slice(0, 60) };
1277
+ }"""
1278
+ ping_result = {"modal_clicked": None, "selector_clicked": False, "error": None}
1279
+ try:
1280
+ if click_selector:
1281
+ loc = page.locator(click_selector).first
1282
+ if await loc.count() > 0 and await loc.is_visible():
1283
+ await loc.click(timeout=5000)
1284
+ ping_result["selector_clicked"] = True
1285
+ except Exception as e:
1286
+ ping_result["error"] = f"click_selector: {e}"
1287
+ try:
1288
+ viewport = page.viewport_size or {"width": 1280, "height": 720}
1289
+ x = random.randint(100, max(101, viewport["width"] - 100))
1290
+ y = random.randint(100, max(101, viewport["height"] - 100))
1291
+ await page.mouse.move(x, y, steps=5)
1292
+ await page.mouse.move(x + random.randint(-40, 40), y + random.randint(-40, 40), steps=5)
1293
+ await page.mouse.wheel(0, random.choice([60, -60, 0]))
1294
+ target = await page.evaluate(keep_working_js)
1295
+ if target:
1296
+ await page.mouse.click(target["x"], target["y"])
1297
+ ping_result["modal_clicked"] = target["text"]
1298
+ if ping_url:
1299
+ await page.evaluate("async (u) => { try { return (await fetch(u)).status } catch (e) { return e.message } }", ping_url)
1300
+ except Exception as e:
1301
+ ping_result["error"] = f"input: {e}"
1302
+ if page in self._configs:
1303
+ self._configs[page]["last_ping"] = {
1304
+ "timestamp": datetime.datetime.now().isoformat(),
1305
+ "details": ping_result,
1306
+ }
1307
+ except asyncio.CancelledError:
1308
+ pass
1309
+ finally:
1310
+ self._tasks.pop(page, None)
1311
+ self._configs.pop(page, None)
1312
+
1313
+ task = asyncio.create_task(_worker())
1314
+ self._tasks[page] = task
1315
+
1316
+
1317
+ keep_alive_mgr = KeepAliveManager()
1318
+
1319
+ async def set_page_media_state(page: Page, block_media: bool):
1320
+ """Enable or disable media blocking on a given page."""
1321
+ setattr(page, "_media_blocked", block_media)
1322
+
1323
+
1324
+ @mcp.tool()
1325
+ @_with_tool_deadline
1326
+ async def status() -> str:
1327
+ """Check connection status to Stealth Browser and list all open tabs."""
1328
+ try:
1329
+ pages = await asyncio.wait_for(session.get_pages(), timeout=CDP_OP_TIMEOUT_S)
1330
+ active_page = session._active_page if (session._active_page is not None and not session._active_page.is_closed()) else None
1331
+ mode_str = "Headless" if session.headless else "Headed"
1332
+ lines = [f"Connected to browser session at {CDP_URL} (Mode: {mode_str})"]
1333
+ lines.append(f"Total open tabs: {len(pages)}")
1334
+ if session.animations is not None:
1335
+ anim_state = "FROZEN" if session.animations is False else "ENABLED"
1336
+ lines.append(f"Animations: {anim_state}")
1337
+ for idx, page in enumerate(pages):
1338
+ tab_id = session.get_tab_id(page)
1339
+ active_marker = " (ACTIVE in this session)" if page == active_page else ""
1340
+ media_status = " [TEXT-ONLY/MEDIA BLOCKED]" if getattr(page, "_media_blocked", False) else ""
1341
+ animations_status = " [ANIMATIONS FROZEN]" if getattr(page, "_animations_motion", None) == "reduce" else ""
1342
+ keep_alive_status = " [KEEP-ALIVE ACTIVE]" if keep_alive_mgr.is_active(page) else ""
1343
+ try:
1344
+ title = await asyncio.wait_for(page.title(), timeout=2.0)
1345
+ except Exception:
1346
+ title = "(Unresponsive / Busy)"
1347
+ lines.append(f"\t[{idx} | {tab_id}] {title} - {page.url}{media_status}{animations_status}{keep_alive_status}{active_marker}")
1348
+ dialog_lines = []
1349
+ unhandled = getattr(session, "_unhandled_task_exceptions", None)
1350
+ if unhandled is not None and unhandled.get("n"):
1351
+ lines.append(f"Unhandled task exceptions since start: {unhandled['n']}")
1352
+ for p, tab_id in list(session._page_to_id.items()):
1353
+ history = getattr(p, "_dialog_history", None)
1354
+ if not history:
1355
+ continue
1356
+ for entry in list(history)[-3:]:
1357
+ dialog_lines.append(f"\t[{tab_id}] {entry['type']}: {entry['message'][:120]} @ {entry['timestamp']}")
1358
+ if dialog_lines:
1359
+ lines.append(f"Recent dialogs (last {len(dialog_lines)}, auto-dismissed unless beforeunload):")
1360
+ lines.extend(dialog_lines[-5:])
1361
+ return "\n".join(lines)
1362
+ except Exception as exc:
1363
+ return f"Disconnected: {exc}"
1364
+
1365
+
1366
+ @mcp.tool()
1367
+ @_with_tool_deadline
1368
+ async def keep_alive(
1369
+ enable: bool = True,
1370
+ tab: Union[int, str] = -1,
1371
+ min_seconds: int = 45,
1372
+ max_seconds: int = 90,
1373
+ ping_url: Optional[str] = None,
1374
+ click_selector: Optional[str] = None,
1375
+ ) -> str:
1376
+ """Keep a tab session alive: trusted CDP mouse/wheel input, modal auto-click, optional click_selector and heartbeat ping_url."""
1377
+ try:
1378
+ page = await session.resolve_page(tab)
1379
+ pages = await asyncio.wait_for(session.get_pages(), timeout=CDP_OP_TIMEOUT_S)
1380
+ target_index = pages.index(page) if page in pages else tab
1381
+
1382
+ if not enable:
1383
+ await keep_alive_mgr.stop(page)
1384
+ return f"Disabled keep-alive on tab [{target_index}] ({page.url})"
1385
+
1386
+ await keep_alive_mgr.start(
1387
+ page=page,
1388
+ min_seconds=min_seconds,
1389
+ max_seconds=max_seconds,
1390
+ ping_url=ping_url,
1391
+ click_selector=click_selector,
1392
+ )
1393
+ ping_info = f", pinging '{ping_url}'" if ping_url else ""
1394
+ click_info = f", real-clicking '{click_selector}'" if click_selector else ""
1395
+ return (
1396
+ f"Activated keep-alive on tab [{target_index}] ({page.url}): "
1397
+ f"jitter interval {min_seconds}-{max_seconds}s, trusted mouse/wheel input, auto-dismiss modals enabled{click_info}{ping_info}."
1398
+ )
1399
+ except Exception as exc:
1400
+ return f"Error managing keep-alive: {exc}"
1401
+
1402
+
1403
+ def _has_explicit_scheme(url: str) -> bool:
1404
+ if url.lower().startswith(("http://", "https://", "about:")):
1405
+ return True
1406
+ try:
1407
+ scheme = urlparse(url).scheme
1408
+ except ValueError:
1409
+ return False
1410
+ if not scheme:
1411
+ return False
1412
+ remainder = url[len(scheme) + 1:]
1413
+ # urlparse reads bare "host:port" as a scheme (dots/digits are valid scheme chars).
1414
+ # A real scheme is followed by "//" or non-numeric content, unlike a port number.
1415
+ if remainder.startswith("//"):
1416
+ return True
1417
+ return not remainder[:1].isdigit()
1418
+
1419
+
1420
+ @mcp.tool()
1421
+ @_with_tool_deadline
1422
+ async def navigate(
1423
+ url: str,
1424
+ block_media: Optional[bool] = None,
1425
+ new_tab: bool = False,
1426
+ tab: Union[int, str] = -1,
1427
+ timeout_ms: int = 30000,
1428
+ wait_until: str = "domcontentloaded",
1429
+ ) -> str:
1430
+ """Navigate a tab to url. block_media=True blocks images/fonts/video (None preserves state); wait_until: 'domcontentloaded'|'commit'|'load'|'networkidle'. Clamped to 60s tool cap."""
1431
+ t0 = time.perf_counter()
1432
+ try:
1433
+ context = await asyncio.wait_for(session.get_context(), timeout=GET_CONTEXT_TIMEOUT_S)
1434
+ if new_tab:
1435
+ page = await asyncio.wait_for(context.new_page(), timeout=NEW_PAGE_TIMEOUT_S)
1436
+ await _apply_animations_to_page(page)
1437
+ session.set_active_page(page)
1438
+ else:
1439
+ page = await session.resolve_page(tab)
1440
+
1441
+ if block_media is not None:
1442
+ await set_page_media_state(page, block_media=block_media)
1443
+
1444
+ if not _has_explicit_scheme(url):
1445
+ url = "https://" + url
1446
+
1447
+ valid_waits = {"commit", "domcontentloaded", "load", "networkidle"}
1448
+ wait_mode = wait_until if wait_until in valid_waits else "domcontentloaded"
1449
+
1450
+ goto_outer_timeout = max(1.0, (timeout_ms / 1000.0)) + GOTO_OUTER_BUFFER_S
1451
+ response = None
1452
+ sw_fallback = False
1453
+ try:
1454
+ response = await asyncio.wait_for(
1455
+ page.goto(url, timeout=timeout_ms, wait_until=wait_mode),
1456
+ timeout=goto_outer_timeout,
1457
+ )
1458
+ except Exception as exc:
1459
+ if "service worker requests do not have an associated frame" in str(exc).lower():
1460
+ sw_fallback = True
1461
+ try:
1462
+ await asyncio.wait_for(
1463
+ page.wait_for_load_state("domcontentloaded", timeout=min(timeout_ms, 5000)),
1464
+ timeout=min(timeout_ms / 1000.0, 5.0) + 1.0,
1465
+ )
1466
+ except Exception:
1467
+ pass
1468
+ else:
1469
+ raise
1470
+
1471
+ if sw_fallback:
1472
+ status = "loaded (service worker)"
1473
+ else:
1474
+ status = response.status if response else "loaded"
1475
+ try:
1476
+ title = await asyncio.wait_for(page.title(), timeout=PAGE_TITLE_TIMEOUT_S)
1477
+ except Exception:
1478
+ title = "(Unavailable)"
1479
+ try:
1480
+ pages = await asyncio.wait_for(session.get_pages(), timeout=CDP_OP_TIMEOUT_S)
1481
+ target_idx = pages.index(page) if page in pages else -1
1482
+ except Exception:
1483
+ target_idx = -1
1484
+ elapsed = int((time.perf_counter() - t0) * 1000)
1485
+ is_media_blocked = getattr(page, "_media_blocked", False)
1486
+ media_tag = " (media blocked)" if is_media_blocked else ""
1487
+ return f"Navigated tab [{target_idx}] to '{url}' [HTTP {status}]{media_tag} ({elapsed}ms, wait_until={wait_mode}) - Title: '{title}'"
1488
+ except (asyncio.TimeoutError, TimeoutError):
1489
+ return f"Navigation error: Timed out after {timeout_ms}ms navigating to '{url}'"
1490
+ except Exception as exc:
1491
+ if "timeout" in exc.__class__.__name__.lower():
1492
+ return f"Navigation error: Timed out after {timeout_ms}ms navigating to '{url}'"
1493
+ return f"Navigation error: {_format_playwright_error(exc)}"
1494
+
1495
+
1496
+ @mcp.tool()
1497
+ @_with_tool_deadline
1498
+ async def new_tab(url: str = "about:blank", block_media: Optional[bool] = None) -> str:
1499
+ """Open a new browser tab and navigate to url (default 'about:blank'). Set block_media=True for high-speed text-only browsing."""
1500
+ result = await navigate(url=url, block_media=block_media, new_tab=True)
1501
+ if result.startswith("Navigation error:"):
1502
+ return result
1503
+ page = None
1504
+ match = re.match(r"Navigated tab \[(\d+)\]", result)
1505
+ if match:
1506
+ try:
1507
+ pages = await asyncio.wait_for(session.get_pages(), timeout=CDP_OP_TIMEOUT_S)
1508
+ idx = int(match.group(1))
1509
+ if 0 <= idx < len(pages):
1510
+ page = pages[idx]
1511
+ except Exception:
1512
+ page = None
1513
+ if page is None:
1514
+ page = session._active_page
1515
+ if page is not None and not page.is_closed():
1516
+ tab_id = session.get_tab_id(page)
1517
+ if f"tab_id={tab_id}" not in result:
1518
+ return f"{result} (tab_id={tab_id})"
1519
+ return result
1520
+
1521
+
1522
+ def _escape_applescript(text: str) -> str:
1523
+ return text.replace("\\", "\\\\").replace('"', '\\"').replace("\r", " ").replace("\n", " ")
1524
+
1525
+
1526
+ def _notify_human(reason: str) -> Optional[subprocess.Popen]:
1527
+ try:
1528
+ safe_msg = _escape_applescript(reason)
1529
+ script = f'display notification "{safe_msg}" with title "stealth-browser"'
1530
+ return subprocess.Popen(
1531
+ ["osascript", "-e", script],
1532
+ stdin=subprocess.DEVNULL,
1533
+ stdout=subprocess.DEVNULL,
1534
+ stderr=subprocess.DEVNULL,
1535
+ )
1536
+ except Exception:
1537
+ return None
1538
+
1539
+
1540
+ def _url_origin(url: str) -> str:
1541
+ match = re.match(r"^(https?://[^/]+)", url or "")
1542
+ return match.group(1) if match else ""
1543
+
1544
+
1545
+ @mcp.tool()
1546
+ async def wait_for_human(
1547
+ reason: str = "Complete login / 2FA / CAPTCHA",
1548
+ url_contains: str = "",
1549
+ url_not_contains: str = "",
1550
+ selector: str = "",
1551
+ timeout_s: int = 180,
1552
+ poll_interval_s: float = 1.5,
1553
+ notify: bool = True,
1554
+ tab: Union[int, str] = -1,
1555
+ ) -> str:
1556
+ """Hand off a tab to the human for login/2FA/CAPTCHA (switches to headed mode if needed, sends optional macOS notification) and poll until url_contains, url_not_contains, selector visible, or URL change."""
1557
+ t0 = time.monotonic()
1558
+ notify_proc: Optional[subprocess.Popen] = None
1559
+ try:
1560
+ page = await session.resolve_page(tab)
1561
+ initial_url = page.url or ""
1562
+ tab_id = session.get_tab_id(page)
1563
+ switched_to_headed = False
1564
+
1565
+ try:
1566
+ detected_headless = await asyncio.wait_for(
1567
+ asyncio.to_thread(session._detect_cdp_headless),
1568
+ timeout=CDP_OP_TIMEOUT_S,
1569
+ )
1570
+ if detected_headless is not None:
1571
+ session.headless = detected_headless
1572
+ except Exception:
1573
+ pass
1574
+
1575
+ if session.headless:
1576
+ restart_res = await restart_browser(headless=False)
1577
+ if isinstance(restart_res, str) and restart_res.startswith("Error"):
1578
+ return f"Error switching to headed mode for human handoff: {restart_res}"
1579
+ switched_to_headed = True
1580
+ pages = await asyncio.wait_for(session.get_pages(), timeout=CDP_OP_TIMEOUT_S)
1581
+ resolved_page = None
1582
+ if initial_url and initial_url != "about:blank" and not initial_url.startswith("chrome://"):
1583
+ for candidate in pages:
1584
+ if candidate.url == initial_url:
1585
+ resolved_page = candidate
1586
+ break
1587
+ if resolved_page is None:
1588
+ origin = _url_origin(initial_url)
1589
+ if origin:
1590
+ for candidate in pages:
1591
+ if (candidate.url or "").startswith(origin):
1592
+ resolved_page = candidate
1593
+ break
1594
+ page = resolved_page if resolved_page is not None else await session.get_active_page()
1595
+ session.set_active_page(page)
1596
+ tab_id = session.get_tab_id(page)
1597
+ else:
1598
+ session.set_active_page(page)
1599
+
1600
+ try:
1601
+ await page.bring_to_front()
1602
+ except Exception:
1603
+ pass
1604
+
1605
+ if notify:
1606
+ notify_proc = _notify_human(reason)
1607
+
1608
+ has_explicit_condition = bool(url_contains or url_not_contains or selector)
1609
+ interval = max(0.005, float(poll_interval_s))
1610
+ deadline = t0 + max(0.0, float(timeout_s))
1611
+ mode_note = " (switched to headed mode)" if switched_to_headed else ""
1612
+
1613
+ while True:
1614
+ session._touch_activity()
1615
+ if page.is_closed():
1616
+ elapsed = time.monotonic() - t0
1617
+ return f"Human handoff ended: tab {tab_id} was closed after {elapsed:.1f}s{mode_note} (reason: {reason})"
1618
+
1619
+ current_url = page.url or ""
1620
+ matched_condition = ""
1621
+ if url_contains and url_contains in current_url:
1622
+ matched_condition = f"url_contains='{url_contains}'"
1623
+ elif url_not_contains and url_not_contains not in current_url:
1624
+ matched_condition = f"url_not_contains='{url_not_contains}'"
1625
+ elif selector:
1626
+ try:
1627
+ visible = await asyncio.wait_for(page.locator(selector).first.is_visible(), timeout=2.0)
1628
+ except Exception:
1629
+ visible = False
1630
+ if visible:
1631
+ matched_condition = f"selector='{selector}' visible"
1632
+ elif not has_explicit_condition and current_url != initial_url:
1633
+ matched_condition = f"URL changed from '{initial_url}'"
1634
+
1635
+ if matched_condition:
1636
+ elapsed = time.monotonic() - t0
1637
+ try:
1638
+ title = await asyncio.wait_for(page.title(), timeout=2.0)
1639
+ except Exception:
1640
+ title = "(Unavailable)"
1641
+ return (
1642
+ f"Human handoff completed ({matched_condition}) in {elapsed:.1f}s{mode_note} "
1643
+ f"[tab_id={tab_id}] - Title: '{title}' - URL: {current_url}"
1644
+ )
1645
+
1646
+ remaining = deadline - time.monotonic()
1647
+ if remaining <= 0:
1648
+ elapsed = time.monotonic() - t0
1649
+ try:
1650
+ title = await asyncio.wait_for(page.title(), timeout=2.0)
1651
+ except Exception:
1652
+ title = "(Unavailable)"
1653
+ return (
1654
+ f"Timed out after {elapsed:.1f}s waiting for human ({reason}){mode_note} "
1655
+ f"[tab_id={tab_id}] - Title: '{title}' - URL: {current_url}"
1656
+ )
1657
+
1658
+ await asyncio.sleep(min(interval, remaining))
1659
+ except Exception as exc:
1660
+ return f"Error during human handoff: {exc}"
1661
+ finally:
1662
+ if notify_proc is not None:
1663
+ try:
1664
+ notify_proc.poll()
1665
+ except Exception:
1666
+ pass
1667
+
1668
+
1669
+ @mcp.tool()
1670
+ @_with_tool_deadline
1671
+ async def set_media(enable_media: bool = True, tab: Union[int, str] = -1) -> str:
1672
+ """Toggle media loading (images, videos, web fonts) on a tab. enable_media=False blocks heavy media for fast text-only browsing."""
1673
+ try:
1674
+ page = await session.resolve_page(tab)
1675
+ await set_page_media_state(page, block_media=not enable_media)
1676
+ pages = await asyncio.wait_for(session.get_pages(), timeout=CDP_OP_TIMEOUT_S)
1677
+ target_idx = pages.index(page) if page in pages else -1
1678
+ state_str = "ENABLED (images, charts, and media will load)" if enable_media else "BLOCKED (high-speed text-only mode)"
1679
+ return f"Media loading is now {state_str} on tab [{target_idx}] ({page.url})"
1680
+ except Exception as exc:
1681
+ return f"Error updating media state: {exc}"
1682
+
1683
+
1684
+ @mcp.tool()
1685
+ @_with_tool_deadline
1686
+ async def set_animations(enabled: bool = False, persist: bool = True, tab: Union[int, str] = -1) -> str:
1687
+ """Freeze CSS animations/transitions via reduced-motion emulation + a kill-stylesheet; sites may serve reduced-motion content variants, and re-enabling fully applies only after restart_browser() because init scripts cannot be removed."""
1688
+ try:
1689
+ page = await session.resolve_page(tab)
1690
+ session.animations = bool(enabled)
1691
+ if persist:
1692
+ _save_persisted_animations(bool(enabled))
1693
+ context = await asyncio.wait_for(session.get_context(), timeout=GET_CONTEXT_TIMEOUT_S)
1694
+ if not enabled:
1695
+ await session._ensure_animation_init_script(context)
1696
+ await _apply_animations_to_page(page)
1697
+ pages = await asyncio.wait_for(session.get_pages(), timeout=CDP_OP_TIMEOUT_S)
1698
+ for other in pages:
1699
+ if other is not page:
1700
+ await _apply_animations_to_page(other)
1701
+ state = "ENABLED (reduced-motion reverted on live pages)" if enabled else "DISABLED (animations frozen)"
1702
+ return (
1703
+ f"Animations {state}. Dynamic emulation applied to {len(pages)} open tab(s); "
1704
+ "structural init script applies to future tabs. Re-enabling fully applies after restart_browser()."
1705
+ )
1706
+ except Exception as exc:
1707
+ return f"Error updating animation state: {exc}"
1708
+
1709
+
1710
+ _BATCH_EVAL_MAX_CHARS = 2000
1711
+ _BATCH_TOTAL_MAX_CHARS = 8000
1712
+ _DEFAULT_OUTPUT_MAX_CHARS = 8000
1713
+
1714
+
1715
+ def _compact_json(obj: Any) -> str:
1716
+ return json.dumps(obj, separators=(",", ":"), ensure_ascii=False, default=str)
1717
+
1718
+
1719
+ def _truncate_text(text: str, max_length: int) -> str:
1720
+ if max_length > 0 and len(text) > max_length:
1721
+ return text[:max_length] + f"\n... [Truncated: {len(text)} total characters]"
1722
+ return text
1723
+
1724
+
1725
+ def _truncate_url(url: str, max_len: int = 160) -> str:
1726
+ s = str(url or "")
1727
+ if len(s) <= max_len:
1728
+ return s
1729
+ return s[: max_len - 3] + "..."
1730
+
1731
+
1732
+ def _truncate_lines(header_fn, lines: list[str], max_length: int, hint: str = "") -> str:
1733
+ if max_length <= 0:
1734
+ return "\n".join([header_fn(len(lines))] + lines)
1735
+ sample_header = header_fn(len(lines))
1736
+ cur = len(sample_header)
1737
+ kept: list[str] = []
1738
+ for line in lines:
1739
+ add = len(line) + 1
1740
+ if kept and cur + add + 90 > max_length:
1741
+ break
1742
+ kept.append(line)
1743
+ cur += add
1744
+ out = [header_fn(len(kept))] + kept
1745
+ if len(kept) < len(lines):
1746
+ extra = f"; {hint}" if hint else ""
1747
+ out.append(f"... [Truncated at {max_length} chars{extra}]")
1748
+ return "\n".join(out)
1749
+
1750
+
1751
+ def _compact_html_tag(tag_str: str) -> str:
1752
+ m = re.match(r"<([a-zA-Z0-9_-]+)([^>]*)>", tag_str)
1753
+ if not m:
1754
+ return tag_str[:80]
1755
+ tag, attrs = m.group(1).lower(), m.group(2)
1756
+ id_m = re.search(r'\bid=["\']([^"\']+)["\']', attrs)
1757
+ cls_m = re.search(r'\bclass=["\']([^"\']+)["\']', attrs)
1758
+ parts = [tag]
1759
+ if id_m:
1760
+ parts.append(f"#{id_m.group(1)[:40]}")
1761
+ if cls_m:
1762
+ first_cls = cls_m.group(1).strip().split()[0][:40]
1763
+ if first_cls:
1764
+ parts.append(f".{first_cls}")
1765
+ return f"<{''.join(parts)}>"
1766
+
1767
+
1768
+ def _format_playwright_error(exc: Exception, max_chars: int = 300) -> str:
1769
+ raw = str(exc).strip()
1770
+ if not raw:
1771
+ return exc.__class__.__name__
1772
+ parts = re.split(r"\n\s*Call log:\s*\n?", raw, maxsplit=1)
1773
+ summary = " ".join(parts[0].strip().split())
1774
+ if len(parts) == 1:
1775
+ return summary if len(summary) <= max_chars else summary[: max_chars - 3] + "..."
1776
+
1777
+ log_lines = [ln.strip().lstrip("- ").strip() for ln in parts[1].splitlines() if ln.strip()]
1778
+ reason = ""
1779
+ hint = ""
1780
+ for ln in log_lines:
1781
+ low = ln.lower()
1782
+ if "intercepts pointer events" in low:
1783
+ tag_m = re.search(r"<[^>]+>", ln)
1784
+ blocker = _compact_html_tag(tag_m.group(0)) if tag_m else "overlay"
1785
+ reason = f"{blocker} intercepts pointer events"
1786
+ hint = " (try force=True)"
1787
+ break
1788
+ if any(k in low for k in (
1789
+ "element is not visible",
1790
+ "element is not enabled",
1791
+ "element is outside of the viewport",
1792
+ "element was detached",
1793
+ "strict mode violation",
1794
+ )):
1795
+ reason = re.sub(r"<[^>]+>", lambda m: _compact_html_tag(m.group(0)), ln)[:120]
1796
+ break
1797
+ if not reason:
1798
+ for ln in reversed(log_lines):
1799
+ low = ln.lower()
1800
+ if not low.startswith(("retrying ", "waiting ")) and "× waiting" not in low:
1801
+ reason = re.sub(r"<[^>]+>", lambda m: _compact_html_tag(m.group(0)), ln)[:120]
1802
+ break
1803
+
1804
+ msg = f"{summary} — {reason}{hint}" if reason else summary
1805
+ return msg if len(msg) <= max_chars else msg[: max_chars - 3] + "..."
1806
+
1807
+
1808
+ def _action_delta_suffix(page: Page, before_url: str, before_dialogs: int) -> str:
1809
+ notes: list[str] = []
1810
+ after_url = getattr(page, "url", "") or ""
1811
+ if after_url and after_url != before_url:
1812
+ notes.append(f"navigated -> {after_url}")
1813
+ hist = getattr(page, "_dialog_history", None)
1814
+ if hist is not None and len(hist) > before_dialogs:
1815
+ last = list(hist)[-1]
1816
+ notes.append(f"dialog[{last.get('type', 'alert')}]: {str(last.get('message', ''))[:80]}")
1817
+ return f" | {'; '.join(notes)}" if notes else ""
1818
+
1819
+
1820
+ _SB_REF_SELECTOR_RE = re.compile(r'^\[data-sb-ref=["\']([^"\']+)["\']\]$')
1821
+
1822
+ _SNAPSHOT_JS = r"""async ({ targetSelector, maxElements, includeShadow, includeIframes, includeHrefs, filter, viewportOnly }) => {
1823
+ const SKIP_TAGS = new Set(['SCRIPT', 'STYLE', 'NOSCRIPT', 'META', 'LINK', 'HEAD', 'TITLE', 'TEMPLATE']);
1824
+ const INTERACTIVE_SEL = 'button, input, select, textarea, a[href], summary, [role="button"], [role="link"], [role="combobox"], [role="option"], [role="tab"], [role="menuitem"], [role="checkbox"], [role="radio"], [role="switch"]';
1825
+ const limit = Math.max(1, Number(maxElements) || 80);
1826
+ const filterStr = String(filter || '').trim();
1827
+ let filterRe = null;
1828
+ if (filterStr) {
1829
+ try {
1830
+ filterRe = new RegExp(filterStr, 'i');
1831
+ } catch (_) {
1832
+ filterRe = null;
1833
+ }
1834
+ }
1835
+ const filterLow = filterStr.toLowerCase();
1836
+
1837
+ const escIdent = (s) => (typeof CSS !== 'undefined' && CSS.escape)
1838
+ ? CSS.escape(String(s))
1839
+ : String(s).replace(/([^\w-])/g, '\\$1');
1840
+ const escAttr = (s) => String(s).replace(/\\/g, '\\\\').replace(/"/g, '\\"');
1841
+
1842
+ const isVisible = (el) => {
1843
+ try {
1844
+ const win = (el.ownerDocument && el.ownerDocument.defaultView) || window;
1845
+ const style = win.getComputedStyle(el);
1846
+ if (!style || style.visibility === 'hidden' || style.display === 'none') return false;
1847
+ const rect = el.getBoundingClientRect();
1848
+ if (!(rect.width > 0 && rect.height > 0)) return false;
1849
+ if (viewportOnly) {
1850
+ const vw = win.innerWidth || document.documentElement.clientWidth || 0;
1851
+ const vh = win.innerHeight || document.documentElement.clientHeight || 0;
1852
+ if (rect.bottom <= 0 || rect.right <= 0 || rect.top >= vh || rect.left >= vw) return false;
1853
+ }
1854
+ return true;
1855
+ } catch (_) {
1856
+ return false;
1857
+ }
1858
+ };
1859
+
1860
+ const matchesFilter = (el) => {
1861
+ if (!filterStr) return true;
1862
+ const hay = [
1863
+ (el.innerText || el.textContent || '').trim(),
1864
+ el.getAttribute('aria-label') || '',
1865
+ el.getAttribute('placeholder') || '',
1866
+ el.name || '',
1867
+ el.id || '',
1868
+ el.getAttribute('href') || '',
1869
+ el.href || '',
1870
+ ].filter(Boolean).join(' ');
1871
+ return filterRe ? filterRe.test(hay) : hay.toLowerCase().includes(filterLow);
1872
+ };
1873
+
1874
+ const clearRefs = (root, visited) => {
1875
+ if (!root || visited.has(root)) return;
1876
+ visited.add(root);
1877
+ try {
1878
+ root.querySelectorAll('[data-sb-ref]').forEach((el) => el.removeAttribute('data-sb-ref'));
1879
+ } catch (_) {}
1880
+ let all = [];
1881
+ try {
1882
+ all = root.querySelectorAll ? root.querySelectorAll('*') : [];
1883
+ } catch (_) {}
1884
+ for (const el of all) {
1885
+ if (el.shadowRoot) clearRefs(el.shadowRoot, visited);
1886
+ const tn = (el.tagName || '').toUpperCase();
1887
+ if (tn === 'IFRAME' || tn === 'FRAME') {
1888
+ try {
1889
+ if (el.contentDocument) clearRefs(el.contentDocument, visited);
1890
+ } catch (_) {}
1891
+ }
1892
+ }
1893
+ };
1894
+
1895
+ clearRefs(document, new Set());
1896
+
1897
+ let startNode = document;
1898
+ if (targetSelector && targetSelector !== 'body') {
1899
+ try {
1900
+ startNode = document.querySelector(targetSelector) || document;
1901
+ } catch (_) {
1902
+ startNode = document;
1903
+ }
1904
+ } else if (document.body) {
1905
+ startNode = document.body;
1906
+ }
1907
+
1908
+ const collected = [];
1909
+ let totalMatched = 0;
1910
+ const countCap = limit * 10;
1911
+ const seen = new Set();
1912
+
1913
+ const walk = (node, ctx) => {
1914
+ if (!node || totalMatched >= countCap) return;
1915
+ if (node.nodeType === 1) {
1916
+ const tn = (node.tagName || '').toUpperCase();
1917
+ if (SKIP_TAGS.has(tn) || seen.has(node)) return;
1918
+ seen.add(node);
1919
+
1920
+ try {
1921
+ if (node.matches && node.matches(INTERACTIVE_SEL) && isVisible(node) && matchesFilter(node)) {
1922
+ totalMatched++;
1923
+ if (collected.length < limit) {
1924
+ collected.push({ el: node, ctx });
1925
+ }
1926
+ if (totalMatched >= countCap) return;
1927
+ }
1928
+ } catch (_) {}
1929
+
1930
+ if (includeShadow && node.shadowRoot) {
1931
+ const shadowCtx = { rootNode: node.shadowRoot, inShadow: true, inIframe: ctx.inIframe };
1932
+ for (const child of node.shadowRoot.children) {
1933
+ walk(child, shadowCtx);
1934
+ if (totalMatched >= countCap) return;
1935
+ }
1936
+ }
1937
+
1938
+ if (includeIframes && (tn === 'IFRAME' || tn === 'FRAME') && isVisible(node)) {
1939
+ try {
1940
+ const doc = node.contentDocument;
1941
+ if (doc && doc.documentElement) {
1942
+ const iframeCtx = { rootNode: doc, inShadow: ctx.inShadow, inIframe: true };
1943
+ walk(doc.documentElement, iframeCtx);
1944
+ if (totalMatched >= countCap) return;
1945
+ }
1946
+ } catch (_) {}
1947
+ }
1948
+
1949
+ for (const child of node.children) {
1950
+ walk(child, ctx);
1951
+ if (totalMatched >= countCap) return;
1952
+ }
1953
+ } else if (node.children) {
1954
+ for (const child of node.children) {
1955
+ walk(child, ctx);
1956
+ if (totalMatched >= countCap) return;
1957
+ }
1958
+ }
1959
+ };
1960
+
1961
+ if (includeIframes) {
1962
+ const frameNeedsLoad = (f) => {
1963
+ try {
1964
+ const w = f.contentWindow;
1965
+ if (!w) return false;
1966
+ void w.location.href;
1967
+ } catch (_) {
1968
+ return false;
1969
+ }
1970
+ try {
1971
+ const d = f.contentDocument;
1972
+ if (d === null) return true;
1973
+ return d.readyState === 'loading';
1974
+ } catch (_) {
1975
+ return false;
1976
+ }
1977
+ };
1978
+ const pendingFrames = () => [...document.querySelectorAll('iframe, frame')].filter(frameNeedsLoad);
1979
+ let pending = pendingFrames();
1980
+ const frameDeadline = Date.now() + 1500;
1981
+ while (pending.length && Date.now() < frameDeadline) {
1982
+ await new Promise((resolve) => setTimeout(resolve, 60));
1983
+ pending = pendingFrames();
1984
+ }
1985
+ }
1986
+
1987
+ walk(startNode, { rootNode: document, inShadow: false, inIframe: false });
1988
+
1989
+ const isUnique = (root, sel, target) => {
1990
+ if (!sel || !root || !root.querySelectorAll) return false;
1991
+ try {
1992
+ const matches = root.querySelectorAll(sel);
1993
+ return matches.length === 1 && matches[0] === target;
1994
+ } catch (_) {
1995
+ return false;
1996
+ }
1997
+ };
1998
+
1999
+ const buildSelector = (el, tag, ref, ctx) => {
2000
+ const refSel = `[data-sb-ref="${ref}"]`;
2001
+ if (ctx.inShadow || ctx.inIframe) return refSel;
2002
+
2003
+ const candidates = [];
2004
+ if (el.id) candidates.push(`#${escIdent(el.id)}`);
2005
+ const testid = el.getAttribute('data-testid');
2006
+ if (testid) candidates.push(`[data-testid="${escAttr(testid)}"]`);
2007
+ if (el.name) candidates.push(`${tag}[name="${escAttr(el.name)}"]`);
2008
+ const ariaLabel = el.getAttribute('aria-label');
2009
+ if (ariaLabel && ariaLabel.length <= 60) {
2010
+ candidates.push(`${tag}[aria-label="${escAttr(ariaLabel)}"]`);
2011
+ }
2012
+ if (typeof el.className === 'string' && el.className.trim()) {
2013
+ const classes = el.className.trim().split(/\s+/).filter((c) => c && !c.includes(':'));
2014
+ for (const cls of classes.slice(0, 3)) {
2015
+ candidates.push(`${tag}.${escIdent(cls)}`);
2016
+ }
2017
+ }
2018
+ if (el.type) candidates.push(`${tag}[type="${escAttr(el.type)}"]`);
2019
+ candidates.push(tag);
2020
+
2021
+ for (const cand of candidates) {
2022
+ if (isUnique(document, cand, el)) return cand;
2023
+ }
2024
+ return refSel;
2025
+ };
2026
+
2027
+ const origin = (window.location && window.location.origin) || '';
2028
+ const items = collected.map(({ el, ctx }, i) => {
2029
+ const ref = `e${i}`;
2030
+ el.setAttribute('data-sb-ref', ref);
2031
+ const tag = (el.tagName || '').toLowerCase();
2032
+ const selector = buildSelector(el, tag, ref, ctx);
2033
+ const text = (el.innerText || el.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
2034
+ const ariaRaw = (el.getAttribute('aria-label') || '').trim();
2035
+ const placeholderRaw = (el.getAttribute('placeholder') || '').trim();
2036
+ const roleRaw = (el.getAttribute('role') || '').trim();
2037
+
2038
+ const attrParts = [];
2039
+ if (el.id && !selector.includes(`#${el.id}`) && !selector.includes(`#${escIdent(el.id)}`)) {
2040
+ attrParts.push(`#${el.id}`);
2041
+ }
2042
+ if (el.name && !selector.includes('[name=')) {
2043
+ attrParts.push(`name=${el.name}`);
2044
+ }
2045
+ if (el.type && !selector.includes('[type=')) {
2046
+ attrParts.push(`type=${el.type}`);
2047
+ }
2048
+ if (roleRaw) {
2049
+ attrParts.push(`role=${roleRaw}`);
2050
+ }
2051
+ if (ariaRaw && !selector.includes('[aria-label=') && ariaRaw.toLowerCase() !== text.toLowerCase()) {
2052
+ attrParts.push(`aria="${ariaRaw.slice(0, 50)}"`);
2053
+ }
2054
+ if (placeholderRaw && !text && !ariaRaw) {
2055
+ attrParts.push(`placeholder="${placeholderRaw.slice(0, 40)}"`);
2056
+ }
2057
+ if (el.value !== undefined && el.value !== '' && tag !== 'button') {
2058
+ attrParts.push(`val="${String(el.value).slice(0, 40)}"`);
2059
+ }
2060
+ if (ctx.inIframe) attrParts.push('[iframe]');
2061
+ if (ctx.inShadow) attrParts.push('[shadow]');
2062
+
2063
+ let href = '';
2064
+ if (includeHrefs && tag === 'a') {
2065
+ const rawHref = (el.getAttribute('href') || '').trim();
2066
+ const lowHref = rawHref.toLowerCase();
2067
+ if (rawHref && rawHref !== '#' && !lowHref.startsWith('javascript:')) {
2068
+ href = el.href || rawHref;
2069
+ if (origin && href.startsWith(origin)) {
2070
+ href = href.slice(origin.length) || '/';
2071
+ }
2072
+ if (href.length > 80) href = href.slice(0, 77) + '...';
2073
+ }
2074
+ }
2075
+
2076
+ return {
2077
+ index: i,
2078
+ ref,
2079
+ tag,
2080
+ selector,
2081
+ text,
2082
+ href,
2083
+ attrs: attrParts.join(' '),
2084
+ };
2085
+ });
2086
+ return { totalMatched, totalCapped: totalMatched >= countCap, items };
2087
+ }"""
2088
+
2089
+ _EXTRACT_JS = r"""({ containerSelector, fields, limit, includeShadow, includeIframes }) => {
2090
+ const TEXT_MAX = 500;
2091
+ const HTML_MAX = 1500;
2092
+ const cap = (v, max) => {
2093
+ if (v === null || v === undefined) return null;
2094
+ const s = String(v);
2095
+ if (s.length > max) return s.slice(0, max) + '... [truncated]';
2096
+ return s;
2097
+ };
2098
+ const roots = [];
2099
+ const seen = new Set();
2100
+ const addRoot = (root) => {
2101
+ if (root && !seen.has(root)) {
2102
+ seen.add(root);
2103
+ roots.push(root);
2104
+ }
2105
+ };
2106
+ addRoot(document);
2107
+ if (includeIframes) {
2108
+ for (const f of document.querySelectorAll('iframe, frame')) {
2109
+ try {
2110
+ const d = f.contentDocument;
2111
+ if (d && d.documentElement) addRoot(d);
2112
+ } catch (_) {}
2113
+ }
2114
+ }
2115
+ let total = 0;
2116
+ const countIn = (root) => {
2117
+ try {
2118
+ total += root.querySelectorAll(containerSelector).length;
2119
+ } catch (_) {}
2120
+ if (!includeShadow) return;
2121
+ try {
2122
+ for (const el of root.querySelectorAll('*')) {
2123
+ if (el.shadowRoot) countIn(el.shadowRoot);
2124
+ }
2125
+ } catch (_) {}
2126
+ };
2127
+ for (const root of roots) countIn(root);
2128
+ const containers = [];
2129
+ const scan = (root) => {
2130
+ if (containers.length >= limit) return;
2131
+ try {
2132
+ for (const el of root.querySelectorAll(containerSelector)) {
2133
+ containers.push(el);
2134
+ if (containers.length >= limit) return;
2135
+ }
2136
+ } catch (_) {}
2137
+ if (!includeShadow) return;
2138
+ try {
2139
+ for (const el of root.querySelectorAll('*')) {
2140
+ if (el.shadowRoot) scan(el.shadowRoot);
2141
+ if (containers.length >= limit) return;
2142
+ }
2143
+ } catch (_) {}
2144
+ };
2145
+ if (total > 0) {
2146
+ for (const root of roots) {
2147
+ scan(root);
2148
+ if (containers.length >= limit) break;
2149
+ }
2150
+ }
2151
+ const rows = containers.map((c, i) => {
2152
+ const row = { _index: i };
2153
+ for (const [name, spec] of Object.entries(fields)) {
2154
+ let val = null;
2155
+ try {
2156
+ let el = c;
2157
+ if (spec.selector) el = c.querySelector(spec.selector);
2158
+ if (el) {
2159
+ if (spec.mode === 'attr') {
2160
+ val = cap(el.getAttribute(spec.attr), TEXT_MAX);
2161
+ } else if (spec.mode === 'html') {
2162
+ val = cap(el.outerHTML, HTML_MAX);
2163
+ } else if (spec.mode === 'inner_html') {
2164
+ val = cap(el.innerHTML, HTML_MAX);
2165
+ } else {
2166
+ val = cap((el.innerText !== undefined ? el.innerText : el.textContent) || '', TEXT_MAX);
2167
+ }
2168
+ }
2169
+ } catch (_) {
2170
+ val = null;
2171
+ }
2172
+ row[name] = val;
2173
+ }
2174
+ return row;
2175
+ });
2176
+ return { url: location.href, title: document.title, total_matched: total, returned: rows.length, rows };
2177
+ }"""
2178
+
2179
+ _JS_FIND_REF_HELPER = r"""const findByRef = (root, refId, visited) => {
2180
+ if (!root || visited.has(root)) return null;
2181
+ visited.add(root);
2182
+ const safe = String(refId).replace(/\\/g, '\\\\').replace(/"/g, '\\"');
2183
+ try {
2184
+ const direct = root.querySelector('[data-sb-ref="' + safe + '"]');
2185
+ if (direct) return direct;
2186
+ } catch (_) {}
2187
+ let all = [];
2188
+ try {
2189
+ all = root.querySelectorAll ? root.querySelectorAll('*') : [];
2190
+ } catch (_) {}
2191
+ for (const el of all) {
2192
+ if (el.shadowRoot) {
2193
+ const hit = findByRef(el.shadowRoot, refId, visited);
2194
+ if (hit) return hit;
2195
+ }
2196
+ const tn = (el.tagName || '').toUpperCase();
2197
+ if (tn === 'IFRAME' || tn === 'FRAME') {
2198
+ try {
2199
+ if (el.contentDocument) {
2200
+ const hit = findByRef(el.contentDocument, refId, visited);
2201
+ if (hit) return hit;
2202
+ }
2203
+ } catch (_) {}
2204
+ }
2205
+ }
2206
+ return null;
2207
+ };"""
2208
+
2209
+ _JS_CLICK_REF = "({ refId }) => {\n" + _JS_FIND_REF_HELPER + r"""
2210
+ const target = findByRef(document, refId, new Set());
2211
+ if (!target) return false;
2212
+ if (target.scrollIntoView) target.scrollIntoView({ block: 'center', inline: 'center' });
2213
+ target.click();
2214
+ return true;
2215
+ }"""
2216
+
2217
+ _JS_TYPE_REF = "({ refId, text, clearFirst, pressEnter }) => {\n" + _JS_FIND_REF_HELPER + r"""
2218
+ const target = findByRef(document, refId, new Set());
2219
+ if (!target) return false;
2220
+ if (target.scrollIntoView) target.scrollIntoView({ block: 'center', inline: 'center' });
2221
+ if (target.focus) target.focus();
2222
+ const nextVal = clearFirst ? String(text) : (String(target.value || '') + String(text));
2223
+ const win = (target.ownerDocument && target.ownerDocument.defaultView) || window;
2224
+ const proto = target.tagName === 'TEXTAREA'
2225
+ ? win.HTMLTextAreaElement && win.HTMLTextAreaElement.prototype
2226
+ : win.HTMLInputElement && win.HTMLInputElement.prototype;
2227
+ const desc = proto && Object.getOwnPropertyDescriptor(proto, 'value');
2228
+ if (desc && desc.set) {
2229
+ desc.set.call(target, nextVal);
2230
+ } else {
2231
+ target.value = nextVal;
2232
+ }
2233
+ target.dispatchEvent(new Event('input', { bubbles: true }));
2234
+ target.dispatchEvent(new Event('change', { bubbles: true }));
2235
+ if (pressEnter) {
2236
+ target.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', bubbles: true }));
2237
+ target.dispatchEvent(new KeyboardEvent('keyup', { key: 'Enter', code: 'Enter', bubbles: true }));
2238
+ }
2239
+ return true;
2240
+ }"""
2241
+
2242
+ _JS_ANNOTATE_OVERLAY = r"""() => {
2243
+ const existing = document.getElementById('__sb_annotation_overlay__');
2244
+ if (existing) existing.remove();
2245
+
2246
+ const entries = [];
2247
+ const collect = (root, ox, oy, visited) => {
2248
+ if (!root || visited.has(root)) return;
2249
+ visited.add(root);
2250
+ let refs = [];
2251
+ try {
2252
+ refs = root.querySelectorAll ? root.querySelectorAll('[data-sb-ref]') : [];
2253
+ } catch (_) {}
2254
+ for (const el of refs) {
2255
+ try {
2256
+ const rect = el.getBoundingClientRect();
2257
+ if (rect.width > 0 && rect.height > 0) {
2258
+ entries.push({
2259
+ ref: el.getAttribute('data-sb-ref') || '',
2260
+ left: rect.left + ox,
2261
+ top: rect.top + oy,
2262
+ width: rect.width,
2263
+ height: rect.height
2264
+ });
2265
+ }
2266
+ } catch (_) {}
2267
+ }
2268
+ let all = [];
2269
+ try {
2270
+ all = root.querySelectorAll ? root.querySelectorAll('*') : [];
2271
+ } catch (_) {}
2272
+ for (const el of all) {
2273
+ if (el.shadowRoot) collect(el.shadowRoot, ox, oy, visited);
2274
+ const tn = (el.tagName || '').toUpperCase();
2275
+ if (tn === 'IFRAME' || tn === 'FRAME') {
2276
+ try {
2277
+ if (el.contentDocument) {
2278
+ const ir = el.getBoundingClientRect();
2279
+ collect(el.contentDocument, ox + ir.left, oy + ir.top, visited);
2280
+ }
2281
+ } catch (_) {}
2282
+ }
2283
+ }
2284
+ };
2285
+
2286
+ collect(document, window.scrollX || 0, window.scrollY || 0, new Set());
2287
+ if (entries.length === 0) return 0;
2288
+
2289
+ const container = document.createElement('div');
2290
+ container.id = '__sb_annotation_overlay__';
2291
+ container.style.cssText = 'position:absolute;top:0;left:0;width:0;height:0;pointer-events:none;z-index:2147483647;';
2292
+
2293
+ for (const item of entries) {
2294
+ const box = document.createElement('div');
2295
+ box.style.cssText = `position:absolute;left:${item.left}px;top:${item.top}px;width:${item.width}px;height:${item.height}px;border:2px solid #e11d48;box-sizing:border-box;pointer-events:none;`;
2296
+ const label = document.createElement('span');
2297
+ label.textContent = item.ref;
2298
+ const labelTop = item.top < 16 ? '0px' : '-16px';
2299
+ label.style.cssText = `position:absolute;left:-2px;top:${labelTop};background:#e11d48;color:#ffffff;font:bold 11px/14px monospace;padding:0 4px;border-radius:2px;white-space:nowrap;pointer-events:none;`;
2300
+ box.appendChild(label);
2301
+ container.appendChild(box);
2302
+ }
2303
+
2304
+ (document.body || document.documentElement).appendChild(container);
2305
+ return entries.length;
2306
+ }"""
2307
+
2308
+ _JS_REMOVE_OVERLAY = "() => { const el = document.getElementById('__sb_annotation_overlay__'); if (el) el.remove(); }"
2309
+
2310
+
2311
+ def _normalize_ref(ref: str) -> str:
2312
+ r = (ref or "").strip()
2313
+ if r.startswith("@"):
2314
+ r = r[1:].strip()
2315
+ return r
2316
+
2317
+
2318
+ def _ref_to_selector(ref_id: str) -> str:
2319
+ escaped = ref_id.replace("\\", "\\\\").replace('"', '\\"')
2320
+ return f'[data-sb-ref="{escaped}"]'
2321
+
2322
+
2323
+ def _secondary_frames(page: Page) -> list:
2324
+ frames = getattr(page, "frames", None) or []
2325
+ main_frame = getattr(page, "main_frame", None)
2326
+ return [f for f in frames if f is not main_frame]
2327
+
2328
+
2329
+ async def _locator_has_match(loc) -> bool:
2330
+ try:
2331
+ cnt = await loc.count()
2332
+ return isinstance(cnt, int) and cnt > 0
2333
+ except Exception:
2334
+ return False
2335
+
2336
+
2337
+ async def _first_visible_locator(loc):
2338
+ try:
2339
+ cnt = await loc.count()
2340
+ except Exception:
2341
+ return None
2342
+ if not isinstance(cnt, int) or cnt <= 0:
2343
+ return None
2344
+ if cnt == 1:
2345
+ first = loc.first
2346
+ try:
2347
+ vis = await first.is_visible()
2348
+ if isinstance(vis, bool) and not vis:
2349
+ return None
2350
+ except Exception:
2351
+ pass
2352
+ return first
2353
+ for idx in range(min(cnt, 10)):
2354
+ item = loc.nth(idx)
2355
+ try:
2356
+ vis = await item.is_visible()
2357
+ if not isinstance(vis, bool) or vis:
2358
+ return item
2359
+ except Exception:
2360
+ return item
2361
+ return None
2362
+
2363
+
2364
+ async def _resolve_locator(page: Page, selector: str = "", ref: str = "", text: str = "") -> tuple:
2365
+ ref_id = _normalize_ref(ref)
2366
+ if not ref_id and selector:
2367
+ m = _SB_REF_SELECTOR_RE.match(selector.strip())
2368
+ if m:
2369
+ ref_id = m.group(1)
2370
+
2371
+ if ref_id:
2372
+ ref_sel = _ref_to_selector(ref_id)
2373
+ label = f"ref '{ref_id}'" if ref else f"'{selector}'"
2374
+ main_loc = page.locator(ref_sel)
2375
+ if await _locator_has_match(main_loc):
2376
+ return main_loc.first, label, ref_id, True
2377
+ for frame in _secondary_frames(page):
2378
+ try:
2379
+ floc = frame.locator(ref_sel)
2380
+ if await _locator_has_match(floc):
2381
+ return floc.first, label, ref_id, True
2382
+ except Exception:
2383
+ continue
2384
+ return main_loc.first, label, ref_id, False
2385
+
2386
+ if selector:
2387
+ return page.locator(selector).first, f"'{selector}'", "", True
2388
+
2389
+ if text:
2390
+ label = f"text '{text}'"
2391
+ scopes = [page] + _secondary_frames(page)
2392
+ for scope in scopes:
2393
+ if hasattr(scope, "get_by_role"):
2394
+ for role in ("button", "link", "tab", "menuitem", "option"):
2395
+ try:
2396
+ cand = await _first_visible_locator(scope.get_by_role(role, name=text))
2397
+ if cand is not None:
2398
+ return cand, label, "", True
2399
+ except Exception:
2400
+ continue
2401
+ if hasattr(scope, "get_by_text"):
2402
+ try:
2403
+ cand = await _first_visible_locator(scope.get_by_text(text))
2404
+ if cand is not None:
2405
+ return cand, label, "", True
2406
+ except Exception:
2407
+ continue
2408
+ return page.get_by_text(text).first, label, "", False
2409
+
2410
+ return None, "", "", False
2411
+
2412
+
2413
+ async def _js_click_ref(page: Page, ref_id: str) -> bool:
2414
+ try:
2415
+ return bool(await asyncio.wait_for(page.evaluate(_JS_CLICK_REF, {"refId": ref_id}), timeout=5.0))
2416
+ except Exception:
2417
+ return False
2418
+
2419
+
2420
+ async def _js_type_ref(page: Page, ref_id: str, text: str, clear_first: bool = True, press_enter: bool = False) -> bool:
2421
+ try:
2422
+ return bool(
2423
+ await asyncio.wait_for(
2424
+ page.evaluate(
2425
+ _JS_TYPE_REF,
2426
+ {"refId": ref_id, "text": text, "clearFirst": clear_first, "pressEnter": press_enter},
2427
+ ),
2428
+ timeout=5.0,
2429
+ )
2430
+ )
2431
+ except Exception:
2432
+ return False
2433
+
2434
+
2435
+ def _format_snapshot_row(el: dict, fallback_idx: int, include_hrefs: bool = False) -> str:
2436
+ ref = el.get("ref") or f"e{el.get('index', fallback_idx)}"
2437
+ tag = el.get("tag", "")
2438
+ sel = str(el.get("selector", "")).strip()
2439
+ text = " ".join(str(el.get("text", "")).split())
2440
+ attrs_raw = " ".join(str(el.get("attrs", "")).split())
2441
+ href = " ".join(str(el.get("href", "") or "").split()) if include_hrefs else ""
2442
+
2443
+ show_sel = bool(sel) and sel != tag and not _SB_REF_SELECTOR_RE.match(sel)
2444
+ if show_sel and attrs_raw:
2445
+ dedup_tokens = [tok for tok in attrs_raw.split(" ") if tok and tok != sel]
2446
+ attrs_raw = " ".join(dedup_tokens)
2447
+
2448
+ if href:
2449
+ if len(href) > 80:
2450
+ href = href[:77] + "..."
2451
+ href_part = f"href={href}"
2452
+ attrs_raw = f"{attrs_raw} {href_part}".strip() if attrs_raw else href_part
2453
+
2454
+ parts = [f"[{ref}]", f"<{tag}>"]
2455
+ if show_sel:
2456
+ parts.append(sel)
2457
+ if text:
2458
+ parts.append(f'"{text}"')
2459
+ if attrs_raw:
2460
+ parts.append(f"({attrs_raw})")
2461
+ return " ".join(parts)
2462
+
2463
+
2464
+ @mcp.tool()
2465
+ @_with_tool_deadline
2466
+ async def snapshot(
2467
+ selector: str = "body",
2468
+ max_elements: int = 80,
2469
+ tab: Union[int, str] = -1,
2470
+ include_shadow: bool = True,
2471
+ include_iframes: bool = True,
2472
+ include_hrefs: bool = False,
2473
+ filter: str = "",
2474
+ viewport_only: bool = False,
2475
+ max_length: int = _DEFAULT_OUTPUT_MAX_CHARS,
2476
+ ) -> str:
2477
+ """List visible interactive elements with refs (e0, e1, ...) across DOM, Shadow DOM, and same-origin iframes. Use filter/viewport_only to narrow; include_hrefs=True to show link URLs."""
2478
+ t0 = time.perf_counter()
2479
+ try:
2480
+ page = await session.resolve_page(tab)
2481
+ try:
2482
+ raw = await asyncio.wait_for(
2483
+ page.evaluate(
2484
+ _SNAPSHOT_JS,
2485
+ {
2486
+ "targetSelector": selector,
2487
+ "maxElements": max_elements,
2488
+ "includeShadow": include_shadow,
2489
+ "includeIframes": include_iframes,
2490
+ "includeHrefs": include_hrefs,
2491
+ "filter": filter,
2492
+ "viewportOnly": viewport_only,
2493
+ },
2494
+ ),
2495
+ timeout=10.0,
2496
+ )
2497
+ except asyncio.TimeoutError:
2498
+ return "Error capturing snapshot: Timed out after 10000ms"
2499
+ elapsed_ms = int((time.perf_counter() - t0) * 1000)
2500
+
2501
+ if isinstance(raw, dict):
2502
+ elements = raw.get("items") or []
2503
+ total_matched = int(raw.get("totalMatched", len(elements)))
2504
+ total_capped = bool(raw.get("totalCapped", False))
2505
+ else:
2506
+ elements = raw or []
2507
+ total_matched = len(elements)
2508
+ total_capped = False
2509
+
2510
+ url_str = _truncate_url(page.url, 160)
2511
+ if not elements:
2512
+ filter_note = f" matching '{filter}'" if filter else ""
2513
+ return f"No interactive elements found{filter_note} on {url_str} ({elapsed_ms}ms)"
2514
+
2515
+ elements = elements[:max_elements]
2516
+ rows = [_format_snapshot_row(el, idx, include_hrefs=include_hrefs) for idx, el in enumerate(elements)]
2517
+ total_label = f"{total_matched}+" if total_capped else str(total_matched)
2518
+ footer = "... [narrow with selector=, filter=, or viewport_only=True]"
2519
+
2520
+ if max_length > 0:
2521
+ kept: list[str] = []
2522
+ header_reserve = len(f"Snapshot {url_str} ({elapsed_ms}ms, showing {len(rows)} of {total_label} items):") + len(footer) + 2
2523
+ budget = max(120, max_length - header_reserve)
2524
+ cur = 0
2525
+ for row in rows:
2526
+ if kept and cur + len(row) + 1 > budget:
2527
+ break
2528
+ kept.append(row)
2529
+ cur += len(row) + 1
2530
+ rows = kept
2531
+
2532
+ shown = len(rows)
2533
+ is_partial = shown < total_matched or total_capped
2534
+ count_str = f"showing {shown} of {total_label} items" if is_partial else f"{shown} items"
2535
+ header = f"Snapshot {url_str} ({elapsed_ms}ms, {count_str}):"
2536
+ lines = [header] + rows
2537
+ if is_partial:
2538
+ lines.append(footer)
2539
+ return "\n".join(lines)
2540
+ except Exception as exc:
2541
+ return f"Error capturing snapshot: {_format_playwright_error(exc)}"
2542
+
2543
+
2544
+ @mcp.tool()
2545
+ @_with_tool_deadline
2546
+ async def batch(actions: list[dict], tab: Union[int, str] = -1) -> str:
2547
+ """Run sequential actions in one turn. Valid actions: click, fill, type, select, press, wait_for, sleep, evaluate (fields: selector, ref, text, value, key, state, ms, force, expression, main_world, timeout_ms)."""
2548
+ t0 = time.perf_counter()
2549
+ try:
2550
+ page = await session.resolve_page(tab)
2551
+ before_url = getattr(page, "url", "") or ""
2552
+ before_dialogs = len(getattr(page, "_dialog_history", None) or ())
2553
+ results = []
2554
+ for idx, item in enumerate(actions):
2555
+ act = item.get("action", "").lower()
2556
+ timeout = item.get("timeout_ms", 4000)
2557
+ sel = (item.get("selector") or "").strip()
2558
+ ref = _normalize_ref(item.get("ref") or "")
2559
+ force = bool(item.get("force", False))
2560
+
2561
+ if act == "click":
2562
+ text_target = item.get("text") or ""
2563
+ if not (sel or ref or text_target):
2564
+ results.append(f"[{idx}] click: SKIPPED (missing 'selector', 'ref', or 'text')")
2565
+ continue
2566
+ loc, label, ref_id, matched = await _resolve_locator(page, selector=sel, ref=ref, text=text_target)
2567
+ try:
2568
+ if force:
2569
+ try:
2570
+ el = await asyncio.wait_for(loc.first.element_handle(), timeout=max(1.0, timeout / 1000.0))
2571
+ if el is not None:
2572
+ await el.evaluate("el => el.click()")
2573
+ else:
2574
+ await loc.click(timeout=timeout, force=True)
2575
+ except Exception:
2576
+ await loc.click(timeout=timeout, force=True)
2577
+ else:
2578
+ await loc.click(timeout=timeout)
2579
+ except Exception:
2580
+ if ref_id and (not matched or force) and await _js_click_ref(page, ref_id):
2581
+ pass
2582
+ else:
2583
+ raise
2584
+ force_tag = " (force)" if force else ""
2585
+ results.append(f"[{idx}] click {label}{force_tag}: OK")
2586
+
2587
+ elif act == "fill":
2588
+ if not (sel or ref):
2589
+ results.append(f"[{idx}] fill: SKIPPED (missing 'selector' or 'ref')")
2590
+ continue
2591
+ text_val = str(item.get("text") if item.get("text") is not None else item.get("value", ""))
2592
+ loc, label, ref_id, matched = await _resolve_locator(page, selector=sel, ref=ref)
2593
+ try:
2594
+ await loc.fill(text_val, timeout=timeout, force=force)
2595
+ except Exception:
2596
+ if ref_id and (not matched or force) and await _js_type_ref(page, ref_id, text_val, clear_first=True, press_enter=False):
2597
+ pass
2598
+ else:
2599
+ raise
2600
+ results.append(f"[{idx}] fill {label}: OK")
2601
+
2602
+ elif act == "type":
2603
+ if not (sel or ref):
2604
+ results.append(f"[{idx}] type: SKIPPED (missing 'selector' or 'ref')")
2605
+ continue
2606
+ text_val = str(item.get("text") if item.get("text") is not None else item.get("value", ""))
2607
+ press_enter = bool(item.get("press_enter", False))
2608
+ loc, label, ref_id, matched = await _resolve_locator(page, selector=sel, ref=ref)
2609
+ try:
2610
+ if force:
2611
+ await loc.click(timeout=timeout, force=True)
2612
+ await loc.type(text_val, timeout=timeout)
2613
+ if press_enter:
2614
+ await loc.press("Enter")
2615
+ except Exception:
2616
+ if ref_id and (not matched or force) and await _js_type_ref(page, ref_id, text_val, clear_first=False, press_enter=press_enter):
2617
+ pass
2618
+ else:
2619
+ raise
2620
+ results.append(f"[{idx}] type {label} ({'with Enter' if press_enter else ''}): OK")
2621
+
2622
+ elif act == "select":
2623
+ if not (sel or ref):
2624
+ results.append(f"[{idx}] select: SKIPPED (missing 'selector' or 'ref')")
2625
+ continue
2626
+ val = str(item.get("value") if item.get("value") is not None else item.get("text", ""))
2627
+ loc, label, _, _ = await _resolve_locator(page, selector=sel, ref=ref)
2628
+ await loc.select_option(val, timeout=timeout, force=force)
2629
+ results.append(f"[{idx}] select {label} option '{val}': OK")
2630
+
2631
+ elif act == "press":
2632
+ key = item.get("key") or item.get("button", "Enter")
2633
+ await page.keyboard.press(key)
2634
+ results.append(f"[{idx}] press '{key}': OK")
2635
+
2636
+ elif act == "wait_for":
2637
+ if not (sel or ref):
2638
+ results.append(f"[{idx}] wait_for: SKIPPED (missing 'selector' or 'ref')")
2639
+ continue
2640
+ state = item.get("state", "visible")
2641
+ loc, label, _, _ = await _resolve_locator(page, selector=sel, ref=ref)
2642
+ await loc.wait_for(state=state, timeout=timeout)
2643
+ results.append(f"[{idx}] wait_for {label} ({state}): OK")
2644
+
2645
+ elif act == "sleep":
2646
+ ms = item.get("ms") or item.get("duration_ms", 200)
2647
+ await asyncio.sleep(ms / 1000.0)
2648
+ results.append(f"[{idx}] sleep {ms}ms: OK")
2649
+
2650
+ elif act == "evaluate":
2651
+ expr = item.get("expression") or item.get("code") or item.get("js", "")
2652
+ main_world = bool(item.get("main_world", False))
2653
+ res = await asyncio.wait_for(
2654
+ page.evaluate(expr, isolated_context=not main_world),
2655
+ timeout=timeout / 1000.0,
2656
+ )
2657
+ res_str = _compact_json(res) if isinstance(res, (dict, list)) else str(res)
2658
+ res_str = _truncate_text(res_str, _BATCH_EVAL_MAX_CHARS)
2659
+ results.append(f"[{idx}] evaluate: {res_str}")
2660
+
2661
+ else:
2662
+ results.append(f"[{idx}] Unknown action '{act}': SKIPPED")
2663
+
2664
+ elapsed = int((time.perf_counter() - t0) * 1000)
2665
+ delta = _action_delta_suffix(page, before_url, before_dialogs)
2666
+ out = f"Batch completed ({len(results)} steps in {elapsed}ms) on {page.url}{delta}:\n" + "\n".join(results)
2667
+ return _truncate_text(out, _BATCH_TOTAL_MAX_CHARS)
2668
+ except Exception as exc:
2669
+ elapsed = int((time.perf_counter() - t0) * 1000)
2670
+ return f"Batch failed after {elapsed}ms: {_format_playwright_error(exc)}"
2671
+
2672
+
2673
+ _GET_CONTENT_CLEAN_JS = r"""({ sel }) => {
2674
+ const el = document.querySelector(sel);
2675
+ if (!el) return '';
2676
+ const JUNK_SEL = 'script, style, svg, noscript, nav, header, footer, [role="banner"], [role="navigation"], [aria-hidden="true"], .cookie-banner, .cookie-consent, #cookie-banner, .advertisement, .ad-banner';
2677
+ const BLOCK_DISPLAY = new Set(['block', 'flex', 'grid', 'list-item', 'table', 'table-row', 'table-caption', 'flow-root']);
2678
+ const parts = [];
2679
+ const walk = (node) => {
2680
+ if (!node) return;
2681
+ if (node.nodeType === 3) {
2682
+ const t = (node.nodeValue || '').replace(/[\t\r\n ]+/g, ' ');
2683
+ if (t.trim()) {
2684
+ parts.push(t);
2685
+ } else if (t && parts.length && !parts[parts.length - 1].endsWith('\n') && !parts[parts.length - 1].endsWith(' ')) {
2686
+ parts.push(' ');
2687
+ }
2688
+ return;
2689
+ }
2690
+ if (node.nodeType !== 1) return;
2691
+ if (node !== el) {
2692
+ if (node.hidden) return;
2693
+ try { if (node.matches && node.matches(JUNK_SEL)) return; } catch (_) {}
2694
+ try {
2695
+ const cs = window.getComputedStyle(node);
2696
+ if (!cs || cs.display === 'none' || cs.visibility === 'hidden') return;
2697
+ } catch (_) {}
2698
+ }
2699
+ const tag = (node.tagName || '').toUpperCase();
2700
+ if (tag === 'BR') {
2701
+ parts.push('\n');
2702
+ return;
2703
+ }
2704
+ let isBlock = false;
2705
+ try {
2706
+ const cs = window.getComputedStyle(node);
2707
+ if (cs && BLOCK_DISPLAY.has(cs.display)) isBlock = true;
2708
+ } catch (_) {}
2709
+ if (isBlock && parts.length && !parts[parts.length - 1].endsWith('\n')) parts.push('\n');
2710
+ for (const child of node.childNodes) walk(child);
2711
+ if (isBlock && parts.length && !parts[parts.length - 1].endsWith('\n')) parts.push('\n');
2712
+ };
2713
+ walk(el);
2714
+ return parts.join('')
2715
+ .split('\n')
2716
+ .map((l) => l.replace(/[ \t]+/g, ' ').trim())
2717
+ .join('\n')
2718
+ .replace(/\n{3,}/g, '\n\n')
2719
+ .trim();
2720
+ }"""
2721
+
2722
+
2723
+ def _filter_content_lines(text: str, pattern: str) -> Optional[str]:
2724
+ lines = text.splitlines()
2725
+ try:
2726
+ rx = re.compile(pattern, re.IGNORECASE)
2727
+ except re.error:
2728
+ rx = re.compile(re.escape(pattern), re.IGNORECASE)
2729
+ matched_indices = [i for i, ln in enumerate(lines) if rx.search(ln)]
2730
+ if not matched_indices:
2731
+ return None
2732
+ keep: set[int] = set()
2733
+ for idx in matched_indices:
2734
+ for j in range(max(0, idx - 1), min(len(lines), idx + 2)):
2735
+ keep.add(j)
2736
+ out: list[str] = []
2737
+ prev = -2
2738
+ for idx in sorted(keep):
2739
+ if prev >= 0 and idx > prev + 1:
2740
+ out.append("--")
2741
+ out.append(lines[idx])
2742
+ prev = idx
2743
+ return "\n".join(out)
2744
+
2745
+
2746
+ @mcp.tool()
2747
+ @_with_tool_deadline
2748
+ async def get_content(
2749
+ selector: str = "body",
2750
+ max_length: int = 4000,
2751
+ interactive_only: bool = False,
2752
+ clean: bool = True,
2753
+ tab: Union[int, str] = -1,
2754
+ offset: int = 0,
2755
+ filter: str = "",
2756
+ ) -> str:
2757
+ """Extract visible text from a tab. Supports offset (negative for tail, e.g. -3000), filter (regex/substring with context), clean=True (strips nav/hidden/whitespace), or interactive_only=True (calls snapshot)."""
2758
+ try:
2759
+ if interactive_only:
2760
+ return await snapshot(selector=selector, tab=tab, filter=filter)
2761
+
2762
+ page = await session.resolve_page(tab)
2763
+ element = page.locator(selector).first
2764
+ if await element.count() == 0:
2765
+ return f"Element '{selector}' not found on page {page.url}"
2766
+
2767
+ if clean:
2768
+ text = await asyncio.wait_for(page.evaluate(_GET_CONTENT_CLEAN_JS, {"sel": selector}), timeout=10.0)
2769
+ text = "\n".join(re.sub(r"[ \t]+", " ", ln).strip() for ln in str(text or "").splitlines())
2770
+ text = re.sub(r"\n{3,}", "\n\n", text).strip()
2771
+ else:
2772
+ text = str(await asyncio.wait_for(element.inner_text(), timeout=10.0) or "").strip()
2773
+
2774
+ if not text:
2775
+ return "(Page element contains no visible text)"
2776
+
2777
+ filter_clean = (filter or "").strip()
2778
+ if filter_clean:
2779
+ filtered = _filter_content_lines(text, filter_clean)
2780
+ if filtered is None:
2781
+ return f"No lines matched filter '{filter_clean}' in '{selector}' on {page.url} ({len(text)} total chars)"
2782
+ text = filtered
2783
+
2784
+ total_len = len(text)
2785
+ if offset > 0 and offset >= total_len:
2786
+ return f"Offset {offset} is past end of content ({total_len} total chars)."
2787
+ start = max(0, total_len + offset) if offset < 0 else offset
2788
+ end = min(total_len, start + max_length) if max_length > 0 else total_len
2789
+ if start > 0 or end < total_len:
2790
+ chunk = text[start:end]
2791
+ tail_note = f"\n... (truncated; pass offset={end} for next chunk)" if end < total_len else ""
2792
+ return f"[Showing chars {start}-{end} of {total_len}]:\n{chunk}{tail_note}"
2793
+ return text
2794
+ except Exception as exc:
2795
+ return f"Error extracting content: {_format_playwright_error(exc)}"
2796
+
2797
+
2798
+ _EXTRACT_MAX_FIELDS = 12
2799
+ _EXTRACT_MAX_LIMIT = 200
2800
+
2801
+
2802
+ def _normalize_extract_fields(fields) -> Optional[dict[str, dict[str, str]]]:
2803
+ if not isinstance(fields, dict) or not fields:
2804
+ return None
2805
+ if len(fields) > _EXTRACT_MAX_FIELDS:
2806
+ return None
2807
+ normalized: dict[str, dict[str, str]] = {}
2808
+ for name, spec in fields.items():
2809
+ key = str(name).strip()
2810
+ if not key or len(key) > 64:
2811
+ return None
2812
+ mode, selector, attr = "text", "", ""
2813
+ if isinstance(spec, dict):
2814
+ mode = str(spec.get("mode") or "text").strip().lower()
2815
+ selector = str(spec.get("selector") or "").strip()
2816
+ attr = str(spec.get("attr") or "").strip()
2817
+ elif isinstance(spec, str) and spec.strip():
2818
+ raw = spec.strip()
2819
+ head, sep, tail = raw.partition(" ")
2820
+ head_l = head.strip().lower()
2821
+ if sep and head_l in ("text", "html", "inner_html"):
2822
+ mode, selector = head_l, tail.strip()
2823
+ elif sep and head_l.startswith("@") and len(head_l) > 1:
2824
+ mode, attr, selector = "attr", head_l[1:], tail.strip()
2825
+ else:
2826
+ m = re.match(r"^(text|html|inner_html):(.+)$", raw)
2827
+ if m:
2828
+ mode, selector = m.group(1), m.group(2).strip()
2829
+ elif re.match(r"^@([\w.-]+)$", raw):
2830
+ mode, attr = "attr", raw[1:]
2831
+ elif raw in ("text", "html", "inner_html"):
2832
+ mode = raw
2833
+ else:
2834
+ mode, selector = "text", raw
2835
+ else:
2836
+ return None
2837
+ if mode not in ("text", "attr", "html", "inner_html"):
2838
+ return None
2839
+ if mode == "attr" and not attr:
2840
+ return None
2841
+ normalized[key] = {"mode": mode, "selector": selector, "attr": attr}
2842
+ return normalized
2843
+
2844
+
2845
+ @mcp.tool()
2846
+ @_with_tool_deadline
2847
+ async def extract(
2848
+ container_selector: str,
2849
+ fields: dict[str, Union[str, dict]],
2850
+ limit: int = 20,
2851
+ include_shadow: bool = True,
2852
+ include_iframes: bool = True,
2853
+ tab: Union[int, str] = -1,
2854
+ max_length: int = _DEFAULT_OUTPUT_MAX_CHARS,
2855
+ ) -> str:
2856
+ """Extract structured JSON rows from repeated containers (cards, tables) across DOM/Shadow/iframes. fields maps name -> 'text:.sel' | '@attr .sel' | 'html:.sel' | {selector, mode, attr} (max 12 fields, limit<=200)."""
2857
+ t0 = time.perf_counter()
2858
+ try:
2859
+ normalized = _normalize_extract_fields(fields)
2860
+ if normalized is None:
2861
+ return (
2862
+ "Error extracting rows: 'fields' must be a non-empty map of at most "
2863
+ f"{_EXTRACT_MAX_FIELDS} field names to a spec string (e.g. '.title', 'text:.title', '@href a.link', "
2864
+ "'html:.thumb') or {'selector': ..., 'mode': 'text'|'attr'|'html'|'inner_html', 'attr': ...}."
2865
+ )
2866
+ limit = min(max(1, int(limit)), _EXTRACT_MAX_LIMIT)
2867
+ container_selector = (container_selector or "").strip()
2868
+ if not container_selector:
2869
+ return "Error extracting rows: 'container_selector' must be non-empty."
2870
+ page = await session.resolve_page(tab)
2871
+ result = await asyncio.wait_for(
2872
+ page.evaluate(
2873
+ _EXTRACT_JS,
2874
+ {
2875
+ "containerSelector": container_selector,
2876
+ "fields": normalized,
2877
+ "limit": limit,
2878
+ "includeShadow": include_shadow,
2879
+ "includeIframes": include_iframes,
2880
+ },
2881
+ ),
2882
+ timeout=15.0,
2883
+ )
2884
+ elapsed_ms = int((time.perf_counter() - t0) * 1000)
2885
+ if not isinstance(result, dict) or "rows" not in result:
2886
+ return f"Error extracting rows: unexpected result from page ({result.__class__.__name__})."
2887
+ if not result["rows"]:
2888
+ return (
2889
+ f"No elements matched '{container_selector}' on {page.url} "
2890
+ f"({elapsed_ms}ms, total_matched={result.get('total_matched', 0)})."
2891
+ )
2892
+ formatted = _truncate_text(_compact_json(result), max_length)
2893
+ return f"Extracted {result['returned']} row(s) from '{container_selector}' ({elapsed_ms}ms):\n{formatted}"
2894
+ except asyncio.TimeoutError:
2895
+ return "Error extracting rows: Timed out after 15000ms"
2896
+ except Exception as exc:
2897
+ return f"Error extracting rows: {_format_playwright_error(exc)}"
2898
+
2899
+
2900
+ @mcp.tool()
2901
+ @_with_tool_deadline
2902
+ async def click(
2903
+ selector: str = "",
2904
+ ref: str = "",
2905
+ text: str = "",
2906
+ force: bool = False,
2907
+ tab: Union[int, str] = -1,
2908
+ timeout_ms: int = 5000,
2909
+ ) -> str:
2910
+ """Click an element by CSS selector, snapshot ref ('e12' or '@e12'), or visible text. Set force=True to bypass pointer-interception overlays."""
2911
+ sel_clean = (selector or "").strip()
2912
+ ref_clean = _normalize_ref(ref)
2913
+ if not (sel_clean or ref_clean or text):
2914
+ return "Error clicking element: provide at least one of 'selector', 'ref', or 'text'"
2915
+ label = f"ref '{ref_clean}'" if ref_clean else (f"'{sel_clean}'" if sel_clean else f"text '{text}'")
2916
+ try:
2917
+ page = await session.resolve_page(tab)
2918
+ before_url = getattr(page, "url", "") or ""
2919
+ before_dialogs = len(getattr(page, "_dialog_history", None) or ())
2920
+ locator, label, ref_id, matched = await _resolve_locator(page, selector=sel_clean, ref=ref_clean, text=text)
2921
+ try:
2922
+ if force:
2923
+ try:
2924
+ el = await asyncio.wait_for(locator.first.element_handle(), timeout=max(1.0, timeout_ms / 1000.0))
2925
+ if el is not None:
2926
+ await el.evaluate("el => el.click()")
2927
+ else:
2928
+ await locator.click(timeout=timeout_ms, force=True)
2929
+ except Exception:
2930
+ await locator.click(timeout=timeout_ms, force=True)
2931
+ else:
2932
+ await locator.click(timeout=timeout_ms)
2933
+ except Exception:
2934
+ if ref_id and (not matched or force) and await _js_click_ref(page, ref_id):
2935
+ pass
2936
+ else:
2937
+ raise
2938
+ force_tag = " (force)" if force else ""
2939
+ delta = _action_delta_suffix(page, before_url, before_dialogs)
2940
+ return f"Clicked element matching {label}{force_tag} on {page.url}{delta}"
2941
+ except Exception as exc:
2942
+ return f"Error clicking element {label}: {_format_playwright_error(exc)}"
2943
+
2944
+
2945
+ @mcp.tool()
2946
+ @_with_tool_deadline
2947
+ async def type(
2948
+ selector: str = "",
2949
+ text: str = "",
2950
+ clear_first: bool = True,
2951
+ press_enter: bool = False,
2952
+ tab: Union[int, str] = -1,
2953
+ timeout_ms: int = 5000,
2954
+ ref: str = "",
2955
+ ) -> str:
2956
+ """Type text into an input/textarea by CSS selector or snapshot ref ('e3' or '@e3')."""
2957
+ sel_clean = (selector or "").strip()
2958
+ ref_clean = _normalize_ref(ref)
2959
+ if not (sel_clean or ref_clean):
2960
+ return "Error typing: provide either 'selector' or 'ref'"
2961
+ label = f"ref '{ref_clean}'" if ref_clean else f"'{sel_clean}'"
2962
+ try:
2963
+ page = await session.resolve_page(tab)
2964
+ before_url = getattr(page, "url", "") or ""
2965
+ before_dialogs = len(getattr(page, "_dialog_history", None) or ())
2966
+ locator, label, ref_id, matched = await _resolve_locator(page, selector=sel_clean, ref=ref_clean)
2967
+ try:
2968
+ if clear_first:
2969
+ await locator.fill(text, timeout=timeout_ms)
2970
+ else:
2971
+ await locator.type(text, timeout=timeout_ms)
2972
+ if press_enter:
2973
+ await locator.press("Enter")
2974
+ except Exception:
2975
+ if ref_id and not matched and await _js_type_ref(page, ref_id, text, clear_first=clear_first, press_enter=press_enter):
2976
+ pass
2977
+ else:
2978
+ raise
2979
+
2980
+ delta = _action_delta_suffix(page, before_url, before_dialogs)
2981
+ if press_enter:
2982
+ return f"Typed text into {label} and pressed Enter{delta}"
2983
+ return f"Typed text into {label}{delta}"
2984
+ except Exception as exc:
2985
+ return f"Error typing into {label}: {_format_playwright_error(exc)}"
2986
+
2987
+
2988
+ @mcp.tool()
2989
+ @_with_tool_deadline
2990
+ async def press_key(key: str, tab: Union[int, str] = -1) -> str:
2991
+ """Press a keyboard key (e.g., 'Enter', 'Tab', 'Escape')."""
2992
+ try:
2993
+ page = await session.resolve_page(tab)
2994
+ before_url = getattr(page, "url", "") or ""
2995
+ before_dialogs = len(getattr(page, "_dialog_history", None) or ())
2996
+ await page.keyboard.press(key)
2997
+ delta = _action_delta_suffix(page, before_url, before_dialogs)
2998
+ return f"Pressed key '{key}' on {page.url}{delta}"
2999
+ except Exception as exc:
3000
+ return f"Error pressing key '{key}': {_format_playwright_error(exc)}"
3001
+
3002
+
3003
+ @mcp.tool()
3004
+ @_with_tool_deadline
3005
+ async def scroll(direction: str = "down", amount: int = 600, tab: Union[int, str] = -1) -> str:
3006
+ """Scroll up or down by amount pixels."""
3007
+ try:
3008
+ page = await session.resolve_page(tab)
3009
+ delta = amount if direction.lower() == "down" else -amount
3010
+ await page.mouse.wheel(0, delta)
3011
+ return f"Scrolled {direction} by {amount}px"
3012
+ except Exception as exc:
3013
+ return f"Error scrolling: {_format_playwright_error(exc)}"
3014
+
3015
+
3016
+ @mcp.tool()
3017
+ @_with_tool_deadline
3018
+ async def screenshot(
3019
+ save_path: str = "",
3020
+ tab: Union[int, str] = -1,
3021
+ full_page: bool = False,
3022
+ selector: str = "",
3023
+ ref: str = "",
3024
+ annotate: bool = False,
3025
+ ) -> str:
3026
+ """Capture a screenshot of the active page, full page, or a specific element (by selector or snapshot ref). Set annotate=True to temporarily overlay snapshot ref labels (e0, e1, ...)."""
3027
+ try:
3028
+ page = await session.resolve_page(tab)
3029
+ if not save_path:
3030
+ timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
3031
+ save_path = f"/tmp/screenshot_{timestamp}.png"
3032
+
3033
+ sel_clean = (selector or "").strip()
3034
+ ref_clean = _normalize_ref(ref)
3035
+ annotated_count = 0
3036
+ try:
3037
+ if annotate:
3038
+ annotated_count = int(await asyncio.wait_for(page.evaluate(_JS_ANNOTATE_OVERLAY), timeout=10.0) or 0)
3039
+ if annotated_count == 0:
3040
+ await snapshot(tab=tab)
3041
+ annotated_count = int(await asyncio.wait_for(page.evaluate(_JS_ANNOTATE_OVERLAY), timeout=10.0) or 0)
3042
+
3043
+ if sel_clean or ref_clean:
3044
+ locator, _, _, _ = await _resolve_locator(page, selector=sel_clean, ref=ref_clean)
3045
+ await locator.screenshot(path=save_path)
3046
+ else:
3047
+ await page.screenshot(path=save_path, full_page=full_page)
3048
+ finally:
3049
+ if annotate:
3050
+ try:
3051
+ await asyncio.wait_for(page.evaluate(_JS_REMOVE_OVERLAY), timeout=5.0)
3052
+ except Exception:
3053
+ pass
3054
+
3055
+ title = await page.title()
3056
+ extras = []
3057
+ if sel_clean or ref_clean:
3058
+ extras.append(f"Element: {f'ref {ref_clean}' if ref_clean else sel_clean}")
3059
+ elif full_page:
3060
+ extras.append("Mode: full_page")
3061
+ if annotate:
3062
+ extras.append(f"Annotated: {annotated_count} ref(s)")
3063
+ extra_line = ("\n" + " | ".join(extras)) if extras else ""
3064
+ return f"Screenshot saved to: {save_path}\nPage Title: {title}\nURL: {page.url}{extra_line}"
3065
+ except Exception as exc:
3066
+ return f"Error taking screenshot: {_format_playwright_error(exc)}"
3067
+
3068
+
3069
+ @mcp.tool()
3070
+ @_with_tool_deadline
3071
+ async def fetch(
3072
+ url: str,
3073
+ method: str = "GET",
3074
+ headers: Optional[dict] = None,
3075
+ body: Optional[Any] = None,
3076
+ response_type: str = "auto",
3077
+ tab: Union[int, str] = -1,
3078
+ timeout_ms: int = 15000,
3079
+ save_path: str = "",
3080
+ max_length: int = _DEFAULT_OUTPUT_MAX_CHARS,
3081
+ ) -> str:
3082
+ """Execute an authenticated in-browser fetch (supports relative, absolute, and blob: URLs). Pass save_path to write binary/PDF responses to disk without entering context."""
3083
+ t0 = time.perf_counter()
3084
+ try:
3085
+ page = await session.resolve_page(tab)
3086
+
3087
+ if isinstance(body, (dict, list)):
3088
+ body = json.dumps(body)
3089
+ if headers is None:
3090
+ headers = {}
3091
+ headers.setdefault("Content-Type", "application/json")
3092
+ save_binary = bool(save_path and save_path.strip())
3093
+ js_script = """async ({ url, method, headers, body, responseType, saveBinary }) => {
3094
+ const options = {
3095
+ method: (method || 'GET').toUpperCase(),
3096
+ credentials: 'include',
3097
+ headers: headers || {}
3098
+ };
3099
+ if (body && !['GET', 'HEAD'].includes(options.method)) {
3100
+ options.body = body;
3101
+ }
3102
+ const tStart = performance.now();
3103
+ try {
3104
+ const res = await window.fetch(url, options);
3105
+ const duration = Math.round(performance.now() - tStart);
3106
+ const resHeaders = {};
3107
+ res.headers.forEach((v, k) => { resHeaders[k] = v; });
3108
+
3109
+ if (saveBinary) {
3110
+ if (!res.ok) {
3111
+ let errorPreview = '';
3112
+ try {
3113
+ errorPreview = (await res.text()).slice(0, 1000);
3114
+ } catch (_) {}
3115
+ return {
3116
+ ok: false,
3117
+ status: res.status,
3118
+ statusText: res.statusText,
3119
+ url: res.url,
3120
+ duration,
3121
+ headers: resHeaders,
3122
+ errorPreview
3123
+ };
3124
+ }
3125
+ const buf = await res.arrayBuffer();
3126
+ const bytes = new Uint8Array(buf);
3127
+ // Multiple of 3 so each btoa chunk avoids intermediate padding and call-stack overflow
3128
+ const chunkSize = 12288;
3129
+ const b64Parts = [];
3130
+ for (let i = 0; i < bytes.length; i += chunkSize) {
3131
+ const slice = bytes.subarray(i, Math.min(i + chunkSize, bytes.length));
3132
+ b64Parts.push(btoa(String.fromCharCode.apply(null, slice)));
3133
+ }
3134
+ return {
3135
+ ok: true,
3136
+ status: res.status,
3137
+ statusText: res.statusText,
3138
+ url: res.url,
3139
+ duration,
3140
+ headers: resHeaders,
3141
+ base64: b64Parts.join(''),
3142
+ sizeBytes: bytes.byteLength
3143
+ };
3144
+ }
3145
+
3146
+ const text = await res.text();
3147
+ let parsed = null;
3148
+ let isJson = false;
3149
+ if (responseType === 'json' || responseType === 'auto') {
3150
+ try {
3151
+ parsed = JSON.parse(text);
3152
+ isJson = true;
3153
+ } catch (_) {}
3154
+ }
3155
+ return {
3156
+ ok: res.ok,
3157
+ status: res.status,
3158
+ statusText: res.statusText,
3159
+ url: res.url,
3160
+ duration,
3161
+ headers: resHeaders,
3162
+ isJson,
3163
+ data: isJson ? parsed : text
3164
+ };
3165
+ } catch (err) {
3166
+ return {
3167
+ error: err.toString(),
3168
+ duration: Math.round(performance.now() - tStart)
3169
+ };
3170
+ }
3171
+ }"""
3172
+ try:
3173
+ result = await asyncio.wait_for(
3174
+ page.evaluate(js_script, {
3175
+ "url": url,
3176
+ "method": method,
3177
+ "headers": headers or {},
3178
+ "body": body,
3179
+ "responseType": response_type,
3180
+ "saveBinary": save_binary,
3181
+ }),
3182
+ timeout=timeout_ms / 1000.0,
3183
+ )
3184
+ except asyncio.TimeoutError:
3185
+ return f"Error executing fetch: Timed out after {timeout_ms}ms"
3186
+ elapsed_total = int((time.perf_counter() - t0) * 1000)
3187
+
3188
+ if "error" in result:
3189
+ return f"Fetch error ({result.get('duration', elapsed_total)}ms): {result['error']}"
3190
+
3191
+ status_str = f"HTTP {result['status']} {result['statusText']} ({result['duration']}ms)"
3192
+ if save_binary:
3193
+ dest_path = os.path.abspath(os.path.expanduser(save_path.strip()))
3194
+ res_headers = result.get("headers") or {}
3195
+ content_type = next(
3196
+ (v for k, v in res_headers.items() if k.lower() == "content-type"),
3197
+ "application/octet-stream",
3198
+ )
3199
+ if not result.get("ok"):
3200
+ preview = (result.get("errorPreview") or "").strip()
3201
+ msg = (
3202
+ f"Fetch failed — {status_str} from {result['url']} "
3203
+ f"(Content-Type: {content_type}); file not saved to {dest_path}"
3204
+ )
3205
+ if preview:
3206
+ msg += f"\nResponse preview: {preview}"
3207
+ return msg
3208
+ raw_bytes = base64.b64decode(result.get("base64") or "")
3209
+ parent_dir = os.path.dirname(dest_path)
3210
+ if parent_dir:
3211
+ os.makedirs(parent_dir, exist_ok=True)
3212
+ with open(dest_path, "wb") as f:
3213
+ f.write(raw_bytes)
3214
+ return (
3215
+ f"{status_str} [SAVED] from {result['url']} -> {dest_path} "
3216
+ f"(Content-Type: {content_type}, {len(raw_bytes)} bytes / {_format_byte_size(len(raw_bytes))})"
3217
+ )
3218
+
3219
+ data = result.get("data")
3220
+ if result.get("isJson") and data is not None:
3221
+ dumped = _truncate_text(_compact_json(data), max_length)
3222
+ return f"{status_str} [JSON] from {result['url']}:\n\n{dumped}"
3223
+ else:
3224
+ text = _truncate_text(str(data or ""), max_length)
3225
+ return f"{status_str} [TEXT] from {result['url']}:\n\n{text}"
3226
+ except Exception as exc:
3227
+ return f"Error executing fetch: {exc}"
3228
+
3229
+
3230
+ def _format_byte_size(size_bytes: Optional[int]) -> str:
3231
+ if size_bytes is None:
3232
+ return "unknown size"
3233
+ if size_bytes < 1024:
3234
+ return f"{size_bytes} B"
3235
+ if size_bytes < 1024 * 1024:
3236
+ return f"{size_bytes / 1024:.1f} KB"
3237
+ return f"{size_bytes / (1024 * 1024):.2f} MB"
3238
+
3239
+
3240
+ class DownloadTracker:
3241
+ """Tracks Playwright download events in a bounded ring buffer without blocking the event loop."""
3242
+
3243
+ def __init__(self, maxlen: int = 100, downloads_dir: Optional[str] = None):
3244
+ self._entries: collections.deque[dict[str, Any]] = collections.deque(maxlen=maxlen)
3245
+ self._next_id: int = 1
3246
+ self._pending_tasks: set[asyncio.Task] = set()
3247
+ self._downloads_dir_override: Optional[str] = downloads_dir
3248
+
3249
+ @property
3250
+ def downloads_dir(self) -> str:
3251
+ return self._downloads_dir_override if self._downloads_dir_override is not None else DOWNLOADS_DIR
3252
+
3253
+ def attach(self, page: Page) -> None:
3254
+ if page is None or getattr(page, "_download_tracker_attached", False):
3255
+ return
3256
+ setattr(page, "_download_tracker_attached", True)
3257
+ page.on("download", self._on_download)
3258
+
3259
+ def _resolve_native_path(self, suggested_filename: str, started_ts: float) -> Optional[str]:
3260
+ target_dir = self.downloads_dir
3261
+ if not suggested_filename or not os.path.isdir(target_dir):
3262
+ return None
3263
+ stem, ext = os.path.splitext(suggested_filename)
3264
+ recent_candidates: list[tuple[float, str]] = []
3265
+ try:
3266
+ with os.scandir(target_dir) as it:
3267
+ for de in it:
3268
+ if not de.is_file():
3269
+ continue
3270
+ name = de.name
3271
+ if name == suggested_filename or (name.startswith(f"{stem} (") and name.endswith(f"){ext}")):
3272
+ try:
3273
+ mtime = de.stat().st_mtime
3274
+ except OSError:
3275
+ continue
3276
+ if mtime >= started_ts - 2.0:
3277
+ recent_candidates.append((mtime, de.path))
3278
+ except OSError:
3279
+ return None
3280
+ if recent_candidates:
3281
+ recent_candidates.sort(key=lambda item: item[0], reverse=True)
3282
+ return os.path.abspath(recent_candidates[0][1])
3283
+ direct = os.path.join(target_dir, suggested_filename)
3284
+ if os.path.isfile(direct):
3285
+ return os.path.abspath(direct)
3286
+ return None
3287
+
3288
+ def _on_download(self, download: Any) -> None:
3289
+ started_ts = time.time()
3290
+ try:
3291
+ url = str(getattr(download, "url", "") or "")
3292
+ except Exception:
3293
+ url = ""
3294
+ try:
3295
+ suggested_filename = str(getattr(download, "suggested_filename", "") or "")
3296
+ except Exception:
3297
+ suggested_filename = ""
3298
+
3299
+ entry: dict[str, Any] = {
3300
+ "id": self._next_id,
3301
+ "url": url,
3302
+ "suggested_filename": suggested_filename,
3303
+ "save_path": None,
3304
+ "status": "in_progress",
3305
+ "size_bytes": None,
3306
+ "started_at": datetime.datetime.now().isoformat(timespec="seconds"),
3307
+ "completed_at": None,
3308
+ "error": None,
3309
+ }
3310
+ self._next_id += 1
3311
+ self._entries.append(entry)
3312
+
3313
+ try:
3314
+ loop = asyncio.get_running_loop()
3315
+ except RuntimeError:
3316
+ return
3317
+ task = loop.create_task(self._await_completion(entry, download, started_ts))
3318
+ self._pending_tasks.add(task)
3319
+ task.add_done_callback(self._pending_tasks.discard)
3320
+
3321
+ async def _await_completion(self, entry: dict[str, Any], download: Any, started_ts: float) -> None:
3322
+ try:
3323
+ failure = await download.failure()
3324
+ except Exception as exc:
3325
+ native_path = self._resolve_native_path(entry["suggested_filename"], started_ts)
3326
+ if native_path is not None:
3327
+ self._mark_completed(entry, native_path)
3328
+ else:
3329
+ self._mark_failed(entry, str(exc))
3330
+ return
3331
+
3332
+ if failure:
3333
+ self._mark_failed(entry, str(failure))
3334
+ return
3335
+
3336
+ path_err: Optional[str] = None
3337
+ save_path: Optional[str] = None
3338
+ try:
3339
+ raw_path = await download.path()
3340
+ if raw_path is not None:
3341
+ save_path = str(raw_path)
3342
+ except Exception as exc:
3343
+ path_err = str(exc)
3344
+
3345
+ if not save_path or not os.path.isfile(save_path):
3346
+ native_path = self._resolve_native_path(entry["suggested_filename"], started_ts)
3347
+ if native_path is not None:
3348
+ save_path = native_path
3349
+
3350
+ if save_path:
3351
+ self._mark_completed(entry, save_path)
3352
+ elif path_err:
3353
+ self._mark_failed(entry, path_err)
3354
+ else:
3355
+ self._mark_completed(entry, None)
3356
+
3357
+ def _mark_completed(self, entry: dict[str, Any], save_path: Optional[str]) -> None:
3358
+ entry["status"] = "completed"
3359
+ entry["save_path"] = save_path
3360
+ if save_path and os.path.isfile(save_path):
3361
+ try:
3362
+ entry["size_bytes"] = os.path.getsize(save_path)
3363
+ except OSError:
3364
+ entry["size_bytes"] = None
3365
+ entry["completed_at"] = datetime.datetime.now().isoformat(timespec="seconds")
3366
+
3367
+ def _mark_failed(self, entry: dict[str, Any], error: str) -> None:
3368
+ entry["status"] = "failed"
3369
+ entry["error"] = error
3370
+ entry["completed_at"] = datetime.datetime.now().isoformat(timespec="seconds")
3371
+
3372
+ async def flush(self) -> None:
3373
+ if self._pending_tasks:
3374
+ await asyncio.gather(*list(self._pending_tasks), return_exceptions=True)
3375
+
3376
+ def list_entries(self, limit: int = 20) -> list[dict[str, Any]]:
3377
+ if limit <= 0:
3378
+ return []
3379
+ return list(self._entries)[-limit:][::-1]
3380
+
3381
+ def list_dir_files(self, limit: int = 20) -> list[dict[str, Any]]:
3382
+ if limit <= 0 or not os.path.isdir(self.downloads_dir):
3383
+ return []
3384
+ files: list[tuple[float, dict[str, Any]]] = []
3385
+ try:
3386
+ with os.scandir(self.downloads_dir) as it:
3387
+ for de in it:
3388
+ if de.name.startswith(".") or not de.is_file():
3389
+ continue
3390
+ try:
3391
+ st = de.stat()
3392
+ except OSError:
3393
+ continue
3394
+ files.append((
3395
+ st.st_mtime,
3396
+ {
3397
+ "name": de.name,
3398
+ "path": os.path.abspath(de.path),
3399
+ "size_bytes": st.st_size,
3400
+ "modified_at": datetime.datetime.fromtimestamp(st.st_mtime).isoformat(timespec="seconds"),
3401
+ },
3402
+ ))
3403
+ except OSError:
3404
+ return []
3405
+ files.sort(key=lambda item: item[0], reverse=True)
3406
+ return [item[1] for item in files[:limit]]
3407
+
3408
+
3409
+ class TelemetryTracker:
3410
+ """Maintains per-page bounded ring buffers for console messages and network responses/failures."""
3411
+
3412
+ MAX_CONSOLE_TEXT = 500
3413
+
3414
+ def __init__(self, maxlen: int = 200):
3415
+ self._maxlen = maxlen
3416
+ self._console: dict[Page, collections.deque[dict[str, Any]]] = {}
3417
+ self._network: dict[Page, collections.deque[dict[str, Any]]] = {}
3418
+ self._cdp_sessions: dict[Page, Any] = {}
3419
+
3420
+ def attach(self, page: Page) -> None:
3421
+ if page is None or getattr(page, "_telemetry_tracker_attached", False):
3422
+ return
3423
+ setattr(page, "_telemetry_tracker_attached", True)
3424
+ self._console.setdefault(page, collections.deque(maxlen=self._maxlen))
3425
+ self._network.setdefault(page, collections.deque(maxlen=self._maxlen))
3426
+
3427
+ page.on("console", lambda msg: self._on_console(page, msg))
3428
+ page.on("pageerror", lambda err: self._on_pageerror(page, err))
3429
+ page.on("response", lambda resp: self._on_response(page, resp))
3430
+ page.on("requestfailed", lambda req: self._on_requestfailed(page, req))
3431
+ page.on("close", lambda _=None: self._on_close(page))
3432
+ page.on("crash", lambda _=None: self._on_crash(page))
3433
+
3434
+ async def ensure_console_capture(self, page: Page) -> bool:
3435
+ """Attach a raw-CDP Runtime console listener to a tab (lazily, on first console_logs call).
3436
+
3437
+ patchright never sends Runtime.enable (stealth), so page.on("console") only sees
3438
+ browser-generated Log entries. Enabling it on-demand trades a small amount of stealth
3439
+ on that single tab for full script console capture.
3440
+ """
3441
+ if page is None or page.is_closed():
3442
+ return False
3443
+ if page in self._cdp_sessions:
3444
+ return True
3445
+ context = getattr(page, "context", None)
3446
+ if context is None:
3447
+ return False
3448
+ try:
3449
+ cdp = await asyncio.wait_for(context.new_cdp_session(page), timeout=10.0)
3450
+ except Exception:
3451
+ return False
3452
+
3453
+ def _on_console_api(ev: Any) -> None:
3454
+ try:
3455
+ level = str(ev.get("type", "log") or "log").lower()
3456
+ if level == "warn":
3457
+ level = "warning"
3458
+ parts: list[str] = []
3459
+ for arg in ev.get("args", []) or []:
3460
+ val = arg.get("value")
3461
+ if val is None:
3462
+ val = arg.get("description")
3463
+ parts.append(str(val) if val is not None else "(opaque object)")
3464
+ text = self._truncate_text(" ".join(parts))
3465
+ location = ""
3466
+ stack = ev.get("stackTrace") or []
3467
+ if isinstance(stack, list) and stack and isinstance(stack[0], dict):
3468
+ location = f"{stack[0].get('url', '')}:{stack[0].get('lineNumber', '')}"
3469
+ buf = self._console.setdefault(page, collections.deque(maxlen=self._maxlen))
3470
+ buf.append({
3471
+ "timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="milliseconds"),
3472
+ "level": level,
3473
+ "text": text,
3474
+ "location": location,
3475
+ })
3476
+ except Exception:
3477
+ pass
3478
+
3479
+ def _on_exception_thrown(ev: Any) -> None:
3480
+ try:
3481
+ details = ev.get("exceptionDetails") or {}
3482
+ text = str(details.get("text") or "")
3483
+ exc = details.get("exception") or {}
3484
+ desc = exc.get("description")
3485
+ buf = self._console.setdefault(page, collections.deque(maxlen=self._maxlen))
3486
+ buf.append({
3487
+ "timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="milliseconds"),
3488
+ "level": "pageerror",
3489
+ "text": self._truncate_text(str(desc) if desc else text),
3490
+ "location": "",
3491
+ })
3492
+ except Exception:
3493
+ pass
3494
+
3495
+ cdp.on("Runtime.consoleAPICalled", _on_console_api)
3496
+ cdp.on("Runtime.exceptionThrown", _on_exception_thrown)
3497
+
3498
+ def _drop_session(_=None) -> None:
3499
+ self._drop_cdp_session(page, cdp)
3500
+
3501
+ page.on("close", _drop_session)
3502
+ page.on("crash", _drop_session)
3503
+ try:
3504
+ await asyncio.wait_for(cdp.send("Runtime.enable"), timeout=5.0)
3505
+ except Exception:
3506
+ await self._detach_quiet(cdp)
3507
+ return False
3508
+ self._cdp_sessions[page] = cdp
3509
+ return True
3510
+
3511
+ def _drop_cdp_session(self, page: Page, cdp) -> None:
3512
+ if self._cdp_sessions.get(page) is cdp:
3513
+ self._cdp_sessions.pop(page, None)
3514
+ self._schedule_detach(cdp)
3515
+
3516
+ @staticmethod
3517
+ async def _detach_quiet(cdp) -> None:
3518
+ try:
3519
+ await cdp.detach()
3520
+ except Exception:
3521
+ pass
3522
+
3523
+ @staticmethod
3524
+ def _schedule_detach(cdp) -> None:
3525
+ try:
3526
+ asyncio.get_running_loop().create_task(TelemetryTracker._detach_quiet(cdp))
3527
+ except Exception:
3528
+ pass
3529
+
3530
+ def _on_close(self, page: Page) -> None:
3531
+ cdp = self._cdp_sessions.pop(page, None)
3532
+ self._console.pop(page, None)
3533
+ self._network.pop(page, None)
3534
+ if cdp is not None:
3535
+ self._schedule_detach(cdp)
3536
+
3537
+ def _on_crash(self, page: Page) -> None:
3538
+ self._cdp_sessions.pop(page, None)
3539
+
3540
+ def _truncate_text(self, text: str) -> str:
3541
+ if len(text) > self.MAX_CONSOLE_TEXT:
3542
+ return text[:self.MAX_CONSOLE_TEXT] + "... [truncated]"
3543
+ return text
3544
+
3545
+ def _on_console(self, page: Page, msg: Any) -> None:
3546
+ buf = self._console.setdefault(page, collections.deque(maxlen=self._maxlen))
3547
+ try:
3548
+ level = str(getattr(msg, "type", "log") or "log").lower()
3549
+ except Exception:
3550
+ level = "log"
3551
+ if level == "warn":
3552
+ level = "warning"
3553
+ try:
3554
+ raw_text = str(getattr(msg, "text", "") or "")
3555
+ except Exception:
3556
+ raw_text = ""
3557
+ location = ""
3558
+ try:
3559
+ loc = getattr(msg, "location", None)
3560
+ if isinstance(loc, dict) and loc.get("url"):
3561
+ line_no = loc.get("lineNumber")
3562
+ location = f"{loc['url']}:{line_no}" if line_no is not None else str(loc["url"])
3563
+ except Exception:
3564
+ location = ""
3565
+ buf.append({
3566
+ "timestamp": datetime.datetime.now().isoformat(timespec="milliseconds"),
3567
+ "level": level,
3568
+ "text": self._truncate_text(raw_text),
3569
+ "location": location,
3570
+ })
3571
+
3572
+ def _on_pageerror(self, page: Page, err: Any) -> None:
3573
+ buf = self._console.setdefault(page, collections.deque(maxlen=self._maxlen))
3574
+ try:
3575
+ raw_text = str(getattr(err, "message", None) or err)
3576
+ except Exception:
3577
+ raw_text = str(err)
3578
+ buf.append({
3579
+ "timestamp": datetime.datetime.now().isoformat(timespec="milliseconds"),
3580
+ "level": "pageerror",
3581
+ "text": self._truncate_text(raw_text),
3582
+ "location": "",
3583
+ })
3584
+
3585
+ def _on_response(self, page: Page, resp: Any) -> None:
3586
+ buf = self._network.setdefault(page, collections.deque(maxlen=self._maxlen))
3587
+ req = getattr(resp, "request", None)
3588
+ method = str(getattr(req, "method", "GET") or "GET").upper()
3589
+ resource_type = str(getattr(req, "resource_type", "other") or "other").lower()
3590
+ try:
3591
+ status = int(getattr(resp, "status", 0))
3592
+ except Exception:
3593
+ status = None
3594
+ url = str(getattr(resp, "url", "") or getattr(req, "url", "") or "")
3595
+
3596
+ content_type = ""
3597
+ size_bytes: Optional[int] = None
3598
+ try:
3599
+ raw_headers = getattr(resp, "headers", None) or {}
3600
+ if isinstance(raw_headers, dict):
3601
+ for k, v in raw_headers.items():
3602
+ kl = k.lower()
3603
+ if kl == "content-type":
3604
+ content_type = str(v)
3605
+ elif kl == "content-length":
3606
+ try:
3607
+ size_bytes = int(str(v).strip())
3608
+ except ValueError:
3609
+ pass
3610
+ except Exception:
3611
+ pass
3612
+
3613
+ duration_ms: Optional[int] = None
3614
+ try:
3615
+ timing = getattr(req, "timing", None)
3616
+ if isinstance(timing, dict):
3617
+ resp_end = timing.get("responseEnd")
3618
+ resp_start = timing.get("responseStart")
3619
+ if isinstance(resp_end, (int, float)) and resp_end > 0:
3620
+ duration_ms = int(round(resp_end))
3621
+ elif isinstance(resp_start, (int, float)) and resp_start >= 0:
3622
+ duration_ms = int(round(resp_start))
3623
+ except Exception:
3624
+ pass
3625
+
3626
+ buf.append({
3627
+ "timestamp": datetime.datetime.now().isoformat(timespec="milliseconds"),
3628
+ "method": method,
3629
+ "status": status,
3630
+ "failure": None,
3631
+ "resource_type": resource_type,
3632
+ "content_type": content_type,
3633
+ "url": url,
3634
+ "size_bytes": size_bytes,
3635
+ "duration_ms": duration_ms,
3636
+ })
3637
+
3638
+ def _on_requestfailed(self, page: Page, req: Any) -> None:
3639
+ buf = self._network.setdefault(page, collections.deque(maxlen=self._maxlen))
3640
+ method = str(getattr(req, "method", "GET") or "GET").upper()
3641
+ resource_type = str(getattr(req, "resource_type", "other") or "other").lower()
3642
+ url = str(getattr(req, "url", "") or "")
3643
+ raw_failure = getattr(req, "failure", None)
3644
+ if isinstance(raw_failure, dict):
3645
+ failure = str(raw_failure.get("errorText") or raw_failure)
3646
+ elif raw_failure:
3647
+ failure = str(raw_failure)
3648
+ else:
3649
+ failure = "failed"
3650
+ buf.append({
3651
+ "timestamp": datetime.datetime.now().isoformat(timespec="milliseconds"),
3652
+ "method": method,
3653
+ "status": None,
3654
+ "failure": failure,
3655
+ "resource_type": resource_type,
3656
+ "content_type": "",
3657
+ "url": url,
3658
+ "size_bytes": None,
3659
+ "duration_ms": None,
3660
+ })
3661
+
3662
+ def get_network(
3663
+ self,
3664
+ page: Page,
3665
+ url_filter: str = "",
3666
+ resource_type: str = "",
3667
+ content_type: str = "",
3668
+ status_min: int = 0,
3669
+ limit: int = 50,
3670
+ clear: bool = False,
3671
+ ) -> tuple[list[dict[str, Any]], int]:
3672
+ buf = self._network.get(page)
3673
+ if not buf:
3674
+ return [], 0
3675
+ total = len(buf)
3676
+ entries = list(buf)
3677
+ if clear:
3678
+ buf.clear()
3679
+
3680
+ url_sub = url_filter.strip().lower()
3681
+ allowed_types = {t.strip().lower() for t in resource_type.split(",") if t.strip()} if resource_type else set()
3682
+ ct_sub = content_type.strip().lower()
3683
+
3684
+ matched = []
3685
+ for item in entries:
3686
+ if url_sub and url_sub not in item["url"].lower():
3687
+ continue
3688
+ if allowed_types and item["resource_type"].lower() not in allowed_types:
3689
+ continue
3690
+ if ct_sub and ct_sub not in item["content_type"].lower():
3691
+ continue
3692
+ if status_min > 0 and (item["status"] is None or item["status"] < status_min):
3693
+ continue
3694
+ matched.append(item)
3695
+
3696
+ if limit <= 0:
3697
+ return [], total
3698
+ return matched[-limit:], total
3699
+
3700
+ def get_console(
3701
+ self,
3702
+ page: Page,
3703
+ level: str = "",
3704
+ limit: int = 50,
3705
+ clear: bool = False,
3706
+ ) -> tuple[list[dict[str, Any]], int]:
3707
+ buf = self._console.get(page)
3708
+ if not buf:
3709
+ return [], 0
3710
+ total = len(buf)
3711
+ entries = list(buf)
3712
+ if clear:
3713
+ buf.clear()
3714
+
3715
+ allowed_levels: set[str] = set()
3716
+ if level:
3717
+ for part in level.split(","):
3718
+ norm = part.strip().lower()
3719
+ if norm == "warn":
3720
+ norm = "warning"
3721
+ if norm:
3722
+ allowed_levels.add(norm)
3723
+
3724
+ matched = [item for item in entries if not allowed_levels or item["level"].lower() in allowed_levels]
3725
+ if limit <= 0:
3726
+ return [], total
3727
+ return matched[-limit:], total
3728
+
3729
+
3730
+ download_tracker = DownloadTracker()
3731
+ telemetry_tracker = TelemetryTracker()
3732
+
3733
+
3734
+ def _attach_page_trackers(page: Page) -> None:
3735
+ download_tracker.attach(page)
3736
+ telemetry_tracker.attach(page)
3737
+ _schedule_animations_on_page(page)
3738
+
3739
+
3740
+ @mcp.tool()
3741
+ @_with_tool_deadline
3742
+ async def downloads(limit: int = 20, include_dir: bool = False) -> str:
3743
+ """List tracked browser downloads (and recent DOWNLOADS_DIR files when include_dir=True)."""
3744
+ try:
3745
+ entries = download_tracker.list_entries(limit=limit)
3746
+ sections: list[str] = []
3747
+ if entries:
3748
+ lines = [f"Tracked browser downloads (showing {len(entries)} of {len(download_tracker._entries)}):"]
3749
+ for item in entries:
3750
+ size_str = _format_byte_size(item["size_bytes"])
3751
+ dest = item["save_path"] or "(pending)"
3752
+ url_str = _truncate_url(item["url"], 140)
3753
+ line = (
3754
+ f"- [#{item['id']}] [{item['status']}] {item['suggested_filename'] or '(unnamed)'} "
3755
+ f"({size_str}) -> {dest} | url: {url_str} | started: {item['started_at']}"
3756
+ )
3757
+ if item["completed_at"]:
3758
+ line += f" | completed: {item['completed_at']}"
3759
+ if item["error"]:
3760
+ line += f" | error: {item['error']}"
3761
+ lines.append(line)
3762
+ sections.append("\n".join(lines))
3763
+ else:
3764
+ hint = "" if include_dir else f" Pass include_dir=True to list files in {download_tracker.downloads_dir}."
3765
+ sections.append(f"No tracked browser downloads yet.{hint}")
3766
+
3767
+ if include_dir:
3768
+ dir_files = download_tracker.list_dir_files(limit=limit)
3769
+ if dir_files:
3770
+ dir_lines = [f"Recent files in {download_tracker.downloads_dir} (showing {len(dir_files)}):"]
3771
+ for f in dir_files:
3772
+ dir_lines.append(
3773
+ f"- {f['name']} ({_format_byte_size(f['size_bytes'])}, modified {f['modified_at']}) -> {f['path']}"
3774
+ )
3775
+ sections.append("\n".join(dir_lines))
3776
+ else:
3777
+ sections.append(f"No files found in {download_tracker.downloads_dir}.")
3778
+
3779
+ return "\n\n".join(sections)
3780
+ except Exception as exc:
3781
+ return f"Error listing downloads: {exc}"
3782
+
3783
+
3784
+ @mcp.tool()
3785
+ @_with_tool_deadline
3786
+ async def network_requests(
3787
+ url_filter: str = "",
3788
+ resource_type: str = "",
3789
+ content_type: str = "",
3790
+ status_min: int = 0,
3791
+ limit: int = 30,
3792
+ clear: bool = False,
3793
+ tab: Union[int, str] = -1,
3794
+ max_length: int = _DEFAULT_OUTPUT_MAX_CHARS,
3795
+ ) -> str:
3796
+ """List captured network responses/failures for a tab. Filter by url_filter, resource_type ('xhr,fetch'), content_type ('json','pdf'), or status_min (e.g. 400)."""
3797
+ try:
3798
+ page = await session.resolve_page(tab)
3799
+ _attach_page_trackers(page)
3800
+ entries, total = telemetry_tracker.get_network(
3801
+ page=page,
3802
+ url_filter=url_filter,
3803
+ resource_type=resource_type,
3804
+ content_type=content_type,
3805
+ status_min=status_min,
3806
+ limit=limit,
3807
+ clear=clear,
3808
+ )
3809
+ cleared_tag = " [buffer cleared]" if clear else ""
3810
+ if not entries:
3811
+ return f"No matching network requests for {page.url} ({total} total captured){cleared_tag}."
3812
+
3813
+ lines: list[str] = []
3814
+ for item in entries:
3815
+ ts = item["timestamp"].split("T")[-1]
3816
+ if item["failure"]:
3817
+ status_part = f"FAILED({item['failure']})"
3818
+ else:
3819
+ status_part = str(item["status"])
3820
+ meta = []
3821
+ if item["content_type"]:
3822
+ meta.append(item["content_type"])
3823
+ if item["size_bytes"] is not None:
3824
+ meta.append(_format_byte_size(item["size_bytes"]))
3825
+ if item["duration_ms"] is not None:
3826
+ meta.append(f"{item['duration_ms']}ms")
3827
+ meta_str = f" ({', '.join(meta)})" if meta else ""
3828
+ lines.append(f"- [{ts}] {status_part} {item['method']} [{item['resource_type']}]{meta_str} {_truncate_url(item['url'], 160)}")
3829
+ return _truncate_lines(
3830
+ lambda shown: f"Network requests for {page.url} (showing {shown} of {total} captured){cleared_tag}:",
3831
+ lines,
3832
+ max_length,
3833
+ hint="filter with url_filter=/resource_type=",
3834
+ )
3835
+ except Exception as exc:
3836
+ return f"Error listing network requests: {exc}"
3837
+
3838
+
3839
+ @mcp.tool()
3840
+ @_with_tool_deadline
3841
+ async def console_logs(
3842
+ level: str = "",
3843
+ limit: int = 50,
3844
+ clear: bool = False,
3845
+ tab: Union[int, str] = -1,
3846
+ max_length: int = _DEFAULT_OUTPUT_MAX_CHARS,
3847
+ ) -> str:
3848
+ """List captured browser console messages and page errors (filter by comma-separated level: 'error,warning,log,pageerror'). Attaches CDP console listener on first call."""
3849
+ try:
3850
+ page = await session.resolve_page(tab)
3851
+ _attach_page_trackers(page)
3852
+ await telemetry_tracker.ensure_console_capture(page)
3853
+ entries, total = telemetry_tracker.get_console(
3854
+ page=page,
3855
+ level=level,
3856
+ limit=limit,
3857
+ clear=clear,
3858
+ )
3859
+ cleared_tag = " [buffer cleared]" if clear else ""
3860
+ if not entries:
3861
+ return f"No matching console logs for {page.url} ({total} total captured){cleared_tag}."
3862
+
3863
+ lines: list[str] = []
3864
+ for item in entries:
3865
+ ts = item["timestamp"].split("T")[-1]
3866
+ loc_str = f" ({_truncate_url(item['location'], 120)})" if item["location"] else ""
3867
+ lines.append(f"- [{ts}] [{item['level']}]{loc_str} {item['text']}")
3868
+ return _truncate_lines(
3869
+ lambda shown: f"Console logs for {page.url} (showing {shown} of {total} captured){cleared_tag}:",
3870
+ lines,
3871
+ max_length,
3872
+ hint="filter with level=",
3873
+ )
3874
+ except Exception as exc:
3875
+ return f"Error listing console logs: {exc}"
3876
+
3877
+
3878
+ @mcp.tool()
3879
+ @_with_tool_deadline
3880
+ async def state(
3881
+ framework: str = "auto",
3882
+ selector: str = "",
3883
+ tab: Union[int, str] = -1,
3884
+ max_length: int = _DEFAULT_OUTPUT_MAX_CHARS,
3885
+ ) -> str:
3886
+ """Inspect in-memory client-side state (framework: 'auto'|'next'|'redux'|'react'|'vue'|'apollo'|'query'; optional selector for React Fiber)."""
3887
+ t0 = time.perf_counter()
3888
+ try:
3889
+ page = await session.resolve_page(tab)
3890
+ js_script = """({ targetFramework, selector }) => {
3891
+ function safeSerialize(obj, maxDepth = 4, maxKeys = 80) {
3892
+ const seen = new WeakSet();
3893
+ function helper(val, depth) {
3894
+ if (val === null || typeof val !== 'object') {
3895
+ if (typeof val === 'function') return '[Function]';
3896
+ if (typeof val === 'symbol') return val.toString();
3897
+ return val;
3898
+ }
3899
+ if (val instanceof Element || val instanceof Node) {
3900
+ return `<${val.tagName ? val.tagName.toLowerCase() : 'Node'}${val.id ? '#' + val.id : ''}>`;
3901
+ }
3902
+ if (seen.has(val)) return '[Circular]';
3903
+ if (depth >= maxDepth) return Array.isArray(val) ? `[Array(${val.length})]` : '[Object]';
3904
+ seen.add(val);
3905
+
3906
+ if (Array.isArray(val)) {
3907
+ const res = [];
3908
+ const len = Math.min(val.length, 60);
3909
+ for (let i = 0; i < len; i++) {
3910
+ res.push(helper(val[i], depth + 1));
3911
+ }
3912
+ if (val.length > len) res.push(`... ${val.length - len} more items`);
3913
+ return res;
3914
+ }
3915
+
3916
+ const res = {};
3917
+ const keys = Object.keys(val).slice(0, maxKeys);
3918
+ for (const k of keys) {
3919
+ try {
3920
+ res[k] = helper(val[k], depth + 1);
3921
+ } catch (_) {
3922
+ res[k] = '[Unserializable]';
3923
+ }
3924
+ }
3925
+ return res;
3926
+ }
3927
+ return helper(obj, 0);
3928
+ }
3929
+
3930
+ const results = [];
3931
+ const fw = (targetFramework || 'auto').toLowerCase();
3932
+
3933
+ // 1. Next.js Hydration Data
3934
+ if ((fw === 'auto' || fw === 'next') && window.__NEXT_DATA__) {
3935
+ results.push({
3936
+ source: 'Next.js (__NEXT_DATA__)',
3937
+ keys: Object.keys(window.__NEXT_DATA__),
3938
+ data: safeSerialize(window.__NEXT_DATA__)
3939
+ });
3940
+ }
3941
+
3942
+ // 2. Nuxt / SSR Initial State
3943
+ if ((fw === 'auto' || fw === 'vue') && window.__NUXT__) {
3944
+ results.push({
3945
+ source: 'Nuxt (__NUXT__)',
3946
+ keys: Object.keys(window.__NUXT__),
3947
+ data: safeSerialize(window.__NUXT__)
3948
+ });
3949
+ }
3950
+ if ((fw === 'auto') && window.__INITIAL_STATE__) {
3951
+ results.push({
3952
+ source: 'Window Initial State (__INITIAL_STATE__)',
3953
+ keys: Object.keys(window.__INITIAL_STATE__),
3954
+ data: safeSerialize(window.__INITIAL_STATE__)
3955
+ });
3956
+ }
3957
+
3958
+ // 3. Global Redux Store
3959
+ if ((fw === 'auto' || fw === 'redux') && window.store && typeof window.store.getState === 'function') {
3960
+ const state = window.store.getState();
3961
+ results.push({
3962
+ source: 'Redux (window.store)',
3963
+ keys: Object.keys(state || {}),
3964
+ data: safeSerialize(state)
3965
+ });
3966
+ }
3967
+
3968
+ // 4. Apollo GraphQL Cache
3969
+ if ((fw === 'auto' || fw === 'apollo') && window.__APOLLO_CLIENT__ && typeof window.__APOLLO_CLIENT__.extract === 'function') {
3970
+ const cache = window.__APOLLO_CLIENT__.extract();
3971
+ results.push({
3972
+ source: 'Apollo GraphQL Cache',
3973
+ keys: Object.keys(cache || {}),
3974
+ data: safeSerialize(cache)
3975
+ });
3976
+ }
3977
+
3978
+ // 5. TanStack / React Query Client
3979
+ if ((fw === 'auto' || fw === 'query') && window.queryClient && typeof window.queryClient.getQueryCache === 'function') {
3980
+ const queries = window.queryClient.getQueryCache().getAll().map(q => ({
3981
+ queryKey: q.queryKey,
3982
+ status: q.state?.status,
3983
+ data: q.state?.data
3984
+ }));
3985
+ results.push({
3986
+ source: 'React Query (window.queryClient)',
3987
+ keys: queries.map(q => JSON.stringify(q.queryKey)),
3988
+ data: safeSerialize(queries)
3989
+ });
3990
+ }
3991
+
3992
+ // 6. Vue Component Tree
3993
+ if (fw === 'auto' || fw === 'vue') {
3994
+ const vueEl = document.querySelector(selector || '#app, [data-v-app], #root');
3995
+ if (vueEl) {
3996
+ if (vueEl.__vue_app__) {
3997
+ const appState = vueEl.__vue_app__._instance?.data || vueEl.__vue_app__._context?.provides;
3998
+ if (appState) {
3999
+ results.push({
4000
+ source: 'Vue 3 (__vue_app__)',
4001
+ keys: Object.keys(appState),
4002
+ data: safeSerialize(appState)
4003
+ });
4004
+ }
4005
+ } else if (vueEl.__vue__) {
4006
+ results.push({
4007
+ source: 'Vue 2 (__vue__)',
4008
+ keys: Object.keys(vueEl.__vue__.$data || {}),
4009
+ data: safeSerialize(vueEl.__vue__.$data)
4010
+ });
4011
+ }
4012
+ }
4013
+ }
4014
+
4015
+ // 7. React Fiber Traversal (Redux Provider or Component Props/State)
4016
+ if (fw === 'auto' || fw === 'react' || fw === 'redux') {
4017
+ const targetEl = selector ? document.querySelector(selector) : (document.querySelector('#root') || document.querySelector('#app') || document.body);
4018
+ if (targetEl) {
4019
+ const fiberKey = Object.keys(targetEl).find(k => k.startsWith('__reactFiber$') || k.startsWith('__reactInternalInstance$'));
4020
+ if (fiberKey) {
4021
+ let current = targetEl[fiberKey];
4022
+ let foundStore = false;
4023
+
4024
+ // Walk up fiber tree to check for Redux context or QueryClient context
4025
+ let ancestor = current;
4026
+ let steps = 0;
4027
+ while (ancestor && steps < 50) {
4028
+ // Redux context check
4029
+ if (!foundStore && ancestor.memoizedProps?.store?.getState) {
4030
+ const state = ancestor.memoizedProps.store.getState();
4031
+ results.push({
4032
+ source: 'Redux Store (via React Fiber Context)',
4033
+ keys: Object.keys(state || {}),
4034
+ data: safeSerialize(state)
4035
+ });
4036
+ foundStore = true;
4037
+ }
4038
+ ancestor = ancestor.return;
4039
+ steps++;
4040
+ }
4041
+
4042
+ // Specific component fiber props & state
4043
+ if (selector || (!results.length && targetEl !== document.body)) {
4044
+ results.push({
4045
+ source: `React Fiber Node (${targetEl.tagName.toLowerCase()}${targetEl.id ? '#' + targetEl.id : ''})`,
4046
+ keys: current.memoizedProps ? Object.keys(current.memoizedProps) : [],
4047
+ props: safeSerialize(current.memoizedProps),
4048
+ state: safeSerialize(current.memoizedState)
4049
+ });
4050
+ }
4051
+ }
4052
+ }
4053
+ }
4054
+
4055
+ return results;
4056
+ }"""
4057
+ try:
4058
+ # Patchright defaults to an isolated world where window.__NEXT_DATA__/Redux/Fiber expandos are invisible
4059
+ results = await asyncio.wait_for(
4060
+ page.evaluate(
4061
+ js_script,
4062
+ {
4063
+ "targetFramework": framework,
4064
+ "selector": selector,
4065
+ },
4066
+ isolated_context=False,
4067
+ ),
4068
+ timeout=10.0,
4069
+ )
4070
+ except asyncio.TimeoutError:
4071
+ return f"Error detecting state: Timed out after 10000ms"
4072
+ elapsed_ms = int((time.perf_counter() - t0) * 1000)
4073
+
4074
+ if not results:
4075
+ return (
4076
+ f"No in-memory state stores (Next.js, Redux, React Fiber, Vue, Apollo, React Query) detected "
4077
+ f"on {page.url} ({elapsed_ms}ms). The page may be server-rendered or state is privately scoped in closures."
4078
+ )
4079
+
4080
+ lines = [f"In-Memory State Detective Results for {page.url} ({elapsed_ms}ms):", ""]
4081
+ for idx, item in enumerate(results):
4082
+ lines.append(f"### [{idx + 1}] Source: {item['source']}")
4083
+ if "keys" in item and item["keys"]:
4084
+ key_preview = ", ".join(f"`{k}`" for k in item["keys"][:20])
4085
+ if len(item["keys"]) > 20:
4086
+ key_preview += f" ... (+{len(item['keys']) - 20} more)"
4087
+ lines.append(f"- **Top-Level Keys ({len(item['keys'])} total)**: {key_preview}")
4088
+
4089
+ payload = item["data"] if "data" in item else {"props": item.get("props"), "state": item.get("state")}
4090
+ dumped = _compact_json(payload)
4091
+ lines.append("```json")
4092
+ lines.append(dumped)
4093
+ lines.append("```\n")
4094
+
4095
+ out = "\n".join(lines)
4096
+ if max_length > 0 and len(out) > max_length:
4097
+ out = out[:max_length] + f"\n... [Truncated: {len(out)} total characters; narrow with framework= or selector=]"
4098
+ return out
4099
+ except Exception as exc:
4100
+ return f"Error detecting state: {exc}"
4101
+
4102
+
4103
+ @mcp.tool()
4104
+ @_with_tool_deadline
4105
+ async def evaluate_js(
4106
+ expression: str = "",
4107
+ tab: Union[int, str] = -1,
4108
+ timeout_ms: int = 15000,
4109
+ script: str = "",
4110
+ max_length: int = _DEFAULT_OUTPUT_MAX_CHARS,
4111
+ main_world: bool = False,
4112
+ ) -> str:
4113
+ """Evaluate JS in isolated world by default (alias: script=). Set main_world=True for page globals."""
4114
+ code = expression if expression and expression.strip() else script
4115
+ if not code or not code.strip():
4116
+ return "JavaScript execution error: 'expression' (or alias 'script') must be non-empty."
4117
+ try:
4118
+ page = await session.resolve_page(tab)
4119
+ result = await asyncio.wait_for(
4120
+ page.evaluate(code, isolated_context=not main_world),
4121
+ timeout=timeout_ms / 1000.0,
4122
+ )
4123
+ if isinstance(result, (dict, list)):
4124
+ formatted = _compact_json(result)
4125
+ else:
4126
+ formatted = str(result)
4127
+ formatted = _truncate_text(formatted, max_length)
4128
+ return f"Result: {formatted}"
4129
+ except asyncio.TimeoutError:
4130
+ return f"JavaScript execution error: Timed out after {timeout_ms}ms"
4131
+ except Exception as exc:
4132
+ return f"JavaScript execution error: {exc}"
4133
+
4134
+
4135
+ @mcp.tool()
4136
+ @_with_tool_deadline
4137
+ async def wait_for(
4138
+ selector: str = "",
4139
+ text: str = "",
4140
+ url_contains: str = "",
4141
+ state: str = "visible",
4142
+ timeout_ms: int = 15000,
4143
+ tab: Union[int, str] = -1,
4144
+ ) -> str:
4145
+ """Wait for a CSS selector state, visible page text substring, URL substring, or combination. Clamped to 60s cap."""
4146
+ if not selector and not text and not url_contains:
4147
+ return "Error in wait_for: specify at least one of 'selector', 'text', or 'url_contains'."
4148
+ valid_states = {"attached", "detached", "hidden", "visible"}
4149
+ if state not in valid_states:
4150
+ return f"Error in wait_for: invalid state '{state}'. Expected one of: {', '.join(sorted(valid_states))}."
4151
+ if timeout_ms <= 0:
4152
+ return f"Error in wait_for: timeout_ms must be > 0 (got {timeout_ms})."
4153
+ timeout_ms = min(timeout_ms, int((TOOL_TOTAL_TIMEOUT_S - 10.0) * 1000))
4154
+
4155
+ t0 = time.perf_counter()
4156
+ deadline = time.monotonic() + (timeout_ms / 1000.0)
4157
+ pending_desc = ""
4158
+ page: Optional[Page] = None
4159
+
4160
+ try:
4161
+ page = await session.resolve_page(tab)
4162
+ matched: list[str] = []
4163
+
4164
+ if url_contains:
4165
+ pending_desc = f"url containing '{url_contains}'"
4166
+ while url_contains not in (page.url or ""):
4167
+ if page.is_closed():
4168
+ return f"Error in wait_for: tab closed while waiting for {pending_desc}"
4169
+ if time.monotonic() >= deadline:
4170
+ raise asyncio.TimeoutError()
4171
+ await asyncio.sleep(min(0.1, max(0.01, deadline - time.monotonic())))
4172
+ matched.append(f"url_contains='{url_contains}'")
4173
+
4174
+ if selector:
4175
+ pending_desc = f"selector '{selector}' ({state})"
4176
+ rem_s = deadline - time.monotonic()
4177
+ if rem_s <= 0:
4178
+ raise asyncio.TimeoutError()
4179
+ await asyncio.wait_for(
4180
+ page.locator(selector).first.wait_for(state=state, timeout=max(1, int(rem_s * 1000))),
4181
+ timeout=rem_s + 2.0,
4182
+ )
4183
+ matched.append(f"selector='{selector}' ({state})")
4184
+
4185
+ if text:
4186
+ pending_desc = f"visible text '{text}'"
4187
+ js_has_text = """(needle) => {
4188
+ const root = document.body || document.documentElement;
4189
+ return Boolean(root && (root.innerText || '').includes(needle));
4190
+ }"""
4191
+ while True:
4192
+ if page.is_closed():
4193
+ return f"Error in wait_for: tab closed while waiting for {pending_desc}"
4194
+ rem_s = deadline - time.monotonic()
4195
+ if rem_s <= 0:
4196
+ raise asyncio.TimeoutError()
4197
+ try:
4198
+ found = await asyncio.wait_for(
4199
+ page.evaluate(js_has_text, text),
4200
+ timeout=min(rem_s, 3.0),
4201
+ )
4202
+ except asyncio.TimeoutError:
4203
+ if time.monotonic() >= deadline:
4204
+ raise
4205
+ found = False
4206
+ except Exception:
4207
+ found = False
4208
+ if found:
4209
+ break
4210
+ if time.monotonic() >= deadline:
4211
+ raise asyncio.TimeoutError()
4212
+ await asyncio.sleep(min(0.1, max(0.01, deadline - time.monotonic())))
4213
+ matched.append(f"text='{text}'")
4214
+
4215
+ elapsed_ms = int((time.perf_counter() - t0) * 1000)
4216
+ return f"Wait condition met ({', '.join(matched)}) on {page.url} ({elapsed_ms}ms)"
4217
+ except (asyncio.TimeoutError, TimeoutError):
4218
+ curr_url = page.url if page is not None else "unknown"
4219
+ return f"Wait timed out after {timeout_ms}ms waiting for {pending_desc or 'condition'} on {curr_url}"
4220
+ except Exception as exc:
4221
+ if "timeout" in exc.__class__.__name__.lower():
4222
+ curr_url = page.url if page is not None else "unknown"
4223
+ return f"Wait timed out after {timeout_ms}ms waiting for {pending_desc or 'condition'} on {curr_url}"
4224
+ return f"Error in wait_for: {_format_playwright_error(exc)}"
4225
+
4226
+
4227
+ @mcp.tool()
4228
+ @_with_tool_deadline
4229
+ async def switch_tab(tab: Union[int, str, None] = None, index: Optional[int] = None) -> str:
4230
+ """Switch focus to an open tab by numeric index or stable tab id like 't2' (see status). Accepts 'tab' or legacy alias 'index'."""
4231
+ target = tab if tab is not None else index
4232
+ if target is None:
4233
+ return "Error switching tab: provide a 'tab' (or 'index') value."
4234
+ try:
4235
+ pages = await asyncio.wait_for(session.get_pages(), timeout=CDP_OP_TIMEOUT_S)
4236
+ if isinstance(target, str):
4237
+ norm = target.strip().lower()
4238
+ resolved = next((i for i, p in enumerate(pages) if session.get_tab_id(p) == norm), -1)
4239
+ if resolved < 0:
4240
+ return f"No open tab with id '{norm}'. Use status() to list open tabs."
4241
+ target = resolved
4242
+ if target < 0 or target >= len(pages):
4243
+ return f"Invalid tab index {target}. Total open tabs: {len(pages)}"
4244
+
4245
+ page = pages[target]
4246
+ session.set_active_page(page)
4247
+ await asyncio.wait_for(page.bring_to_front(), timeout=CDP_OP_TIMEOUT_S)
4248
+ try:
4249
+ title = await asyncio.wait_for(page.title(), timeout=PAGE_TITLE_TIMEOUT_S)
4250
+ except Exception:
4251
+ title = "(Unavailable)"
4252
+ return f"Switched to tab [{target}]: '{title}' ({page.url})"
4253
+ except asyncio.TimeoutError:
4254
+ return f"Error switching tab [{target}]: Timed out"
4255
+ except Exception as exc:
4256
+ return f"Error switching tab: {exc}"
4257
+
4258
+
4259
+ @mcp.tool()
4260
+ @_with_tool_deadline
4261
+ async def close_tab(tab: Union[int, str, None] = None, index: Optional[int] = None) -> str:
4262
+ """Close a tab by numeric index or stable tab id like 't2' (-1 closes active tab, -99 or closing last tab terminates the browser window). Accepts 'tab' or legacy alias 'index'."""
4263
+ target = tab if tab is not None else (index if index is not None else -1)
4264
+ try:
4265
+ if target == -99:
4266
+ return await close_browser()
4267
+
4268
+ pages = await asyncio.wait_for(session.get_pages(), timeout=CDP_OP_TIMEOUT_S)
4269
+ if not pages:
4270
+ return await close_browser()
4271
+
4272
+ if isinstance(target, str):
4273
+ norm = target.strip().lower()
4274
+ resolved = next((i for i, p in enumerate(pages) if session.get_tab_id(p) == norm), -1)
4275
+ if resolved < 0:
4276
+ return f"No open tab with id '{norm}'. Use status() to list open tabs."
4277
+ target = resolved
4278
+
4279
+ if target == -1:
4280
+ if session._active_page is not None and not session._active_page.is_closed():
4281
+ page = session._active_page
4282
+ else:
4283
+ page = pages[-1]
4284
+ target_index = pages.index(page) if page in pages else -1
4285
+ else:
4286
+ if target < 0 or target >= len(pages):
4287
+ return f"Invalid tab index {target}. Total open tabs: {len(pages)}"
4288
+ page = pages[target]
4289
+ target_index = target
4290
+
4291
+ url = page.url
4292
+ tab_id = session.get_tab_id(page)
4293
+ try:
4294
+ await asyncio.wait_for(keep_alive_mgr.stop(page), timeout=CDP_OP_TIMEOUT_S)
4295
+ except Exception:
4296
+ pass
4297
+ try:
4298
+ await asyncio.wait_for(page.close(), timeout=PAGE_CLOSE_TIMEOUT_S)
4299
+ except asyncio.TimeoutError:
4300
+ probe_ok = await asyncio.wait_for(asyncio.to_thread(session._probe_cdp_ready), timeout=2.0)
4301
+ if probe_ok:
4302
+ return f"Error closing tab [{target_index}]: Timed out after {int(PAGE_CLOSE_TIMEOUT_S * 1000)}ms (renderer unresponsive; browser still reachable, try restart_browser)"
4303
+ try:
4304
+ await asyncio.wait_for(session.close(), timeout=5.0)
4305
+ except Exception:
4306
+ pass
4307
+ try:
4308
+ await asyncio.wait_for(asyncio.to_thread(_force_kill_browser_processes), timeout=10.0)
4309
+ except Exception:
4310
+ pass
4311
+ return f"Error closing tab [{target_index}]: renderer unresponsive and CDP endpoint dead — wedged browser force-restarted; the next call relaunches it, reopen the tab and re-navigate."
4312
+
4313
+ remaining = await asyncio.wait_for(session.get_pages(), timeout=CDP_OP_TIMEOUT_S)
4314
+ if page == session._active_page:
4315
+ session._active_page = remaining[-1] if remaining else None
4316
+ if not remaining:
4317
+ await close_browser()
4318
+ return f"Closed last tab [{target_index}] ({tab_id}) ({url}). Browser window completely closed."
4319
+ return f"Closed tab [{target_index}] ({tab_id}) ({url}). Remaining open tabs: {len(remaining)}"
4320
+ except asyncio.TimeoutError:
4321
+ return f"Error closing tab [{target}]: Timed out"
4322
+ except Exception as exc:
4323
+ return f"Error closing tab: {exc}"
4324
+
4325
+
4326
+ def _force_kill_browser_processes():
4327
+ """Terminates lingering Chromium processes strictly associated with the agent's profile or CDP port."""
4328
+ try:
4329
+ subprocess.run(["pkill", "-f", "--", f"--user-data-dir={PROFILE_DIR}"], capture_output=True)
4330
+ subprocess.run(["pkill", "-f", "--", f"--remote-debugging-port={CDP_PORT}"], capture_output=True)
4331
+ time.sleep(0.3)
4332
+ subprocess.run(["pkill", "-9", "-f", "--", f"--user-data-dir={PROFILE_DIR}"], capture_output=True)
4333
+ subprocess.run(["pkill", "-9", "-f", "--", f"--remote-debugging-port={CDP_PORT}"], capture_output=True)
4334
+ for lock_name in ("SingletonLock", "SingletonSocket", "SingletonCookie"):
4335
+ lock_path = os.path.join(PROFILE_DIR, lock_name)
4336
+ if os.path.islink(lock_path) or os.path.exists(lock_path):
4337
+ try:
4338
+ os.unlink(lock_path)
4339
+ except Exception:
4340
+ pass
4341
+ except Exception:
4342
+ pass
4343
+
4344
+
4345
+ @mcp.tool()
4346
+ @_with_tool_deadline
4347
+ async def close_browser(force_kill: bool = True) -> str:
4348
+ """Completely close the browser window, terminate all browser and renderer processes, and release all resources."""
4349
+ try:
4350
+ cdp_timed_out = False
4351
+ if session._browser is not None and session._browser.is_connected():
4352
+ try:
4353
+ cdp = await asyncio.wait_for(
4354
+ session._browser.new_browser_cdp_session(),
4355
+ timeout=BROWSER_CLOSE_TIMEOUT_S,
4356
+ )
4357
+ await asyncio.wait_for(cdp.send("Browser.close"), timeout=BROWSER_CLOSE_TIMEOUT_S)
4358
+ except asyncio.TimeoutError:
4359
+ cdp_timed_out = True
4360
+ except Exception:
4361
+ pass
4362
+ if not cdp_timed_out and session._context is not None:
4363
+ try:
4364
+ await asyncio.wait_for(session._context.close(), timeout=BROWSER_CLOSE_TIMEOUT_S)
4365
+ except Exception:
4366
+ pass
4367
+ if not cdp_timed_out and session._browser is not None:
4368
+ try:
4369
+ await asyncio.wait_for(session._browser.close(), timeout=BROWSER_CLOSE_TIMEOUT_S)
4370
+ except Exception:
4371
+ pass
4372
+ try:
4373
+ await asyncio.wait_for(session.close(), timeout=BROWSER_CLOSE_TIMEOUT_S)
4374
+ except Exception:
4375
+ session.close_sync()
4376
+ _save_persisted_headless(None)
4377
+ if force_kill:
4378
+ try:
4379
+ await asyncio.wait_for(asyncio.to_thread(_force_kill_browser_processes), timeout=10.0)
4380
+ except Exception:
4381
+ pass
4382
+ return "Browser completely closed and all resources released."
4383
+ except Exception as exc:
4384
+ return f"Error closing browser: {exc}"
4385
+
4386
+
4387
+ async def _restart_browser_inner(headless: Optional[bool] = None, url: Optional[str] = None) -> str:
4388
+ preserved_urls: list[str] = []
4389
+ try:
4390
+ pages = await asyncio.wait_for(session.get_pages(), timeout=CDP_OP_TIMEOUT_S)
4391
+ for p in pages:
4392
+ if not p.is_closed():
4393
+ curr = p.url
4394
+ if curr and curr != "about:blank" and not curr.startswith("chrome://") and not curr.startswith("chrome-error://"):
4395
+ preserved_urls.append(curr)
4396
+ except Exception:
4397
+ pass
4398
+
4399
+ if not preserved_urls:
4400
+ try:
4401
+ active = session._active_page
4402
+ if active is not None and not active.is_closed():
4403
+ curr = active.url
4404
+ if curr and curr != "about:blank" and not curr.startswith("chrome://") and not curr.startswith("chrome-error://"):
4405
+ preserved_urls.append(curr)
4406
+ except Exception:
4407
+ pass
4408
+
4409
+ target_url = url if url is not None else (preserved_urls[0] if preserved_urls else None)
4410
+ extra_urls = preserved_urls if url is not None else preserved_urls[1:]
4411
+
4412
+ if headless is not None:
4413
+ session.headless = bool(headless)
4414
+
4415
+ await close_browser(force_kill=True)
4416
+ _save_persisted_headless(session.headless)
4417
+ await asyncio.sleep(0.3)
4418
+ page = await session.get_active_page()
4419
+ if target_url:
4420
+ try:
4421
+ await asyncio.wait_for(
4422
+ page.goto(target_url, timeout=15000, wait_until="domcontentloaded"),
4423
+ timeout=18.0,
4424
+ )
4425
+ except Exception:
4426
+ pass
4427
+ ctx = await asyncio.wait_for(session.get_context(), timeout=GET_CONTEXT_TIMEOUT_S)
4428
+ for extra_url in extra_urls:
4429
+ if url is not None and extra_url == url:
4430
+ continue
4431
+ try:
4432
+ new_page = await asyncio.wait_for(ctx.new_page(), timeout=NEW_PAGE_TIMEOUT_S)
4433
+ await _apply_animations_to_page(new_page)
4434
+ await asyncio.wait_for(
4435
+ new_page.goto(extra_url, timeout=10000, wait_until="domcontentloaded"),
4436
+ timeout=12.0,
4437
+ )
4438
+ except Exception:
4439
+ pass
4440
+ try:
4441
+ title = await asyncio.wait_for(page.title(), timeout=PAGE_TITLE_TIMEOUT_S)
4442
+ except Exception:
4443
+ title = "(Unavailable)"
4444
+ mode_str = "Headless" if session.headless else "Headed"
4445
+ reopened = f" (reopened {len(preserved_urls)} tab(s))" if preserved_urls and url is None else ""
4446
+ return f"Browser restarted successfully in {mode_str} mode on tab [0]: '{title}' ({page.url}){reopened}"
4447
+
4448
+
4449
+ @mcp.tool()
4450
+ @_with_tool_deadline
4451
+ async def restart_browser(headless: Optional[bool] = None, url: Optional[str] = None) -> str:
4452
+ """Restart Chromium cleanly, preserving non-blank tabs unless url overrides tab [0]. headless=None keeps current mode."""
4453
+ try:
4454
+ return await asyncio.wait_for(
4455
+ _restart_browser_inner(headless=headless, url=url),
4456
+ timeout=RESTART_BROWSER_TIMEOUT_S,
4457
+ )
4458
+ except asyncio.TimeoutError:
4459
+ return f"Error restarting browser: Timed out after {int(RESTART_BROWSER_TIMEOUT_S)}s"
4460
+ except Exception as exc:
4461
+ return f"Error restarting browser: {exc}"
4462
+
4463
+
4464
+ @mcp.tool()
4465
+ @_with_tool_deadline
4466
+ async def set_headless(headless: bool = True, force: bool = False) -> str:
4467
+ """Switch headless (default) vs headed mode; restarts Chromium on change (switching to headless refuses if non-blank tabs exist unless force=True). Prefer wait_for_human() for login/2FA."""
4468
+ pages: list[Page] = []
4469
+ try:
4470
+ pages = await asyncio.wait_for(session.get_pages(), timeout=CDP_OP_TIMEOUT_S)
4471
+ except Exception:
4472
+ pages = []
4473
+
4474
+ try:
4475
+ detected_headless = await asyncio.wait_for(
4476
+ asyncio.to_thread(session._detect_cdp_headless),
4477
+ timeout=CDP_OP_TIMEOUT_S,
4478
+ )
4479
+ if detected_headless is not None:
4480
+ session.headless = detected_headless
4481
+ except Exception:
4482
+ pass
4483
+
4484
+ if session.headless == headless and (session._context is not None or session._browser is not None):
4485
+ mode_str = "Headless" if headless else "Headed"
4486
+ return f"Browser is already running in {mode_str} mode."
4487
+
4488
+ active_tabs = [
4489
+ (idx, p.url)
4490
+ for idx, p in enumerate(pages)
4491
+ if not p.is_closed() and p.url and p.url != "about:blank" and not p.url.startswith("chrome://")
4492
+ ]
4493
+ if headless and active_tabs and not force:
4494
+ target_mode = "Headless" if headless else "Headed"
4495
+ tab_list = "\n".join(f"\t[{idx}] {tab_url}" for idx, tab_url in active_tabs)
4496
+ return (
4497
+ f"Refusing to restart browser to switch to {target_mode} mode because {len(active_tabs)} "
4498
+ f"tab(s) are currently open (switching modes restarts Chromium and may disrupt active logins/sessions):\n"
4499
+ f"{tab_list}\n"
4500
+ f"Keep using the current browser mode, ask the user before interrupting, or call "
4501
+ f"set_headless(headless={headless}, force=True) to restart and reopen these URLs."
4502
+ )
4503
+
4504
+ return await restart_browser(headless=headless)
4505
+
4506
+
4507
+ def _install_browser() -> int:
4508
+ from patchright.__main__ import main as patchright_main
4509
+
4510
+ print(f"Installing Patchright Chromium (no headless shell) for {__version__}...")
4511
+ sys.argv = ["patchright", "install", "chromium", "--no-shell", "--no-progress", "--no-remove"]
4512
+ try:
4513
+ patchright_main()
4514
+ except SystemExit as exc:
4515
+ return int(exc.code or 0)
4516
+ return 0
4517
+
4518
+
4519
+ def _doctor(smoke: bool = False) -> int:
4520
+ checks = []
4521
+
4522
+ python_ok = sys.version_info >= (3, 11)
4523
+ checks.append(("Python >= 3.11", python_ok, sys.version.split()[0]))
4524
+
4525
+ try:
4526
+ from importlib.metadata import version as _dist_version
4527
+
4528
+ deps = {name: _dist_version(name) for name in ("adblock", "mcp", "patchright")}
4529
+ deps_ok = deps["mcp"] == "1.30.0"
4530
+ checks.append(("Dependencies", deps_ok, ", ".join(f"{k}={v}" for k, v in deps.items())))
4531
+ except Exception as exc:
4532
+ checks.append(("Dependencies", False, str(exc)))
4533
+
4534
+ cheatsheet_ok = os.path.isfile(_CHEATSHEET_FILE)
4535
+ checks.append(("Cheat-sheet written", cheatsheet_ok, _CHEATSHEET_FILE))
4536
+
4537
+ cdp_running = session._probe_cdp_ready()
4538
+ checks.append((f"CDP endpoint ({CDP_URL})", cdp_running, "reachable" if cdp_running else "not running (will launch on first browser call)"))
4539
+
4540
+ if cdp_running:
4541
+ from patchright.async_api import async_playwright
4542
+
4543
+ async def _probe():
4544
+ async with async_playwright() as pw:
4545
+ browser = await pw.chromium.connect_over_cdp(CDP_URL, timeout=1500)
4546
+ return len(browser.contexts[0].pages) if browser.contexts else 0
4547
+
4548
+ try:
4549
+ tabs = asyncio.run(_probe())
4550
+ checks.append(("CDP attach", True, f"{tabs} tab(s) visible"))
4551
+ except Exception as exc:
4552
+ checks.append(("CDP attach", False, str(exc)))
4553
+ else:
4554
+ async def _probe_executable():
4555
+ from patchright.async_api import async_playwright as _async_playwright
4556
+
4557
+ async with _async_playwright() as pw:
4558
+ return pw.chromium.executable_path
4559
+
4560
+ try:
4561
+ exe = asyncio.run(_probe_executable())
4562
+ browser_ok = os.path.isfile(exe) or bool(BROWSER_EXECUTABLE and os.path.isfile(BROWSER_EXECUTABLE))
4563
+ checks.append(("Browser executable", browser_ok, exe))
4564
+ except Exception as exc:
4565
+ checks.append(("Browser executable", False, str(exc)))
4566
+
4567
+ if smoke and not cdp_running:
4568
+ try:
4569
+ page = asyncio.run(session.get_active_page())
4570
+ title = asyncio.run(page.title())
4571
+ checks.append(("Browser smoke test", True, f"active tab: {title}"))
4572
+ session.close_sync()
4573
+ except Exception as exc:
4574
+ checks.append(("Browser smoke test", False, str(exc)))
4575
+
4576
+ informational = {f"CDP endpoint ({CDP_URL})", "Browser executable"}
4577
+ width = max(len(label) for label, _, _ in checks)
4578
+ failures = 0
4579
+ for label, ok, detail in checks:
4580
+ status = "OK" if ok else "FAIL"
4581
+ if not ok and label not in informational:
4582
+ failures += 1
4583
+ if not ok and label in informational:
4584
+ status = "INFO"
4585
+ print(f"[{status}] {label.ljust(width)} {detail}")
4586
+
4587
+ if failures:
4588
+ print(f"\n{failures} check(s) failed. Run 'stealth-browser --install-browser' to install Chromium.")
4589
+ return 1
4590
+ print("\nAll checks passed. stealth-browser is ready.")
4591
+ return 0
4592
+
4593
+
4594
+ def main():
4595
+ parser = argparse.ArgumentParser(
4596
+ prog="stealth-browser",
4597
+ description="FastMCP server providing browser automation tools over CDP or standalone stealth Chromium using patchright."
4598
+ )
4599
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
4600
+ parser.add_argument("--install-browser", action="store_true", help="Download the Patchright Chromium build used by the stealth browser")
4601
+ parser.add_argument("--doctor", action="store_true", help="Check installation health and verify the MCP server can start")
4602
+ parser.add_argument("--smoke", action="store_true", help="With --doctor, launch the browser and open a tab")
4603
+ args = parser.parse_args()
4604
+
4605
+ if args.install_browser:
4606
+ raise SystemExit(_install_browser())
4607
+ if args.doctor or args.smoke:
4608
+ raise SystemExit(_doctor(smoke=args.smoke))
4609
+
4610
+ def _handle_signal(signum, _frame):
4611
+ raise SystemExit(0)
4612
+
4613
+ for sig in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP):
4614
+ signal.signal(sig, _handle_signal)
4615
+
4616
+ try:
4617
+ mcp.run()
4618
+ except (KeyboardInterrupt, SystemExit):
4619
+ pass
4620
+ finally:
4621
+ session.close_sync()
4622
+ os._exit(0)
4623
+
4624
+
4625
+ if __name__ == "__main__":
4626
+ main()