treg-sdk 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
treg_sdk/__init__.py ADDED
@@ -0,0 +1,24 @@
1
+ """treg SDK: call the tool catalog and your own tools, and let your customers connect their own
2
+ accounts through treg's apps, then call tools as one of them."""
3
+
4
+ from ._client import (
5
+ DEFAULT_BASE_URL,
6
+ AsyncTreg,
7
+ CallResult,
8
+ ConnectReturn,
9
+ Treg,
10
+ TregError,
11
+ parse_connect_return,
12
+ )
13
+ from ._version import __version__
14
+
15
+ __all__ = [
16
+ "DEFAULT_BASE_URL",
17
+ "AsyncTreg",
18
+ "CallResult",
19
+ "ConnectReturn",
20
+ "Treg",
21
+ "TregError",
22
+ "parse_connect_return",
23
+ "__version__",
24
+ ]
treg_sdk/_client.py ADDED
@@ -0,0 +1,495 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import re
6
+ from dataclasses import dataclass
7
+ from typing import Any, AsyncIterator, Iterator, Mapping, Optional, Sequence, Union
8
+ from urllib.parse import parse_qs, quote, unquote, urlsplit
9
+
10
+ import httpx
11
+
12
+ from ._version import __version__
13
+
14
+ DEFAULT_BASE_URL = "https://treg.to"
15
+ DEFAULT_TIMEOUT = 120.0
16
+
17
+ QueryValue = Union[str, int, float, bool, None, Sequence[Union[str, int, float, bool]]]
18
+
19
+
20
+ class TregError(Exception):
21
+ """A non-2xx answer: treg's own refusal (``code`` is its kind) or the provider's error,
22
+ relayed as the provider sent it (``code`` is None)."""
23
+
24
+ def __init__(self, status: int, body: Any, headers: httpx.Headers):
25
+ self.status = status
26
+ self.body = body
27
+ self.headers = headers
28
+ self.code = _error_code(body)
29
+ self.call_id = headers.get("x-treg-call-id")
30
+ super().__init__(f"treg {status}{' ' + self.code if self.code else ''}: {_error_text(body)}")
31
+
32
+
33
+ def _error_code(body: Any) -> Optional[str]:
34
+ if isinstance(body, dict):
35
+ if isinstance(body.get("error"), str):
36
+ return body["error"]
37
+ detail = body.get("detail")
38
+ if isinstance(detail, dict) and isinstance(detail.get("error"), str):
39
+ return detail["error"]
40
+ return None
41
+
42
+
43
+ def _error_text(body: Any) -> str:
44
+ if isinstance(body, str):
45
+ return body[:300]
46
+ if isinstance(body, dict):
47
+ detail = body.get("detail", body.get("message", body.get("error")))
48
+ if isinstance(detail, str):
49
+ return detail
50
+ if isinstance(detail, dict):
51
+ text = detail.get("detail", detail.get("message"))
52
+ if isinstance(text, str):
53
+ return text
54
+ return json.dumps(body, default=repr)[:300]
55
+
56
+
57
+ @dataclass
58
+ class CallResult:
59
+ status: int
60
+ headers: httpx.Headers
61
+ data: Any
62
+ """The parsed JSON body, text, or ``bytes`` for anything else (audio, images, files)."""
63
+ """The parsed JSON body, or the text when the answer is not JSON."""
64
+ call_id: Optional[str]
65
+ """Store this: ``calls.get(call_id)`` and ``calls.result(call_id)`` resolve it later."""
66
+ cost_micro: int
67
+ """What this call cost in micro-USD (1e-6 USD); 0 when it was not billed."""
68
+
69
+
70
+ @dataclass
71
+ class ConnectReturn:
72
+ status: str
73
+ provider: Optional[str]
74
+ reason: Optional[str]
75
+
76
+
77
+ def parse_connect_return(url: str) -> Optional[ConnectReturn]:
78
+ """Read the outcome treg appends to your ``return_url`` when it sends your customer back."""
79
+ params = parse_qs(urlsplit(url).query)
80
+ status = (params.get("treg_connect") or [None])[0]
81
+ if status not in ("connected", "failed"):
82
+ return None
83
+ return ConnectReturn(status=status, provider=(params.get("provider") or [None])[0],
84
+ reason=(params.get("reason") or [None])[0])
85
+
86
+
87
+ def _seg(value: str) -> str:
88
+ """One id as one path segment: ``.`` and ``..`` would name another path."""
89
+ if value in ("", ".", ".."):
90
+ raise ValueError(f"not an id: {value!r}")
91
+ return quote(value, safe="")
92
+
93
+
94
+ def _call_path(target: str) -> str:
95
+ """``/call/<target>``, refusing a ``.`` or ``..`` segment at any depth of percent-encoding: it
96
+ would send the token to another route. URL parsing may read ``\\`` as ``/`` and drop tabs,
97
+ newlines and outer spaces."""
98
+ rest = target.lstrip("/")
99
+ path = re.split(r"[?#]", rest, maxsplit=1)[0]
100
+ for _ in range(4):
101
+ if not path or any(re.sub(r"[\x00-\x20]", "", s) in (".", "..") for s in re.split(r"[/\\]", path)):
102
+ break
103
+ decoded = unquote(path)
104
+ if decoded == path:
105
+ return "/call/" + rest
106
+ path = decoded
107
+ raise ValueError(f"not a tool or path: {target!r}")
108
+
109
+
110
+ def _query(params: Optional[Mapping[str, QueryValue]]) -> list[tuple[str, str]]:
111
+ out: list[tuple[str, str]] = []
112
+ for key, value in (params or {}).items():
113
+ if value is None:
114
+ continue
115
+ for v in value if isinstance(value, (list, tuple)) else [value]:
116
+ out.append((key, ("true" if v else "false") if isinstance(v, bool) else str(v)))
117
+ return out
118
+
119
+
120
+ # An answer of any other type (audio, images, files) stays bytes.
121
+ _TEXT = re.compile(r"^text/|[/+]xml|javascript|urlencoded|yaml")
122
+
123
+
124
+ def _parse(response: httpx.Response) -> Any:
125
+ if not response.content:
126
+ return None
127
+ content_type = response.headers.get("content-type", "text/plain").lower()
128
+ if "json" in content_type:
129
+ try:
130
+ return response.json()
131
+ except ValueError:
132
+ return response.text
133
+ return response.text if _TEXT.search(content_type) else response.content
134
+
135
+
136
+ # The default of ``end_user``: a team call. None is a missing id, and raises.
137
+ _TEAM: Any = object()
138
+
139
+
140
+ def _end_user_id(value: str) -> str:
141
+ """A missing id must not turn a customer's call into a call on the team's own account."""
142
+ if not isinstance(value, str) or not value.strip():
143
+ raise ValueError("end_user must be your customer's id, not blank")
144
+ return value
145
+
146
+
147
+ def _call_headers(end_user, meta, max_cost_usd, idempotency_key, headers) -> httpx.Headers:
148
+ # Case-insensitive, so a header the caller spelled another way is replaced, never sent beside.
149
+ out = httpx.Headers(dict(headers or {}))
150
+ if end_user is not _TEAM:
151
+ out["X-Treg-End-User"] = _end_user_id(end_user)
152
+ if meta:
153
+ out["X-Treg-Meta"] = ", ".join(f"{k}={v}" for k, v in meta.items())
154
+ if max_cost_usd is not None:
155
+ out["X-Treg-Route-Max-Cost"] = str(max_cost_usd)
156
+ if idempotency_key:
157
+ out["Idempotency-Key"] = idempotency_key
158
+ return out
159
+
160
+
161
+ def _result(response: httpx.Response) -> CallResult:
162
+ return CallResult(status=response.status_code, headers=response.headers, data=_parse(response),
163
+ call_id=response.headers.get("x-treg-call-id"),
164
+ cost_micro=int(response.headers.get("x-treg-cost-micro") or 0))
165
+
166
+
167
+ def _connect_body(provider, capability, return_url, label) -> dict:
168
+ body = {"provider": provider, "capability": capability, "return_url": return_url, "label": label}
169
+ return {k: v for k, v in body.items() if v is not None}
170
+
171
+
172
+ def _list_params(after, limit, q, provider, attention) -> dict:
173
+ return {"after": after, "limit": limit, "q": q or None, "provider": provider or None,
174
+ "attention": "true" if attention else None}
175
+
176
+
177
+ class _Base:
178
+ def __init__(self, token: Optional[str], base_url: Optional[str], org: Optional[str],
179
+ headers: Optional[Mapping[str, str]]):
180
+ self.token = token if token is not None else os.environ.get("TREG_TOKEN", "")
181
+ self.base_url = (base_url or os.environ.get("TREG_URL") or DEFAULT_BASE_URL).rstrip("/")
182
+ self.org = org
183
+ self._headers = httpx.Headers({"User-Agent": f"treg-sdk-python/{__version__}"})
184
+ self._headers.update(dict(headers or {}))
185
+ if self.token:
186
+ self._headers["X-Treg-Token"] = self.token
187
+ if org:
188
+ self._headers["X-Treg-Org"] = org
189
+
190
+ def mcp_config(self, end_user: str = _TEAM) -> dict:
191
+ """The MCP server address and headers for an agent runtime. With ``end_user``, every tool
192
+ call acts as that customer; the model cannot pick or change the account."""
193
+ headers = {"Authorization": f"Bearer {self.token}"}
194
+ if self.org:
195
+ headers["X-Treg-Org"] = self.org
196
+ if end_user is not _TEAM:
197
+ headers["X-Treg-End-User"] = _end_user_id(end_user)
198
+ return {"url": f"{self.base_url}/mcp/", "headers": headers}
199
+
200
+ def _build(self, method: str, path: str, *, params=None, json_body=None, content=None,
201
+ headers=None) -> dict:
202
+ merged = self._headers.copy()
203
+ merged.update(headers)
204
+ # httpx's own `params` would replace a query already in the path.
205
+ url = self.base_url + path.partition("#")[0]
206
+ if query := str(httpx.QueryParams(_query(params))):
207
+ url += ("&" if "?" in url else "?") + query
208
+ # Never follow a redirect: it would resend X-Treg-Token to wherever an upstream points.
209
+ kwargs: dict[str, Any] = {"method": method, "url": url, "headers": merged,
210
+ "follow_redirects": False}
211
+ if content is not None:
212
+ kwargs["content"] = content
213
+ elif json_body is not None:
214
+ kwargs["content"] = json.dumps(json_body).encode()
215
+ merged.setdefault("Content-Type", "application/json")
216
+ return kwargs
217
+
218
+
219
+ def _checked(response: httpx.Response) -> httpx.Response:
220
+ if response.status_code >= 400:
221
+ raise TregError(response.status_code, _parse(response), response.headers)
222
+ return response
223
+
224
+
225
+ class Treg(_Base):
226
+ """treg client. ``Treg()`` reads ``TREG_TOKEN`` and ``TREG_URL`` from the environment.
227
+
228
+ Call tools with ``call``; manage your customers' connections with ``end_users``."""
229
+
230
+ def __init__(self, token: Optional[str] = None, *, base_url: Optional[str] = None,
231
+ org: Optional[str] = None, headers: Optional[Mapping[str, str]] = None,
232
+ timeout: float = DEFAULT_TIMEOUT, http_client: Optional[httpx.Client] = None):
233
+ super().__init__(token, base_url, org, headers)
234
+ self._http = http_client or httpx.Client(timeout=timeout)
235
+ self.end_users = EndUsers(self)
236
+ self.catalog = Catalog(self)
237
+ self.calls = Calls(self)
238
+
239
+ def __enter__(self) -> "Treg":
240
+ return self
241
+
242
+ def __exit__(self, *exc) -> None:
243
+ self.close()
244
+
245
+ def close(self) -> None:
246
+ self._http.close()
247
+
248
+ def _request(self, method: str, path: str, **kwargs) -> httpx.Response:
249
+ return _checked(self._http.request(**self._build(method, path, **kwargs)))
250
+
251
+ def _json(self, method: str, path: str, **kwargs) -> Any:
252
+ return _parse(self._request(method, path, **kwargs))
253
+
254
+ def call(self, target: str, *, method: Optional[str] = None,
255
+ params: Optional[Mapping[str, QueryValue]] = None, json: Any = None,
256
+ content: Optional[bytes] = None, end_user: str = _TEAM,
257
+ meta: Optional[Mapping[str, str]] = None, max_cost_usd: Optional[float] = None,
258
+ idempotency_key: Optional[str] = None,
259
+ headers: Optional[Mapping[str, str]] = None) -> CallResult:
260
+ """Call a catalog tool by id (``google-search-console.sites``), a provider path or one of
261
+ your own tools. ``end_user`` acts as one of your customers; leave it out for a team call
262
+ (None raises). Raises ``TregError`` on any
263
+ non-2xx answer, the provider's errors included."""
264
+ verb = method or ("POST" if json is not None or content is not None else "GET")
265
+ return _result(self._request(
266
+ verb.upper(), _call_path(target), params=params, json_body=json,
267
+ content=content,
268
+ headers=_call_headers(end_user, meta, max_cost_usd, idempotency_key, headers)))
269
+
270
+ def for_end_user(self, end_user: str) -> "EndUserClient":
271
+ """A client whose every call acts as one of your customers."""
272
+ return EndUserClient(self, end_user)
273
+
274
+
275
+ class EndUserClient:
276
+ def __init__(self, client: Treg, end_user: str):
277
+ self._client = client
278
+ self.end_user = _end_user_id(end_user)
279
+
280
+ def call(self, target: str, **kwargs) -> CallResult:
281
+ return self._client.call(target, end_user=self.end_user, **kwargs)
282
+
283
+ def connect(self, provider: str, **kwargs) -> dict:
284
+ return self._client.end_users.connect(self.end_user, provider, **kwargs)
285
+
286
+ def get(self) -> dict:
287
+ return self._client.end_users.get(self.end_user)
288
+
289
+ def disconnect(self, provider: str) -> dict:
290
+ return self._client.end_users.disconnect(self.end_user, provider)
291
+
292
+ def remove(self) -> dict:
293
+ return self._client.end_users.remove(self.end_user)
294
+
295
+ def mcp_config(self) -> dict:
296
+ return self._client.mcp_config(end_user=self.end_user)
297
+
298
+
299
+ class EndUsers:
300
+ """Your customers ("end users") and the accounts they connected through treg's apps."""
301
+
302
+ def __init__(self, client: Treg):
303
+ self._client = client
304
+
305
+ def connect(self, end_user: str, provider: str, *, capability: Optional[str] = None,
306
+ return_url: Optional[str] = None, label: Optional[str] = None) -> dict:
307
+ """A one-time consent link (``consent_url``) for this customer. Make it on your backend."""
308
+ return self._client._json("POST", f"/end-users/{_seg(end_user)}/connect",
309
+ json_body=_connect_body(provider, capability, return_url, label))
310
+
311
+ def list(self, *, after: Optional[str] = None, limit: Optional[int] = None, q: str = "",
312
+ provider: str = "", attention: bool = False) -> dict:
313
+ """One page, oldest first: ``end_users``, ``total`` and ``next`` (pass it as ``after``)."""
314
+ return self._client._json("GET", "/end-users",
315
+ params=_list_params(after, limit, q, provider, attention))
316
+
317
+ def iterate(self, *, limit: Optional[int] = None, q: str = "", provider: str = "",
318
+ attention: bool = False) -> Iterator[dict]:
319
+ """Every match, page by page."""
320
+ after = None
321
+ while True:
322
+ page = self.list(after=after, limit=limit, q=q, provider=provider, attention=attention)
323
+ yield from page["end_users"]
324
+ after = page.get("next")
325
+ if not after:
326
+ return
327
+
328
+ def get(self, end_user: str) -> dict:
329
+ """The customer's connections, with status and expiry. No token material."""
330
+ return self._client._json("GET", f"/end-users/{_seg(end_user)}")
331
+
332
+ def disconnect(self, end_user: str, provider: str) -> dict:
333
+ """Forget the customer's connection to one provider. It is not revoked at the platform."""
334
+ return self._client._json(
335
+ "DELETE", f"/end-users/{_seg(end_user)}/connections/{_seg(provider)}")
336
+
337
+ def remove(self, end_user: str) -> dict:
338
+ """Forget the customer and every connection they made."""
339
+ return self._client._json("DELETE", f"/end-users/{_seg(end_user)}")
340
+
341
+
342
+ class Catalog:
343
+ def __init__(self, client: Treg):
344
+ self._client = client
345
+
346
+ def search(self, q: str, *, limit: Optional[int] = None) -> dict:
347
+ """Find tools by the job they do. Each result has an id and a price."""
348
+ return self._client._json("GET", "/catalog/search", params={"q": q, "limit": limit})
349
+
350
+ def get(self, endpoint_id: str) -> dict:
351
+ """One tool: its parameters, method and an example."""
352
+ return self._client._json("GET", f"/catalog/endpoints/{_seg(endpoint_id)}")
353
+
354
+
355
+ class Calls:
356
+ def __init__(self, client: Treg):
357
+ self._client = client
358
+
359
+ def get(self, call_id: str) -> dict:
360
+ """The record of one call by its ``X-Treg-Call-Id``."""
361
+ return self._client._json("GET", f"/calls/{_seg(call_id)}")
362
+
363
+ def result(self, call_id: str) -> Any:
364
+ """The stored answer of a successful catalog call whose answer you lost."""
365
+ return self._client._json("GET", f"/calls/{_seg(call_id)}/result")
366
+
367
+
368
+ # ---- async -------------------------------------------------------------------------------------
369
+
370
+
371
+ class AsyncTreg(_Base):
372
+ """The same client for asyncio."""
373
+
374
+ def __init__(self, token: Optional[str] = None, *, base_url: Optional[str] = None,
375
+ org: Optional[str] = None, headers: Optional[Mapping[str, str]] = None,
376
+ timeout: float = DEFAULT_TIMEOUT, http_client: Optional[httpx.AsyncClient] = None):
377
+ super().__init__(token, base_url, org, headers)
378
+ self._http = http_client or httpx.AsyncClient(timeout=timeout)
379
+ self.end_users = AsyncEndUsers(self)
380
+ self.catalog = AsyncCatalog(self)
381
+ self.calls = AsyncCalls(self)
382
+
383
+ async def __aenter__(self) -> "AsyncTreg":
384
+ return self
385
+
386
+ async def __aexit__(self, *exc) -> None:
387
+ await self.close()
388
+
389
+ async def close(self) -> None:
390
+ await self._http.aclose()
391
+
392
+ async def _request(self, method: str, path: str, **kwargs) -> httpx.Response:
393
+ return _checked(await self._http.request(**self._build(method, path, **kwargs)))
394
+
395
+ async def _json(self, method: str, path: str, **kwargs) -> Any:
396
+ return _parse(await self._request(method, path, **kwargs))
397
+
398
+ async def call(self, target: str, *, method: Optional[str] = None,
399
+ params: Optional[Mapping[str, QueryValue]] = None, json: Any = None,
400
+ content: Optional[bytes] = None, end_user: str = _TEAM,
401
+ meta: Optional[Mapping[str, str]] = None, max_cost_usd: Optional[float] = None,
402
+ idempotency_key: Optional[str] = None,
403
+ headers: Optional[Mapping[str, str]] = None) -> CallResult:
404
+ verb = method or ("POST" if json is not None or content is not None else "GET")
405
+ return _result(await self._request(
406
+ verb.upper(), _call_path(target), params=params, json_body=json,
407
+ content=content,
408
+ headers=_call_headers(end_user, meta, max_cost_usd, idempotency_key, headers)))
409
+
410
+ def for_end_user(self, end_user: str) -> "AsyncEndUserClient":
411
+ return AsyncEndUserClient(self, end_user)
412
+
413
+
414
+ class AsyncEndUserClient:
415
+ def __init__(self, client: AsyncTreg, end_user: str):
416
+ self._client = client
417
+ self.end_user = _end_user_id(end_user)
418
+
419
+ async def call(self, target: str, **kwargs) -> CallResult:
420
+ return await self._client.call(target, end_user=self.end_user, **kwargs)
421
+
422
+ async def connect(self, provider: str, **kwargs) -> dict:
423
+ return await self._client.end_users.connect(self.end_user, provider, **kwargs)
424
+
425
+ async def get(self) -> dict:
426
+ return await self._client.end_users.get(self.end_user)
427
+
428
+ async def disconnect(self, provider: str) -> dict:
429
+ return await self._client.end_users.disconnect(self.end_user, provider)
430
+
431
+ async def remove(self) -> dict:
432
+ return await self._client.end_users.remove(self.end_user)
433
+
434
+ def mcp_config(self) -> dict:
435
+ return self._client.mcp_config(end_user=self.end_user)
436
+
437
+
438
+ class AsyncEndUsers:
439
+ def __init__(self, client: AsyncTreg):
440
+ self._client = client
441
+
442
+ async def connect(self, end_user: str, provider: str, *, capability: Optional[str] = None,
443
+ return_url: Optional[str] = None, label: Optional[str] = None) -> dict:
444
+ return await self._client._json(
445
+ "POST", f"/end-users/{_seg(end_user)}/connect",
446
+ json_body=_connect_body(provider, capability, return_url, label))
447
+
448
+ async def list(self, *, after: Optional[str] = None, limit: Optional[int] = None, q: str = "",
449
+ provider: str = "", attention: bool = False) -> dict:
450
+ return await self._client._json("GET", "/end-users",
451
+ params=_list_params(after, limit, q, provider, attention))
452
+
453
+ async def iterate(self, *, limit: Optional[int] = None, q: str = "", provider: str = "",
454
+ attention: bool = False) -> AsyncIterator[dict]:
455
+ after = None
456
+ while True:
457
+ page = await self.list(after=after, limit=limit, q=q, provider=provider,
458
+ attention=attention)
459
+ for end_user in page["end_users"]:
460
+ yield end_user
461
+ after = page.get("next")
462
+ if not after:
463
+ return
464
+
465
+ async def get(self, end_user: str) -> dict:
466
+ return await self._client._json("GET", f"/end-users/{_seg(end_user)}")
467
+
468
+ async def disconnect(self, end_user: str, provider: str) -> dict:
469
+ return await self._client._json(
470
+ "DELETE", f"/end-users/{_seg(end_user)}/connections/{_seg(provider)}")
471
+
472
+ async def remove(self, end_user: str) -> dict:
473
+ return await self._client._json("DELETE", f"/end-users/{_seg(end_user)}")
474
+
475
+
476
+ class AsyncCatalog:
477
+ def __init__(self, client: AsyncTreg):
478
+ self._client = client
479
+
480
+ async def search(self, q: str, *, limit: Optional[int] = None) -> dict:
481
+ return await self._client._json("GET", "/catalog/search", params={"q": q, "limit": limit})
482
+
483
+ async def get(self, endpoint_id: str) -> dict:
484
+ return await self._client._json("GET", f"/catalog/endpoints/{_seg(endpoint_id)}")
485
+
486
+
487
+ class AsyncCalls:
488
+ def __init__(self, client: AsyncTreg):
489
+ self._client = client
490
+
491
+ async def get(self, call_id: str) -> dict:
492
+ return await self._client._json("GET", f"/calls/{_seg(call_id)}")
493
+
494
+ async def result(self, call_id: str) -> Any:
495
+ return await self._client._json("GET", f"/calls/{_seg(call_id)}/result")
treg_sdk/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
treg_sdk/py.typed ADDED
File without changes
@@ -0,0 +1,112 @@
1
+ Metadata-Version: 2.5
2
+ Name: treg-sdk
3
+ Version: 0.1.0
4
+ Summary: treg SDK: call the tool catalog and your own tools, and let your customers connect their accounts and call tools as them.
5
+ Project-URL: Homepage, https://treg.to
6
+ Project-URL: Source, https://github.com/superdesigndev/treg/tree/main/packages/sdk-python
7
+ License-Expression: Apache-2.0
8
+ Keywords: agents,mcp,oauth,sdk,tools,treg
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Typing :: Typed
11
+ Requires-Python: >=3.9
12
+ Requires-Dist: httpx<1,>=0.24
13
+ Description-Content-Type: text/markdown
14
+
15
+ # treg-sdk
16
+
17
+ The treg SDK for Python 3.9+, sync (`Treg`) and async (`AsyncTreg`).
18
+
19
+ - Call any catalog tool or one of your team's own tools, with no provider key in your code.
20
+ - Let **your customers** connect their own accounts (Instagram, Facebook Pages, Search Console,
21
+ Google Analytics, Meta Ads, ...) through treg's approved apps, then call tools **as one of them**.
22
+
23
+ ```bash
24
+ pip install treg-sdk
25
+ ```
26
+
27
+ Use an org-scoped token (`treg org agent-new <name>`), on your backend only. A token pinned to a tag
28
+ cannot act for your customers. `Treg()` reads
29
+ `TREG_TOKEN` and `TREG_URL` from the environment.
30
+
31
+ ```python
32
+ from treg_sdk import Treg
33
+
34
+ treg = Treg()
35
+ r = treg.call("google-search-console.sites")
36
+ print(r.data, r.call_id, r.cost_micro)
37
+ ```
38
+
39
+ ## Your customers' accounts
40
+
41
+ **1. Once:** ask treg to turn this on for your team. Then a team admin lists the hosts treg may send customers back to:
42
+ `PATCH /orgs/<team id>/settings {"connect_return_hosts": ["app.example.com"]}`.
43
+
44
+ **2. Make a consent link on your backend** and send the customer to it. Use your own id for them.
45
+
46
+ ```python
47
+ link = treg.end_users.connect(
48
+ "cust_42", "instagram",
49
+ return_url="https://app.example.com/integrations/done",
50
+ label="Ana's bakery",
51
+ )
52
+ # redirect the customer to link["consent_url"] (it works once, for link["expires_in_seconds"])
53
+ ```
54
+
55
+ **3. Read the outcome** when treg sends the customer back:
56
+
57
+ ```python
58
+ from treg_sdk import parse_connect_return
59
+
60
+ parse_connect_return(request_url) # ConnectReturn(status="connected" | "failed", provider, reason)
61
+ ```
62
+
63
+ **4. Call a catalog tool as that customer.** On an account provider only their
64
+ connection serves the call, never your team's. Search and data tools run on your team's key or balance.
65
+ Send `meta` too (`{"customer": "cust_42"}`): spend and limits per customer read only these tags.
66
+
67
+ ```python
68
+ ana = treg.for_end_user("cust_42")
69
+ sites = ana.call("google-search-console.sites")
70
+ ```
71
+
72
+ **Manage them:**
73
+
74
+ ```python
75
+ treg.end_users.list(q="cust", provider="instagram", attention=True)
76
+ for c in treg.end_users.iterate():
77
+ print(c["end_user"], c["providers"])
78
+ treg.end_users.get("cust_42") # connections, status, expiry
79
+ treg.end_users.disconnect("cust_42", "instagram")
80
+ treg.end_users.remove("cust_42")
81
+ ```
82
+
83
+ **An agent with MCP:** give the runtime this config. The model cannot choose or change the account.
84
+
85
+ ```python
86
+ cfg = treg.for_end_user("cust_42").mcp_config() # {"url": ..., "headers": {...}}
87
+ ```
88
+
89
+ ## Async
90
+
91
+ ```python
92
+ from treg_sdk import AsyncTreg
93
+
94
+ async with AsyncTreg() as treg:
95
+ r = await treg.for_end_user("cust_42").call("google-search-console.sites")
96
+ ```
97
+
98
+ ## Errors
99
+
100
+ Any non-2xx answer raises `TregError` with `status`, `code` (treg's error kind, for example
101
+ `end_user_not_connected` or `route_max_cost`; `None` for the provider's own error), `body` and
102
+ `call_id`.
103
+
104
+ ## Call options
105
+
106
+ `params`, `json` or `content`, `method`, `end_user`, `meta` (tags for spend and limits per customer),
107
+ `max_cost_usd` (refuse the call when its hold would pass this many USD), `idempotency_key`,
108
+ `headers`.
109
+
110
+ Leave `end_user` out for a call on your team's own account. A missing id (`None`) raises an error.
111
+
112
+ The full guide: https://treg.to/integrate.md
@@ -0,0 +1,7 @@
1
+ treg_sdk/__init__.py,sha256=qo6qeiYInlHluPz_Hp1bM1_aZwPuRC1KK_p9BWkRmks,515
2
+ treg_sdk/_client.py,sha256=0NIlybMLEV-ml1GVxAG43bMt5vuUJreyuHZmw63jfyI,20633
3
+ treg_sdk/_version.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
4
+ treg_sdk/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ treg_sdk-0.1.0.dist-info/METADATA,sha256=SkkiL6CuS_rJ7s7KLBOfY1FoIlEan6g3ml5SJRCbdCM,3766
6
+ treg_sdk-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
7
+ treg_sdk-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any