Spaces:
Sleeping
Sleeping
File size: 2,636 Bytes
fb07b17 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | 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)
|