#!/usr/bin/env python3 """ OAuth Setup Utility for Gmail MCP Server This script helps users set up OAuth authentication for the Gmail MCP server. """ import sys import os import json from pathlib import Path from oauth_manager import oauth_manager from logger import logger from dotenv import load_dotenv load_dotenv() import os def print_banner(): """Print setup banner""" print("=" * 60) print("šŸ“§ Gmail MCP Server - OAuth Setup") print("=" * 60) print() def print_step(step_num: int, title: str): """Print step header""" print(f"\nšŸ”¹ Step {step_num}: {title}") print("-" * 50) def check_dependencies(): """Check if required dependencies are installed""" try: import google.auth import google_auth_oauthlib import googleapiclient import cryptography print("āœ… All required dependencies are installed") return True except ImportError as e: print(f"āŒ Missing dependency: {e}") print("\nPlease install the required dependencies:") print("pip install google-auth google-auth-oauthlib google-api-python-client cryptography") return False def setup_google_cloud_project(): """Guide user through Google Cloud project setup""" print_step(1, "Google Cloud Project Setup") print("You need to create a Google Cloud project and enable the Gmail API.") print("\nšŸ“‹ Follow these steps:") print("1. Go to: https://console.cloud.google.com/") print("2. Create a new project or select an existing one") print("3. Enable the Gmail API:") print(" - Go to 'APIs & Services' > 'Library'") print(" - Search for 'Gmail API'") print(" - Click 'Enable'") input("\nāœ… Press Enter when you've completed these steps...") def setup_oauth_consent(): """Guide user through OAuth consent screen setup""" print_step(2, "OAuth Consent Screen Setup") print("Now you need to configure the OAuth consent screen.") print("\nšŸ“‹ Follow these steps:") print("1. Go to: https://console.cloud.google.com/apis/credentials/consent") print("2. Choose 'External' user type (unless using Google Workspace)") print("3. Fill in the app information:") print(" - App name: 'Gmail MCP Server' (or your preferred name)") print(" - User support email: Your email address") print(" - Developer contact: Your email address") print("4. Add these scopes:") print(" - https://www.googleapis.com/auth/gmail.readonly") print(" - https://www.googleapis.com/auth/gmail.modify") print("5. Add your email as a test user") print("6. Complete the setup") input("\nāœ… Press Enter when you've completed these steps...") def setup_oauth_credentials(): """Guide user through OAuth credentials setup""" print_step(3, "OAuth Client Credentials Setup") client_id = os.getenv("GOOGLE_CLIENT_ID") client_secret = os.getenv("GOOGLE_CLIENT_SECRET") if not client_id or not client_secret: print("āŒ Missing GOOGLE_CLIENT_ID or GOOGLE_CLIENT_SECRET in your .env") print(" Please add:") print(" GOOGLE_CLIENT_ID=your-client-id") print(" GOOGLE_CLIENT_SECRET=your-client-secret") return False try: oauth_manager.setup_client_secrets(client_id, client_secret) print("āœ… OAuth credentials saved successfully") return True except Exception as e: print(f"āŒ Failed to save credentials: {e}") return False def test_authentication(): """Test the OAuth authentication flow""" print_step(4, "Authentication Test") print("Now let's test the authentication flow.") print("This will open your web browser for authentication.") confirm = input("\n🌐 Ready to open browser for authentication? (y/n): ").strip().lower() if confirm != 'y': print("Authentication test skipped.") return False try: print("\nšŸ”„ Starting authentication flow...") success = oauth_manager.authenticate_interactive() if success: print("āœ… Authentication successful!") # Test getting user info user_email = oauth_manager.get_user_email() if user_email: print(f"āœ… Authenticated as: {user_email}") return True else: print("āŒ Authentication failed") return False except Exception as e: print(f"āŒ Authentication error: {e}") return False def show_completion_info(): """Show completion information and next steps""" print("\n" + "=" * 60) print("šŸŽ‰ Setup Complete!") print("=" * 60) print("\nāœ… Your Gmail MCP server is now configured with OAuth authentication!") print("\nšŸ“ Next steps:") print("1. Start the MCP server:") print(" python email_mcp_server_oauth.py") print("\n2. Configure Claude Desktop:") print(' Add this to your MCP configuration:') print(' {') print(' "mcpServers": {') print(' "gmail-oauth": {') print(' "command": "npx",') print(' "args": ["mcp-remote", "http://localhost:7860/gradio_api/mcp/sse"]') print(' }') print(' }') print(' }') print("\nšŸ” Security notes:") print("- Your credentials are encrypted and stored locally") print("- Tokens are automatically refreshed when needed") print("- You can revoke access anytime from Google Account settings") credentials_dir = oauth_manager.credentials_dir print(f"\nšŸ“ Credentials stored in: {credentials_dir}") def show_help(): """Show help information""" print("Gmail MCP Server OAuth Setup") print("\nUsage:") print(" python setup_oauth.py # Full interactive setup") print(" python setup_oauth.py --help # Show this help") print(" python setup_oauth.py --auth # Re-authenticate only") print(" python setup_oauth.py --status # Check authentication status") print(" python setup_oauth.py --clear # Clear stored credentials") def check_status(): """Check authentication status""" print("šŸ” Checking authentication status...") if oauth_manager.is_authenticated(): user_email = oauth_manager.get_user_email() print(f"āœ… Authenticated as: {user_email}") return True else: print("āŒ Not authenticated") return False def clear_credentials(): """Clear stored credentials""" confirm = input("āš ļø This will clear all stored credentials. Continue? (y/n): ").strip().lower() if confirm == 'y': oauth_manager.clear_credentials() print("āœ… Credentials cleared") else: print("Operation cancelled") def main(): """Main setup function""" if len(sys.argv) > 1: arg = sys.argv[1].lower() if arg in ['--help', '-h', 'help']: show_help() return elif arg == '--status': check_status() return elif arg == '--auth': print("šŸ”„ Starting re-authentication...") if test_authentication(): print("āœ… Re-authentication successful") else: print("āŒ Re-authentication failed") return elif arg == '--clear': clear_credentials() return else: print(f"Unknown argument: {arg}") show_help() return # Full interactive setup print_banner() # Check if already authenticated if oauth_manager.is_authenticated(): user_email = oauth_manager.get_user_email() print(f"āœ… Already authenticated as: {user_email}") choice = input("\nšŸ”„ Do you want to re-authenticate? (y/n): ").strip().lower() if choice == 'y': if test_authentication(): show_completion_info() else: print("Setup complete - you're already authenticated!") return # Check dependencies if not check_dependencies(): return # Full setup flow try: setup_google_cloud_project() setup_oauth_consent() if not setup_oauth_credentials(): print("āŒ Setup failed at credentials step") return if test_authentication(): show_completion_info() else: print("āŒ Setup completed but authentication test failed") print("You can try authentication later with: python setup_oauth.py --auth") except KeyboardInterrupt: print("\n\nāš ļø Setup interrupted by user") except Exception as e: print(f"\nāŒ Setup failed: {e}") if __name__ == "__main__": main()