chrome-remote-debugging-mcp 0.1.0__tar.gz

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.
@@ -0,0 +1,29 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main, master]
6
+ pull_request:
7
+
8
+ jobs:
9
+ test:
10
+ runs-on: ubuntu-latest
11
+ strategy:
12
+ fail-fast: false
13
+ matrix:
14
+ python-version: ["3.10", "3.11", "3.12", "3.13"]
15
+
16
+ steps:
17
+ - uses: actions/checkout@v4
18
+
19
+ - name: Install uv
20
+ uses: astral-sh/setup-uv@v5
21
+ with:
22
+ python-version: ${{ matrix.python-version }}
23
+ enable-cache: true
24
+
25
+ - name: Install dependencies
26
+ run: uv sync --group dev
27
+
28
+ - name: Run tests with coverage
29
+ run: uv run pytest --cov --cov-report=term-missing
@@ -0,0 +1,30 @@
1
+ name: Publish
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+
7
+ jobs:
8
+ publish:
9
+ runs-on: ubuntu-latest
10
+ environment: pypi
11
+ permissions:
12
+ id-token: write # OIDC token for Trusted Publishing — no API token needed
13
+
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+
17
+ - name: Install uv
18
+ uses: astral-sh/setup-uv@v5
19
+ with:
20
+ enable-cache: true
21
+
22
+ - name: Build sdist + wheel
23
+ run: uv build
24
+
25
+ - name: Check artifacts
26
+ run: uv run --with twine twine check dist/*
27
+
28
+ - name: Publish to PyPI
29
+ uses: pypa/gh-action-pypi-publish@release/v1
30
+ # no `password:` — OIDC Trusted Publishing handles auth
@@ -0,0 +1,20 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ build/
6
+ dist/
7
+ .eggs/
8
+
9
+ # Virtualenvs / tooling
10
+ .venv/
11
+ venv/
12
+ .pytest_cache/
13
+ .ruff_cache/
14
+ .mypy_cache/
15
+ .coverage
16
+ htmlcov/
17
+ coverage.xml
18
+
19
+ # Local MCP client config (repo root only)
20
+ /.mcp.json
@@ -0,0 +1,44 @@
1
+ # CLAUDE.md
2
+
3
+ This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4
+
5
+ ## What this is
6
+
7
+ An MCP server (stdio transport, built on `FastMCP`) that controls an *already-running* Chrome over the Chrome DevTools Protocol (CDP). It does **not** launch Chrome — a browser must already be listening on the remote-debugging endpoint (`google-chrome --remote-debugging-port=9222`). Currently a skeleton meant to be extended with more tools.
8
+
9
+ ## Commands
10
+
11
+ ```bash
12
+ uv sync # venv + runtime + dev group (pytest, pytest-cov)
13
+
14
+ pytest -q # full suite; addopts enforce 100% branch coverage
15
+ pytest tests/test_server.py::test_ping_connected --no-cov # single test — see gate note
16
+
17
+ python -m chrome_remote_debugging_mcp # run server over stdio
18
+ uvx --from . chrome-remote-debugging-mcp
19
+ ```
20
+
21
+ Tests need **no real Chrome and no network** — the CDP layer / websockets are monkeypatched (see `_stub` in `tests/test_server.py`, `FakeWS` in `tests/test_cdp.py`).
22
+
23
+ `pyproject.toml` bakes `--cov-branch --cov-fail-under=100` into pytest `addopts`, so **any partial run (one test or one file) reports a coverage failure and exits non-zero even when the tests themselves pass** — append `--no-cov` for those. The full `pytest` run must stay at 100%, so a new tool needs tests covering every branch (including its `{"error": ...}` paths). `__main__.py` is coverage-omitted (entry shim). CI (`.github/workflows/ci.yml`) reruns the suite on Python 3.10–3.13.
24
+
25
+ ## Architecture
26
+
27
+ Two layers, deliberately separated so `cdp.py` stays testable without MCP:
28
+
29
+ - **`cdp.py`** — thin CDP client, zero MCP awareness. Two HTTP probes (`list_targets` → `GET /json/list`, `get_version` → `GET /json/version`) and one `send(ws_url, method, params)` that opens a **fresh websocket per command**, sends one frame, and reads until a message whose `id` matches (unrelated CDP *events* have no matching id and are skipped). Raises `CDPError` on a CDP-level error.
30
+ - **`server.py`** — `FastMCP` instance + all `@mcp.tool()` functions + `main()`. Each tool resolves a target, calls `cdp.send`, and shapes the result.
31
+
32
+ Two invariants to preserve when adding tools:
33
+
34
+ 1. **Tools never raise — they return dicts.** On any failure return `{"error": "..."}`. Every existing tool wraps its CDP calls in try/except and converts exceptions (including `cdp.CDPError`) to an `{"error": ...}` payload. This is the contract MCP clients rely on.
35
+ 2. **Target resolution goes through `_resolve_target(tab_id)`.** It filters to `type == "page"` targets, defaults to the first page tab when `tab_id` is `None`, and raises `_TargetError` (a human-readable message) when Chrome is unreachable / no tabs / unknown id / not attachable. Callers catch `_TargetError` and return it as `{"error": ...}`.
36
+
37
+ `cdp_command` is the raw escape hatch: it forwards any `method` + `params` to `cdp.send`. Because it targets a **page** websocket, only page-domain methods work (`Page.*`, `DOM.*`, `Runtime.*`, `Network.*`, …); browser-level domains (`Browser.*`, `Target.*`) do not — they'd need the browser-level socket from `get_version`, which is not wired up.
38
+
39
+ ## Conventions
40
+
41
+ - Config comes from env vars read once at import in `server.py`: `CDP_URL` (default `http://localhost:9222`), and the optional SSH tunnel pair `SSH_PROXY_TO` / `SSH_PROXY_PORT`.
42
+ - **Optional SSH tunnel** (`tunnel.py`): when `SSH_PROXY_TO` (e.g. `user@remote`) is set, `main()` opens `ssh -N -L 127.0.0.1:<local>:<host>:<port> <target>` to the `CDP_URL` endpoint (now interpreted as the *remote-side* address), then rewrites the module-global `CDP_URL` to the forwarded `http://127.0.0.1:<local>`. `SSH_PROXY_PORT` fixes the local port (else auto). A local forward — not SOCKS5 — is required: Chrome's debugging port refuses any `Host` header that is not `localhost`/`127.0.0.1`. Tools are unchanged because they read `CDP_URL` at call time.
43
+ - `cdp._ids` is a module-level `itertools.count` for command/response correlation; tests monkeypatch it to reset for deterministic frame-id assertions — keep it module-level.
44
+ - All I/O is `async`; tools are `async def` and tests drive them with `asyncio.run(_fn(tool)())`. `_fn` unwraps the tool whether `@mcp.tool()` returns the raw function or a wrapper.
@@ -0,0 +1,97 @@
1
+ Metadata-Version: 2.4
2
+ Name: chrome-remote-debugging-mcp
3
+ Version: 0.1.0
4
+ Summary: MCP server for controlling Chrome over the DevTools Protocol (CDP).
5
+ Author-email: Evgenii Danilin <evgenii.danilin.m@gmail.com>
6
+ License-Expression: MIT
7
+ Keywords: cdp,chrome,devtools,mcp,remote-debugging
8
+ Requires-Python: >=3.10
9
+ Requires-Dist: httpx>=0.27
10
+ Requires-Dist: mcp>=1.2.0
11
+ Requires-Dist: websockets>=12.0
12
+ Description-Content-Type: text/markdown
13
+
14
+ # chrome-remote-debugging-mcp
15
+
16
+ MCP server that controls a running Chrome over the **Chrome DevTools Protocol (CDP)**.
17
+ It connects to Chrome's remote-debugging endpoint and exposes browser control as MCP tools.
18
+
19
+ ## Requirements
20
+
21
+ - Python ≥ 3.10
22
+ - A Chrome/Chromium started with remote debugging:
23
+
24
+ ```bash
25
+ google-chrome --remote-debugging-port=9222
26
+ ```
27
+
28
+ ## Register with an MCP client
29
+
30
+ Example `mcpServers` entry:
31
+
32
+ ```json
33
+ {
34
+ "mcpServers": {
35
+ "chrome-remote-debugging": {
36
+ "command": "uvx",
37
+ "args": ["chrome-remote-debugging-mcp"],
38
+ "env": { "CDP_URL": "http://localhost:9222" }
39
+ }
40
+ }
41
+ }
42
+ ```
43
+
44
+ ## Tools
45
+
46
+ | Tool | Args | Returns |
47
+ |-------------|-----------------------------|-------------------------------------------|
48
+ | `ping` | — | `{connected, cdp_url, browser, protocol}` |
49
+ | `list_tabs` | — | `{"tabs": [{id, title, url, type}, ...]}` |
50
+ | `navigate` | `url`, `tab_id?` | `{tab_id, url, frameId}` |
51
+ | `evaluate` | `expression`, `tab_id?` | `{tab_id, value, type}` |
52
+ | `cdp_command` | `method`, `params?`, `tab_id?` | `{tab_id, method, result}` |
53
+
54
+ `cdp_command` is a raw CDP escape hatch: pass any CDP `method` + `params` and get
55
+ the raw response, for cases the typed tools above don't cover. It targets a *page*
56
+ socket, so page-domain methods work (`Page.*`, `DOM.*`, `Runtime.*`,
57
+ `Network.*`, …); browser-level domains (`Browser.*`, `Target.*`) do not.
58
+
59
+ On any Chrome connection problem a tool returns `{"error": "..."}` instead of
60
+ crashing.
61
+
62
+ ### Configuration
63
+
64
+ | Env var | Default | Meaning |
65
+ |-----------|---------------------------|--------------------------------|
66
+ | `CDP_URL` | `http://localhost:9222` | Chrome remote-debugging origin |
67
+
68
+ ## SSH tunnel (optional)
69
+
70
+ To control a Chrome that only listens on a remote host's loopback, set:
71
+
72
+ | Env var | Default | Meaning |
73
+ |---------|---------|---------|
74
+ | `CDP_URL` | `http://localhost:9222` | Chrome endpoint. With a tunnel active, the **remote-side** address to forward to. |
75
+ | `SSH_PROXY_TO` | unset | SSH target, e.g. `user@remote`. Presence enables the tunnel. |
76
+ | `SSH_PROXY_PORT` | unset | Fixed local port. Auto-assigned when unset. |
77
+
78
+ The server runs `ssh -N -L 127.0.0.1:<local>:<host>:<port> <target>` and points
79
+ CDP at the forwarded port. Requires key-based SSH auth (`BatchMode=yes`) and the
80
+ `ssh` client on `PATH`. The tunnel uses `StrictHostKeyChecking=accept-new`
81
+ (trust-on-first-use: unknown host keys are accepted automatically on first
82
+ connect).
83
+
84
+ ## Develop
85
+
86
+ ```bash
87
+ uv sync # venv + runtime + dev group
88
+ pytest -q
89
+ ```
90
+
91
+ Locally, from a checkout (no publish needed):
92
+
93
+ ```bash
94
+ uvx --from . chrome-remote-debugging-mcp
95
+ # or
96
+ python -m chrome_remote_debugging_mcp
97
+ ```
@@ -0,0 +1,84 @@
1
+ # chrome-remote-debugging-mcp
2
+
3
+ MCP server that controls a running Chrome over the **Chrome DevTools Protocol (CDP)**.
4
+ It connects to Chrome's remote-debugging endpoint and exposes browser control as MCP tools.
5
+
6
+ ## Requirements
7
+
8
+ - Python ≥ 3.10
9
+ - A Chrome/Chromium started with remote debugging:
10
+
11
+ ```bash
12
+ google-chrome --remote-debugging-port=9222
13
+ ```
14
+
15
+ ## Register with an MCP client
16
+
17
+ Example `mcpServers` entry:
18
+
19
+ ```json
20
+ {
21
+ "mcpServers": {
22
+ "chrome-remote-debugging": {
23
+ "command": "uvx",
24
+ "args": ["chrome-remote-debugging-mcp"],
25
+ "env": { "CDP_URL": "http://localhost:9222" }
26
+ }
27
+ }
28
+ }
29
+ ```
30
+
31
+ ## Tools
32
+
33
+ | Tool | Args | Returns |
34
+ |-------------|-----------------------------|-------------------------------------------|
35
+ | `ping` | — | `{connected, cdp_url, browser, protocol}` |
36
+ | `list_tabs` | — | `{"tabs": [{id, title, url, type}, ...]}` |
37
+ | `navigate` | `url`, `tab_id?` | `{tab_id, url, frameId}` |
38
+ | `evaluate` | `expression`, `tab_id?` | `{tab_id, value, type}` |
39
+ | `cdp_command` | `method`, `params?`, `tab_id?` | `{tab_id, method, result}` |
40
+
41
+ `cdp_command` is a raw CDP escape hatch: pass any CDP `method` + `params` and get
42
+ the raw response, for cases the typed tools above don't cover. It targets a *page*
43
+ socket, so page-domain methods work (`Page.*`, `DOM.*`, `Runtime.*`,
44
+ `Network.*`, …); browser-level domains (`Browser.*`, `Target.*`) do not.
45
+
46
+ On any Chrome connection problem a tool returns `{"error": "..."}` instead of
47
+ crashing.
48
+
49
+ ### Configuration
50
+
51
+ | Env var | Default | Meaning |
52
+ |-----------|---------------------------|--------------------------------|
53
+ | `CDP_URL` | `http://localhost:9222` | Chrome remote-debugging origin |
54
+
55
+ ## SSH tunnel (optional)
56
+
57
+ To control a Chrome that only listens on a remote host's loopback, set:
58
+
59
+ | Env var | Default | Meaning |
60
+ |---------|---------|---------|
61
+ | `CDP_URL` | `http://localhost:9222` | Chrome endpoint. With a tunnel active, the **remote-side** address to forward to. |
62
+ | `SSH_PROXY_TO` | unset | SSH target, e.g. `user@remote`. Presence enables the tunnel. |
63
+ | `SSH_PROXY_PORT` | unset | Fixed local port. Auto-assigned when unset. |
64
+
65
+ The server runs `ssh -N -L 127.0.0.1:<local>:<host>:<port> <target>` and points
66
+ CDP at the forwarded port. Requires key-based SSH auth (`BatchMode=yes`) and the
67
+ `ssh` client on `PATH`. The tunnel uses `StrictHostKeyChecking=accept-new`
68
+ (trust-on-first-use: unknown host keys are accepted automatically on first
69
+ connect).
70
+
71
+ ## Develop
72
+
73
+ ```bash
74
+ uv sync # venv + runtime + dev group
75
+ pytest -q
76
+ ```
77
+
78
+ Locally, from a checkout (no publish needed):
79
+
80
+ ```bash
81
+ uvx --from . chrome-remote-debugging-mcp
82
+ # or
83
+ python -m chrome_remote_debugging_mcp
84
+ ```
@@ -0,0 +1,41 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "chrome-remote-debugging-mcp"
7
+ version = "0.1.0"
8
+ description = "MCP server for controlling Chrome over the DevTools Protocol (CDP)."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ authors = [{ name = "Evgenii Danilin", email = "evgenii.danilin.m@gmail.com" }]
13
+ keywords = ["mcp", "chrome", "cdp", "devtools", "remote-debugging"]
14
+ dependencies = [
15
+ "mcp>=1.2.0",
16
+ "httpx>=0.27",
17
+ "websockets>=12.0",
18
+ ]
19
+
20
+ [dependency-groups]
21
+ dev = ["pytest>=8", "pytest-cov>=5"]
22
+
23
+ [project.scripts]
24
+ chrome-remote-debugging-mcp = "chrome_remote_debugging_mcp.server:main"
25
+
26
+ [tool.hatch.build.targets.wheel]
27
+ packages = ["src/chrome_remote_debugging_mcp"]
28
+
29
+ [tool.pytest.ini_options]
30
+ testpaths = ["tests"]
31
+ addopts = "--cov --cov-branch --cov-report=term-missing --cov-fail-under=100"
32
+
33
+ [tool.coverage.run]
34
+ source = ["chrome_remote_debugging_mcp"]
35
+ omit = ["*/__main__.py"] # entry shim: only runs under `python -m`, no logic
36
+
37
+ [tool.coverage.report]
38
+ exclude_lines = [
39
+ "pragma: no cover",
40
+ 'if __name__ == .__main__.:',
41
+ ]
@@ -0,0 +1,3 @@
1
+ """chrome-remote-debugging-mcp — control a running Chrome over CDP via MCP."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,6 @@
1
+ """Enable ``python -m chrome_remote_debugging_mcp``."""
2
+
3
+ from .server import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
@@ -0,0 +1,65 @@
1
+ """Thin Chrome DevTools Protocol (CDP) client.
2
+
3
+ One job: talk to a running Chrome's remote-debugging endpoint. It can
4
+ enumerate targets over HTTP and issue a single CDP command over a target's
5
+ WebSocket. No MCP awareness lives here, which keeps it independently testable.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import itertools
11
+ import json
12
+
13
+ import httpx
14
+ import websockets
15
+
16
+ # Monotonic ids for CDP command/response correlation. Module-level so a test
17
+ # can reset it via monkeypatch for deterministic frame assertions.
18
+ _ids = itertools.count(1)
19
+
20
+
21
+ class CDPError(Exception):
22
+ """Raised when Chrome returns a CDP-level ``error`` for a command."""
23
+
24
+
25
+ async def list_targets(cdp_url: str) -> list[dict]:
26
+ """Return raw Chrome target objects via ``GET {cdp_url}/json/list``.
27
+
28
+ Each target dict carries ``id``, ``type``, ``title``, ``url`` and, for
29
+ attachable targets, ``webSocketDebuggerUrl``.
30
+ """
31
+ async with httpx.AsyncClient() as client:
32
+ resp = await client.get(f"{cdp_url}/json/list", timeout=10.0)
33
+ resp.raise_for_status()
34
+ return resp.json()
35
+
36
+
37
+ async def get_version(cdp_url: str) -> dict:
38
+ """Return Chrome/Browser info via ``GET {cdp_url}/json/version``.
39
+
40
+ Cheapest CDP endpoint — used as a connectivity probe. Carries ``Browser``,
41
+ ``Protocol-Version``, ``User-Agent``, and the browser-level websocket url.
42
+ """
43
+ async with httpx.AsyncClient() as client:
44
+ resp = await client.get(f"{cdp_url}/json/version", timeout=10.0)
45
+ resp.raise_for_status()
46
+ return resp.json()
47
+
48
+
49
+ async def send(ws_url: str, method: str, params: dict | None = None) -> dict:
50
+ """Open ``ws_url``, run one CDP command, and return its ``result``.
51
+
52
+ Unrelated CDP events (which have no matching ``id``) are skipped until the
53
+ response for this command arrives. Raises :class:`CDPError` on a CDP error.
54
+ """
55
+ command = {"id": next(_ids), "method": method, "params": params or {}}
56
+ async with websockets.connect(ws_url, max_size=None) as ws:
57
+ await ws.send(json.dumps(command))
58
+ while True:
59
+ message = json.loads(await ws.recv())
60
+ if message.get("id") != command["id"]:
61
+ continue # unrelated CDP event; keep waiting
62
+ if "error" in message:
63
+ error = message["error"]
64
+ raise CDPError(error.get("message", str(error)))
65
+ return message.get("result", {})
@@ -0,0 +1,236 @@
1
+ """FastMCP server exposing Chrome control over CDP as MCP tools.
2
+
3
+ Run over stdio (the default transport) as a console script or via
4
+ ``python -m chrome_remote_debugging_mcp``. The Chrome endpoint is read from the
5
+ ``CDP_URL`` environment variable (default ``http://localhost:9222``).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ from urllib.parse import urlparse
12
+
13
+ from mcp.server.fastmcp import FastMCP
14
+
15
+ from . import cdp
16
+ from .tunnel import SshLocalForwardTunnel
17
+
18
+
19
+ def _env_int(name: str) -> int | None:
20
+ """Read an int env var; ``None`` when unset or blank."""
21
+ raw = os.environ.get(name)
22
+ if raw is None or not raw.strip():
23
+ return None
24
+ return int(raw)
25
+
26
+
27
+ def _split_endpoint(url: str) -> tuple[str, int]:
28
+ """Parse a CDP URL into the ``(host, port)`` an ``ssh -L`` forward targets.
29
+
30
+ Defaults the port to 9222 when the URL omits it.
31
+ """
32
+ parsed = urlparse(url)
33
+ return parsed.hostname or "localhost", parsed.port or 9222
34
+
35
+
36
+ # When SSH_PROXY_TO is set, CDP_URL is the *remote-side* endpoint that gets
37
+ # forwarded; main() rewrites CDP_URL to the local forwarded URL at startup.
38
+ CDP_URL = os.environ.get("CDP_URL", "http://localhost:9222")
39
+ SSH_PROXY_TO = os.environ.get("SSH_PROXY_TO") or None
40
+ SSH_PROXY_PORT = _env_int("SSH_PROXY_PORT")
41
+
42
+ mcp = FastMCP("chrome-remote-debugging-mcp")
43
+
44
+
45
+ class _TargetError(Exception):
46
+ """Raised when a usable page target can't be resolved (reported as error)."""
47
+
48
+
49
+ async def _page_targets() -> list[dict]:
50
+ """Return only the ``page`` targets from Chrome (i.e. real tabs)."""
51
+ targets = await cdp.list_targets(CDP_URL)
52
+ return [t for t in targets if t.get("type") == "page"]
53
+
54
+
55
+ async def _resolve_target(tab_id: str | None) -> tuple[dict, str]:
56
+ """Resolve ``tab_id`` (or the first page tab) to ``(target, ws_url)``.
57
+
58
+ Raises :class:`_TargetError` with a human-readable message when Chrome is
59
+ unreachable, no tabs are open, the id is unknown, or the target is not
60
+ attachable.
61
+ """
62
+ try:
63
+ pages = await _page_targets()
64
+ except Exception as exc: # network / HTTP failure
65
+ raise _TargetError(f"cannot reach Chrome at {CDP_URL}: {exc}")
66
+ if not pages:
67
+ raise _TargetError("no page targets open")
68
+
69
+ if tab_id is None:
70
+ target = pages[0]
71
+ else:
72
+ target = next((t for t in pages if t.get("id") == tab_id), None)
73
+ if target is None:
74
+ raise _TargetError(f"tab {tab_id} not found")
75
+
76
+ ws_url = target.get("webSocketDebuggerUrl")
77
+ if not ws_url:
78
+ raise _TargetError("target has no webSocketDebuggerUrl (already attached?)")
79
+ return target, ws_url
80
+
81
+
82
+ @mcp.tool()
83
+ async def ping() -> dict:
84
+ """Check connectivity to Chrome's DevTools endpoint (``CDP_URL``).
85
+
86
+ Returns ``{"connected": True, "cdp_url", "browser", "protocol"}`` when
87
+ Chrome answers, or ``{"connected": False, "cdp_url", "error": ...}`` when it
88
+ is unreachable.
89
+ """
90
+ try:
91
+ info = await cdp.get_version(CDP_URL)
92
+ except Exception as exc:
93
+ return {"connected": False, "cdp_url": CDP_URL, "error": str(exc)}
94
+ return {
95
+ "connected": True,
96
+ "cdp_url": CDP_URL,
97
+ "browser": info.get("Browser"),
98
+ "protocol": info.get("Protocol-Version"),
99
+ }
100
+
101
+
102
+ @mcp.tool()
103
+ async def list_tabs() -> dict:
104
+ """List open Chrome page tabs.
105
+
106
+ Returns ``{"tabs": [{id, title, url, type}, ...]}`` or ``{"error": ...}``
107
+ if Chrome is unreachable.
108
+ """
109
+ try:
110
+ pages = await _page_targets()
111
+ except Exception as exc:
112
+ return {"error": f"cannot reach Chrome at {CDP_URL}: {exc}"}
113
+ return {
114
+ "tabs": [
115
+ {
116
+ "id": t.get("id"),
117
+ "title": t.get("title"),
118
+ "url": t.get("url"),
119
+ "type": t.get("type"),
120
+ }
121
+ for t in pages
122
+ ]
123
+ }
124
+
125
+
126
+ @mcp.tool()
127
+ async def navigate(url: str, tab_id: str | None = None) -> dict:
128
+ """Navigate a Chrome tab to ``url``.
129
+
130
+ Uses the first page tab when ``tab_id`` is omitted. Returns
131
+ ``{"tab_id", "url", "frameId"}`` on success, ``{"error": ...}`` otherwise.
132
+ """
133
+ try:
134
+ target, ws_url = await _resolve_target(tab_id)
135
+ except _TargetError as exc:
136
+ return {"error": str(exc)}
137
+
138
+ try:
139
+ result = await cdp.send(ws_url, "Page.navigate", {"url": url})
140
+ except cdp.CDPError as exc:
141
+ return {"error": f"CDP error: {exc}"}
142
+ except Exception as exc:
143
+ return {"error": f"navigation failed: {exc}"}
144
+
145
+ return {"tab_id": target.get("id"), "url": url, "frameId": result.get("frameId")}
146
+
147
+
148
+ @mcp.tool()
149
+ async def evaluate(expression: str, tab_id: str | None = None) -> dict:
150
+ """Evaluate a JavaScript ``expression`` in a Chrome tab.
151
+
152
+ Uses the first page tab when ``tab_id`` is omitted. Awaits promises and
153
+ returns the value by value. Returns ``{"tab_id", "value", "type"}`` on
154
+ success, or ``{"error": ...}`` on failure or an uncaught JS exception.
155
+ """
156
+ try:
157
+ target, ws_url = await _resolve_target(tab_id)
158
+ except _TargetError as exc:
159
+ return {"error": str(exc)}
160
+
161
+ try:
162
+ result = await cdp.send(
163
+ ws_url,
164
+ "Runtime.evaluate",
165
+ {"expression": expression, "returnByValue": True, "awaitPromise": True},
166
+ )
167
+ except cdp.CDPError as exc:
168
+ return {"error": f"CDP error: {exc}"}
169
+ except Exception as exc:
170
+ return {"error": f"evaluate failed: {exc}"}
171
+
172
+ if "exceptionDetails" in result:
173
+ details = result["exceptionDetails"]
174
+ text = (
175
+ details.get("exception", {}).get("description")
176
+ or details.get("text")
177
+ or "JS exception"
178
+ )
179
+ return {"error": f"JS exception: {text}"}
180
+
181
+ value = result.get("result", {})
182
+ return {"tab_id": target.get("id"), "value": value.get("value"), "type": value.get("type")}
183
+
184
+
185
+ @mcp.tool()
186
+ async def cdp_command(
187
+ method: str, params: dict | None = None, tab_id: str | None = None
188
+ ) -> dict:
189
+ """Send a raw CDP command and return its raw result — escape hatch.
190
+
191
+ Use when the higher-level tools don't cover what you need. ``method`` is any
192
+ CDP method (e.g. ``"Page.captureScreenshot"``, ``"DOM.getDocument"``,
193
+ ``"Network.enable"``); ``params`` are its parameters. Runs against the given
194
+ tab (or the first page tab). Note: this targets a *page* websocket, so
195
+ page-domain methods work; browser-level domains (``Browser.*``, ``Target.*``)
196
+ do not. Returns ``{"tab_id", "method", "result"}`` or ``{"error": ...}``.
197
+ """
198
+ try:
199
+ target, ws_url = await _resolve_target(tab_id)
200
+ except _TargetError as exc:
201
+ return {"error": str(exc)}
202
+
203
+ try:
204
+ result = await cdp.send(ws_url, method, params or {})
205
+ except cdp.CDPError as exc:
206
+ return {"error": f"CDP error: {exc}"}
207
+ except Exception as exc:
208
+ return {"error": f"CDP command failed: {exc}"}
209
+
210
+ return {"tab_id": target.get("id"), "method": method, "result": result}
211
+
212
+
213
+ def main() -> None:
214
+ """Console-script entry point: run the MCP server over stdio.
215
+
216
+ When ``SSH_PROXY_TO`` is set, open an ``ssh -L`` tunnel to the CDP endpoint
217
+ first and repoint ``CDP_URL`` at the forwarded local port, so every tool
218
+ (which reads ``CDP_URL`` at call time) transparently egresses through the
219
+ remote host. The tunnel lives exactly as long as the server.
220
+ """
221
+ global CDP_URL
222
+ tunnel: SshLocalForwardTunnel | None = None
223
+ if SSH_PROXY_TO:
224
+ host, port = _split_endpoint(CDP_URL)
225
+ tunnel = SshLocalForwardTunnel(SSH_PROXY_TO, host, port, SSH_PROXY_PORT)
226
+ tunnel.start()
227
+ CDP_URL = tunnel.local_url
228
+ try:
229
+ mcp.run()
230
+ finally:
231
+ if tunnel is not None:
232
+ tunnel.stop()
233
+
234
+
235
+ if __name__ == "__main__":
236
+ main()