driverkit 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.
@@ -0,0 +1,262 @@
1
+ """
2
+ An MCP server over one driverkit tab.
3
+
4
+ **This is the server that runs today, and it has no dependencies.** The tool
5
+ generation it exposes lives in :mod:`driverkit.mcp_core`, shared with
6
+ :mod:`driverkit.fastmcp_server`; this file is the transport and nothing else.
7
+ The point of the whole arrangement, stated where the core states it: the tool
8
+ list is generated from the tab's manifest, so nothing in this package knows the
9
+ name of a single verb.
10
+
11
+ **Transport.** This hand-rolls MCP stdio over JSON-RPC 2.0 rather than using
12
+ the ``mcp`` package. The surface needed is ``initialize``,
13
+ ``notifications/initialized``, ``tools/list``, ``tools/call`` and ``ping``, and
14
+ implementing it directly keeps the Python half dependency-free, which matches
15
+ the TS core's own promise of zero runtime dependencies. ``handle()`` is a pure
16
+ dict-to-dict function so the protocol can be tested without a subprocess.
17
+
18
+ **Authentication.** Stdio has none and needs none: the client launched this
19
+ process, so the trust boundary is the operating system's and there is nothing
20
+ on a wire to authenticate. What this server does need is a credential *of its
21
+ own* for the relay, naming the person whose tabs it may drive — see ``--token``.
22
+ An agent-facing server reachable over HTTP is a different problem and is what
23
+ :mod:`driverkit.fastmcp_server` is for; it is not hand-rolled here, because an
24
+ HTTP authentication scheme nobody else implements is one nobody else audits.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import json
30
+ import os
31
+ import sys
32
+ from typing import Any, Mapping, TextIO
33
+
34
+ from .client import Driverkit, DriverkitError
35
+ from .mcp_core import (
36
+ LIST_TABS,
37
+ READ_SCREEN,
38
+ TabTools,
39
+ arg_schema,
40
+ instructions_for,
41
+ pick_tab,
42
+ render_tabs,
43
+ tools_for,
44
+ verb_tool,
45
+ )
46
+ from .types import Manifest
47
+
48
+ __all__ = [
49
+ "PROTOCOL_VERSION",
50
+ "SERVER_NAME",
51
+ "SERVER_VERSION",
52
+ "LIST_TABS",
53
+ "READ_SCREEN",
54
+ "arg_schema",
55
+ "verb_tool",
56
+ "tools_for",
57
+ "render_tabs",
58
+ "pick_tab",
59
+ "McpServer",
60
+ "main",
61
+ ]
62
+
63
+ PROTOCOL_VERSION = "2025-06-18"
64
+ SERVER_NAME = "driverkit"
65
+ SERVER_VERSION = "0.0.0"
66
+
67
+
68
+ # ---- the server ----------------------------------------------------------
69
+
70
+
71
+ class McpServer:
72
+ """JSON-RPC 2.0 over stdio, in front of :class:`driverkit.mcp_core.TabTools`.
73
+
74
+ Everything about *what* the tools are lives in the core. This class decides
75
+ only what goes on the wire, which is why it is the half that can be tested
76
+ with a dict and no subprocess.
77
+ """
78
+
79
+ def __init__(self, client: Driverkit, tab: str) -> None:
80
+ self.client = client
81
+ self.tab = tab
82
+ self.tools = TabTools(client, tab)
83
+
84
+ def manifest(self) -> Manifest:
85
+ return self.tools.manifest()
86
+
87
+ # -- JSON-RPC ---------------------------------------------------------
88
+
89
+ def handle(self, message: Mapping[str, Any]) -> dict[str, Any] | None:
90
+ """One JSON-RPC message in, at most one out.
91
+
92
+ Returns ``None`` for a notification. A JSON-RPC notification has no
93
+ ``id`` and must get no reply at all — answering one is the most common
94
+ way a hand-rolled MCP server hangs a client, which sees a response it
95
+ has no pending request for.
96
+ """
97
+ message_id = message.get("id")
98
+ method = message.get("method")
99
+ params = message.get("params") or {}
100
+ is_notification = "id" not in message
101
+
102
+ try:
103
+ if method == "initialize":
104
+ result = self._initialize(params)
105
+ elif method in ("notifications/initialized", "notifications/cancelled"):
106
+ return None
107
+ elif method == "ping":
108
+ result = {}
109
+ elif method == "tools/list":
110
+ result = {"tools": self.tools.tools()}
111
+ elif method == "tools/call":
112
+ result = self._tools_call(params)
113
+ else:
114
+ if is_notification:
115
+ return None
116
+ return _error(message_id, -32601, f"method not found: {method}")
117
+ except DriverkitError as err:
118
+ # A transport failure is a JSON-RPC error, not a tool result:
119
+ # nothing ran, so there is no outcome to report to the model. A
120
+ # refusal takes the other path — see _tools_call.
121
+ if is_notification:
122
+ return None
123
+ return _error(message_id, -32603, f"driverkit: {err}")
124
+ except Exception as err: # pragma: no cover - last line of defence
125
+ if is_notification:
126
+ return None
127
+ return _error(message_id, -32603, f"{type(err).__name__}: {err}")
128
+
129
+ if is_notification:
130
+ return None
131
+ return {"jsonrpc": "2.0", "id": message_id, "result": result}
132
+
133
+ def _initialize(self, params: Mapping[str, Any]) -> dict[str, Any]:
134
+ manifest = self.manifest()
135
+ return {
136
+ # The client's requested version is not echoed back blindly: the
137
+ # spec says the server states what it actually speaks and lets the
138
+ # client disconnect if that is unacceptable.
139
+ "protocolVersion": PROTOCOL_VERSION,
140
+ "capabilities": {"tools": {"listChanged": False}},
141
+ "serverInfo": {"name": f"{SERVER_NAME}/{manifest.app}", "version": SERVER_VERSION},
142
+ "instructions": instructions_for(manifest),
143
+ }
144
+
145
+ def _tools_call(self, params: Mapping[str, Any]) -> dict[str, Any]:
146
+ """``tools/call`` — the core does the work, this wraps it in MCP content.
147
+
148
+ The ``isError`` reasoning is all in :meth:`TabTools.call`, where both
149
+ servers read it. Repeating it here would be a second opinion about what
150
+ counts as an error, and the one that drifts is the one that turns an
151
+ unknown commit into a retried commit.
152
+ """
153
+ outcome = self.tools.call(str(params.get("name")), params.get("arguments") or {})
154
+ return _content(outcome.text, is_error=outcome.is_error)
155
+
156
+ # -- stdio ------------------------------------------------------------
157
+
158
+ def serve(self, stdin: TextIO | None = None, stdout: TextIO | None = None) -> None:
159
+ """Read newline-delimited JSON-RPC from stdin, write replies to stdout.
160
+
161
+ Nothing but JSON-RPC may ever reach stdout — a stray ``print`` corrupts
162
+ the stream — so diagnostics go to stderr.
163
+ """
164
+ source = stdin if stdin is not None else sys.stdin
165
+ sink = stdout if stdout is not None else sys.stdout
166
+
167
+ for line in source:
168
+ line = line.strip()
169
+ if not line:
170
+ continue
171
+ try:
172
+ message = json.loads(line)
173
+ except ValueError:
174
+ _write(sink, _error(None, -32700, "parse error"))
175
+ continue
176
+ if not isinstance(message, Mapping):
177
+ _write(sink, _error(None, -32600, "invalid request"))
178
+ continue
179
+ reply = self.handle(message)
180
+ if reply is not None:
181
+ _write(sink, reply)
182
+
183
+
184
+ def _content(text: str, *, is_error: bool = False) -> dict[str, Any]:
185
+ return {"content": [{"type": "text", "text": text}], "isError": is_error}
186
+
187
+
188
+ def _error(message_id: Any, code: int, message: str) -> dict[str, Any]:
189
+ return {"jsonrpc": "2.0", "id": message_id, "error": {"code": code, "message": message}}
190
+
191
+
192
+ def _write(sink: TextIO, payload: Mapping[str, Any]) -> None:
193
+ sink.write(json.dumps(payload) + "\n")
194
+ sink.flush()
195
+
196
+
197
+ # ---- entry point ---------------------------------------------------------
198
+
199
+
200
+ def main(argv: list[str] | None = None) -> int:
201
+ import argparse
202
+
203
+ parser = argparse.ArgumentParser(
204
+ prog="driverkit-mcp",
205
+ description="Expose one driverkit tab to an MCP client.",
206
+ )
207
+ parser.add_argument("--relay", default="http://127.0.0.1:7777", help="relay base URL")
208
+ parser.add_argument(
209
+ "--token",
210
+ default=os.environ.get("DK_TOKEN"),
211
+ help="the tab token this server presents to the relay (env DK_TOKEN). Minted by the "
212
+ "app's backend; it names the person whose tabs this server may see. A relay with no "
213
+ "auth configured needs none. Prefer the env var: an argument is visible in `ps`.",
214
+ )
215
+ parser.add_argument(
216
+ "--tab",
217
+ default=None,
218
+ help="tab id to drive. Omit it for the tab the person is looking at: with several "
219
+ "connected, the focused one is used, and if that is ambiguous this refuses and prints "
220
+ "the tabs rather than guessing.",
221
+ )
222
+ args = parser.parse_args(argv)
223
+
224
+ client = Driverkit(args.relay, token=args.token)
225
+ tab = args.tab
226
+ if tab is None:
227
+ try:
228
+ tabs = client.tabs()
229
+ except DriverkitError as err:
230
+ print(f"driverkit: {err}", file=sys.stderr)
231
+ return 1
232
+ # `pick_tab` holds the whole rule, including the cases where it declines
233
+ # to answer; see it for the four of them. Guessing here would mean
234
+ # driving somebody's other screen. Note the listing is already scoped
235
+ # to this token's principal, so "connected" here means "connected and
236
+ # yours".
237
+ chosen = pick_tab(tabs)
238
+ if chosen is None:
239
+ # ASKED, NOT GUESSED, and the listing is the question. A person who
240
+ # is told which tabs are open and which one they are looking at can
241
+ # answer in one line; a server that picked the first one gives them
242
+ # nothing to notice until a commit lands in the wrong window.
243
+ print(
244
+ "driverkit: cannot tell which tab you mean, so pass --tab. "
245
+ + (
246
+ "More than one tab is focused or none of them reports focus"
247
+ if tabs
248
+ else "No tabs are connected"
249
+ )
250
+ + ". connected:\n"
251
+ + render_tabs(tabs, ""),
252
+ file=sys.stderr,
253
+ )
254
+ return 1
255
+ tab = chosen.id
256
+
257
+ McpServer(client, tab).serve()
258
+ return 0
259
+
260
+
261
+ if __name__ == "__main__": # pragma: no cover
262
+ raise SystemExit(main())