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,436 @@
1
+ """Typed change specifications for the MCP plan_changes tool.
2
+
3
+ The CLI still passes the JSON object through to the planner. MCP validates the
4
+ same shapes first and returns a validation_error envelope when one does not match.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import copy
10
+ from typing import Annotated, Any, Literal, TypeVar, cast
11
+
12
+ from pydantic import (
13
+ BaseModel,
14
+ ConfigDict,
15
+ Field,
16
+ TypeAdapter,
17
+ ValidationError,
18
+ field_validator,
19
+ model_validator,
20
+ )
21
+
22
+ from .errors import ValidationError as InputError
23
+
24
+ _STRICT = ConfigDict(extra="forbid", strict=True)
25
+
26
+
27
+ _T = TypeVar("_T")
28
+
29
+
30
+ def _omit(value: _T | None) -> _T:
31
+ """Reject JSON null for a field the caller may only omit."""
32
+ if value is None:
33
+ raise ValueError("null is not accepted; omit the field")
34
+ return value
35
+
36
+
37
+ class InsertedPart(BaseModel):
38
+ """One document part to insert. Other part fields are kept."""
39
+
40
+ model_config = ConfigDict(extra="allow", strict=True)
41
+
42
+ contentType: str = Field(min_length=1, description="Part content type, such as text.")
43
+
44
+
45
+ class DocumentInsert(BaseModel):
46
+ """Insert one or more document parts."""
47
+
48
+ model_config = _STRICT
49
+
50
+ operation: Literal["insert"] = Field(description="Insert one or more document parts.")
51
+ position: str = Field(
52
+ default="end_of_document",
53
+ min_length=1,
54
+ description=(
55
+ "Where to insert. beginning_of_document, end_of_document, or a part ID. "
56
+ "A part ID inserts immediately before that part. Defaults to end_of_document."
57
+ ),
58
+ )
59
+ parts: list[InsertedPart] = Field(
60
+ min_length=1,
61
+ description="Document parts to insert. Each part needs a contentType.",
62
+ )
63
+
64
+
65
+ class DocumentDelete(BaseModel):
66
+ """Delete one document part or a contiguous range."""
67
+
68
+ model_config = _STRICT
69
+
70
+ operation: Literal["delete"] = Field(description="Delete a range of document parts.")
71
+ from_part_id: str = Field(
72
+ min_length=1, description="First document part ID in the range to delete."
73
+ )
74
+ to_part_id: str | None = Field(
75
+ default=None,
76
+ min_length=1,
77
+ description="Last document part ID in the range. Omit it to delete only from_part_id.",
78
+ )
79
+
80
+ @field_validator("to_part_id")
81
+ @classmethod
82
+ def to_part_present(cls, value: str | None) -> str | None:
83
+ """Allow the field to be omitted, and reject JSON null."""
84
+ return _omit(value)
85
+
86
+
87
+ class DocumentMove(BaseModel):
88
+ """Move one document part or a contiguous range."""
89
+
90
+ model_config = _STRICT
91
+
92
+ operation: Literal["move"] = Field(description="Move a range of document parts.")
93
+ from_part_id: str = Field(
94
+ min_length=1, description="First document part ID in the range to move."
95
+ )
96
+ to_part_id: str | None = Field(
97
+ default=None,
98
+ min_length=1,
99
+ description="Last document part ID in the range. Omit it to move only from_part_id.",
100
+ )
101
+ position: str = Field(
102
+ min_length=1,
103
+ description=(
104
+ "Where to move the range. beginning_of_document, end_of_document, or a part ID. "
105
+ "A part ID moves the range immediately before that part."
106
+ ),
107
+ )
108
+
109
+ @field_validator("to_part_id")
110
+ @classmethod
111
+ def to_part_present(cls, value: str | None) -> str | None:
112
+ """Allow the field to be omitted, and reject JSON null."""
113
+ return _omit(value)
114
+
115
+
116
+ class DocumentReplaceText(BaseModel):
117
+ """Replace the text of one text document part."""
118
+
119
+ model_config = _STRICT
120
+
121
+ operation: Literal["replace_text"] = Field(
122
+ description="Replace the text of one text document part."
123
+ )
124
+ part_id: str = Field(min_length=1, description="Document part ID of the text part to replace.")
125
+ text: str = Field(description="Replacement text.")
126
+ formats: list[Any] | None = Field(
127
+ default=None,
128
+ description="Text formats to store. Omit to keep the part's current formats.",
129
+ )
130
+ links: list[Any] | None = Field(
131
+ default=None,
132
+ description="Links to store. Omit to keep the part's current links.",
133
+ )
134
+ mentions: list[Any] | None = Field(
135
+ default=None,
136
+ description="Mentions to store. Omit to keep the part's current mentions.",
137
+ )
138
+ indentation: int | None = Field(
139
+ default=None,
140
+ ge=0,
141
+ description="Indentation level, zero or greater. Omit to keep the current indentation.",
142
+ )
143
+
144
+ @field_validator("formats", "links", "mentions", "indentation")
145
+ @classmethod
146
+ def optional_present(cls, value: Any) -> Any:
147
+ """Allow these fields to be omitted, and reject JSON null."""
148
+ return _omit(value)
149
+
150
+
151
+ class CellUpdate(BaseModel):
152
+ """One unstructured-table cell write."""
153
+
154
+ model_config = _STRICT
155
+
156
+ row: int = Field(ge=0, description="Zero-based row index.")
157
+ column: int = Field(ge=0, description="Zero-based column index.")
158
+ value: Any = Field(description="New cell input. It is stored as text.")
159
+
160
+
161
+ class TableSetCells(BaseModel):
162
+ """Set the input of selected unstructured-table cells."""
163
+
164
+ model_config = _STRICT
165
+
166
+ operation: Literal["set_cells"] = Field(
167
+ description="Replace the input of selected unstructured-table cells."
168
+ )
169
+ table_part_id: str = Field(
170
+ min_length=1,
171
+ pattern=r"^docpart_",
172
+ description="Document part ID of the unstructured table. It starts with docpart_.",
173
+ )
174
+ updates: list[CellUpdate] = Field(
175
+ min_length=1,
176
+ description="Cells to write. Each item has row, column, and value.",
177
+ )
178
+
179
+
180
+ class TableAppendRows(BaseModel):
181
+ """Append rows to an unstructured table."""
182
+
183
+ model_config = _STRICT
184
+
185
+ operation: Literal["append_rows"] = Field(
186
+ description="Append rows to the end of an unstructured table."
187
+ )
188
+ table_part_id: str = Field(
189
+ min_length=1,
190
+ pattern=r"^docpart_",
191
+ description="Document part ID of the unstructured table. It starts with docpart_.",
192
+ )
193
+ rows: list[Any] = Field(
194
+ min_length=1,
195
+ description=(
196
+ "Rows to append. Each row is a list of cells or an object with a cells list. "
197
+ "The row must match the table width."
198
+ ),
199
+ )
200
+
201
+
202
+ class FieldValueInput(BaseModel):
203
+ """One schema field value. The only property is value."""
204
+
205
+ model_config = _STRICT
206
+
207
+ value: Any = Field(
208
+ description=(
209
+ "New field value, or null to clear an optional field. The type must match "
210
+ "the schema field."
211
+ )
212
+ )
213
+
214
+
215
+ class FieldChange(BaseModel):
216
+ """Update fields on the entry's assigned schema."""
217
+
218
+ model_config = _STRICT
219
+
220
+ schema_fields: dict[str, FieldValueInput] = Field(
221
+ min_length=1,
222
+ description=(
223
+ "Entry schema fields to update. Keys are V3 system names or field-definition "
224
+ "IDs. Each value is an object with a single value property."
225
+ ),
226
+ )
227
+
228
+
229
+ class AssayResultRecord(BaseModel):
230
+ """One new result record for a notebook table upload."""
231
+
232
+ model_config = _STRICT
233
+
234
+ schemaId: str = Field(
235
+ min_length=1,
236
+ description="Result schema ID. It must be the schema assigned to the table.",
237
+ )
238
+ projectId: str | None = Field(
239
+ default=None,
240
+ min_length=1,
241
+ description="Project ID for the new result, or null to leave it unscoped.",
242
+ )
243
+ fields: dict[str, FieldValueInput] = Field(
244
+ description=(
245
+ "Result fields. Keys are V3 system names or field-definition IDs. Each value "
246
+ "is an object with a single value property."
247
+ )
248
+ )
249
+
250
+ @model_validator(mode="before")
251
+ @classmethod
252
+ def omit_id(cls, data: Any) -> Any:
253
+ """Result ids are assigned by the server. A caller-supplied id is rejected."""
254
+ if isinstance(data, dict) and "id" in data:
255
+ raise ValueError("Notebook table uploads use server-assigned result IDs; omit id")
256
+ return data
257
+
258
+
259
+ class ResultUpload(BaseModel):
260
+ """Upload new result records to an explicit V2 result table."""
261
+
262
+ model_config = _STRICT
263
+
264
+ table_id: str = Field(
265
+ min_length=1,
266
+ pattern=r"^strtbl_",
267
+ description="V2 result table ID. It starts with strtbl_.",
268
+ )
269
+ assay_results: list[AssayResultRecord] = Field(
270
+ min_length=1,
271
+ description="New result records to upload to that table.",
272
+ )
273
+
274
+
275
+ class ResultCsvUpdate(BaseModel):
276
+ """Update existing results from a CSV file and an explicit column map."""
277
+
278
+ model_config = _STRICT
279
+
280
+ operation: Literal["update"] = Field(description="Update existing results from a CSV file.")
281
+ csv_path: str = Field(
282
+ min_length=1,
283
+ description=(
284
+ "Path to a CSV file on this machine. An assay-result export writes a file "
285
+ "this planner can read."
286
+ ),
287
+ )
288
+ id_column: str = Field(
289
+ min_length=1,
290
+ description="CSV header that holds the result id. Export writes this column as id.",
291
+ )
292
+ column_map: dict[str, Annotated[str, Field(min_length=1)]] = Field(
293
+ min_length=1,
294
+ description=(
295
+ "CSV header to a field display name, system name, or field-definition id. "
296
+ "The plan resolves each one to a field-definition id."
297
+ ),
298
+ )
299
+
300
+ @field_validator("column_map")
301
+ @classmethod
302
+ def column_names(cls, value: dict[str, str]) -> dict[str, str]:
303
+ """Reject a blank CSV header. The planner strips and checks the rest."""
304
+ if any(not key.strip() for key in value):
305
+ raise ValueError("column_map keys must be CSV column names")
306
+ return value
307
+
308
+
309
+ ChangeSpecification = (
310
+ DocumentInsert
311
+ | DocumentDelete
312
+ | DocumentMove
313
+ | DocumentReplaceText
314
+ | TableSetCells
315
+ | TableAppendRows
316
+ | FieldChange
317
+ | ResultUpload
318
+ | ResultCsvUpdate
319
+ )
320
+
321
+ _BY_OPERATION: dict[str, type[BaseModel]] = {
322
+ "insert": DocumentInsert,
323
+ "delete": DocumentDelete,
324
+ "move": DocumentMove,
325
+ "replace_text": DocumentReplaceText,
326
+ "set_cells": TableSetCells,
327
+ "append_rows": TableAppendRows,
328
+ "update": ResultCsvUpdate,
329
+ }
330
+
331
+ _SUPPORTED = [
332
+ "document: insert, delete, move, replace_text",
333
+ "table: set_cells, append_rows",
334
+ "fields: schema_fields",
335
+ "results upload: table_id and assay_results",
336
+ "results update: operation update, csv_path, id_column, column_map",
337
+ ]
338
+
339
+
340
+ def _inline_json_schema(schema: dict[str, Any]) -> dict[str, Any]:
341
+ """Copy a schema so every local $ref is replaced by its definition.
342
+
343
+ MCP publishes a parameter schema on its own. A $ref to a definition that lives
344
+ only inside this object does not resolve there.
345
+ """
346
+ definitions = schema.get("$defs", {})
347
+
348
+ def resolve(node: Any) -> Any:
349
+ if isinstance(node, dict):
350
+ ref = node.get("$ref")
351
+ if isinstance(ref, str) and ref.startswith("#/$defs/"):
352
+ target = cast(
353
+ dict[str, Any],
354
+ resolve(copy.deepcopy(definitions[ref.removeprefix("#/$defs/")])),
355
+ )
356
+ extras = {key: resolve(value) for key, value in node.items() if key != "$ref"}
357
+ return {**target, **extras}
358
+ return {key: resolve(value) for key, value in node.items() if key != "$defs"}
359
+ if isinstance(node, list):
360
+ return [resolve(item) for item in node]
361
+ return node
362
+
363
+ return cast(dict[str, Any], resolve(schema))
364
+
365
+
366
+ CHANGE_SPECIFICATION_SCHEMA: dict[str, Any] = _inline_json_schema(
367
+ TypeAdapter(ChangeSpecification).json_schema()
368
+ )
369
+
370
+
371
+ def _model_for(value: dict[str, Any]) -> type[BaseModel]:
372
+ """Pick the one shape this object is claiming to be."""
373
+ operation = value.get("operation")
374
+ if isinstance(operation, str) and operation in _BY_OPERATION:
375
+ return _BY_OPERATION[operation]
376
+ if any(key in value for key in ("csv_path", "id_column", "column_map")):
377
+ return ResultCsvUpdate
378
+ has_fields = "schema_fields" in value
379
+ has_results = "table_id" in value or "assay_results" in value
380
+ if has_fields and has_results:
381
+ raise InputError(
382
+ "Change specification mixes field updates and result records",
383
+ details={"supported": _SUPPORTED},
384
+ )
385
+ if has_fields:
386
+ return FieldChange
387
+ if has_results:
388
+ return ResultUpload
389
+ raise InputError(
390
+ "Change specification does not match a supported shape",
391
+ details={"supported": _SUPPORTED},
392
+ )
393
+
394
+
395
+ def _error_details(exc: ValidationError) -> list[dict[str, Any]]:
396
+ """JSON-safe locations and messages. The rejected values are not included."""
397
+ details = []
398
+ for err in exc.errors():
399
+ details.append(
400
+ {
401
+ "path": ".".join(str(part) for part in err["loc"]),
402
+ "message": str(err["msg"]),
403
+ "type": str(err["type"]),
404
+ }
405
+ )
406
+ return details
407
+
408
+
409
+ def _error_message(exc: ValidationError) -> str:
410
+ """One sentence naming each invalid field."""
411
+ pieces = []
412
+ for err in exc.errors():
413
+ path = ".".join(str(part) for part in err["loc"]) or "specification"
414
+ pieces.append(f"{path}: {err['msg']}")
415
+ return "Change specification is invalid: " + "; ".join(pieces)
416
+
417
+
418
+ def parse_change_specification(value: Any) -> dict[str, Any]:
419
+ """Validate a plan_changes specification and return the planner's object.
420
+
421
+ Omitted optional fields stay omitted. JSON null is kept only for projectId
422
+ and for a field value, where null is meaningful.
423
+
424
+ Raises InputError when the value is not one of the supported shapes.
425
+ """
426
+ if not isinstance(value, dict):
427
+ raise InputError(
428
+ "Change specification must be an object",
429
+ details={"received": type(value).__name__},
430
+ )
431
+ model = _model_for(value)
432
+ try:
433
+ parsed = model.model_validate(value)
434
+ except ValidationError as exc:
435
+ raise InputError(_error_message(exc), details={"errors": _error_details(exc)}) from exc
436
+ return parsed.model_dump(mode="json", exclude_unset=True)