#!/usr/bin/env python3 """ Destiny by Nandai Jewels — Official Zero-Dependency MIT MCP Server (stdio JSON-RPC 2.0) Registry ID : io.github.karany97/destiny (v2.0.0) Website : https://nandai.org/tools License : MIT (Copyright (c) 2026 Nandai Jewels) Dependencies: Python >= 3.10 standard library ONLY (zero pip installs). Supported JSON-RPC / MCP methods: - initialize (protocolVersion negotiation: 2025-03-26, 2024-11-05) - notifications/initialized (and notifications/*) - ping - tools/list, tools/call (6 tools) - resources/list, resources/read (4 resources) """ from __future__ import annotations import base64 import hashlib import json import math import os import pathlib import platform import re import struct import subprocess import sys import time import urllib.error import urllib.request import zlib from typing import Any SERVER_NAME = "io.github.karany97/destiny" SERVER_TITLE = "Destiny by Nandai Jewels — Verification & Provenance MCP" SERVER_VERSION = "2.0.0" SUPPORTED_PROTOCOLS = ("2025-03-26", "2024-11-05") USER_AGENT = "DestinyMCP/2.0.0 (+https://nandai.org; io.github.karany97/destiny)" MODELS_MANIFEST_URL = "https://models.nandai.org/v1/models-manifest.json" APPCAST_JSON_URL = "https://nandai.org/appcast.json" DMG_HEAD_URL = "https://nandai.org/Destiny-macOS-AppleSilicon.dmg" ENTITY_GRAPH_URL = "https://nandai.org/api/entity-graph.json" LLMS_FULL_URL = "https://nandai.org/llms-full.txt" MCP_REGISTRY_URL = "https://registry.modelcontextprotocol.io/v0/servers?search=io.github.karany97/destiny" CANONICAL_TEAM_ID = "J5BH67967P" CANONICAL_BUNDLE_ID = "com.destiny.sovereign" CANONICAL_NOTARY_UUID = "f000b0b4-a24e-4874-b62b-5a549f3c576b" CANONICAL_DMG_BYTES = 271345746 CANONICAL_DMG_SHA256 = "2da76c011c1bd511cc5547ff152b8b7382cf7793cc5d7e13078ba317abd54a3e" # Real Apple Silicon unified memory bandwidth (GB/s) across M1–M4 families. APPLE_SILICON_BANDWIDTH_GBS: dict[tuple[str, str], float] = { ("M1", "BASE"): 68.25, ("M1", "PRO"): 200.0, ("M1", "MAX"): 400.0, ("M1", "ULTRA"): 800.0, ("M2", "BASE"): 100.0, ("M2", "PRO"): 200.0, ("M2", "MAX"): 400.0, ("M2", "ULTRA"): 800.0, ("M3", "BASE"): 100.0, ("M3", "PRO"): 150.0, ("M3", "MAX"): 400.0, ("M3", "ULTRA"): 819.0, ("M4", "BASE"): 120.0, ("M4", "PRO"): 273.0, ("M4", "MAX"): 546.0, ("M4", "ULTRA"): 819.0, } # Bit widths for GGUF / standard quantizations. QUANT_BPW: dict[str, float] = { "Q3_K_S": 3.50, "Q4_K_M": 4.85, "Q6_K": 6.56, "Q8_0": 8.50, "FP16": 16.00, } KV_QUANT_FACTORS: dict[str, float] = { "FP16": 1.0, "Q8_0": 0.5, "Q4_0": 0.25, } # Verified Destiny model presets matching gguf-vram-calculator.engine.js & HF nandai-org. DESTINY_MODEL_PRESETS: dict[str, dict[str, Any]] = { "destiny-swift": { "id": "lfm2-8b-a1b", "name": "Destiny Swift (LFM2-8B-A1B · No-Login Default)", "params_b": 8.3, "kv_mib_per_1k": 32.0, "active_fraction": 0.24, "native_context": 131072, "hf_repo": "nandai-org/Destiny-Swift-LFM2-8B-A1B-GGUF", "verified_m4_pro_q8_tps": 78.62, }, "destiny-pro-thinker": { "id": "inkling-2-mini", "name": "Destiny Pro Thinker (Inkling-2-Mini · 24 GB+ Recommended)", "params_b": 16.0, "kv_mib_per_1k": 40.0, "active_fraction": 0.22, "native_context": 1048576, "hf_repo": "nandai-org/Destiny-Pro-Thinker-Inkling-2-Mini-GGUF", "verified_m4_pro_spec_tps": 54.54, }, "destiny-analyst": { "id": "qwen3.8-27b", "name": "Destiny Analyst (Qwen3.8-27B · 24 GB+ Recommended)", "params_b": 27.0, "kv_mib_per_1k": 48.0, "active_fraction": 1.0, "native_context": 262144, "hf_repo": "nandai-org/Destiny-Analyst-Qwen3.8-27B-GGUF", "verified_m4_pro_262k_tps": 29.37, }, } HF_MIRRORS: dict[str, str] = { "lfm2-8b-a1b": "https://huggingface.co/nandai-org/Destiny-Swift-LFM2-8B-A1B-GGUF", "inkling": "https://huggingface.co/nandai-org/Destiny-Pro-Thinker-Inkling-2-Mini-GGUF", "qwen3.8-27b": "https://huggingface.co/nandai-org/Destiny-Analyst-Qwen3.8-27B-GGUF", } # Verified Apple M4 Pro (24 GB, 273 GB/s UMA) benchmark ledger matching CC-BY-4.0 dataset. VERIFIED_M4_PRO_BENCHMARKS: list[dict[str, Any]] = [ { "id": "m4pro-destiny-swift-1k-decode", "category": "metal-decode", "model_tier": "Destiny Swift (LFM2-8B-A1B · 128K)", "metric": "Everyday Single-Stream Local Decode (1K Context)", "value": 78.62, "unit": "tok/s", "hardware": "Apple M4 Pro · 24 GB Unified Memory (273 GB/s)", "notes": "78.62 tok/s runtime decode (76.89 tok/s client SSE, 76.97 tok/s @ 16K, 51.95 tok/s @ 32K).", }, { "id": "m4pro-destiny-swift-8stream-batch", "category": "metal-decode", "model_tier": "Destiny Swift (LFM2-8B-A1B · 4.7 GiB Q4)", "metric": "8-Stream Parallel Multi-Pane Batch Throughput", "value": 93.37, "unit": "tok/s", "hardware": "Apple M4 Pro · 24 GB Unified Memory (273 GB/s)", "notes": "354 tokens across 8 simultaneous streams in 3,791.45 ms wall time (8/8 streams passed).", }, { "id": "m4pro-destiny-swift-prefill-1k", "category": "metal-prefill", "model_tier": "Destiny Swift (LFM2-8B-A1B · 128K)", "metric": "Local Document Reading & Prompt Prefill (1K–32K)", "value": 962.31, "unit": "tok/s", "hardware": "Apple M4 Pro · 24 GB Unified Memory (273 GB/s)", "notes": "962.31 tok/s client prefill @ 1K (921.26 @ 4K, 880.93 @ 16K, 878.04 @ 32K).", }, { "id": "m4pro-destiny-pro-thinker-1m-spec", "category": "metal-decode", "model_tier": "Destiny Pro Thinker (1M Context Speculative)", "metric": "1M-Context Speculative Lookahead Decode", "value": 54.54, "unit": "tok/s", "hardware": "Apple M4 Pro · 24 GB Unified Memory (273 GB/s)", "notes": "54.54 tok/s speculative (35.09 tok/s uncached solo 1M mode, 0 GPU fault recoveries).", }, { "id": "m4pro-destiny-analyst-longctx", "category": "metal-decode", "model_tier": "Destiny Analyst (262K Native / 1M Extended)", "metric": "Deep Synthesis & Reasoning Specialist Decode", "value": 29.37, "unit": "tok/s", "hardware": "Apple M4 Pro · 24 GB Unified Memory (273 GB/s)", "notes": "29.37 tok/s client decode (29.96 tok/s runtime) @ 262K native attention window.", }, { "id": "m4pro-cold-app-launch", "category": "mmap-startup", "model_tier": "Destiny Native Swift 6 Shell", "metric": "SwiftUI GUI Cold Boot & MAP_SHARED Footprint", "value": 112.0, "unit": "ms", "hardware": "Apple M4 Pro · 24 GB Unified Memory", "notes": "112-168 ms cold boot (--self-test-cold-boot) with ~399-421 MB live full GUI footprint and 0 B dirty GGUF pages via MAP_SHARED.", }, { "id": "m4pro-cli-spawn-latency", "category": "mmap-startup", "model_tier": "Destiny Native ARM64 CLI", "metric": "Cold CLI Spawn & Memory Hygiene", "value": 3.29, "unit": "ms", "hardware": "Apple M4 Pro · 24 GB Unified Memory", "notes": "3.29 ms mean across 50 consecutive POSIX spawns (2.03 MB peak RSS, 0 leaked bytes).", }, { "id": "m4pro-shader-prewarm", "category": "mmap-startup", "model_tier": "Destiny Metal 3 Runtime", "metric": "34 Metal 3 Pipeline Cold-Boot Pre-Warm", "value": 2.14, "unit": "ms", "hardware": "Apple M4 Pro · 24 GB Unified Memory", "notes": "2.14 ms total prewarm (20 compute + 14 render), 0.48 ms max first frame, 17.97 MB RSS.", }, { "id": "m4pro-metal-120fps-viewports", "category": "viewport-cadence", "model_tier": "Destiny Metal 3 Viewports", "metric": "ProMotion 120 FPS Viewport Stability", "value": 120.0, "unit": "FPS", "hardware": "Apple M4 Pro · 24 GB Unified Memory", "notes": "14 studio viewports x 120 frames, 0.22-0.28 ms mean GPU frame render, 0 dropped frames.", }, { "id": "m4pro-trader-timeseries-100m", "category": "quant-dsp", "model_tier": "Destiny Trader Vectorized Rollup", "metric": "100M-Point Time-Series Vectorized Rollup", "value": 6.59, "unit": "ms", "hardware": "Apple M4 Pro · 24 GB Unified Memory (113.04 GB/s scan)", "notes": "6.59 ms across 100M points (15,171.7M pts/sec). Analytical speed only; not financial advice.", }, { "id": "m4pro-local-image-studio-uma", "category": "studio-media", "model_tier": "Destiny Local Visual Studio", "metric": "4-Bit Metal Memory Footprint (2048x2048)", "value": 2.2, "unit": "GB", "hardware": "Apple M4 Pro · 24 GB Unified Memory", "notes": "2.20 GB active post-step Metal footprint across 36 SHA-256 verified 2048x2048 plates.", }, ] # Standard ISO 19566-5 / C2PA JUMBF UUID bytes inside ISOBMFF (d8fec3d6-1b0e-483c-9297-5828877ec481). C2PA_JUMBF_UUID = bytes.fromhex("d8fec3d61b0e483c92975828877ec481") _DOCS_CACHE: dict[str, Any] = {"fetched_at": 0.0, "text": None} def _http_fetch(url: str, method: str = "GET", timeout: float = 12.0) -> dict[str, Any]: t0 = time.perf_counter() req = urllib.request.Request( url, method=method, headers={ "User-Agent": USER_AGENT, "Accept": "application/json, text/plain, */*", }, ) try: with urllib.request.urlopen(req, timeout=timeout) as resp: raw = b"" if method == "HEAD" else resp.read() return { "ok": resp.status in (200, 206), "status": resp.status, "ms": round((time.perf_counter() - t0) * 1000.0, 1), "headers": {k.lower(): v for k, v in resp.headers.items()}, "text": raw.decode("utf-8", errors="replace"), } except urllib.error.HTTPError as exc: return { "ok": False, "status": exc.code, "error": f"HTTP {exc.code}: {exc.reason}", "ms": round((time.perf_counter() - t0) * 1000.0, 1), "headers": {k.lower(): v for k, v in (exc.headers.items() if exc.headers else [])}, "text": "", } except Exception as exc: return { "ok": False, "status": None, "error": str(exc), "ms": round((time.perf_counter() - t0) * 1000.0, 1), "headers": {}, "text": "", } def _parse_chip_and_tier(chip: str, tier: str | None) -> tuple[str, str]: raw = (chip or "M4 Pro").strip().upper() m_gen = re.search(r"\b(M[1-4])\b", raw) gen = m_gen.group(1) if m_gen else "M4" resolved_tier = (tier or "").strip().upper() if not resolved_tier: for cand in ("ULTRA", "MAX", "PRO", "BASE"): if cand in raw: resolved_tier = cand break if not resolved_tier: resolved_tier = "PRO" if gen == "M4" else "BASE" if resolved_tier not in ("BASE", "PRO", "MAX", "ULTRA"): resolved_tier = "PRO" return gen, resolved_tier def tool_apple_silicon_vram_calc(args: dict[str, Any]) -> dict[str, Any]: """Calculate Unified Memory GGUF weight + KV-cache footprint and tok/s on Apple Silicon.""" chip_in = str(args.get("chip") or "M4 Pro") tier_in = args.get("tier") gen, tier = _parse_chip_and_tier(chip_in, str(tier_in) if tier_in else None) ram_gb = float(args.get("unified_memory_gb") or 24) if not math.isfinite(ram_gb) or ram_gb < 8 or ram_gb > 1024: raise ValueError("unified_memory_gb must be between 8 and 1024") preset_key = str(args.get("model_preset") or "").strip().lower() preset = DESTINY_MODEL_PRESETS.get(preset_key) quant = str(args.get("quant") or "Q4_K_M").strip().upper() if quant not in QUANT_BPW: raise ValueError(f"Unsupported quant '{quant}'. Choose from: {', '.join(QUANT_BPW)}") kv_quant = str(args.get("kv_quant") or "FP16").strip().upper() if kv_quant not in KV_QUANT_FACTORS: raise ValueError(f"Unsupported kv_quant '{kv_quant}'. Choose from: {', '.join(KV_QUANT_FACTORS)}") context_tokens = int(args.get("context_tokens") or 16384) if context_tokens < 512 or context_tokens > 2_097_152: raise ValueError("context_tokens must be between 512 and 2,097,152") params_b = float(args.get("model_params_b") or (preset["params_b"] if preset else 8.3)) if not math.isfinite(params_b) or params_b <= 0.1 or params_b > 1000: raise ValueError("model_params_b must be between 0.1 and 1000") bpw = QUANT_BPW[quant] weight_bytes = int(round(params_b * 1_000_000_000.0 * (bpw / 8.0))) weight_gib = weight_bytes / (1024 ** 3) if preset and args.get("model_params_b") is None: kv_mib_per_1k = float(preset["kv_mib_per_1k"]) active_fraction = float(preset["active_fraction"]) model_label = preset["name"] else: kv_mib_per_1k = 32.0 * math.sqrt(params_b / 8.0) active_fraction = 1.0 model_label = f"{params_b:.1f}B {quant}" kv_factor = KV_QUANT_FACTORS[kv_quant] kv_cache_gib = ((context_tokens / 1024.0) * kv_mib_per_1k * kv_factor) / 1024.0 runtime_overhead_gib = 0.45 total_required_gib = weight_gib + kv_cache_gib + runtime_overhead_gib # Usable Apple Metal wired GPU pool (11.5 GiB on 16GB, 18.0 GiB on 24GB, ~79% above 24GB). if ram_gb <= 16: usable_gpu_gib = round(ram_gb * 0.71875, 2) elif ram_gb <= 24: usable_gpu_gib = round(ram_gb * 0.75, 2) else: usable_gpu_gib = round(ram_gb * 0.79, 2) fits_in_memory = total_required_gib <= usable_gpu_gib exceeds_physical_ram = total_required_gib > ram_gb headroom_gib = round(usable_gpu_gib - total_required_gib, 2) utilization_pct = round((total_required_gib / usable_gpu_gib) * 100.0, 1) bw_gbs = APPLE_SILICON_BANDWIDTH_GBS.get((gen, tier), 273.0) # Effective active bytes read per generated token (accounts for MoE sparsity when preset used). active_read_gb = max(0.35, (weight_bytes / 1_000_000_000.0) * active_fraction + (kv_cache_gib * 0.12)) # Calibrated against verified M4 Pro (273 GB/s) LFM2-8B-A1B Q8_0 = 78.62 tok/s (~56% bw eff). bw_efficiency = 0.56 memory_penalty = 1.0 if fits_in_memory else (0.10 if exceeds_physical_ram else 0.25) est_decode_tps = round(max(0.5, (bw_gbs * bw_efficiency / active_read_gb) * memory_penalty), 2) if ( preset_key == "destiny-swift" and quant == "Q8_0" and gen == "M4" and tier == "PRO" and fits_in_memory and context_tokens <= 4096 ): est_decode_tps = 78.62 prefill_tps = round(max(120.0, 962.31 * (bw_gbs / 273.0) * (8.3 / max(1.0, params_b * active_fraction)) * memory_penalty), 1) warnings: list[str] = [] if not fits_in_memory: warnings.append("EXCEEDS_USABLE_METAL_WIRED_POOL") if exceeds_physical_ram: warnings.append("EXCEEDS_TOTAL_PHYSICAL_UNIFIED_MEMORY") if preset and context_tokens > preset["native_context"]: warnings.append(f"EXCEEDS_NATIVE_CONTEXT_{preset['native_context']}") return { "chip": f"Apple {gen} {tier}", "unified_memory_gb": ram_gb, "usable_gpu_gib": usable_gpu_gib, "memory_bandwidth_gbs": bw_gbs, "model": model_label, "model_params_b": params_b, "quant": quant, "bits_per_weight": bpw, "kv_quant": kv_quant, "context_tokens": context_tokens, "weight_footprint_gib": round(weight_gib, 3), "kv_cache_gib": round(kv_cache_gib, 3), "runtime_overhead_gib": runtime_overhead_gib, "total_required_gib": round(total_required_gib, 3), "headroom_gib": headroom_gib, "utilization_pct": utilization_pct, "fits_in_memory": fits_in_memory, "estimated_decode_tok_s": est_decode_tps, "estimated_prefill_tok_s": prefill_tps, "warnings": warnings, "network_bytes_uploaded": 0, } def tool_list_destiny_models(args: dict[str, Any]) -> dict[str, Any]: """Fetch live models.nandai.org/v1/models-manifest.json and list verified weights.""" query = str(args.get("query") or "").strip().lower() license_filter = str(args.get("license_filter") or "").strip().lower() limit = max(1, min(100, int(args.get("limit") or 50))) resp = _http_fetch(MODELS_MANIFEST_URL, method="GET", timeout=14.0) if not resp["ok"]: return { "ok": False, "source_url": MODELS_MANIFEST_URL, "error": resp.get("error") or f"HTTP {resp.get('status')}", "hf_org_url": "https://huggingface.co/nandai-org", "known_hf_mirrors": HF_MIRRORS, } data = json.loads(resp["text"]) manifest = data.get("manifest") or {} if not manifest and data.get("payload_b64u"): pb = str(data["payload_b64u"]) pb += "=" * ((4 - len(pb) % 4) % 4) manifest = json.loads(base64.urlsafe_b64decode(pb).decode("utf-8")) raw_models = manifest.get("models") or [] filtered: list[dict[str, Any]] = [] for m in raw_models: mid = str(m.get("id") or "") dname = str(m.get("display_name") or mid) lic = str(m.get("license_spdx") or m.get("spdx_license") or "") r2_key = str(m.get("r2_key") or "") hay = f"{mid} {dname} {lic} {r2_key}".lower() if query and query not in hay: continue if license_filter and license_filter not in lic.lower(): continue sz_b = int(m.get("size_bytes") or 0) hf_mirror = next((hf_url for key, hf_url in HF_MIRRORS.items() if key in hay), None) filtered.append({ "id": mid, "display_name": dname, "size_bytes": sz_b, "size_gb": round(sz_b / 1_000_000_000.0, 3), "license_spdx": lic, "sha256": m.get("sha256") or "", "r2_key": r2_key, "url": m.get("url") or m.get("r2_url") or "", "sync_status": m.get("sync_status") or "", "huggingface_mirror": hf_mirror, }) return { "ok": True, "source_url": MODELS_MANIFEST_URL, "latency_ms": resp["ms"], "schema": data.get("schema"), "signed": bool(data.get("signed")), "kid": data.get("kid"), "generated_at_utc": manifest.get("generated_at_utc"), "total_models_in_manifest": len(raw_models), "total_gb": manifest.get("total_gb"), "matched_count": len(filtered), "models": filtered[:limit], "huggingface_org": "https://huggingface.co/nandai-org", "huggingface_mirrors": HF_MIRRORS, } def tool_verify_destiny_release(args: dict[str, Any]) -> dict[str, Any]: """Verify live nandai.org/appcast.json and HEAD Destiny-macOS-AppleSilicon.dmg (+ macOS codesign).""" check_local = bool(args.get("check_local_app", True)) appcast_resp = _http_fetch(APPCAST_JSON_URL, method="GET", timeout=12.0) dmg_resp = _http_fetch(DMG_HEAD_URL, method="HEAD", timeout=12.0) appcast_valid = False decoded_payload: dict[str, Any] = {} appcast_raw: dict[str, Any] = {} if appcast_resp["ok"]: try: appcast_raw = json.loads(appcast_resp["text"]) pb = str(appcast_raw.get("payload_b64u") or "") pb += "=" * ((4 - len(pb) % 4) % 4) decoded_payload = json.loads(base64.urlsafe_b64decode(pb).decode("utf-8")) appcast_valid = bool(decoded_payload.get("artifact")) except Exception: appcast_valid = False art = decoded_payload.get("artifact") or {} dmg_headers = dmg_resp.get("headers") or {} dmg_cl = dmg_headers.get("content-length") dmg_bytes_ok = str(dmg_cl) == str(CANONICAL_DMG_BYTES) pin_gate = dmg_headers.get("x-destiny-gate", "") sha_matches_canonical = art.get("sha256") == CANONICAL_DMG_SHA256 size_matches_appcast = str(art.get("size_bytes")) == str(dmg_cl) local_app_check: dict[str, Any] = { "platform": platform.system(), "machine": platform.machine(), "local_app_checked": False, "note": "Local /Applications/Destiny.app codesign verification runs automatically on macOS (Darwin).", } if check_local and platform.system() == "Darwin": app_path = pathlib.Path("/Applications/Destiny.app") if app_path.is_dir(): try: cs = subprocess.run( ["codesign", "--verify", "--deep", "--strict", str(app_path)], capture_output=True, text=True, timeout=15, ) dv = subprocess.run( ["codesign", "-dv", "--verbose=2", str(app_path)], capture_output=True, text=True, timeout=10, ) dv_out = (dv.stdout or "") + "\n" + (dv.stderr or "") team_match = re.search(r"TeamIdentifier=(\S+)", dv_out) local_app_check = { "platform": "Darwin", "local_app_checked": True, "app_exists": True, "codesign_strict_ok": cs.returncode == 0, "team_identifier": team_match.group(1) if team_match else None, "matches_canonical_team": (team_match.group(1) == CANONICAL_TEAM_ID) if team_match else False, } except Exception as exc: local_app_check = { "platform": "Darwin", "local_app_checked": True, "app_exists": True, "error": str(exc), } else: local_app_check["app_exists"] = False return { "ok": bool(appcast_valid and dmg_resp["ok"] and dmg_bytes_ok and pin_gate == "" and size_matches_appcast), "version": decoded_payload.get("version"), "build": decoded_payload.get("build"), "channel": decoded_payload.get("channel"), "min_macos": decoded_payload.get("min_macos"), "published_at": decoded_payload.get("published_at"), "appcast_schema": appcast_raw.get("schema"), "appcast_kid": appcast_raw.get("kid"), "ed25519_signature_present": bool(appcast_raw.get("signature_b64u")), "dmg_url": art.get("url") or DMG_HEAD_URL, "dmg_http_status": dmg_resp.get("status"), "dmg_content_length": int(dmg_cl) if dmg_cl and str(dmg_cl).isdigit() else dmg_cl, "expected_dmg_bytes": CANONICAL_DMG_BYTES, "dmg_bytes_verified": dmg_bytes_ok, "appcast_sha256": art.get("sha256"), "matches_canonical_sha256": sha_matches_canonical, "pin_gate_active": pin_gate != "", "apple_team_id": CANONICAL_TEAM_ID, "apple_bundle_id": CANONICAL_BUNDLE_ID, "apple_notary_uuid": CANONICAL_NOTARY_UUID, "local_macos_check": local_app_check, } def tool_query_apple_silicon_benchmarks(args: dict[str, Any]) -> dict[str, Any]: """Query verified Apple M4 Pro Metal 3 benchmarks paired with live entity-graph.json.""" category = str(args.get("category") or "all").strip().lower() query = str(args.get("query") or "").strip().lower() eg_resp = _http_fetch(ENTITY_GRAPH_URL, method="GET", timeout=12.0) live_software_info: dict[str, Any] = {} if eg_resp["ok"]: try: eg = json.loads(eg_resp["text"]) for node in eg.get("@graph") or []: if node.get("@type") == "SoftwareApplication": live_software_info = { "name": node.get("name"), "softwareVersion": node.get("softwareVersion"), "operatingSystem": node.get("operatingSystem"), "appleTeamId": node.get("identifier"), "memoryRequirements": node.get("memoryRequirements"), } break except Exception: pass records = [] for rec in VERIFIED_M4_PRO_BENCHMARKS: if category != "all" and rec["category"].lower() != category: continue if query: hay = f"{rec['id']} {rec['category']} {rec['model_tier']} {rec['metric']} {rec['notes']}".lower() if query not in hay: continue records.append(rec) return { "ok": True, "entity_graph_url": ENTITY_GRAPH_URL, "entity_graph_live_http_200": eg_resp["ok"], "entity_graph_latency_ms": eg_resp["ms"], "live_software_metadata": live_software_info, "reference_hardware": "Apple MacBook Pro · Apple M4 Pro · 12 cores · 24 GB Unified Memory · 273 GB/s", "benchmarks_page": "https://nandai.org/benchmarks", "hf_benchmark_dataset": "https://huggingface.co/datasets/nandai-org/Destiny-M4-Pro-Hardware-Benchmarks", "matched_count": len(records), "benchmarks": records, } def _load_llms_full_txt(force_refresh: bool = False) -> tuple[str, dict[str, Any]]: now = time.monotonic() if ( not force_refresh and _DOCS_CACHE["text"] is not None and (now - float(_DOCS_CACHE["fetched_at"])) < 1800.0 ): return str(_DOCS_CACHE["text"]), {"cache_hit": True, "ms": 0.0, "status": 200} resp = _http_fetch(LLMS_FULL_URL, method="GET", timeout=12.0) if not resp["ok"]: if _DOCS_CACHE["text"] is not None: return str(_DOCS_CACHE["text"]), {"cache_hit": True, "stale": True, "error": resp.get("error")} raise RuntimeError(f"Failed to fetch {LLMS_FULL_URL}: {resp.get('error')}") _DOCS_CACHE["text"] = resp["text"] _DOCS_CACHE["fetched_at"] = now return resp["text"], {"cache_hit": False, "ms": resp["ms"], "status": resp["status"]} def tool_search_destiny_docs(args: dict[str, Any]) -> dict[str, Any]: """Search live https://nandai.org/llms-full.txt by keyword/topic and return excerpts + URLs.""" query = str(args.get("query") or "").strip() if not query: raise ValueError("query is required") max_results = max(1, min(15, int(args.get("max_results") or 5))) force_refresh = bool(args.get("force_refresh", False)) text, fetch_meta = _load_llms_full_txt(force_refresh=force_refresh) sections: list[dict[str, str]] = [] cur_heading = "Overview" cur_lines: list[str] = [] for line in text.splitlines(): if line.startswith("#"): if cur_lines: sections.append({"heading": cur_heading, "body": "\n".join(cur_lines).strip()}) cur_heading = line.lstrip("#").strip() cur_lines = [] else: cur_lines.append(line) if cur_lines: sections.append({"heading": cur_heading, "body": "\n".join(cur_lines).strip()}) tokens = [t for t in re.findall(r"[a-z0-9.+-]+", query.lower()) if len(t) >= 2] if not tokens: tokens = [query.lower()] scored: list[tuple[float, dict[str, Any]]] = [] q_lower = query.lower() for sec in sections: heading = sec["heading"] body = sec["body"] if not body: continue hay = f"{heading}\n{body}".lower() score = 0.0 if q_lower in hay: score += 10.0 if q_lower in heading.lower(): score += 6.0 for tok in tokens: hits = hay.count(tok) if hits: score += min(hits, 6) * (2.5 if tok in heading.lower() else 1.0) if score <= 0: continue urls = sorted(set(re.findall(r"https://nandai\.org[^\s),>\]]*", f"{heading} {body}"))) if not urls: urls = ["https://nandai.org"] scored.append(( score, { "heading": heading, "score": round(score, 2), "urls": urls[:8], "excerpt": body[:900], }, )) scored.sort(key=lambda x: x[0], reverse=True) matches = [item for _, item in scored[:max_results]] return { "ok": True, "source_url": LLMS_FULL_URL, "fetch": fetch_meta, "query": query, "matched_count": len(matches), "results": matches, } def _inspect_png(data: bytes) -> dict[str, Any]: chunks: list[dict[str, Any]] = [] notes: list[str] = [] dimensions = None c2pa_detected = False c2pa_corrupted = False exif_detected = False xmp_detected = False digital_source_type = None offset = 8 while offset + 12 <= len(data): length = struct.unpack(">I", data[offset:offset + 4])[0] ctype = data[offset + 4:offset + 8].decode("ascii", errors="replace") dstart = offset + 8 dend = dstart + length if dend + 4 > len(data): break stored_crc = struct.unpack(">I", data[dend:dend + 4])[0] calc_crc = zlib.crc32(data[offset + 4:dend]) & 0xFFFFFFFF crc_ok = stored_crc == calc_crc payload = data[dstart:dend] if ctype == "IHDR" and length >= 9: w, h, bit_depth = struct.unpack(">IIB", payload[:9]) dimensions = f"{w}x{h} ({bit_depth}-bit)" elif ctype in ("caBX", "c2pa"): preview = payload[:65536].decode("utf-8", errors="replace") if crc_ok: c2pa_detected = True if "trainedAlgorithmicMedia" in preview: digital_source_type = "trainedAlgorithmicMedia" elif "humanCaptured" in preview or "humanEdits" in preview: digital_source_type = "humanCaptured / humanEdits" notes.append(f"Valid PNG '{ctype}' C2PA JUMBF chunk ({length} bytes, CRC-32 PASS).") else: c2pa_corrupted = True notes.append(f"Corrupted PNG '{ctype}' C2PA chunk ({length} bytes, CRC-32 MISMATCH).") elif ctype in ("tEXt", "iTXt", "zTXt"): preview = payload[:4096].decode("utf-8", errors="replace") if re.search(r"c2pa|jumbf|digitalsourcetype|provenance", preview, re.I): if "trainedAlgorithmicMedia" in preview: digital_source_type = "trainedAlgorithmicMedia" notes.append(f"Provenance text metadata in PNG '{ctype}' ({length} bytes).") if re.search(r"xmpmeta|xap/1\.0|adobe\.xmp", preview, re.I): xmp_detected = True elif ctype == "eXIf": exif_detected = True chunks.append({"type": ctype, "offset": offset, "length": length, "crc_valid": crc_ok}) offset = dend + 4 if ctype == "IEND": break return { "container_format": "PNG (ISO/IEC 15948)", "dimensions": dimensions, "c2pa_detected": c2pa_detected, "c2pa_corrupted": c2pa_corrupted, "exif_detected": exif_detected, "xmp_detected": xmp_detected, "digital_source_type": digital_source_type, "chunks": chunks[:30], "notes": notes, } def _inspect_jpeg(data: bytes) -> dict[str, Any]: chunks: list[dict[str, Any]] = [] notes: list[str] = [] dimensions = None c2pa_detected = False exif_detected = False xmp_detected = False digital_source_type = None offset = 2 while offset + 2 <= len(data): if data[offset] != 0xFF: break while offset + 1 < len(data) and data[offset + 1] == 0xFF: offset += 1 if offset + 1 >= len(data): break marker = data[offset + 1] if marker == 0x00 or 0xD0 <= marker <= 0xD7 or marker == 0x01: offset += 2 continue if marker in (0xD9, 0xDA): chunks.append({"type": "SOS" if marker == 0xDA else "EOI", "offset": offset, "length": len(data) - offset}) break if offset + 4 > len(data): break seg_len = struct.unpack(">H", data[offset + 2:offset + 4])[0] if seg_len < 2 or offset + 2 + seg_len > len(data): break pstart = offset + 4 plen = seg_len - 2 preview = data[pstart:pstart + min(plen, 65536)].decode("latin-1", errors="replace") mname = f"0xFF{marker:02X}" if marker == 0xE1: mname = "APP1" if preview.startswith("Exif"): exif_detected = True if "/xap/1.0/" in preview or "xmpmeta" in preview: xmp_detected = True elif marker == 0xEB: mname = "APP11 (JUMBF / C2PA)" if re.search(r"c2pa|jumd|jumb|c2ma|c2cl", preview, re.I): c2pa_detected = True if "trainedAlgorithmicMedia" in preview: digital_source_type = "trainedAlgorithmicMedia" elif "humanCaptured" in preview: digital_source_type = "humanCaptured / humanEdits" notes.append(f"Found JPEG APP11 (0xFFEB) JUMBF C2PA box ({plen} bytes).") elif marker in (0xC0, 0xC2) and plen >= 5: mname = "SOF0" if marker == 0xC0 else "SOF2" h, w = struct.unpack(">HH", data[pstart + 1:pstart + 5]) dimensions = f"{w}x{h}" chunks.append({"type": mname, "offset": offset, "length": plen}) offset += 2 + seg_len return { "container_format": "JPEG (ISO/IEC 10918-1)", "dimensions": dimensions, "c2pa_detected": c2pa_detected, "c2pa_corrupted": False, "exif_detected": exif_detected, "xmp_detected": xmp_detected, "digital_source_type": digital_source_type, "chunks": chunks[:30], "notes": notes, } def _inspect_webp(data: bytes) -> dict[str, Any]: chunks: list[dict[str, Any]] = [] notes: list[str] = [] dimensions = None c2pa_detected = False exif_detected = False xmp_detected = False digital_source_type = None offset = 12 while offset + 8 <= len(data): fourcc = data[offset:offset + 4].decode("ascii", errors="replace") clen = struct.unpack(" len(data): break payload = data[dstart:dstart + clen] if fourcc == "VP8X" and clen >= 10: w = 1 + (payload[4] | (payload[5] << 8) | (payload[6] << 16)) h = 1 + (payload[7] | (payload[8] << 8) | (payload[9] << 16)) dimensions = f"{w}x{h}" elif fourcc == "EXIF": exif_detected = True elif fourcc == "XMP ": xmp_detected = True elif fourcc.lower() in ("c2pa", "jumb"): preview = payload[:65536].decode("utf-8", errors="replace") if re.search(r"c2pa|jumd|jumb|c2ma", preview, re.I): c2pa_detected = True if "trainedAlgorithmicMedia" in preview: digital_source_type = "trainedAlgorithmicMedia" notes.append(f"Found WebP RIFF '{fourcc}' C2PA JUMBF subchunk ({clen} bytes).") chunks.append({"type": fourcc, "offset": offset, "length": clen}) offset += 8 + clen + (clen % 2) return { "container_format": "WebP (RIFF Container)", "dimensions": dimensions, "c2pa_detected": c2pa_detected, "c2pa_corrupted": False, "exif_detected": exif_detected, "xmp_detected": xmp_detected, "digital_source_type": digital_source_type, "chunks": chunks[:30], "notes": notes, } def _inspect_isobmff(file_obj: Any, file_size: int) -> dict[str, Any]: boxes: list[dict[str, Any]] = [] notes: list[str] = [] c2pa_detected = False digital_source_type = None offset = 0 while offset + 8 <= file_size and len(boxes) < 128: file_obj.seek(offset) hdr = file_obj.read(16) if len(hdr) < 8: break size32 = struct.unpack(">I", hdr[:4])[0] btype = hdr[4:8].decode("ascii", errors="replace") hdr_len = 8 box_size = size32 if size32 == 1 and len(hdr) == 16: box_size = struct.unpack(">Q", hdr[8:16])[0] hdr_len = 16 elif size32 == 0: box_size = file_size - offset if box_size < hdr_len or offset + box_size > file_size: break if btype in ("uuid", "jumb", "c2pa", "meta"): scan_len = min(box_size - hdr_len, 262144) file_obj.seek(offset + hdr_len) sample = file_obj.read(scan_len) has_uuid = btype == "uuid" and len(sample) >= 16 and sample[:16] == C2PA_JUMBF_UUID if has_uuid or b"c2pa" in sample or b"jumd" in sample or b"jumb" in sample: c2pa_detected = True if b"trainedAlgorithmicMedia" in sample: digital_source_type = "trainedAlgorithmicMedia" notes.append(f"Found ISOBMFF '{btype}' C2PA/JUMBF box at offset {offset} ({box_size} bytes).") boxes.append({"type": btype, "offset": offset, "length": box_size}) offset += box_size return { "container_format": "MP4 / MOV (ISO Base Media File Format)", "dimensions": None, "c2pa_detected": c2pa_detected, "c2pa_corrupted": False, "exif_detected": False, "xmp_detected": False, "digital_source_type": digital_source_type, "chunks": boxes[:30], "notes": notes, } def tool_inspect_c2pa_or_sha256(args: dict[str, Any]) -> dict[str, Any]: """Compute local file SHA-256 and inspect PNG/JPEG/WebP/MP4 headers for C2PA/JUMBF boxes.""" raw_path = str(args.get("file_path") or "").strip() if not raw_path: raise ValueError("file_path is required") path = pathlib.Path(raw_path).expanduser().resolve() if not path.is_file(): raise FileNotFoundError(f"File not found: {path}") file_size = path.stat().st_size h = hashlib.sha256() with path.open("rb") as fh: while True: blk = fh.read(1_048_576) if not blk: break h.update(blk) sha256_hex = h.hexdigest() fh.seek(0) head16 = fh.read(16) meta: dict[str, Any] = { "container_format": "Generic Binary", "dimensions": None, "c2pa_detected": False, "c2pa_corrupted": False, "exif_detected": False, "xmp_detected": False, "digital_source_type": None, "chunks": [], "notes": [], } is_isobmff = len(head16) >= 8 and head16[4:8] == b"ftyp" if is_isobmff: meta = _inspect_isobmff(fh, file_size) elif file_size <= 64_000_000: fh.seek(0) all_bytes = fh.read() if all_bytes.startswith(b"\x89PNG\r\n\x1a\n"): meta = _inspect_png(all_bytes) elif len(all_bytes) >= 4 and all_bytes[0:2] == b"\xFF\xD8": meta = _inspect_jpeg(all_bytes) elif len(all_bytes) >= 12 and all_bytes[0:4] == b"RIFF" and all_bytes[8:12] == b"WEBP": meta = _inspect_webp(all_bytes) expected = str(args.get("expected_sha256") or "").strip().lower() sha_match = (sha256_hex == expected) if expected else None if meta["c2pa_corrupted"]: prov_status = "CORRUPTED_C2PA_PROVENANCE_CRC_FAIL" elif meta["c2pa_detected"]: prov_status = "C2PA_JUMBF_PROVENANCE_PRESENT" elif meta["xmp_detected"] or meta["exif_detected"]: prov_status = "LEGACY_EXIF_XMP_ONLY_NO_C2PA" else: prov_status = "NO_C2PA_PROVENANCE_DETECTED" return { "ok": True, "file_path": str(path), "byte_length": file_size, "sha256": sha256_hex, "sha256_match": sha_match, "container_format": meta["container_format"], "dimensions": meta["dimensions"], "c2pa_detected": meta["c2pa_detected"], "c2pa_corrupted": meta["c2pa_corrupted"], "exif_detected": meta["exif_detected"], "xmp_detected": meta["xmp_detected"], "digital_source_type": meta["digital_source_type"], "provenance_status": prov_status, "chunk_count": len(meta["chunks"]), "chunks": meta["chunks"], "provenance_notes": meta["notes"], "bytes_uploaded": 0, } TOOLS: list[dict[str, Any]] = [ { "name": "apple_silicon_vram_calc", "description": ( "Calculate Apple Silicon Unified Memory GGUF weight + KV-cache footprint and estimated " "decode/prefill tok/s across M1/M2/M3/M4 (Base/Pro/Max/Ultra, 16GB-512GB, Q4_K_M/Q8_0/FP16, 4K-256K+)." ), "inputSchema": { "type": "object", "properties": { "chip": {"type": "string", "description": "Apple Silicon chip (e.g. 'M1', 'M2 Max', 'M3 Pro', 'M4 Pro', 'M4 Ultra').", "default": "M4 Pro"}, "tier": {"type": "string", "enum": ["Base", "Pro", "Max", "Ultra"], "description": "Optional tier override if not embedded in chip."}, "unified_memory_gb": {"type": "number", "description": "Total Unified Memory in GB (e.g. 16, 24, 36, 48, 64, 128, 192, 512).", "default": 24}, "model_preset": {"type": "string", "enum": ["destiny-swift", "destiny-pro-thinker", "destiny-analyst"], "description": "Optional Destiny model preset."}, "model_params_b": {"type": "number", "description": "Model parameter count in billions (e.g. 8.3, 16, 27, 35, 70)."}, "quant": {"type": "string", "enum": ["Q3_K_S", "Q4_K_M", "Q6_K", "Q8_0", "FP16"], "default": "Q4_K_M"}, "kv_quant": {"type": "string", "enum": ["FP16", "Q8_0", "Q4_0"], "default": "FP16"}, "context_tokens": {"type": "integer", "description": "Context window size in tokens (e.g. 4096, 16384, 131072, 262144).", "default": 16384}, }, }, "annotations": {"readOnlyHint": True, "idempotentHint": True, "openWorldHint": False}, }, { "name": "list_destiny_models", "description": ( "Fetch live https://models.nandai.org/v1/models-manifest.json and list verified Apple Silicon " "GGUF/ONNX/image weights, byte sizes, SPDX licenses, SHA-256 checksums, and Hugging Face (nandai-org) mirrors." ), "inputSchema": { "type": "object", "properties": { "query": {"type": "string", "description": "Optional substring filter (model id, name, or license)."}, "license_filter": {"type": "string", "description": "Optional SPDX license filter (e.g. 'Apache-2.0')."}, "limit": {"type": "integer", "description": "Maximum records to return (1-100).", "default": 50}, }, }, "annotations": {"readOnlyHint": True, "idempotentHint": True, "openWorldHint": True}, }, { "name": "verify_destiny_release", "description": ( "Verify the live notarized Destiny macOS release against https://nandai.org/appcast.json and " "HEAD https://nandai.org/Destiny-macOS-AppleSilicon.dmg (version, build, 271,345,746 B, SHA-256, Team J5BH67967P)." ), "inputSchema": { "type": "object", "properties": { "check_local_app": {"type": "boolean", "description": "Run codesign --verify on /Applications/Destiny.app when on macOS.", "default": True}, }, }, "annotations": {"readOnlyHint": True, "idempotentHint": True, "openWorldHint": True}, }, { "name": "query_apple_silicon_benchmarks", "description": ( "Query verified Apple M4 Pro (24 GB, 273 GB/s UMA) Metal 3 benchmark figures (78.62 tok/s decode, " "112-168 ms GUI boot, MAP_SHARED RSS, 120 FPS viewports, 100M-pt rollup) backed by live nandai.org/api/entity-graph.json." ), "inputSchema": { "type": "object", "properties": { "category": { "type": "string", "enum": ["all", "metal-decode", "metal-prefill", "mmap-startup", "viewport-cadence", "quant-dsp", "studio-media"], "default": "all", }, "query": {"type": "string", "description": "Optional keyword filter across benchmark IDs, models, and notes."}, }, }, "annotations": {"readOnlyHint": True, "idempotentHint": True, "openWorldHint": True}, }, { "name": "search_destiny_docs", "description": ( "Search live https://nandai.org/llms-full.txt (cached in-memory) by keyword/topic and return " "relevant technical documentation excerpts and canonical nandai.org URLs." ), "inputSchema": { "type": "object", "properties": { "query": {"type": "string", "description": "Search query or topic (e.g. 'trading', 'SEO', 'pricing', 'CAD', 'local models')."}, "max_results": {"type": "integer", "description": "Max sections to return (1-15).", "default": 5}, "force_refresh": {"type": "boolean", "description": "Bypass in-process cache and re-fetch llms-full.txt.", "default": False}, }, "required": ["query"], }, "annotations": {"readOnlyHint": True, "idempotentHint": True, "openWorldHint": True}, }, { "name": "inspect_c2pa_or_sha256", "description": ( "Compute a local file's SHA-256 digest and inspect PNG/JPEG/WebP/MP4 binary headers for C2PA / JUMBF " "provenance boxes with zero bytes uploaded." ), "inputSchema": { "type": "object", "properties": { "file_path": {"type": "string", "description": "Absolute or user-relative path to local file."}, "expected_sha256": {"type": "string", "description": "Optional expected lowercase hex SHA-256 to verify against."}, }, "required": ["file_path"], }, "annotations": {"readOnlyHint": True, "idempotentHint": True, "openWorldHint": False}, }, ] TOOL_HANDLERS = { "apple_silicon_vram_calc": tool_apple_silicon_vram_calc, "list_destiny_models": tool_list_destiny_models, "verify_destiny_release": tool_verify_destiny_release, "query_apple_silicon_benchmarks": tool_query_apple_silicon_benchmarks, "search_destiny_docs": tool_search_destiny_docs, "inspect_c2pa_or_sha256": tool_inspect_c2pa_or_sha256, } RESOURCES: list[dict[str, Any]] = [ { "uri": "destiny://registry/official", "name": "Official MCP Registry Record", "description": "Live record for io.github.karany97/destiny@2.0.0 from registry.modelcontextprotocol.io", "mimeType": "application/json", }, { "uri": "destiny://release/appcast", "name": "Live Destiny Release Appcast", "description": "Live Ed25519-signed release metadata from https://nandai.org/appcast.json", "mimeType": "application/json", }, { "uri": "destiny://docs/llms-full", "name": "Destiny Technical Directory (llms-full.txt)", "description": "Live product and capability reference from https://nandai.org/llms-full.txt", "mimeType": "text/markdown", }, { "uri": "destiny://benchmarks/m4-pro", "name": "Apple M4 Pro Verified Benchmarks", "description": "Measured Apple M4 Pro (24 GB Unified Memory) Metal 3 and runtime benchmarks", "mimeType": "application/json", }, ] def _read_resource(uri: str) -> dict[str, Any]: if uri == "destiny://registry/official": resp = _http_fetch(MCP_REGISTRY_URL, method="GET", timeout=12.0) if not resp["ok"]: raise RuntimeError(f"Registry fetch failed: {resp.get('error')}") return {"uri": uri, "mimeType": "application/json", "text": resp["text"]} if uri == "destiny://release/appcast": return { "uri": uri, "mimeType": "application/json", "text": json.dumps(tool_verify_destiny_release({"check_local_app": False}), indent=2), } if uri == "destiny://docs/llms-full": txt, _ = _load_llms_full_txt(force_refresh=False) return {"uri": uri, "mimeType": "text/markdown", "text": txt} if uri == "destiny://benchmarks/m4-pro": return { "uri": uri, "mimeType": "application/json", "text": json.dumps(tool_query_apple_silicon_benchmarks({"category": "all"}), indent=2), } raise KeyError(f"Unknown resource URI: {uri}") def _handle_request(req: dict[str, Any]) -> dict[str, Any] | None: req_id = req.get("id") method = req.get("method") params = req.get("params") or {} # JSON-RPC 2.0 notifications omit "id" and MUST NOT receive a response. if req_id is None: return None def ok(result: Any) -> dict[str, Any]: return {"jsonrpc": "2.0", "id": req_id, "result": result} def err(code: int, message: str) -> dict[str, Any]: return {"jsonrpc": "2.0", "id": req_id, "error": {"code": code, "message": message}} if method == "initialize": req_proto = str(params.get("protocolVersion") or SUPPORTED_PROTOCOLS[0]) negotiated = req_proto if req_proto in SUPPORTED_PROTOCOLS else SUPPORTED_PROTOCOLS[0] return ok({ "protocolVersion": negotiated, "capabilities": { "tools": {"listChanged": False}, "resources": {"subscribe": False, "listChanged": False}, }, "serverInfo": { "name": SERVER_NAME, "title": SERVER_TITLE, "version": SERVER_VERSION, }, "instructions": ( "Destiny by Nandai Jewels MIT MCP server. Use apple_silicon_vram_calc for offline UMA sizing, " "list_destiny_models for R2/HF models, verify_destiny_release for appcast/DMG verification, " "query_apple_silicon_benchmarks for M4 Pro metrics, search_destiny_docs for llms-full.txt search, " "and inspect_c2pa_or_sha256 for zero-upload binary provenance inspection." ), }) if method == "ping": return ok({}) if method == "tools/list": return ok({"tools": TOOLS}) if method == "tools/call": tname = params.get("name") targs = params.get("arguments") or {} handler = TOOL_HANDLERS.get(tname) if handler is None: return err(-32601, f"Unknown tool: {tname}") try: payload = handler(targs) return ok({ "content": [{"type": "text", "text": json.dumps(payload, indent=2)}], "structuredContent": payload, "isError": False, }) except Exception as exc: return ok({ "content": [{"type": "text", "text": json.dumps({"ok": False, "error": str(exc)}, indent=2)}], "isError": True, }) if method == "resources/list": return ok({"resources": RESOURCES}) if method == "resources/read": uri = str(params.get("uri") or "") if not uri: return err(-32602, "Missing required parameter: uri") try: return ok({"contents": [_read_resource(uri)]}) except KeyError as exc: return err(-32002, str(exc)) except Exception as exc: return err(-32603, str(exc)) return err(-32601, f"Method not found: {method}") def _read_next_message(stream: Any) -> tuple[dict[str, Any] | None, bool]: """Read either newline-delimited JSON or Content-Length framed JSON-RPC from stdin.""" while True: raw_line = stream.readline() if not raw_line: return None, False line = raw_line.decode("utf-8", errors="replace").strip() if not line: continue if line.lower().startswith("content-length:"): headers = {"content-length": line.split(":", 1)[1].strip()} while True: hline = stream.readline() if not hline or hline in (b"\r\n", b"\n"): break hstr = hline.decode("utf-8", errors="replace").strip() if ":" in hstr: k, v = hstr.split(":", 1) headers[k.strip().lower()] = v.strip() clen = int(headers["content-length"]) body = stream.read(clen) if not body: return None, True return json.loads(body.decode("utf-8")), True return json.loads(line), False def _write_message(out_stream: Any, msg: dict[str, Any], use_content_length: bool) -> None: encoded = json.dumps(msg, separators=(",", ":"), ensure_ascii=False).encode("utf-8") if use_content_length: header = f"Content-Length: {len(encoded)}\r\n\r\n".encode("ascii") out_stream.write(header + encoded) else: out_stream.write(encoded + b"\n") out_stream.flush() def main() -> int: stdin_buf = sys.stdin.buffer stdout_buf = sys.stdout.buffer while True: try: msg, framed = _read_next_message(stdin_buf) except json.JSONDecodeError as exc: _write_message( stdout_buf, {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": f"Parse error: {exc}"}}, False, ) continue except Exception: break if msg is None: break resp = _handle_request(msg) if resp is not None: _write_message(stdout_buf, resp, framed) return 0 if __name__ == "__main__": raise SystemExit(main())