@allansantos-dev/smart-tool 0.9.81 → 0.9.82
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.
- package/CHANGELOG.md +64 -0
- package/NOTICE +1 -1
- package/README.md +41 -13
- package/agent_redirect.py +32 -0
- package/autostart.py +32 -25
- package/browser_bridge.py +320 -0
- package/browser_control.py +76 -39
- package/browser_service_client.py +1 -7
- package/client_hooks.py +41 -42
- package/code_graph.py +56 -15
- package/code_graph_java.mjs +21 -12
- package/code_health.py +14 -9
- package/codex_config.py +3 -0
- package/daemon_launcher.py +37 -5
- package/doc_candidates.py +63 -0
- package/doc_check.py +9 -3
- package/doc_extras.py +2 -3
- package/doc_insights.py +26 -2
- package/doc_prose.py +59 -11
- package/doc_registry.py +241 -0
- package/doc_scope.py +205 -39
- package/doc_turn.py +205 -0
- package/doc_validate.py +52 -9
- package/document_read.py +4 -2
- package/edit_shape.py +119 -0
- package/endpoint_sync.py +3 -21
- package/engine_home.py +95 -0
- package/hook_call.py +132 -0
- package/hook_decision.py +100 -6
- package/hooks/pretool_router.py +36 -30
- package/hooks/turn_end.py +40 -0
- package/index_views.py +5 -0
- package/install.py +24 -9
- package/lazy_mcp_proxy.py +10 -9
- package/local_embedder.py +8 -1
- package/locales/pt-BR.json +1 -2
- package/model_breaker.py +6 -5
- package/package.json +2 -2
- package/process_limits.py +17 -3
- package/project_identity.py +19 -1
- package/project_scan.py +98 -0
- package/scout_access.py +48 -0
- package/shell_reads.py +67 -0
- package/smart_tool_daemon.py +144 -39
- package/tray.py +31 -0
- package/venv_launch.py +67 -0
- package/version.py +1 -1
- package/web_adapters/node/engine-home.mjs +42 -0
- package/web_adapters/node/package-lock.json +13 -0
- package/web_adapters/node/package.json +1 -0
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
"""Playwright MCP over the daemon's HTTP server, for clients that keep one stdio server per conversation.
|
|
2
|
+
|
|
3
|
+
Codex starts every registered stdio server once per conversation thread, so each open thread held its own proxy
|
|
4
|
+
process even when it never opened a browser. Codex registers `playwright` by URL instead (browser_control) and this
|
|
5
|
+
bridge answers it at `/playwright/mcp` as an MCP Streamable HTTP server (JSON replies): `initialize`, `ping` and
|
|
6
|
+
`tools/list` come from the handshake cache browser_control wrote, and the first tool call starts ONE shared Playwright
|
|
7
|
+
MCP server (its own HTTP mode, `--isolated`: every MCP session gets a browser context of its own) that all client
|
|
8
|
+
sessions use through a child session each. The child is killed with its process tree after IDLE_S without a request,
|
|
9
|
+
and when the daemon exits (on Windows a kill-on-close job ends it even when the daemon is killed hard); the next tool
|
|
10
|
+
call starts it again.
|
|
11
|
+
|
|
12
|
+
`browser_run_code_unsafe` and the rest of browser_control.DENIED_TOOLS are neither listed nor callable here.
|
|
13
|
+
"""
|
|
14
|
+
import http.client
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import socket
|
|
18
|
+
import subprocess
|
|
19
|
+
import threading
|
|
20
|
+
import time
|
|
21
|
+
import uuid
|
|
22
|
+
|
|
23
|
+
import browser_control
|
|
24
|
+
import lazy_mcp_proxy
|
|
25
|
+
import paths
|
|
26
|
+
import process_limits
|
|
27
|
+
|
|
28
|
+
PATH = browser_control.BRIDGE_PATH
|
|
29
|
+
IDLE_S = 3600
|
|
30
|
+
START_TIMEOUT_S = lazy_mcp_proxy.INIT_TIMEOUT_S
|
|
31
|
+
REQUEST_TIMEOUT_S = 300
|
|
32
|
+
LOG_PATH = os.path.join(paths.DATA_DIR, "playwright-bridge.log")
|
|
33
|
+
_NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0)
|
|
34
|
+
_ACCEPT = "application/json, text/event-stream"
|
|
35
|
+
_INIT_ID = "smart-tool-bridge-init"
|
|
36
|
+
_DEFAULT_CLIENT = {"protocolVersion": lazy_mcp_proxy.KNOWN_PROTOCOLS[2], "capabilities": {},
|
|
37
|
+
"clientInfo": {"name": "smart-tool-bridge", "version": "1"}}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _error(request_id, code, message):
|
|
41
|
+
return {"jsonrpc": "2.0", "id": request_id, "error": {"code": code, "message": message[:500]}}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _free_port():
|
|
45
|
+
with socket.socket() as probe:
|
|
46
|
+
probe.bind(("127.0.0.1", 0))
|
|
47
|
+
return probe.getsockname()[1]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _log_tail(limit=300):
|
|
51
|
+
try:
|
|
52
|
+
return process_limits.file_tail(LOG_PATH, limit)
|
|
53
|
+
except OSError:
|
|
54
|
+
return ""
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _matching(message, request_id):
|
|
58
|
+
"""The JSON-RPC response in message (a dict, or a batch list) for request_id, else None."""
|
|
59
|
+
for item in message if isinstance(message, list) else [message]:
|
|
60
|
+
if isinstance(item, dict) and item.get("id") == request_id and ("result" in item or "error" in item):
|
|
61
|
+
return item
|
|
62
|
+
return None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _read_reply(response, request_id):
|
|
66
|
+
"""The response to request_id in an HTTP reply that is plain JSON or an event stream whose `data:` events hold
|
|
67
|
+
JSON-RPC messages (notifications may precede the response). RuntimeError when there is none."""
|
|
68
|
+
if not response.getheader("Content-Type", "").startswith("text/event-stream"):
|
|
69
|
+
found = _matching(json.loads(response.read()), request_id)
|
|
70
|
+
else:
|
|
71
|
+
found, data = None, []
|
|
72
|
+
for raw in response:
|
|
73
|
+
line = raw.decode("utf-8", "replace").rstrip("\r\n")
|
|
74
|
+
if line.startswith("data:"):
|
|
75
|
+
data.append(line[5:].removeprefix(" "))
|
|
76
|
+
elif not line and data:
|
|
77
|
+
try:
|
|
78
|
+
found = _matching(json.loads("\n".join(data)), request_id)
|
|
79
|
+
except ValueError:
|
|
80
|
+
pass
|
|
81
|
+
data = []
|
|
82
|
+
if found:
|
|
83
|
+
break
|
|
84
|
+
if found is None:
|
|
85
|
+
raise RuntimeError(f"the browser server sent no response to request {request_id!r}")
|
|
86
|
+
return found
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class _Child:
|
|
90
|
+
"""The shared Playwright MCP server: its process, its port, and the child session id it gave each client session."""
|
|
91
|
+
|
|
92
|
+
def __init__(self, proc, port):
|
|
93
|
+
self.proc, self.port = proc, port
|
|
94
|
+
self.sessions = {}
|
|
95
|
+
self.gone = threading.Event()
|
|
96
|
+
|
|
97
|
+
def alive(self):
|
|
98
|
+
return self.proc.poll() is None
|
|
99
|
+
|
|
100
|
+
def kill(self):
|
|
101
|
+
lazy_mcp_proxy.Proxy.kill(self.proc)
|
|
102
|
+
self.proc.wait(10)
|
|
103
|
+
self.gone.set()
|
|
104
|
+
|
|
105
|
+
def request(self, method, session, message=None):
|
|
106
|
+
"""One HTTP request to the child's MCP endpoint; returns (Mcp-Session-Id header, JSON-RPC response or None).
|
|
107
|
+
RuntimeError on an HTTP error status or a missing response, OSError when the child cannot be reached."""
|
|
108
|
+
headers = {"Accept": _ACCEPT, "Content-Type": "application/json"}
|
|
109
|
+
if session:
|
|
110
|
+
headers["Mcp-Session-Id"] = session
|
|
111
|
+
connection = http.client.HTTPConnection("127.0.0.1", self.port, timeout=REQUEST_TIMEOUT_S)
|
|
112
|
+
try:
|
|
113
|
+
connection.request(method, "/mcp", json.dumps(message) if message else None, headers)
|
|
114
|
+
response = connection.getresponse()
|
|
115
|
+
if response.status >= 300:
|
|
116
|
+
raise RuntimeError(f"the browser server answered HTTP {response.status}: "
|
|
117
|
+
f"{response.read(300).decode('utf-8', 'replace').strip()}")
|
|
118
|
+
if not message or "id" not in message:
|
|
119
|
+
response.read()
|
|
120
|
+
return response.getheader("Mcp-Session-Id"), None
|
|
121
|
+
return response.getheader("Mcp-Session-Id"), _read_reply(response, message["id"])
|
|
122
|
+
finally:
|
|
123
|
+
connection.close()
|
|
124
|
+
|
|
125
|
+
def open_session(self, params):
|
|
126
|
+
"""A child session initialized with the client's own initialize params."""
|
|
127
|
+
session, reply = self.request("POST", None, {"jsonrpc": "2.0", "id": _INIT_ID, "method": "initialize",
|
|
128
|
+
"params": params})
|
|
129
|
+
if "error" in reply:
|
|
130
|
+
raise RuntimeError(f"the browser server refused initialize: {reply['error']}")
|
|
131
|
+
if not session:
|
|
132
|
+
raise RuntimeError("the browser server gave no Mcp-Session-Id")
|
|
133
|
+
self.request("POST", session, {"jsonrpc": "2.0", "method": "notifications/initialized"})
|
|
134
|
+
return session
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class Bridge:
|
|
138
|
+
"""The HTTP-independent half of the endpoint: `post` and `delete` take what the daemon read from a request and
|
|
139
|
+
return what it must answer. Client sessions live here; the shared child and the child sessions are started when a
|
|
140
|
+
tool call needs them."""
|
|
141
|
+
|
|
142
|
+
def __init__(self, idle_s=IDLE_S, clock=time.monotonic, watch=True):
|
|
143
|
+
"""idle_s: seconds without a request after which the child stops; clock: monotonic seconds (replaceable in
|
|
144
|
+
tests); watch: whether a thread stops the idle child (False leaves it to `stop_if_idle` calls)."""
|
|
145
|
+
self._idle_s, self._clock, self._watch = idle_s, clock, watch
|
|
146
|
+
self._lock = threading.Lock()
|
|
147
|
+
self._sessions = {}
|
|
148
|
+
self._last_used = clock()
|
|
149
|
+
self.child = None
|
|
150
|
+
self.active = 0
|
|
151
|
+
self._job = None
|
|
152
|
+
|
|
153
|
+
def post(self, session_id, message):
|
|
154
|
+
"""One JSON-RPC message of a client POST. Returns (HTTP status, extra headers, JSON payload or None).
|
|
155
|
+
Notifications and client responses mean nothing to the bridge: 202. A request whose session is unknown, or
|
|
156
|
+
absent when it is not `initialize`, is 404."""
|
|
157
|
+
method, request_id = message.get("method"), message.get("id")
|
|
158
|
+
if method == "initialize" and request_id is not None:
|
|
159
|
+
return self._initialize(request_id, message.get("params"))
|
|
160
|
+
with self._lock:
|
|
161
|
+
known = session_id in self._sessions
|
|
162
|
+
if not known:
|
|
163
|
+
return 404, {}, _error(request_id, -32600, "unknown or missing Mcp-Session-Id: send initialize first")
|
|
164
|
+
if method is None or request_id is None:
|
|
165
|
+
return 202, {}, None
|
|
166
|
+
if method == "ping":
|
|
167
|
+
return 200, {}, {"jsonrpc": "2.0", "id": request_id, "result": {}}
|
|
168
|
+
if method == "tools/list":
|
|
169
|
+
return self._answer_tools_list(request_id)
|
|
170
|
+
params = message.get("params")
|
|
171
|
+
name = params.get("name") if isinstance(params, dict) else None
|
|
172
|
+
if method == "tools/call" and name in browser_control.DENIED_TOOLS:
|
|
173
|
+
return 200, {}, _error(request_id, -32602, f"tool {name} is not available through Smart Tool")
|
|
174
|
+
return self._forward(session_id, message)
|
|
175
|
+
|
|
176
|
+
def delete(self, session_id):
|
|
177
|
+
"""Ends the client session and its child session; 204, or 404 when the session is unknown."""
|
|
178
|
+
with self._lock:
|
|
179
|
+
if self._sessions.pop(session_id, None) is None:
|
|
180
|
+
return 404
|
|
181
|
+
child = self.child
|
|
182
|
+
child_session = child.sessions.pop(session_id, None) if child else None
|
|
183
|
+
if child_session:
|
|
184
|
+
try:
|
|
185
|
+
child.request("DELETE", child_session)
|
|
186
|
+
except (OSError, RuntimeError, http.client.HTTPException):
|
|
187
|
+
pass # the child is gone or lost the session: its browser context went with it
|
|
188
|
+
return 204
|
|
189
|
+
|
|
190
|
+
def stop(self):
|
|
191
|
+
"""Kills the shared child with its process tree; client sessions stay and the next tool call starts it again."""
|
|
192
|
+
with self._lock:
|
|
193
|
+
self._drop_child()
|
|
194
|
+
|
|
195
|
+
def stop_if_idle(self):
|
|
196
|
+
"""Stops the child when no request reached it for the idle time and none is running; True when it stopped."""
|
|
197
|
+
with self._lock:
|
|
198
|
+
if self.child is None or self.active or self._clock() - self._last_used < self._idle_s:
|
|
199
|
+
return False
|
|
200
|
+
self._drop_child()
|
|
201
|
+
return True
|
|
202
|
+
|
|
203
|
+
def _initialize(self, request_id, params):
|
|
204
|
+
try:
|
|
205
|
+
handshake = lazy_mcp_proxy.load_handshake(browser_control.HANDSHAKE_PATH)
|
|
206
|
+
except RuntimeError as exc:
|
|
207
|
+
return 200, {}, _error(request_id, -32000, str(exc))
|
|
208
|
+
session_id = uuid.uuid4().hex
|
|
209
|
+
with self._lock:
|
|
210
|
+
self._sessions[session_id] = params if isinstance(params, dict) else _DEFAULT_CLIENT
|
|
211
|
+
result = lazy_mcp_proxy.local_initialize(handshake, params if isinstance(params, dict) else None)
|
|
212
|
+
return 200, {"Mcp-Session-Id": session_id}, {"jsonrpc": "2.0", "id": request_id, "result": result}
|
|
213
|
+
|
|
214
|
+
@staticmethod
|
|
215
|
+
def _answer_tools_list(request_id):
|
|
216
|
+
try:
|
|
217
|
+
tools = lazy_mcp_proxy.load_handshake(browser_control.HANDSHAKE_PATH)["tools"]
|
|
218
|
+
except RuntimeError as exc:
|
|
219
|
+
return 200, {}, _error(request_id, -32000, str(exc))
|
|
220
|
+
tools = [tool for tool in tools if tool.get("name") not in browser_control.DENIED_TOOLS]
|
|
221
|
+
return 200, {}, {"jsonrpc": "2.0", "id": request_id, "result": {"tools": tools}}
|
|
222
|
+
|
|
223
|
+
def _forward(self, session_id, message):
|
|
224
|
+
"""Passes a request to the client session's child session and returns the child's response; a failure at any
|
|
225
|
+
step is a -32000 error that says which."""
|
|
226
|
+
request_id = message["id"]
|
|
227
|
+
try:
|
|
228
|
+
child, child_session = self._acquire(session_id)
|
|
229
|
+
except (OSError, RuntimeError, ValueError, subprocess.SubprocessError, http.client.HTTPException) as exc:
|
|
230
|
+
return 200, {}, _error(request_id, -32000, f"could not start the browser server: {exc}")
|
|
231
|
+
try:
|
|
232
|
+
_session, reply = child.request("POST", child_session, message)
|
|
233
|
+
return 200, {}, reply
|
|
234
|
+
except (OSError, RuntimeError, ValueError, http.client.HTTPException) as exc:
|
|
235
|
+
return 200, {}, _error(request_id, -32000, f"the browser server failed: {exc}")
|
|
236
|
+
finally:
|
|
237
|
+
self._release()
|
|
238
|
+
|
|
239
|
+
def _acquire(self, session_id):
|
|
240
|
+
"""The running child and the session's child session (both created when missing), counted as in use until
|
|
241
|
+
`_release`."""
|
|
242
|
+
with self._lock:
|
|
243
|
+
params = self._sessions.get(session_id)
|
|
244
|
+
if params is None:
|
|
245
|
+
raise RuntimeError("the session ended")
|
|
246
|
+
if self.child is not None and not self.child.alive():
|
|
247
|
+
self._drop_child()
|
|
248
|
+
if self.child is None:
|
|
249
|
+
self.child = self._start_child()
|
|
250
|
+
child = self.child
|
|
251
|
+
if session_id not in child.sessions:
|
|
252
|
+
child.sessions[session_id] = child.open_session(params)
|
|
253
|
+
self.active += 1
|
|
254
|
+
self._last_used = self._clock()
|
|
255
|
+
return child, child.sessions[session_id]
|
|
256
|
+
|
|
257
|
+
def _release(self):
|
|
258
|
+
with self._lock:
|
|
259
|
+
self.active -= 1
|
|
260
|
+
self._last_used = self._clock()
|
|
261
|
+
|
|
262
|
+
def _start_child(self):
|
|
263
|
+
"""Starts the shared Playwright MCP server on a free loopback port and waits until it accepts connections;
|
|
264
|
+
RuntimeError (child killed) when it exits or stays closed for START_TIMEOUT_S."""
|
|
265
|
+
command = browser_control.server_command()
|
|
266
|
+
port = _free_port()
|
|
267
|
+
os.makedirs(os.path.dirname(LOG_PATH), exist_ok=True)
|
|
268
|
+
os.makedirs(browser_control.OUTPUT_DIR, exist_ok=True)
|
|
269
|
+
with open(LOG_PATH, "wb") as log:
|
|
270
|
+
# The server's own host check accepts only the Host header of the address it serves.
|
|
271
|
+
proc = subprocess.Popen([*command, "--port", str(port), "--host", "127.0.0.1",
|
|
272
|
+
"--allowed-hosts", f"127.0.0.1:{port}"], cwd=browser_control.OUTPUT_DIR,
|
|
273
|
+
stdin=subprocess.DEVNULL, stdout=log, stderr=log, creationflags=_NO_WINDOW)
|
|
274
|
+
child = _Child(proc, port)
|
|
275
|
+
try:
|
|
276
|
+
self._bind_to_daemon(proc)
|
|
277
|
+
self._wait_for_port(child)
|
|
278
|
+
except BaseException:
|
|
279
|
+
child.kill()
|
|
280
|
+
raise
|
|
281
|
+
if self._watch:
|
|
282
|
+
threading.Thread(target=self._watch_idle, args=(child,), daemon=True).start()
|
|
283
|
+
return child
|
|
284
|
+
|
|
285
|
+
def _bind_to_daemon(self, proc):
|
|
286
|
+
"""Puts the child in a kill-on-close job, so its tree dies with the daemon even when the daemon is killed hard
|
|
287
|
+
and `stop` never runs. OSError when the system refuses: an unbound child would outlive the daemon."""
|
|
288
|
+
if os.name != "nt":
|
|
289
|
+
return
|
|
290
|
+
self._job = process_limits.bind_to_kill_on_close_job(self._job, proc)
|
|
291
|
+
|
|
292
|
+
@staticmethod
|
|
293
|
+
def _wait_for_port(child):
|
|
294
|
+
deadline = time.monotonic() + START_TIMEOUT_S
|
|
295
|
+
while True:
|
|
296
|
+
code = child.proc.poll()
|
|
297
|
+
if code is not None:
|
|
298
|
+
raise RuntimeError(f"the browser server exited with code {code} before opening its port: {_log_tail()}")
|
|
299
|
+
try:
|
|
300
|
+
socket.create_connection(("127.0.0.1", child.port), timeout=1).close()
|
|
301
|
+
return
|
|
302
|
+
except OSError:
|
|
303
|
+
pass
|
|
304
|
+
if time.monotonic() >= deadline:
|
|
305
|
+
raise RuntimeError(f"the browser server did not open its port in {START_TIMEOUT_S}s: {_log_tail()}")
|
|
306
|
+
time.sleep(0.1)
|
|
307
|
+
|
|
308
|
+
def _watch_idle(self, child):
|
|
309
|
+
interval = max(0.05, min(30.0, self._idle_s / 4))
|
|
310
|
+
while not child.gone.wait(interval):
|
|
311
|
+
self.stop_if_idle()
|
|
312
|
+
|
|
313
|
+
def _drop_child(self):
|
|
314
|
+
"""Kills the child and forgets its sessions; the caller holds the lock."""
|
|
315
|
+
child, self.child = self.child, None
|
|
316
|
+
if child is not None:
|
|
317
|
+
child.kill()
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
BRIDGE = Bridge()
|
package/browser_control.py
CHANGED
|
@@ -7,9 +7,11 @@ as the agent would: machines whose policy forbids it (corporate IT blocking remo
|
|
|
7
7
|
keep today's read-only behavior, and the reason is shown in the setup screen instead of an error. A server named
|
|
8
8
|
`playwright` the user already registered is left untouched.
|
|
9
9
|
|
|
10
|
-
|
|
11
|
-
a Node process kept idle in each session that never opens a browser cost about 97 MB of commit each. The
|
|
12
|
-
the handshake from the cache the probe writes (HANDSHAKE_PATH) and starts the real server on the first
|
|
10
|
+
Claude Code gets lazy_mcp_proxy.py around the real server as a stdio command: every session starts the registered
|
|
11
|
+
servers, and a Node process kept idle in each session that never opens a browser cost about 97 MB of commit each. The
|
|
12
|
+
proxy answers the handshake from the cache the probe writes (HANDSHAKE_PATH) and starts the real server on the first
|
|
13
|
+
tool call. Codex keeps one stdio server set per conversation thread, so it gets a URL instead: the daemon serves the
|
|
14
|
+
same tools at BRIDGE_PATH (browser_bridge.py) from one shared, lazily started server.
|
|
13
15
|
|
|
14
16
|
Pages the agent opens are untrusted input. The server never exposes tools a page registers (WebMCP); the User-Agent of
|
|
15
17
|
every request the browser makes ends with AGENT_UA_MARK, which the daemon refuses, so a page cannot steer the agent
|
|
@@ -27,6 +29,7 @@ import tempfile
|
|
|
27
29
|
import threading
|
|
28
30
|
import time
|
|
29
31
|
import tomllib
|
|
32
|
+
import urllib.parse
|
|
30
33
|
|
|
31
34
|
import atomic_io
|
|
32
35
|
import chromium_flags
|
|
@@ -36,6 +39,7 @@ import install_runtime
|
|
|
36
39
|
import lazy_mcp_proxy
|
|
37
40
|
import node_locator
|
|
38
41
|
import paths
|
|
42
|
+
import venv_launch
|
|
39
43
|
|
|
40
44
|
SERVER = "playwright"
|
|
41
45
|
CLI = install_runtime.PLAYWRIGHT_MCP_CLI
|
|
@@ -49,6 +53,7 @@ MCP_PLAYWRIGHT_BUNDLE = install_runtime.NODE_DIR / "node_modules" / "playwright-
|
|
|
49
53
|
OUTPUT_MAX_BYTES = 100 * 1024 * 1024
|
|
50
54
|
PROBE_TIMEOUT_S = 60
|
|
51
55
|
DENIED_TOOLS = ("browser_run_code_unsafe",)
|
|
56
|
+
BRIDGE_PATH = "/playwright/mcp"
|
|
52
57
|
_CODEX_TABLE_RE = re.compile(rf"^\[mcp_servers\.{SERVER}\][ \t]*\r?\n", re.M)
|
|
53
58
|
_CHROMIUM_PROBE = ("import sys\n"
|
|
54
59
|
f"sys.path.insert(0, {os.path.dirname(os.path.abspath(__file__))!r})\n"
|
|
@@ -86,13 +91,23 @@ def server_command():
|
|
|
86
91
|
"--executable-path", executable, "--output-dir", OUTPUT_DIR, "--output-max-size", str(OUTPUT_MAX_BYTES)]
|
|
87
92
|
|
|
88
93
|
|
|
89
|
-
def
|
|
90
|
-
"""The command registered in the clients: lazy_mcp_proxy.py (console Python of this installation) around command,
|
|
91
|
-
the real server line, answering from HANDSHAKE_PATH until a tool call needs the real one."""
|
|
94
|
+
def _console_python():
|
|
92
95
|
python = sys.executable
|
|
93
96
|
if os.path.basename(python).lower() == "pythonw.exe":
|
|
94
97
|
python = os.path.join(os.path.dirname(python), "python.exe")
|
|
95
|
-
return
|
|
98
|
+
return python
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def lazy_command(command):
|
|
102
|
+
"""The command registered in the clients: lazy_mcp_proxy.py around command, the real server line, answering from
|
|
103
|
+
HANDSHAKE_PATH until a tool call needs the real one. It runs on the base interpreter of this installation's venv,
|
|
104
|
+
which `lazy_environment` points at the venv, so each client session holds one proxy process instead of two."""
|
|
105
|
+
return [venv_launch.direct(_console_python())[0], PROXY, "--handshake", HANDSHAKE_PATH, "--", *command]
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def lazy_environment():
|
|
109
|
+
"""Environment variables registered with `lazy_command` (empty outside a Windows venv)."""
|
|
110
|
+
return venv_launch.direct(_console_python())[1]
|
|
96
111
|
|
|
97
112
|
|
|
98
113
|
def is_agent_browser(headers):
|
|
@@ -201,9 +216,8 @@ def registered():
|
|
|
201
216
|
return found
|
|
202
217
|
|
|
203
218
|
|
|
204
|
-
def
|
|
205
|
-
"""
|
|
206
|
-
server's too; an empty list when it is not registered."""
|
|
219
|
+
def _entry(client):
|
|
220
|
+
"""The client's `playwright` server entry as a dict; None when absent or when the client's file cannot be read."""
|
|
207
221
|
try:
|
|
208
222
|
if client == "claude":
|
|
209
223
|
with open(endpoint_sync.claude_json(), encoding="utf-8") as stream:
|
|
@@ -212,8 +226,26 @@ def registered_executables(client):
|
|
|
212
226
|
with open(_codex_config(), encoding="utf-8") as stream:
|
|
213
227
|
entry = (tomllib.loads(stream.read()).get("mcp_servers") or {}).get(SERVER)
|
|
214
228
|
except (OSError, ValueError, AttributeError):
|
|
215
|
-
return
|
|
216
|
-
|
|
229
|
+
return None
|
|
230
|
+
return entry if isinstance(entry, dict) else None
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def bridge_url():
|
|
234
|
+
"""URL of the daemon's Playwright MCP endpoint, on the address of the smart-tool entry Codex already holds (the
|
|
235
|
+
daemon keeps that one current at every start). RuntimeError when Codex holds no smart-tool entry."""
|
|
236
|
+
held = endpoint_sync.registrations().get("codex")
|
|
237
|
+
if not held:
|
|
238
|
+
raise RuntimeError(f"Codex has no {endpoint_sync.SERVER} MCP entry to take the daemon's address from; "
|
|
239
|
+
f"register {endpoint_sync.SERVER} in Codex first.")
|
|
240
|
+
parts = urllib.parse.urlsplit(held)
|
|
241
|
+
return f"{parts.scheme}://{parts.netloc}{BRIDGE_PATH}"
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def registered_executables(client):
|
|
245
|
+
"""Executables the client's `playwright` server needs: the registered command and, behind lazy_mcp_proxy, the real
|
|
246
|
+
server's too; an empty list when it is not registered or is a URL (served by the daemon, nothing to launch)."""
|
|
247
|
+
entry = _entry(client)
|
|
248
|
+
command = entry.get("command") if entry else None
|
|
217
249
|
if not isinstance(command, str):
|
|
218
250
|
return []
|
|
219
251
|
args = entry.get("args") if isinstance(entry.get("args"), list) else []
|
|
@@ -221,35 +253,36 @@ def registered_executables(client):
|
|
|
221
253
|
return [command] + ([real] if isinstance(real, str) else [])
|
|
222
254
|
|
|
223
255
|
|
|
224
|
-
def
|
|
225
|
-
"""Whether the client's registration
|
|
226
|
-
|
|
256
|
+
def _registration_usable(client):
|
|
257
|
+
"""Whether the client's registration is the current kind and the handshake cache it needs is readable. Claude Code:
|
|
258
|
+
through lazy_mcp_proxy, which answers from that cache. Codex: the URL of the daemon now running, whose bridge
|
|
259
|
+
answers from it. A registration of an older version (the Node server directly, a Codex stdio command) or a lost
|
|
260
|
+
cache both need ensure."""
|
|
261
|
+
entry = _entry(client) or {}
|
|
227
262
|
try:
|
|
228
|
-
if client == "
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
with open(_codex_config(), encoding="utf-8") as stream:
|
|
233
|
-
entry = (tomllib.loads(stream.read()).get("mcp_servers") or {}).get(SERVER)
|
|
234
|
-
args = entry.get("args") or []
|
|
235
|
-
if PROXY not in args:
|
|
263
|
+
if client == "codex":
|
|
264
|
+
if entry.get("url") != bridge_url():
|
|
265
|
+
return False
|
|
266
|
+
elif PROXY not in (entry.get("args") or []):
|
|
236
267
|
return False
|
|
237
268
|
lazy_mcp_proxy.load_handshake(HANDSHAKE_PATH)
|
|
238
|
-
except
|
|
269
|
+
except RuntimeError:
|
|
239
270
|
return False
|
|
240
271
|
return True
|
|
241
272
|
|
|
242
273
|
|
|
243
274
|
def heal(log=None):
|
|
244
|
-
"""Registers again, through ensure, each registration of ours
|
|
245
|
-
written into the client's configuration,
|
|
246
|
-
|
|
275
|
+
"""Registers again, through ensure, each registration of ours that no longer works: an executable that is gone
|
|
276
|
+
(a moved or reinstalled Node is written into the client's configuration), a lost handshake cache, a registration
|
|
277
|
+
of an older kind, or a Codex URL that is not the daemon's now (its port changed). Returns {client: ensure's
|
|
278
|
+
outcome} for the clients refreshed."""
|
|
247
279
|
refreshed = {}
|
|
248
280
|
for client in ("claude", "codex"):
|
|
249
|
-
|
|
281
|
+
entry = _entry(client) or {}
|
|
282
|
+
managed = isinstance(entry.get("command"), str) or (client == "codex" and isinstance(entry.get("url"), str))
|
|
250
283
|
ours = status().get(client, {}).get("state") in ("registered", "undenied")
|
|
251
|
-
if ours and
|
|
252
|
-
|
|
284
|
+
if ours and managed and not (all(node_locator.exists(path) for path in registered_executables(client))
|
|
285
|
+
and _registration_usable(client)):
|
|
253
286
|
refreshed[client] = ensure(client, log)
|
|
254
287
|
return refreshed
|
|
255
288
|
|
|
@@ -331,12 +364,15 @@ def deny_unsafe_tools(client):
|
|
|
331
364
|
raise ValueError(f"Client without MCP registration: {client!r}")
|
|
332
365
|
|
|
333
366
|
|
|
334
|
-
def register_command(client, command):
|
|
335
|
-
"""Official CLI command that registers a stdio server (Claude Code: user scope, every project).
|
|
367
|
+
def register_command(client, command, env=None):
|
|
368
|
+
"""Official CLI command that registers a stdio server (Claude Code: user scope, every project) with env. The server
|
|
369
|
+
name goes before `--env`, whose values Claude Code reads up to the next option, so a name after it was taken for a
|
|
370
|
+
variable."""
|
|
371
|
+
variables = [part for name, value in (env or {}).items() for part in ("--env", f"{name}={value}")]
|
|
336
372
|
if client == "claude":
|
|
337
|
-
return ["claude", "mcp", "add", "--scope", "user", SERVER, "--", *command]
|
|
373
|
+
return ["claude", "mcp", "add", "--scope", "user", SERVER, *variables, "--", *command]
|
|
338
374
|
if client == "codex":
|
|
339
|
-
return ["codex", "mcp", "add", SERVER, "--", *command]
|
|
375
|
+
return ["codex", "mcp", "add", SERVER, *variables, "--", *command]
|
|
340
376
|
raise ValueError(f"Client without MCP registration: {client!r}")
|
|
341
377
|
|
|
342
378
|
|
|
@@ -369,12 +405,13 @@ def _clip(text, limit=300):
|
|
|
369
405
|
|
|
370
406
|
|
|
371
407
|
def _add(client, command):
|
|
372
|
-
"""Registers the
|
|
373
|
-
other tools' comments)
|
|
408
|
+
"""Registers the server whose real command line is command: Codex by the URL of the daemon's bridge, its
|
|
409
|
+
config.toml edited in place (its CLI rewrites the whole file and drops other tools' comments); Claude Code as a
|
|
410
|
+
stdio lazy_command through its CLI."""
|
|
374
411
|
if client == "codex":
|
|
375
|
-
codex_config.set_server(_codex_config(), SERVER, {"
|
|
412
|
+
codex_config.set_server(_codex_config(), SERVER, {"url": bridge_url()})
|
|
376
413
|
else:
|
|
377
|
-
endpoint_sync.run_cli(register_command(client, command))
|
|
414
|
+
endpoint_sync.run_cli(register_command(client, lazy_command(command), lazy_environment()))
|
|
378
415
|
|
|
379
416
|
|
|
380
417
|
def _remove(client):
|
|
@@ -423,7 +460,7 @@ def ensure(client, log=None):
|
|
|
423
460
|
if ours and client == "claude":
|
|
424
461
|
set_claude_deny(False)
|
|
425
462
|
return _record(client, "unavailable", problem[:300], log)
|
|
426
|
-
_add(client,
|
|
463
|
+
_add(client, command)
|
|
427
464
|
if not registered().get(client):
|
|
428
465
|
return _record(client, "unavailable", "the registration finished, but the server did not appear in the "
|
|
429
466
|
"client's configuration", log)
|
|
@@ -96,13 +96,7 @@ class BrowserService:
|
|
|
96
96
|
def _bind_to_daemon(self, proc):
|
|
97
97
|
# Kill-on-close job: the browser tree dies with the daemon even when the daemon is killed hard.
|
|
98
98
|
try:
|
|
99
|
-
|
|
100
|
-
self.job = process_limits.kill_on_close_job()
|
|
101
|
-
kernel32, job = self.job
|
|
102
|
-
import ctypes
|
|
103
|
-
from ctypes import wintypes
|
|
104
|
-
if not kernel32.AssignProcessToJobObject(wintypes.HANDLE(job), wintypes.HANDLE(proc._handle)):
|
|
105
|
-
raise ctypes.WinError(ctypes.get_last_error())
|
|
99
|
+
self.job = process_limits.bind_to_kill_on_close_job(self.job, proc)
|
|
106
100
|
except OSError as exc:
|
|
107
101
|
self.stderr_tail += f"\nprocess outside the job object: {exc}\n"
|
|
108
102
|
|