chrome-remote-debugging-mcp 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.
- chrome_remote_debugging_mcp/__init__.py +3 -0
- chrome_remote_debugging_mcp/__main__.py +6 -0
- chrome_remote_debugging_mcp/cdp.py +65 -0
- chrome_remote_debugging_mcp/server.py +236 -0
- chrome_remote_debugging_mcp/tunnel.py +161 -0
- chrome_remote_debugging_mcp-0.1.0.dist-info/METADATA +97 -0
- chrome_remote_debugging_mcp-0.1.0.dist-info/RECORD +9 -0
- chrome_remote_debugging_mcp-0.1.0.dist-info/WHEEL +4 -0
- chrome_remote_debugging_mcp-0.1.0.dist-info/entry_points.txt +2 -0
|
@@ -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()
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""Optional embedded SSH local-port-forward tunnel.
|
|
2
|
+
|
|
3
|
+
When ``SSH_PROXY_TO`` is set, the server spawns
|
|
4
|
+
``ssh -N -L 127.0.0.1:<local_port>:<remote_host>:<remote_port> <target>`` and
|
|
5
|
+
points the CDP layer at the forwarded local port. This lets the MCP server run
|
|
6
|
+
on the host while reaching a Chrome remote-debugging endpoint that only listens
|
|
7
|
+
on a *remote* host's loopback (e.g. Chrome started with
|
|
8
|
+
``--remote-debugging-port=9222`` on a box reachable only over SSH).
|
|
9
|
+
|
|
10
|
+
A local forward (``-L``) is used rather than a SOCKS5 dynamic forward (``-D``)
|
|
11
|
+
because Chrome's debugging port has DNS-rebinding protection: it refuses any
|
|
12
|
+
request whose ``Host`` header is not ``localhost``/``127.0.0.1``. Forwarding a
|
|
13
|
+
local port keeps the ``Host`` header at ``127.0.0.1`` and makes Chrome emit
|
|
14
|
+
``webSocketDebuggerUrl`` values that already point back through the local port.
|
|
15
|
+
|
|
16
|
+
Everything here logs to **stderr**: stdout is the MCP stdio (JSON-RPC) channel
|
|
17
|
+
and must never be polluted.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import atexit
|
|
23
|
+
import contextlib
|
|
24
|
+
import socket
|
|
25
|
+
import subprocess
|
|
26
|
+
import sys
|
|
27
|
+
import threading
|
|
28
|
+
import time
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _pick_free_port() -> int:
|
|
32
|
+
"""Ask the OS for an unused loopback TCP port."""
|
|
33
|
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
|
34
|
+
s.bind(("127.0.0.1", 0))
|
|
35
|
+
return s.getsockname()[1]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _port_open(port: int) -> bool:
|
|
39
|
+
"""True once something accepts connections on 127.0.0.1:port."""
|
|
40
|
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
|
41
|
+
s.settimeout(0.5)
|
|
42
|
+
return s.connect_ex(("127.0.0.1", port)) == 0
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _log(msg: str) -> None:
|
|
46
|
+
print(f"[ssh-tunnel] {msg}", file=sys.stderr, flush=True)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class SshLocalForwardTunnel:
|
|
50
|
+
"""A managed ``ssh -N -L`` local port forward.
|
|
51
|
+
|
|
52
|
+
Lifecycle mirrors the server: ``start()`` before serving, ``stop()`` after.
|
|
53
|
+
Forwards a local loopback port to ``remote_host:remote_port`` as resolved on
|
|
54
|
+
the *remote* side of the ssh connection.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
def __init__(
|
|
58
|
+
self,
|
|
59
|
+
target: str,
|
|
60
|
+
remote_host: str,
|
|
61
|
+
remote_port: int,
|
|
62
|
+
local_port: int | None = None,
|
|
63
|
+
*,
|
|
64
|
+
connect_timeout: float = 15.0,
|
|
65
|
+
) -> None:
|
|
66
|
+
self.target = target
|
|
67
|
+
self.remote_host = remote_host
|
|
68
|
+
self.remote_port = remote_port
|
|
69
|
+
self.local_port = local_port if (local_port is not None and local_port > 0) else _pick_free_port()
|
|
70
|
+
self._connect_timeout = connect_timeout
|
|
71
|
+
self._proc: subprocess.Popen[str] | None = None
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def local_url(self) -> str:
|
|
75
|
+
return f"http://127.0.0.1:{self.local_port}"
|
|
76
|
+
|
|
77
|
+
def _build_cmd(self) -> list[str]:
|
|
78
|
+
# BatchMode=yes: fail fast instead of hanging on a password prompt
|
|
79
|
+
# (key-based auth is required for an unattended tunnel).
|
|
80
|
+
# ExitOnForwardFailure=yes: if the local -L bind fails, ssh exits so we
|
|
81
|
+
# surface the error rather than a silently-dead forward.
|
|
82
|
+
# ServerAlive*: detect a dropped connection and let ssh tear down.
|
|
83
|
+
return [
|
|
84
|
+
"ssh",
|
|
85
|
+
"-N",
|
|
86
|
+
"-T",
|
|
87
|
+
"-o", "BatchMode=yes",
|
|
88
|
+
"-o", "ExitOnForwardFailure=yes",
|
|
89
|
+
"-o", "ServerAliveInterval=30",
|
|
90
|
+
"-o", "ServerAliveCountMax=3",
|
|
91
|
+
"-o", "StrictHostKeyChecking=accept-new",
|
|
92
|
+
"-L", f"127.0.0.1:{self.local_port}:{self.remote_host}:{self.remote_port}",
|
|
93
|
+
self.target,
|
|
94
|
+
]
|
|
95
|
+
|
|
96
|
+
def _drain_stderr(self) -> None:
|
|
97
|
+
"""Forward the ssh child's stderr to our log so a full pipe never
|
|
98
|
+
blocks it and steady-state ssh diagnostics stay visible."""
|
|
99
|
+
proc = self._proc
|
|
100
|
+
if proc is None or proc.stderr is None:
|
|
101
|
+
return
|
|
102
|
+
try:
|
|
103
|
+
for line in proc.stderr:
|
|
104
|
+
_log(line.rstrip())
|
|
105
|
+
except (ValueError, OSError):
|
|
106
|
+
pass # pipe closed during shutdown
|
|
107
|
+
|
|
108
|
+
def start(self) -> None:
|
|
109
|
+
"""Spawn ssh and block until the forwarded port accepts connections."""
|
|
110
|
+
cmd = self._build_cmd()
|
|
111
|
+
_log(f"starting: {' '.join(cmd)}")
|
|
112
|
+
self._proc = subprocess.Popen(
|
|
113
|
+
cmd,
|
|
114
|
+
stdin=subprocess.DEVNULL,
|
|
115
|
+
stdout=subprocess.DEVNULL,
|
|
116
|
+
stderr=subprocess.PIPE,
|
|
117
|
+
text=True,
|
|
118
|
+
)
|
|
119
|
+
# Ensure the child never outlives us even on an unclean exit.
|
|
120
|
+
atexit.register(self.stop)
|
|
121
|
+
|
|
122
|
+
deadline = time.monotonic() + self._connect_timeout
|
|
123
|
+
while time.monotonic() < deadline:
|
|
124
|
+
if self._proc.poll() is not None:
|
|
125
|
+
err = self._proc.stderr.read() if self._proc.stderr else ""
|
|
126
|
+
raise RuntimeError(
|
|
127
|
+
f"ssh tunnel to {self.target} exited early "
|
|
128
|
+
f"(code {self._proc.returncode}): {err.strip() or '<no stderr>'}"
|
|
129
|
+
)
|
|
130
|
+
if _port_open(self.local_port):
|
|
131
|
+
threading.Thread(target=self._drain_stderr, daemon=True).start()
|
|
132
|
+
_log(f"local forward ready on {self.local_url}")
|
|
133
|
+
return
|
|
134
|
+
time.sleep(0.2)
|
|
135
|
+
|
|
136
|
+
self.stop()
|
|
137
|
+
raise RuntimeError(
|
|
138
|
+
f"ssh tunnel to {self.target} not ready within {self._connect_timeout:.0f}s"
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
def stop(self) -> None:
|
|
142
|
+
"""Terminate the ssh child (idempotent)."""
|
|
143
|
+
if self._proc is None:
|
|
144
|
+
return
|
|
145
|
+
proc, self._proc = self._proc, None
|
|
146
|
+
if proc.poll() is None:
|
|
147
|
+
proc.terminate()
|
|
148
|
+
with contextlib.suppress(subprocess.TimeoutExpired):
|
|
149
|
+
proc.wait(timeout=5)
|
|
150
|
+
if proc.poll() is None:
|
|
151
|
+
proc.kill()
|
|
152
|
+
with contextlib.suppress(subprocess.TimeoutExpired):
|
|
153
|
+
proc.wait(timeout=5)
|
|
154
|
+
_log("stopped")
|
|
155
|
+
|
|
156
|
+
def __enter__(self) -> "SshLocalForwardTunnel":
|
|
157
|
+
self.start()
|
|
158
|
+
return self
|
|
159
|
+
|
|
160
|
+
def __exit__(self, *exc: object) -> None:
|
|
161
|
+
self.stop()
|
|
@@ -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,9 @@
|
|
|
1
|
+
chrome_remote_debugging_mcp/__init__.py,sha256=nAS9EwJAOwZ1po4SoCTFtJwckHicjLNBJsey0_S1iyo,104
|
|
2
|
+
chrome_remote_debugging_mcp/__main__.py,sha256=OBwMHYpO07v7ErYDGVM8F_EQ4RHm_FRhdprC0NlBn20,121
|
|
3
|
+
chrome_remote_debugging_mcp/cdp.py,sha256=EWR1e3L-BhIzgIoiO7aT-4fvvsaeaSPo1RL16a8Ts5s,2419
|
|
4
|
+
chrome_remote_debugging_mcp/server.py,sha256=l504nAbtYr-uGRIr38qcuBxPRUVw2OvFzXFS9chaGJs,7770
|
|
5
|
+
chrome_remote_debugging_mcp/tunnel.py,sha256=h4vX9CSZyMkSOzjkLuTTP_I9unE6Apqffq-XAzITcuk,5868
|
|
6
|
+
chrome_remote_debugging_mcp-0.1.0.dist-info/METADATA,sha256=FnkE6urhQwct-j9Xl0sG1P8koUoswZ93Z8P7zUuXYng,3341
|
|
7
|
+
chrome_remote_debugging_mcp-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
|
|
8
|
+
chrome_remote_debugging_mcp-0.1.0.dist-info/entry_points.txt,sha256=WinY5PI0qhT5dQKcDBt6dnzgejUmyloOQMyShYZlUp4,88
|
|
9
|
+
chrome_remote_debugging_mcp-0.1.0.dist-info/RECORD,,
|