python3 - <<'PY'
import json,hashlib,shutil,time,os

token_path=os.path.expanduser("~/.config/mcp-bearer-token")
token=open(token_path).read().strip()
expected="05c8f7892be09cefb23bafb3680e30c1ecbe83e71ab1a653e398a783a2d4774f"
assert hashlib.sha256(token.encode()).hexdigest()==expected, "canonical token hash mismatch - ABORT"
bearer="Bearer "+token

ms=os.path.expanduser("~/.claude/mcp_settings.json")
d=json.load(open(ms))
entry=d["mcpServers"]["advancedmd"]
before=entry["headers"].get("Authorization","")
before_h=hashlib.sha256(before.replace("Bearer ","").strip().encode()).hexdigest() if before else "(none)"
# backup
bak=ms+".bak-tokenfix-"+time.strftime("%Y%m%d-%H%M%S")
shutil.copy2(ms,bak)
entry.setdefault("type","http")
entry["url"]="https://claude-cloud.tail053faf.ts.net:8443/advancedmd/mcp"
entry.setdefault("headers",{})["Authorization"]=bearer
json.dump(d,open(ms,"w"),indent=2)
print(f"mcp_settings.json: backup={bak}")
print(f"  before token sha256={before_h}")
print(f"  after  token sha256={expected}")

# repair empty stub in ~/.claude.json if present
cj=os.path.expanduser("~/.claude.json")
try:
    dd=json.load(open(cj))
except Exception as e:
    dd=None
    print(f"~/.claude.json: load err {e}")
def fix_claude_json(o):
    changed=False
    if isinstance(o,dict):
        for k,v in list(o.items()):
            if k=="advancedmd" and isinstance(v,dict):
                if not v.get("url") or not (v.get("headers") or {}).get("Authorization"):
                    v["type"]="http"
                    v["url"]="https://claude-cloud.tail053faf.ts.net:8443/advancedmd/mcp"
                    v.setdefault("headers",{})["Authorization"]=bearer
                    changed=True
            if isinstance(v,(dict,list)):
                if fix_claude_json(v): changed=True
    elif isinstance(o,list):
        for x in o:
            if fix_claude_json(x): changed=True
    return changed
if dd is not None:
    bak2=cj+".bak-tokenfix-"+time.strftime("%Y%m%d-%H%M%S")
    shutil.copy2(cj,bak2)
    if fix_claude_json(dd):
        json.dump(dd,open(cj,"w"),indent=2)
        print(f"~/.claude.json: repaired advancedmd stub, backup={bak2}")
    else:
        os.remove(bak2)
        print("~/.claude.json: advancedmd stub already ok or not present, no change")
print("FIX_DONE")
PY
