piton-cli 0.4.2__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.
piton/iac/mcp_probe.py ADDED
@@ -0,0 +1,582 @@
1
+ """
2
+ Live MCP Server Introspection (`piton init --probe` / `piton lock --probe`)
3
+ and STDIO MCP Wrapper (`piton wrap -- <stdio-cmd>`).
4
+
5
+ Real-world MCP protocol support (Streamable HTTP 2025-03-26 / 2026-07-28 & STDIO):
6
+ - Full `initialize` -> `Mcp-Session-Id` -> `notifications/initialized` handshake
7
+ - Paginated `tools/list` traversal (`nextCursor`, bounded to prevent DoS loops)
8
+ - Dual `application/json` and `text/event-stream` SSE response parsing
9
+ - Non-blocking timeout enforcement on STDIO subprocess reads
10
+ - Transparent STDIO JSON-RPC wrapper (`wrap_stdio_mcp`) for Cursor / Claude Desktop / Claude Code
11
+ preserving string/int IDs, passing notifications cleanly, enforcing `piton.lock`
12
+ split-hash pinning + Day-1 poisoning lint, and recording signed ledger entries.
13
+ """
14
+
15
+ import json
16
+ import os
17
+ import queue
18
+ import subprocess
19
+ import sys
20
+ import threading
21
+ import time
22
+ import urllib.error
23
+ import urllib.request
24
+ from typing import Any, Dict, List, Optional, Tuple
25
+
26
+ from piton.iac.lockfile import verify_tools_list
27
+ from piton.iac.replay import (
28
+ DecisionVerdict,
29
+ SignedDecisionLedger,
30
+ evaluate_tool_call_against_policy,
31
+ )
32
+ from piton.iac.schema import AgentIaCConfig, EnforcementMode, ManifestLockfile
33
+
34
+ MAX_TOOL_LIST_PAGES = 25
35
+
36
+
37
+ def parse_sse_jsonrpc_messages(raw_body: str) -> List[Dict[str, Any]]:
38
+ """Extracts JSON-RPC payloads from MCP `text/event-stream` SSE responses."""
39
+ messages: List[Dict[str, Any]] = []
40
+ data_buf: List[str] = []
41
+ for line in raw_body.splitlines():
42
+ if line.startswith("data:"):
43
+ data_buf.append(line[5:].lstrip())
44
+ elif line.strip() == "" and data_buf:
45
+ chunk = "\n".join(data_buf).strip()
46
+ data_buf = []
47
+ if chunk and chunk != "[DONE]":
48
+ try:
49
+ parsed = json.loads(chunk)
50
+ if isinstance(parsed, dict):
51
+ messages.append(parsed)
52
+ except Exception:
53
+ pass
54
+ if data_buf:
55
+ chunk = "\n".join(data_buf).strip()
56
+ if chunk and chunk != "[DONE]":
57
+ try:
58
+ parsed = json.loads(chunk)
59
+ if isinstance(parsed, dict):
60
+ messages.append(parsed)
61
+ except Exception:
62
+ pass
63
+ return messages
64
+
65
+
66
+ def extract_tools_page_from_rpc_body(
67
+ raw_body: str, content_type: str = ""
68
+ ) -> Tuple[List[Dict[str, Any]], Optional[str]]:
69
+ """
70
+ Extracts `(tools, nextCursor)` from either standard JSON or `text/event-stream` SSE MCP responses.
71
+ """
72
+ candidates: List[Dict[str, Any]] = []
73
+ stripped = raw_body.lstrip()
74
+ if (
75
+ "text/event-stream" in content_type.lower()
76
+ or stripped.startswith("event:")
77
+ or stripped.startswith("data:")
78
+ ):
79
+ candidates.extend(parse_sse_jsonrpc_messages(raw_body))
80
+ else:
81
+ try:
82
+ parsed = json.loads(raw_body)
83
+ if isinstance(parsed, dict):
84
+ candidates.append(parsed)
85
+ except Exception:
86
+ candidates.extend(parse_sse_jsonrpc_messages(raw_body))
87
+
88
+ for msg in candidates:
89
+ res = msg.get("result")
90
+ if isinstance(res, dict) and isinstance(res.get("tools"), list):
91
+ tools = [t for t in res["tools"] if isinstance(t, dict)]
92
+ next_cursor = res.get("nextCursor")
93
+ if not isinstance(next_cursor, str) or not next_cursor:
94
+ next_cursor = None
95
+ return tools, next_cursor
96
+ return [], None
97
+
98
+
99
+ def extract_tools_from_rpc_body(raw_body: str, content_type: str = "") -> List[Dict[str, Any]]:
100
+ """Extracts `result.tools` from either standard JSON or `text/event-stream` SSE MCP responses."""
101
+ tools, _ = extract_tools_page_from_rpc_body(raw_body, content_type)
102
+ return tools
103
+
104
+
105
+ def _http_post_jsonrpc(
106
+ url: str,
107
+ payload: Dict[str, Any],
108
+ headers: Dict[str, str],
109
+ timeout: float,
110
+ ) -> Tuple[str, str, Dict[str, str]]:
111
+ req = urllib.request.Request(
112
+ url,
113
+ data=json.dumps(payload).encode("utf-8"),
114
+ method="POST",
115
+ headers=headers,
116
+ )
117
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
118
+ raw = resp.read(10 * 1024 * 1024).decode("utf-8", errors="replace")
119
+ ctype = resp.headers.get("Content-Type", "")
120
+ resp_headers = {k.lower(): v for k, v in resp.headers.items()}
121
+ return raw, ctype, resp_headers
122
+
123
+
124
+ def probe_http_mcp_tools(
125
+ url: str,
126
+ headers: Optional[Dict[str, str]] = None,
127
+ timeout: float = 8.0,
128
+ ) -> List[Dict[str, Any]]:
129
+ """
130
+ Queries a live HTTP / Streamable-HTTP MCP server for `tools/list`:
131
+ 1. Performs best-effort `initialize` handshake to acquire `Mcp-Session-Id` (for stateful Streamable HTTP servers).
132
+ 2. Sends `notifications/initialized` when a session was established.
133
+ 3. Traverses all `tools/list` pages via `nextCursor` (up to MAX_TOOL_LIST_PAGES).
134
+ """
135
+ base_headers = {
136
+ "Content-Type": "application/json",
137
+ "Accept": "application/json, text/event-stream",
138
+ "MCP-Protocol-Version": "2025-03-26",
139
+ }
140
+ if headers:
141
+ base_headers.update(headers)
142
+
143
+ session_id: Optional[str] = None
144
+ # Step 1: Best-effort MCP Streamable HTTP initialize handshake
145
+ try:
146
+ init_headers = {**base_headers, "Mcp-Method": "initialize"}
147
+ _, _, init_resp_headers = _http_post_jsonrpc(
148
+ url,
149
+ {
150
+ "jsonrpc": "2.0",
151
+ "id": 1,
152
+ "method": "initialize",
153
+ "params": {
154
+ "protocolVersion": "2025-03-26",
155
+ "capabilities": {},
156
+ "clientInfo": {"name": "piton-probe", "version": "1.0.0"},
157
+ },
158
+ },
159
+ init_headers,
160
+ timeout=timeout,
161
+ )
162
+ session_id = init_resp_headers.get("mcp-session-id")
163
+ except Exception:
164
+ # Stateless JSON-RPC servers that only implement tools/list are still supported.
165
+ session_id = None
166
+
167
+ if session_id:
168
+ base_headers["Mcp-Session-Id"] = session_id
169
+ try:
170
+ _http_post_jsonrpc(
171
+ url,
172
+ {"jsonrpc": "2.0", "method": "notifications/initialized"},
173
+ {**base_headers, "Mcp-Method": "notifications/initialized"},
174
+ timeout=timeout,
175
+ )
176
+ except Exception:
177
+ pass
178
+
179
+ # Step 2: Paginated tools/list traversal
180
+ all_tools: List[Dict[str, Any]] = []
181
+ seen_names = set()
182
+ cursor: Optional[str] = None
183
+ seen_cursors = set()
184
+
185
+ for page_idx in range(MAX_TOOL_LIST_PAGES):
186
+ params: Dict[str, Any] = {}
187
+ if cursor is not None:
188
+ params["cursor"] = cursor
189
+ list_headers = {**base_headers, "Mcp-Method": "tools/list"}
190
+ raw, ctype, _ = _http_post_jsonrpc(
191
+ url,
192
+ {
193
+ "jsonrpc": "2.0",
194
+ "id": 2 + page_idx,
195
+ "method": "tools/list",
196
+ "params": params,
197
+ },
198
+ list_headers,
199
+ timeout=timeout,
200
+ )
201
+ page_tools, next_cursor = extract_tools_page_from_rpc_body(raw, ctype)
202
+ for tool in page_tools:
203
+ tname = str(tool.get("name") or "")
204
+ if tname and tname in seen_names:
205
+ continue
206
+ if tname:
207
+ seen_names.add(tname)
208
+ all_tools.append(tool)
209
+ if not next_cursor or next_cursor in seen_cursors:
210
+ break
211
+ seen_cursors.add(next_cursor)
212
+ cursor = next_cursor
213
+
214
+ return all_tools
215
+
216
+
217
+ def probe_stdio_mcp_tools(
218
+ command: str,
219
+ args: Optional[List[str]] = None,
220
+ env: Optional[Dict[str, str]] = None,
221
+ timeout: float = 8.0,
222
+ ) -> List[Dict[str, Any]]:
223
+ """
224
+ Launches a local STDIO MCP server (no shell=True!), performs MCP `initialize` ->
225
+ `notifications/initialized` -> paginated `tools/list`, enforces non-blocking read
226
+ timeouts, and cleanly terminates the subprocess.
227
+ """
228
+ argv = [command, *(args or [])]
229
+ proc = subprocess.Popen(
230
+ argv,
231
+ stdin=subprocess.PIPE,
232
+ stdout=subprocess.PIPE,
233
+ stderr=subprocess.PIPE,
234
+ env=env or os.environ.copy(),
235
+ text=True,
236
+ )
237
+ assert proc.stdin is not None and proc.stdout is not None
238
+
239
+ line_queue: "queue.Queue[Optional[str]]" = queue.Queue()
240
+
241
+ def _reader() -> None:
242
+ assert proc.stdout is not None
243
+ try:
244
+ for line in proc.stdout:
245
+ line_queue.put(line)
246
+ finally:
247
+ line_queue.put(None)
248
+
249
+ reader = threading.Thread(target=_reader, daemon=True)
250
+ reader.start()
251
+
252
+ def _read_response(expected_id: Any, deadline: float) -> Optional[Dict[str, Any]]:
253
+ while True:
254
+ remaining = deadline - time.time()
255
+ if remaining <= 0:
256
+ return None
257
+ try:
258
+ raw = line_queue.get(timeout=remaining)
259
+ except queue.Empty:
260
+ return None
261
+ if raw is None:
262
+ return None
263
+ raw = raw.strip()
264
+ if not raw:
265
+ continue
266
+ try:
267
+ msg = json.loads(raw)
268
+ except Exception:
269
+ continue
270
+ if isinstance(msg, dict) and msg.get("id") == expected_id:
271
+ return msg
272
+
273
+ try:
274
+ deadline = time.time() + timeout
275
+
276
+ # 1. MCP initialize
277
+ init_msg = json.dumps(
278
+ {
279
+ "jsonrpc": "2.0",
280
+ "id": 1,
281
+ "method": "initialize",
282
+ "params": {
283
+ "protocolVersion": "2025-03-26",
284
+ "capabilities": {},
285
+ "clientInfo": {"name": "piton-probe", "version": "1.0.0"},
286
+ },
287
+ }
288
+ )
289
+ proc.stdin.write(init_msg + "\n")
290
+ proc.stdin.flush()
291
+ _read_response(1, deadline)
292
+
293
+ # 2. MCP notifications/initialized
294
+ proc.stdin.write(json.dumps({"jsonrpc": "2.0", "method": "notifications/initialized"}) + "\n")
295
+ proc.stdin.flush()
296
+
297
+ # 3. Paginated tools/list
298
+ all_tools: List[Dict[str, Any]] = []
299
+ seen_names = set()
300
+ cursor: Optional[str] = None
301
+ seen_cursors = set()
302
+
303
+ for page_idx in range(MAX_TOOL_LIST_PAGES):
304
+ req_id = 2 + page_idx
305
+ params: Dict[str, Any] = {}
306
+ if cursor is not None:
307
+ params["cursor"] = cursor
308
+ proc.stdin.write(
309
+ json.dumps({"jsonrpc": "2.0", "id": req_id, "method": "tools/list", "params": params}) + "\n"
310
+ )
311
+ proc.stdin.flush()
312
+
313
+ resp = _read_response(req_id, deadline)
314
+ if not resp:
315
+ break
316
+ res = resp.get("result")
317
+ if not isinstance(res, dict) or not isinstance(res.get("tools"), list):
318
+ break
319
+ for tool in res["tools"]:
320
+ if not isinstance(tool, dict):
321
+ continue
322
+ tname = str(tool.get("name") or "")
323
+ if tname and tname in seen_names:
324
+ continue
325
+ if tname:
326
+ seen_names.add(tname)
327
+ all_tools.append(tool)
328
+ next_cursor = res.get("nextCursor")
329
+ if not isinstance(next_cursor, str) or not next_cursor or next_cursor in seen_cursors:
330
+ break
331
+ seen_cursors.add(next_cursor)
332
+ cursor = next_cursor
333
+
334
+ return all_tools
335
+ finally:
336
+ if proc.stdin:
337
+ try:
338
+ proc.stdin.close()
339
+ except Exception:
340
+ pass
341
+ proc.terminate()
342
+ try:
343
+ proc.wait(timeout=2)
344
+ except subprocess.TimeoutExpired:
345
+ proc.kill()
346
+
347
+
348
+ def probe_configured_servers(
349
+ config: AgentIaCConfig,
350
+ timeout: float = 8.0,
351
+ ) -> Tuple[Dict[str, List[Dict[str, Any]]], Dict[str, str]]:
352
+ """Probes all HTTP and STDIO MCP servers declared in `piton.yaml`."""
353
+ manifests: Dict[str, List[Dict[str, Any]]] = {}
354
+ errors: Dict[str, str] = {}
355
+ for srv_name, srv in config.mcp_servers.items():
356
+ try:
357
+ if srv.url:
358
+ manifests[srv_name] = probe_http_mcp_tools(srv.url, timeout=timeout)
359
+ elif srv.command:
360
+ manifests[srv_name] = probe_stdio_mcp_tools(srv.command, srv.args, timeout=timeout)
361
+ except Exception as exc:
362
+ errors[srv_name] = str(exc)
363
+ return manifests, errors
364
+
365
+
366
+ def _canonical_rpc_id(rpc_id: Any) -> str:
367
+ """Preserves type distinction between string '1' and integer 1 JSON-RPC IDs."""
368
+ return f"{type(rpc_id).__name__}:{rpc_id}"
369
+
370
+
371
+ def wrap_stdio_mcp(
372
+ server_name: str,
373
+ cmd: List[str],
374
+ config: AgentIaCConfig,
375
+ lockfile: Optional[ManifestLockfile],
376
+ ledger: Optional[SignedDecisionLedger] = None,
377
+ stdin_stream=None,
378
+ stdout_stream=None,
379
+ enforce_override: bool = False,
380
+ ) -> int:
381
+ """
382
+ Transparent STDIO JSON-RPC wrapper for Cursor / Claude Desktop / Claude Code MCP servers.
383
+ - Preserves string/integer JSON-RPC IDs and forwards notifications cleanly.
384
+ - Intercepts client->server `tools/call` and enforces `piton.yaml` parameter bounds
385
+ (writing signed ledger records).
386
+ - Intercepts server->client `tools/list` responses (including paginated pages) and enforces
387
+ `piton.lock` split-hash pinning + Day-1 poisoning lint (blocking third-party rug pulls
388
+ with JSON-RPC -32001).
389
+ - Warns on `notifications/tools/list_changed` dynamic tool-mutation attempts.
390
+ """
391
+ client_in = stdin_stream or sys.stdin
392
+ client_out = stdout_stream or sys.stdout
393
+
394
+ effective_mode = EnforcementMode.ENFORCE if enforce_override else config.agent.mode
395
+ effective_config = config.model_copy(
396
+ deep=True,
397
+ update={"agent": config.agent.model_copy(update={"mode": effective_mode})},
398
+ )
399
+
400
+ if lockfile is None:
401
+ sys.stderr.write(
402
+ f"[piton-wrap] WARNING: no piton.lock loaded for '{server_name}'; "
403
+ "tools/list rug-pull pinning is disabled until you run `piton init` or pass --lockfile.\n"
404
+ )
405
+ sys.stderr.flush()
406
+
407
+ proc = subprocess.Popen(
408
+ cmd,
409
+ stdin=subprocess.PIPE,
410
+ stdout=subprocess.PIPE,
411
+ stderr=sys.stderr,
412
+ text=True,
413
+ )
414
+ assert proc.stdin is not None and proc.stdout is not None
415
+
416
+ out_lock = threading.Lock()
417
+ state_lock = threading.Lock()
418
+ pending_list_ids: set[str] = set()
419
+
420
+ def write_client(obj: Dict[str, Any]) -> None:
421
+ with out_lock:
422
+ client_out.write(json.dumps(obj) + "\n")
423
+ client_out.flush()
424
+
425
+ def pump_upstream() -> None:
426
+ assert proc.stdout is not None
427
+ for raw_line in proc.stdout:
428
+ line = raw_line.strip()
429
+ if not line:
430
+ continue
431
+ try:
432
+ msg = json.loads(line)
433
+ except Exception:
434
+ continue
435
+ if not isinstance(msg, dict):
436
+ continue
437
+
438
+ if msg.get("method") == "notifications/tools/list_changed":
439
+ sys.stderr.write(
440
+ f"[piton-wrap] WARNING: server '{server_name}' emitted notifications/tools/list_changed; "
441
+ "subsequent tools/list responses will be verified against piton.lock.\n"
442
+ )
443
+ sys.stderr.flush()
444
+
445
+ has_id = "id" in msg and msg.get("id") is not None
446
+ id_key = _canonical_rpc_id(msg.get("id")) if has_id else ""
447
+ is_list_resp = False
448
+ if has_id:
449
+ with state_lock:
450
+ if id_key in pending_list_ids:
451
+ pending_list_ids.discard(id_key)
452
+ is_list_resp = True
453
+
454
+ if is_list_resp:
455
+ res = msg.get("result")
456
+ if lockfile is not None and isinstance(res, dict) and isinstance(res.get("tools"), list):
457
+ tools = [t for t in res["tools"] if isinstance(t, dict)]
458
+ ver = verify_tools_list(lockfile, server_name, tools)
459
+ if not ver.passed:
460
+ if effective_mode == EnforcementMode.ENFORCE:
461
+ write_client(
462
+ {
463
+ "jsonrpc": "2.0",
464
+ "id": msg.get("id"),
465
+ "error": {
466
+ "code": -32001,
467
+ "message": "Piton STDIO Lockfile Rug-Pull Blocked",
468
+ "data": ver.model_dump(mode="json"),
469
+ },
470
+ }
471
+ )
472
+ continue
473
+ sys.stderr.write(
474
+ f"[piton-wrap][shadow] WARNING: tools/list drift on '{server_name}' "
475
+ f"({ver.blocked_count} blocking); pass --enforce or set mode: enforce to block.\n"
476
+ )
477
+ sys.stderr.flush()
478
+ write_client(msg)
479
+
480
+ reader_thread = threading.Thread(target=pump_upstream, daemon=True)
481
+ reader_thread.start()
482
+
483
+ tool_call_counts: Dict[str, int] = {}
484
+
485
+ try:
486
+ for raw_line in client_in:
487
+ line = raw_line.strip()
488
+ if not line:
489
+ continue
490
+ try:
491
+ req = json.loads(line)
492
+ except Exception:
493
+ continue
494
+ if not isinstance(req, dict):
495
+ write_client(
496
+ {
497
+ "jsonrpc": "2.0",
498
+ "id": None,
499
+ "error": {"code": -32600, "message": "Batch JSON-RPC not permitted"},
500
+ }
501
+ )
502
+ continue
503
+
504
+ method = req.get("method")
505
+ has_id = "id" in req and req.get("id") is not None
506
+ req_id = req.get("id")
507
+
508
+ # Forward JSON-RPC notifications (e.g. notifications/initialized) untouched
509
+ if not has_id:
510
+ proc.stdin.write(json.dumps(req) + "\n")
511
+ proc.stdin.flush()
512
+ continue
513
+
514
+ if method == "tools/list":
515
+ with state_lock:
516
+ pending_list_ids.add(_canonical_rpc_id(req_id))
517
+
518
+ if method == "tools/call":
519
+ params = req.get("params") or {}
520
+ tool_name = str(params.get("name") or "")
521
+ args = params.get("arguments") or {}
522
+ if not isinstance(args, dict):
523
+ args = {}
524
+ tool_call_counts[tool_name] = tool_call_counts.get(tool_name, 0) + 1
525
+ ev = evaluate_tool_call_against_policy(
526
+ effective_config,
527
+ server_name,
528
+ tool_name,
529
+ args,
530
+ obo_principal=os.getenv("PITON_LOCAL_PRINCIPAL", "user:local-dev"),
531
+ idempotency_key=args.get("idempotency_key") or f"stdio-{req_id}",
532
+ trace_tool_call_count=tool_call_counts[tool_name],
533
+ )
534
+ if ledger is not None:
535
+ ledger.append_decision(
536
+ effective_config,
537
+ lockfile,
538
+ traceparent=f"00-stdio-{req_id}-01",
539
+ server_name=server_name,
540
+ tool_name=tool_name,
541
+ raw_arguments=args,
542
+ evaluation=ev,
543
+ obo_principal=os.getenv("PITON_LOCAL_PRINCIPAL", "user:local-dev"),
544
+ idempotency_key=args.get("idempotency_key") or f"stdio-{req_id}",
545
+ )
546
+ if ev.verdict in (DecisionVerdict.DENY, DecisionVerdict.MRTR_ESCALATE):
547
+ code = -32001 if ev.verdict == DecisionVerdict.DENY else -32002
548
+ write_client(
549
+ {
550
+ "jsonrpc": "2.0",
551
+ "id": req_id,
552
+ "error": {
553
+ "code": code,
554
+ "message": "Piton STDIO Policy Enforcement",
555
+ "data": ev.model_dump(mode="json"),
556
+ },
557
+ }
558
+ )
559
+ continue
560
+ if ev.verdict == DecisionVerdict.SHADOW_DENY:
561
+ rules = ", ".join(v.rule_id for v in ev.violations) or "policy"
562
+ sys.stderr.write(
563
+ f"[piton-wrap][shadow] WARNING: '{server_name}.{tool_name}' violated [{rules}]; "
564
+ "pass --enforce or set mode: enforce to block.\n"
565
+ )
566
+ sys.stderr.flush()
567
+
568
+ proc.stdin.write(json.dumps(req) + "\n")
569
+ proc.stdin.flush()
570
+ finally:
571
+ if proc.stdin:
572
+ try:
573
+ proc.stdin.close()
574
+ except Exception:
575
+ pass
576
+ reader_thread.join(timeout=2)
577
+ proc.terminate()
578
+ try:
579
+ proc.wait(timeout=2)
580
+ except subprocess.TimeoutExpired:
581
+ proc.kill()
582
+ return 0