nini-computer-use 0.4.4__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,213 @@
1
+ """MCP stdio transport: newline-delimited JSON-RPC 2.0.
2
+
3
+ Why a hand-written loop: the surface Nini needs is three methods
4
+ (``initialize`` / ``tools/list`` / ``tools/call``), and the server must never
5
+ write anything but protocol lines to stdout — a stray ``print`` desynchronises
6
+ every MCP client. Keeping the loop here means the framing, the id correlation
7
+ and the error codes are readable in one file and testable without a socket.
8
+
9
+ Rules implemented:
10
+
11
+ * one JSON object per line on stdin/stdout, UTF-8, no BOM, no banners;
12
+ * ``initialize`` negotiates a protocol version we actually support;
13
+ * notifications (no ``id``) never get a response, including ``notifications/exit``;
14
+ * unknown methods → ``-32601``; unknown tools / invalid arguments → ``-32602``;
15
+ malformed JSON → ``-32700`` with ``id: null`` (the client can still recover);
16
+ * ``tools/list`` works without macOS permissions — only ``tools/call`` fails.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import sys
23
+ from typing import Any, BinaryIO
24
+
25
+ from .errors import BadArguments, CuError
26
+ from .tools import (
27
+ INSTRUCTIONS,
28
+ SERVER_NAME,
29
+ SERVER_VERSION,
30
+ TOOL_NAMES,
31
+ ComputerUseService,
32
+ error_result,
33
+ )
34
+
35
+ PROTOCOL_VERSION = "2025-06-18"
36
+ SUPPORTED_PROTOCOLS = ("2025-06-18", "2025-03-26", "2024-11-05")
37
+
38
+ PARSE_ERROR = -32700
39
+ INVALID_REQUEST = -32600
40
+ METHOD_NOT_FOUND = -32601
41
+ INVALID_PARAMS = -32602
42
+ INTERNAL_ERROR = -32603
43
+
44
+
45
+ def _error(request_id: Any, code: int, message: str, data: Any = None) -> dict[str, Any]:
46
+ body: dict[str, Any] = {
47
+ "jsonrpc": "2.0",
48
+ "id": request_id,
49
+ "error": {"code": code, "message": message},
50
+ }
51
+ if data is not None:
52
+ body["error"]["data"] = data
53
+ return body
54
+
55
+
56
+ def _result(request_id: Any, result: dict[str, Any]) -> dict[str, Any]:
57
+ return {"jsonrpc": "2.0", "id": request_id, "result": result}
58
+
59
+
60
+ class McpServer:
61
+ """Single-threaded MCP server over a line-oriented stream pair."""
62
+
63
+ def __init__(
64
+ self,
65
+ service: ComputerUseService,
66
+ *,
67
+ stdin: BinaryIO | None = None,
68
+ stdout: BinaryIO | None = None,
69
+ stderr: Any = None,
70
+ protocol_version: str = PROTOCOL_VERSION,
71
+ ) -> None:
72
+ self.service = service
73
+ self.stdin = stdin if stdin is not None else sys.stdin.buffer
74
+ self.stdout = stdout if stdout is not None else sys.stdout.buffer
75
+ self.stderr = stderr if stderr is not None else sys.stderr
76
+ self.protocol_version = protocol_version
77
+ self.negotiated: str | None = None
78
+ self.closed = False
79
+ self.requests_handled = 0
80
+ self.last_activity: str | None = None
81
+
82
+ # -- protocol ----------------------------------------------------------
83
+ def handle(self, message: Any) -> dict[str, Any] | None:
84
+ """Return the response object, or ``None`` for notifications."""
85
+ if not isinstance(message, dict):
86
+ return _error(None, INVALID_REQUEST, "request must be a JSON object")
87
+ method = message.get("method")
88
+ is_notification = "id" not in message or message.get("id") is None
89
+ request_id = message.get("id")
90
+ if not isinstance(method, str) or not method:
91
+ return (
92
+ None if is_notification else _error(request_id, INVALID_REQUEST, "missing 'method'")
93
+ )
94
+
95
+ if method == "notifications/initialized":
96
+ return None
97
+ if method == "notifications/cancelled":
98
+ return None
99
+ if method == "notifications/exit":
100
+ self.closed = True
101
+ return None
102
+ if is_notification:
103
+ # Unknown notifications are ignored per JSON-RPC; logging to stderr
104
+ # keeps stdout protocol-only.
105
+ print(f"nini-computer-use: ignoring notification {method}", file=self.stderr)
106
+ return None
107
+
108
+ try:
109
+ if method == "initialize":
110
+ return _result(request_id, self._initialize(message.get("params")))
111
+ if method == "ping":
112
+ return _result(request_id, {})
113
+ if method == "tools/list":
114
+ return _result(request_id, {"tools": self.service.list_tools()})
115
+ if method == "tools/call":
116
+ return self._tools_call(request_id, message.get("params"))
117
+ if method in {"resources/list", "resources/templates/list", "prompts/list"}:
118
+ return _error(request_id, METHOD_NOT_FOUND, f"{method} is not supported")
119
+ except BadArguments as exc:
120
+ return _error(request_id, INVALID_PARAMS, exc.message, exc.payload())
121
+ except CuError as exc: # pragma: no cover - defensively mapped
122
+ return _result(request_id, error_result(exc))
123
+ except Exception as exc: # noqa: BLE001 - keep serving other requests
124
+ print(f"nini-computer-use: internal error: {exc!r}", file=self.stderr)
125
+ return _error(request_id, INTERNAL_ERROR, f"internal error: {type(exc).__name__}")
126
+ return _error(request_id, METHOD_NOT_FOUND, f"method not found: {method}")
127
+
128
+ def _initialize(self, params: Any) -> dict[str, Any]:
129
+ requested = params.get("protocolVersion") if isinstance(params, dict) else None
130
+ version = (
131
+ requested
132
+ if isinstance(requested, str) and requested in SUPPORTED_PROTOCOLS
133
+ else self.protocol_version
134
+ )
135
+ self.negotiated = version
136
+ client = params.get("clientInfo") if isinstance(params, dict) else None
137
+ client_name = client.get("name") if isinstance(client, dict) else None
138
+ print(
139
+ f"nini-computer-use: initialize from {client_name or 'unknown client'} "
140
+ f"(protocol {version})",
141
+ file=self.stderr,
142
+ )
143
+ return {
144
+ "protocolVersion": version,
145
+ "capabilities": {"tools": {"listChanged": False}, "logging": {}},
146
+ "serverInfo": {"name": SERVER_NAME, "version": SERVER_VERSION},
147
+ "instructions": INSTRUCTIONS,
148
+ }
149
+
150
+ def _tools_call(self, request_id: Any, params: Any) -> dict[str, Any]:
151
+ if not isinstance(params, dict):
152
+ return _error(request_id, INVALID_PARAMS, "tools/call params must be an object")
153
+ name = params.get("name")
154
+ if not isinstance(name, str) or not name:
155
+ return _error(request_id, INVALID_PARAMS, "tools/call needs a string 'name'")
156
+ arguments = params.get("arguments")
157
+ if arguments is None:
158
+ arguments = {}
159
+ if not isinstance(arguments, dict):
160
+ return _error(request_id, INVALID_PARAMS, "'arguments' must be an object")
161
+ if name not in TOOL_NAMES:
162
+ unknown = BadArguments(f"unknown tool '{name}'", data={"tools": list(TOOL_NAMES)})
163
+ return _error(request_id, INVALID_PARAMS, unknown.message, unknown.payload())
164
+ try:
165
+ return _result(request_id, self.service.call_tool(name, arguments))
166
+ except BadArguments as exc:
167
+ return _error(request_id, INVALID_PARAMS, exc.message, exc.payload())
168
+
169
+ # -- loop --------------------------------------------------------------
170
+ def serve_forever(self) -> int:
171
+ while not self.closed:
172
+ raw = self.stdin.readline()
173
+ if not raw:
174
+ break # EOF: the host closed our stdin
175
+ text = raw.decode("utf-8", "replace").strip()
176
+ if not text:
177
+ continue
178
+ self.last_activity = text[:200]
179
+ self.requests_handled += 1
180
+ try:
181
+ message = json.loads(text)
182
+ except json.JSONDecodeError as exc:
183
+ self._write(_error(None, PARSE_ERROR, f"invalid JSON: {exc.msg}"))
184
+ continue
185
+ try:
186
+ response = self.handle(message)
187
+ except CuError as exc: # pragma: no cover - handle() already maps these
188
+ response = _result(
189
+ message.get("id") if isinstance(message, dict) else None, error_result(exc)
190
+ )
191
+ if response is not None:
192
+ self._write(response)
193
+ return 0
194
+
195
+ def _write(self, payload: dict[str, Any]) -> None:
196
+ line = json.dumps(payload, ensure_ascii=False, separators=(",", ":")) + "\n"
197
+ try:
198
+ self.stdout.write(line.encode("utf-8"))
199
+ self.stdout.flush()
200
+ except (BrokenPipeError, ValueError): # pragma: no cover - host went away
201
+ self.closed = True
202
+
203
+
204
+ __all__ = [
205
+ "INTERNAL_ERROR",
206
+ "INVALID_PARAMS",
207
+ "INVALID_REQUEST",
208
+ "METHOD_NOT_FOUND",
209
+ "PARSE_ERROR",
210
+ "PROTOCOL_VERSION",
211
+ "SUPPORTED_PROTOCOLS",
212
+ "McpServer",
213
+ ]