"""Zero-Trust Physics standard-library MCP stdio client and IEEE-754 / SHA-384 helpers. Consumes the frozen v0.15.3 monument binaries (`mcp_stdio` and `genesis_seal`) strictly read-only with zero network calls and zero external dependencies. """ from __future__ import annotations import hashlib import json import os import platform import select import shlex import struct import subprocess import tempfile from typing import Any CORE_DIR = os.path.dirname(os.path.abspath(__file__)) LAB_ROOT = os.path.dirname(CORE_DIR) SPECTRUM_ROOT = os.path.dirname(LAB_ROOT) def _host_arch_subdir() -> str | None: sys_name = platform.system() mach = platform.machine() if sys_name == "Darwin" and mach == "arm64": return "macos-arm64" if sys_name == "Linux" and mach in ("aarch64", "arm64"): return "linux-arm64" if sys_name == "Linux" and mach in ("x86_64", "amd64"): return "linux-amd64" return None _ARCH_SUBDIR = _host_arch_subdir() DEFAULT_ENGINE_CANDIDATES = tuple( p for p in ( os.path.join(LAB_ROOT, "bin", _ARCH_SUBDIR, "mcp_stdio") if _ARCH_SUBDIR else None, os.path.join(LAB_ROOT, "bin", "mcp_stdio"), "/root/ztp_bin/mcp_stdio", os.path.join(SPECTRUM_ROOT, "genesis_workspace", "target", "release", "mcp_stdio"), "/usr/local/bin/mcp_stdio", ) if p is not None ) DEFAULT_SEAL_CANDIDATES = tuple( p for p in ( os.path.join(LAB_ROOT, "bin", _ARCH_SUBDIR, "genesis_seal") if _ARCH_SUBDIR else None, os.path.join(LAB_ROOT, "bin", "genesis_seal"), "/root/ztp_bin/genesis_seal", os.path.join(SPECTRUM_ROOT, "genesis_workspace", "target", "release", "genesis_seal"), "/usr/local/bin/genesis_seal", ) if p is not None ) EXPECTED_ENGINE_VERSION_PREFIX = "0.15." EXPECTED_SEAL_RULE = "zero-trust-physics/seal/v2" class ZtpError(RuntimeError): """Raised on MCP transport or protocol errors.""" def resolve_engine_bin(explicit: str | None = None) -> str: """Resolve the frozen `mcp_stdio` binary path.""" candidates = [explicit] if explicit else [] env_bin = os.environ.get("ZTP_ENGINE") if env_bin: candidates.append(env_bin) candidates.extend(DEFAULT_ENGINE_CANDIDATES) for path in candidates: if path and os.path.isfile(path) and os.access(path, os.X_OK): return os.path.abspath(path) raise FileNotFoundError( "Could not locate executable mcp_stdio binary. Set ZTP_ENGINE or populate genesis_lab/bin/mcp_stdio." ) def resolve_seal_bin(explicit: str | None = None) -> str: """Resolve the frozen `genesis_seal` binary path.""" candidates = [explicit] if explicit else [] env_bin = os.environ.get("ZTP_SEAL_BIN") if env_bin: candidates.append(env_bin) candidates.extend(DEFAULT_SEAL_CANDIDATES) for path in candidates: if path and os.path.isfile(path) and os.access(path, os.X_OK): return os.path.abspath(path) raise FileNotFoundError( "Could not locate executable genesis_seal binary. Set ZTP_SEAL_BIN or populate genesis_lab/bin/genesis_seal." ) def f64_to_hex(val: float) -> str: """Return 16 lowercase hex digits of IEEE-754 binary64 big-endian representation.""" return struct.pack(">d", float(val)).hex() def f64_from_hex(hex_str: str) -> float: """Decode 16-hex-digit IEEE-754 binary64 value to Python float.""" if not isinstance(hex_str, str) or len(hex_str) != 16: raise ValueError(f"Expected 16-hex-digit string, got {hex_str!r}") return struct.unpack(">d", bytes.fromhex(hex_str))[0] def is_valid_sha384_hex(s: Any) -> bool: """True iff `s` is 96 lowercase hexadecimal digits.""" if not isinstance(s, str) or len(s) != 96: return False return all(c in "0123456789abcdef" for c in s) def decode_frame64(frame_hex: str) -> dict[str, Any]: """Decode a 64-byte (128-hex-char) kernel LastStateFrame64 into Python floats & flags.""" if not isinstance(frame_hex, str) or len(frame_hex) != 128: raise ValueError(f"Expected 128-hex-char frame_hex, got length {len(str(frame_hex))}") raw = bytes.fromhex(frame_hex) t_s = struct.unpack(" tuple[bool, str]: """Verify `receipt_sha384` directly from raw answer text per `zero-trust-physics/seal/v2`.""" if not isinstance(raw_answer_text, str): return False, "raw_answer_text is not a string" text = raw_answer_text.strip() sig_marker = ',"signature":{' if sig_marker in text and text.endswith("}}"): idx_sig = text.rfind(sig_marker) text = text[:idx_sig] + "}" marker = ',"receipt_sha384":"' idx = text.rfind(marker) if idx == -1: return False, "missing receipt_sha384 marker" tail = text[idx + len(marker) :] if not tail.endswith('"}') or len(tail) != 98: return False, "malformed receipt_sha384 tail" claimed = tail[:96] if not is_valid_sha384_hex(claimed): return False, "receipt_sha384 is not 96 lowercase hex digits" body_to_hash = (text[:idx] + "}").encode("utf-8") recomputed = hashlib.sha384(body_to_hash).hexdigest() if recomputed != claimed: return False, f"receipt mismatch: claimed {claimed[:16]}... != recomputed {recomputed[:16]}..." if '"seal_rule":"zero-trust-physics/seal/v2"' not in text[:idx]: return False, "missing or invalid seal_rule v2" return True, recomputed def sealed_form_text(obj: Any) -> str: """Exact canonical request text (`sealed_form`) per engine specification.""" if obj is None: return "null" if obj is True: return "true" if obj is False: return "false" if isinstance(obj, str): out = ['"'] for ch in obj: code = ord(ch) if ch == '"': out.append('\\"') elif ch == "\\": out.append("\\\\") elif code == 0x08: out.append("\\b") elif code == 0x09: out.append("\\t") elif code == 0x0A: out.append("\\n") elif code == 0x0C: out.append("\\f") elif code == 0x0D: out.append("\\r") elif code < 0x20: out.append(f"\\u00{code:02x}") else: out.append(ch) out.append('"') return "".join(out) if isinstance(obj, (int, float)): return "x" + f64_to_hex(float(obj)) if isinstance(obj, list): return "[" + ",".join(sealed_form_text(item) for item in obj) + "]" if isinstance(obj, dict): keys = sorted(obj.keys(), key=lambda k: k.encode("utf-8")) return "{" + ",".join(f"{sealed_form_text(k)}:{sealed_form_text(obj[k])}" for k in keys) + "}" raise TypeError(f"Unsupported type in sealed_form_text: {type(obj)}") def recompute_chain_seal_offline( upstream_commitment_hex: str, chain_obj: dict[str, Any], downstream_seal_hex: str, ) -> str: """Recompute `chain_seal` offline.""" handed_entries = [] for h in chain_obj["handed"]: val_json = json.dumps(h["value_hex"], separators=(",", ":")) unit_json = "null" if h["unit"] is None else sealed_form_text(h["unit"]) entry = ( f'{{"from":{sealed_form_text(h["from"])},' f'"to":{sealed_form_text(h["to"])},' f'"unit":{unit_json},' f'"value_hex":{val_json}}}' ) handed_entries.append(entry) coupling_json = "null" if chain_obj["coupling"] is None else sealed_form_text(chain_obj["coupling"]) middle = ( f'{{"kind":{sealed_form_text(chain_obj["kind"])},' f'"coupling":{coupling_json},' f'"handed":[{",".join(handed_entries)}]}}' ) payload = (upstream_commitment_hex + middle + downstream_seal_hex).encode("utf-8") return hashlib.sha384(payload).hexdigest() def run_genesis_seal_cli(subcommand: str, payload_text: str, seal_bin: str | None = None) -> tuple[bool, str]: """Invoke frozen `genesis_seal` binary (`verify-run` or `verify-chain`) on a temporary JSON file.""" exe = resolve_seal_bin(seal_bin) with tempfile.NamedTemporaryFile("w", suffix=".json", encoding="utf-8", delete=False) as tf: tf.write(payload_text) tmp_path = tf.name try: proc = subprocess.run( [exe, subcommand, tmp_path], capture_output=True, text=True, timeout=15, ) combined = (proc.stdout + "\n" + proc.stderr).strip() holds = proc.returncode == 0 and ("holds: true" in proc.stdout or '"holds":true' in proc.stdout.replace(" ", "")) return holds, combined finally: try: os.unlink(tmp_path) except OSError: pass class McpStdioClient: """Deterministic MCP stdio client speaking JSON-RPC 2.0 to `mcp_stdio`.""" def __init__(self, engine_bin: str | None = None, timeout_s: float = 120.0): self.engine_path = resolve_engine_bin(engine_bin) self.timeout_s = timeout_s cmd = shlex.split(self.engine_path) if " " in self.engine_path and not os.path.exists(self.engine_path) else [self.engine_path] self.proc = subprocess.Popen( cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, ) self._id = 0 self.server_info: dict[str, Any] = {} self.call_log: list[dict[str, Any]] = [] self._connect() def _send(self, message: dict[str, Any]) -> dict[str, Any]: assert self.proc.stdin is not None and self.proc.stdout is not None line = json.dumps(message, separators=(",", ":")) + "\n" self.proc.stdin.write(line.encode("utf-8")) self.proc.stdin.flush() if "id" not in message: return {} while True: ready, _, _ = select.select([self.proc.stdout], [], [], self.timeout_s) if not ready: raise ZtpError(f"Timeout waiting for mcp_stdio after {self.timeout_s}s") raw = self.proc.stdout.readline() if not raw: raise ZtpError("mcp_stdio closed stdout unexpectedly") resp = json.loads(raw.decode("utf-8")) if resp.get("id") == message["id"]: if "error" in resp: raise ZtpError(f"MCP error: {resp['error']}") return resp.get("result", {}) def _connect(self) -> None: self._id += 1 res = self._send( { "jsonrpc": "2.0", "id": self._id, "method": "initialize", "params": { "protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "genesis-lab-monolith", "version": "3.0.0"}, }, } ) self.server_info = res.get("serverInfo") or {} version = str(self.server_info.get("version", "")) if not version.startswith(EXPECTED_ENGINE_VERSION_PREFIX): raise ZtpError(f"Unexpected mcp_stdio version: {self.server_info!r}") self._send({"jsonrpc": "2.0", "method": "notifications/initialized"}) def list_tools(self) -> list[dict[str, Any]]: self._id += 1 res = self._send({"jsonrpc": "2.0", "id": self._id, "method": "tools/list", "params": {}}) return list(res.get("tools") or []) def call_raw(self, tool_name: str, arguments: dict[str, Any] | None = None) -> tuple[str, bool]: """Call a tool and return `(raw_text, is_error)` preserving exact engine byte spelling.""" args = arguments if arguments is not None else {} self._id += 1 result = self._send( { "jsonrpc": "2.0", "id": self._id, "method": "tools/call", "params": {"name": tool_name, "arguments": args}, } ) text = "".join(c.get("text", "") for c in (result.get("content") or [])) is_err = bool(result.get("isError")) self.call_log.append({"tool": tool_name, "arguments": args, "is_error": is_err}) return text, is_err def call_json(self, tool_name: str, arguments: dict[str, Any] | None = None) -> tuple[Any, str, bool]: """Call a tool and return `(parsed_or_str, raw_text, is_error)`.""" raw_text, is_err = self.call_raw(tool_name, arguments) try: parsed = json.loads(raw_text) except ValueError: parsed = raw_text return parsed, raw_text, is_err def close(self) -> None: if self.proc.poll() is None: self.proc.terminate() try: self.proc.wait(timeout=3) except subprocess.TimeoutExpired: self.proc.kill() def __enter__(self) -> "McpStdioClient": return self def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> None: self.close()