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,487 @@
1
+ """Paged, read-only discovery of entries, schemas, and dropdown options.
2
+
3
+ Entry filters are sent to the API version that actually applies them. V3
4
+ ``GET /entry/items`` has no folder parameter and live tenants ignore
5
+ ``folderId`` on that route, so a folder filter uses V2 ``GET /entries``.
6
+ A name that contains a comma also uses V2. ``name.anyOf`` and
7
+ ``names.anyOf`` are comma-separated lists, and the contract documents no
8
+ escape for a comma inside one name. V2 ``name`` is a single entry name.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import base64
14
+ import json
15
+ from datetime import UTC, datetime
16
+ from typing import Any
17
+
18
+ from .api import BenchlingAPI
19
+ from .errors import UpstreamError, ValidationError
20
+
21
+ LIST_LIMIT = 50
22
+ LIST_LIMIT_MAX = 100
23
+ SCHEMA_KINDS = ("entry", "result", "run")
24
+ SCHEMA_PATHS = {
25
+ "entry": "/entry-schema/items",
26
+ "result": "/result-schema/items",
27
+ "run": "/run-schema/items",
28
+ }
29
+
30
+ # Filters each entry-list route applies on the server. Nothing is filtered locally.
31
+ V3_ENTRY_FILTERS = ("project", "schema", "name", "modified_at")
32
+ V2_ENTRY_FILTERS = ("folder", "project", "schema", "name", "modified_at")
33
+
34
+
35
+ def schema_collection(schema_id: str) -> str:
36
+ """Return the V3 collection path segment for a schema id prefix."""
37
+ if schema_id.startswith("assaysch_"):
38
+ return "result-schema"
39
+ if schema_id.startswith("runsch_"):
40
+ return "run-schema"
41
+ return "entry-schema"
42
+
43
+
44
+ def check_limit(limit: object) -> int:
45
+ """Require a page size in the Benchling range of 1 to 100. Booleans are rejected."""
46
+ if isinstance(limit, bool) or not isinstance(limit, int) or not 1 <= limit <= LIST_LIMIT_MAX:
47
+ raise ValidationError("limit must be between 1 and 100")
48
+ return limit
49
+
50
+
51
+ def _text(value: object, label: str) -> str:
52
+ if not isinstance(value, str) or not value.strip():
53
+ raise ValidationError(f"{label} must be a non-empty string")
54
+ text = value.strip()
55
+ if "," in text:
56
+ raise ValidationError(f"{label} must not contain a comma")
57
+ return text
58
+
59
+
60
+ def _optional_text(value: object, label: str) -> str | None:
61
+ if value is None:
62
+ return None
63
+ return _text(value, label)
64
+
65
+
66
+ def _entry_name(value: object) -> str | None:
67
+ """One entry name. A comma is allowed; the caller chooses a parameter that can carry it."""
68
+ if value is None:
69
+ return None
70
+ if not isinstance(value, str) or not value.strip():
71
+ raise ValidationError("name must be a non-empty string")
72
+ return value.strip()
73
+
74
+
75
+ def _bound(value: object, *, end_of_day: bool) -> datetime | None:
76
+ """Parse a date or an RFC3339 timestamp that includes a time zone.
77
+
78
+ A bare date is the start or end of that UTC day. A timestamp with no zone
79
+ is rejected.
80
+ """
81
+ if value is None:
82
+ return None
83
+ if not isinstance(value, str) or not value.strip():
84
+ raise ValidationError("Modified date must be YYYY-MM-DD or an RFC3339 timestamp")
85
+ text = value.strip()
86
+ if len(text) == 10 and text[4] == "-" and text[7] == "-":
87
+ text = f"{text}T23:59:59Z" if end_of_day else f"{text}T00:00:00Z"
88
+ try:
89
+ parsed = datetime.fromisoformat(text.replace("Z", "+00:00"))
90
+ except ValueError as exc:
91
+ raise ValidationError("Modified date must be YYYY-MM-DD or an RFC3339 timestamp") from exc
92
+ if parsed.tzinfo is None or parsed.tzinfo.utcoffset(parsed) is None:
93
+ raise ValidationError(
94
+ "Modified timestamp has no time zone. Use YYYY-MM-DD or an RFC3339 "
95
+ "timestamp with a zone, such as 2026-06-15T12:00:00Z."
96
+ )
97
+ return parsed.astimezone(UTC)
98
+
99
+
100
+ def _timestamp_fraction(value: str) -> str:
101
+ """The source fractional seconds, including the dot, so ``.500`` stays ``.500``."""
102
+ start = value.find(".")
103
+ if start == -1:
104
+ return ""
105
+ end = start + 1
106
+ while end < len(value) and value[end].isdigit():
107
+ end += 1
108
+ if end == start + 1:
109
+ return ""
110
+ return value[start:end]
111
+
112
+
113
+ def utc_timestamp(value: object) -> object:
114
+ """Rewrite a timezone-aware timestamp as UTC with a ``Z`` suffix.
115
+
116
+ V2 listing responses use ``+00:00`` and V3 responses use ``Z``. A value that
117
+ is not a timezone-aware timestamp is returned unchanged.
118
+ """
119
+ if not isinstance(value, str) or not value:
120
+ return value
121
+ try:
122
+ parsed = datetime.fromisoformat(value.strip().replace("Z", "+00:00"))
123
+ except ValueError:
124
+ return value
125
+ if parsed.tzinfo is None or parsed.tzinfo.utcoffset(parsed) is None:
126
+ return value
127
+ utc = parsed.astimezone(UTC)
128
+ return f"{utc.strftime('%Y-%m-%dT%H:%M:%S')}{_timestamp_fraction(value)}Z"
129
+
130
+
131
+ def _stamp(value: datetime) -> str:
132
+ return value.strftime("%Y-%m-%dT%H:%M:%SZ")
133
+
134
+
135
+ def _modified_range(after: object, before: object) -> tuple[datetime | None, datetime | None]:
136
+ start = _bound(after, end_of_day=False)
137
+ end = _bound(before, end_of_day=True)
138
+ if start is not None and end is not None and start > end:
139
+ raise ValidationError("modified_after must not be later than modified_before")
140
+ return start, end
141
+
142
+
143
+ def _v2_modified(start: datetime | None, end: datetime | None) -> str | None:
144
+ """Inclusive V2 ``modifiedAt`` expression. V2 takes one comparison string."""
145
+ parts: list[str] = []
146
+ if start is not None:
147
+ parts.append(f">= {_stamp(start)}")
148
+ if end is not None:
149
+ parts.append(f"<= {_stamp(end)}")
150
+ return " AND ".join(parts) or None
151
+
152
+
153
+ def _items(payload: dict[str, Any], *, path: str, key: str = "items") -> list[dict[str, Any]]:
154
+ raw = payload.get(key)
155
+ if not isinstance(raw, list):
156
+ raise UpstreamError(
157
+ "Benchling pagination response has an unexpected shape",
158
+ details={"path": path, "expected_key": key, "keys": sorted(payload)},
159
+ )
160
+ items: list[dict[str, Any]] = []
161
+ for item in raw:
162
+ if not isinstance(item, dict):
163
+ raise UpstreamError("Benchling returned a non-object list item", details={"path": path})
164
+ items.append(item)
165
+ return items
166
+
167
+
168
+ def _next_token(payload: dict[str, Any]) -> str | None:
169
+ token = payload.get("nextToken")
170
+ if token is None or token == "":
171
+ return None
172
+ if not isinstance(token, str):
173
+ raise UpstreamError("Benchling returned a pagination token that is not a string")
174
+ return token
175
+
176
+
177
+ def entry_summary(item: dict[str, Any]) -> dict[str, Any]:
178
+ """One entry row, the same shape from a V3 item or a V2 entry."""
179
+ schema = item.get("typedSchema") or item.get("schema")
180
+ if isinstance(schema, dict):
181
+ schema_id = schema.get("id")
182
+ elif isinstance(schema, str):
183
+ schema_id = schema
184
+ else:
185
+ schema_id = item.get("schemaId")
186
+ folder = item.get("folder")
187
+ if isinstance(folder, dict):
188
+ folder_id = folder.get("id")
189
+ else:
190
+ folder_id = item.get("folderId")
191
+ project = item.get("project") or item.get("reviewSource")
192
+ if isinstance(project, dict):
193
+ project_id = project.get("id")
194
+ else:
195
+ project_id = item.get("projectId")
196
+ return {
197
+ "id": item.get("id"),
198
+ "name": item.get("name"),
199
+ "display_id": item.get("displayId"),
200
+ "modified_at": utc_timestamp(item.get("modifiedAt")),
201
+ "schema_id": schema_id,
202
+ "project_id": project_id,
203
+ "folder_id": folder_id,
204
+ }
205
+
206
+
207
+ async def _one_page(
208
+ api: BenchlingAPI,
209
+ path: str,
210
+ params: dict[str, Any],
211
+ *,
212
+ version: int,
213
+ item_key: str,
214
+ limit: int,
215
+ ) -> tuple[list[dict[str, Any]], str | None]:
216
+ """Read upstream pages until ``limit`` items are collected or the list ends."""
217
+ query = dict(params)
218
+ query["pageSize"] = limit
219
+ collected: list[dict[str, Any]] = []
220
+ seen: set[str] = set()
221
+ token: str | None = query.get("nextToken")
222
+ if isinstance(token, str):
223
+ seen.add(token)
224
+ while len(collected) < limit:
225
+ query["pageSize"] = limit - len(collected)
226
+ payload = await api.request("GET", path, version=version, params=query)
227
+ page = _items(payload, path=path, key=item_key)
228
+ if len(page) > query["pageSize"]:
229
+ raise UpstreamError(
230
+ "Benchling returned more items than pageSize",
231
+ details={"path": path, "page_size": query["pageSize"], "returned": len(page)},
232
+ )
233
+ collected.extend(page)
234
+ token = _next_token(payload)
235
+ if not token:
236
+ return collected, None
237
+ if token in seen:
238
+ raise UpstreamError(
239
+ "Benchling returned a repeated pagination token",
240
+ details={"path": path},
241
+ )
242
+ seen.add(token)
243
+ query["nextToken"] = token
244
+ return collected, token
245
+
246
+
247
+ async def list_entries(
248
+ api: BenchlingAPI,
249
+ *,
250
+ project: object = None,
251
+ folder: object = None,
252
+ schema_id: object = None,
253
+ name: object = None,
254
+ modified_after: object = None,
255
+ modified_before: object = None,
256
+ limit: object = LIST_LIMIT,
257
+ cursor: object = None,
258
+ ) -> dict[str, Any]:
259
+ """Return one page of entries.
260
+
261
+ Without a folder, and when the name has no comma, filters are V3 query
262
+ parameters. A folder filter, or a name that contains a comma, sends the
263
+ whole query to V2 so every filter is applied together.
264
+ """
265
+ page_size = check_limit(limit)
266
+ project_id = _optional_text(project, "project")
267
+ folder_id = _optional_text(folder, "folder")
268
+ schema = _optional_text(schema_id, "schema")
269
+ entry_name = _entry_name(name)
270
+ start, end = _modified_range(modified_after, modified_before)
271
+ if cursor is not None and (not isinstance(cursor, str) or not cursor):
272
+ raise ValidationError("cursor must be a non-empty string")
273
+ # V3 name.anyOf and V2 names.anyOf split on commas. V2 name is one name.
274
+ comma_name = entry_name is not None and "," in entry_name
275
+
276
+ if folder_id is not None or comma_name:
277
+ params: dict[str, Any] = {}
278
+ if folder_id is not None:
279
+ params["folderId"] = folder_id
280
+ if project_id is not None:
281
+ params["projectId"] = project_id
282
+ if schema is not None:
283
+ params["schemaId"] = schema
284
+ if entry_name is not None:
285
+ if comma_name:
286
+ params["name"] = entry_name
287
+ else:
288
+ params["names.anyOf"] = entry_name
289
+ modified = _v2_modified(start, end)
290
+ if modified is not None:
291
+ params["modifiedAt"] = modified
292
+ if isinstance(cursor, str):
293
+ params["nextToken"] = cursor
294
+ items, token = await _one_page(
295
+ api, "/entries", params, version=2, item_key="entries", limit=page_size
296
+ )
297
+ routing = {
298
+ "api_version": 2,
299
+ "path": "/entries",
300
+ "server_side": list(V2_ENTRY_FILTERS),
301
+ "client_side": [],
302
+ }
303
+ else:
304
+ params = {}
305
+ if project_id is not None:
306
+ params["project.eq"] = project_id
307
+ if schema is not None:
308
+ params["schema.eq"] = schema
309
+ if entry_name is not None:
310
+ params["name.anyOf"] = entry_name
311
+ if start is not None:
312
+ params["modifiedAt.gte"] = _stamp(start)
313
+ if end is not None:
314
+ params["modifiedAt.lte"] = _stamp(end)
315
+ if isinstance(cursor, str):
316
+ params["nextToken"] = cursor
317
+ items, token = await _one_page(
318
+ api, "/entry/items", params, version=3, item_key="items", limit=page_size
319
+ )
320
+ routing = {
321
+ "api_version": 3,
322
+ "path": "/entry/items",
323
+ "server_side": list(V3_ENTRY_FILTERS),
324
+ "client_side": [],
325
+ }
326
+ return {
327
+ "items": [entry_summary(item) for item in items],
328
+ "next_token": token,
329
+ "routing": routing,
330
+ }
331
+
332
+
333
+ def _encode_cursor(kind: str, token: str | None) -> str:
334
+ raw = json.dumps({"kind": kind, "token": token}, separators=(",", ":")).encode()
335
+ return base64.urlsafe_b64encode(raw).decode().rstrip("=")
336
+
337
+
338
+ def _decode_cursor(cursor: object, order: tuple[str, ...] | list[str]) -> tuple[int, str | None]:
339
+ if not isinstance(cursor, str) or not cursor:
340
+ raise ValidationError("cursor must be a non-empty string")
341
+ stripped = cursor.rstrip("=")
342
+ padded = stripped + "=" * (-len(stripped) % 4)
343
+ try:
344
+ payload = json.loads(base64.urlsafe_b64decode(padded))
345
+ except (ValueError, json.JSONDecodeError) as exc:
346
+ raise ValidationError("Schema page token is not valid") from exc
347
+ if not isinstance(payload, dict):
348
+ raise ValidationError("Schema page token is not valid")
349
+ kind = payload.get("kind")
350
+ token = payload.get("token")
351
+ if (
352
+ not isinstance(kind, str)
353
+ or kind not in order
354
+ or (token is not None and not isinstance(token, str))
355
+ ):
356
+ raise ValidationError(
357
+ "Schema page token does not match this list",
358
+ details={"kind": kind},
359
+ )
360
+ if token == "":
361
+ token = None
362
+ return order.index(kind), token
363
+
364
+
365
+ def _schema_summary(item: dict[str, Any], kind: str) -> dict[str, Any]:
366
+ return {
367
+ "id": item.get("id"),
368
+ "name": item.get("name"),
369
+ "kind": kind,
370
+ "modified_at": utc_timestamp(item.get("modifiedAt")),
371
+ }
372
+
373
+
374
+ async def list_schemas(
375
+ api: BenchlingAPI,
376
+ *,
377
+ kind: object = None,
378
+ limit: object = LIST_LIMIT,
379
+ cursor: object = None,
380
+ ) -> dict[str, Any]:
381
+ """Return one page of entry, result, and run schemas.
382
+
383
+ Upstream pages are followed until the page is full or every requested kind
384
+ is exhausted. The next token resumes at the following upstream page.
385
+ """
386
+ page_size = check_limit(limit)
387
+ if kind is None:
388
+ order = list(SCHEMA_KINDS)
389
+ elif kind in SCHEMA_KINDS:
390
+ order = [str(kind)]
391
+ else:
392
+ raise ValidationError(
393
+ "Schema kind must be entry, result, or run",
394
+ details={"supported": list(SCHEMA_KINDS)},
395
+ )
396
+ index = 0
397
+ token: str | None = None
398
+ if cursor is not None:
399
+ index, token = _decode_cursor(cursor, order)
400
+
401
+ items: list[dict[str, Any]] = []
402
+ seen: dict[str, set[str]] = {}
403
+ while index < len(order) and len(items) < page_size:
404
+ current = order[index]
405
+ path = SCHEMA_PATHS[current]
406
+ while len(items) < page_size:
407
+ params: dict[str, Any] = {"pageSize": page_size - len(items)}
408
+ if token:
409
+ params["nextToken"] = token
410
+ payload = await api.request("GET", path, params=params)
411
+ page = _items(payload, path=path)
412
+ if len(page) > params["pageSize"]:
413
+ raise UpstreamError(
414
+ "Benchling returned more items than pageSize",
415
+ details={
416
+ "path": path,
417
+ "page_size": params["pageSize"],
418
+ "returned": len(page),
419
+ },
420
+ )
421
+ items.extend(_schema_summary(item, current) for item in page)
422
+ token = _next_token(payload)
423
+ if not token:
424
+ break
425
+ seen_tokens = seen.setdefault(current, set())
426
+ if token in seen_tokens:
427
+ raise UpstreamError(
428
+ "Benchling returned a repeated pagination token",
429
+ details={"path": path},
430
+ )
431
+ seen_tokens.add(token)
432
+ if len(items) >= page_size:
433
+ break
434
+ index += 1
435
+ token = None
436
+
437
+ next_token: str | None = None
438
+ if len(items) >= page_size:
439
+ if token:
440
+ next_token = _encode_cursor(order[index], token)
441
+ elif index + 1 < len(order):
442
+ next_token = _encode_cursor(order[index + 1], None)
443
+ return {"items": items, "next_token": next_token, "kinds": order}
444
+
445
+
446
+ def dropdown_id_of(field: dict[str, Any]) -> str | None:
447
+ """Return the dropdown id a field definition points at, if it has one."""
448
+ direct = field.get("dropdownId")
449
+ if isinstance(direct, str) and direct:
450
+ return direct
451
+ link = field.get("linkDefinition")
452
+ if isinstance(link, dict):
453
+ linked = link.get("id")
454
+ if isinstance(linked, str) and linked:
455
+ return linked
456
+ return None
457
+
458
+
459
+ async def load_dropdown(api: BenchlingAPI, dropdown_id: str) -> dict[str, Any]:
460
+ """Fetch one dropdown and every option on ``/dropdown/{id}/options/items``."""
461
+ dropdown = await api.request("GET", f"/dropdown/{dropdown_id}")
462
+ options = await api.request("GET", f"/dropdown/{dropdown_id}/options/items")
463
+ raw = options.get("items")
464
+ if not isinstance(raw, list):
465
+ raise UpstreamError(
466
+ "Dropdown options response has an unexpected shape",
467
+ details={"dropdown_id": dropdown_id, "keys": sorted(options)},
468
+ )
469
+ parsed: list[dict[str, Any]] = []
470
+ for item in raw:
471
+ if not isinstance(item, dict):
472
+ raise UpstreamError(
473
+ "Benchling returned a non-object dropdown option",
474
+ details={"dropdown_id": dropdown_id},
475
+ )
476
+ parsed.append(
477
+ {
478
+ "id": item.get("id"),
479
+ "name": item.get("name"),
480
+ "archived": bool(item.get("archived")),
481
+ }
482
+ )
483
+ return {
484
+ "id": dropdown.get("id", dropdown_id),
485
+ "name": dropdown.get("name"),
486
+ "options": parsed,
487
+ }