import json, urllib.request, sys

URL="https://claude-cloud.tail053faf.ts.net/advancedmd/mcp"
AUTH="Bearer f10221f209ad50494fd1fd86e62bda9236449b3b35b0a2d97b1ca7bfb86208b7"

def post(body, session=None):
    data = json.dumps(body).encode()
    req = urllib.request.Request(URL, data=data, method="POST")
    req.add_header("Authorization", AUTH)
    req.add_header("Content-Type","application/json")
    req.add_header("Accept","application/json, text/event-stream")
    if session: req.add_header("Mcp-Session-Id", session)
    resp = urllib.request.urlopen(req, timeout=60)
    sid = resp.headers.get("Mcp-Session-Id")
    raw = resp.read().decode()
    # parse SSE or json
    out=None
    if raw.lstrip().startswith("{"):
        out=json.loads(raw)
    else:
        for line in raw.splitlines():
            if line.startswith("data:"):
                try: out=json.loads(line[5:].strip())
                except: pass
    return sid, out

# initialize
sid, init = post({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"builder","version":"1"}}})
print("SESSION:", sid)
print("INIT ok:", bool(init and 'result' in init))
# initialized notification
if sid:
    data = json.dumps({"jsonrpc":"2.0","method":"notifications/initialized"}).encode()
    req = urllib.request.Request(URL, data=data, method="POST")
    req.add_header("Authorization", AUTH); req.add_header("Content-Type","application/json")
    req.add_header("Accept","application/json, text/event-stream"); req.add_header("Mcp-Session-Id", sid)
    try: urllib.request.urlopen(req, timeout=30).read()
    except Exception as e: print("notif err", e)
# test one call
_, r = post({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"get_appointment_history","arguments":{"patientid":"17572416"}}}, session=sid)
txt = r['result']['content'][0]['text']
d = json.loads(txt)
print("TEST call count:", d.get('count'))
open('/tmp/amd_session.txt','w').write(sid)
