mgbam commited on
Commit
ee146eb
·
verified ·
1 Parent(s): 2c1c247

Update mcp/clients.py

Browse files
Files changed (1) hide show
  1. mcp/clients.py +15 -15
mcp/clients.py CHANGED
@@ -1,30 +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()
 
1
  # mcp/clients.py
2
+ ```python
3
+ import os, httpx
4
  from functools import lru_cache
5
  from typing import Any, Dict
6
 
7
+ class APIError(Exception):
8
+ pass
9
 
10
  class BaseClient:
11
+ def __init__(self, base_url: str, api_key_env: str = None):
12
+ self.base = base_url.rstrip("/")
13
  self.key = os.getenv(api_key_env) if api_key_env else None
14
  self._client = httpx.AsyncClient(timeout=10)
15
 
16
  async def request(self, method: str, path: str, **kwargs) -> Any:
17
+ url = f"{self.base}/{path.lstrip('/')}"
18
+ headers = kwargs.pop("headers", {})
19
  if self.key:
20
+ headers["Authorization"] = f"Bearer {self.key}"
21
+ response = await self._client.request(method, url, headers=headers, **kwargs)
 
 
22
  try:
23
+ response.raise_for_status()
24
  except httpx.HTTPStatusError as e:
25
+ raise APIError(f"{response.status_code} @ {url}") from e
26
+ content_type = response.headers.get("Content-Type", "")
27
+ return response.json() if content_type.startswith("application/json") else response.text
 
28
 
29
  async def close(self):
30
+ await self._client.aclose()