import json, urllib.request, time
URL="https://claude-cloud.tail053faf.ts.net/advancedmd/mcp"
AUTH="Bearer f10221f209ad50494fd1fd86e62bda9236449b3b35b0a2d97b1ca7bfb86208b7"
def _post(body, sid=None):
    d=json.dumps(body).encode(); r=urllib.request.Request(URL,data=d,method="POST")
    r.add_header("Authorization",AUTH); r.add_header("Content-Type","application/json")
    r.add_header("Accept","application/json, text/event-stream")
    if sid: r.add_header("Mcp-Session-Id",sid)
    resp=urllib.request.urlopen(r,timeout=120); s=resp.headers.get("Mcp-Session-Id"); raw=resp.read().decode()
    o=None
    if raw.lstrip().startswith("{"): o=json.loads(raw)
    else:
        for ln in raw.splitlines():
            if ln.startswith("data:"):
                try:o=json.loads(ln[5:].strip())
                except:pass
    return s,o
def session():
    sid,_=_post({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"b","version":"1"}}})
    dd=json.dumps({"jsonrpc":"2.0","method":"notifications/initialized"}).encode()
    r=urllib.request.Request(URL,data=dd,method="POST"); r.add_header("Authorization",AUTH)
    r.add_header("Content-Type","application/json"); r.add_header("Accept","application/json, text/event-stream"); r.add_header("Mcp-Session-Id",sid)
    urllib.request.urlopen(r,timeout=30).read(); return sid
def call(sid,name,args):
    _,o=_post({"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":name,"arguments":args}}, sid)
    txt=o['result']['content'][0]['text']
    if txt.startswith("Error:"): raise RuntimeError(txt)
    return json.loads(txt)
