import asyncio from agents.mcp import MCPServerStreamableHttp, MCPServerStreamableHttpParams from dotenv import load_dotenv, find_dotenv import os import aiohttp load_dotenv(find_dotenv()) # Read MCP host from env or fallback to localhost MCP_HOST = os.getenv("MCP_HOST", "localhost") # Define MCP endpoints SERVER_MCP_ENDPOINT_URL_1 = f"http://{MCP_HOST}:8000/mcp/" SERVER_MCP_ENDPOINT_URL_2 = f"http://{MCP_HOST}:8001/mcp/" # MCP client parameter instances linkedin_params = MCPServerStreamableHttpParams(url=SERVER_MCP_ENDPOINT_URL_1) weather_params = MCPServerStreamableHttpParams(url=SERVER_MCP_ENDPOINT_URL_2) # Utility: Wait for MCP server to be ready before attempting connection async def wait_for_mcp_server(url: str, retries: int = 10, delay: int = 2): for attempt in range(retries): try: async with aiohttp.ClientSession() as session: async with session.get(url, timeout=3) as resp: print( f"[✓] MCP server responded with status {resp.status} at {url}" ) return except Exception as e: print(f"[{attempt+1}/{retries}] MCP not ready: {e}") await asyncio.sleep(delay) raise RuntimeError( f"[✗] MCP server at {url} is not available after {retries} attempts." ) # Public: Connect to LinkedIn MCP server async def get_mcp_linkedin_client(max_retries=3, retry_delay=2): for attempt in range(max_retries): try: await wait_for_mcp_server(SERVER_MCP_ENDPOINT_URL_1) client = MCPServerStreamableHttp(params=linkedin_params) await client.connect() print("[✓] Connected to LinkedIn MCP server") return client except Exception as e: print(f"[{attempt+1}/{max_retries}] Failed to connect to LinkedIn MCP: {e}") if attempt == max_retries - 1: raise await asyncio.sleep(retry_delay) # Public: Connect to Weather MCP server async def get_mcp_weather_client(max_retries=3, retry_delay=2): for attempt in range(max_retries): try: await wait_for_mcp_server(SERVER_MCP_ENDPOINT_URL_2) client = MCPServerStreamableHttp(params=weather_params) await client.connect() print("[✓] Connected to Weather MCP server") return client except Exception as e: print(f"[{attempt+1}/{max_retries}] Failed to connect to Weather MCP: {e}") if attempt == max_retries - 1: raise await asyncio.sleep(retry_delay)