test_auth.pyโข4.42 kB
#!/usr/bin/env python3
"""
Test authentication for Google Drive MCP Server
This script tests the OAuth flow and creates the token.json file.
"""
from pathlib import Path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
SCOPES = ['https://www.googleapis.com/auth/drive']
def test_authentication():
"""Test Google Drive authentication."""
print("๐ Testing Google Drive Authentication")
print("=" * 50)
print()
token_path = Path.home() / '.google-drive-mcp' / 'token.json'
credentials_path = Path.home() / '.google-drive-mcp' / 'credentials.json'
# Check if credentials file exists
if not credentials_path.exists():
print(f"โ ERROR: Credentials file not found!")
print(f"Expected location: {credentials_path}")
print()
print("Please:")
print("1. Download your OAuth credentials from Google Cloud Console")
print("2. Save it as credentials.json in ~/.google-drive-mcp/")
return False
print(f"โ
Found credentials file: {credentials_path}")
print()
creds = None
# Check for existing token
if token_path.exists():
print(f"๐ Found existing token: {token_path}")
print("Loading existing credentials...")
creds = Credentials.from_authorized_user_file(str(token_path), SCOPES)
print()
# If no valid credentials, authenticate
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
print("๐ Refreshing expired token...")
creds.refresh(Request())
print("โ
Token refreshed successfully!")
else:
print("๐ Starting OAuth authentication flow...")
print()
print("๐ A browser window will open shortly.")
print(" Please sign in and authorize the app.")
print()
try:
flow = InstalledAppFlow.from_client_secrets_file(
str(credentials_path), SCOPES)
creds = flow.run_local_server(port=0)
print()
print("โ
Authentication successful!")
except Exception as e:
print(f"โ Authentication failed: {e}")
return False
# Save credentials for next run
print(f"๐พ Saving token to: {token_path}")
with open(token_path, 'w') as token:
token.write(creds.to_json())
print("โ
Token saved!")
else:
print("โ
Existing credentials are valid!")
print()
print("๐งช Testing API access...")
try:
# Build the service and make a test API call
service = build('drive', 'v3', credentials=creds)
# Try to list files in root (just get the first one)
results = service.files().list(
pageSize=1,
fields="files(id, name)"
).execute()
files = results.get('files', [])
print("โ
Successfully connected to Google Drive API!")
print()
if files:
print(f"Test successful! Found file: '{files[0]['name']}'")
else:
print("Test successful! (No files found in root, but connection works)")
print()
print("=" * 50)
print("โจ All tests passed!")
print()
print("Next steps:")
print("1. Configure Claude Desktop (see SETUP_GUIDE.md Step 4)")
print("2. Restart Claude Desktop")
print("3. Try asking Claude to list your Drive contents")
return True
except Exception as e:
print(f"โ API test failed: {e}")
print()
print("Please check:")
print("- Google Drive API is enabled in Cloud Console")
print("- OAuth consent screen is configured")
print("- You authorized the correct Google account")
return False
if __name__ == "__main__":
try:
success = test_authentication()
exit(0 if success else 1)
except KeyboardInterrupt:
print("\n\nโ ๏ธ Authentication cancelled by user")
exit(1)
except Exception as e:
print(f"\n\nโ Unexpected error: {e}")
exit(1)