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:
1 parent
b767f8a4e9
commit
c17f74097b
55 files changed
+3974
-10
No files matched your search
Executable
+246
@@ -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())
|
||||
Reference in new issue
Block a user