letitloop 0.2.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.
Files changed (175) hide show
  1. letitloop-0.2.0.dist-info/METADATA +232 -0
  2. letitloop-0.2.0.dist-info/RECORD +175 -0
  3. letitloop-0.2.0.dist-info/WHEEL +5 -0
  4. letitloop-0.2.0.dist-info/entry_points.txt +4 -0
  5. letitloop-0.2.0.dist-info/licenses/LICENSE +21 -0
  6. letitloop-0.2.0.dist-info/top_level.txt +1 -0
  7. orchestrator/SKILL.md +292 -0
  8. orchestrator/__init__.py +151 -0
  9. orchestrator/anti_ouroboros.py +78 -0
  10. orchestrator/approval.py +139 -0
  11. orchestrator/ast_node_splicer.py +130 -0
  12. orchestrator/ast_splicer.py +94 -0
  13. orchestrator/audit.py +88 -0
  14. orchestrator/budget.py +195 -0
  15. orchestrator/checkpoint.py +248 -0
  16. orchestrator/cli.py +1971 -0
  17. orchestrator/codebase_introspector.py +66 -0
  18. orchestrator/component_slicer.py +185 -0
  19. orchestrator/config.py +152 -0
  20. orchestrator/contract.py +404 -0
  21. orchestrator/dag_validator.py +172 -0
  22. orchestrator/elasticity_governor.py +80 -0
  23. orchestrator/env_doctor.py +166 -0
  24. orchestrator/errors.py +211 -0
  25. orchestrator/events.py +120 -0
  26. orchestrator/evidence.py +203 -0
  27. orchestrator/exceptions.py +37 -0
  28. orchestrator/experimental/arena_arbiter.py +260 -0
  29. orchestrator/experimental/fuzz_engine.py +206 -0
  30. orchestrator/experimental/mutation_tester.py +382 -0
  31. orchestrator/failure.py +226 -0
  32. orchestrator/fast_sandbox.py +126 -0
  33. orchestrator/feasibility_gate.py +115 -0
  34. orchestrator/feedback.py +302 -0
  35. orchestrator/fixtures/__init__.py +0 -0
  36. orchestrator/fixtures/example_contract.json +50 -0
  37. orchestrator/fixtures/generated/evidence-cli-run-test-step-1.json +47 -0
  38. orchestrator/fixtures/generated/evidence-cli-run-test-step-2.json +47 -0
  39. orchestrator/fixtures/generated/evidence-inject-test-a.json +47 -0
  40. orchestrator/fixtures/generated/evidence-inject-test-b.json +47 -0
  41. orchestrator/fixtures/generated/evidence-inject-test-c.json +47 -0
  42. orchestrator/fixtures/generated/evidence-json-test-a.json +47 -0
  43. orchestrator/fixtures/generated/evidence-json-test-b.json +47 -0
  44. orchestrator/fixtures/generated/fail-report-fail-task-1.json +47 -0
  45. orchestrator/fixtures/generated/fail-report-json-task-1.json +47 -0
  46. orchestrator/fixtures/generated/fail-report-success-task-1.json +47 -0
  47. orchestrator/fixtures/generated/fuzz-engine-design.json +63 -0
  48. orchestrator/fixtures/generated/fuzz-engine-impl.json +62 -0
  49. orchestrator/fixtures/generated/fuzz-engine-tests.json +62 -0
  50. orchestrator/fixtures/generated/fuzz-engine-verify.json +62 -0
  51. orchestrator/fixtures/generated/goal-orch-step-1.json +63 -0
  52. orchestrator/fixtures/generated/goal-orch-step-2.json +62 -0
  53. orchestrator/fixtures/generated/goal-orch-step-3.json +62 -0
  54. orchestrator/fixtures/generated/goal-orch-step-4.json +62 -0
  55. orchestrator/fixtures/generated/goal-orch-step-5.json +62 -0
  56. orchestrator/fixtures/generated/goal-orch-step-6.json +63 -0
  57. orchestrator/fixtures/generated/implement-a-thread-safe-token-bucket-rat-task-1.json +53 -0
  58. orchestrator/fixtures/generated/orchestrator-checkpoint-rollback-3.json +63 -0
  59. orchestrator/fixtures/generated/orchestrator-checkpoint-rollback.json +62 -0
  60. orchestrator/fixtures/generated/orchestrator-live-telemetry-2.json +62 -0
  61. orchestrator/fixtures/generated/orchestrator-live-telemetry.json +62 -0
  62. orchestrator/fixtures/generated/orchestrator-spec-synthesis-1.json +62 -0
  63. orchestrator/fixtures/generated/orchestrator-spec-synthesis.json +62 -0
  64. orchestrator/fixtures/generated/orchestrator-test-verification-4.json +62 -0
  65. orchestrator/fixtures/generated/orchestrator-test-verification.json +62 -0
  66. orchestrator/fixtures/generated/perf-step-1.json +61 -0
  67. orchestrator/fixtures/generated/perf-step-2.json +62 -0
  68. orchestrator/fixtures/generated/perf-step-3.json +62 -0
  69. orchestrator/fixtures/generated/perf-step-4.json +62 -0
  70. orchestrator/fixtures/generated/perf-step-5.json +63 -0
  71. orchestrator/fixtures/generated/phase2-proof-two-step-step-1.json +47 -0
  72. orchestrator/fixtures/generated/phase2-proof-two-step-step-2.json +47 -0
  73. orchestrator/fixtures/generated/planner-spec-synthesis-impl.json +59 -0
  74. orchestrator/fixtures/generated/self-evolution-ast-formatter.json +69 -0
  75. orchestrator/fixtures/generated/self-evolution-checkpoint-rollback.json +70 -0
  76. orchestrator/fixtures/generated/self-evolution-spec-synthesis.json +70 -0
  77. orchestrator/fixtures/generated/self-evolution-step-1.json +70 -0
  78. orchestrator/fixtures/generated/self-evolution-step-2.json +70 -0
  79. orchestrator/fixtures/generated/self-evolution-step-3.json +70 -0
  80. orchestrator/fixtures/generated/self-evolution-step-4.json +70 -0
  81. orchestrator/fixtures/generated/self-evolution-step-5.json +65 -0
  82. orchestrator/fixtures/generated/self-evolution-telemetry.json +70 -0
  83. orchestrator/fixtures/generated/self-evolution-tests.json +71 -0
  84. orchestrator/fixtures/generated/spec-telemetry-research-design.json +64 -0
  85. orchestrator/fixtures/generated/spec-telemetry-step-1.json +62 -0
  86. orchestrator/fixtures/generated/spec-telemetry-step-2.json +62 -0
  87. orchestrator/fixtures/generated/spec-telemetry-step-3.json +62 -0
  88. orchestrator/fixtures/generated/spec-telemetry-step-4.json +62 -0
  89. orchestrator/fixtures/generated/spec-telemetry-step-5.json +62 -0
  90. orchestrator/fixtures/generated/spec-telemetry-verification.json +58 -0
  91. orchestrator/fixtures/generated/token-bucket-impl.json +69 -0
  92. orchestrator/fixtures/generated/token-bucket-step-1.json +70 -0
  93. orchestrator/fixtures/generated/token-bucket-step-2.json +70 -0
  94. orchestrator/fixtures/generated/token-bucket-step-3.json +60 -0
  95. orchestrator/fixtures/generated/token-bucket-tests.json +70 -0
  96. orchestrator/fixtures/generated/token-bucket-verify.json +61 -0
  97. orchestrator/fixtures/generated/trace-ux-tests-step-1.json +64 -0
  98. orchestrator/fixtures/generated/trace-ux-tests-step-2.json +64 -0
  99. orchestrator/fixtures/generated/trace-ux-tests-step-3.json +62 -0
  100. orchestrator/fixtures/generated/tui-live-telemetry-impl.json +59 -0
  101. orchestrator/fixtures/phase1_proof_escalation_contract.json +41 -0
  102. orchestrator/fixtures/phase1_proof_happy_path_contract.json +83 -0
  103. orchestrator/fixtures/phase1_proof_qc_contract.json +41 -0
  104. orchestrator/fixtures/phase1_proof_repair_contract.json +41 -0
  105. orchestrator/fixtures/phase2_proof_two_step_goal.json +15 -0
  106. orchestrator/fixtures/run_proofs.py +299 -0
  107. orchestrator/fixtures/test_normalizer.py +16 -0
  108. orchestrator/generator.py +239 -0
  109. orchestrator/goal.py +245 -0
  110. orchestrator/handoff.py +86 -0
  111. orchestrator/hybrid_worker.py +840 -0
  112. orchestrator/impossibility.py +162 -0
  113. orchestrator/limits.py +60 -0
  114. orchestrator/live_evolution_engine.py +247 -0
  115. orchestrator/llm.py +291 -0
  116. orchestrator/local_tool_calling.py +285 -0
  117. orchestrator/lock.py +404 -0
  118. orchestrator/mcp_client.py +571 -0
  119. orchestrator/mcp_server.py +344 -0
  120. orchestrator/memory_bridge.py +182 -0
  121. orchestrator/metrics.py +159 -0
  122. orchestrator/micro_epoch.py +42 -0
  123. orchestrator/models.py +350 -0
  124. orchestrator/parsing.py +237 -0
  125. orchestrator/patch_applier.py +154 -0
  126. orchestrator/plan_preview.py +138 -0
  127. orchestrator/plan_quality.py +357 -0
  128. orchestrator/planner.py +532 -0
  129. orchestrator/preferences.py +115 -0
  130. orchestrator/preflight.py +141 -0
  131. orchestrator/process_guard.py +357 -0
  132. orchestrator/prometheus_exporter.py +207 -0
  133. orchestrator/prompts.py +275 -0
  134. orchestrator/proposal_ledger.py +194 -0
  135. orchestrator/provenance.py +263 -0
  136. orchestrator/provider_scheduler.py +394 -0
  137. orchestrator/qc/__init__.py +153 -0
  138. orchestrator/qc/aggregator.py +330 -0
  139. orchestrator/qc/parsing.py +287 -0
  140. orchestrator/qc/personas.py +242 -0
  141. orchestrator/qc/runner.py +569 -0
  142. orchestrator/qc_overrule.py +87 -0
  143. orchestrator/qc_review.py +282 -0
  144. orchestrator/quality_lenses.py +314 -0
  145. orchestrator/quality_plan.py +449 -0
  146. orchestrator/quality_plane.py +103 -0
  147. orchestrator/reconcile.py +191 -0
  148. orchestrator/replanner.py +433 -0
  149. orchestrator/research.py +176 -0
  150. orchestrator/review_artifact.py +672 -0
  151. orchestrator/safety.py +271 -0
  152. orchestrator/schemas.py +230 -0
  153. orchestrator/scope.py +466 -0
  154. orchestrator/sensory_radar.py +79 -0
  155. orchestrator/skill_installer.py +140 -0
  156. orchestrator/sse_server.py +160 -0
  157. orchestrator/state.py +871 -0
  158. orchestrator/subprocess_helper.py +131 -0
  159. orchestrator/supervisor/__init__.py +184 -0
  160. orchestrator/supervisor/_shared.py +164 -0
  161. orchestrator/supervisor/cleanup.py +185 -0
  162. orchestrator/supervisor/core.py +1680 -0
  163. orchestrator/supervisor/recovery.py +367 -0
  164. orchestrator/supervisor/reporting.py +251 -0
  165. orchestrator/surgical_extractor.py +119 -0
  166. orchestrator/telemetry.py +61 -0
  167. orchestrator/templates.py +268 -0
  168. orchestrator/token_gate.py +245 -0
  169. orchestrator/tui.py +649 -0
  170. orchestrator/verifier.py +1103 -0
  171. orchestrator/webhooks.py +168 -0
  172. orchestrator/worker.py +469 -0
  173. orchestrator/worker_adapters.py +815 -0
  174. orchestrator/worker_pool.py +121 -0
  175. orchestrator/worktree.py +364 -0
@@ -0,0 +1,571 @@
1
+ """Bidirectional Model Context Protocol (MCP) Client Adapter for letitloop.
2
+
3
+ Enables letitloop workers to dynamically discover and execute tools exposed
4
+ by local or remote MCP servers (e.g. database query tools, browser automation,
5
+ filesystem extensions) over the ``stdio`` and ``sse`` (HTTP+SSE) transports,
6
+ and exposes :class:`McpClientManager` to manage a fleet of configured servers.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import logging
13
+ import os
14
+ import subprocess
15
+ import threading
16
+ import time
17
+ import urllib.error
18
+ import urllib.request
19
+ from abc import ABC, abstractmethod
20
+ from typing import Any, Dict, List, Optional
21
+ from urllib.parse import urljoin
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+ MCP_PROTOCOL_VERSION = "2024-11-05"
26
+
27
+
28
+ class McpClientError(Exception):
29
+ """Base error for MCP Client operations."""
30
+
31
+
32
+ class BaseMcpClient(ABC):
33
+ """Common client surface shared by every MCP transport.
34
+
35
+ Concrete transports only implement the low-level JSON-RPC plumbing
36
+ (``_send_request`` / ``_send_notification``); the protocol-level surface
37
+ (``initialize``, ``list_tools``, ``call_tool``, ``close``) lives here.
38
+ """
39
+
40
+ PROTOCOL_VERSION = MCP_PROTOCOL_VERSION
41
+
42
+ def __init__(self):
43
+ # RLock so transports that serialize whole requests under the lock
44
+ # (e.g. SseMcpClient._send_request) can still call _next_id().
45
+ self._msg_id = 0
46
+ self._lock = threading.RLock()
47
+ self._is_initialized = False
48
+
49
+ @abstractmethod
50
+ def _send_request(self, method: str, params: Dict[str, Any]) -> Dict[str, Any]:
51
+ """Send a synchronous JSON-RPC request and wait for the response."""
52
+
53
+ @abstractmethod
54
+ def _send_notification(self, method: str, params: Dict[str, Any]) -> None:
55
+ """Send a one-way JSON-RPC notification (no response expected)."""
56
+
57
+ @abstractmethod
58
+ def close(self) -> None:
59
+ """Release the transport resources."""
60
+
61
+ def _next_id(self) -> int:
62
+ with self._lock:
63
+ self._msg_id += 1
64
+ return self._msg_id
65
+
66
+ def initialize(self) -> Dict[str, Any]:
67
+ """Perform the MCP initialize handshake and mark the client ready."""
68
+ init_res = self._send_request(
69
+ "initialize",
70
+ {
71
+ "protocolVersion": self.PROTOCOL_VERSION,
72
+ "capabilities": {"tools": {}},
73
+ "clientInfo": {"name": "letitloop-mcp-client", "version": "0.1.1"},
74
+ },
75
+ )
76
+ if "error" in init_res:
77
+ raise McpClientError(f"MCP initialization error: {init_res['error']}")
78
+
79
+ # Send initialized notification
80
+ self._send_notification("notifications/initialized", {})
81
+ self._is_initialized = True
82
+ return init_res.get("result", {})
83
+
84
+ def list_tools(self) -> List[Dict[str, Any]]:
85
+ """List all available tools provided by the MCP server."""
86
+ resp = self._send_request("tools/list", {})
87
+ if "error" in resp:
88
+ raise McpClientError(f"Failed to list tools: {resp['error']}")
89
+ return resp.get("result", {}).get("tools", [])
90
+
91
+ def call_tool(self, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
92
+ """Call a specific tool on the MCP server and return its content payload."""
93
+ resp = self._send_request("tools/call", {"name": name, "arguments": arguments})
94
+ if "error" in resp:
95
+ raise McpClientError(f"Tool '{name}' returned error: {resp['error']}")
96
+ return resp.get("result", {})
97
+
98
+
99
+ class StdioMcpClient(BaseMcpClient):
100
+ """JSON-RPC 2.0 client for interacting with stdio MCP servers."""
101
+
102
+ def __init__(
103
+ self,
104
+ command: List[str],
105
+ env: Optional[Dict[str, str]] = None,
106
+ cwd: Optional[str] = None,
107
+ timeout: float = 30.0,
108
+ ):
109
+ super().__init__()
110
+ self.command = command
111
+ self.env = env or os.environ.copy()
112
+ self.cwd = cwd
113
+ self.timeout = timeout
114
+ self.process: Optional[subprocess.Popen] = None
115
+
116
+ def start(self) -> None:
117
+ """Start the stdio subprocess and perform the initialize handshake."""
118
+ try:
119
+ self.process = subprocess.Popen(
120
+ self.command,
121
+ stdin=subprocess.PIPE,
122
+ stdout=subprocess.PIPE,
123
+ stderr=subprocess.PIPE,
124
+ env=self.env,
125
+ cwd=self.cwd,
126
+ text=True,
127
+ bufsize=1,
128
+ )
129
+ except OSError as e:
130
+ raise McpClientError(f"Failed to start MCP server subprocess: {e}") from e
131
+
132
+ # Handshake: initialize + notifications/initialized
133
+ self.initialize()
134
+
135
+ def _send_request(self, method: str, params: Dict[str, Any]) -> Dict[str, Any]:
136
+ """Send a synchronous JSON-RPC request and wait for the response."""
137
+ if not self.process or not self.process.stdin or not self.process.stdout:
138
+ raise McpClientError("MCP process is not running.")
139
+
140
+ req_id = self._next_id()
141
+ msg = {
142
+ "jsonrpc": "2.0",
143
+ "id": req_id,
144
+ "method": method,
145
+ "params": params,
146
+ }
147
+ line = json.dumps(msg) + "\n"
148
+
149
+ try:
150
+ self.process.stdin.write(line)
151
+ self.process.stdin.flush()
152
+ except OSError as e:
153
+ raise McpClientError(f"Error writing to MCP server stdin: {e}") from e
154
+
155
+ # Read line from stdout
156
+ try:
157
+ resp_line = self.process.stdout.readline()
158
+ if not resp_line:
159
+ raise McpClientError("MCP server process closed connection (empty line read).")
160
+ return json.loads(resp_line)
161
+ except (json.JSONDecodeError, OSError) as e:
162
+ raise McpClientError(f"Failed to read/parse response from MCP server: {e}") from e
163
+
164
+ def _send_notification(self, method: str, params: Dict[str, Any]) -> None:
165
+ """Send a one-way JSON-RPC notification (no response expected)."""
166
+ if not self.process or not self.process.stdin:
167
+ return
168
+ msg = {
169
+ "jsonrpc": "2.0",
170
+ "method": method,
171
+ "params": params,
172
+ }
173
+ try:
174
+ self.process.stdin.write(json.dumps(msg) + "\n")
175
+ self.process.stdin.flush()
176
+ except OSError:
177
+ pass
178
+
179
+ def close(self) -> None:
180
+ """Terminate the MCP server process gracefully."""
181
+ if self.process:
182
+ try:
183
+ if self.process.stdin:
184
+ self.process.stdin.close()
185
+ self.process.terminate()
186
+ self.process.wait(timeout=2.0)
187
+ except (OSError, subprocess.TimeoutExpired):
188
+ self.process.kill()
189
+ self.process = None
190
+ self._is_initialized = False
191
+
192
+ def __enter__(self) -> StdioMcpClient:
193
+ self.start()
194
+ return self
195
+
196
+ def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
197
+ self.close()
198
+
199
+
200
+ class SseMcpClient(BaseMcpClient):
201
+ """JSON-RPC 2.0 client for MCP servers exposed over HTTP+SSE.
202
+
203
+ Implements the MCP HTTP+SSE transport: the client opens a long-lived
204
+ ``GET text/event-stream`` connection, discovers the POST message endpoint
205
+ from an ``event: endpoint`` frame, posts JSON-RPC messages there, and
206
+ reads responses back off the SSE stream.
207
+ """
208
+
209
+ def __init__(
210
+ self,
211
+ url: str,
212
+ headers: Optional[Dict[str, str]] = None,
213
+ timeout: float = 30.0,
214
+ ):
215
+ super().__init__()
216
+ self.url = url
217
+ self.headers = dict(headers or {})
218
+ self.timeout = timeout
219
+ self.endpoint: Optional[str] = None
220
+ self._stream: Any = None
221
+
222
+ def start(self) -> None:
223
+ """Open the SSE stream, discover the message endpoint, and handshake."""
224
+ if self._stream is not None:
225
+ return
226
+ self._open_stream()
227
+ deadline = time.monotonic() + self.timeout
228
+ while True:
229
+ if time.monotonic() > deadline:
230
+ self.close()
231
+ raise McpClientError(f"Timed out waiting for endpoint event from MCP server at {self.url}")
232
+ frame = self._read_sse_frame()
233
+ if frame is None:
234
+ self.close()
235
+ raise McpClientError(f"SSE stream closed before endpoint event from MCP server at {self.url}")
236
+ event_name, data_lines = frame
237
+ if event_name == "endpoint":
238
+ uri = "\n".join(data_lines).strip()
239
+ if uri:
240
+ self.endpoint = urljoin(self.url, uri)
241
+ break
242
+ self.initialize()
243
+
244
+ def _open_stream(self) -> None:
245
+ req = urllib.request.Request(
246
+ self.url,
247
+ headers={"Accept": "text/event-stream", **self.headers},
248
+ method="GET",
249
+ )
250
+ try:
251
+ self._stream = urllib.request.urlopen(req, timeout=self.timeout) # nosec B310
252
+ except (urllib.error.URLError, OSError) as e:
253
+ raise McpClientError(f"Failed to open SSE stream to MCP server at {self.url}: {e}") from e
254
+
255
+ def _read_sse_frame(self) -> Optional[tuple]:
256
+ """Read one line-based SSE frame.
257
+
258
+ Returns ``(event_name, data_lines)`` or ``None`` on EOF/closed stream.
259
+ Handles LF/CRLF line endings, ``field: value`` syntax with optional
260
+ space, and ``:`` comment lines per the SSE specification.
261
+ """
262
+ stream = self._stream
263
+ if stream is None:
264
+ return None
265
+ event_name: Optional[str] = None
266
+ data_lines: List[str] = []
267
+ while True:
268
+ raw = stream.readline()
269
+ if not raw:
270
+ return None
271
+ if isinstance(raw, bytes):
272
+ line = raw.decode("utf-8", errors="replace").rstrip("\r\n")
273
+ else:
274
+ line = str(raw).rstrip("\r\n")
275
+ if line == "":
276
+ if event_name is None and not data_lines:
277
+ continue
278
+ return (event_name, data_lines)
279
+ if line.startswith(":"):
280
+ continue
281
+ field, _, value = line.partition(":")
282
+ if value.startswith(" "):
283
+ value = value[1:]
284
+ if field == "event":
285
+ event_name = value
286
+ elif field == "data":
287
+ data_lines.append(value)
288
+
289
+ def _post_message(self, payload: Dict[str, Any]) -> Optional[Dict[str, Any]]:
290
+ """POST a JSON-RPC message to the discovered endpoint.
291
+
292
+ Returns an inline JSON response body only when the server replies
293
+ synchronously with application/json carrying an id; otherwise None
294
+ (the response will arrive on the SSE stream).
295
+ """
296
+ if self.endpoint is None:
297
+ raise McpClientError("MCP SSE client has no message endpoint; call start() first.")
298
+ body = json.dumps(payload).encode("utf-8")
299
+ req = urllib.request.Request(
300
+ self.endpoint,
301
+ data=body,
302
+ headers={
303
+ "Content-Type": "application/json",
304
+ "Accept": "application/json",
305
+ **self.headers,
306
+ },
307
+ method="POST",
308
+ )
309
+ try:
310
+ resp = urllib.request.urlopen(req, timeout=self.timeout) # nosec B310
311
+ except (urllib.error.URLError, OSError) as e:
312
+ raise McpClientError(f"Failed to POST message to MCP endpoint {self.endpoint}: {e}") from e
313
+ try:
314
+ status = getattr(resp, "status", None) or resp.getcode()
315
+ if status >= 400:
316
+ raise McpClientError(f"MCP endpoint {self.endpoint} returned HTTP {status}")
317
+ content_type = (resp.headers.get("Content-Type") or "").lower()
318
+ if "application/json" in content_type:
319
+ raw = resp.read()
320
+ if raw.strip():
321
+ try:
322
+ parsed = json.loads(raw.decode("utf-8"))
323
+ except json.JSONDecodeError:
324
+ logger.debug("Ignoring non-JSON body from MCP endpoint %s", self.endpoint)
325
+ return None
326
+ if isinstance(parsed, dict) and "id" in parsed:
327
+ return parsed
328
+ return None
329
+ finally:
330
+ resp.close()
331
+
332
+ def _wait_for_response(self, req_id: int, deadline: float) -> Dict[str, Any]:
333
+ """Consume SSE frames until the JSON-RPC response with ``req_id`` arrives."""
334
+ while True:
335
+ if time.monotonic() > deadline:
336
+ raise McpClientError(f"Timed out waiting for MCP response to request id {req_id}.")
337
+ frame = self._read_sse_frame()
338
+ if frame is None:
339
+ raise McpClientError("MCP SSE stream closed before a response was received.")
340
+ _, data_lines = frame
341
+ payload = "\n".join(data_lines).strip()
342
+ if not payload:
343
+ continue
344
+ try:
345
+ msg = json.loads(payload)
346
+ except json.JSONDecodeError:
347
+ logger.debug("Ignoring malformed SSE data frame: %.200s", payload)
348
+ continue
349
+ if isinstance(msg, dict) and msg.get("id") == req_id:
350
+ return msg
351
+
352
+ def _send_request(self, method: str, params: Dict[str, Any]) -> Dict[str, Any]:
353
+ with self._lock:
354
+ if self.endpoint is None or self._stream is None:
355
+ raise McpClientError("MCP SSE client is not connected; call start() first.")
356
+ req_id = self._next_id()
357
+ msg = {
358
+ "jsonrpc": "2.0",
359
+ "id": req_id,
360
+ "method": method,
361
+ "params": params,
362
+ }
363
+ self._post_message(msg)
364
+ return self._wait_for_response(req_id, time.monotonic() + self.timeout)
365
+
366
+ def _send_notification(self, method: str, params: Dict[str, Any]) -> None:
367
+ if self.endpoint is None:
368
+ return
369
+ msg = {
370
+ "jsonrpc": "2.0",
371
+ "method": method,
372
+ "params": params,
373
+ }
374
+ try:
375
+ self._post_message(msg)
376
+ except McpClientError:
377
+ pass
378
+
379
+ def close(self) -> None:
380
+ """Close the SSE connection (idempotent)."""
381
+ stream = self._stream
382
+ self._stream = None
383
+ self.endpoint = None
384
+ self._is_initialized = False
385
+ if stream is not None:
386
+ try:
387
+ stream.close()
388
+ except OSError:
389
+ pass
390
+
391
+ def __enter__(self) -> SseMcpClient:
392
+ self.start()
393
+ return self
394
+
395
+ def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
396
+ self.close()
397
+
398
+
399
+ class McpClientManager:
400
+ """Lazy multi-server MCP client registry.
401
+
402
+ Loads configuration shaped like::
403
+
404
+ {"servers": {
405
+ "local-fs": {"transport": "stdio", "command": ["python", "-m", "fs_server"], "env": {}},
406
+ "remote-tools": {"transport": "sse", "url": "https://host/sse", "headers": {}}
407
+ }}
408
+
409
+ Clients are spawned lazily on first use and cached until
410
+ :meth:`disconnect` / :meth:`shutdown_all`.
411
+ """
412
+
413
+ DEFAULT_CONFIG_REL_PATH = os.path.join(".letitloop", "mcp.json")
414
+
415
+ def __init__(self, servers_config: Optional[Dict[str, Dict[str, Any]]] = None):
416
+ self._configs: Dict[str, Dict[str, Any]] = dict(servers_config or {})
417
+ self._clients: Dict[str, BaseMcpClient] = {}
418
+ self._connected: set = set()
419
+ self._lock = threading.Lock()
420
+
421
+ @classmethod
422
+ def from_config(cls, path: Any = None, workspace: Optional[str] = None) -> McpClientManager:
423
+ """Build a manager from ``<workspace>/.letitloop/mcp.json``.
424
+
425
+ ``path`` may be an explicit config file path, an already-parsed config
426
+ dict, or omitted to resolve against ``workspace`` (defaulting to the
427
+ current working directory).
428
+ """
429
+ source = path if isinstance(path, str) else "<config>"
430
+ if isinstance(path, dict):
431
+ data = path
432
+ else:
433
+ if path is None:
434
+ root = workspace if workspace is not None else os.getcwd()
435
+ path = os.path.join(root, cls.DEFAULT_CONFIG_REL_PATH)
436
+ source = path
437
+ try:
438
+ with open(path, "r", encoding="utf-8") as f:
439
+ data = json.load(f)
440
+ except (json.JSONDecodeError, OSError) as e:
441
+ raise McpClientError(f"Failed to load MCP config from {source}: {e}") from e
442
+
443
+ if not isinstance(data, dict):
444
+ raise McpClientError(f"MCP config {source} must be a JSON object.")
445
+ servers = data.get("servers", data)
446
+ if not isinstance(servers, dict):
447
+ raise McpClientError(f"MCP config {source}: 'servers' must map names to settings objects.")
448
+ return cls(servers_config=servers)
449
+
450
+ @property
451
+ def connected(self) -> set:
452
+ """Names of currently connected servers (copy)."""
453
+ return set(self._connected)
454
+
455
+ def connect(self, name: str) -> BaseMcpClient:
456
+ """Lazily spawn, cache, and return the client for ``name``."""
457
+ with self._lock:
458
+ existing = self._clients.get(name)
459
+ if existing is not None:
460
+ return existing
461
+ cfg = self._configs.get(name)
462
+ if cfg is None:
463
+ raise McpClientError(f"Unknown MCP server '{name}'. Configured servers: {sorted(self._configs)}")
464
+ client = self._build_client(name, cfg)
465
+ try:
466
+ client.start()
467
+ except Exception as exc:
468
+ try:
469
+ client.close()
470
+ except Exception:
471
+ pass
472
+ raise McpClientError(f"Failed to connect to MCP server '{name}': {exc}") from exc
473
+ self._clients[name] = client
474
+ self._connected.add(name)
475
+ return client
476
+
477
+ def _build_client(self, name: str, cfg: Dict[str, Any]) -> BaseMcpClient:
478
+ if not isinstance(cfg, dict):
479
+ raise McpClientError(f"MCP server '{name}': settings must be an object.")
480
+ transport = cfg.get("transport") or ("sse" if cfg.get("url") else "stdio")
481
+
482
+ if transport == "stdio":
483
+ command = cfg.get("command")
484
+ if not command or not isinstance(command, list):
485
+ raise McpClientError(f"MCP server '{name}': stdio transport requires a 'command' list.")
486
+ extra_env = cfg.get("env") or {}
487
+ if not isinstance(extra_env, dict):
488
+ raise McpClientError(f"MCP server '{name}': 'env' must be an object.")
489
+ env = os.environ.copy()
490
+ env.update({str(k): str(v) for k, v in extra_env.items()})
491
+ return StdioMcpClient(command=[str(part) for part in command], env=env)
492
+
493
+ if transport == "sse":
494
+ url = cfg.get("url")
495
+ if not url or not isinstance(url, str):
496
+ raise McpClientError(f"MCP server '{name}': sse transport requires a 'url'.")
497
+ headers = cfg.get("headers") or {}
498
+ if not isinstance(headers, dict):
499
+ raise McpClientError(f"MCP server '{name}': 'headers' must be an object.")
500
+ return SseMcpClient(url=url, headers={str(k): str(v) for k, v in headers.items()})
501
+
502
+ raise McpClientError(f"MCP server '{name}': unsupported transport {transport!r}.")
503
+
504
+ def ensure_servers(self, required: List[str]) -> None:
505
+ """Connect every required server or raise listing what failed."""
506
+ missing = [name for name in required if name not in self._configs]
507
+ if missing:
508
+ raise McpClientError(f"MCP servers not configured: {missing}. Available: {sorted(self._configs)}")
509
+ failures: List[str] = []
510
+ for name in required:
511
+ try:
512
+ self.connect(name)
513
+ except McpClientError as exc:
514
+ failures.append(str(exc))
515
+ if failures:
516
+ raise McpClientError("Unreachable MCP servers: " + "; ".join(failures))
517
+
518
+ def list_tools(self, server: str) -> List[Dict[str, Any]]:
519
+ """List tools provided by ``server`` (connecting lazily)."""
520
+ return self.connect(server).list_tools()
521
+
522
+ def call_tool(self, server: str, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
523
+ """Call ``<name>`` on ``server`` with ``arguments`` (connecting lazily)."""
524
+ return self.connect(server).call_tool(name, arguments)
525
+
526
+ def as_worker_tool_defs(self, servers: Optional[List[str]] = None) -> List[Dict[str, Any]]:
527
+ """Translate discovered MCP tools into namespaced worker tool defs.
528
+
529
+ Each def is ``{"name": "<server>__<tool>", "description": ..., "inputSchema": ...}``.
530
+ With ``servers=None`` every configured server is discovered.
531
+ """
532
+ if servers is None:
533
+ targets = list(self._configs.keys())
534
+ else:
535
+ unknown = [srv for srv in servers if srv not in self._configs]
536
+ if unknown:
537
+ raise McpClientError(f"Unknown MCP servers requested: {unknown}. Available: {sorted(self._configs)}")
538
+ targets = list(dict.fromkeys(servers))
539
+ defs: List[Dict[str, Any]] = []
540
+ for srv in targets:
541
+ for tool in self.list_tools(srv):
542
+ defs.append(
543
+ {
544
+ "name": f"{srv}__{tool.get('name', '')}",
545
+ "description": tool.get("description", ""),
546
+ "inputSchema": tool.get("inputSchema", {"type": "object"}),
547
+ }
548
+ )
549
+ return defs
550
+
551
+ def disconnect(self, server: str) -> None:
552
+ """Close and forget the client for ``server`` (idempotent)."""
553
+ with self._lock:
554
+ client = self._clients.pop(server, None)
555
+ self._connected.discard(server)
556
+ if client is not None:
557
+ try:
558
+ client.close()
559
+ except Exception as exc:
560
+ logger.warning("Error closing MCP client '%s': %s", server, exc)
561
+
562
+ def shutdown_all(self) -> None:
563
+ """Disconnect every live client (idempotent)."""
564
+ for name in list(self._clients.keys()):
565
+ self.disconnect(name)
566
+
567
+ def __enter__(self) -> McpClientManager:
568
+ return self
569
+
570
+ def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
571
+ self.shutdown_all()