chrome-remote-debugging-mcp 0.1.0__tar.gz → 0.2.1__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.
Files changed (47) hide show
  1. chrome_remote_debugging_mcp-0.2.1/CLAUDE.md +71 -0
  2. chrome_remote_debugging_mcp-0.2.1/PKG-INFO +298 -0
  3. chrome_remote_debugging_mcp-0.2.1/README.md +285 -0
  4. {chrome_remote_debugging_mcp-0.1.0 → chrome_remote_debugging_mcp-0.2.1}/pyproject.toml +3 -3
  5. chrome_remote_debugging_mcp-0.2.1/scripts/capture_ax_fixtures.py +113 -0
  6. chrome_remote_debugging_mcp-0.2.1/scripts/smoke_browse.py +121 -0
  7. {chrome_remote_debugging_mcp-0.1.0 → chrome_remote_debugging_mcp-0.2.1}/src/chrome_remote_debugging_mcp/__init__.py +1 -1
  8. chrome_remote_debugging_mcp-0.2.1/src/chrome_remote_debugging_mcp/actions.py +248 -0
  9. chrome_remote_debugging_mcp-0.2.1/src/chrome_remote_debugging_mcp/autoconnect.py +176 -0
  10. chrome_remote_debugging_mcp-0.2.1/src/chrome_remote_debugging_mcp/ax.py +537 -0
  11. chrome_remote_debugging_mcp-0.2.1/src/chrome_remote_debugging_mcp/browse.py +290 -0
  12. chrome_remote_debugging_mcp-0.2.1/src/chrome_remote_debugging_mcp/cdp.py +389 -0
  13. chrome_remote_debugging_mcp-0.2.1/src/chrome_remote_debugging_mcp/debuglog.py +74 -0
  14. chrome_remote_debugging_mcp-0.2.1/src/chrome_remote_debugging_mcp/launcher.py +192 -0
  15. chrome_remote_debugging_mcp-0.2.1/src/chrome_remote_debugging_mcp/server.py +581 -0
  16. {chrome_remote_debugging_mcp-0.1.0 → chrome_remote_debugging_mcp-0.2.1}/src/chrome_remote_debugging_mcp/tunnel.py +38 -8
  17. chrome_remote_debugging_mcp-0.2.1/tests/conftest.py +31 -0
  18. chrome_remote_debugging_mcp-0.2.1/tests/fixtures/hn.json.gz +0 -0
  19. chrome_remote_debugging_mcp-0.2.1/tests/fixtures/probe.html +21 -0
  20. chrome_remote_debugging_mcp-0.2.1/tests/fixtures/probe.json +1 -0
  21. chrome_remote_debugging_mcp-0.2.1/tests/fixtures/probe_cross.html +1 -0
  22. chrome_remote_debugging_mcp-0.2.1/tests/fixtures/probe_raw.json +1 -0
  23. chrome_remote_debugging_mcp-0.2.1/tests/fixtures/probe_same.html +1 -0
  24. chrome_remote_debugging_mcp-0.2.1/tests/fixtures/wikipedia.json.gz +0 -0
  25. chrome_remote_debugging_mcp-0.2.1/tests/fixtures/youtube.json.gz +0 -0
  26. chrome_remote_debugging_mcp-0.2.1/tests/test_actions.py +388 -0
  27. chrome_remote_debugging_mcp-0.2.1/tests/test_autoconnect.py +253 -0
  28. chrome_remote_debugging_mcp-0.2.1/tests/test_ax.py +915 -0
  29. chrome_remote_debugging_mcp-0.2.1/tests/test_browse.py +746 -0
  30. chrome_remote_debugging_mcp-0.2.1/tests/test_cdp.py +1043 -0
  31. chrome_remote_debugging_mcp-0.2.1/tests/test_debuglog.py +19 -0
  32. chrome_remote_debugging_mcp-0.2.1/tests/test_fixtures.py +90 -0
  33. chrome_remote_debugging_mcp-0.2.1/tests/test_launcher.py +349 -0
  34. chrome_remote_debugging_mcp-0.2.1/tests/test_server.py +1038 -0
  35. {chrome_remote_debugging_mcp-0.1.0 → chrome_remote_debugging_mcp-0.2.1}/tests/test_tunnel.py +94 -0
  36. {chrome_remote_debugging_mcp-0.1.0 → chrome_remote_debugging_mcp-0.2.1}/uv.lock +3 -3
  37. chrome_remote_debugging_mcp-0.1.0/CLAUDE.md +0 -44
  38. chrome_remote_debugging_mcp-0.1.0/PKG-INFO +0 -97
  39. chrome_remote_debugging_mcp-0.1.0/README.md +0 -84
  40. chrome_remote_debugging_mcp-0.1.0/src/chrome_remote_debugging_mcp/cdp.py +0 -65
  41. chrome_remote_debugging_mcp-0.1.0/src/chrome_remote_debugging_mcp/server.py +0 -236
  42. chrome_remote_debugging_mcp-0.1.0/tests/test_cdp.py +0 -140
  43. chrome_remote_debugging_mcp-0.1.0/tests/test_server.py +0 -287
  44. {chrome_remote_debugging_mcp-0.1.0 → chrome_remote_debugging_mcp-0.2.1}/.github/workflows/ci.yml +0 -0
  45. {chrome_remote_debugging_mcp-0.1.0 → chrome_remote_debugging_mcp-0.2.1}/.github/workflows/publish.yml +0 -0
  46. {chrome_remote_debugging_mcp-0.1.0 → chrome_remote_debugging_mcp-0.2.1}/.gitignore +0 -0
  47. {chrome_remote_debugging_mcp-0.1.0 → chrome_remote_debugging_mcp-0.2.1}/src/chrome_remote_debugging_mcp/__main__.py +0 -0
@@ -0,0 +1,71 @@
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). By default it does **not** launch Chrome — a browser must already be listening on the remote-debugging endpoint (`google-chrome --remote-debugging-port=9222 --user-data-dir=<dir>` — since Chrome 136 the port is not opened for the default profile, so a non-default `--user-data-dir` is mandatory). Currently a skeleton meant to be extended with more tools. The opt-in exceptions are `CHROME_LAUNCH` (see Conventions), which makes the server start a local Chrome itself, and `CHROME_AUTOCONNECT`, which attaches to the user's own running Chrome (debugging enabled in `chrome://inspect/#remote-debugging`) after one "Allow" click.
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
+ uv run python scripts/capture_ax_fixtures.py # refresh tests/fixtures (needs live Chrome; see its docstring)
21
+ uv run python scripts/smoke_browse.py # end-to-end check against a live Chrome
22
+ ```
23
+
24
+ Tests need **no real Chrome and no network** — the CDP layer / websockets are monkeypatched (see `_stub` / `FakeBrowser` in `tests/test_server.py`, `FakeBrowserWS` in `tests/test_cdp.py`).
25
+
26
+ `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.
27
+
28
+ ## Architecture
29
+
30
+ Six modules, layered so the I/O-free pieces (`cdp.py`, `ax.py`) stay testable
31
+ without a browser and the MCP-aware layer (`server.py`) stays thin:
32
+
33
+ - **`cdp.py`** — thin CDP client, zero MCP awareness. `Browser` holds **one persistent connection to Chrome's browser-level websocket**, opened lazily by the first `call(method, params, *, session_id=None, timeout=None)` and reopened by the next call after it dies (never retried on its own). Commands are multiplexed over it by `id`: a single reader task resolves each caller's future from the matching reply and drops events, except `Target.detachedFromTarget`. A tab is addressed as `Page(browser, target_id)`; `send(page, method, params)` runs a command in that tab's **flattened session** (`Target.attachToTarget {flatten: true}`), attached on first use and cached until `Target.detachedFromTarget` or the connection dies. The only HTTP request is `browser_ws_url` → `GET /json/version`, for the socket's address (autoConnect makes none: its provider reads `DevToolsActivePort`); `Browser` asks for it on every (re)connect, so a respawned tunnel or relaunched Chrome is picked up. `Browser(ws_url, *, connect=None, connect_wait=None, wait_message=None)` takes the async address provider plus two optional hooks for autoConnect: `connect(url)` replaces the default `websockets.connect`, and `connect_wait` bounds how long a *caller* waits for the connection — on expiry it raises `CDPConnectTimeout` (a `CDPTimeout`, so also not a `CDPError`) with `wait_message`, while the attempt keeps running in the background (waiters use `asyncio.wait`, not `asyncio.shield`, so neither a cancelled nor a timed-out caller cancels it; the session attach and reply futures still use `shield`). `call_scope()` (applied to every tool by `server._scoped`) makes a tool call open at most one connection: if the first attempt fails, later `call`s in the same scope re-raise that error instead of dialling again. Raises `CDPError` on a CDP-level error; `CDPTimeout` when a reply exceeds `SEND_TIMEOUT` (30 s; per-call `timeout=` override; the connection stays open), `CDPDisconnected` when the connection closes before the reply, and `TargetDetached` when the tab's session goes away first — all three deliberately *not* `CDPError` subclasses, so `actions.py`'s CDPError→stale-ref conversion never misreads a stalled or dropped transport (e.g. a half-dead ssh tunnel) or a closed tab as a stale ref.
34
+ - **`ax.py`** — accessibility tree → view lines. **Pure: no I/O, no `cdp` import.** Holds every rendering rule (role tables, filtering, block grouping, indentation). Because it is pure it is tested directly against captured trees in `tests/fixtures/`, with no Chrome and no mocks. When it needs data the tree lacks — DOM attributes for elements Chrome could not name — it does not fetch: `unnamed_backend_ids(nodes)` reports what is needed and the caller passes it back via `render_nodes(..., attrs=...)`.
35
+ - **`actions.py`** — one page action → CDP frames. Uses real `Input.*` events resolved through `DOM.getBoxModel`, never synthetic JS events, so `isTrusted` is true — with one documented exception: `select` sets a `<select>`'s value with `Runtime.callFunctionOn` and dispatches `input`/`change` itself, because a native option popup is browser chrome, not page content, and cannot be driven by a click. Handlers that convert a CDP failure into a stale-ref message catch `cdp.CDPError` only, never bare `Exception`, so a transport failure (e.g. the websocket itself dying) is reported honestly instead of being misdiagnosed as a stale ref. Raises `ActionError` with agent-readable text.
36
+ - **`autoconnect.py`** — address provider and connect hook for `CHROME_AUTOCONNECT`. `AutoConnect(ssh_target, user_data_dir, local_port)`: `ws_url()` re-reads `<user-data-dir>/DevToolsActivePort` (locally, or via `ssh cat`) on every (re)connect and, over ssh, lazily (re)points a local-forward tunnel it owns at the port the file names; `connect(url)` opens the websocket with **no handshake timeout** and maps HTTP 403 / refused / closed sockets to `AutoConnectError` (a `ConnectionError`, not a `CDPError`); `wait_message` is the text of the 45 s (`ALLOW_WAIT`) "click Allow" error; `describe()` names the source for messages. No HTTP: in this mode Chrome answers `/json/*` with 404.
37
+ - **`browse.py`** — per-tab ref registry (`REGISTRY[tab_id] = _Snapshot(refs, main_frame_id, loader_id)`, where `refs` is `{ref: (frame_id, backend_node_id)}`), snapshot assembly across frames guarded by a per-tab `asyncio.Lock`, and batch execution that stops at the first failure. Registry entries (and their locks, in `_LOCKS`) are pruned only by `browse.forget`, which the `close_tab` tool calls; a tab closed any other way (by the user, by the page) leaves its entry behind.
38
+ - **`server.py`** — `FastMCP` instance + all `@mcp.tool()` functions + `main()`, plus the process-wide `cdp.Browser` (`_BROWSER`, created by the first `_browser()`; its address provider reads `CDP_URL` at connect time — in autoConnect mode it is `AutoConnect.ws_url` instead, which reads `DevToolsActivePort`). Tabs are listed, opened and closed with `Target.getTargets` / `Target.createTarget` / `Target.closeTarget` over that connection. Imports the browse module as `from . import browse as browse_engine`, because the tool function `browse` would otherwise shadow the module name — never write `import browse` when describing this layout.
39
+
40
+ Four invariants to preserve when adding tools:
41
+
42
+ 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.
43
+ 2. **Target resolution goes through `_resolve_target(tab_id)`.** It filters to `type == "page"` targets and raises `_TargetError` (a human-readable message) when Chrome is unreachable / unknown id. There is no "default tab": only `navigate` and `browse` accept `tab_id=None`, and they route it through `_target_or_new`, which opens a fresh tab via `Target.createTarget {url: "about:blank"}`, then `Page.navigate`. Every other tab-scoped tool takes a required `tab_id`. Callers catch `_TargetError` and return it as `{"error": ...}`.
44
+ 3. **`ax.py` stays pure.** No imports from `cdp`, no `async`. This is what makes the rendering rules testable against fixtures; adding I/O there would force mocks into every rule test.
45
+ 4. **Every tool goes under `@_scoped`, directly below `@mcp.tool()`.** It runs the tool inside `cdp.call_scope()`, so one tool call opens at most one connection; without it a retry loop inside the tool could reconnect mid-call, and in autoConnect mode each reconnect can cost the user another "Allow" dialog. `test_every_tool_is_scoped` in `tests/test_server.py` checks every registered tool.
46
+
47
+ `cdp_command` is the raw escape hatch: it forwards any `method` + `params` to `cdp.send`, i.e. into the tab's **persistent session**, so `objectId`/`nodeId` values and domain state survive between calls while the tab is open and the connection lives. It deliberately does not filter methods, but events are never delivered, so a command that waits on the client to answer an event hangs the tab until it is undone or the tab is closed: `Fetch.enable` (undo: `Fetch.disable`), `Debugger.pause` (`Debugger.resume`), `Target.setAutoAttach {waitForDebuggerOnStart: true}` (`…{waitForDebuggerOnStart: false}`), `Page.setInterceptFileChooserDialog {enabled: true}` (`…{enabled: false}`). Its docstring says so. `Browser.*` and `Target.*` are not supported through it; their results are undefined.
48
+
49
+ **Refs are per-snapshot, by design.** Numbering follows tree order, so a DOM change earlier in the document shifts every later ref. `browse.snapshot` replaces the tab's registry wholesale, and staleness is detected per verb by whichever CDP getter that verb calls against the (possibly dead) backend id: `DOM.getBoxModel` via `resolve_box` for `click`, `type` (which clicks first) and `hover`; `DOM.scrollIntoViewIfNeeded` called directly for a bare scroll-by-ref; and `DOM.resolveNode` via `_call_on_node` for `select`, `check` and `uncheck` — whichever one runs, a dead node makes it fail with `cdp.CDPError`, caught and re-raised as an agent-readable stale-ref message. A closed tab (`cdp.TargetDetached`) or a dropped connection (`cdp.CDPDisconnected`) is not a `CDPError` and so never becomes a stale-ref message; it reaches the tool's `{"error": ...}` as itself. An interactive node with no `backendDOMNodeId` renders without a `#N` rather than consuming a ref number it could never resolve back through (see `_content_line` in `ax.py`) — this is what keeps the printed refs and the ref map in lockstep by construction; do not "fix" it into always numbering. Do not add ref stability without re-reading D4 in `.superpowers/docs/specs/2026-09-03-browse-tools-design.md`.
50
+
51
+ **Actions can only reach the main frame.** Every action is dispatched in the page target's own session, which addresses only the main frame's renderer — a node from a same- or cross-origin child frame lives in a different coordinate space (and, cross-origin, a different renderer process) this tool cannot reach. `browse._resolve` therefore refuses a ref whose `frame_id` differs from the snapshot's `main_frame_id` with an honest "not the main frame" error instead of forwarding it to fail later as a misleading stale ref. Do not attempt coordinate offsetting or a per-frame socket to "fix" this — it is a documented limitation (see the design document's Out of scope section), not a bug.
52
+
53
+ **A snapshot's refs are only valid for that document, not just that array shape.** `browse.snapshot` stamps each `_Snapshot` with the main frame's `Page.Frame.loaderId`. `backendNodeId` numbering is monotonic and unique only within one renderer process; a cross-process navigation restarts it from 1, so without this stamp an old ref could resolve to a live, unrelated node in the new document instead of failing as stale. `run_actions` re-fetches the current loaderId before running any action in a batch and refuses the whole batch if it no longer matches.
54
+
55
+ **Snapshot assembly is serialised per tab.** `browse.snapshot` runs its whole body under `_lock_for(tab_id)`, an `asyncio.Lock` created lazily per tab id. Without it, two concurrent `browse`/`browse_view` calls on the same tab could finish in either order and the one that lost the race would return a view whose refs no longer match what `REGISTRY[tab_id]` ends up holding. The lock is per-tab, never global — do not collapse `_LOCKS` into a single lock; that would serialise unrelated tabs against each other for no reason.
56
+
57
+ **`wait_for` refuses `text` and `ref_gone` together.** `actions.wait_for` would silently prefer `text` if both were passed through; `browse._perform` rejects the combination up front with an `ActionError` instead of letting one condition win unannounced. Do not remove this guard to simplify the call site — it is the only thing standing between "ambiguous input" and "silently wrong behavior".
58
+
59
+ **The accessibility tree does not include child frames.** The main frame's `Iframe` node has empty `childIds`. `browse.snapshot` therefore walks `Page.getFrameTree` and calls `Accessibility.getFullAXTree({frameId})` once per frame. In the assembled view, every frame after the first is marked with a `frame <id>` line showing only the **first 8 characters** of the frame id (a display truncation only — the registry keys on the full id, never the truncated one).
60
+
61
+ **`Accessibility.*` and `DOM.*` getters need no `enable` call**; `enable` gates a domain's event stream, not its commands. Every command for a tab runs in that tab's one cached session, so state a command creates (an `objectId`, a `nodeId`, an enabled domain) outlives it until the tab detaches or the connection dies — which is why `actions.py` releases the objects it resolves (`Runtime.releaseObject`) rather than leaking them into a long-lived session.
62
+
63
+ ## Conventions
64
+
65
+ - Config comes from env vars read once at import in `server.py`: `CDP_URL` (default `http://localhost:9222`), the optional SSH tunnel pair `SSH_PROXY_TO` / `SSH_PROXY_PORT`, the optional `CHROME_LAUNCH` and `CHROME_AUTOCONNECT` flags, and `CHROME_USER_DATA_DIR` (autoConnect only).
66
+ - **Optional debug log** (`debuglog.py`): `MCP_DEBUG_LOG` (read once at import) wraps every registered tool so each call's arguments, result (or exception) and duration are appended to a file — `1`/`true`/`yes`/`on` → `/tmp/chrome-remote-debugging-mcp.log`, any other non-falsy value is the path. Unset/falsy leaves the tools unwrapped. `debuglog.install(mcp)` runs at the bottom of `server.py`, after every `@mcp.tool()` is registered; it is intended to stay committed.
67
+ - **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 the browser connection reads `CDP_URL` each time it (re)connects. ssh dies on its own when the connection drops (`ServerAlive*`); `server._ensure_tunnel()` — called from `_page_targets`, `_open_target` and `ping`, i.e. before any CDP traffic — respawns it on the **same** local port via `SshLocalForwardTunnel.ensure_alive()` (in a worker thread, under a lock), so `CDP_URL` stays valid. A failed respawn surfaces as the tool's `{"error": ...}`. A `stop()`-ed tunnel is never resurrected.
68
+ - **Optional Chrome auto-launch** (`launcher.py`): `CHROME_LAUNCH` (`1`/`true`/`yes`/`on`) makes the server start its own local Chrome instead of connecting to `CDP_URL`. It is mutually exclusive with `CDP_URL` and `SSH_PROXY_TO` — `main()` raises `SystemExit` when combined ("set" means present in the environment, tracked as `_CDP_URL_SET`). `main()` only creates the `ChromeLauncher`; the launch is **lazy**: `server._ensure_chrome()` — called right after `_ensure_tunnel()` in `_page_targets`, `_open_target` and `ping` — runs `ChromeLauncher.ensure_alive()` in a worker thread (under a lock) and rewrites `CDP_URL` on **every** call, because a relaunch lands on a new port. Chrome is started with `--remote-debugging-port=0` in the persistent profile `~/.cache/chrome-remote-debugging-mcp/chrome-profile`, and the port is read from `<profile>/DevToolsActivePort`. If a Chrome already serves that profile (another MCP session), the launcher attaches instead of launching; ownership is `_proc is not None`, and `stop()` (on server exit) closes Chrome only when this instance launched it — never break that, or one session would kill another's browser. Chrome's stdout goes to `DEVNULL` because stdout is the MCP channel. Launching over SSH is a planned second stage, not supported yet.
69
+ - **Optional autoConnect** (`autoconnect.py`): `CHROME_AUTOCONNECT` (`1`/`true`/`yes`/`on`) attaches to the user's own Chrome, locally or over `SSH_PROXY_TO`; `CHROME_USER_DATA_DIR` (default `~/.config/google-chrome`) says where its `DevToolsActivePort` lives and is ignored without autoConnect. It is mutually exclusive with `CDP_URL` and `CHROME_LAUNCH` (`main()` raises `SystemExit`); `SSH_PROXY_TO` is allowed but `main()` starts **no** eager tunnel — `AutoConnect` owns a lazy one, so `_TUNNEL` stays None and `_ensure_tunnel()` is a no-op. `main()` only creates the `AutoConnect` (`_AUTOCONNECT`, stopped on exit); `_browser()` then wires its `ws_url`/`connect`/`wait_message` and `connect_wait=ALLOW_WAIT` into `cdp.Browser`, and `_endpoint()` (the `describe()` string, else `CDP_URL`) replaces `CDP_URL` in every user-facing message. Chrome shows an "Allow" dialog once per server process (per websocket), so: one connection per tool call (`call_scope`), and **never add a reconnect loop, a handshake/attempt timeout or any retry** — each abandoned attempt costs the user another dialog. The pending attempt outlives a `CDPConnectTimeout`; the next call joins it, or, if it already failed with no caller left waiting (e.g. Deny after the 45 s wait), raises that failure once instead of dialling (`Browser._unreceived`).
70
+ - `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.
71
+ - 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,298 @@
1
+ Metadata-Version: 2.5
2
+ Name: chrome-remote-debugging-mcp
3
+ Version: 0.2.1
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<2,>=1.2.0
11
+ Requires-Dist: websockets>=14.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 --user-data-dir="$HOME/.config/chrome-remote-debugging-mcp"
26
+ ```
27
+
28
+ `--user-data-dir` is required: since Chrome 136 the debugging port is not
29
+ opened for the default profile. The separate profile starts logged out of
30
+ every site; keep it at a persistent path so logins survive restarts.
31
+
32
+ Alternatively, set `CHROME_LAUNCH=1` and let the server start Chrome itself —
33
+ see [Auto-launch Chrome](#auto-launch-chrome-optional).
34
+
35
+ ## Register with an MCP client
36
+
37
+ Example `mcpServers` entry:
38
+
39
+ ```json
40
+ {
41
+ "mcpServers": {
42
+ "chrome-remote-debugging": {
43
+ "command": "uvx",
44
+ "args": ["chrome-remote-debugging-mcp"],
45
+ "env": { "CDP_URL": "http://localhost:9222" }
46
+ }
47
+ }
48
+ }
49
+ ```
50
+
51
+ ## Tools
52
+
53
+ | Tool | Args | Returns |
54
+ |-------------|-----------------------------|-------------------------------------------|
55
+ | `ping` | — | `{connected, cdp_url, browser, protocol}` |
56
+ | `list_tabs` | — | `{"tabs": [{id, title, url, type}, ...]}` |
57
+ | `navigate` | `url`, `tab_id?` | `{tab_id, url, frameId}` |
58
+ | `evaluate` | `expression`, `tab_id`, `output_path?` | `{tab_id, value, type}` |
59
+ | `evaluate_file` | `path`, `tab_id`, `output_path?` | `{tab_id, value, type}` |
60
+ | `cdp_command` | `method`, `tab_id`, `params?` | `{tab_id, method, result}` |
61
+ | `browse` | `url`, `tab_id?` | `{tab_id, url, view, refs}` |
62
+ | `browse_view` | `tab_id` | `{tab_id, view, refs}` |
63
+ | `browse_act` | `actions_list`, `tab_id` | `{tab_id, steps, view, refs}` |
64
+ | `close_tab` | `tab_id` | `{tab_id, closed}` |
65
+
66
+ `navigate` and `browse` open a **new tab** when `tab_id` is omitted and return its
67
+ id; every other tab-scoped tool requires an explicit `tab_id`. Close tabs you are
68
+ done with via `close_tab`.
69
+
70
+ `evaluate` is meant for short snippets. For a long script, write it to a file and
71
+ pass its absolute path to `evaluate_file`: the file is read on the machine running
72
+ the server (not the one running Chrome) and evaluated exactly like an `evaluate`
73
+ expression, with the file named in JS stack traces.
74
+
75
+ For a large result (e.g. the text of a Jira issue), pass `output_path` to either
76
+ tool: an absolute path (`~` is expanded) on the machine running the server. The
77
+ value is written there instead of returned — a string as is (UTF-8), anything else
78
+ as indented JSON — overwriting any existing file, and the tool returns
79
+ `{tab_id, path, type, bytes}`. On an error nothing is written.
80
+
81
+ `cdp_command` is a raw CDP escape hatch: pass any CDP `method` + `params` and get
82
+ the raw response, for cases the typed tools above don't cover. It runs in the
83
+ tab's persistent session, so `objectId`/`nodeId` values and domain state (e.g.
84
+ after `Network.enable`) carry over between calls while the tab is open and the
85
+ server's connection to Chrome stays up. Events
86
+ are not delivered, so a command that waits for the client to answer one hangs
87
+ the tab until it is undone or the tab is closed: `Fetch.enable` (undo with
88
+ `Fetch.disable`), `Debugger.pause` (`Debugger.resume`), `Target.setAutoAttach`
89
+ with `waitForDebuggerOnStart: true` (set it back to `false`) and
90
+ `Page.setInterceptFileChooserDialog` with `enabled: true` (set it to `false`).
91
+ `Browser.*` and `Target.*` are not supported; their results are undefined.
92
+
93
+ On any Chrome connection problem a tool returns `{"error": "..."}` instead of
94
+ crashing.
95
+
96
+ ### Browsing a page
97
+
98
+ `browse` returns what a person would see, not HTML. The view is built from
99
+ Chrome's accessibility tree, so it covers closed shadow DOM and cross-origin
100
+ iframes — content a JavaScript DOM walk cannot reach — while hidden elements are
101
+ filtered out by Chrome itself.
102
+
103
+ ```
104
+ url https://news.ycombinator.com/
105
+ title Hacker News
106
+
107
+ link#1 -> #
108
+ link#2 "Hacker News" -> /news
109
+ link#3 "new" -> /newest
110
+ link#4 "past" -> /front
111
+ link#5 "comments" -> /newcomments
112
+ link#6 "ask" -> /ask
113
+ link#7 "show" -> /show
114
+ link#8 "jobs" -> /jobs
115
+ link#9 "submit" -> /submit
116
+ link#10 "login" -> /login?goto=news
117
+
118
+ | | | |
119
+ |---|---|---|
120
+ | 1. | link#11 -> /vote?id=49546753&how=up&goto=news | link#12 "Pre-Release of Polars 2.0" -> https://pola.rs/posts/announcing-polars-2/ link#13 "pola.rs" -> /from?site=pola.rs |
121
+ | | 107 points by link#14 "komape" -> /user?id=komape link#15 "2 hours ago" -> /item?id=49546753 link#16 "hide" -> /hide?id=49546753&goto=news link#17 "18 comments" -> /item?id=49546753 | |
122
+ …
123
+ ```
124
+
125
+ (the unedited opening of a real view, rendered from the front-page tree captured in
126
+ `tests/fixtures/hn.json.gz`.
127
+ Numbering and printing order follow document order, not Chrome's
128
+ breadth-first `Accessibility.getFullAXTree` array, so the site header's nine
129
+ navigation links print first — refs `#1`-`#10` — and only then the front
130
+ page's stories. Those sit in a semantic `<table>`, so they print as a Markdown
131
+ table: each cell's content joined on one line, links keeping their refs. The
132
+ stories, ref numbers and comment counts will differ on any given run; the
133
+ front page changes constantly.)
134
+
135
+ A blank line separates blocks and indentation shows nesting, one level per
136
+ block of ancestry — see `block_path` in `ax.py`. A table (`table`, `grid`,
137
+ `treegrid`) prints as a Markdown grid: its first row is the header when it
138
+ holds a `columnheader`, otherwise the header is left blank; short rows are
139
+ padded (the tree carries no colspan), rows with no content are dropped, and a
140
+ `|` inside a cell is escaped as `\|`.
141
+
142
+ A link shows where it goes after `->`: just the path when it stays on the
143
+ page's own origin, just `#fragment` when it points at the page itself (a
144
+ `href="#"` tab or toggle prints as `-> #`), the full url otherwise; a url
145
+ longer than 120 characters is cut with `…`. A `combobox`/`listbox` lists its
146
+ options in braces — all of them, e.g. `{один | два}` — and a
147
+ `slider`/`spinbutton` shows its bounds as `[min..max]`.
148
+
149
+ Every interactive
150
+ element Chrome can address carries a `#N` ref (the rare element with no backend
151
+ DOM id — see the invariants in `CLAUDE.md` — renders without one rather than
152
+ taking a number it can't be resolved back through). Pass those refs to
153
+ `browse_act`, which runs a batch of actions and returns one new view:
154
+
155
+ ```json
156
+ [{"do": "type", "ref": 9, "text": "polars"},
157
+ {"do": "press", "key": "Enter"},
158
+ {"do": "wait_for", "text": "results", "timeout": 5},
159
+ {"do": "click", "ref": 20}]
160
+ ```
161
+
162
+ Supported actions: `click`, `type`, `press`, `select`, `check`, `uncheck`,
163
+ `scroll`, `hover`, `wait_for`. Actions are dispatched as real CDP input events,
164
+ so sites that check `isTrusted` behave normally — except `select`: a native
165
+ `<option>` list is browser chrome, not page content, so its value is set
166
+ programmatically and `input`/`change` events are dispatched for the page to see.
167
+
168
+ **Refs live for one view.** Numbering follows document order, so any change
169
+ earlier in the page shifts every later number. Refs from an older view are
170
+ rejected with a `stale` or `not in the current view` error rather than clicking
171
+ the wrong thing. Take a new view and use its numbers.
172
+
173
+ **Refs in a child frame can be seen but not acted on.** The view is built from
174
+ every frame — including cross-origin iframes, which a JavaScript DOM walk
175
+ cannot reach at all — so an element inside one still gets a `#N` ref and
176
+ prints in the view. But every action is dispatched in the page target's own
177
+ session, which only ever reaches the main frame's renderer; a node in a
178
+ same- or cross-origin child frame lives in a different coordinate space (and,
179
+ cross-origin, a different renderer process) this tool has no way to address.
180
+ Acting on such a ref is refused with an explicit "not the main frame" error
181
+ rather than being sent anyway to fail later as a misleading stale ref.
182
+
183
+ For a page whose content arrives after load — most single-page applications —
184
+ `browse` waits for the document, not for the content. Use an explicit
185
+ `wait_for` step.
186
+
187
+ ### Configuration
188
+
189
+ | Env var | Default | Meaning |
190
+ |-----------|---------------------------|--------------------------------|
191
+ | `CDP_URL` | `http://localhost:9222` | Chrome remote-debugging origin |
192
+ | `CHROME_LAUNCH` | unset (off) | `1`/`true`/`yes`/`on` → start a local Chrome on first use instead of connecting to `CDP_URL`. Cannot be combined with `CDP_URL` or `SSH_PROXY_TO`. |
193
+ | `CHROME_AUTOCONNECT` | unset (off) | `1`/`true`/`yes`/`on` → attach to your own running Chrome (see [Attach to your own Chrome](#attach-to-your-own-chrome-autoconnect)). Cannot be combined with `CDP_URL` or `CHROME_LAUNCH`; works with `SSH_PROXY_TO` (and honours `SSH_PROXY_PORT`). |
194
+ | `CHROME_USER_DATA_DIR` | `~/.config/google-chrome` | Chrome profile directory holding `DevToolsActivePort`. Only used with `CHROME_AUTOCONNECT` (on the remote host when `SSH_PROXY_TO` is set). |
195
+ | `MCP_DEBUG_LOG` | unset (off) | Log every tool call — arguments, result, duration — to a file. `1`/`true`/`yes`/`on` → `/tmp/chrome-remote-debugging-mcp.log`; any other value is the log file path; `0`/`false`/`no`/`off` or empty → off. Read once at startup. |
196
+
197
+ ## Auto-launch Chrome (optional)
198
+
199
+ ```json
200
+ {
201
+ "mcpServers": {
202
+ "chrome-remote-debugging": {
203
+ "command": "uvx",
204
+ "args": ["chrome-remote-debugging-mcp"],
205
+ "env": { "CHROME_LAUNCH": "1" }
206
+ }
207
+ }
208
+ }
209
+ ```
210
+
211
+ The first tool call starts Chrome (`google-chrome`, `google-chrome-stable`,
212
+ `chromium` or `chromium-browser`, whichever is first on `PATH`) with its own
213
+ persistent profile at `~/.cache/chrome-remote-debugging-mcp/chrome-profile`
214
+ and a debugging port Chrome picks itself. Log in to sites once in that window;
215
+ the logins survive restarts. If Chrome is closed, the next tool call starts it
216
+ again. Several MCP sessions share the same Chrome; it is closed when the
217
+ session that started it exits.
218
+
219
+ Do not set `CDP_URL` or `SSH_PROXY_TO` together with `CHROME_LAUNCH` — the
220
+ server refuses to start.
221
+
222
+ ## Attach to your own Chrome (autoConnect)
223
+
224
+ Use your everyday Chrome, with its logins, instead of a separate debugging profile:
225
+
226
+ ```json
227
+ {
228
+ "mcpServers": {
229
+ "chrome-remote-debugging": {
230
+ "command": "uvx",
231
+ "args": ["chrome-remote-debugging-mcp"],
232
+ "env": { "CHROME_AUTOCONNECT": "1" }
233
+ }
234
+ }
235
+ }
236
+ ```
237
+
238
+ Open `chrome://inspect/#remote-debugging` in that Chrome and switch remote
239
+ debugging on. The server finds Chrome through `<profile>/DevToolsActivePort`
240
+ (`CHROME_USER_DATA_DIR`, default `~/.config/google-chrome`); Chrome serves no
241
+ HTTP in this mode. The first tool call makes Chrome show an **Allow** dialog;
242
+ click it. That is once per server process: the connection then stays open.
243
+
244
+ - **Debugging is off.** The tool returns "Chrome is not accepting debugging
245
+ connections: ask the user to enable remote debugging in
246
+ chrome://inspect/#remote-debugging, then call the tool again; that call makes
247
+ Chrome show an "Allow" dialog for the user to click". Switch it on, call
248
+ again and click **Allow** in the dialog that call opens.
249
+ - **"has not accepted the debugging connection within 45s".** Chrome is
250
+ waiting for you to click **Allow**. Click it and call the tool again; the
251
+ pending connection is kept, so no second dialog appears.
252
+ - **The server was restarted while the Allow dialog was open.** Chrome keeps
253
+ that dialog even though nothing is waiting on it. Close it with Deny or ×;
254
+ clicking Allow does nothing for the new server process, which shows its own.
255
+ - **"refused the debugging connection (HTTP 403)".** You clicked Deny, or
256
+ debugging is off. Enable it in `chrome://inspect/#remote-debugging` and call
257
+ the tool again; that call opens a new Allow dialog — click it.
258
+ - **The connection dropped mid-work** (Chrome restarted, debugging toggled).
259
+ The next tool call reconnects and Chrome shows one new Allow dialog.
260
+
261
+ For a Chrome on another machine add `SSH_PROXY_TO` (e.g. `user@remote`) and,
262
+ if needed, `CHROME_USER_DATA_DIR` for the remote profile. The server reads
263
+ `DevToolsActivePort` over `ssh` and opens the `ssh -L` forward itself, on
264
+ demand; the Allow dialog appears on the remote Chrome.
265
+
266
+ Do not set `CDP_URL` or `CHROME_LAUNCH` together with `CHROME_AUTOCONNECT` —
267
+ the server refuses to start.
268
+
269
+ ## SSH tunnel (optional)
270
+
271
+ To control a Chrome that only listens on a remote host's loopback, set:
272
+
273
+ | Env var | Default | Meaning |
274
+ |---------|---------|---------|
275
+ | `CDP_URL` | `http://localhost:9222` | Chrome endpoint. With a tunnel active, the **remote-side** address to forward to. |
276
+ | `SSH_PROXY_TO` | unset | SSH target, e.g. `user@remote`. Presence enables the tunnel. |
277
+ | `SSH_PROXY_PORT` | unset | Fixed local port. Auto-assigned when unset. |
278
+
279
+ The server runs `ssh -N -L 127.0.0.1:<local>:<host>:<port> <target>` and points
280
+ CDP at the forwarded port. Requires key-based SSH auth (`BatchMode=yes`) and the
281
+ `ssh` client on `PATH`. The tunnel uses `StrictHostKeyChecking=accept-new`
282
+ (trust-on-first-use: unknown host keys are accepted automatically on first
283
+ connect).
284
+
285
+ ## Develop
286
+
287
+ ```bash
288
+ uv sync # venv + runtime + dev group
289
+ pytest -q
290
+ ```
291
+
292
+ Locally, from a checkout (no publish needed):
293
+
294
+ ```bash
295
+ uvx --from . chrome-remote-debugging-mcp
296
+ # or
297
+ python -m chrome_remote_debugging_mcp
298
+ ```