#!/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 import time 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.db.sqlite_meta import record_api_telemetry # 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.rest import ( # noqa: E402 compute_response_etag, dispatch_rest_v1, matches_if_none_match, ) from hyperstitionstud_io.mcp.tools import MCP_TOOLS_SCHEMA, call_mcp_tool # noqa: E402 SERVER_INFO = { "name": "hyperstitionstudio-mcp", "version": "2.17.1", "namespace_urn": "urn:io:hyperstitionstud:mcp:2.17.1", } def dispatch_jsonrpc(req: dict[str, Any], traffic_source: str = "internal_test") -> 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 t0_ns = time.perf_counter_ns() rpc_pattern = method if method == "tools/call": rpc_pattern = f"tools/call:{params.get('name', '')}" elif method == "prompts/get": rpc_pattern = f"prompts/get:{params.get('name', '')}" status_code = 200 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: status_code = 404 return { "jsonrpc": "2.0", "id": req_id, "error": {"code": -32601, "message": f"Method not found: {method}"}, } except Exception as exc: status_code = 422 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)}, } finally: elapsed_us = max(1, (time.perf_counter_ns() - t0_ns) // 1000) rpc_params: dict[str, str] = {} if method == "tools/call" and isinstance(params, dict): t_args = params.get("arguments") or {} if isinstance(t_args, dict): for p_k in ("symbol", "symbol_filter", "lens", "lang", "unit_filter"): if p_k in t_args and t_args[p_k]: norm_k = "symbol" if p_k == "symbol_filter" else p_k rpc_params[norm_k] = str(t_args[p_k]) record_api_telemetry( protocol="mcp_jsonrpc", method="POST", endpoint_pattern=rpc_pattern or "unknown", status_code=status_code, latency_us=elapsed_us, isolation_ok=True, traffic_source=traffic_source, param_events=rpc_params, ) 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_payload(self, status: int, content_type: str, payload: Any, etag: str | None = None) -> None: if status == 304: self.send_response(304) if etag: self.send_header("ETag", etag) self.send_header("Cache-Control", "public, max-age=60, must-revalidate") 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, If-None-Match") self.send_header("Access-Control-Expose-Headers", "ETag") self.end_headers() return if isinstance(payload, str): body = payload.encode("utf-8") else: body = (json.dumps(payload, indent=2, ensure_ascii=False) + "\n").encode("utf-8") computed_etag = etag or compute_response_etag(payload) self.send_response(status) self.send_header("Content-Type", content_type) self.send_header("Content-Length", str(len(body))) if computed_etag: self.send_header("ETag", computed_etag) self.send_header("Cache-Control", "public, max-age=60, must-revalidate") 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, If-None-Match") self.send_header("Access-Control-Expose-Headers", "ETag") self.end_headers() self.wfile.write(body) def _send_json(self, status: int, payload: Any, etag: str | None = None) -> None: self._send_payload(status, "application/json; charset=utf-8", payload, etag=etag) 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, If-None-Match") self.send_header("Access-Control-Expose-Headers", "ETag") self.end_headers() def _classify_traffic_source(self) -> str: ua = (self.headers.get("User-Agent") or "").strip() if "HyperstitionPublicSmoke" in ua or "HyperstitionInternalTest" in ua: return "internal_test" return "external_production" def do_GET(self) -> None: try: inm = self.headers.get("If-None-Match") tsrc = self._classify_traffic_source() if self.path.startswith("/api/v1"): status, ctype, payload = dispatch_rest_v1("GET", self.path, traffic_source=tsrc) etag = compute_response_etag(payload) if status == 200 else None if status == 200 and inm and etag and matches_if_none_match(inm, etag): record_api_telemetry( protocol="rest_v1", method="GET", endpoint_pattern=self.path.split("?", 1)[0], status_code=304, latency_us=1, isolation_ok=True, traffic_source=tsrc, ) self._send_payload(304, ctype, "", etag=etag) return self._send_payload(status, ctype, payload, etag=etag) return manifest = { "serverInfo": SERVER_INFO, "protocols": ["2025-03-26", "2024-11-05"], "transport": "streamable-http", "endpoints": { "jsonrpc_post": "/mcp", "manifest_get": "/mcp", "rest_api_v1": "/api/v1", "openapi_3_1": "/api/v1/openapi.json", }, "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], } m_etag = compute_response_etag(manifest) if inm and matches_if_none_match(inm, m_etag): self._send_payload(304, "application/json; charset=utf-8", "", etag=m_etag) return self._send_json(200, manifest, etag=m_etag) except Exception as exc: self._send_json(500, {"ok": False, "error": {"code": "INTERNAL_ERROR", "status": 500, "message": str(exc)}}) # 7. Stateless Read-Only MCP (/mcp) & REST API v1 (/api/v1/*) HTTP Server -> 127.0.0.1:8095 # Note: Do NOT call dispatch_jsonrpc or dispatch_rest_v1 inside do_POST without top-level try/except def do_POST(self) -> None: try: 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_bytes = self.rfile.read(length) if length > 0 else b"" tsrc = self._classify_traffic_source() if self.path.startswith("/api/v1"): status, ctype, payload = dispatch_rest_v1("POST", self.path, raw_bytes, traffic_source=tsrc) self._send_payload(status, ctype, payload) return if not raw_bytes: self._send_json(400, {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "Invalid content length"}}) return raw = raw_bytes.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, traffic_source=tsrc) if resp is None: self.send_response(202) self.end_headers() return self._send_json(200, resp) except Exception as exc: self._send_json(500, {"ok": False, "error": {"code": "INTERNAL_ERROR", "status": 500, "message": str(exc)}}) 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())