import sys,json,pathlib,urllib.request,urllib.parse,hashlib,base64,secrets
port,pairfile,out=sys.argv[1:]
origin='http://127.0.0.1:'+port
redirect='http://localhost:51234/callback'
def post(path,data,form=False):
    body=urllib.parse.urlencode(data).encode() if form else json.dumps(data).encode()
    req=urllib.request.Request(origin+path,data=body,headers={'Content-Type':'application/x-www-form-urlencoded' if form else 'application/json'})
    try:
        with urllib.request.urlopen(req) as r:return json.load(r)
    except urllib.error.HTTPError as e:
        print(e.code,e.read().decode());raise
client=post('/oauth/mcp/register',{'client_name':'Project create proof','redirect_uris':[redirect],'grant_types':['authorization_code','refresh_token'],'token_endpoint_auth_method':'none'})
verifier=secrets.token_urlsafe(48)
challenge=base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=')
params={'response_type':'code','client_id':client['client_id'],'redirect_uri':redirect,'code_challenge':challenge,'code_challenge_method':'S256','state':'proof','resource':origin+'/mcp'}
result=post('/oauth/mcp/decision',{'authorization':params,'decision':{'_tag':'pairing-code','access':'full-access','code':json.loads(pathlib.Path(pairfile).read_text())['credential']}})
code=urllib.parse.parse_qs(urllib.parse.urlparse(result['redirectTo']).query)['code'][0]
token=post('/oauth/mcp/token',{'grant_type':'authorization_code','code':code,'redirect_uri':redirect,'client_id':client['client_id'],'code_verifier':verifier,'resource':origin+'/mcp'},True)
pathlib.Path(out).write_text(token['access_token'])
print('MCP OAuth authorization completed')
