|
| 1 | +import asyncio |
| 2 | +from typing import Optional |
| 3 | + |
| 4 | +import typer |
| 5 | +from rich.prompt import Confirm, Prompt |
| 6 | + |
| 7 | +from mcp_agent.cli.auth import ( |
| 8 | + UserCredentials, |
| 9 | + load_credentials, |
| 10 | + save_credentials, |
| 11 | +) |
| 12 | +from mcp_agent.cli.config import settings |
| 13 | +from mcp_agent.cli.core.api_client import APIClient |
| 14 | +from mcp_agent.cli.exceptions import CLIError |
| 15 | +from mcp_agent.cli.utils.ux import ( |
| 16 | + print_info, |
| 17 | + print_success, |
| 18 | + print_warning, |
| 19 | +) |
| 20 | + |
| 21 | +from .constants import DEFAULT_API_AUTH_PATH |
| 22 | + |
| 23 | + |
| 24 | +def _load_user_credentials(api_key: str) -> UserCredentials: |
| 25 | + """Load credentials with user profile data fetched from API. |
| 26 | +
|
| 27 | + Args: |
| 28 | + api_key: The API key |
| 29 | +
|
| 30 | + Returns: |
| 31 | + UserCredentials object with profile data if available |
| 32 | + """ |
| 33 | + |
| 34 | + async def fetch_profile() -> UserCredentials: |
| 35 | + """Fetch user profile from the API.""" |
| 36 | + client = APIClient(settings.API_BASE_URL, api_key) |
| 37 | + |
| 38 | + response = await client.post("user/get_profile", {}) |
| 39 | + user_data = response.json() |
| 40 | + |
| 41 | + user_profile = user_data.get("user", {}) |
| 42 | + |
| 43 | + return UserCredentials( |
| 44 | + api_key=api_key, |
| 45 | + username=user_profile.get("name"), |
| 46 | + email=user_profile.get("email"), |
| 47 | + ) |
| 48 | + |
| 49 | + try: |
| 50 | + return asyncio.run(fetch_profile()) |
| 51 | + except Exception as e: |
| 52 | + print_warning(f"Could not fetch user profile: {str(e)}") |
| 53 | + # Fallback to minimal credentials |
| 54 | + return UserCredentials(api_key=api_key) |
| 55 | + |
| 56 | + |
| 57 | +def login( |
| 58 | + api_key: Optional[str] = typer.Option( |
| 59 | + None, |
| 60 | + "--api-key", |
| 61 | + help="Optionally set an existing API key to use for authentication, bypassing manual login.", |
| 62 | + envvar="MCP_API_KEY", |
| 63 | + ), |
| 64 | + no_open: bool = typer.Option( |
| 65 | + False, |
| 66 | + "--no-open", |
| 67 | + help="Don't automatically open browser for authentication.", |
| 68 | + ), |
| 69 | +) -> str: |
| 70 | + """Authenticate to MCP Agent Cloud API. |
| 71 | +
|
| 72 | + Direct to the api keys page for obtaining credentials, routing through login. |
| 73 | +
|
| 74 | + Args: |
| 75 | + api_key: Optionally set an existing API key to use for authentication, bypassing manual login. |
| 76 | + no_open: Don't automatically open browser for authentication. |
| 77 | +
|
| 78 | + Returns: |
| 79 | + API key string. Prints success message if login is successful. |
| 80 | + """ |
| 81 | + |
| 82 | + existing_credentials = load_credentials() |
| 83 | + if existing_credentials and not existing_credentials.is_token_expired: |
| 84 | + if not Confirm.ask("You are already logged in. Do you want to login again?"): |
| 85 | + print_info("Using existing credentials.") |
| 86 | + return existing_credentials.api_key |
| 87 | + |
| 88 | + if api_key: |
| 89 | + print_info("Using provided API key for authentication (MCP_API_KEY).") |
| 90 | + if not _is_valid_api_key(api_key): |
| 91 | + raise CLIError("Invalid API key provided.") |
| 92 | + |
| 93 | + credentials = _load_user_credentials(api_key) |
| 94 | + |
| 95 | + save_credentials(credentials) |
| 96 | + print_success("API key set.") |
| 97 | + if credentials.username: |
| 98 | + print_info(f"Logged in as: {credentials.username}") |
| 99 | + return api_key |
| 100 | + |
| 101 | + base_url = settings.API_BASE_URL |
| 102 | + |
| 103 | + return _handle_browser_auth(base_url, no_open) |
| 104 | + |
| 105 | + |
| 106 | +def _handle_browser_auth(base_url: str, no_open: bool) -> str: |
| 107 | + """Handle browser-based authentication flow. |
| 108 | +
|
| 109 | + Args: |
| 110 | + base_url: API base URL |
| 111 | + no_open: Whether to skip automatic browser opening |
| 112 | +
|
| 113 | + Returns: |
| 114 | + API key string |
| 115 | + """ |
| 116 | + auth_url = f"{base_url}/{DEFAULT_API_AUTH_PATH}" |
| 117 | + |
| 118 | + # TODO: This flow should be updated to OAuth2. Probably need to spin up local server to handle |
| 119 | + # the oauth2 callback url. |
| 120 | + if not no_open: |
| 121 | + print_info("Opening MCP Agent Cloud API login in browser...") |
| 122 | + print_info( |
| 123 | + f"If the browser doesn't automatically open, you can manually visit: {auth_url}" |
| 124 | + ) |
| 125 | + typer.launch(auth_url) |
| 126 | + else: |
| 127 | + print_info(f"Please visit: {auth_url}") |
| 128 | + |
| 129 | + return _handle_manual_key_input() |
| 130 | + |
| 131 | + |
| 132 | +def _handle_manual_key_input() -> str: |
| 133 | + """Handle manual API key input. |
| 134 | +
|
| 135 | + Returns: |
| 136 | + API key string |
| 137 | + """ |
| 138 | + input_api_key = Prompt.ask("Please enter your API key :key:") |
| 139 | + |
| 140 | + if not input_api_key: |
| 141 | + print_warning("No API key provided.") |
| 142 | + raise CLIError("Failed to set valid API key") |
| 143 | + |
| 144 | + if not _is_valid_api_key(input_api_key): |
| 145 | + print_warning("Invalid API key provided.") |
| 146 | + raise CLIError("Failed to set valid API key") |
| 147 | + |
| 148 | + credentials = _load_user_credentials(input_api_key) |
| 149 | + |
| 150 | + save_credentials(credentials) |
| 151 | + print_success("API key set.") |
| 152 | + if credentials.username: |
| 153 | + print_info(f"Logged in as: {credentials.username}") |
| 154 | + |
| 155 | + return input_api_key |
| 156 | + |
| 157 | + |
| 158 | +def _is_valid_api_key(api_key: str) -> bool: |
| 159 | + """Validate the API key. |
| 160 | +
|
| 161 | + Args: |
| 162 | + api_key: The API key to validate. |
| 163 | +
|
| 164 | + Returns: |
| 165 | + bool: True if the API key is valid, False otherwise. |
| 166 | + """ |
| 167 | + return api_key.startswith("lm_mcp_api_") |
0 commit comments