Files
encyclopedia-knowledge-graph/docs/archive/PLAN-MCP-REST-API-ADAPTER.md
T

15 KiB
Raw Blame History

Plan: Unified Stateless REST API & OpenAPI 3.1 Adapter (/api/v1/*) for the hyperstitionstud.io MCP Server (v2.0.17)

  • Document ID: PLAN-MCP-REST-API-ADAPTER (v2.0.17)
  • Target Module: /workspace/hyperstitionstudio-core/src/hyperstitionstud_io/mcp/server.py & /workspace/hyperstitionstudio-core/src/hyperstitionstud_io/mcp/rest.py
  • Public HTTPS & Local Routes:
    • REST API v1 Base URL: https://hyperstitionstud.io/api/v1/* (and http://127.0.0.1:8095/api/v1/*)
    • OpenAPI 3.1.0 Specification: https://hyperstitionstud.io/api/v1/openapi.json (auto-compiled at runtime from MCP_TOOLS_SCHEMA, STATIC_RESOURCES, RESOURCE_TEMPLATES, and MCP_PROMPTS)
    • Existing JSON-RPC 2.0 MCP Endpoint (100% Preserved): https://hyperstitionstud.io/mcp (POST /mcp & GET /mcp)
  • Core Architectural Principle: Single Daemon, Single Port (127.0.0.1:8095), Zero Code Duplication. The existing _MCPHTTPHandler inside hyperstitionstud_io.mcp.server (hyperstition-mcp.service) serves both MCP JSON-RPC 2.0 clients at /mcp and standard HTTP/REST clients (curl, browser fetch(), Python requests, Pandas/R notebooks, TradingView webhooks, OpenAI/Anthropic function-calling) at /api/v1/*, wrapping every execution inside ReadOnlyIsolationGuard and returning unwrapped native JSON with an embedded cryptographic isolation_receipt.

1. Why Non-MCP Clients Need a First-Class REST Adapter (/api/v1/*)

While Model Context Protocol (MCP) clients communicate via stateful stdio pipes or JSON-RPC 2.0 envelopes ({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "...", "arguments": {...}}}) where tool results are double-serialized as stringified JSON inside result.content[0].text, standard non-MCP consumers face three unnecessary friction points:

  1. Double-Encoded JSON Unwrapping Overhead: In MCP tools/call, the payload returned by call_mcp_tool() is serialized into a string inside {"result": {"content": [{"type": "text", "text": "{...}"}]}}. Standard HTTP clients (curl | jq, browser fetch(), Pandas pd.read_json(), quantitative scripts) expect a single-pass parsed JSON response (application/json) with standard HTTP status codes (200 OK, 400 Bad Request, 404 Not Found, 405 Method Not Allowed, 422 Unprocessable Entity).
  2. GET Query-String Addressability & HTTP Edge Caching: Read-only queries—such as looking up node 125 in the Knowledge Graph, fetching NVDA from the closing-bell financial harvest, or reading Dossier 65—should be directly addressable via idempotent GET URLs (GET /api/v1/quant/harvest?symbol=NVDA or GET /api/v1/graph/nodes/aq:125) that work in any browser address bar without constructing a POST body.
  3. OpenAPI 3.1.0 Discovery (openapi.json): Non-MCP agent frameworks (OpenAI Actions, LangChain OpenAPI toolkits, Postman, Insomnia, Swagger UI) ingest standard OpenAPI 3.1.0 schemas rather than MCP tools/list JSON-RPC handshakes.

2. Unified Dual-Protocol Architecture (Caddy :443 -> hs-mcp 127.0.0.1:8095)

No second background daemon or extra systemd service is needed. Caddy routes both /mcp* and /api/v1* to the same stateless, ProtectSystem=strict hyperstition-mcp.service process on 127.0.0.1:8095:

+---------------------------------------------------------------------------------------------------+
| CLIENT LAYER                                                                                      |
|  • MCP Clients (Hermes, Claude, Cursor) -----> POST /mcp (JSON-RPC 2.0 Envelope)                  |
|  • Non-MCP Clients (curl, JS fetch, Pandas, -> GET / POST /api/v1/* (Native REST JSON + OpenAPI)  |
|    OpenAI Actions, Quant Notebooks, Browser)                                                      |
+---------------------------------------------------+-----------------------------------------------+
                                                    |
                                                    v
+---------------------------------------------------------------------------------------------------+
| CADDY 2 REVERSE PROXY (`/etc/caddy/Caddyfile` on `hyperstitionstud.io`)                           |
|   @api_and_mcp path /mcp /mcp/* /api/v1 /api/v1/*                                                 |
|   handle @api_and_mcp { reverse_proxy 127.0.0.1:8095 }                                            |
+---------------------------------------------------+-----------------------------------------------+
                                                    |
                                                    v
+---------------------------------------------------------------------------------------------------+
| SINGLE STATELESS PYTHON DAEMON (`hyperstitionstud_io.mcp.server` • `127.0.0.1:8095`)              |
|  • Enforces `ReadOnlyIsolationGuard` (pre/post SHA-256 verification of upstream registries)       |
|  • Routes `/mcp`      -> `dispatch_jsonrpc()` (MCP 2025-03-26 / 2024-11-05 JSON-RPC 2.0)          |
|  • Routes `/api/v1/*` -> `dispatch_rest_v1()` (Unwrapped REST JSON + Query-Param Coercion)        |
+---------------------------------------------------------------------------------------------------+

3. Complete /api/v1/* REST Endpoint Specification

Every capability in hyperstitionstud_io.mcp (11 tools, 7 static resources, 2 resource templates, and 4 guided prompts) is exposed through both a generic 1-to-1 reflection endpoint (/api/v1/tools/<tool_name>) and ergonomic resource-oriented REST aliases:

3.1 Discovery, Health & OpenAPI 3.1 Endpoints

HTTP Method & Path Description Underlying Function
GET /api/v1 or GET /api/v1/status Server version (v2.0.17), URN namespace, endpoint directory, tool/resource/prompt counts, and live ReadOnlyIsolationGuard SHA-256 status. SERVER_INFO + guard.audit_receipt()
GET /api/v1/openapi.json Full OpenAPI 3.1.0 schema dynamically compiled from MCP_TOOLS_SCHEMA, STATIC_RESOURCES, RESOURCE_TEMPLATES, and MCP_PROMPTS. build_openapi_v1_spec()
GET /api/v1/doctor Run hs-doctor environment, font, CMUdict, and SHA-256 isolation diagnostics. hs_run_doctor_and_audit

3.2 Generic 1-to-1 Tool Execution Endpoints (Supports Both GET Query Params & POST JSON Body)

Any existing or future tool registered in MCP_TOOLS_SCHEMA is automatically callable at /api/v1/tools/{tool_name} with zero manual routing code:

HTTP Method & Path Query / Body Parameters Behavior & Type Coercion
GET /api/v1/tools None Returns the list of all 11 tool definitions and their JSON Schemas (MCP_TOOLS_SCHEMA).
POST /api/v1/tools/{tool_name} JSON object matching the tool's inputSchema (e.g. {"terms": ["Nvidia", "Anthropic"], "quant_mode": "spoken"}). Validates required fields against inputSchema, executes call_mcp_tool(tool_name, body), and returns native JSON.
GET /api/v1/tools/{tool_name}?... URL query parameters (e.g. ?symbol_filter=NVDA&harvest_mode=us-closing-bell or ?terms=Nvidia,Anthropic). Automatically coerces query strings using the tool's inputSchema ("integer" -> int, "boolean" -> bool, "array" -> comma-separated or repeated param) and executes call_mcp_tool().

3.3 Ergonomic Domain-Specific REST Endpoints (Ciphers, Zoology, Graph, Quant, IPLD & Citations)

For clean integration with /quant/, /learn/, /graph/, and external scripts, the REST adapter maps domain nouns directly onto the 11 MCP tools:

Domain HTTP Method & Path Query / JSON Parameters Mapped MCP Tool
Ciphers & Phonetics GET or POST /api/v1/ciphers/evaluate terms (array or comma-list), quant_mode (digit|off|spoken|dual) hs_evaluate_aq_and_ingglish
Singularity Zoology GET or POST /api/v1/zoology/classify terms (array or comma-list), headline_text (optional string) hs_classify_singularity
ETI Tier List GET /api/v1/zoology/tier-list ?build_filter=all&register=academic|fund_manager|corporate_board|fantasy_football hs_inspect_eti_tier_list
Anchor Revisions GET or POST /api/v1/zoology/anchor-revision anchor_id, new_digit_str, new_spoken_eng hs_simulate_anchor_revision
Knowledge Graph GET /api/v1/graph/query ?query=125&include_neighbors=true (also GET /api/v1/graph/nodes/{node_id}) hs_query_knowledge_graph
Glossary & Encyclopedia GET /api/v1/glossary/search ?query=monopoly&guild_filter=S6&limit=15 hs_search_glossary_encyclopedia
Archive Equations GET /api/v1/archive/equations ?target_sum=333&keyword=envideea&limit=20 hs_search_archive_equations
Quant Finance Harvest GET /api/v1/quant/harvest ?harvest_mode=us-closing-bell&symbol_filter=NVDA (also GET /api/v1/quant/instruments/{symbol}) hs_scan_financial_quant_harvest
IPLD dag-json CIDv1 GET or POST /api/v1/ipld/cid ?registry_name=glossary-registry (or POST arbitrary {"json_object": {...}}) hs_compute_ipld_dag_json_cid
Grounded Citations POST /api/v1/citations/verify {"draft_path": "...", "ledger_variant": "common", "require_evidence": true} hs_verify_grounded_citations

3.4 Static Resources, Dossiers, Schemas & Guided Prompts Endpoints

HTTP Method & Path Description Underlying Resource / Prompt
GET /api/v1/resources Lists all 7 static URN resources and 2 URI templates. STATIC_RESOURCES + RESOURCE_TEMPLATES
GET /api/v1/resources/{slug} Returns parsed JSON for slug in {glossary-registry, encyclopedia-manifest, eti-tier-list, singularity-matrix, memetic-registry, quantitative-anchors, knowledge-graph-summary}. read_mcp_resource("urn:io:hyperstitionstud:resource:" + slug)
GET /api/v1/dossiers/{number} Returns {dossier_number, uri, mime_type: "text/markdown", markdown: "..."} for Dossier 01..71 (or raw text/markdown when Accept: text/markdown or ?format=raw is passed). read_mcp_resource("urn:io:hyperstitionstud:dossier:" + number)
GET /api/v1/schemas/{schema_slug} Returns the raw v1 JSON Schema (glossary-registry, encyclopedia-graph, learn-progress-state, financial-aq-harvest). read_mcp_resource("urn:io:hyperstitionstud:schema:v1:" + schema_slug)
GET /api/v1/prompts Lists all 4 guided workflow prompt templates and their required arguments. MCP_PROMPTS
GET or POST /api/v1/prompts/{prompt_name} Renders the prompt messages with supplied query/JSON arguments (?headline=... or ?audience=fund_manager&focus_guild=S1). get_mcp_prompt(prompt_name, args)

4. Standardized REST Response Envelope & Error Contract

To give non-MCP callers deterministic metadata without double-stringifying the result, every /api/v1/* JSON response uses a flat, single-parsed envelope (with optional ?raw=1 query flag to return the bare data object directly):

4.1 Successful Response (HTTP 200 OK)

{
  "ok": true,
  "version": "2.0.17",
  "endpoint": "/api/v1/quant/harvest",
  "tool": "hs_scan_financial_quant_harvest",
  "data": {
    "$schema": "./schemas/v1/financial-aq-harvest.schema.json",
    "$id": "urn:io:hyperstitionstud:schema:v1:financial-aq-harvest",
    "harvest_mode": "us-closing-bell",
    "instruments": [ ... ]
  },
  "isolation_verified": true
}

(When ?raw=1 or ?unwrap=true is passed, data is returned at the top level directly so curl -s 'https://hyperstitionstud.io/api/v1/quant/harvest?symbol_filter=NVDA&raw=1' | jq .instruments[0] works with zero wrapper keys).

4.2 Error Response (HTTP 400 / 404 / 405 / 422 / 500)

{
  "ok": false,
  "version": "2.0.17",
  "error": {
    "code": "INVALID_ARGUMENTS",
    "status": 422,
    "message": "Missing required parameter 'terms' for tool 'hs_evaluate_aq_and_ingglish'."
  }
}

5. Concrete Client Usage Examples (Zero MCP Client Required)

  1. curl + jq (Evaluate Base-36 AQ & Ingglish Locks via GET):
    curl -s "https://hyperstitionstud.io/api/v1/ciphers/evaluate?terms=schizoanalysis,abstract%20machine,synthetic%20data" | jq .data
    
  2. curl (Fetch NVDA Closing-Bell Quantitative Telemetry & Scope 1–3 Locks):
    curl -s "https://hyperstitionstud.io/api/v1/quant/instruments/NVDA" | jq .data
    
  3. Browser fetch() / JavaScript Client:
    const resp = await fetch("/api/v1/graph/nodes/aq:125?include_neighbors=true");
    const { data } = await resp.json();
    console.log(data.matched_nodes, data.neighbors);
    
  4. Python urllib / requests / Pandas Notebook:
    import requests
    df_rows = requests.get("https://hyperstitionstud.io/api/v1/zoology/tier-list", params={"register": "fund_manager", "raw": "1"}).json()["builds"]
    

6. Three-Phase Implementation Sequence (Phases 1–3)

Phase 1: Create src/hyperstitionstud_io/mcp/rest.py (Router, Schema-Driven Query Coercer & OpenAPI 3.1 Builder)

  1. Implement coerce_query_params(query_str, input_schema) to convert URL query strings (?terms=a,b&limit=10&include_neighbors=false) into typed Python dicts matching each tool's JSON Schema in MCP_TOOLS_SCHEMA.
  2. Implement build_openapi_v1_spec() to auto-generate the OpenAPI 3.1.0 specification document (/api/v1/openapi.json) directly from MCP_TOOLS_SCHEMA, STATIC_RESOURCES, RESOURCE_TEMPLATES, and MCP_PROMPTS so adding a new MCP tool automatically adds its REST route and OpenAPI entry.
  3. Implement dispatch_rest_v1(method, path, query_str, body_bytes, headers) executing inside ReadOnlyIsolationGuard(cfg.read_only_files) and returning (http_status, content_type, payload).

Phase 2: Wire /api/v1/* into src/hyperstitionstud_io/mcp/server.py & deploy/Caddyfile

  1. Update _MCPHTTPHandler.do_GET() and _MCPHTTPHandler.do_POST() in src/hyperstitionstud_io/mcp/server.py to route any path starting with /api/v1 to dispatch_rest_v1(), while keeping /mcp 100% unchanged for MCP Streamable HTTP JSON-RPC 2.0 clients.
  2. Register src/hyperstitionstud_io/mcp/rest.py in src/hyperstitionstud_io/version_sync.py if it carries version strings (or import SERVER_INFO["version"] directly from server.py).
  3. Update /workspace/hyperstitionstudio-core/deploy/Caddyfile so the reverse proxy rule matches both /mcp and /api/v1:
    @mcp_and_rest_api path /mcp /mcp/* /api/v1 /api/v1/*
    handle @mcp_and_rest_api {
        reverse_proxy 127.0.0.1:8095
    }
    

Phase 3: Verification in tests/test_core_suite.py & deploy/test-first-deployment.sh

  1. Add unit tests in tests/test_core_suite.py testing dispatch_rest_v1() across:
    • GET /api/v1/status and GET /api/v1/openapi.json (validating OpenAPI 3.1.0 structure),
    • GET /api/v1/ciphers/evaluate?terms=schizoanalysis,abstract%20machine,synthetic%20data,
    • POST /api/v1/tools/hs_evaluate_aq_and_ingglish,
    • GET /api/v1/quant/instruments/NVDA,
    • GET /api/v1/graph/nodes/aq:125,
    • GET /api/v1/resources/eti-tier-list and GET /api/v1/dossiers/65,
    • GET /api/v1/prompts/analyze_headline_zoology?headline=Nvidia+halts, and
    • 404 / 422 structured error responses + ReadOnlyIsolationGuard invariance.
  2. Add /api/v1/status, /api/v1/openapi.json, and /api/v1/quant/instruments/NVDA checks to deploy/test-first-deployment.sh.