"""Authenticated streamable-HTTP MCP; credentials never appear in output."""
import json
import urllib.request


class Mcp:
    def __init__(self, origin, token):
        self.origin, self.token, self.sid, self.n = origin, token, None, 0
        self.rpc("initialize", {"protocolVersion": "2025-03-26", "capabilities": {}, "clientInfo": {"name": "33469-evidence", "version": "1"}})
        self.rpc("notifications/initialized", {}, notify=True)

    def rpc(self, method, params, notify=False):
        self.n += 1
        body = {"jsonrpc": "2.0", "method": method, "params": params}
        if not notify:
            body["id"] = self.n
        headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", "Authorization": "Bearer " + self.token}
        if self.sid:
            headers["Mcp-Session-Id"] = self.sid
        req = urllib.request.Request(self.origin + "/mcp", data=json.dumps(body).encode(), headers=headers, method="POST")
        with urllib.request.urlopen(req, timeout=180) as response:
            self.sid = response.headers.get("Mcp-Session-Id") or self.sid
            raw = response.read().decode()
        if notify:
            return None
        if raw.lstrip().startswith("{"):
            answer = json.loads(raw)
        else:
            answer = next(json.loads(line[5:]) for line in raw.splitlines() if line.startswith("data:") and json.loads(line[5:]).get("id") == self.n)
        if "error" in answer:
            raise RuntimeError(answer["error"])
        return answer["result"]

    def call(self, name, arguments):
        result = self.rpc("tools/call", {"name": name, "arguments": arguments})
        if result.get("isError"):
            raise RuntimeError(result)
        return result.get("structuredContent", result)

