import json import os from pathlib import Path from google_auth_oauthlib.flow import InstalledAppFlow if os.name != "nt": os.umask(0o077) root = Path.home() / ".config" / "google-analytics-mcp" root.mkdir(parents=True, exist_ok=True) if os.name != "nt": root.chmod(0o700) client = json.loads( (root / "oauth_client.json").read_text(encoding="utf-8-sig") ) if "installed" not in client: raise SystemExit("Use an OAuth client JSON created for a Desktop app.") project = client["installed"].get("project_id") if not project: raise SystemExit("The OAuth client JSON is missing project_id.") flow = InstalledAppFlow.from_client_config( client, scopes=["https://www.googleapis.com/auth/analytics.readonly"], ) credentials = flow.run_local_server( port=0, prompt="consent", access_type="offline" ) if not credentials.refresh_token: raise SystemExit("Google did not return a refresh token. Authorise again.") data = json.loads(credentials.to_json()) data.update(type="authorized_user", quota_project_id=project) path = root / "credentials.json" path.write_text(json.dumps(data, indent=2), encoding="utf-8") if os.name != "nt": path.chmod(0o600) print("Credentials:", path) print("Project:", project)