Skip to content

Commit 37b2177

Browse files
committed
Update server.py
1 parent 3acd879 commit 37b2177

File tree

1 file changed

+68
-17
lines changed

1 file changed

+68
-17
lines changed

src/scrapegraph_mcp/server.py

Lines changed: 68 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
"""
1111

1212
import json
13+
import logging
1314
import os
1415
from typing import Any, Dict, Optional, List, Union
1516

@@ -18,6 +19,13 @@
1819
from smithery.decorators import smithery
1920
from pydantic import BaseModel, Field
2021

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+
2129

2230
class ScapeGraphClient:
2331
"""Client for interacting with the ScapeGraph API."""
@@ -351,27 +359,64 @@ def get_api_key(ctx: Context) -> str:
351359
Raises:
352360
ValueError: If no API key is found
353361
"""
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
368391

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()
370396

371397

372398
# Create MCP server instance
373399
mcp = FastMCP("ScapeGraph API MCP Server")
374400

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+
375420

376421
# Add prompts to help users interact with the server
377422
@mcp.prompt()
@@ -1201,8 +1246,14 @@ def create_server() -> FastMCP:
12011246

12021247
def main() -> None:
12031248
"""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
12061257

12071258

12081259
if __name__ == "__main__":

0 commit comments

Comments
 (0)