qtpilot-bridge 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.
File without changes
@@ -0,0 +1,63 @@
1
+ """Line-delimited JSON-RPC 2.0 client for the probe socket."""
2
+ import json
3
+ import socket
4
+
5
+ DEFAULT_TIMEOUT = 10.0
6
+
7
+ class ProbeError(Exception):
8
+ def __init__(self, kind: str, message: str):
9
+ super().__init__(f"{kind}: {message}")
10
+ self.kind = kind
11
+
12
+ class ProbeClient:
13
+ def __init__(self, host: str, port: int, timeout: float = DEFAULT_TIMEOUT):
14
+ self._sock = socket.create_connection((host, port), timeout=timeout)
15
+ self._file = self._sock.makefile("rwb")
16
+ self._next_id = 1
17
+ self._default_timeout = timeout
18
+
19
+ def request(self, method: str, params: dict | None = None, timeout: float | None = None) -> dict:
20
+ if timeout is not None:
21
+ self._sock.settimeout(timeout)
22
+ try:
23
+ req_id = self._next_id
24
+ self._next_id += 1
25
+ msg = {"jsonrpc": "2.0", "id": req_id, "method": method, "params": params or {}}
26
+ self._file.write(json.dumps(msg).encode() + b"\n")
27
+ self._file.flush()
28
+ while True:
29
+ try:
30
+ line = self._file.readline()
31
+ except (socket.timeout, TimeoutError):
32
+ # The connection is unusable after an abandoned request: a late reply
33
+ # would desync every subsequent id, so close instead of leaving it open.
34
+ self.close()
35
+ raise ProbeError("timeout", "application not responding")
36
+ if not line:
37
+ raise ProbeError("connection_closed", "probe closed the connection")
38
+ resp = json.loads(line)
39
+ if resp.get("id") != req_id:
40
+ continue # stray/late response for an abandoned request; keep reading
41
+ if "error" in resp:
42
+ err = resp["error"]
43
+ kind = (err.get("data") or {}).get("kind", "unknown")
44
+ raise ProbeError(kind, err.get("message", ""))
45
+ return resp["result"]
46
+ finally:
47
+ if timeout is not None:
48
+ try:
49
+ self._sock.settimeout(self._default_timeout)
50
+ except OSError:
51
+ pass # socket was closed above (e.g. on timeout); nothing to restore
52
+
53
+ def close(self):
54
+ # makefile() holds a reference to the socket (not a dup'd fd): both must be
55
+ # closed, or the TCP connection stays open and the probe never sees the disconnect.
56
+ try:
57
+ self._file.close()
58
+ except OSError:
59
+ pass
60
+ try:
61
+ self._sock.close()
62
+ except OSError:
63
+ pass
@@ -0,0 +1,248 @@
1
+ """qt-pilot MCP server: drive Qt applications (snapshot, click, type, screenshot...)."""
2
+ import base64
3
+ import json
4
+ from typing import Any
5
+
6
+ from mcp.server.fastmcp import FastMCP, Image
7
+
8
+ from . import session as session_mod
9
+
10
+ mcp = FastMCP("qtpilot")
11
+ _sessions: dict[str, session_mod.AppSession] = {}
12
+ _next_session = 1
13
+
14
+
15
+ def _session(session_id: str | None) -> session_mod.AppSession:
16
+ if not _sessions:
17
+ raise RuntimeError("no app sessions; call app_launch first")
18
+ if session_id is None:
19
+ session_id = max(_sessions, key=lambda s: int(s[1:]))
20
+ if session_id not in _sessions:
21
+ raise RuntimeError(f"unknown session {session_id}; known: {sorted(_sessions)}")
22
+ app = _sessions[session_id]
23
+ if not app.alive:
24
+ raise RuntimeError(f"session_dead: {session_id} (app exited)")
25
+ return app
26
+
27
+
28
+ def _rpc(session_id: str | None, method: str, params: dict | None = None, timeout: float | None = None) -> Any:
29
+ return _session(session_id).client.request(method, params or {}, timeout=timeout)
30
+
31
+
32
+ def _dumps(value: Any) -> str:
33
+ return json.dumps(value, indent=1)
34
+
35
+
36
+ @mcp.tool()
37
+ def app_launch(exe: str, args: list[str] | None = None, cwd: str | None = None,
38
+ env: dict[str, str] | None = None) -> str:
39
+ """Launch a Qt executable with the qt-pilot probe injected via env, optionally merged with
40
+ caller-supplied env vars, then wait for handshake. Use this first. Returns the session id
41
+ used by every other tool."""
42
+ global _next_session
43
+ session_id = f"s{_next_session}"
44
+ _next_session += 1
45
+ app = session_mod.launch(exe, session_id, args=args, cwd=cwd, extra_env=env)
46
+ _sessions[session_id] = app
47
+ return _dumps({"session": session_id, **app.initialize_result})
48
+
49
+
50
+ @mcp.tool()
51
+ def app_attach(port: int, token: str) -> str:
52
+ """Attach to an already-running app that was started with QTPILOT_PORT/QTPILOT_TOKEN env set."""
53
+ global _next_session
54
+ session_id = f"s{_next_session}"
55
+ _next_session += 1
56
+ app = session_mod.attach(port, token, session_id)
57
+ _sessions[session_id] = app
58
+ return _dumps({"session": session_id, **app.initialize_result})
59
+
60
+
61
+ @mcp.tool()
62
+ def app_list() -> str:
63
+ """List known app sessions and whether each process is still alive."""
64
+ return _dumps({sid: {"alive": app.alive, "port": app.port} for sid, app in _sessions.items()})
65
+
66
+
67
+ @mcp.tool()
68
+ def app_stop(session: str) -> str:
69
+ """Terminate a launched app process and forget the session."""
70
+ app = _sessions.pop(session, None)
71
+ if app is None:
72
+ return _dumps({"stopped": False, "reason": "unknown session"})
73
+ if app.process and app.process.poll() is None:
74
+ app.process.kill()
75
+ if app.client:
76
+ app.client.close()
77
+ return _dumps({"stopped": True})
78
+
79
+
80
+ @mcp.tool()
81
+ def windows(session: str | None = None) -> str:
82
+ """List top-level windows (refs, titles, geometry). Cheap orientation call."""
83
+ return _dumps(_rpc(session, "windows"))
84
+
85
+
86
+ @mcp.tool()
87
+ def snapshot(session: str | None = None, window: str | None = None, root: str | None = None,
88
+ max_depth: int = 100, include_invisible: bool = False) -> str:
89
+ """UI tree with element refs — the primary way to SEE the app. Prefer this over screenshot
90
+ for finding elements and checking existence/visibility; use screenshot only for pixels."""
91
+ params: dict = {"maxDepth": max_depth, "includeInvisible": include_invisible}
92
+ if window:
93
+ params["window"] = window
94
+ if root:
95
+ params["root"] = root
96
+ return _dumps(_rpc(session, "snapshot", params))
97
+
98
+
99
+ @mcp.tool()
100
+ def query(session: str | None = None, object_name: str | None = None, text: str | None = None,
101
+ class_name: str | None = None, qml_type: str | None = None) -> str:
102
+ """Find elements by objectName / visible text / C++ class / QML type (filters AND-combine)."""
103
+ params = {k: v for k, v in {"objectName": object_name, "text": text,
104
+ "className": class_name, "qmlType": qml_type}.items() if v}
105
+ return _dumps(_rpc(session, "query", params))
106
+
107
+
108
+ @mcp.tool()
109
+ def properties(ref: str, session: str | None = None) -> str:
110
+ """Full Q_PROPERTY dump of an element (values, types, writability)."""
111
+ return _dumps(_rpc(session, "properties", {"ref": ref}))
112
+
113
+
114
+ @mcp.tool()
115
+ def screenshot(session: str | None = None, ref: str | None = None, window: str | None = None) -> Image:
116
+ """PNG of a window (window=ref) or a single element (ref=...). Use when pixels matter
117
+ (viewports, rendering); prefer snapshot for structure."""
118
+ params = {}
119
+ if ref:
120
+ params["ref"] = ref
121
+ if window:
122
+ params["window"] = window
123
+ result = _rpc(session, "screenshot", params)
124
+ return Image(data=base64.b64decode(result["base64"]), format="png")
125
+
126
+
127
+ def _click(session, ref, window, x, y, button, count, modifiers):
128
+ params: dict = {"button": button, "count": count}
129
+ if ref:
130
+ params["ref"] = ref
131
+ if window:
132
+ params["window"] = window
133
+ if x is not None:
134
+ params["x"] = x
135
+ if y is not None:
136
+ params["y"] = y
137
+ if modifiers:
138
+ params["modifiers"] = modifiers
139
+ return _dumps(_rpc(session, "click", params))
140
+
141
+
142
+ @mcp.tool()
143
+ def click(ref: str | None = None, session: str | None = None, window: str | None = None,
144
+ x: float | None = None, y: float | None = None,
145
+ modifiers: list[str] | None = None) -> str:
146
+ """Left-click an element by ref (its center), or raw window coordinates (pass window + x/y —
147
+ for 3D viewports and canvases). modifiers: ctrl/shift/alt/meta."""
148
+ return _click(session, ref, window, x, y, "left", 1, modifiers)
149
+
150
+
151
+ @mcp.tool()
152
+ def double_click(ref: str | None = None, session: str | None = None, window: str | None = None,
153
+ x: float | None = None, y: float | None = None) -> str:
154
+ """Double-click an element or window coordinates."""
155
+ return _click(session, ref, window, x, y, "left", 2, None)
156
+
157
+
158
+ @mcp.tool()
159
+ def right_click(ref: str | None = None, session: str | None = None, window: str | None = None,
160
+ x: float | None = None, y: float | None = None) -> str:
161
+ """Right-click (context menu) an element or window coordinates."""
162
+ return _click(session, ref, window, x, y, "right", 1, None)
163
+
164
+
165
+ @mcp.tool()
166
+ def type_text(ref: str, text: str, session: str | None = None) -> str:
167
+ """Focus the element and type text into it character by character."""
168
+ return _dumps(_rpc(session, "type_text", {"ref": ref, "text": text}))
169
+
170
+
171
+ @mcp.tool()
172
+ def press_key(key: str, ref: str | None = None, session: str | None = None) -> str:
173
+ """Press a key chord in QKeySequence syntax, e.g. 'Ctrl+Z', 'Enter', 'F5'.
174
+ Optional ref focuses that element first."""
175
+ params: dict = {"key": key}
176
+ if ref:
177
+ params["ref"] = ref
178
+ return _dumps(_rpc(session, "press_key", params))
179
+
180
+
181
+ @mcp.tool()
182
+ def drag(session: str | None = None, from_ref: str | None = None, to_ref: str | None = None,
183
+ from_x: float | None = None, from_y: float | None = None,
184
+ to_x: float | None = None, to_y: float | None = None,
185
+ window: str | None = None, steps: int = 10) -> str:
186
+ """Press-move-release drag: between element centers (from_ref/to_ref) or window coordinates.
187
+ Also usable for viewport rotation gestures."""
188
+ from_spec: dict = {"ref": from_ref} if from_ref else {"x": from_x, "y": from_y}
189
+ to_spec: dict = {"ref": to_ref} if to_ref else {"x": to_x, "y": to_y}
190
+ params: dict = {"from": from_spec, "to": to_spec, "steps": steps}
191
+ if window:
192
+ params["window"] = window
193
+ return _dumps(_rpc(session, "drag", params))
194
+
195
+
196
+ @mcp.tool()
197
+ def wheel(session: str | None = None, ref: str | None = None, window: str | None = None,
198
+ x: float | None = None, y: float | None = None,
199
+ delta_y: float = -120, delta_x: float = 0) -> str:
200
+ """Mouse-wheel scroll over an element or window position. delta_y<0 scrolls down/away."""
201
+ params: dict = {"deltaY": delta_y, "deltaX": delta_x}
202
+ if ref:
203
+ params["ref"] = ref
204
+ if window:
205
+ params["window"] = window
206
+ if x is not None:
207
+ params["x"] = x
208
+ if y is not None:
209
+ params["y"] = y
210
+ return _dumps(_rpc(session, "wheel", params))
211
+
212
+
213
+ @mcp.tool()
214
+ def wait_for(condition: str, session: str | None = None, ref: str | None = None,
215
+ object_name: str | None = None, text: str | None = None,
216
+ property_name: str | None = None, value: Any = None, timeout_ms: int = 5000) -> str:
217
+ """Wait until: exists | gone | visible | enabled | property_equals. Identify the element via
218
+ ref or object_name/text query. For property_equals pass property_name and value."""
219
+ params: dict = {"condition": condition, "timeoutMs": timeout_ms}
220
+ if ref:
221
+ params["ref"] = ref
222
+ else:
223
+ params["query"] = {k: v for k, v in {"objectName": object_name, "text": text}.items() if v}
224
+ if property_name:
225
+ params["property"] = property_name
226
+ if value is not None:
227
+ params["value"] = value
228
+ return _dumps(_rpc(session, "wait_for", params, timeout=timeout_ms / 1000 + 5))
229
+
230
+
231
+ @mcp.tool()
232
+ def invoke(ref: str, method: str, args: list[Any] | None = None, session: str | None = None) -> str:
233
+ """Call a slot/Q_INVOKABLE on an element/object by name with JSON args (max 4)."""
234
+ return _dumps(_rpc(session, "invoke", {"ref": ref, "method": method, "args": args or []}))
235
+
236
+
237
+ @mcp.tool()
238
+ def set_property(ref: str, property_name: str, value: Any, session: str | None = None) -> str:
239
+ """Write a Q_PROPERTY on an element (e.g. visible=false)."""
240
+ return _dumps(_rpc(session, "set_property", {"ref": ref, "property": property_name, "value": value}))
241
+
242
+
243
+ def main() -> None:
244
+ mcp.run()
245
+
246
+
247
+ if __name__ == "__main__":
248
+ main()
@@ -0,0 +1,111 @@
1
+ """Launch/attach lifecycle for probe-enabled Qt applications."""
2
+ import os
3
+ import secrets
4
+ import socket
5
+ import subprocess
6
+ import threading
7
+ import time
8
+ from dataclasses import dataclass, field
9
+ from typing import IO
10
+
11
+ from . import protocol
12
+
13
+ HANDSHAKE_TIMEOUT = 30.0
14
+ STDERR_TAIL_BYTES = 2000
15
+
16
+ def _free_port() -> int:
17
+ with socket.socket() as s:
18
+ s.bind(("127.0.0.1", 0))
19
+ return s.getsockname()[1]
20
+
21
+ class _StderrDrainer:
22
+ """Continuously drains a child process's stderr on a daemon thread.
23
+
24
+ Left undrained, the child's entire stderr output accumulates in the OS
25
+ pipe buffer; once it fills, the child blocks in write() on whatever
26
+ thread is logging -- for a Qt app that's the GUI thread, which also runs
27
+ the probe's TCP server, so a full pipe silently hangs every request.
28
+ Keeps only the last STDERR_TAIL_BYTES bytes, for error diagnostics.
29
+ """
30
+
31
+ def __init__(self, stream: IO[bytes]) -> None:
32
+ self._buf = bytearray()
33
+ self._lock = threading.Lock()
34
+ self._thread = threading.Thread(target=self._run, args=(stream,), daemon=True)
35
+ self._thread.start()
36
+
37
+ def _run(self, stream: IO[bytes]) -> None:
38
+ try:
39
+ while True:
40
+ chunk = stream.read(4096)
41
+ if not chunk:
42
+ break
43
+ with self._lock:
44
+ self._buf.extend(chunk)
45
+ del self._buf[:-STDERR_TAIL_BYTES]
46
+ except (OSError, ValueError):
47
+ pass # stream closed under us; nothing left to drain
48
+
49
+ def tail(self) -> str:
50
+ with self._lock:
51
+ return bytes(self._buf).decode(errors="replace")
52
+
53
+ def join(self, timeout: float = 1.0) -> None:
54
+ self._thread.join(timeout)
55
+
56
+ @dataclass
57
+ class AppSession:
58
+ session_id: str
59
+ port: int
60
+ token: str
61
+ process: subprocess.Popen | None
62
+ client: protocol.ProbeClient | None = None
63
+ initialize_result: dict = field(default_factory=dict)
64
+
65
+ @property
66
+ def alive(self) -> bool:
67
+ return self.process is None or self.process.poll() is None
68
+
69
+ def launch(exe: str, session_id: str, args: list[str] | None = None,
70
+ cwd: str | None = None, extra_env: dict | None = None,
71
+ probe_dir: str | None = None) -> AppSession:
72
+ port = _free_port()
73
+ token = secrets.token_hex(16)
74
+ env = dict(os.environ)
75
+ env.update(extra_env or {})
76
+ env["QT_QPA_GENERIC_PLUGINS"] = "qtpilotprobe"
77
+ probe_dir = probe_dir or os.environ.get("QTPILOT_PROBE_DIR", "")
78
+ env["QT_PLUGIN_PATH"] = probe_dir + os.pathsep + env.get("QT_PLUGIN_PATH", "")
79
+ env["QTPILOT_PORT"] = str(port)
80
+ env["QTPILOT_TOKEN"] = token
81
+ process = subprocess.Popen([exe, *(args or [])], cwd=cwd, env=env,
82
+ stderr=subprocess.PIPE, stdout=subprocess.DEVNULL)
83
+ assert process.stderr is not None # stderr=PIPE was requested above
84
+ stderr_drainer = _StderrDrainer(process.stderr)
85
+ session = AppSession(session_id, port, token, process)
86
+ deadline = time.monotonic() + HANDSHAKE_TIMEOUT
87
+ last_error = None
88
+ while time.monotonic() < deadline:
89
+ if process.poll() is not None:
90
+ stderr_drainer.join(timeout=1.0)
91
+ raise RuntimeError(
92
+ f"app exited with {process.returncode} before handshake; stderr: {stderr_drainer.tail()}")
93
+ try:
94
+ client = protocol.ProbeClient("127.0.0.1", port, timeout=2.0)
95
+ session.initialize_result = client.request(
96
+ "initialize", {"token": token, "protocolVersion": 1})
97
+ session.client = client
98
+ return session
99
+ except (OSError, protocol.ProbeError) as e:
100
+ last_error = e
101
+ time.sleep(0.25)
102
+ process.kill()
103
+ stderr_drainer.join(timeout=1.0)
104
+ raise RuntimeError(
105
+ f"probe handshake timed out after {HANDSHAKE_TIMEOUT}s: {last_error}; "
106
+ f"stderr: {stderr_drainer.tail()}")
107
+
108
+ def attach(port: int, token: str, session_id: str) -> AppSession:
109
+ client = protocol.ProbeClient("127.0.0.1", port)
110
+ result = client.request("initialize", {"token": token, "protocolVersion": 1})
111
+ return AppSession(session_id, port, token, process=None, client=client, initialize_result=result)
@@ -0,0 +1,32 @@
1
+ Metadata-Version: 2.4
2
+ Name: qtpilot-bridge
3
+ Version: 0.1.0
4
+ Summary: MCP bridge for qt-pilot: drive Qt applications from AI agents
5
+ License: MIT
6
+ Project-URL: Homepage, https://github.com/saldoran/qt-pilot
7
+ Project-URL: Repository, https://github.com/saldoran/qt-pilot
8
+ Requires-Python: >=3.11
9
+ Description-Content-Type: text/markdown
10
+ Requires-Dist: mcp>=1.2
11
+ Provides-Extra: dev
12
+ Requires-Dist: pytest>=8; extra == "dev"
13
+ Requires-Dist: pytest-asyncio>=0.24; extra == "dev"
14
+ Requires-Dist: ruff>=0.6; extra == "dev"
15
+
16
+ # qtpilot-bridge
17
+
18
+ MCP server that lets AI agents drive Qt 6 applications: launch with an injected probe
19
+ plugin, snapshot the UI tree, read properties, click, type, drag, wait for state and take
20
+ screenshots.
21
+
22
+ This package is the Python half of [qt-pilot](https://github.com/saldoran/qt-pilot). It
23
+ requires the qt-pilot **probe plugin** built against the same Qt major.minor line as the
24
+ target application — see the repository README for the 3-command CMake build.
25
+
26
+ ## Usage
27
+
28
+ ```bash
29
+ claude mcp add qtpilot -e QTPILOT_PROBE_DIR=/abs/path/to/probe-install/plugins -- uvx qtpilot-bridge
30
+ ```
31
+
32
+ Then ask the agent to `app_launch` your Qt executable. MIT licensed.
@@ -0,0 +1,9 @@
1
+ qtpilot_bridge/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ qtpilot_bridge/protocol.py,sha256=MUpbQzs9-53z-vIcmQ-F7MNSIf6VdoYov64P6x4zGMM,2620
3
+ qtpilot_bridge/server.py,sha256=dqYm8c69e6nRD1f1HdnGSu1hqHugcsMKxd3AJbLp3Q4,9727
4
+ qtpilot_bridge/session.py,sha256=q2gbnPc4KqEXxMlDZDwdNZHp2lneotUAQ7Kd-_YLWaM,4221
5
+ qtpilot_bridge-0.1.0.dist-info/METADATA,sha256=JCj_fFRjV1kQz_rof1Uqv0LQG177b4VXUVyt-9nOkaA,1166
6
+ qtpilot_bridge-0.1.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
7
+ qtpilot_bridge-0.1.0.dist-info/entry_points.txt,sha256=KlMpIr-pBvGL9N3fe0Okm7zZ605eLLvfh668lWqV7WQ,62
8
+ qtpilot_bridge-0.1.0.dist-info/top_level.txt,sha256=vdP5e1Bprqes85mY5CiKfPUQu7G4u-s6kSCe1WqxBBo,15
9
+ qtpilot_bridge-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ qtpilot-bridge = qtpilot_bridge.server:main
@@ -0,0 +1 @@
1
+ qtpilot_bridge