Create clients.py
Browse files- mcp/clients.py +30 -0
mcp/clients.py
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# mcp/clients.py
|
2 |
+
import os, httpx, asyncio
|
3 |
+
from functools import lru_cache
|
4 |
+
from typing import Any, Dict
|
5 |
+
|
6 |
+
class APIError(Exception): pass
|
7 |
+
|
8 |
+
class BaseClient:
|
9 |
+
def __init__(self, base: str, api_key_env: str = None):
|
10 |
+
self.base = base
|
11 |
+
self.key = os.getenv(api_key_env) if api_key_env else None
|
12 |
+
self._client = httpx.AsyncClient(timeout=10)
|
13 |
+
|
14 |
+
async def request(self, method: str, path: str, **kwargs) -> Any:
|
15 |
+
# automatically attach API key if present
|
16 |
+
if self.key:
|
17 |
+
if "headers" not in kwargs: kwargs["headers"] = {}
|
18 |
+
kwargs["headers"]["Authorization"] = f"Bearer {self.key}"
|
19 |
+
url = f"{self.base.rstrip('/')}/{path.lstrip('/')}"
|
20 |
+
resp = await self._client.request(method, url, **kwargs)
|
21 |
+
try:
|
22 |
+
resp.raise_for_status()
|
23 |
+
except httpx.HTTPStatusError as e:
|
24 |
+
raise APIError(f"{resp.status_code} @ {url}") from e
|
25 |
+
# auto-parse JSON or text
|
26 |
+
ct = resp.headers.get("Content-Type","")
|
27 |
+
return resp.json() if ct.startswith("application/json") else resp.text
|
28 |
+
|
29 |
+
async def close(self):
|
30 |
+
await self._client.aclose()
|