# Scratch MCP JSON-RPC driver for #25723. Usage: python3 -I mcp.py <origin> <tokenfile> <workspace>
import json, sys, urllib.request
origin, tokenfile, workspace = sys.argv[1:4]
token = open(tokenfile).read().strip()
state = {"sid": None, "id": 0}
def post(msg):
    h = {"content-type": "application/json", "accept": "application/json, text/event-stream", "authorization": f"Bearer {token}"}
    if state["sid"]: h["mcp-session-id"] = state["sid"]; h["mcp-protocol-version"] = "2025-06-18"
    req = urllib.request.Request(origin + "/mcp", data=json.dumps(msg).encode(), headers=h, method="POST")
    with urllib.request.urlopen(req) as r:
        state["sid"] = r.headers.get("mcp-session-id") or state["sid"]
        body = r.read().decode()
    for line in body.splitlines():
        if line.startswith("data:"): return json.loads(line[5:])
    return json.loads(body) if body.strip() else None
def call(name, args):
    state["id"] += 1
    res = post({"jsonrpc": "2.0", "id": state["id"], "method": "tools/call", "params": {"name": name, "arguments": args}})["result"]
    out = res.get("structuredContent") or res.get("content")
    print(f"> {name} {json.dumps(args)}\n< isError={res.get('isError', False)} {json.dumps(out)[:600]}\n")
    return out
post({"jsonrpc": "2.0", "id": 0, "method": "initialize", "params": {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "issue-25723-driver", "version": "0"}}})
post({"jsonrpc": "2.0", "method": "notifications/initialized"})
caps = call("orchestrator_capabilities", {})
claude = next(p for p in caps["providers"] if p["providerInstanceId"] == "claudeAgent")
print("claudeAgent advertised:", [m["id"] for m in claude["models"]], "omitted", claude.get("omittedModels"), "\n")
project = call("t3_project_create", {"title": "issue-25723", "workspaceRoot": workspace})
pid = project.get("id")
thread = call("t3_thread_launch", {"title": "configure probe", "projectId": pid, "modelSelection": {"instanceId": "claudeAgent", "model": claude["models"][0]["id"]}})
tid = thread.get("threadId") or thread.get("thread", {}).get("id")
call("t3_thread_configure", {"threadId": tid, "modelSelection": {"instanceId": "claudeAgent", "model": "claude-issue-25723-unadvertised"}})
call("t3_thread_configure", {"threadId": tid, "modelSelection": {"instanceId": "codex", "model": "claude-issue-25723-unadvertised"}})
call("t3_thread_configure", {"threadId": tid, "modelSelection": {"instanceId": "missing-instance", "model": "x"}})
call("t3_thread_configure", {"threadId": tid})
call("t3_thread_configure", {"threadId": tid, "modelSelection": {"instanceId": "claudeAgent", "model": claude["models"][-1]["id"]}})
call("t3_thread_configure", {"threadId": tid})
