benchling-toolkit 0.4.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.
Files changed (38) hide show
  1. benchling_toolkit/__init__.py +6 -0
  2. benchling_toolkit/api.py +219 -0
  3. benchling_toolkit/auth.py +133 -0
  4. benchling_toolkit/change_spec.py +436 -0
  5. benchling_toolkit/cli.py +840 -0
  6. benchling_toolkit/config.py +57 -0
  7. benchling_toolkit/credentials.py +257 -0
  8. benchling_toolkit/environment.py +188 -0
  9. benchling_toolkit/errors.py +104 -0
  10. benchling_toolkit/export.py +662 -0
  11. benchling_toolkit/keychain.py +323 -0
  12. benchling_toolkit/listing.py +487 -0
  13. benchling_toolkit/mcp_server.py +847 -0
  14. benchling_toolkit/models.py +290 -0
  15. benchling_toolkit/plans/__init__.py +13 -0
  16. benchling_toolkit/plans/base.py +60 -0
  17. benchling_toolkit/plans/document.py +298 -0
  18. benchling_toolkit/plans/fields.py +300 -0
  19. benchling_toolkit/plans/planner.py +318 -0
  20. benchling_toolkit/plans/repository.py +105 -0
  21. benchling_toolkit/plans/result_update.py +845 -0
  22. benchling_toolkit/plans/results.py +184 -0
  23. benchling_toolkit/plans/table.py +241 -0
  24. benchling_toolkit/py.typed +0 -0
  25. benchling_toolkit/redact.py +67 -0
  26. benchling_toolkit/runtime.py +82 -0
  27. benchling_toolkit/services.py +1206 -0
  28. benchling_toolkit/tls.py +10 -0
  29. benchling_toolkit-0.4.0.data/data/share/benchling-toolkit/contracts/list-parameters.json +32 -0
  30. benchling_toolkit-0.4.0.data/data/share/benchling-toolkit/contracts/openapi-manifest.json +48 -0
  31. benchling_toolkit-0.4.0.data/data/share/benchling-toolkit/schemas/change-spec.schema.json +173 -0
  32. benchling_toolkit-0.4.0.data/data/share/benchling-toolkit/schemas/envelope.schema.json +30 -0
  33. benchling_toolkit-0.4.0.dist-info/METADATA +576 -0
  34. benchling_toolkit-0.4.0.dist-info/RECORD +38 -0
  35. benchling_toolkit-0.4.0.dist-info/WHEEL +5 -0
  36. benchling_toolkit-0.4.0.dist-info/entry_points.txt +2 -0
  37. benchling_toolkit-0.4.0.dist-info/licenses/LICENSE +22 -0
  38. benchling_toolkit-0.4.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,6 @@
1
+ """Safe, auditable Benchling tools shared by the CLI and MCP server."""
2
+
3
+ from .models import Envelope
4
+
5
+ __all__ = ["Envelope"]
6
+ __version__ = "0.4.0"
@@ -0,0 +1,219 @@
1
+ """Async Benchling HTTP client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import random
7
+ from collections.abc import AsyncIterator
8
+ from typing import Any
9
+
10
+ import httpx
11
+
12
+ from .auth import AuthManager
13
+ from .errors import (
14
+ AccessError,
15
+ ApiDriftError,
16
+ AuthenticationError,
17
+ ConflictError,
18
+ NotFoundError,
19
+ PartialCompletionError,
20
+ UpstreamError,
21
+ ValidationError,
22
+ )
23
+ from .models import Environment
24
+ from .redact import redact_text
25
+ from .tls import verified_context
26
+
27
+
28
+ class APIPayload(dict[str, Any]):
29
+ """JSON object from Benchling, with the HTTP status kept beside the body.
30
+
31
+ The status is an attribute, not a key, so journals and callers that treat the
32
+ payload as the response body do not see it unless they read ``status_code``.
33
+ """
34
+
35
+ status_code: int
36
+
37
+ def __init__(self, body: dict[str, Any], status_code: int) -> None:
38
+ super().__init__(body)
39
+ self.status_code = status_code
40
+
41
+
42
+ class BenchlingAPI:
43
+ """Small V2/V3 client with read-only retries and normalized errors."""
44
+
45
+ def __init__(
46
+ self,
47
+ environment: Environment,
48
+ auth: AuthManager,
49
+ *,
50
+ http: httpx.AsyncClient | None = None,
51
+ max_read_attempts: int = 3,
52
+ ) -> None:
53
+ self.environment = environment
54
+ self.auth = auth
55
+ self.http = http or httpx.AsyncClient(timeout=30.0, verify=verified_context())
56
+ self._owns_http = http is None
57
+ self.max_read_attempts = max_read_attempts
58
+
59
+ async def close(self) -> None:
60
+ """Close the HTTP client only if this instance created it."""
61
+ if self._owns_http:
62
+ await self.http.aclose()
63
+
64
+ async def request(
65
+ self,
66
+ method: str,
67
+ path: str,
68
+ *,
69
+ version: int = 3,
70
+ params: dict[str, Any] | None = None,
71
+ json: Any = None,
72
+ early_access: bool | None = None,
73
+ ) -> APIPayload:
74
+ """Send one request and return the decoded JSON object.
75
+
76
+ Only GET is retried. A non-GET with no confirmed response raises
77
+ PartialCompletionError because the write may have been applied.
78
+ """
79
+ method = method.upper()
80
+ if not path.startswith("/"):
81
+ raise ValidationError("API path must start with '/'")
82
+ base = f"{self.environment.base_url}/api/v{version}"
83
+ headers = {"Accept": "application/json", **self.auth.headers(self.environment)}
84
+ if version == 3 and early_access is not False:
85
+ headers["EARLY-ACCESS"] = "true"
86
+ attempts = self.max_read_attempts if method == "GET" else 1
87
+ response: httpx.Response | None = None
88
+ for attempt in range(attempts):
89
+ try:
90
+ response = await self.http.request(
91
+ method, f"{base}{path}", params=params, json=json, headers=headers
92
+ )
93
+ except (httpx.TimeoutException, httpx.NetworkError) as exc:
94
+ if method != "GET" or attempt + 1 >= attempts:
95
+ error_cls = PartialCompletionError if method != "GET" else UpstreamError
96
+ raise error_cls(
97
+ "Benchling request did not produce a confirmed response. Check the tenant URL.",
98
+ details={"method": method, "path": path, "reason": redact_text(str(exc))},
99
+ retryable=method == "GET",
100
+ ) from exc
101
+ await self._backoff(attempt, None)
102
+ continue
103
+ if (
104
+ method == "GET"
105
+ and response.status_code in {408, 429, 500, 502, 503, 504}
106
+ and attempt + 1 < attempts
107
+ ):
108
+ await self._backoff(attempt, response)
109
+ continue
110
+ break
111
+ assert response is not None
112
+ return self._decode(response, method=method, path=path)
113
+
114
+ async def paginate(
115
+ self,
116
+ path: str,
117
+ *,
118
+ version: int = 3,
119
+ params: dict[str, Any] | None = None,
120
+ item_key: str = "items",
121
+ max_items: int | None = None,
122
+ ) -> AsyncIterator[dict[str, Any]]:
123
+ """Yield items across nextToken pages, stopping at max_items.
124
+
125
+ Raises UpstreamError on a malformed page or a repeated token.
126
+ """
127
+ query = dict(params or {})
128
+ yielded = 0
129
+ seen_tokens: set[str] = set()
130
+ while True:
131
+ payload = await self.request("GET", path, version=version, params=query)
132
+ items = payload.get(item_key)
133
+ if not isinstance(items, list):
134
+ raise UpstreamError(
135
+ "Benchling pagination response has an unexpected shape",
136
+ details={"path": path, "expected_key": item_key, "keys": sorted(payload)},
137
+ )
138
+ for item in items:
139
+ if not isinstance(item, dict):
140
+ raise UpstreamError("Benchling returned a non-object list item")
141
+ yield item
142
+ yielded += 1
143
+ if max_items is not None and yielded >= max_items:
144
+ return
145
+ token = payload.get("nextToken")
146
+ if not token:
147
+ return
148
+ if token in seen_tokens:
149
+ raise UpstreamError(
150
+ "Benchling returned a repeated pagination token",
151
+ details={"path": path},
152
+ )
153
+ seen_tokens.add(token)
154
+ query["nextToken"] = token
155
+
156
+ async def _backoff(self, attempt: int, response: httpx.Response | None) -> None:
157
+ delay: float | None = None
158
+ if response is not None:
159
+ raw = response.headers.get("Retry-After")
160
+ try:
161
+ delay = min(float(raw), 10.0) if raw else None
162
+ except ValueError:
163
+ delay = None
164
+ if delay is None:
165
+ delay = min(0.25 * (2**attempt) + random.random() * 0.1, 2.0)
166
+ await asyncio.sleep(delay)
167
+
168
+ def _decode(self, response: httpx.Response, *, method: str, path: str) -> APIPayload:
169
+ payload: Any
170
+ if response.content:
171
+ try:
172
+ payload = response.json()
173
+ except ValueError:
174
+ payload = {"body": response.text[:2000]}
175
+ else:
176
+ payload = {}
177
+ details = {
178
+ "status": response.status_code,
179
+ "method": method,
180
+ "path": path,
181
+ "response": payload,
182
+ "request_id": response.headers.get("X-Request-ID"),
183
+ }
184
+ if response.status_code in {200, 201, 202, 204}:
185
+ if not isinstance(payload, dict):
186
+ raise UpstreamError(
187
+ "Benchling returned an unexpected response shape", details=details
188
+ )
189
+ return APIPayload(payload, response.status_code)
190
+ if response.status_code == 400:
191
+ raise ValidationError("Benchling rejected the request", details=details)
192
+ if response.status_code == 401:
193
+ raise AuthenticationError("Benchling authentication failed", details=details)
194
+ if response.status_code == 403:
195
+ raise AccessError("Benchling denied access", details=details)
196
+ if response.status_code == 404:
197
+ raise NotFoundError("Benchling resource was not found", details=details)
198
+ if response.status_code == 405:
199
+ allow = response.headers.get("Allow")
200
+ if allow:
201
+ details["allow"] = allow
202
+ raise ApiDriftError(
203
+ "This endpoint no longer supports this method. The Benchling API has drifted from this client.",
204
+ details=details,
205
+ )
206
+ if response.status_code == 409:
207
+ raise ConflictError("The Benchling resource changed since it was read", details=details)
208
+ if response.status_code == 429:
209
+ raise UpstreamError("Benchling rate limit exceeded", details=details, retryable=True)
210
+ if response.status_code >= 500 and method != "GET":
211
+ raise PartialCompletionError(
212
+ "Benchling returned a server error after receiving a write request; completion is unknown",
213
+ details=details,
214
+ )
215
+ if response.status_code >= 500:
216
+ raise UpstreamError(
217
+ "Benchling returned a server error", details=details, retryable=True
218
+ )
219
+ raise UpstreamError("Unexpected Benchling response", details=details)
@@ -0,0 +1,133 @@
1
+ """OAuth client-credentials token handling."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ from collections.abc import Mapping
7
+ from datetime import UTC, datetime, timedelta
8
+ from typing import Any
9
+
10
+ import httpx
11
+
12
+ from .errors import AuthenticationError, UpstreamError
13
+ from .models import Environment, TokenBundle
14
+ from .redact import redact_text, register_secret
15
+ from .tls import verified_context
16
+
17
+
18
+ class AuthManager:
19
+ """Client-credentials auth with an in-memory, per-environment token cache."""
20
+
21
+ def __init__(
22
+ self,
23
+ secrets: Mapping[str, str],
24
+ *,
25
+ http: httpx.Client | None = None,
26
+ ) -> None:
27
+ self.secrets = dict(secrets)
28
+ for secret in self.secrets.values():
29
+ register_secret(secret)
30
+ self.http = http or httpx.Client(timeout=30.0, verify=verified_context())
31
+ self._owns_http = http is None
32
+ self._app_tokens: dict[tuple[str, str, str | None], TokenBundle] = {}
33
+ self._app_lock = threading.Lock()
34
+
35
+ def close(self) -> None:
36
+ """Close the HTTP client only if this manager created it."""
37
+ if self._owns_http:
38
+ self.http.close()
39
+
40
+ def headers(self, environment: Environment) -> dict[str, str]:
41
+ """Return a Bearer Authorization header, fetching a token if the cache is empty or expired.
42
+
43
+ Raises AuthenticationError when credentials are missing or rejected.
44
+ """
45
+ return self._app_headers(environment)
46
+
47
+ def status(self, environment: Environment) -> dict[str, Any]:
48
+ """Describe credential state without network calls or exposing secrets."""
49
+ bundle = self._app_tokens.get(
50
+ (environment.name, environment.base_url, environment.client_id)
51
+ )
52
+ secret_present = bool(self.secrets.get(environment.name))
53
+ return {
54
+ "env": environment.name,
55
+ "method": environment.auth_method.value,
56
+ "configured": bool(environment.client_id and secret_present),
57
+ "secret_present": secret_present,
58
+ "tenant_url": environment.base_url,
59
+ "client_id": environment.client_id,
60
+ "credential_source": "keyring",
61
+ "identity": "app",
62
+ "access_token_cached": bundle.usable() if bundle else False,
63
+ }
64
+
65
+ def _app_headers(self, environment: Environment) -> dict[str, str]:
66
+ # Client credentials issue no refresh token. A long-lived MCP process
67
+ # requests a new access token on expiry; each CLI has its own cache.
68
+ with self._app_lock:
69
+ cache_key = (environment.name, environment.base_url, environment.client_id)
70
+ bundle = self._app_tokens.get(cache_key)
71
+ if bundle and bundle.usable():
72
+ return {"Authorization": f"Bearer {bundle.access_token}"}
73
+ secret = self.secrets.get(environment.name)
74
+ if not secret or not environment.client_id:
75
+ raise AuthenticationError("App client credentials are missing")
76
+ payload = self._token_request(
77
+ environment,
78
+ {
79
+ "grant_type": "client_credentials",
80
+ "client_id": environment.client_id,
81
+ "client_secret": secret,
82
+ },
83
+ )
84
+ bundle = self._bundle(payload)
85
+ if bundle.token_type.lower() != "bearer":
86
+ raise UpstreamError("Benchling returned an unsupported token type")
87
+ self._app_tokens[cache_key] = bundle
88
+ return {"Authorization": f"Bearer {bundle.access_token}"}
89
+
90
+ def _token_request(self, environment: Environment, data: dict[str, str]) -> dict[str, Any]:
91
+ identity = {"env": environment.name, "tenant_url": environment.base_url}
92
+ try:
93
+ response = self.http.post(
94
+ f"{environment.base_url}/oauth/token",
95
+ data=data,
96
+ headers={"Accept": "application/json"},
97
+ )
98
+ except httpx.HTTPError as exc:
99
+ raise UpstreamError(
100
+ "Could not reach the Benchling token endpoint. Check the tenant URL.",
101
+ details={**identity, "reason": redact_text(str(exc))},
102
+ retryable=True,
103
+ ) from exc
104
+ if response.status_code == 401:
105
+ raise AuthenticationError(
106
+ f"Benchling at {environment.base_url} rejected the client ID or secret.",
107
+ details={**identity, "status": response.status_code},
108
+ )
109
+ if response.status_code >= 400:
110
+ raise AuthenticationError(
111
+ "Benchling rejected authentication",
112
+ details={**identity, "status": response.status_code},
113
+ )
114
+ try:
115
+ token_response: dict[str, Any] = response.json()
116
+ return token_response
117
+ except ValueError as exc:
118
+ raise UpstreamError("Benchling returned an invalid token response") from exc
119
+
120
+ def _bundle(self, payload: dict[str, Any]) -> TokenBundle:
121
+ if not payload.get("access_token") or not payload.get("expires_in"):
122
+ raise UpstreamError(
123
+ "Benchling returned an incomplete token response",
124
+ details={"keys": sorted(payload)},
125
+ )
126
+ access_token = str(payload["access_token"])
127
+ register_secret(access_token)
128
+ now = datetime.now(UTC)
129
+ return TokenBundle(
130
+ access_token=access_token,
131
+ token_type=payload.get("token_type", "Bearer"),
132
+ expires_at=now + timedelta(seconds=int(payload["expires_in"])),
133
+ )