File size: 8,910 Bytes
c5c5634
 
 
 
 
 
 
 
 
 
 
 
 
b09e6c1
 
 
 
c5c5634
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b09e6c1
 
 
 
 
 
 
 
 
 
c5c5634
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
#!/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()