""" hyperstitionstud_io.mcp.tools — 10 Deterministic MCP Tools for the hyperstitionstud.io Ecosystem. All tools execute strictly in read-only mode inside ReadOnlyIsolationGuard. """ from __future__ import annotations import json import re from pathlib import Path from typing import Any from hyperstitionstud_io.ci.citation_sources import load_ledger, verify_draft from hyperstitionstud_io.ci.doctor import run_diagnostics from hyperstitionstud_io.ciphers import ( compute_aq, compute_variance, evaluate_bidirectional_lock, is_repdigit_37, prime_rank, ) from hyperstitionstud_io.config import load_workspace_config from hyperstitionstud_io.ipld import inspect_dag_json_payload from hyperstitionstud_io.phonetics import translate_batch from hyperstitionstud_io.quant.collector import build_financial_quant_harvest REGISTER_STAT_LABELS = { "academic": { "ARM_chokepoint_armor": "ARM (G4 Isometric Chokepoint Armor)", "VEL_teleoplexic_velocity": "VEL (Teleoplexic Escape Velocity)", "COL_variance_collapse": "COL (G1 Variance-Collapse Compression)", "CAP_trophic_capture": "CAP (S×S6 Double-Articulation & Capture)", "PRM_prime_mutation_iq": "PRM (Prime & G5 Twin-Prime Mutation IQ)", "RES_repricing_resilience": "RES (Tri-Modal Repricing & State-Gate Resilience)", }, "fund_manager": { "ARM_chokepoint_armor": "Chokepoint Moat", "VEL_teleoplexic_velocity": "Signal Velocity", "COL_variance_collapse": "Convergence Power", "CAP_trophic_capture": "Institutional Coupling", "PRM_prime_mutation_iq": "Idiosyncratic Asymmetry", "RES_repricing_resilience": "Regime Robustness", }, "corporate_board": { "ARM_chokepoint_armor": "Supply-Chain Moat", "VEL_teleoplexic_velocity": "Execution Agility", "COL_variance_collapse": "Cross-Unit Synergy", "CAP_trophic_capture": "Governance & Balance-Sheet Integration", "PRM_prime_mutation_iq": "Proprietary IP Density", "RES_repricing_resilience": "Stress-Test Resilience", }, "fantasy_football": { "ARM_chokepoint_armor": "Pass Protection", "VEL_teleoplexic_velocity": "Breakaway Speed", "COL_variance_collapse": "Stack Power", "CAP_trophic_capture": "Front-Office Cap Reach", "PRM_prime_mutation_iq": "Playbook IQ", "RES_repricing_resilience": "All-Weather Durability", }, } MCP_TOOLS_SCHEMA: list[dict[str, Any]] = [ { "name": "hs_evaluate_aq_and_ingglish", "description": "Compute Base-36 Alphanumeric Qabbala (AQ), Gen 0 -> Gen 1 CMUdict Ingglish translation, prime ranks, repdigit status, G1 variance collapse, and 12-field bidirectional locks for a list of terms.", "inputSchema": { "type": "object", "properties": { "terms": {"type": "array", "items": {"type": "string"}, "description": "English words or phrases to evaluate."}, "quant_mode": {"type": "string", "enum": ["digit", "off", "spoken", "dual"], "default": "digit"}, }, "required": ["terms"], }, }, { "name": "hs_classify_singularity", "description": "Classify terms or a headline into Landian-Deleuzean Singularity Classes S1-S6, check S×S6 Double Articulation, and evaluate Two-Gate state-matched M1-M7+ memetic activation.", "inputSchema": { "type": "object", "properties": { "terms": {"type": "array", "items": {"type": "string"}}, "headline_text": {"type": "string", "default": ""}, }, "required": ["terms"], }, }, { "name": "hs_query_knowledge_graph", "description": "Query the 388-node, 1,282-edge Encyclopedia Knowledge Graph by node ID (e.g. 'build:S1', 'aq:125', 'spec:blackwell'), headword, Ingglish token, or integer AQ coordinate.", "inputSchema": { "type": "object", "properties": { "query": {"type": "string"}, "include_neighbors": {"type": "boolean", "default": True}, }, "required": ["query"], }, }, { "name": "hs_search_glossary_encyclopedia", "description": "Search the 282 canonical glossary entries, 190 bilingual lexical specimens, and 22 Encyclopedia volumes by keyword, guild (S1..S6, M1..M7+), or integer AQ value.", "inputSchema": { "type": "object", "properties": { "query": {"type": "string"}, "guild_filter": {"type": "string", "default": ""}, "limit": {"type": "integer", "default": 15}, }, "required": ["query"], }, }, { "name": "hs_inspect_eti_tier_list", "description": "Return the Ecological Trophic Index (ETI 0-100) Assemblage Builds Tier List (S+ to D/F), 6-stat scorecards, and 13 Multi-Build Flex Singularities in the requested stakeholder register.", "inputSchema": { "type": "object", "properties": { "build_filter": {"type": "string", "default": "all"}, "register": {"type": "string", "enum": ["academic", "fund_manager", "corporate_board", "fantasy_football"], "default": "academic"}, }, }, }, { "name": "hs_simulate_anchor_revision", "description": "Simulate a Quantitative Economic Anchor Revision (Q_old -> Q_new) across digit and spoken modes, detecting Iso-Digital conservation, S1-S6 ring migrations, and 3-path counter-substitutions.", "inputSchema": { "type": "object", "properties": { "anchor_id": {"type": "string", "description": "Registered anchor ID (e.g. 'lazarus_heist_6b', 'anthropic_ipo_price_83', 'bangladesh_factories_481')."}, "new_digit_str": {"type": "string", "description": "New quantitative figure string, e.g. '$7B' or '841'."}, "new_spoken_eng": {"type": "string", "description": "Spoken English words for the new figure, e.g. 'seven billion'."}, }, "required": ["anchor_id", "new_digit_str", "new_spoken_eng"], }, }, { "name": "hs_search_archive_equations", "description": "Search all 71 verified archive and zoology dossiers for cross-scale (333 / 666 / 777) equations matching a target sum or keyword.", "inputSchema": { "type": "object", "properties": { "target_sum": {"type": "integer", "description": "Optional target sum (e.g. 333, 666, 777)."}, "keyword": {"type": "string", "default": ""}, "limit": {"type": "integer", "default": 20}, }, }, }, { "name": "hs_verify_grounded_citations", "description": "Verify inline [n] citations, Sources block URLs (via local-config path_mounts), and verbatim evidence quotes in a Markdown draft against a citation ledger.", "inputSchema": { "type": "object", "properties": { "draft_path": {"type": "string"}, "ledger_variant": {"type": "string", "enum": ["common", "english_aq"], "default": "common"}, "require_evidence": {"type": "boolean", "default": True}, }, "required": ["draft_path"], }, }, { "name": "hs_compute_ipld_dag_json_cid", "description": "Serialize a named workspace JSON registry or custom JSON object under the canonical IPLD dag-json (0x0129) codec and compute its SHA-256 digest and Base32 CIDv1 ('baguqeera...').", "inputSchema": { "type": "object", "properties": { "registry_name": { "type": "string", "description": "Optional workspace registry slug: 'glossary-registry', 'encyclopedia-manifest', 'singularity-zoology-matrix', 'memetic-superclass-registry', 'assemblage-builds-tier-list', 'quantitative-economic-anchors', or 'encyclopedia-graph'.", }, "json_object": {"type": "object", "description": "Optional arbitrary JSON object to encode as dag-json."}, }, }, }, { "name": "hs_run_doctor_and_audit", "description": "Run hs-doctor environment/font/CMUdict diagnostics and verify ReadOnlyIsolationGuard SHA-256 locks across the workspace.", "inputSchema": { "type": "object", "properties": {}, }, }, { "name": "hs_scan_financial_quant_harvest", "description": "Harvest or evaluate the 24-instrument S1-S6 quantitative financial telemetry watchlist for Scope 1-3 contingent meaning locks, M1-M6 regime triggers, and IPLD dag-json CIDv1 provenance.", "inputSchema": { "type": "object", "properties": { "harvest_mode": {"type": "string", "enum": ["us-closing-bell", "utc-rollover"], "default": "us-closing-bell"}, "symbol_filter": {"type": "string", "default": "", "description": "Optional ticker symbol filter (e.g. 'NVDA', 'ASML', 'BTC-USD')."}, }, }, }, ] def call_mcp_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]: cfg = load_workspace_config() if name == "hs_evaluate_aq_and_ingglish": terms = [str(t) for t in arguments.get("terms", [])] qmode = arguments.get("quant_mode", "digit") ing_map = translate_batch(terms) items = [] for t in terms: ing = ing_map.get(t, t.lower()) lock = evaluate_bidirectional_lock(t, ing) if qmode in ("off", "spoken", "dual"): lock["eng_aq_quant_mode"] = compute_aq(t, quant_mode="off" if qmode == "off" else "spoken") lock["ing_aq_quant_mode"] = compute_aq(ing, quant_mode="off" if qmode == "off" else "spoken") lock["is_repdigit_37_ing"] = is_repdigit_37(lock["ing_aq"]) items.append(lock) gen0_var = compute_variance([x["eng_aq"] for x in items]) gen1_var = compute_variance([x["ing_aq"] for x in items]) return { "term_count": len(items), "gen0_written_variance": gen0_var, "gen1_ingglish_variance": gen1_var, "variance_collapsed_g1": round(gen0_var - gen1_var, 2), "exact_gen1_singularity": (len(items) >= 2 and gen1_var == 0.0), "evaluations": items, } if name == "hs_classify_singularity": terms = [str(t) for t in arguments.get("terms", [])] headline = str(arguments.get("headline_text", "")).lower() mat = json.loads((cfg.zoology_dir / "taxonomy" / "singularity-zoology-matrix.json").read_text(encoding="utf-8")) mem = json.loads((cfg.zoology_dir / "taxonomy" / "memetic-superclass-registry.json").read_text(encoding="utf-8")) ing_map = translate_batch(terms) classified = [] guilds_hit: set[str] = set() for t in terms: ing = ing_map.get(t, t.lower()) lock = evaluate_bidirectional_lock(t, ing) matched_classes = [] for cid, cobj in mat.get("classes", {}).items(): sig_coords = set(cobj.get("signature_coordinates", [])) kw_set = {k.lower() for k in cobj.get("keywords", [])} if t.lower() in kw_set or lock["ing_aq"] in sig_coords: matched_classes.append(cid) guilds_hit.add(cid) lock["matched_classes"] = matched_classes or ["UNCLASSIFIED"] classified.append(lock) machinic_hit = bool(guilds_hit & {"S1", "S2", "S3", "S4", "S5"}) capture_hit = "S6" in guilds_hit active_memetic = [] for mid, mobj in mem.get("canonical_subclasses", {}).items(): triggers = [tr.lower() for tr in mobj.get("state_gate_triggers", [])] if any(tr in headline for tr in triggers) or any(any(tr in t.lower() for tr in triggers) for t in terms): active_memetic.append({"id": mid, "name": mobj.get("name"), "thermodynamic_state": mobj.get("thermodynamic_state")}) return { "guilds_activated": sorted(guilds_hit), "double_articulated_s_x_s6": (machinic_hit and capture_hit), "state_gated_memetic_subclasses": active_memetic, "classified_terms": classified, } if name == "hs_query_knowledge_graph": q = str(arguments.get("query", "")).strip().lower() inc_nbr = bool(arguments.get("include_neighbors", True)) kg_path = cfg.knowledge_graph_dir / "encyclopedia-graph.json" kg = json.loads(kg_path.read_text(encoding="utf-8")) matches = [] for n in kg["nodes"]: if ( n["id"].lower() == q or q in n["label"].lower() or q == str(n.get("ing_aq", "")) or q == str(n.get("aq_value", "")) or q == (n.get("eng", "") or "").lower() or q == (n.get("ing", "") or "").lower() ): matches.append(n) if not matches: return {"query": q, "match_count": 0, "matched_node_ids": [], "primary_node": None} primary = matches[0] nid = primary["id"] incident = [] if inc_nbr: incident = [ {"relation": e["relation"], "source": e["source"], "target": e["target"], "label": e["label"], "weight": e["weight"]} for e in kg["edges"] if e["source"] == nid or e["target"] == nid ] return { "query": q, "match_count": len(matches), "matched_node_ids": [m["id"] for m in matches[:25]], "primary_node": primary, "incident_edge_count": len(incident), "sample_incident_edges": incident[:25], } if name == "hs_search_glossary_encyclopedia": q = str(arguments.get("query", "")).strip().lower() g_filt = str(arguments.get("guild_filter", "")).strip().upper() limit = int(arguments.get("limit", 15)) gl = json.loads((cfg.zoology_dir / "taxonomy" / "glossary-registry.json").read_text(encoding="utf-8")) hits = [] for sec in gl.get("sections", []): for ent in sec.get("entries", []): if q in ent["term"].lower() or q in ent["definition"].lower() or q == str(ent.get("ing_aq", "")): hits.append({"type": "ConceptualEntry", "section": sec["section_title"], **ent}) for ent in gl.get("custom_entries", []): if q in ent["term"].lower() or q in ent["definition"].lower() or q == str(ent.get("ing_aq", "")): hits.append({"type": "CustomEntry", "section": "8B", **ent}) for spec in gl.get("bilingual_vocabulary_ledger", []): if g_filt and g_filt not in spec.get("classes", []): continue if ( not q or q in spec["eng"].lower() or q in spec["ing"].lower() or q == str(spec["ing_aq"]) or q == str(spec["eng_aq"]) ): hits.append({"type": "BilingualSpecimen", **spec}) return {"query": q, "guild_filter": g_filt, "total_matches": len(hits), "results": hits[:limit]} if name == "hs_inspect_eti_tier_list": b_filt = str(arguments.get("build_filter", "all")).strip().upper() reg = str(arguments.get("register", "academic")).strip().lower() tl = json.loads((cfg.zoology_dir / "taxonomy" / "assemblage-builds-tier-list.json").read_text(encoding="utf-8")) labels = REGISTER_STAT_LABELS.get(reg, REGISTER_STAT_LABELS["academic"]) rows = [] for r in tl.get("rows", []): if b_filt not in ("ALL", "") and b_filt not in r["eval_num"].upper() and b_filt not in r["title"].upper(): continue translated_stats = {labels.get(k, k): v for k, v in r.get("stats_6", {}).items()} rows.append({ "rank": r["rank"], "eval_num": r["eval_num"], "title": r["title"], "tier_band": r["tier_Band"], "eti_score": r["curve_score"], "roster_slot": r["roster_slot"], "double_articulated": r["double_articulated"], "gen0_var_collapsed": r["gen0_var_collapsed"], "translated_stats_6": translated_stats, "full_lock1": r["full_lock1"], "full_lock2": r["full_lock2"], "trophic_bridges": r["trophic_bridges"], }) return { "register": reg, "build_count": len(rows), "multi_build_flex_coordinates": [292, 256, 211, 193, 183, 153, 137, 136, 133, 125, 96, 95, 91, 81], "builds": rows, } if name == "hs_simulate_anchor_revision": aid = str(arguments.get("anchor_id", "")).strip() new_dig = str(arguments.get("new_digit_str", "")).strip() new_sp_eng = str(arguments.get("new_spoken_eng", "")).strip() anc_data = json.loads((cfg.zoology_dir / "taxonomy" / "quantitative-economic-anchors.json").read_text(encoding="utf-8")) anchor = next((a for a in anc_data.get("anchors", []) if a["anchor_id"] == aid), None) if anchor is None: return {"error": f"Unknown anchor_id '{aid}'", "available_anchors": [a["anchor_id"] for a in anc_data.get("anchors", [])]} old_dig_aq = compute_aq(re.sub(r"[^0-9]", "", anchor["q_digit"])) new_dig_aq = compute_aq(re.sub(r"[^0-9]", "", new_dig)) old_sp_ing = anchor["q_spoken_ing"] new_sp_ing = translate_batch([new_sp_eng]).get(new_sp_eng, new_sp_eng.lower()) old_sp_aq = compute_aq(old_sp_ing) new_sp_aq = compute_aq(new_sp_ing) d_dig = new_dig_aq - old_dig_aq d_sp = new_sp_aq - old_sp_aq return { "anchor_id": aid, "entity": anchor["entity"], "old_digit": {"str": anchor["q_digit"], "aq": old_dig_aq}, "new_digit": {"str": new_dig, "aq": new_dig_aq, "delta_q": d_dig, "iso_digital_conserved": d_dig == 0}, "old_spoken": {"eng": anchor["q_spoken_eng"], "ing": old_sp_ing, "aq": old_sp_aq, "prime_rank": prime_rank(old_sp_aq)}, "new_spoken": {"eng": new_sp_eng, "ing": new_sp_ing, "aq": new_sp_aq, "delta_q": d_sp, "prime_rank": prime_rank(new_sp_aq)}, "counter_substitution_required_delta": {"digit_mode_slot_shift": -d_dig, "spoken_mode_slot_shift": -d_sp}, "quant_free_invariant_equations": anchor.get("quant_free_lexical_equations", []), } if name == "hs_search_archive_equations": t_sum = arguments.get("target_sum") kw = str(arguments.get("keyword", "")).strip().lower() limit = int(arguments.get("limit", 20)) eqs = [] for d_dir in (cfg.zoology_dir / "dossiers", cfg.archive_dir / "ingglish-aq-archive"): if not d_dir.is_dir(): continue for md_f in sorted(d_dir.glob("*.md")): txt = md_f.read_text(encoding="utf-8") for m in re.finditer(r'-\s+`([^`]+)`\s+\("([^"]+)"\)\s+—\s+`([^`]+)=\s*(\d+)`', txt): ing_s, eng_s, brk_s, val_s = m.group(1).strip(), m.group(2).strip(), m.group(3).strip(), int(m.group(4)) if t_sum is not None and val_s != int(t_sum): continue if kw and kw not in ing_s.lower() and kw not in eng_s.lower() and kw not in md_f.name.lower(): continue eqs.append({"ing": ing_s, "eng": eng_s, "breakdown": brk_s, "target": val_s, "dossier": md_f.name}) if len(eqs) >= limit: break if len(eqs) >= limit: break return {"match_count": len(eqs), "equations": eqs[:limit]} if name == "hs_verify_grounded_citations": dp = Path(str(arguments.get("draft_path", ""))) if not dp.is_absolute(): dp = cfg.zoology_dir / dp variant = str(arguments.get("ledger_variant", "common")) req_ev = bool(arguments.get("require_evidence", True)) l_name = "citations-ledger-english-aq.json" if variant == "english_aq" else "citations-ledger-common.json" l_path = cfg.zoology_dir / "taxonomy" / l_name sources = load_ledger(l_path)["sources"] code, errors, warnings = verify_draft(dp, sources, require_evidence=req_ev) return { "draft_path": str(dp), "ledger_path": str(l_path), "passed": code == 0, "exit_code": code, "errors": errors, "warnings": warnings, } if name == "hs_compute_ipld_dag_json_cid": reg_name = arguments.get("registry_name") if reg_name: reg_map = { "glossary-registry": cfg.zoology_dir / "taxonomy" / "glossary-registry.json", "encyclopedia-manifest": cfg.zoology_dir / "encyclopedia" / "encyclopedia-manifest.json", "singularity-zoology-matrix": cfg.zoology_dir / "taxonomy" / "singularity-zoology-matrix.json", "memetic-superclass-registry": cfg.zoology_dir / "taxonomy" / "memetic-superclass-registry.json", "assemblage-builds-tier-list": cfg.zoology_dir / "taxonomy" / "assemblage-builds-tier-list.json", "quantitative-economic-anchors": cfg.zoology_dir / "taxonomy" / "quantitative-economic-anchors.json", "encyclopedia-graph": cfg.knowledge_graph_dir / "encyclopedia-graph.json", } p = reg_map.get(str(reg_name)) if p is None or not p.is_file(): return {"error": f"Unknown registry_name '{reg_name}'", "available": sorted(reg_map.keys())} raw_bytes = p.read_bytes() obj = json.loads(raw_bytes.decode("utf-8")) info = inspect_dag_json_payload(obj) info["registry_name"] = reg_name info["source_path"] = str(p) return info obj = arguments.get("json_object", {}) return inspect_dag_json_payload(obj) if name == "hs_run_doctor_and_audit": return run_diagnostics() if name == "hs_scan_financial_quant_harvest": h_mode = str(arguments.get("harvest_mode", "us-closing-bell")) sym_f = str(arguments.get("symbol_filter", "")).strip().upper() payload = build_financial_quant_harvest(harvest_mode=h_mode) if sym_f: payload["instruments"] = [x for x in payload["instruments"] if sym_f in x["symbol"].upper() or sym_f in x["entity_eng"].upper()] return payload raise ValueError(f"Unknown MCP tool: {name}")