#!/usr/bin/env python3
"""
Gmail OAuth Setup Helper
This script helps you complete the initial OAuth flow to obtain a refresh token
for the Gmail MCP server.
Usage:
1. Download credentials.json from Google Cloud Console
2. Place it in this directory
3. Run: python oauth_setup.py
4. Follow the browser prompts to authorize
5. Copy the refresh token displayed at the end
6. Store in OpenBao with the command shown
"""
import os
import sys
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# Gmail API scope - full mailbox access
SCOPES = ['https://www.googleapis.com/auth/gmail.modify']
def main():
"""Run OAuth flow and display refresh token."""
credentials_path = 'credentials.json'
if not os.path.exists(credentials_path):
print("❌ Error: credentials.json not found!")
print("\nPlease download your OAuth credentials from Google Cloud Console:")
print("1. Go to https://console.cloud.google.com/")
print("2. Navigate to APIs & Services > Credentials")
print("3. Create OAuth client ID (Desktop app)")
print("4. Download credentials.json")
print("5. Place it in this directory")
sys.exit(1)
print("🔐 Starting Gmail OAuth Flow...")
print(f"📋 Scopes requested: {', '.join(SCOPES)}")
print("\nA browser window will open for authorization...")
print("Please log in with your Google account and grant access.\n")
try:
flow = InstalledAppFlow.from_client_secrets_file(
credentials_path,
SCOPES
)
creds = flow.run_local_server(port=0)
print("\n✅ OAuth flow completed successfully!")
print("\n" + "="*70)
print("📝 CREDENTIALS TO STORE IN OPENBAO")
print("="*70)
# Extract client ID and secret from credentials file
import json
with open(credentials_path) as f:
creds_data = json.load(f)
client_id = creds_data['installed']['client_id']
client_secret = creds_data['installed']['client_secret']
print(f"\nClient ID: {client_id}")
print(f"Client Secret: {client_secret}")
print(f"Refresh Token: {creds.refresh_token}")
# Determine username from git config
import subprocess
try:
result = subprocess.run(
["git", "config", "user.email"],
capture_output=True,
text=True,
timeout=2
)
if result.returncode == 0:
email = result.stdout.strip()
username = email.split('@')[0]
else:
username = os.getenv("USER", "unknown")
except:
username = os.getenv("USER", "unknown")
print("\n" + "="*70)
print("🔧 STORE IN OPENBAO")
print("="*70)
print("\nRun this command to store credentials:\n")
print(f'bao kv put secret/client0/prod-mcp-gmail-{username} \\')
print(f' client_id="{client_id}" \\')
print(f' client_secret="{client_secret}" \\')
print(f' refresh_token="{creds.refresh_token}"')
print("\n" + "="*70)
print("\n✅ Setup complete! Run the command above to finish configuration.")
except Exception as e:
print(f"\n❌ Error during OAuth flow: {e}")
sys.exit(1)
if __name__ == "__main__":
main()