import os,sys,subprocess,json
port,tool=sys.argv[1:3]
for pid in os.listdir('/proc'):
  if not pid.isdigit(): continue
  try:
    env=dict(s.split('=',1) for s in open('/proc/'+pid+'/environ').read().split('\0') if '=' in s)
    if env.get('T3_ACP_MCP_ENDPOINT') != 'http://127.0.0.1:'+port+'/mcp': continue
    if not env.get('T3_ACP_MCP_AUTHORIZATION'): continue
    args=json.loads(sys.argv[3]) if len(sys.argv)>3 else {}
    subprocess.run(['node','apps/server/src/bin.ts','acp-mcp-call',tool,json.dumps(args)],env={**os.environ,**{k:v for k,v in env.items() if k.startswith('T3_ACP_MCP_')}},check=True)
    break
  except (FileNotFoundError,PermissionError,ProcessLookupError): pass
else: raise Exception('Active Replay MCP session not found')
