""" hyperstitionstud_io.mcp.rest — Unified Stateless REST API & OpenAPI 3.1.0 Adapter (`/api/v1/*`). Exposes all tools in `MCP_TOOLS_SCHEMA`, static resources in `STATIC_RESOURCES`, templates in `RESOURCE_TEMPLATES`, and guided prompts in `MCP_PROMPTS` over standard HTTP GET/POST REST endpoints on the existing `hs-mcp` (`127.0.0.1:8095`) server, guarded by `ReadOnlyIsolationGuard`. """ from __future__ import annotations import json import re import time import urllib.parse from typing import Any from hyperstitionstud_io import __version__ as CURRENT_VERSION from hyperstitionstud_io.config import load_workspace_config from hyperstitionstud_io.db.sqlite_meta import record_api_telemetry from hyperstitionstud_io.glossary import ReadOnlyIsolationGuard from hyperstitionstud_io.mcp.prompts import MCP_PROMPTS, get_mcp_prompt from hyperstitionstud_io.mcp.resources import ( RESOURCE_TEMPLATES, STATIC_RESOURCES, read_mcp_resource, ) from hyperstitionstud_io.mcp.tools import MCP_TOOLS_SCHEMA, call_mcp_tool # Domain-specific REST aliases mapped to (tool_name, default_arg_overrides) REST_DOMAIN_ALIASES: dict[str, str] = { "/api/v1/doctor": "hs_run_doctor_and_audit", "/api/v1/ciphers/evaluate": "hs_evaluate_aq_and_ingglish", "/api/v1/zoology/classify": "hs_classify_singularity", "/api/v1/zoology/tier-list": "hs_inspect_eti_tier_list", "/api/v1/zoology/anchor-revision": "hs_simulate_anchor_revision", "/api/v1/graph/query": "hs_query_knowledge_graph", "/api/v1/glossary/search": "hs_search_glossary_encyclopedia", "/api/v1/archive/equations": "hs_search_archive_equations", "/api/v1/quant/harvest": "hs_scan_financial_quant_harvest", "/api/v1/quant/timeseries": "hs_inspect_quant_timeseries", "/api/v1/ipld/cid": "hs_compute_ipld_dag_json_cid", "/api/v1/citations/verify": "hs_verify_grounded_citations", } def _find_tool_schema(tool_name: str) -> dict[str, Any] | None: for t in MCP_TOOLS_SCHEMA: if t["name"] == tool_name: return t return None def coerce_query_params(query_str: str, input_schema: dict[str, Any] | None = None) -> tuple[dict[str, Any], bool]: """ Parse URL query string and coerce values according to `input_schema["properties"]`. Returns `(coerced_args, unwrap_raw_flag)`. """ parsed = urllib.parse.parse_qs(query_str, keep_blank_values=False) props = ((input_schema or {}).get("properties") or {}) out: dict[str, Any] = {} unwrap = False for k, vals in parsed.items(): if k in ("raw", "unwrap") and vals and vals[-1].lower() in ("1", "true", "yes"): unwrap = True continue p_spec = props.get(k) or {} p_type = p_spec.get("type", "string") if p_type == "array": arr: list[str] = [] for v in vals: arr.extend(x.strip() for x in v.split(",") if x.strip()) out[k] = arr elif p_type == "integer": out[k] = int(vals[-1]) elif p_type == "number": out[k] = float(vals[-1]) elif p_type == "boolean": out[k] = vals[-1].lower() in ("1", "true", "yes") else: out[k] = vals[-1] return out, unwrap def build_openapi_v1_spec() -> dict[str, Any]: """ Dynamically compile an OpenAPI 3.1.0 specification from MCP_TOOLS_SCHEMA, STATIC_RESOURCES, RESOURCE_TEMPLATES, and MCP_PROMPTS. """ paths: dict[str, Any] = { "/api/v1/status": { "get": { "operationId": "getStatus", "summary": "Server status, endpoint directory, and ReadOnlyIsolationGuard verification.", "responses": {"200": {"description": "OK"}}, } }, "/api/v1/openapi.json": { "get": { "operationId": "getOpenApiSpec", "summary": "OpenAPI 3.1.0 schema for all REST and MCP capabilities.", "responses": {"200": {"description": "OK"}}, } }, "/api/v1/tools": { "get": { "operationId": "listTools", "summary": "List all registered MCP/REST tools and their JSON inputSchemas.", "responses": {"200": {"description": "OK"}}, } }, "/api/v1/resources": { "get": { "operationId": "listResources", "summary": "List all static URN resources and URI templates.", "responses": {"200": {"description": "OK"}}, } }, "/api/v1/prompts": { "get": { "operationId": "listPrompts", "summary": "List all guided workflow prompt templates.", "responses": {"200": {"description": "OK"}}, } }, } for tool in MCP_TOOLS_SCHEMA: t_name = tool["name"] schema = tool.get("inputSchema", {"type": "object"}) op_spec = { "summary": tool.get("description", ""), "responses": {"200": {"description": "Successful tool execution"}}, } paths[f"/api/v1/tools/{t_name}"] = { "get": {"operationId": f"get_{t_name}", **op_spec}, "post": { "operationId": f"post_{t_name}", "requestBody": {"content": {"application/json": {"schema": schema}}}, **op_spec, }, } for alias_path, t_name in REST_DOMAIN_ALIASES.items(): tool = _find_tool_schema(t_name) or {} paths[alias_path] = { "get": { "operationId": f"alias_get_{t_name}", "summary": f"REST alias for {t_name}: {tool.get('description', '')}", "responses": {"200": {"description": "OK"}}, }, "post": { "operationId": f"alias_post_{t_name}", "summary": f"REST alias for {t_name}", "responses": {"200": {"description": "OK"}}, }, } return { "openapi": "3.1.0", "info": { "title": "hyperstitionstud.io Unified REST & MCP API", "version": CURRENT_VERSION, "description": "Stateless read-only REST API (/api/v1/*) and MCP Streamable HTTP (/mcp) interface.", }, "servers": [{"url": "/"}], "paths": paths, } def _wrap_response(endpoint: str, data: Any, unwrap: bool = False, tool_name: str | None = None) -> dict[str, Any]: if unwrap and isinstance(data, dict): return data resp: dict[str, Any] = { "ok": True, "version": CURRENT_VERSION, "endpoint": endpoint, } if tool_name: resp["tool"] = tool_name resp["data"] = data resp["isolation_verified"] = True return resp def _error_response(status: int, code: str, message: str) -> tuple[int, str, dict[str, Any]]: return ( status, "application/json; charset=utf-8", { "ok": False, "version": CURRENT_VERSION, "error": {"code": code, "status": status, "message": message}, }, ) def _normalize_rest_endpoint_pattern(path: str) -> str: if re.match(r"^/api/v1/graph/nodes/.+$", path): return "/api/v1/graph/nodes/{node_id}" if re.match(r"^/api/v1/quant/instruments/[^/]+$", path): return "/api/v1/quant/instruments/{symbol}" if re.match(r"^/api/v1/zoology/pokedex/[^/]+$", path): return "/api/v1/zoology/pokedex/{symbol}" if re.match(r"^/api/v1/resources/[a-z0-9-]+$", path): return "/api/v1/resources/{slug}" if re.match(r"^/api/v1/dossiers/\d+$", path): return "/api/v1/dossiers/{number}" if re.match(r"^/api/v1/schemas/[a-z0-9-]+$", path): return "/api/v1/schemas/{schema_slug}" if re.match(r"^/api/v1/prompts/[a-z0-9_]+$", path): return "/api/v1/prompts/{prompt_name}" return path def _dispatch_rest_v1_inner( method: str, path: str, query_str: str, body_bytes: bytes = b"", ) -> tuple[int, str, Any]: cfg = load_workspace_config() try: with ReadOnlyIsolationGuard(cfg.read_only_files) as guard: # 1. Discovery & OpenAPI if path in ("/api/v1", "/api/v1/status") and method == "GET": _, unwrap = coerce_query_params(query_str) status_data = { "name": "hyperstitionstudio-rest-api", "version": CURRENT_VERSION, "namespace_urn": f"urn:io:hyperstitionstud:api:v1:{CURRENT_VERSION}", "protocols": {"rest_v1": "/api/v1", "openapi_3_1": "/api/v1/openapi.json", "mcp_jsonrpc": "/mcp"}, "counts": { "tools": len(MCP_TOOLS_SCHEMA), "static_resources": len(STATIC_RESOURCES), "resource_templates": len(RESOURCE_TEMPLATES), "prompts": len(MCP_PROMPTS), "domain_aliases": len(REST_DOMAIN_ALIASES), }, "domain_endpoints": sorted(REST_DOMAIN_ALIASES.keys()), "isolation_receipt": guard.audit_receipt(), } return 200, "application/json; charset=utf-8", _wrap_response(path, status_data, unwrap=unwrap) if path == "/api/v1/openapi.json" and method == "GET": return 200, "application/json; charset=utf-8", build_openapi_v1_spec() if path == "/api/v1/tools" and method == "GET": _, unwrap = coerce_query_params(query_str) return 200, "application/json; charset=utf-8", _wrap_response(path, {"tools": MCP_TOOLS_SCHEMA}, unwrap=unwrap) if path == "/api/v1/resources" and method == "GET": _, unwrap = coerce_query_params(query_str) return 200, "application/json; charset=utf-8", _wrap_response( path, {"resources": STATIC_RESOURCES, "resourceTemplates": RESOURCE_TEMPLATES}, unwrap=unwrap, ) if path == "/api/v1/prompts" and method == "GET": _, unwrap = coerce_query_params(query_str) return 200, "application/json; charset=utf-8", _wrap_response(path, {"prompts": MCP_PROMPTS}, unwrap=unwrap) # 2. Parameterized Path Shorthands: # - /api/v1/graph/nodes/{node_id} # - /api/v1/quant/instruments/{symbol} # - /api/v1/zoology/pokedex/{symbol} # - /api/v1/resources/{slug} # - /api/v1/dossiers/{number} # - /api/v1/schemas/{schema_slug} # - /api/v1/prompts/{prompt_name} m_node = re.match(r"^/api/v1/graph/nodes/(.+)$", path) if m_node and method == "GET": node_id = urllib.parse.unquote(m_node.group(1)) q_args, unwrap = coerce_query_params(query_str, _find_tool_schema("hs_query_knowledge_graph")["inputSchema"]) q_args["query"] = node_id res = call_mcp_tool("hs_query_knowledge_graph", q_args) return 200, "application/json; charset=utf-8", _wrap_response(path, res, unwrap=unwrap, tool_name="hs_query_knowledge_graph") m_inst = re.match(r"^/api/v1/quant/instruments/([^/]+)$", path) if m_inst and method == "GET": sym = urllib.parse.unquote(m_inst.group(1)) q_args, unwrap = coerce_query_params(query_str, _find_tool_schema("hs_scan_financial_quant_harvest")["inputSchema"]) q_args["symbol_filter"] = sym res = call_mcp_tool("hs_scan_financial_quant_harvest", q_args) return 200, "application/json; charset=utf-8", _wrap_response(path, res, unwrap=unwrap, tool_name="hs_scan_financial_quant_harvest") m_pkx = re.match(r"^/api/v1/zoology/pokedex/([^/]+)$", path) if m_pkx and method == "GET": sym = urllib.parse.unquote(m_pkx.group(1)) q_args, unwrap = coerce_query_params(query_str, _find_tool_schema("hs_inspect_quant_timeseries")["inputSchema"]) q_args["symbol"] = sym q_args["lens"] = "pokedex_scanner" res = call_mcp_tool("hs_inspect_quant_timeseries", q_args) return 200, "application/json; charset=utf-8", _wrap_response(path, res, unwrap=unwrap, tool_name="hs_inspect_quant_timeseries") m_res = re.match(r"^/api/v1/resources/([a-z0-9-]+)$", path) if m_res and method == "GET": slug = m_res.group(1) _, unwrap = coerce_query_params(query_str) uri = f"urn:io:hyperstitionstud:resource:{slug}" r_out = read_mcp_resource(uri) parsed_json = json.loads(r_out["contents"][0]["text"]) return 200, "application/json; charset=utf-8", _wrap_response(path, parsed_json, unwrap=unwrap) m_dos = re.match(r"^/api/v1/dossiers/(\d+)$", path) if m_dos and method == "GET": num = int(m_dos.group(1)) q_args, unwrap = coerce_query_params(query_str) uri = f"urn:io:hyperstitionstud:dossier:{num}" r_out = read_mcp_resource(uri) md_text = r_out["contents"][0]["text"] if q_args.get("format") == "raw": return 200, "text/markdown; charset=utf-8", md_text dos_payload: dict[str, Any] = { "dossier_number": num, "uri": uri, "mime_type": "text/markdown", "markdown": md_text, } hl_q = str(q_args.get("highlight", "")).strip() if hl_q: hl_low = hl_q.lower() lines = md_text.splitlines() matched_passages: list[dict[str, Any]] = [] for l_idx, ln in enumerate(lines): if hl_low in ln.lower(): start_i = max(0, l_idx - 1) end_i = min(len(lines), l_idx + 2) matched_passages.append({ "line_number": l_idx + 1, "line": ln, "context": "\n".join(lines[start_i:end_i]), }) dos_payload["highlight_query"] = hl_q dos_payload["match_count"] = len(matched_passages) dos_payload["matched_passages"] = matched_passages[:25] return 200, "application/json; charset=utf-8", _wrap_response( path, dos_payload, unwrap=unwrap, ) m_sch = re.match(r"^/api/v1/schemas/([a-z0-9-]+)$", path) if m_sch and method == "GET": slug = m_sch.group(1) uri = f"urn:io:hyperstitionstud:schema:v1:{slug}" r_out = read_mcp_resource(uri) return 200, "application/schema+json; charset=utf-8", json.loads(r_out["contents"][0]["text"]) m_prm = re.match(r"^/api/v1/prompts/([a-z0-9_]+)$", path) if m_prm: p_name = m_prm.group(1) p_args, unwrap = coerce_query_params(query_str) if method == "POST" and body_bytes: p_args.update(json.loads(body_bytes.decode("utf-8"))) p_out = get_mcp_prompt(p_name, p_args) return 200, "application/json; charset=utf-8", _wrap_response(path, p_out, unwrap=unwrap) # 3. Generic /api/v1/tools/{tool_name} or Domain Alias Execution target_tool: str | None = None if path in REST_DOMAIN_ALIASES: target_tool = REST_DOMAIN_ALIASES[path] else: m_tool = re.match(r"^/api/v1/tools/([a-z0-9_]+)$", path) if m_tool: target_tool = m_tool.group(1) if target_tool: t_schema = _find_tool_schema(target_tool) if t_schema is None: return _error_response(404, "UNKNOWN_TOOL", f"Unknown tool: {target_tool}") in_schema = t_schema.get("inputSchema") or {} t_args, unwrap = coerce_query_params(query_str, in_schema) if method == "POST" and body_bytes: body_obj = json.loads(body_bytes.decode("utf-8")) if isinstance(body_obj, dict): if body_obj.pop("raw", False) or body_obj.pop("unwrap", False): unwrap = True t_args.update(body_obj) required_fields = in_schema.get("required") or [] missing = [req_f for req_f in required_fields if req_f not in t_args] if missing: return _error_response( 422, "MISSING_REQUIRED_PARAMETER", f"Missing required parameter(s) {missing} for tool '{target_tool}'.", ) out = call_mcp_tool(target_tool, t_args) return 200, "application/json; charset=utf-8", _wrap_response(path, out, unwrap=unwrap, tool_name=target_tool) return _error_response(404, "ENDPOINT_NOT_FOUND", f"Unknown REST API v1 endpoint: {path}") except ValueError as exc: msg = str(exc) status = 404 if ("Unknown" in msg or "No dossier" in msg) else 422 return _error_response(status, "VALIDATION_ERROR", msg) except Exception as exc: return _error_response(500, "INTERNAL_ERROR", str(exc)) def compute_response_etag(payload: Any) -> str: """ Compute a deterministic strong HTTP ETag (`""`) for any REST/MCP response payload. """ import hashlib from hyperstitionstud_io.ipld import compute_dag_json_cidv1 if isinstance(payload, dict): cid_top = (payload.get("ipld_dag_json_cidv1") or {}).get("/") if isinstance(cid_top, str) and cid_top: return f'"{cid_top}"' data_sub = payload.get("data") if isinstance(data_sub, dict): cid_sub = (data_sub.get("ipld_dag_json_cidv1") or {}).get("/") if isinstance(cid_sub, str) and cid_sub: return f'"{cid_sub}"' try: return f'"{compute_dag_json_cidv1(payload)}"' except Exception: pass raw_bytes = ( payload.encode("utf-8") if isinstance(payload, str) else json.dumps(payload, sort_keys=True, ensure_ascii=False).encode("utf-8") ) return f'"sha256-{hashlib.sha256(raw_bytes).hexdigest()[:40]}"' def matches_if_none_match(if_none_match: str | None, etag: str) -> bool: """ Evaluate RFC 9110 `If-None-Match` header against a strong or weak ETag. """ if not if_none_match or not etag: return False inm_raw = if_none_match.strip() if inm_raw == "*": return True target_norm = etag.strip() if target_norm.startswith("W/"): target_norm = target_norm[2:].strip() for part in inm_raw.split(","): cand = part.strip() if cand.startswith("W/"): cand = cand[2:].strip() if cand == target_norm or cand.strip('"') == target_norm.strip('"'): return True return False def dispatch_rest_v1( method: str, raw_path: str, body_bytes: bytes = b"", if_none_match: str | None = None, ) -> tuple[int, str, Any]: """ Dispatch an HTTP GET or POST request under `/api/v1/*` and automatically record the request metadata and latency in the SQLite REST API metadata database (`api-telemetry.db`). When `if_none_match` matches the deterministic response ETag on a `GET` `200` response, records `status_code=304` (`304 Not Modified`) and returns `(304, content_type, "")`. Returns `(http_status_code, content_type, response_payload_or_text)`. """ parsed_url = urllib.parse.urlsplit(raw_path) path = parsed_url.path.rstrip("/") or "/api/v1" query_str = parsed_url.query t0_ns = time.perf_counter_ns() status, ctype, payload = _dispatch_rest_v1_inner(method, path, query_str, body_bytes) if status == 200 and method.upper() == "GET" and if_none_match: etag = compute_response_etag(payload) if matches_if_none_match(if_none_match, etag): status = 304 payload = "" elapsed_us = max(1, (time.perf_counter_ns() - t0_ns) // 1000) record_api_telemetry( protocol="rest_v1", method=method.upper(), endpoint_pattern=_normalize_rest_endpoint_pattern(path), status_code=status, latency_us=elapsed_us, isolation_ok=True, ) return status, ctype, payload