#!/usr/bin/env python3 """Phone-authorized Prize Bot MCP adapter. Requires Python 3.10+; no packages.""" import argparse import contextlib import hashlib import json import os from pathlib import Path import shutil import subprocess import sys import tempfile import time import urllib.error import urllib.parse import urllib.request DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code" DEFAULT_ENDPOINT = "https://api.prizebot.dev/api/mcp" MAX_BODY = 256 * 1024 MAX_RESPONSE = 8 * 1024 * 1024 class OAuthError(Exception): def __init__(self, code, status=400): self.code, self.status = code, status super().__init__(code) class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): return None def origin(url): value = urllib.parse.urlsplit(url) if not value.hostname or value.username or value.password or value.fragment: raise ValueError("URL must not contain credentials or a fragment.") if value.scheme != "https" and not ( value.scheme == "http" and value.hostname in ("127.0.0.1", "::1", "localhost") ): raise ValueError("HTTPS is required outside local development.") return f"{value.scheme}://{value.netloc}" def trusted(url, issuer): if origin(url) != issuer: raise ValueError("OAuth endpoint does not match the trusted API origin.") return url class API: def __init__(self): self.opener = urllib.request.build_opener(NoRedirect()) def request(self, url, *, form=None, data=None, token=None, protocol=None): headers = {"Accept": "application/json, text/event-stream", "User-Agent": "prizebot-mcp/1.0"} body = None if form is not None: body = urllib.parse.urlencode(form).encode() headers["Content-Type"] = "application/x-www-form-urlencoded" elif data is not None: body = json.dumps(data, separators=(",", ":")).encode() headers["Content-Type"] = "application/json" if token: headers["Authorization"] = "Bearer " + token if protocol: headers["MCP-Protocol-Version"] = protocol try: with self.opener.open(urllib.request.Request(url, data=body, headers=headers), timeout=30) as response: content = response.read(MAX_RESPONSE + 1) if len(content) > MAX_RESPONSE: raise ValueError("Remote response exceeds 8 MiB.") return json.loads(content) if content else None except urllib.error.HTTPError as error: # Never include response bodies, tokens, or authorization headers in logs. try: code = json.loads(error.read(4096)).get("error") except (ValueError, AttributeError): code = None known = {"authorization_pending", "slow_down", "access_denied", "expired_token", "invalid_grant", "invalid_client", "invalid_scope", "invalid_target", "insufficient_scope"} raise OAuthError(code if isinstance(code, str) and code in known else f"HTTP {error.code}", error.code) from None class Store: def __init__(self, endpoint, home=None): self.root = Path(home or os.environ.get("PRIZEBOT_MCP_HOME", Path.home() / ".config/prizebot/mcp")) self.root.mkdir(parents=True, exist_ok=True, mode=0o700) os.chmod(self.root, 0o700) self.path = self.root / (hashlib.sha256(endpoint.encode()).hexdigest() + ".json") self.lock_path = self.path.with_suffix(".lock") @contextlib.contextmanager def locked(self): import fcntl fd = os.open(self.lock_path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600) with os.fdopen(fd, "a+") as lock: fcntl.flock(lock, fcntl.LOCK_EX) try: yield finally: fcntl.flock(lock, fcntl.LOCK_UN) def read(self): try: fd = os.open(self.path, os.O_RDONLY | os.O_NOFOLLOW) except FileNotFoundError: raise ValueError("Not connected. Ask your agent to run the setup command.") from None with os.fdopen(fd) as file: stat = os.fstat(file.fileno()) if stat.st_uid != os.getuid() or stat.st_mode & 0o077: raise ValueError("Credential file must be owned by this user with mode 0600.") return json.load(file) def write(self, state): fd, name = tempfile.mkstemp(dir=self.root, prefix=".credentials-") try: with os.fdopen(fd, "w") as file: json.dump(state, file) file.flush() os.fsync(file.fileno()) os.replace(name, self.path) finally: if os.path.exists(name): os.unlink(name) class Client: def __init__(self, endpoint, store=None, api=None): parsed = urllib.parse.urlsplit(endpoint) if parsed.query: raise ValueError("MCP endpoint must not have a query string.") self.endpoint, self.issuer = endpoint.rstrip("/"), origin(endpoint) self.store, self.api = store or Store(self.endpoint), api or API() # STDIO clients use initialize/initialized. July 2026 stateless HTTP # removes that handshake, so use the server's supported session-based # protocol at this transport boundary. self.protocol = "2025-11-25" def discover(self): path = urllib.parse.urlsplit(self.endpoint).path metadata = self.api.request(self.issuer + "/.well-known/oauth-protected-resource" + path) if metadata.get("resource") != self.endpoint or self.issuer not in metadata.get("authorization_servers", []): raise ValueError("Protected resource discovery does not match the requested server.") server = self.api.request(self.issuer + "/.well-known/oauth-authorization-server") if server.get("issuer") != self.issuer or DEVICE_GRANT not in server.get("grant_types_supported", []): raise ValueError("This server does not support phone pairing yet. Deploy the device-authorization update first.") for key in ("registration_endpoint", "device_authorization_endpoint", "token_endpoint", "revocation_endpoint"): trusted(server[key], self.issuer) return server def setup(self, scopes, name): server = self.discover() client = self.api.request(server["registration_endpoint"], data={ "client_name": name, "grant_types": [DEVICE_GRANT, "refresh_token"], "redirect_uris": [], "response_types": [], "token_endpoint_auth_method": "none", }) pairing = self.api.request(server["device_authorization_endpoint"], form={ "client_id": client["client_id"], "resource": self.endpoint, "scope": scopes, }) link = pairing["verification_uri_complete"] if origin(link) != origin(pairing["verification_uri"]) or urllib.parse.urlsplit(link).path != urllib.parse.urlsplit(pairing["verification_uri"]).path: raise ValueError("Pairing link does not match the verification endpoint.") print("Open this link on your phone and approve the requested access:", flush=True) print(link, flush=True) print("Connection code: " + pairing["user_code"], flush=True) interval = max(5, int(pairing.get("interval", 5))) deadline = time.monotonic() + min(600, int(pairing["expires_in"])) while time.monotonic() < deadline: time.sleep(interval) if time.monotonic() >= deadline: break try: tokens = self.api.request(server["token_endpoint"], form={ "grant_type": DEVICE_GRANT, "device_code": pairing["device_code"], "client_id": client["client_id"], "resource": self.endpoint, }) except OAuthError as error: if error.code == "authorization_pending": continue if error.code == "slow_down": interval += 5 continue raise except (TimeoutError, urllib.error.URLError): # A timeout after an exchange might have issued credentials. # Retrying a device code is safe (one-use); an unknown result # ends setup without replaying a rotating refresh credential. interval *= 2 continue with self.store.locked(): self.store.write({"endpoint": self.endpoint, "issuer": self.issuer, "client_id": client["client_id"], "token_endpoint": server["token_endpoint"], "revocation_endpoint": server["revocation_endpoint"], **tokens, "expires_at": time.time() + tokens["expires_in"], "refresh_pending": False}) return raise ValueError("Pairing expired. Ask your agent to start a new setup request.") def access_token(self): with self.store.locked(): state = self.store.read() if state.get("endpoint") != self.endpoint or state.get("issuer") != self.issuer: raise ValueError("Saved credentials belong to a different server.") if state.get("refresh_pending"): raise ValueError("The previous refresh outcome is uncertain. Reconnect through setup.") if state["expires_at"] <= time.time() + 60: trusted(state["token_endpoint"], self.issuer) # Persist the uncertain state before sending a single-use refresh # so a crash or network failure cannot cause token-family replay. state["refresh_pending"] = True self.store.write(state) tokens = self.api.request(state["token_endpoint"], form={ "grant_type": "refresh_token", "client_id": state["client_id"], "resource": self.endpoint, "refresh_token": state["refresh_token"], }) state.update(tokens) state.update(expires_at=time.time() + tokens["expires_in"], refresh_pending=False) self.store.write(state) return state["access_token"] def rpc(self, message): if message.get("method") == "initialize": message = {**message, "params": {**message.get("params", {}), "protocolVersion": self.protocol}} response = self.api.request(self.endpoint, data=message, token=self.access_token(), protocol=self.protocol) if message.get("method") == "initialize" and response and "result" in response: self.protocol = response["result"]["protocolVersion"] return response def verify(self): self.rpc({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": self.protocol, "capabilities": {}, "clientInfo": {"name": "prizebot-phone-adapter", "version": "1.0.0"}, }}) self.rpc({"jsonrpc": "2.0", "method": "notifications/initialized"}) for request_id, tool in ((2, "read_agent_guide"), (3, "prizebot_get_account")): response = self.rpc({"jsonrpc": "2.0", "id": request_id, "method": "tools/call", "params": {"name": tool, "arguments": {}}}) if not response or "error" in response or response.get("result", {}).get("isError"): raise ValueError("Authorization was saved, but verification failed. Check access before using tools.") def serve(self): while line := sys.stdin.buffer.readline(MAX_BODY + 1): message = None try: if len(line) > MAX_BODY: while not line.endswith(b"\n"): line = sys.stdin.buffer.readline(MAX_BODY + 1) if not line: break raise ValueError("MCP request exceeds 256 KiB.") message = json.loads(line) if not isinstance(message, dict) or message.get("jsonrpc") != "2.0": raise ValueError("Expected one JSON-RPC 2.0 message per line.") response = self.rpc(message) except (ValueError, KeyError, OAuthError, urllib.error.URLError, TimeoutError) as error: if not isinstance(message, dict) or "id" not in message: print("Prize Bot request failed. Check the connection or reconnect.", file=sys.stderr, flush=True) continue code = error.code if isinstance(error, OAuthError) else "remote_request_failed" response = {"jsonrpc": "2.0", "id": message["id"], "error": { "code": -32000, "message": f"Prize Bot: {code}. Check access. If a write was sent, inspect its result before retrying.", }} if response is not None and isinstance(message, dict) and "id" in message: print(json.dumps(response, separators=(",", ":")), flush=True) def install_codex(endpoint): codex = shutil.which("codex") if not codex: raise ValueError("Codex CLI was not found. Credentials are saved; install the CLI before registering the adapter.") target = Path.home() / ".local/share/prizebot/mcp/prizebot_mcp.py" target.parent.mkdir(parents=True, exist_ok=True, mode=0o700) source = Path(__file__).resolve() if source != target.resolve(): fd, temp = tempfile.mkstemp(dir=target.parent) os.close(fd) try: shutil.copyfile(source, temp) os.chmod(temp, 0o700) os.replace(temp, target) finally: if os.path.exists(temp): os.unlink(temp) subprocess.run([codex, "mcp", "add", "prizebot", "--", sys.executable, str(target), "serve", "--endpoint", endpoint], check=True) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("command", choices=("setup", "serve", "status", "logout")) parser.add_argument("--endpoint", default=DEFAULT_ENDPOINT) parser.add_argument("--scopes", default="personal:read") parser.add_argument("--name", default="Prize Bot for Codex") parser.add_argument("--codex", action="store_true", help="Register the adapter after a successful setup") args = parser.parse_args() client = Client(args.endpoint) if args.command == "setup": client.setup(args.scopes, args.name) client.verify() if args.codex: install_codex(client.endpoint) print("Connected to Prize Bot. Start a new agent session to load its tools.", flush=True) elif args.command == "serve": client.serve() elif args.command == "status": client.verify() print("Connected to Prize Bot.") else: with client.store.locked(): state = client.store.read() client.api.request(trusted(state["revocation_endpoint"], client.issuer), form={"client_id": state["client_id"], "token": state["refresh_token"]}) client.store.path.unlink() print("Prize Bot access revoked and local credentials removed.") if __name__ == "__main__": try: main() except (ValueError, OAuthError, urllib.error.URLError, TimeoutError, subprocess.CalledProcessError, OSError) as error: if isinstance(error, OAuthError): reason = error.code elif isinstance(error, ValueError): reason = str(error) else: reason = "Connection or setup failed. Check network access and try setup again." print("Prize Bot: " + reason, file=sys.stderr) sys.exit(1)