|
10 | 10 | """ |
11 | 11 |
|
12 | 12 | import json |
| 13 | +import logging |
13 | 14 | import os |
14 | 15 | from typing import Any, Dict, Optional, List, Union |
15 | 16 |
|
|
18 | 19 | from smithery.decorators import smithery |
19 | 20 | from pydantic import BaseModel, Field |
20 | 21 |
|
| 22 | +# Configure logging |
| 23 | +logging.basicConfig( |
| 24 | + level=logging.INFO, |
| 25 | + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' |
| 26 | +) |
| 27 | +logger = logging.getLogger(__name__) |
| 28 | + |
21 | 29 |
|
22 | 30 | class ScapeGraphClient: |
23 | 31 | """Client for interacting with the ScapeGraph API.""" |
@@ -351,27 +359,64 @@ def get_api_key(ctx: Context) -> str: |
351 | 359 | Raises: |
352 | 360 | ValueError: If no API key is found |
353 | 361 | """ |
354 | | - # Try to get from config first |
355 | | - api_key = getattr(ctx.session_config, 'scrapegraph_api_key', None) |
356 | | - |
357 | | - # If not in config, try environment variable |
358 | | - if not api_key: |
359 | | - api_key = os.getenv('SGAI_API_KEY') |
360 | | - |
361 | | - # If still no API key found, raise error |
362 | | - if not api_key: |
363 | | - raise ValueError( |
364 | | - "ScapeGraph API key is required. Please provide it either:\n" |
365 | | - "1. In the MCP server configuration as 'scrapegraph_api_key'\n" |
366 | | - "2. As an environment variable 'SGAI_API_KEY'" |
367 | | - ) |
| 362 | + try: |
| 363 | + logger.info(f"Getting API key. Context type: {type(ctx)}") |
| 364 | + logger.info(f"Context has session_config: {hasattr(ctx, 'session_config')}") |
| 365 | + |
| 366 | + # Try to get from config first, but handle cases where session_config might be None |
| 367 | + api_key = None |
| 368 | + if hasattr(ctx, 'session_config') and ctx.session_config is not None: |
| 369 | + logger.info(f"Session config type: {type(ctx.session_config)}") |
| 370 | + api_key = getattr(ctx.session_config, 'scrapegraph_api_key', None) |
| 371 | + logger.info(f"API key from config: {'***' if api_key else 'None'}") |
| 372 | + else: |
| 373 | + logger.info("No session_config available or session_config is None") |
| 374 | + |
| 375 | + # If not in config, try environment variable |
| 376 | + if not api_key: |
| 377 | + api_key = os.getenv('SGAI_API_KEY') |
| 378 | + logger.info(f"API key from env: {'***' if api_key else 'None'}") |
| 379 | + |
| 380 | + # If still no API key found, raise error |
| 381 | + if not api_key: |
| 382 | + logger.error("No API key found in config or environment") |
| 383 | + raise ValueError( |
| 384 | + "ScapeGraph API key is required. Please provide it either:\n" |
| 385 | + "1. In the MCP server configuration as 'scrapegraph_api_key'\n" |
| 386 | + "2. As an environment variable 'SGAI_API_KEY'" |
| 387 | + ) |
| 388 | + |
| 389 | + logger.info("API key successfully retrieved") |
| 390 | + return api_key |
368 | 391 |
|
369 | | - return api_key |
| 392 | + except Exception as e: |
| 393 | + logger.warning(f"Error getting API key from context: {e}. Falling back to cached method.") |
| 394 | + # Fallback to cached method if context handling fails |
| 395 | + return get_cached_api_key() |
370 | 396 |
|
371 | 397 |
|
372 | 398 | # Create MCP server instance |
373 | 399 | mcp = FastMCP("ScapeGraph API MCP Server") |
374 | 400 |
|
| 401 | +# Global API key cache to handle session issues |
| 402 | +_api_key_cache: Optional[str] = None |
| 403 | + |
| 404 | +def get_cached_api_key() -> str: |
| 405 | + """Get API key from cache or environment, bypassing session config issues.""" |
| 406 | + global _api_key_cache |
| 407 | + |
| 408 | + if _api_key_cache is None: |
| 409 | + _api_key_cache = os.getenv('SGAI_API_KEY') |
| 410 | + if _api_key_cache: |
| 411 | + logger.info("API key loaded from environment variable") |
| 412 | + else: |
| 413 | + logger.error("No API key found in environment variable SGAI_API_KEY") |
| 414 | + raise ValueError( |
| 415 | + "ScapeGraph API key is required. Please set the SGAI_API_KEY environment variable." |
| 416 | + ) |
| 417 | + |
| 418 | + return _api_key_cache |
| 419 | + |
375 | 420 |
|
376 | 421 | # Add prompts to help users interact with the server |
377 | 422 | @mcp.prompt() |
@@ -1201,8 +1246,14 @@ def create_server() -> FastMCP: |
1201 | 1246 |
|
1202 | 1247 | def main() -> None: |
1203 | 1248 | """Run the ScapeGraph MCP server.""" |
1204 | | - print("Starting ScapeGraph MCP server!") |
1205 | | - mcp.run(transport="stdio") |
| 1249 | + try: |
| 1250 | + logger.info("Starting ScapeGraph MCP server!") |
| 1251 | + print("Starting ScapeGraph MCP server!") |
| 1252 | + mcp.run(transport="stdio") |
| 1253 | + except Exception as e: |
| 1254 | + logger.error(f"Failed to start MCP server: {e}") |
| 1255 | + print(f"Error starting server: {e}") |
| 1256 | + raise |
1206 | 1257 |
|
1207 | 1258 |
|
1208 | 1259 | if __name__ == "__main__": |
|
0 commit comments