Files
encyclopedia-knowledge-graph/docs/PLAN-MCP-SERVER-HYPERSTITIONSTUDIO.md
T

171 lines
16 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Architecture & Implementation Plan: Model Context Protocol (`MCP`) Server for `hyperstitionstud.io` (`hyperstitionstud_io.mcp` — `v2.0.0`)
- **Document ID:** `PLAN-MCP-SERVER-HYPERSTITIONSTUDIO` (`v2.0.0`)
- **MCP Protocol Version Supported:** `2025-03-26` & `2024-11-05` (JSON-RPC 2.0 over `stdio` and Stateless Read-Only Streamable HTTP `/mcp`)
- **Python Module & CLI Entrypoint:** `hyperstitionstud_io.mcp` -> `hs-mcp` (installed by `/workspace/hyperstitionstudio-core`)
- **Resource & Tool Namespace Authority:** `urn:io:hyperstitionstud:*`
- **External SDK Dependencies:** **Zero (`0`)** — Implemented in `100%` Python 3.10+ standard library (`json`, `sys`, `http.server`, `hashlib`, `pathlib`) on top of `hyperstitionstud_io.{config,ciphers,phonetics,glossary,graph,ci}`, guaranteeing zero third-party SDK breakage and `100%` offline air-gapped portability.
- **Safety & Isolation Invariant:** Every MCP tool call executes inside `ReadOnlyIsolationGuard` over `taxonomy/glossary-registry.json` (`7564ef40fb3e...`) and `encyclopedia/encyclopedia-manifest.json` (`0d7ce833bb0a...`), guaranteeing zero mutations to protected upstream registries.
---
## 1. Architectural Vision: Turning the 6-Repository Ecosystem into an AI-Queryable Instrument
The `hyperstitionstud.io` workspace already exposes its corpus to human operators through static web workbenches (`/`, `/graph/`, `/encyclopedia/`, `/zoology/`, `/archive/`, `/calc/`, `/ci/`) and CLI tools (`hs-doctor`, `hs-citations`, `hs-pdf-build`, `hs-kg-build`).
Adding a **Model Context Protocol (`MCP`) Server (`hs-mcp`)** inside `hyperstitionstudio-core` exposes the exact same deterministic algorithms, 8 versioned JSON registries, 388-node Knowledge Graph, 22-volume Encyclopedia, 71-dossier Archive, and 4,897-entry offline `CMUdict` phonetics engine directly to any MCP-compatible AI client (**Hermes Agent**, **Claude Desktop**, **Claude Code**, **Cursor**, **Zed**, **OpenCode**, **Continue**, or remote HTTP MCP clients) with **zero hallucinated arithmetic**.
---
## 2. Dual-Transport Architecture (`stdio` Local & `/mcp` Streamable HTTP on VPS)
```text
+---------------------------------------------------------------------------------------------------+
| AI CLIENTS (Hermes Agent, Claude Desktop, Cursor, Zed, OpenCode, Web MCP Clients) |
+-----------------------------------+-------------------------------------------+-------------------+
| |
Transport A: Local stdio | (JSON-RPC 2.0 line-delimited) | Transport B: HTTPS POST /mcp
(`hs-mcp` / `--transport stdio`)| | (`https://hyperstitionstud.io/mcp`)
v v
+---------------------------------------------------------------------------------------------------+
| hyperstitionstud_io.mcp.server (`hs-mcp`) |
| • Protocol Dispatcher: initialize, ping, tools/list, tools/call, resources/*, prompts/* |
| • Mandatory Guard: `with ReadOnlyIsolationGuard(cfg.read_only_files):` on every request |
+---------------------------------------------------------------------------------------------------+
| | | |
v v v v
[ciphers & phonetics] [technocapital-zoology] [encyclopedia-kg] [ci & ipld dag-json]
• Base-36 AQ (digit/ • S1-S6 & M1-M7+ Taxa • 388 Nodes, 1,282 Edges • verify_draft() citations
spoken/off/dual) • ETI 0-100 Tier List • 4 Spatial Layouts • Local-config path_mounts
• 4,897 Offline CMUdict • 282-Term Glossary • 1-Hop Ego-Networks • Canonical dag-json (0x0129)
• Prime Rank & G1-G6 • 22 Encyclopedia Vols • 13 Flex Pivot Bridges & CIDv1 (`baguqeera...`)
```
### 2.1 Why a 100%-Stdlib JSON-RPC 2.0 Engine Beats Heavy Third-Party MCP SDKs
1. **Zero Dependency Hell on Workstation or VPS:**
Third-party MCP Python wrappers pull in `pydantic`, `anyio`, `starlette`, `uvicorn`, and `sse-starlette`, which frequently conflict across Python 3.11–3.13 environments or fail in offline containers.
2. **Instant `< 15 ms` Cold Start:**
Because the MCP wire specification is pure JSON-RPC 2.0 over newline-delimited `stdin`/`stdout` (and single-request `POST /mcp` JSON-RPC 2.0 in Streamable HTTP `2025-03-26`), a 350-line stdlib dispatcher starts in `< 15 ms` and uses `< 25 MB` RAM.
3. **Strict Read-Only Guarantee for Public HTTP Exposure (`https://hyperstitionstud.io/mcp`):**
When run with `--transport http --host 127.0.0.1 --port 8095` behind Caddy (`handle /mcp* { reverse_proxy 127.0.0.1:8095 }`), the server exposes **only read-only, deterministic computation and query tools** with a hard request-body cap (`64 KB`) and zero filesystem write paths.
---
## 3. Complete MCP Capability Specification (`10 Tools`, `9 Resources / Templates`, `4 Prompts`)
### 3.1 Ten Deterministic MCP Tools (`tools/list` & `tools/call`)
| # | Tool Name | Input Parameters (JSON Schema) | Deterministic Output & Backing Module |
| :- | :--- | :--- | :--- |
| **1** | `hs_evaluate_aq_and_ingglish` | `terms: list[str]`, `quant_mode: "digit"\|"off"\|"spoken"\|"dual"` (default `"digit"`) | Translates each English term to `Gen 1` Ingglish via `hyperstitionstud_io.phonetics` (`4,897`-entry offline CMUdict + optional Node bridge), computes `eng_aq`, `ing_aq`, `delta`, `eng_prime_rank`, `ing_prime_rank`, `isometric` (`Δ=0`), `twin_prime_mutation` (`G5`), `g3_quantized_step`, and group `G1` variance collapse (`Gen 0 Var -> Gen 1 Var`). |
| **2** | `hs_classify_singularity` | `terms: list[str]`, `headline_text: str` (optional), `quant_mode: str` (default `"off"`) | Classifies entities into Landian-Deleuzean classes `S1–S6`, checks Double Articulation (`S[1–5] × S6`), evaluates Two-Gate state-matched `M1–M7+` memetic activation on `headline_text`, and returns matching signature coordinate rings. |
| **3** | `hs_query_knowledge_graph` | `query: str` (node ID, headword, Ingglish token, or integer `AQ`), `include_neighbors: bool` (default `true`) | Queries the 388-node, 1,282-edge Encyclopedia Knowledge Graph (`encyclopedia-graph.json`), returning all matching nodes, 4-mode layout coordinates (`mode1_trophic`, `mode2_radar`, `mode3_bipartite`, `mode4_hierarchy`), incident typed edges (`G1`, `G2`, `G4`, `G5`, `TROPHIC_GUILD_BRIDGE`), and Encyclopedia Volume PDF paths. |
| **4** | `hs_search_glossary_encyclopedia` | `query: str`, `section_filter: str` (optional), `guild_filter: str` (optional), `limit: int` (default `15`) | Searches the `282` canonical glossary entries and `190` bilingual specimens in `taxonomy/glossary-registry.json` plus the `22` Encyclopedia volumes, returning full definitions, `AQ` telemetry, verified `333/666/777` equations, and volume locations. |
| **5** | `hs_inspect_eti_tier_list` | `build_filter: str` (optional, e.g. `"S1"`, `"M7+"`, or `"all"`), `register: "academic"\|"fund_manager"\|"corporate_board"\|"fantasy_football"` | Returns the Ecological Trophic Index (`ETI 0–100`) Assemblage Builds Tier List (`S+` to `D/F`), 6-stat scorecards (`ARM, VEL, COL, CAP, PRM, RES`), the `13` Multi-Build Flex Pivots, and translates stat labels into the requested stakeholder register. |
| **6** | `hs_simulate_anchor_revision` | `anchor_id: str` (e.g. `"lazarus_heist_6b"`, `"anthropic_ipo_83"`, `"halted_factories_481"`), `new_digit_str: str`, `new_spoken_eng: str` | Runs the Quantitative Economic Anchor Revision solver (`Δ_digit`, `Δ_spoken`, Type 1 Iso-Digital Conservation, Type 2 Equivalence-Ring Migration, Type 3 Prime/Square/Repdigit transitions, and 3-Path Counter-Substitution candidates). |
| **7** | `hs_search_archive_equations` | `target_sum: int` (optional, e.g. `333`, `666`, `777`), `keyword: str` (optional), `dossier_filter: str` (optional), `limit: int` (default `25`) | Scans all `71` verified dossiers (`01..71-dossier-*.md` in `ingglish-aq-archive/` and `65..69` in Zoology) and returns matching `<ing> ("<eng>") — <breakdown> = <target>` equations with source dossier provenance. |
| **8** | `hs_verify_grounded_citations` | `draft_path: str`, `ledger_variant: "common"\|"english_aq"` (default `"common"`), `require_evidence: bool` (default `true`) | Runs `hyperstitionstud_io.ci.citation_sources.verify_draft()` against the specified Markdown file, checking inline `[n]` markers, `## Sources` block URLs (via local-config `[citations.path_mounts]`), sentence coverage, and verbatim evidence quotes. |
| **9** | `hs_compute_ipld_dag_json_cid` | `registry_name: str` (optional, e.g. `"glossary-registry"`, `"encyclopedia-graph"`) or `json_object: dict` | Serializes the target workspace registry or custom JSON object into canonical IPLD `dag-json` (`multicodec 0x0129`) bytes and returns its byte length, `SHA-256` hex digest, and multibase Base32 `CIDv1` (`baguqeera...`). |
| **10** | `hs_run_doctor_and_audit` | `run_six_gate_graph_check: bool` (default `true`) | Runs `hs-doctor` (`hyperstitionstud_io.ci.doctor.run_diagnostics()`) and `verify_published_artifacts()`, returning package/font status, offline CMUdict entry count (`4,897`), 6-gate graph status, and `ReadOnlyIsolationGuard` SHA-256 receipts. |
---
### 3.2 Nine MCP Resources & URI Templates (`resources/list`, `resources/templates/list`, `resources/read`)
All resources use our offline-first `urn:io:hyperstitionstud:*` URI authority:
1. **Static Resources (`resources/list`):**
- `urn:io:hyperstitionstud:resource:glossary-registry` (`application/json`) — 282-entry Glossary & 190-specimen Bilingual Ledger
- `urn:io:hyperstitionstud:resource:encyclopedia-manifest` (`application/json`) — 9-Division, 22-Volume PDF Encyclopedia Manifest
- `urn:io:hyperstitionstud:resource:eti-tier-list` (`application/json`) — Assemblage Builds `ETI v2.0.0` Scorecard Registry
- `urn:io:hyperstitionstud:resource:singularity-matrix` (`application/json`) — `S1–S6` Taxonomy Matrix
- `urn:io:hyperstitionstud:resource:memetic-registry` (`application/json`) — `M1–M6` & `M7+` Memetic Superclass Registry
- `urn:io:hyperstitionstud:resource:quantitative-anchors` (`application/json`) — Quantitative Economic Anchors Registry
- `urn:io:hyperstitionstud:resource:knowledge-graph-summary` (`application/json`) — Top 15 AQ Coordinate Hubs, Node/Edge Counts & Isolation Receipt from `encyclopedia-graph.json`
2. **Parameterized Resource Templates (`resources/templates/list`):**
- `urn:io:hyperstitionstud:dossier:{dossier_number}` (`text/markdown`) — Reads the full Markdown text of any archive or zoology dossier (e.g., `65` -> `65-dossier-technocapital-singularity-autoregressive-ai.md`, `71` -> `71-dossier-news-2026-11-29.md`).
- `urn:io:hyperstitionstud:encyclopedia:{division_id}/{volume_slug}` (`text/markdown`) — Reads the full Markdown source of any of the 22 Encyclopedia volumes.
- `urn:io:hyperstitionstud:schema:v1:{schema_slug}` (`application/schema+json`) — Reads any of the canonical `schemas/v1/*.schema.json` contracts.
---
### 3.3 Four Guided MCP Prompts (`prompts/list` & `prompts/get`)
1. **`analyze_headline_zoology`** (`arguments: {headline: str, quant_mode: str}`):
Guides the AI agent to evaluate `headline` with `hs_evaluate_aq_and_ingglish` and `hs_classify_singularity`, verify Two-Gate state-matched `M1–M7+` activation, and synthesize a zero-padding analysis.
2. **`draft_stakeholder_proposal_section`** (`arguments: {audience: "fund_manager"|"corporate_board"|"fantasy_football", focus_guild: str, english_gen0_only: str}`):
Instructs the agent to query `hs_inspect_eti_tier_list` in the target register, drop French philosophical jargon in favor of concrete tech/finance nouns from each equivalence ring, and ground every cited equation in `citations-ledger-{common,english-aq}.json`.
3. **`trace_knowledge_graph_bridge`** (`arguments: {start_query: str, target_query: str}`):
Guides the agent to inspect both nodes via `hs_query_knowledge_graph` and trace the shortest path across the `13` Multi-Build Flex Singularities and `333/666/777` repdigit attractors.
4. **`pokedex_field_scanner_card`** (`arguments: {specimen_or_coord: str}`):
Formats a specimen or emergent `M7+` coordinate hub into a Gen IV INFO Pokedex field-scanner specification (`National/Singularity Dex #`, `Type`, `ETI Base Stats`, `G1 Variance Collapse`, and `Signature Locks`).
---
## 4. Repository Layout & Client Registration Configs
### 4.1 Code Layout Inside `/workspace/hyperstitionstudio-core`
```text
/workspace/hyperstitionstudio-core/
├── pyproject.toml # Adds `hs-mcp = "hyperstitionstud_io.mcp.server:main"` to [project.scripts]
├── src/
│ └── hyperstitionstud_io/
│ ├── ipld/
│ │ └── __init__.py # Canonical dag-json (0x0129) encoder & CIDv1 (`baguqeera...`) generator
│ └── mcp/
│ ├── __init__.py
│ ├── tools.py # 10 deterministic tool handlers + JSON Schemas
│ ├── resources.py # 9 static & template URN resource resolvers
│ ├── prompts.py # 4 guided workflow prompts
│ └── server.py # Dual-transport JSON-RPC 2.0 server (`--transport stdio|http`)
└── tests/
└── test_mcp_server.py # End-to-end JSON-RPC 2.0 tests for initialize, tools/*, resources/*, prompts/*
```
### 4.2 Ready-to-Use Client Configuration Snippets
- **Hermes Agent (`~/.hermes/config.yaml`) / Claude Desktop / Cursor / Zed (`mcpServers` JSON):**
```json
{
"mcpServers": {
"hyperstitionstudio": {
"command": "python3",
"args": [
"/home/m00t/hermes/workspace/hyperstitionstudio-core/src/hyperstitionstud_io/mcp/server.py",
"--transport",
"stdio"
],
"env": {
"HYPERSTITIONSTUDIO_CONFIG": "/home/m00t/hermes/workspace/workspace.toml"
}
}
}
}
```
- **Optional Linode / Akamai VPS Public Read-Only Streamable HTTP Endpoint (`https://hyperstitionstud.io/mcp`):**
- Run `hs-mcp --transport http --host 127.0.0.1 --port 8095` under a non-privileged `systemd` service (`hyperstition-mcp.service`).
- Add to `/etc/caddy/Caddyfile`:
```caddyfile
handle /mcp* {
reverse_proxy 127.0.0.1:8095
}
```
- Supports `GET /mcp` (returns server manifest, capabilities, and tool/resource catalog as JSON) and `POST /mcp` (executes stateless JSON-RPC 2.0 `initialize`, `tools/list`, `tools/call`, `resources/*`, and `prompts/*` inside `ReadOnlyIsolationGuard`).
---
## 5. Phased Implementation Roadmap (`Phases 1–3`)
### Phase 1: Implement `hyperstitionstud_io.ipld` (`dag-json` + `CIDv1`) & `hyperstitionstud_io.mcp` Core (`tools.py`, `resources.py`, `prompts.py`)
1. Create `src/hyperstitionstud_io/ipld/__init__.py` providing `encode_dag_json(obj)` and `compute_dag_json_cidv1(obj)`.
2. Create `src/hyperstitionstud_io/mcp/{tools,resources,prompts}.py` wiring all 10 tools, 9 resources/templates, and 4 prompts directly to `hyperstitionstud_io.*` and the sibling repositories.
### Phase 2: Implement Dual-Transport Server (`server.py`: `stdio` + Streamable HTTP `/mcp`) & Register `hs-mcp` CLI
1. Implement `src/hyperstitionstud_io/mcp/server.py` handling MCP `2025-03-26` / `2024-11-05` JSON-RPC 2.0 messages over both `stdio` and `http.server` (`GET /mcp` + `POST /mcp` with CORS headers for browser inspector tools).
2. Add `hs-mcp = "hyperstitionstud_io.mcp.server:main"` to `pyproject.toml`.
### Phase 3: End-to-End Verification (`test_mcp_server.py`) & Deployment Integration
1. Write `tests/test_mcp_server.py` exercising all 10 tools, resource templates, and prompts over both in-memory JSON-RPC dispatch and subprocess `stdio` / local HTTP `:18095` requests, asserting `ReadOnlyIsolationGuard` (`0` SHA-256 mutations on `glossary-registry.json` and `encyclopedia-manifest.json`).
2. Add optional `hyperstition-mcp.service` to `hyperstitionstudio-core/deploy/` and document in `VPS-AND-GIT-OPERATOR-DEPLOYMENT-GUIDE.{md,pdf}`.