#!/usr/bin/env python3 """Terminal login and refresh-aware stdio MCP bridge for GoThru. Python stdlib only.""" import argparse import contextlib import getpass import http.client import math import json import os from pathlib import Path import re import stat import sys import tempfile import time import urllib.error import urllib.parse import urllib.request ISSUER = 'https://id.gothru.org/realms/gothru' TOKEN_URL = ISSUER + '/protocol/openid-connect/token' DEVICE_URL = ISSUER + '/protocol/openid-connect/auth/device' REVOKE_URL = ISSUER + '/protocol/openid-connect/revoke' MCP_URL = 'https://mcp.gothru.co/mcp' CLIENT_ID = 'gothru-mcp-agent' MAX_BODY = 32 * 1024 * 1024 class LoginError(Exception): pass class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): return None OPENER = urllib.request.build_opener(NoRedirect) def http_request(url, body, headers, timeout=140, method='POST'): req = urllib.request.Request(url, data=body, headers=headers, method=method) try: response = OPENER.open(req, timeout=timeout) except urllib.error.HTTPError as exc: response = exc except (OSError, urllib.error.URLError): raise LoginError('GoThru could not be reached. Your saved credentials were retained.') from None with response: try: raw = response.read(MAX_BODY + 1) except (OSError, http.client.HTTPException): raise LoginError('GoThru response was interrupted. The operation was not retried.') from None if len(raw) > MAX_BODY: raise LoginError('GoThru returned an oversized response.') return response.code, dict(response.headers.items()), raw def oauth(url, fields): status, _, raw = http_request(url, urllib.parse.urlencode(fields).encode(), {'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'}, timeout=30) try: result = json.loads(raw) except (ValueError, UnicodeError): raise LoginError('The identity service returned an invalid response.') from None if not isinstance(result, dict): raise LoginError('The identity service returned an invalid response.') if status != 200: code = result.get('error') allowed = {'authorization_pending', 'slow_down', 'access_denied', 'expired_token', 'invalid_grant', 'invalid_client', 'unauthorized_client', 'invalid_scope'} raise LoginError(code if code in allowed else 'identity_service_error') return result class Credentials: def __init__(self, profile='default', directory=None): if not re.fullmatch(r'[A-Za-z0-9_-]{1,64}', profile): raise LoginError('Profile names can contain only letters, numbers, underscores and hyphens.') self.directory = Path(directory or (Path.home() / '.config' / 'gothru-mcp')) self.path = self.directory / (profile + '.json') self.lock_path = self.directory / (profile + '.lock') def prepare_directory(self): self.directory.mkdir(mode=0o700, parents=True, exist_ok=True) s = self.directory.lstat() if not stat.S_ISDIR(s.st_mode) or s.st_uid != os.getuid() or s.st_mode & 0o077: raise LoginError('The GoThru credentials directory must be owned by you with mode 700.') @contextlib.contextmanager def locked(self): import fcntl self.prepare_directory() fd = os.open(self.lock_path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600) try: s = os.fstat(fd) if not stat.S_ISREG(s.st_mode) or s.st_uid != os.getuid() or s.st_mode & 0o077: raise LoginError('Unsafe GoThru credentials lock file.') fcntl.flock(fd, fcntl.LOCK_EX) yield finally: os.close(fd) def load(self): try: fd = os.open(self.path, os.O_RDONLY | os.O_NOFOLLOW) with os.fdopen(fd) as f: s = os.fstat(f.fileno()) if not stat.S_ISREG(s.st_mode) or s.st_uid != os.getuid() or s.st_mode & 0o077 or s.st_size > 128 * 1024: raise LoginError('Unsafe GoThru credentials file; expected your private mode-600 file.') v = json.load(f) except FileNotFoundError: raise LoginError('Sign in first: python3 gothru_mcp_agent.py login') from None except (ValueError, OSError): raise LoginError('GoThru credentials cannot be read safely. Sign in again.') from None if (not isinstance(v, dict) or v.get('issuer') != ISSUER or v.get('client_id') != CLIENT_ID or not isinstance(v.get('refresh_token'), str) or not v['refresh_token'] or type(v.get('expires_at')) not in [int, float] or not math.isfinite(v['expires_at'])): raise LoginError('Invalid GoThru credentials. Sign in again.') return v def save(self, v): self.prepare_directory() fd, name = tempfile.mkstemp(prefix='.gothru-', dir=self.directory) try: with os.fdopen(fd, 'w') as f: os.fchmod(f.fileno(), 0o600) json.dump(v, f) f.flush() os.fsync(f.fileno()) os.replace(name, self.path) directory_fd = os.open(self.directory, os.O_RDONLY | os.O_DIRECTORY) try: os.fsync(directory_fd) finally: os.close(directory_fd) finally: if os.path.exists(name): os.unlink(name) def access_token(self, force=False): with self.locked(): current = self.load() if not force and isinstance(current.get('access_token'), str) and current.get('expires_at', 0) > time.time() + 45: return current['access_token'] try: result = oauth(TOKEN_URL, {'grant_type': 'refresh_token', 'client_id': CLIENT_ID, 'refresh_token': current['refresh_token']}) except LoginError as exc: if str(exc) in ['invalid_grant', 'invalid_client', 'unauthorized_client']: raise LoginError('Your GoThru session ended or was revoked. Run login again.') from None raise # Never reuse a previous refresh token after a successful exchange. updated = token_record(result) self.save(updated) return updated['access_token'] def token_record(result): if (not isinstance(result.get('access_token'), str) or not result['access_token'] or not isinstance(result.get('refresh_token'), str) or not result['refresh_token'] or str(result.get('token_type', '')).lower() != 'bearer' or type(result.get('expires_in')) is not int or not 0 < result['expires_in'] <= 86400): raise LoginError('The identity service did not return a renewable GoThru session.') return {'issuer': ISSUER, 'client_id': CLIENT_ID, 'access_token': result['access_token'], 'refresh_token': result['refresh_token'], 'expires_at': time.time() + result['expires_in']} def login(args, credentials): scope = 'openid profile email tours.read' + (' tours.write' if args.write else '') if args.method == 'password': username = args.username or input('GoThru email or username: ').strip() if args.password_stdin: password = sys.stdin.readline().rstrip('\r\n') else: if not sys.stdin.isatty(): raise LoginError('Use a terminal password prompt, or --password-stdin with a secret-manager pipe.') password = getpass.getpass('GoThru password: ') try: result = oauth(TOKEN_URL, {'grant_type': 'password', 'client_id': CLIENT_ID, 'username': username, 'password': password, 'scope': scope}) except LoginError as exc: if str(exc) == 'invalid_grant': raise LoginError('Sign-in failed. Check your password or use --method device for Google sign-in or required account actions.') from None raise finally: password = None else: device = oauth(DEVICE_URL, {'client_id': CLIENT_ID, 'scope': scope}) verification = device.get('verification_uri_complete') or device.get('verification_uri') uri = urllib.parse.urlsplit(verification or '') if uri.scheme != 'https' or uri.netloc != 'id.gothru.org' or not device.get('device_code') or not device.get('user_code'): raise LoginError('Invalid GoThru device authorization response.') print('Open this address on your own computer or phone:\n' + verification, file=sys.stderr) print('Confirmation code: ' + str(device['user_code']), file=sys.stderr) interval = max(5, min(int(device.get('interval', 5)), 60)) deadline = time.monotonic() + min(int(device.get('expires_in', 600)), 900) while True: time.sleep(interval) if time.monotonic() >= deadline: raise LoginError('The device sign-in request expired. Run login again.') try: result = oauth(TOKEN_URL, {'grant_type': 'urn:ietf:params:oauth:grant-type:device_code', 'client_id': CLIENT_ID, 'device_code': device['device_code']}) break except LoginError as exc: if str(exc) == 'authorization_pending': continue if str(exc) == 'slow_down': interval += 5 continue raise with credentials.locked(): credentials.save(token_record(result)) print('GoThru sign-in saved. Claude/Codex can now use the serve command.', file=sys.stderr) def decode_mcp_response(headers, raw, request_id): content_type = next((v for k, v in headers.items() if k.lower() == 'content-type'), '') if 'text/event-stream' not in content_type: try: return json.loads(raw) if raw else None except (ValueError, UnicodeError): raise LoginError('MCP returned invalid JSON.') from None for event in raw.decode('utf-8').replace('\r\n', '\n').split('\n\n'): lines = [line[5:].lstrip() for line in event.splitlines() if line.startswith('data:')] if lines: try: value = json.loads('\n'.join(lines)) except ValueError: continue if isinstance(value, dict) and value.get('id') == request_id: return value raise LoginError('MCP did not return a matching response.') class Bridge: def __init__(self, credentials): self.credentials = credentials self.session_id = None self.initialize_request = None self.protocol = '2025-06-18' def send(self, message, retry=True): token = self.credentials.access_token() headers = {'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json', 'Accept': 'application/json, text/event-stream', 'MCP-Protocol-Version': self.protocol} if self.session_id: headers['Mcp-Session-Id'] = self.session_id status, response_headers, raw = http_request(MCP_URL, json.dumps(message).encode(), headers) if status == 401 and retry: self.credentials.access_token(force=True) return self.send(message, retry=False) if status == 404 and self.session_id and self.initialize_request and retry: # The server rejected this unknown session before executing any tool. self.session_id = None self.send(self.initialize_request, retry=False) self.send({'jsonrpc':'2.0','method':'notifications/initialized'}, retry=False) return self.send(message, retry=False) if status in [401, 403]: raise LoginError('GoThru rejected this session or permission. Sign in again if your account changed.') if status not in [200, 202, 204]: raise LoginError('MCP request failed (HTTP %d).' % status) sid = next((v for k, v in response_headers.items() if k.lower() == 'mcp-session-id'), None) if sid: self.session_id = sid value = decode_mcp_response(response_headers, raw, message.get('id')) if message.get('method') == 'initialize': self.initialize_request = message if isinstance(value, dict): self.protocol = value.get('result', {}).get('protocolVersion', self.protocol) return value def close(self): if not self.session_id: return # Delete only this MCP transport; keep the reusable native agent login. try: with self.credentials.locked(): current = self.credentials.load() if current.get('access_token') and current['expires_at'] > time.time(): http_request(MCP_URL, None, {'Authorization':'Bearer '+current['access_token'], 'Mcp-Session-Id':self.session_id,'MCP-Protocol-Version':self.protocol},timeout=5,method='DELETE') except (LoginError, OSError): pass self.session_id = None def serve(credentials): bridge = Bridge(credentials) try: for line in sys.stdin: if len(line) > MAX_BODY: raise LoginError('Oversized MCP request.') request = None try: request = json.loads(line) if not isinstance(request, dict) or request.get('jsonrpc') != '2.0': raise LoginError('Invalid MCP request.') response = bridge.send(request) if 'id' in request and response is not None: print(json.dumps(response), flush=True) except (LoginError, ValueError): print('GoThru MCP request failed. Check connectivity or run login again.', file=sys.stderr) if isinstance(request, dict) and 'id' in request: print(json.dumps({'jsonrpc':'2.0','id':request['id'],'error':{'code':-32001, 'message':'GoThru authentication or connection failed. Run the helper login command again.'}}), flush=True) finally: bridge.close() def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--profile', default='default') commands = parser.add_subparsers(dest='command', required=True) p = commands.add_parser('login') p.add_argument('--method', choices=['password','device'], default='password') p.add_argument('--username') p.add_argument('--password-stdin', action='store_true') p.add_argument('--write', action='store_true', help='Request optional write scope; current tool permissions still apply') commands.add_parser('serve') commands.add_parser('status') commands.add_parser('logout') args = parser.parse_args() credentials = Credentials(args.profile) if args.command == 'login': login(args, credentials) elif args.command == 'serve': serve(credentials) elif args.command == 'status': credentials.access_token() print('GoThru sign-in is ready; automatic refresh is enabled.') else: with credentials.locked(): current = credentials.load() status, _, _ = http_request(REVOKE_URL, urllib.parse.urlencode({'client_id':CLIENT_ID, 'token':current['refresh_token'],'token_type_hint':'refresh_token'}).encode(), {'Content-Type':'application/x-www-form-urlencoded'},timeout=30) if status != 200: raise LoginError('The login could not be revoked; local credentials were retained.') credentials.path.unlink() print('This agent login was revoked and its local credentials removed.') if __name__ == '__main__': try: main() except (LoginError, KeyboardInterrupt) as error: print('GoThru: ' + (str(error) if isinstance(error, LoginError) else 'Cancelled.'), file=sys.stderr) sys.exit(1)