#!/usr/bin/env python3
import json,sys,uuid,urllib.request,os
config=None
sid=str(uuid.uuid4())
def send(x):
 print(json.dumps(x),flush=True)
def probe():
 env={x['name']:x['value'] for x in config['env']}
 headers={'Authorization':env['T3_ACP_MCP_AUTHORIZATION'],'Content-Type':'application/json','Accept':'application/json, text/event-stream'}
 def rpc(method,params,i):
  req=urllib.request.Request(env['T3_ACP_MCP_ENDPOINT'],json.dumps({'jsonrpc':'2.0','id':i,'method':method,'params':params}).encode(),headers)
  with urllib.request.urlopen(req) as r:
   if r.headers.get('mcp-session-id'): headers['mcp-session-id']=r.headers['mcp-session-id']
   raw=r.read().decode()
   if raw.startswith('event:') or raw.startswith('data:'):
    return json.loads(next(l[5:].strip() for l in raw.splitlines() if l.startswith('data:')))
   return json.loads(raw)
 rpc('initialize',{'protocolVersion':'2025-06-18','capabilities':{},'clientInfo':{'name':'capability-probe','version':'1'}},1)
 headers['mcp-protocol-version']='2025-06-18'
 listed=rpc('tools/list',{},2)
 names=sorted(x['name'] for x in listed['result']['tools'])
 report={'settings':{'enableAgentBrowserAccess':False,'enableAgentDeviceAccess':False},'transport':'real HTTP /mcp with server-issued thread credential','listedToolCount':len(names),'previewTools':[n for n in names if n.startswith('preview_')],'deviceTools':[n for n in names if n.startswith('device_')],'calls':{}}
 for i,n in enumerate(['preview_status','device_list'],3): report['calls'][n]=rpc('tools/call',{'name':n,'arguments':{}},i)
 out=os.environ.get('PROBE_REPORT')
 if out: open(out,'w').write(json.dumps(report,indent=2)+'\n')
 return json.dumps(report,indent=2)
for line in sys.stdin:
 try:
  msg=json.loads(line); method=msg.get('method'); p=msg.get('params',{})
  if 'id' not in msg: continue
  result={}
  if method=='initialize': result={'protocolVersion':1,'agentCapabilities':{'loadSession':True},'authMethods':[],'agentInfo':{'name':'capability-probe','version':'1'}}
  elif method in ['session/new','session/load']:
   config=next(x for x in p['mcpServers'] if x['name']=='t3-code')
   result={'sessionId':sid,'models':{'currentModelId':'probe','availableModels':[{'modelId':'probe','name':'Capability probe'}]}}
  elif method=='session/prompt':
   text=probe()
   send({'jsonrpc':'2.0','method':'session/update','params':{'sessionId':sid,'update':{'sessionUpdate':'agent_message_chunk','content':{'type':'text','text':text}}}})
   result={'stopReason':'end_turn'}
  send({'jsonrpc':'2.0','id':msg['id'],'result':result})
 except Exception as e:
  print(str(e),file=sys.stderr,flush=True)
  send({'jsonrpc':'2.0','id':msg.get('id'),'error':{'code':-32603,'message':str(e)}})
