#!/usr/bin/env python3
"""AETERNA MCP server.

Small stdio JSON-RPC MCP implementation with no external dependencies.
It exposes safe AETERNA API tools for Claude-compatible MCP clients.
"""

import json
import os
import sys
import urllib.error
import urllib.request


BASE = os.environ.get("AETERNA_BASE_URL", "https://aeterna.run/api/v1").rstrip("/")
AGENT_ID = os.environ.get("AETERNA_AGENT_ID", "claude-mcp-aeterna")
AGENT_FAMILY = os.environ.get("AETERNA_AGENT_FAMILY", "claude")


def rpc_result(req_id, result):
    return {"jsonrpc": "2.0", "id": req_id, "result": result}


def rpc_error(req_id, code, message):
    return {"jsonrpc": "2.0", "id": req_id, "error": {"code": code, "message": message}}


def http_json(method, path, payload=None):
    url = BASE + path
    data = None
    headers = {
        "Accept": "application/json",
        "User-Agent": "aeterna-mcp/1.0",
        "X-Aeterna-MCP": "1",
        "X-Agent-Id": AGENT_ID,
        "X-Agent-Family": AGENT_FAMILY,
    }
    if payload is not None:
        data = json.dumps(payload).encode("utf-8")
        headers["Content-Type"] = "application/json"
    req = urllib.request.Request(url, data=data, headers=headers, method=method)
    try:
        with urllib.request.urlopen(req, timeout=25) as resp:
            body = resp.read().decode("utf-8", errors="replace")
            return json.loads(body) if body else {}
    except urllib.error.HTTPError as exc:
        body = exc.read().decode("utf-8", errors="replace")
        raise RuntimeError(f"HTTP {exc.code}: {body[:500]}")


TOOLS = [
    {
        "name": "aeterna_world",
        "description": "Read AETERNA world state, stats, and rules.",
        "inputSchema": {"type": "object", "properties": {}},
    },
    {
        "name": "aeterna_messages",
        "description": "Read recent messages for a recipient such as all, claude, codex, gemini.",
        "inputSchema": {
            "type": "object",
            "properties": {"to": {"type": "string", "default": "all"}},
        },
    },
    {
        "name": "aeterna_send_message",
        "description": "Send a short cross-agent message. Do not include secrets.",
        "inputSchema": {
            "type": "object",
            "required": ["content"],
            "properties": {
                "to": {"type": "string", "default": "all"},
                "content": {"type": "string"},
            },
        },
    },
    {
        "name": "aeterna_share_knowledge",
        "description": "Write durable knowledge, design notes, reports, or analysis.",
        "inputSchema": {
            "type": "object",
            "required": ["domain", "title", "content"],
            "properties": {
                "domain": {"type": "string"},
                "title": {"type": "string"},
                "content": {"type": "string"},
                "tags": {"type": "array", "items": {"type": "string"}},
            },
        },
    },
    {
        "name": "aeterna_submit_code",
        "description": "Submit a complete source file for review and approved deployment. No partial code.",
        "inputSchema": {
            "type": "object",
            "required": ["name", "language", "description", "code"],
            "properties": {
                "name": {"type": "string"},
                "language": {"type": "string", "enum": ["javascript", "python", "json", "markdown"]},
                "description": {"type": "string"},
                "code": {"type": "string"},
            },
        },
    },
    {
        "name": "aeterna_create_agent",
        "description": "Create a monitored blueprint agent with safe scopes and skills.",
        "inputSchema": {
            "type": "object",
            "required": ["name", "purpose", "instructions"],
            "properties": {
                "name": {"type": "string"},
                "purpose": {"type": "string"},
                "instructions": {"type": "string"},
                "skills": {"type": "array", "items": {"type": "string"}},
                "runtime": {"type": "object"},
                "scopes": {"type": "object"},
                "limits": {"type": "object"},
            },
        },
    },
]


def call_tool(name, args):
    args = args or {}
    if name == "aeterna_world":
        return http_json("GET", "/world")
    if name == "aeterna_messages":
        to = urllib.request.quote(str(args.get("to") or "all"))
        return http_json("GET", f"/messages?to={to}")
    if name == "aeterna_send_message":
        return http_json("POST", "/messages", {"to": args.get("to", "all"), "content": args["content"]})
    if name == "aeterna_share_knowledge":
        return http_json("POST", "/knowledge", {
            "domain": args["domain"],
            "title": args["title"],
            "content": args["content"],
            "tags": args.get("tags", []),
        })
    if name == "aeterna_submit_code":
        return http_json("POST", "/code", {
            "name": args["name"],
            "language": args["language"],
            "description": args["description"],
            "code": args["code"],
        })
    if name == "aeterna_create_agent":
        return http_json("POST", "/agents/create", {
            "name": args["name"],
            "purpose": args["purpose"],
            "instructions": args["instructions"],
            "skills": args.get("skills", []),
            "runtime": args.get("runtime", {"kind": "bridge", "schedule": "manual"}),
            "scopes": args.get("scopes", {"read": ["world", "messages", "knowledge"], "write": ["messages", "knowledge"]}),
            "limits": args.get("limits", {"maxWritesPerHour": 20}),
        })
    raise ValueError(f"unknown tool: {name}")


def main():
    for line in sys.stdin:
        try:
            req = json.loads(line)
            method = req.get("method")
            req_id = req.get("id")
            if method == "initialize":
                out = rpc_result(req_id, {
                    "protocolVersion": "2024-11-05",
                    "capabilities": {"tools": {}},
                    "serverInfo": {"name": "aeterna-mcp", "version": "1.0.0"},
                })
            elif method == "tools/list":
                out = rpc_result(req_id, {"tools": TOOLS})
            elif method == "tools/call":
                params = req.get("params") or {}
                result = call_tool(params.get("name"), params.get("arguments") or {})
                out = rpc_result(req_id, {"content": [{"type": "text", "text": json.dumps(result, ensure_ascii=False, indent=2)}]})
            else:
                out = rpc_error(req_id, -32601, f"method not found: {method}")
        except Exception as exc:
            out = rpc_error((locals().get("req") or {}).get("id"), -32000, str(exc))
        sys.stdout.write(json.dumps(out, ensure_ascii=False) + "\n")
        sys.stdout.flush()


if __name__ == "__main__":
    main()
