"""Minimal streamable-HTTP MCP client for a T3 dev server: mcp.py <origin> <tokenfile> <tool> <json-args>"""
import json, sys, urllib.request
origin, tokfile, tool, args = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
tok = open(tokfile).read().strip()
url = origin.rstrip('/') + '/mcp'
sid = None
def call(method, params, notify=False, rid=[0]):
    global sid
    rid[0] += 1
    body = {"jsonrpc": "2.0", "method": method, "params": params}
    if not notify: body["id"] = rid[0]
    h = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", "Authorization": "Bearer " + tok}
    if sid: h["Mcp-Session-Id"] = sid
    req = urllib.request.Request(url, data=json.dumps(body).encode(), headers=h, method="POST")
    try:
        r = urllib.request.urlopen(req, timeout=600)
    except urllib.error.HTTPError as e:
        print("HTTP", e.code, e.read().decode()[:2000]); sys.exit(1)
    sid = r.headers.get("Mcp-Session-Id") or sid
    raw = r.read().decode()
    if notify: return None
    if raw.lstrip().startswith("{"): return json.loads(raw)
    out = None
    for line in raw.splitlines():
        if line.startswith("data:"):
            d = json.loads(line[5:])
            if d.get("id") == rid[0]: out = d
    return out
call("initialize", {"protocolVersion": "2025-03-26", "capabilities": {}, "clientInfo": {"name": "issue-33454-driver", "version": "0"}})
call("notifications/initialized", {}, notify=True)
if tool == "--list":
    res = call("tools/list", {})
    print("\n".join(t["name"] for t in res["result"]["tools"]))
else:
    res = call("tools/call", {"name": tool, "arguments": json.loads(args)})
    r = res.get("result", res)
    if "structuredContent" in r: print(json.dumps(r["structuredContent"], indent=1))
    else: print(json.dumps(r, indent=1))
