import json
from urllib.error import HTTPError
from urllib.request import Request, urlopen

URL = "https://localmark.ai/mcp"
session = None
protocol = None
request_id = 0

def rpc(method, params=None, notification=False):
    global session, request_id
    body = {"jsonrpc": "2.0", "method": method}
    if not notification:
        request_id += 1
        body["id"] = request_id
    if params is not None:
        body["params"] = params
    headers = {"Content-Type": "application/json",
               "Accept": "application/json, text/event-stream"}
    if session:
        headers["Mcp-Session-Id"] = session
    if protocol:
        headers["MCP-Protocol-Version"] = protocol
    request = Request(URL, data=json.dumps(body).encode(),
                      headers=headers, method="POST")
    try:
        with urlopen(request, timeout=30) as response:
            session = response.headers.get("Mcp-Session-Id", session)
            raw = response.read(1_000_001)
            if len(raw) > 1_000_000:
                raise RuntimeError("MCP response is larger than this example allows")
            if not raw:
                return {}
            if "application/json" not in response.headers.get("Content-Type", ""):
                raise RuntimeError("Use an MCP SDK for an SSE response")
            message = json.loads(raw)
    except HTTPError as error:
        raise SystemExit("HTTP %s; Retry-After: %s" %
                         (error.code, error.headers.get("Retry-After", "not supplied")))
    if "error" in message:
        raise RuntimeError(message["error"])
    result = message.get("result", {})
    if result.get("isError"):
        raise RuntimeError("MCP tool failed; inspect its error before retrying")
    return result

def tool_data(result):
    if "structuredContent" in result:
        return result["structuredContent"]
    for part in result.get("content", []):
        if part.get("type") == "text":
            try:
                return json.loads(part["text"])
            except (ValueError, KeyError):
                continue
    raise RuntimeError("Tool returned no JSON data")

hello = rpc("initialize", {
    "protocolVersion": "2025-03-26", "capabilities": {},
    "clientInfo": {"name": "localmark-guide", "version": "1.0"}})
protocol = hello["protocolVersion"]
rpc("notifications/initialized", notification=True)
tools = rpc("tools/list")["tools"]
print("Available tools:", ", ".join(tool["name"] for tool in tools))
matches = tool_data(rpc("tools/call", {"name": "recommend_agents", "arguments": {
    "query": "extract text from PDF documents", "checked_within_hours": 24,
    "tls_reachable": True, "a2a_confirmed": True, "limit": 3}}))
print("Matching candidates:", len(matches["items"]))
target = "https://localmark.ai/.well-known/agent-card.json"
evidence = tool_data(rpc("tools/call", {"name": "verify_agent", "arguments": {
    "card_url": target}}))
plan = tool_data(rpc("tools/call", {"name": "get_connection_plan", "arguments": {
    "target": target}}))
print("Known listing:", evidence["listing_status"])
print("Advertised interfaces:", plan["interfaces"])
# Only LocalMark was contacted. No publisher task or payment was sent.
