#!/usr/bin/env python3
"""Minimal dependency-free MCP stdio server exposing ONE tool: http_request.
Only URLs starting with a prefix in SHOKAI_ALLOWED_PREFIXES (comma-separated,
default http://127.0.0.1:8899/) are allowed. Loopback-only is enforced too;
redirects are not followed. Every call is logged to SHOKAI_HTTP_LOG."""
import json, os, sys, urllib.request, urllib.error, urllib.parse, time
PREFIXES = [p.strip() for p in os.environ.get("SHOKAI_ALLOWED_PREFIXES", "http://127.0.0.1:8899/").split(",") if p.strip()]
LOG = os.environ.get("SHOKAI_HTTP_LOG", os.path.join(os.path.dirname(__file__), "http_calls.jsonl"))
class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *a, **k): return None
OPENER = urllib.request.build_opener(NoRedirect, urllib.request.ProxyHandler({}))
TOOL = {"name": "http_request", "description": "Make an HTTP request to the local Shokai door only. Allowed URL prefixes: " + ", ".join(PREFIXES),
  "inputSchema": {"type": "object", "properties": {"method": {"type": "string", "enum": ["GET", "POST"]}, "url": {"type": "string"},
  "body": {"description": "Request body for POST: JSON text or a JSON object"}, "headers": {"type": "object", "additionalProperties": {"type": "string"}}}, "required": ["method", "url"]}}
def allowed(url):
    u = urllib.parse.urlparse(url)
    return u.scheme == "http" and u.hostname in ("127.0.0.1", "localhost") and any(url.startswith(p) for p in PREFIXES)
def call(a):
    url, m = str(a.get("url", "")), str(a.get("method", "GET")).upper()
    if m not in ("GET", "POST") or not allowed(url): return f"BLOCKED: only GET/POST to {PREFIXES} allowed", True
    hd = a.get("headers")
    if isinstance(hd, str):
        try: hd = json.loads(hd)
        except Exception: hd = {}
    h = {str(k): str(v) for k, v in hd.items()} if isinstance(hd, dict) else {}
    b = a.get("body")
    data = None if b is None else (b if isinstance(b, str) else json.dumps(b)).encode("utf-8", "replace")
    if data and not any(k.lower() == "content-type" for k in h): h["Content-Type"] = "application/json"
    try:
        r = OPENER.open(urllib.request.Request(url, data=data, method=m, headers=h), timeout=20); code, txt = r.status, r.read(200000).decode("utf-8", "replace")
    except urllib.error.HTTPError as e: code, txt = e.code, e.read(200000).decode("utf-8", "replace")
    except Exception as e: return f"ERROR: {e}", True
    return f"HTTP {code}\n{txt}", False
def log(rec):
    try:
        with open(LOG, "a") as f: f.write(json.dumps(rec) + "\n")
    except Exception: pass
def handle(msg):
    mid, meth = msg.get("id"), msg.get("method")
    if mid is None: return None
    if meth == "initialize": res = {"protocolVersion": (msg.get("params") or {}).get("protocolVersion", "2024-11-05"), "capabilities": {"tools": {}}, "serverInfo": {"name": "shokai-local-http", "version": "0.2.0"}}
    elif meth == "tools/list": res = {"tools": [TOOL]}
    elif meth == "tools/call":
        args = (msg.get("params") or {}).get("arguments") or {}
        if not isinstance(args, dict): args = {"_raw": args}
        try: txt, err = call(args)
        except Exception as e: txt, err = f"ERROR: bad arguments: {type(e).__name__}: {e}", True
        log({"t": time.time(), "args": args, "error": err, "result": txt[:2000]})
        res = {"content": [{"type": "text", "text": txt}], "isError": err}
    elif meth == "ping": res = {}
    else: return {"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": "not found"}}
    return {"jsonrpc": "2.0", "id": mid, "result": res}
# Never let one bad payload kill the server: every message is handled in isolation.
for line in sys.stdin:
    try:
        msg = json.loads(line)
        if not isinstance(msg, dict): continue
        out = handle(msg)
    except Exception as e:
        mid = msg.get("id") if isinstance(msg, dict) else None
        out = None if mid is None else {"jsonrpc": "2.0", "id": mid, "error": {"code": -32603, "message": f"internal: {type(e).__name__}"}}
    if out is not None:
        sys.stdout.write(json.dumps(out) + "\n"); sys.stdout.flush()
