"""Tecrube API and MCP client. Single file, standard library only (Python 3.9+). from tecrube import Tecrube client = Tecrube("tk_your_key") print(client.get("/account/me")) print(client.call_tool("list_campaigns", days=7)) Docs: https://tecrube.com/en/docs/api """ from __future__ import annotations import json import time import urllib.error import urllib.parse import urllib.request from typing import Any, Dict, List, Optional __version__ = "1.0.0" __all__ = ["Tecrube", "TecrubeError"] _BEKLEMELI = {429, 500, 502, 503, 504} class TecrubeError(Exception): """API or tool error. `status` is the HTTP status (0 when the server could not be reached), `body` the parsed answer.""" def __init__(self, status: int, message: str, body: Any = None) -> None: super().__init__(f"{status}: {message}" if status else message) self.status = status self.message = message self.body = body class Tecrube: """`api_key` is a `tk_…` key from Settings › API. Read scope reads; write scope acts as a workspace admin.""" def __init__(self, api_key: str, *, base_url: str = "https://tecrube.com/api/v1", mcp_url: str = "https://tecrube.com/mcp", timeout: float = 60.0, max_retries: int = 2) -> None: if not api_key: raise ValueError("api_key is required") self._key = api_key self.base_url = base_url.rstrip("/") self.mcp_url = mcp_url self.timeout = timeout self.max_retries = max_retries self._kimlik = 0 # ------------------------------------------------------------------ REST def get(self, path: str, **params: Any) -> Any: return self.request("GET", path, params=params) def post(self, path: str, body: Any = None) -> Any: return self.request("POST", path, body=body) def patch(self, path: str, body: Any = None) -> Any: return self.request("PATCH", path, body=body) def put(self, path: str, body: Any = None) -> Any: return self.request("PUT", path, body=body) def delete(self, path: str) -> Any: return self.request("DELETE", path) def openapi(self) -> Dict[str, Any]: """The OpenAPI document of every endpoint available to API keys.""" return self.get("/api-referansi/openapi.json") def request(self, method: str, path: str, *, params: Optional[Dict[str, Any]] = None, body: Any = None) -> Any: adres = f"{self.base_url}/{path.lstrip('/')}" temiz = {k: v for k, v in (params or {}).items() if v is not None} if temiz: adres += "?" + urllib.parse.urlencode(temiz, doseq=True) # Yazma isteği yanıtı alınamadıysa işlem yapılmış olabilir: yalnız okuma ve hız sınırı yeniden denenir. return self._gonder(method, adres, body, yeniden=method == "GET") # ------------------------------------------------------------------ MCP def tools(self) -> List[Dict[str, Any]]: """Every MCP tool with its description and input schema.""" return self._rpc("tools/list")["tools"] def call_tool(self, name: str, **arguments: Any) -> Any: """Runs an MCP tool and returns its result. Changes go through preview and approval, as in the panel.""" sonuc = self._rpc("tools/call", {"name": name, "arguments": arguments}) veri = sonuc.get("structuredContent") if veri is None: metin = "".join(p.get("text", "") for p in sonuc.get("content", [])) try: veri = json.loads(metin) except ValueError: veri = metin if sonuc.get("isError"): mesaj = veri.get("error") if isinstance(veri, dict) else None raise TecrubeError(200, str(mesaj or veri)[:500], veri) return veri def _rpc(self, method: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: self._kimlik += 1 cevap = self._gonder("POST", self.mcp_url, {"jsonrpc": "2.0", "id": self._kimlik, "method": method, "params": params or {}}, yeniden=method == "tools/list") if cevap.get("error"): raise TecrubeError(200, str(cevap["error"].get("message")), cevap["error"]) return cevap["result"] # ------------------------------------------------------------------ iç def _gonder(self, method: str, adres: str, govde: Any, *, yeniden: bool) -> Any: veri = None if govde is None else json.dumps(govde).encode("utf-8") basliklar = {"Authorization": f"Bearer {self._key}", "Accept": "application/json", "User-Agent": f"tecrube-python/{__version__}"} if veri is not None: basliklar["Content-Type"] = "application/json" deneme = 0 while True: istek = urllib.request.Request(adres, data=veri, headers=basliklar, method=method) try: with urllib.request.urlopen(istek, timeout=self.timeout) as yanit: return _coz(yanit.read()) except urllib.error.HTTPError as e: ham = e.read() bekle = _bekleme(e.headers.get("Retry-After"), deneme) if e.code in _BEKLEMELI and (yeniden or e.code == 429) and deneme < self.max_retries: deneme += 1 time.sleep(bekle) continue icerik = _coz(ham) raise TecrubeError(e.code, _mesaj(icerik, e.reason), icerik) from None except (urllib.error.URLError, TimeoutError) as e: if yeniden and deneme < self.max_retries: deneme += 1 time.sleep(_bekleme(None, deneme)) continue raise TecrubeError(0, f"could not reach {adres}: {e}") from None def _coz(ham: bytes) -> Any: if not ham: return None try: return json.loads(ham) except ValueError: return ham.decode("utf-8", "replace") def _mesaj(icerik: Any, yedek: Any) -> str: if isinstance(icerik, dict): ayrinti = icerik.get("detail", icerik) if isinstance(ayrinti, dict): return str(ayrinti.get("message_en") or ayrinti.get("message") or ayrinti.get("error") or ayrinti) return str(ayrinti) return str(icerik or yedek) def _bekleme(baslik: Optional[str], deneme: int) -> float: try: return min(float(baslik), 60.0) if baslik else min(2.0 ** deneme, 8.0) except ValueError: return min(2.0 ** deneme, 8.0)