feat(v2.0.8): implement ipld dag-json/CIDv1, quant financial collector, MCP server (hs-mcp), /learn/ sub-page, /gallery/ sub-page, and global Lemurs footer

This commit is contained in:
Hermes Agent committed 2026-11-30 03:39:56 +00:00
1 parent b767f8a4e9
commit c17f74097b
55 files changed
+3974 -10

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
"""
hyperstitionstud_io.mcp — Model Context Protocol (MCP) Server for hyperstitionstud.io.
Supports MCP 2025-03-26 & 2024-11-05 over both stdio and stateless Streamable HTTP (/mcp).
"""
from hyperstitionstud_io.mcp.server import dispatch_jsonrpc, main
__all__ = ["dispatch_jsonrpc", "main"]
+90
View File
@@ -0,0 +1,90 @@
"""
hyperstitionstud_io.mcp.prompts — Guided Workflow Prompts for MCP Clients.
"""
from __future__ import annotations
from typing import Any
MCP_PROMPTS: list[dict[str, Any]] = [
{
"name": "analyze_headline_zoology",
"description": "Extract tokens from a news headline or financial event, evaluate Gen 0 -> Gen 1 Ingglish AQ locks, check Two-Gate M1-M7+ activation, and synthesize a zero-padding Technocapital Singularity analysis.",
"arguments": [
{"name": "headline", "description": "Headline or event description to analyze.", "required": True},
],
},
{
"name": "draft_stakeholder_proposal_section",
"description": "Draft an evidence-grounded section for a Fund Manager, Corporate Board, or Fantasy Roster stakeholder using native register metrics and verified citation ledger IDs.",
"arguments": [
{"name": "audience", "description": "Target register: fund_manager, corporate_board, or fantasy_football.", "required": True},
{"name": "focus_guild", "description": "Target guild/build, e.g. S1, S2, S3, S6, M1, or M7+.", "required": False},
],
},
{
"name": "trace_knowledge_graph_bridge",
"description": "Trace how two concepts, specimens, or guilds connect across the 13 Multi-Build Flex Singularities and 333/666/777 attractors in the Encyclopedia Knowledge Graph.",
"arguments": [
{"name": "start_query", "description": "Starting node query (e.g. 'Blackwell' or '125').", "required": True},
{"name": "target_query", "description": "Target node query (e.g. 'Anthropic' or 'S6').", "required": True},
],
},
{
"name": "pokedex_field_scanner_card",
"description": "Format a Technocapital Singularity specimen or emergent M7+ coordinate hub as a Gen IV INFO Pokedex field-scanner card.",
"arguments": [
{"name": "specimen_or_coord", "description": "Specimen name or integer AQ coordinate (e.g. '129' or 'M7+').", "required": True},
],
},
]
def get_mcp_prompt(name: str, arguments: dict[str, Any] | None = None) -> dict[str, Any]:
args = arguments or {}
if name == "analyze_headline_zoology":
hl = args.get("headline", "<headline>")
text = (
f"Analyze the following headline under the Technocapital Singularity Zoology framework:\n"
f"Headline: \"{hl}\"\n\n"
"Step 1: Call `hs_evaluate_aq_and_ingglish` and `hs_classify_singularity` on the core nouns, verbs, and entities in the headline.\n"
"Step 2: Check for G1 Variance-Collapse Triads (Gen 0 dispersion -> Gen 1 exact equivalence), G2 Cross-Gen Twins, and G4 Isometric Chokepoints (Δ = 0).\n"
"Step 3: Check whether both Machinic Phylum (S1-S5) and Apparatus of Capture (S6) are co-present (Double Articulation), and unlock an M1-M6 memetic subclass ONLY if the headline's observable thermodynamic state matches.\n"
"Step 4: Call `hs_search_archive_equations` to ground the analysis in verified 333/666/777 equations with 0.0% generic padding."
)
elif name == "draft_stakeholder_proposal_section":
aud = args.get("audience", "fund_manager")
fg = args.get("focus_guild", "all")
text = (
f"Draft a stakeholder analysis section for audience='{aud}' focusing on build='{fg}':\n"
f"Step 1: Call `hs_inspect_eti_tier_list` with `register='{aud}'` and `build_filter='{fg}'`.\n"
"Step 2: Omit French philosophical jargon (Deleuze, Guattari, Body without Organs, Schizoanalysis) and cite only concrete tech/finance nouns from each equivalence ring (e.g. synthetic data == asset management = 292, capital == capture = 125, ASML == asset = 81, TSMC == loss = 91).\n"
"Step 3: Ground all claims with inline [n] citations verified via `hs_verify_grounded_citations`."
)
elif name == "trace_knowledge_graph_bridge":
s_q = args.get("start_query", "125")
t_q = args.get("target_query", "193")
text = (
f"Trace the topological bridge between '{s_q}' and '{t_q}' in the Encyclopedia Knowledge Graph:\n"
f"Step 1: Call `hs_query_knowledge_graph` for '{s_q}' and for '{t_q}'.\n"
"Step 2: Identify shared AQCoordinateHub nodes, 13-Flex Pivots (292, 256, 211, 193, 183, 153, 137, 136, 133, 125, 96, 95, 91/81), and 333/666/777 repdigit attractors connecting their 1-hop ego networks."
)
elif name == "pokedex_field_scanner_card":
spec = args.get("specimen_or_coord", "129")
text = (
f"Synthesize a Gen IV INFO Pokedex field-scanner card for '{spec}':\n"
f"Step 1: Call `hs_query_knowledge_graph` with `query='{spec}'` and `hs_inspect_eti_tier_list`.\n"
"Step 2: Output the Pokedex header (Dex #, Taxon Class S1-S6 / M1-M7+, ETI Tier S+..D), the 6-stat telemetry bar (ARM, VEL, COL, CAP, PRM, RES), the G1 Variance-Collapse equation, and the 3-line field scanner entry."
)
else:
raise ValueError(f"Unknown MCP prompt: {name}")
return {
"description": f"Guided prompt for {name}",
"messages": [
{
"role": "user",
"content": {"type": "text", "text": text},
}
],
}
+134
View File
@@ -0,0 +1,134 @@
"""
hyperstitionstud_io.mcp.resources — Static & Template URN Resources for MCP Clients.
"""
from __future__ import annotations
import json
import re
from typing import Any
from hyperstitionstud_io.config import load_workspace_config
STATIC_RESOURCES: list[dict[str, str]] = [
{
"uri": "urn:io:hyperstitionstud:resource:glossary-registry",
"name": "Comprehensive Glossary & Bilingual Ledger (v1.6.0, 282 Entries)",
"mimeType": "application/json",
"description": "Canonical 282-entry Glossary & 190-specimen Bilingual Vocabulary Ledger.",
},
{
"uri": "urn:io:hyperstitionstud:resource:encyclopedia-manifest",
"name": "22-Volume PDF Encyclopedia Manifest (v1.7.0, 122 Pages)",
"mimeType": "application/json",
"description": "Manifest of the 9 Ontological Divisions (00-08) and 22 Alphabetized PDF Volumes.",
},
{
"uri": "urn:io:hyperstitionstud:resource:eti-tier-list",
"name": "Assemblage Builds Ecological Trophic Index (ETI v2.0.0) Tier List",
"mimeType": "application/json",
"description": "9 Taxon Assemblage Builds ranked S+ to D/F across 6 zoological base stats.",
},
{
"uri": "urn:io:hyperstitionstud:resource:singularity-matrix",
"name": "Technocapital Singularity Zoology Matrix (S1-S6)",
"mimeType": "application/json",
"description": "Six-Class Landian-Deleuzean Singularity Taxonomy and signature coordinate rings.",
},
{
"uri": "urn:io:hyperstitionstud:resource:memetic-registry",
"name": "State-Gated Memetic Superclass Registry (M1-M6 & Emergent M7+)",
"mimeType": "application/json",
"description": "Two-Gate state-matched memetic subclasses and M7_candidate_2026_11_28 nucleation telemetry.",
},
{
"uri": "urn:io:hyperstitionstud:resource:quantitative-anchors",
"name": "Quantitative Economic Anchors Registry",
"mimeType": "application/json",
"description": "Registered quantitative anchors ($6B Lazarus heist, $83 Anthropic IPO, 481 halted factories).",
},
{
"uri": "urn:io:hyperstitionstud:resource:knowledge-graph-summary",
"name": "Encyclopedia Knowledge Graph Summary (388 Nodes, 1,282 Edges)",
"mimeType": "application/json",
"description": "Node/edge ontology counts, top 15 AQ coordinate hubs by degree, and SHA-256 isolation receipt.",
},
]
RESOURCE_TEMPLATES: list[dict[str, str]] = [
{
"uriTemplate": "urn:io:hyperstitionstud:dossier:{dossier_number}",
"name": "Canonical Archive or Zoology Dossier by Number (01..71)",
"mimeType": "text/markdown",
"description": "Read the full Markdown text and verified 333/666/777 equations of Dossier {dossier_number} (e.g. 65..71).",
},
{
"uriTemplate": "urn:io:hyperstitionstud:schema:v1:{schema_slug}",
"name": "Workspace Offline URN JSON Schema (v1)",
"mimeType": "application/schema+json",
"description": "Read a v1 JSON Schema contract (e.g. glossary-registry, encyclopedia-graph, learn-progress-state).",
},
]
def read_mcp_resource(uri: str) -> dict[str, Any]:
cfg = load_workspace_config()
static_map = {
"urn:io:hyperstitionstud:resource:glossary-registry": cfg.zoology_dir / "taxonomy" / "glossary-registry.json",
"urn:io:hyperstitionstud:resource:encyclopedia-manifest": cfg.zoology_dir / "encyclopedia" / "encyclopedia-manifest.json",
"urn:io:hyperstitionstud:resource:eti-tier-list": cfg.zoology_dir / "taxonomy" / "assemblage-builds-tier-list.json",
"urn:io:hyperstitionstud:resource:singularity-matrix": cfg.zoology_dir / "taxonomy" / "singularity-zoology-matrix.json",
"urn:io:hyperstitionstud:resource:memetic-registry": cfg.zoology_dir / "taxonomy" / "memetic-superclass-registry.json",
"urn:io:hyperstitionstud:resource:quantitative-anchors": cfg.zoology_dir / "taxonomy" / "quantitative-economic-anchors.json",
}
if uri in static_map:
p = static_map[uri]
return {
"contents": [
{"uri": uri, "mimeType": "application/json", "text": p.read_text(encoding="utf-8")}
]
}
if uri == "urn:io:hyperstitionstud:resource:knowledge-graph-summary":
kg = json.loads((cfg.knowledge_graph_dir / "encyclopedia-graph.json").read_text(encoding="utf-8"))
summary = {
"version": kg.get("version"),
"namespace_urn": kg.get("namespace_urn"),
"counts": kg.get("counts"),
"isolation_verified": kg.get("isolation_verified"),
"top_coordinate_hubs_by_degree": kg.get("top_coordinate_hubs_by_degree"),
}
return {
"contents": [
{"uri": uri, "mimeType": "application/json", "text": json.dumps(summary, indent=2)}
]
}
m_dos = re.match(r"^urn:io:hyperstitionstud:dossier:(\d+)$", uri)
if m_dos:
num = int(m_dos.group(1))
prefix = f"{num:02d}-"
for d_dir in (cfg.zoology_dir / "dossiers", cfg.archive_dir / "ingglish-aq-archive"):
if d_dir.is_dir():
matches = sorted(d_dir.glob(f"{prefix}*.md"))
if matches:
return {
"contents": [
{"uri": uri, "mimeType": "text/markdown", "text": matches[0].read_text(encoding="utf-8")}
]
}
raise ValueError(f"No dossier found matching number {num:02d}")
m_sch = re.match(r"^urn:io:hyperstitionstud:schema:v1:([a-z0-9-]+)$", uri)
if m_sch:
slug = m_sch.group(1)
sp = cfg.core_dir / "schemas" / "v1" / f"{slug}.schema.json"
if sp.is_file():
return {
"contents": [
{"uri": uri, "mimeType": "application/schema+json", "text": sp.read_text(encoding="utf-8")}
]
}
raise ValueError(f"Unknown schema slug: {slug}")
raise ValueError(f"Unknown MCP resource URI: {uri}")
+246
View File
@@ -0,0 +1,246 @@
#!/usr/bin/env python3
"""
hyperstitionstud_io.mcp.server — Dual-Transport JSON-RPC 2.0 MCP Server (`hs-mcp`).
Supports:
1. `--transport stdio` (default): newline-delimited JSON-RPC 2.0 over stdin/stdout.
2. `--transport http`: stateless Streamable HTTP JSON-RPC 2.0 on `GET /mcp` and `POST /mcp`.
Enforces ReadOnlyIsolationGuard on every tool call so protected upstream registries never mutate.
"""
from __future__ import annotations
import argparse
import json
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
from typing import Any
_SRC_DIR = Path(__file__).resolve().parents[2]
if _SRC_DIR.is_dir() and str(_SRC_DIR) not in sys.path:
sys.path.insert(0, str(_SRC_DIR))
from hyperstitionstud_io.config import load_workspace_config # noqa: E402
from hyperstitionstud_io.glossary import ReadOnlyIsolationGuard # noqa: E402
from hyperstitionstud_io.mcp.prompts import MCP_PROMPTS, get_mcp_prompt # noqa: E402
from hyperstitionstud_io.mcp.resources import ( # noqa: E402
RESOURCE_TEMPLATES,
STATIC_RESOURCES,
read_mcp_resource,
)
from hyperstitionstud_io.mcp.tools import MCP_TOOLS_SCHEMA, call_mcp_tool # noqa: E402
SERVER_INFO = {
"name": "hyperstitionstudio-mcp",
"version": "2.0.0",
"namespace_urn": "urn:io:hyperstitionstud:mcp:2.0.0",
}
def dispatch_jsonrpc(req: dict[str, Any]) -> dict[str, Any] | None:
"""
Process a single JSON-RPC 2.0 request or notification and return the JSON-RPC 2.0 response
(or None for notifications without an 'id').
"""
method = req.get("method", "")
req_id = req.get("id")
params = req.get("params") or {}
if method.startswith("notifications/"):
return None
cfg = load_workspace_config()
try:
with ReadOnlyIsolationGuard(cfg.read_only_files):
if method == "initialize":
client_proto = params.get("protocolVersion", "2024-11-05")
proto = client_proto if client_proto in ("2025-03-26", "2024-11-05") else "2024-11-05"
result: dict[str, Any] = {
"protocolVersion": proto,
"capabilities": {
"tools": {"listChanged": False},
"resources": {"subscribe": False, "listChanged": False},
"prompts": {"listChanged": False},
},
"serverInfo": SERVER_INFO,
}
elif method == "ping":
result = {}
elif method == "tools/list":
result = {"tools": MCP_TOOLS_SCHEMA}
elif method == "tools/call":
t_name = str(params.get("name", ""))
t_args = params.get("arguments") or {}
out = call_mcp_tool(t_name, t_args)
result = {
"content": [
{
"type": "text",
"text": json.dumps(out, indent=2, ensure_ascii=False),
}
],
"isError": False,
}
elif method == "resources/list":
result = {"resources": STATIC_RESOURCES}
elif method == "resources/templates/list":
result = {"resourceTemplates": RESOURCE_TEMPLATES}
elif method == "resources/read":
uri = str(params.get("uri", ""))
result = read_mcp_resource(uri)
elif method == "prompts/list":
result = {"prompts": MCP_PROMPTS}
elif method == "prompts/get":
p_name = str(params.get("name", ""))
p_args = params.get("arguments") or {}
result = get_mcp_prompt(p_name, p_args)
else:
return {
"jsonrpc": "2.0",
"id": req_id,
"error": {"code": -32601, "message": f"Method not found: {method}"},
}
except Exception as exc:
if method == "tools/call":
return {
"jsonrpc": "2.0",
"id": req_id,
"result": {
"content": [{"type": "text", "text": json.dumps({"error": str(exc)})}],
"isError": True,
},
}
return {
"jsonrpc": "2.0",
"id": req_id,
"error": {"code": -32602, "message": str(exc)},
}
return {"jsonrpc": "2.0", "id": req_id, "result": result}
def run_stdio_server() -> int:
for raw_line in sys.stdin:
line = raw_line.strip()
if not line:
continue
try:
req = json.loads(line)
except json.JSONDecodeError as exc:
err_resp = {
"jsonrpc": "2.0",
"id": None,
"error": {"code": -32700, "message": f"Parse error: {exc}"},
}
sys.stdout.write(json.dumps(err_resp) + "\n")
sys.stdout.flush()
continue
resp = dispatch_jsonrpc(req)
if resp is not None:
sys.stdout.write(json.dumps(resp, ensure_ascii=False) + "\n")
sys.stdout.flush()
return 0
class _MCPHTTPHandler(BaseHTTPRequestHandler):
def log_message(self, format: str, *args: Any) -> None:
return
def _send_json(self, status: int, payload: Any) -> None:
body = (json.dumps(payload, indent=2, ensure_ascii=False) + "\n").encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
self.send_header("Access-Control-Allow-Headers", "Content-Type")
self.end_headers()
self.wfile.write(body)
def do_OPTIONS(self) -> None:
self.send_response(204)
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
self.send_header("Access-Control-Allow-Headers", "Content-Type")
self.end_headers()
def do_GET(self) -> None:
manifest = {
"serverInfo": SERVER_INFO,
"protocols": ["2025-03-26", "2024-11-05"],
"transport": "streamable-http",
"endpoints": {"jsonrpc_post": "/mcp", "manifest_get": "/mcp"},
"counts": {
"tools": len(MCP_TOOLS_SCHEMA),
"static_resources": len(STATIC_RESOURCES),
"resource_templates": len(RESOURCE_TEMPLATES),
"prompts": len(MCP_PROMPTS),
},
"tools": [t["name"] for t in MCP_TOOLS_SCHEMA],
"resources": [r["uri"] for r in STATIC_RESOURCES],
"prompts": [p["name"] for p in MCP_PROMPTS],
}
self._send_json(200, manifest)
def do_POST(self) -> None:
length = int(self.headers.get("Content-Length", "0"))
if length <= 0 or length > 65536:
self._send_json(400, {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "Invalid content length"}})
return
raw = self.rfile.read(length).decode("utf-8")
try:
req = json.loads(raw)
except json.JSONDecodeError as exc:
self._send_json(400, {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": str(exc)}})
return
resp = dispatch_jsonrpc(req)
if resp is None:
self.send_response(202)
self.end_headers()
return
self._send_json(200, resp)
def run_http_server(host: str, port: int) -> int:
srv = HTTPServer((host, port), _MCPHTTPHandler)
print(f"[hs-mcp] Serving stateless read-only MCP HTTP endpoint on http://{host}:{port}/mcp", flush=True)
try:
srv.serve_forever()
except KeyboardInterrupt:
pass
finally:
srv.server_close()
return 0
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(prog="hs-mcp", description="Model Context Protocol (MCP) Server for hyperstitionstud.io.")
ap.add_argument("--transport", choices=["stdio", "http"], default="stdio", help="Transport mode (default: stdio).")
ap.add_argument("--host", default="127.0.0.1", help="Bind address for HTTP transport (default: 127.0.0.1).")
ap.add_argument("--port", type=int, default=8095, help="Bind port for HTTP transport (default: 8095).")
ap.add_argument("--dump-manifest", action="store_true", help="Print MCP capability manifest as JSON and exit.")
args = ap.parse_args(argv)
if args.dump_manifest:
print(
json.dumps(
{
"serverInfo": SERVER_INFO,
"tools": MCP_TOOLS_SCHEMA,
"resources": STATIC_RESOURCES,
"resourceTemplates": RESOURCE_TEMPLATES,
"prompts": MCP_PROMPTS,
},
indent=2,
)
)
return 0
if args.transport == "http":
return run_http_server(args.host, args.port)
return run_stdio_server()
if __name__ == "__main__":
raise SystemExit(main())
+458
View File
@@ -0,0 +1,458 @@
"""
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}")