Team Ai
Apppublic

Coding-With-Raptor/Likendin-Agent

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
mcp_client.py69 linesDownload Raw Back to mcp_client_tools
1import asyncio2from agents.mcp import MCPServerStreamableHttp, MCPServerStreamableHttpParams3from dotenv import load_dotenv, find_dotenv4import os5import aiohttp6 7load_dotenv(find_dotenv())8 9# Read MCP host from env or fallback to localhost10MCP_HOST = os.getenv("MCP_HOST", "localhost")11 12# Define MCP endpoints13SERVER_MCP_ENDPOINT_URL_1 = f"http://{MCP_HOST}:8000/mcp/"14SERVER_MCP_ENDPOINT_URL_2 = f"http://{MCP_HOST}:8001/mcp/"15 16# MCP client parameter instances17linkedin_params = MCPServerStreamableHttpParams(url=SERVER_MCP_ENDPOINT_URL_1)18weather_params = MCPServerStreamableHttpParams(url=SERVER_MCP_ENDPOINT_URL_2)19 20 21# Utility: Wait for MCP server to be ready before attempting connection22async def wait_for_mcp_server(url: str, retries: int = 10, delay: int = 2):23    for attempt in range(retries):24        try:25            async with aiohttp.ClientSession() as session:26                async with session.get(url, timeout=3) as resp:27                    print(28                        f"[✓] MCP server responded with status {resp.status} at {url}"29                    )30                    return31        except Exception as e:32            print(f"[{attempt+1}/{retries}] MCP not ready: {e}")33            await asyncio.sleep(delay)34    raise RuntimeError(35        f"[✗] MCP server at {url} is not available after {retries} attempts."36    )37 38 39# Public: Connect to LinkedIn MCP server40async def get_mcp_linkedin_client(max_retries=3, retry_delay=2):41    for attempt in range(max_retries):42        try:43            await wait_for_mcp_server(SERVER_MCP_ENDPOINT_URL_1)44            client = MCPServerStreamableHttp(params=linkedin_params)45            await client.connect()46            print("[✓] Connected to LinkedIn MCP server")47            return client48        except Exception as e:49            print(f"[{attempt+1}/{max_retries}] Failed to connect to LinkedIn MCP: {e}")50            if attempt == max_retries - 1:51                raise52            await asyncio.sleep(retry_delay)53 54 55# Public: Connect to Weather MCP server56async def get_mcp_weather_client(max_retries=3, retry_delay=2):57    for attempt in range(max_retries):58        try:59            await wait_for_mcp_server(SERVER_MCP_ENDPOINT_URL_2)60            client = MCPServerStreamableHttp(params=weather_params)61            await client.connect()62            print("[✓] Connected to Weather MCP server")63            return client64        except Exception as e:65            print(f"[{attempt+1}/{max_retries}] Failed to connect to Weather MCP: {e}")66            if attempt == max_retries - 1:67                raise68            await asyncio.sleep(retry_delay)69