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,840 @@
1
+ """Typer CLI: every command prints a JSON Envelope on stdout and exits with an ExitCode."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import getpass
7
+ import io
8
+ import json
9
+ import os
10
+ import sys
11
+ from collections.abc import Awaitable, Callable
12
+ from pathlib import Path
13
+ from typing import Any, NoReturn
14
+
15
+ import typer
16
+
17
+ from . import __version__
18
+ from .credentials import build_environment, collect_status, login, login_fix_values, logout
19
+ from .environment import ENV_NAME, EnvironmentConfigStore, invalid_environment_name
20
+ from .errors import (
21
+ AuthenticationError,
22
+ BenchlingAgentError,
23
+ ExitCode,
24
+ UpstreamError,
25
+ ValidationError,
26
+ )
27
+ from .export import export_dataset
28
+ from .keychain import Keychain, bind_login_fix
29
+ from .models import Envelope, Environment, PlanFamily
30
+ from .redact import redact_text
31
+ from .runtime import Runtime
32
+
33
+ app = typer.Typer(
34
+ name="benchling",
35
+ help="Safe, auditable tools for structured Benchling entry data.",
36
+ no_args_is_help=True,
37
+ pretty_exceptions_enable=False,
38
+ )
39
+ auth_app = typer.Typer(help="Log in, log out, and inspect saved environments.")
40
+ entry_app = typer.Typer(help="Resolve, list, fetch, and inspect entries.")
41
+ entry_fields_app = typer.Typer(help="Read entry schema fields.")
42
+ section_app = typer.Typer(help="Read entry sections.")
43
+ part_app = typer.Typer(help="Read document parts.")
44
+ table_app = typer.Typer(help="Read unstructured tables.")
45
+ schema_app = typer.Typer(help="List and read entry, result, and run schemas.")
46
+ results_app = typer.Typer(help="Read result records and results-table rows.")
47
+ changes_app = typer.Typer(help="Preview and explicitly apply safe changes.")
48
+ mcp_app = typer.Typer(help="Run the local MCP server.")
49
+
50
+ app.add_typer(auth_app, name="auth")
51
+ app.add_typer(entry_app, name="entry")
52
+ entry_app.add_typer(entry_fields_app, name="fields")
53
+ app.add_typer(section_app, name="section")
54
+ app.add_typer(part_app, name="part")
55
+ app.add_typer(table_app, name="table")
56
+ app.add_typer(schema_app, name="schema")
57
+ app.add_typer(results_app, name="results")
58
+ app.add_typer(changes_app, name="changes")
59
+ app.add_typer(mcp_app, name="mcp")
60
+
61
+
62
+ class State:
63
+ """Per-invocation state stored on the Typer context; env is the --env selection."""
64
+
65
+ def __init__(self, env: str | None) -> None:
66
+ self.env = env
67
+
68
+
69
+ def _show_version(value: bool) -> None:
70
+ if value:
71
+ typer.echo(f"benchling-toolkit {__version__}")
72
+ raise typer.Exit()
73
+
74
+
75
+ @app.callback()
76
+ def root(
77
+ ctx: typer.Context,
78
+ env: str | None = typer.Option(None, "--env", "-e", help="Environment name."),
79
+ version: bool = typer.Option(
80
+ False, "--version", callback=_show_version, is_eager=True, help="Show version and exit."
81
+ ),
82
+ ) -> None:
83
+ """Safe, auditable tools for structured Benchling entry data."""
84
+ ctx.obj = State(env)
85
+
86
+
87
+ def _json(value: Any) -> str:
88
+ if hasattr(value, "model_dump"):
89
+ value = value.model_dump(mode="json")
90
+ return json.dumps(value, indent=2, ensure_ascii=False, default=str)
91
+
92
+
93
+ def _emit(envelope: Envelope[Any]) -> None:
94
+ typer.echo(_json(envelope))
95
+
96
+
97
+ async def _run_with_runtime(
98
+ env: str | None, call: Callable[[Runtime], Awaitable[Any]]
99
+ ) -> tuple[Any, Environment]:
100
+ runtime = Runtime(env)
101
+ try:
102
+ return await call(runtime), runtime.environment
103
+ finally:
104
+ await runtime.close()
105
+
106
+
107
+ def _execute(env: str | None, call: Callable[[Runtime], Awaitable[Any]]) -> None:
108
+ try:
109
+ result, runtime_env = asyncio.run(_run_with_runtime(env, call))
110
+ _emit(
111
+ Envelope.success(
112
+ result,
113
+ env=runtime_env.name,
114
+ tenant_url=runtime_env.base_url,
115
+ )
116
+ )
117
+ except BenchlingAgentError as exc:
118
+ _emit(Envelope.failure(exc))
119
+ raise typer.Exit(int(exc.exit_code)) from None
120
+ except Exception as exc:
121
+ error = UpstreamError("Unexpected local failure", details={"type": type(exc).__name__})
122
+ _emit(Envelope.failure(error))
123
+ raise typer.Exit(int(ExitCode.UPSTREAM)) from None
124
+
125
+
126
+ def _prompt(label: str, *, tty: bool) -> str:
127
+ """Read one non-secret line. --secret-stdin keeps stdin free for the secret."""
128
+ if tty:
129
+ line = _read_terminal(label)
130
+ else:
131
+ typer.echo(f"{label}: ", nl=False, err=True)
132
+ line = sys.stdin.readline()
133
+ if not line.strip():
134
+ raise ValidationError(f"{label} is required")
135
+ return line.strip()
136
+
137
+
138
+ def _read_terminal(label: str) -> str:
139
+ """Prompt on the controlling terminal so a piped secret is not consumed.
140
+
141
+ Builtin open(..., "r+") is rejected on Linux and macOS: a terminal is not
142
+ seekable, and Python's text wrapper tries to seek. os.open plus FileIO
143
+ is the mode the standard library uses for /dev/tty.
144
+ """
145
+ prompt = f"{label}: "
146
+ try:
147
+ if os.name == "nt":
148
+ with (
149
+ open("CONOUT$", "w", encoding="utf-8") as output,
150
+ open("CONIN$", encoding="utf-8") as incoming,
151
+ ):
152
+ output.write(prompt)
153
+ output.flush()
154
+ return incoming.readline()
155
+ return _read_posix_tty("/dev/tty", prompt)
156
+ except OSError as exc:
157
+ raise ValidationError(
158
+ "A terminal is required for the tenant URL and client ID when --secret-stdin is set"
159
+ ) from exc
160
+
161
+
162
+ def _read_posix_tty(path: str, prompt: str) -> str:
163
+ """Read one line from a terminal device. ``path`` is /dev/tty in production."""
164
+ fd = os.open(path, os.O_RDWR | os.O_NOCTTY)
165
+ stream = io.TextIOWrapper(
166
+ io.FileIO(fd, "w+"),
167
+ encoding="utf-8",
168
+ errors="replace",
169
+ line_buffering=True,
170
+ write_through=True,
171
+ )
172
+ try:
173
+ stream.write(prompt)
174
+ stream.flush()
175
+ return stream.readline()
176
+ finally:
177
+ stream.close()
178
+
179
+
180
+ def _stdin_is_tty() -> bool:
181
+ try:
182
+ return bool(sys.stdin.isatty())
183
+ except Exception:
184
+ return False
185
+
186
+
187
+ def _controlling_tty_available() -> bool:
188
+ if os.name == "nt":
189
+ try:
190
+ with open("CONIN$", encoding="utf-8"):
191
+ return True
192
+ except OSError:
193
+ return False
194
+ try:
195
+ fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY)
196
+ except OSError:
197
+ return False
198
+ os.close(fd)
199
+ return True
200
+
201
+
202
+ def _prompts_available(*, secret_on_stdin: bool) -> bool:
203
+ """True when a human can be prompted. A piped secret must not use stdin for that."""
204
+ if secret_on_stdin:
205
+ return _controlling_tty_available()
206
+ return _stdin_is_tty() or _controlling_tty_available()
207
+
208
+
209
+ def _noninteractive_login_error(*, url: bool, client: bool, secret: bool) -> ValidationError:
210
+ flags: list[str] = []
211
+ if url:
212
+ flags.append("--tenant-url")
213
+ if client:
214
+ flags.append("--client-id")
215
+ if secret:
216
+ flags.append("--secret-stdin")
217
+ if len(flags) == 1:
218
+ listed = flags[0]
219
+ elif len(flags) == 2:
220
+ listed = f"{flags[0]} and {flags[1]}"
221
+ else:
222
+ listed = ", ".join(flags[:-1]) + ", and " + flags[-1]
223
+ return ValidationError(
224
+ f"No terminal is available to prompt for login. Pass {listed}.",
225
+ details={"missing_flags": flags},
226
+ )
227
+
228
+
229
+ def _read_secret(secret_stdin: bool) -> str:
230
+ """Read the client secret from stdin or a hidden prompt. Never from argv."""
231
+ if secret_stdin:
232
+ value = sys.stdin.read()
233
+ if value.endswith("\r\n"):
234
+ value = value[:-2]
235
+ elif value.endswith("\n"):
236
+ value = value[:-1]
237
+ if value.strip() == "":
238
+ raise ValidationError("No client secret was received on stdin")
239
+ return value
240
+ try:
241
+ secret = getpass.getpass("Client secret (not echoed): ")
242
+ except EOFError as exc:
243
+ raise ValidationError("Client secret is required") from exc
244
+ if secret == "":
245
+ raise ValidationError("Client secret is required")
246
+ return secret
247
+
248
+
249
+ def _auth_failure(exc: BenchlingAgentError) -> NoReturn:
250
+ _emit(Envelope.failure(exc))
251
+ raise typer.Exit(int(exc.exit_code)) from None
252
+
253
+
254
+ def _require_env_name(name: str | None, store: EnvironmentConfigStore) -> str:
255
+ names = store.configured_names() if store.environments_path.exists() else []
256
+ if not name:
257
+ raise ValidationError(
258
+ "An environment is required; pass --env NAME",
259
+ details={"available_envs": names},
260
+ )
261
+ if not ENV_NAME.match(name):
262
+ raise invalid_environment_name(name, available=names)
263
+ return name
264
+
265
+
266
+ def _blank_to_none(value: str | None) -> str | None:
267
+ if value is None:
268
+ return None
269
+ stripped = value.strip()
270
+ return stripped or None
271
+
272
+
273
+ @auth_app.command("login")
274
+ def auth_login(
275
+ ctx: typer.Context,
276
+ env: str | None = typer.Option(None, "--env", "-e", help="Environment name to save."),
277
+ tenant_url: str | None = typer.Option(
278
+ None,
279
+ "--tenant-url",
280
+ help="Tenant URL or bare host. https:// is added when omitted; a trailing /api/v2 or /api/v3 is removed.",
281
+ ),
282
+ client_id: str | None = typer.Option(None, "--client-id", help="App client ID."),
283
+ secret_stdin: bool = typer.Option(
284
+ False,
285
+ "--secret-stdin",
286
+ help="Read the client secret from stdin. It is never accepted as an argument.",
287
+ ),
288
+ ) -> None:
289
+ """Save a verified client secret for one environment.
290
+
291
+ With --tenant-url, --client-id, and --secret-stdin, login does not need a
292
+ terminal. Otherwise the missing values are prompted when a terminal exists.
293
+ The secret is never accepted as an argument. Nothing is saved unless a
294
+ client-credentials token request succeeds.
295
+ """
296
+ state: State = ctx.obj
297
+ store = EnvironmentConfigStore()
298
+ try:
299
+ name = _require_env_name(env or state.env, store)
300
+ url = _blank_to_none(tenant_url)
301
+ client = _blank_to_none(client_id)
302
+ fix_url, fix_client = login_fix_values(store, name, url, client)
303
+ with bind_login_fix(env=name, tenant_url=fix_url, client_id=fix_client):
304
+ Keychain().require()
305
+ missing_url = url is None
306
+ missing_client = client is None
307
+ missing_secret = not secret_stdin
308
+ if (missing_url or missing_client or missing_secret) and not _prompts_available(
309
+ secret_on_stdin=secret_stdin
310
+ ):
311
+ raise _noninteractive_login_error(
312
+ url=missing_url, client=missing_client, secret=missing_secret
313
+ )
314
+ use_terminal = secret_stdin or not _stdin_is_tty()
315
+ if missing_url:
316
+ url = _prompt("Tenant URL", tty=use_terminal)
317
+ if missing_client:
318
+ client = _prompt("Client ID", tty=use_terminal)
319
+ assert url is not None and client is not None
320
+ build_environment(name, url, client)
321
+ secret = _read_secret(secret_stdin)
322
+ environment = login(
323
+ store,
324
+ Keychain(),
325
+ name=name,
326
+ tenant_url=url,
327
+ client_id=client,
328
+ secret=secret,
329
+ )
330
+ except BenchlingAgentError as exc:
331
+ _auth_failure(exc)
332
+ _emit(
333
+ Envelope.success(
334
+ {
335
+ "env": environment.name,
336
+ "tenant_url": environment.base_url,
337
+ "client_id": environment.client_id,
338
+ "credential_source": "keyring",
339
+ "saved": True,
340
+ },
341
+ env=environment.name,
342
+ tenant_url=environment.base_url,
343
+ )
344
+ )
345
+
346
+
347
+ @auth_app.command("logout")
348
+ def auth_logout(
349
+ ctx: typer.Context,
350
+ env: str | None = typer.Option(None, "--env", "-e", help="Environment name to remove."),
351
+ ) -> None:
352
+ """Remove an environment from environments.json and delete its keychain secret."""
353
+ state: State = ctx.obj
354
+ store = EnvironmentConfigStore()
355
+ try:
356
+ name = _require_env_name(env or state.env, store)
357
+ logout(store, Keychain(), name)
358
+ except BenchlingAgentError as exc:
359
+ _auth_failure(exc)
360
+ _emit(Envelope.success({"env": name, "removed": True}, env=name))
361
+
362
+
363
+ @auth_app.command("status")
364
+ def auth_status(
365
+ ctx: typer.Context,
366
+ env: str | None = typer.Option(
367
+ None, "--env", "-e", help="Limit the report to one environment."
368
+ ),
369
+ check: bool = typer.Option(
370
+ False,
371
+ "--check",
372
+ help="Request an access token and report the result. The token is not printed or saved.",
373
+ ),
374
+ ) -> None:
375
+ """Show configured environments and whether a keychain secret is present.
376
+
377
+ The secret is never printed. Without --env, every saved environment is listed.
378
+ --check performs a live token request and does not print or save the token.
379
+ """
380
+ state: State = ctx.obj
381
+ selected = env or state.env
382
+ store = EnvironmentConfigStore()
383
+ try:
384
+ report = collect_status(store, Keychain(), name=selected, check=check)
385
+ except BenchlingAgentError as exc:
386
+ _auth_failure(exc)
387
+ meta: dict[str, Any] = {}
388
+ if selected and selected in report.environments:
389
+ meta = {
390
+ "env": selected,
391
+ "tenant_url": report.environments[selected]["tenant_url"],
392
+ }
393
+ payload = {"environments": report.environments}
394
+ if report.failed_envs:
395
+ messages = [
396
+ str(report.environments[name]["token_check"]["message"]) for name in report.failed_envs
397
+ ]
398
+ message = (
399
+ messages[0] if len(messages) == 1 else "Token check failed: " + "; ".join(messages)
400
+ )
401
+ _auth_failure(
402
+ AuthenticationError(
403
+ message,
404
+ details={
405
+ "environments": payload["environments"],
406
+ "failed_envs": report.failed_envs,
407
+ },
408
+ )
409
+ )
410
+ _emit(Envelope.success(payload, **meta))
411
+
412
+
413
+ def _doctor_failure_message(result: dict[str, Any]) -> str:
414
+ failed = [check for check in result.get("checks", []) if not check.get("ok")]
415
+ if not failed:
416
+ return "Doctor checks failed"
417
+ summary = str(failed[0].get("error") or "Doctor checks failed")
418
+ hint = str(failed[0].get("hint") or "")
419
+ if hint and hint not in summary:
420
+ return f"{summary}. {hint}"
421
+ return summary
422
+
423
+
424
+ @app.command()
425
+ def doctor(ctx: typer.Context) -> None:
426
+ """Check configuration, authentication and API connectivity for the environment."""
427
+ state: State = ctx.obj
428
+ try:
429
+ result, runtime_env = asyncio.run(
430
+ _run_with_runtime(state.env, lambda runtime: runtime.service.doctor())
431
+ )
432
+ except BenchlingAgentError as exc:
433
+ _emit(Envelope.failure(exc))
434
+ raise typer.Exit(int(exc.exit_code)) from None
435
+ except Exception as exc:
436
+ error = UpstreamError("Unexpected local failure", details={"type": type(exc).__name__})
437
+ _emit(Envelope.failure(error))
438
+ raise typer.Exit(int(ExitCode.UPSTREAM)) from None
439
+ meta = {"env": runtime_env.name, "tenant_url": runtime_env.base_url}
440
+ if isinstance(result, dict) and result.get("ok") is False:
441
+ _emit(
442
+ Envelope.failure(
443
+ AuthenticationError(_doctor_failure_message(result), details=result),
444
+ **meta,
445
+ )
446
+ )
447
+ raise typer.Exit(int(ExitCode.AUTHENTICATION)) from None
448
+ _emit(Envelope.success(result, **meta))
449
+
450
+
451
+ @entry_app.command("resolve")
452
+ def entry_resolve(ctx: typer.Context, reference: str) -> None:
453
+ """Resolve an entry ID, display ID or URL to its canonical entry."""
454
+ state: State = ctx.obj
455
+ _execute(state.env, lambda runtime: runtime.service.resolve_entry(reference))
456
+
457
+
458
+ @entry_app.command("get")
459
+ def entry_get(
460
+ ctx: typer.Context,
461
+ reference: str,
462
+ full: bool = typer.Option(False, help="Retrieve all available structured content."),
463
+ ) -> None:
464
+ """Fetch an entry snapshot; --full retrieves all available structured content."""
465
+ state: State = ctx.obj
466
+ _execute(state.env, lambda runtime: runtime.service.get_entry(reference, full=full))
467
+
468
+
469
+ @entry_app.command("inspect")
470
+ def entry_inspect(ctx: typer.Context, reference: str) -> None:
471
+ """Summarize an entry's structure (sections, parts, tables, schemas) without full content."""
472
+ state: State = ctx.obj
473
+ _execute(state.env, lambda runtime: runtime.service.inspect_entry(reference))
474
+
475
+
476
+ @entry_app.command("list")
477
+ def entry_list(
478
+ ctx: typer.Context,
479
+ project: str | None = typer.Option(None, "--project", help="Project ID."),
480
+ folder: str | None = typer.Option(None, "--folder", help="Folder ID. Uses the V2 entry list."),
481
+ schema: str | None = typer.Option(None, "--schema", help="Entry schema ID."),
482
+ name: str | None = typer.Option(
483
+ None,
484
+ "--name",
485
+ help="Exact entry name. A comma in the name uses the V2 name parameter.",
486
+ ),
487
+ modified_after: str | None = typer.Option(
488
+ None,
489
+ "--modified-after",
490
+ help="Inclusive lower bound: YYYY-MM-DD or an RFC3339 timestamp with a time zone.",
491
+ ),
492
+ modified_before: str | None = typer.Option(
493
+ None,
494
+ "--modified-before",
495
+ help="Inclusive upper bound: YYYY-MM-DD or an RFC3339 timestamp with a time zone.",
496
+ ),
497
+ limit: int = typer.Option(50, "--limit", min=1, max=100, help="Page size, from 1 to 100."),
498
+ cursor: str | None = typer.Option(None, "--cursor", help="next_token from the previous page."),
499
+ ) -> None:
500
+ """List entries. A folder filter is applied by V2; the other filters are server-side too."""
501
+ state: State = ctx.obj
502
+ _execute(
503
+ state.env,
504
+ lambda runtime: runtime.service.list_entries(
505
+ project=project,
506
+ folder=folder,
507
+ schema_id=schema,
508
+ name=name,
509
+ modified_after=modified_after,
510
+ modified_before=modified_before,
511
+ limit=limit,
512
+ cursor=cursor,
513
+ ),
514
+ )
515
+
516
+
517
+ @entry_fields_app.command("get")
518
+ def entry_fields_get(ctx: typer.Context, reference: str) -> None:
519
+ """Get the schema field values of an entry."""
520
+ state: State = ctx.obj
521
+ _execute(state.env, lambda runtime: runtime.service.get_entry_fields(reference))
522
+
523
+
524
+ @section_app.command("get")
525
+ def section_get(ctx: typer.Context, reference: str, section: str) -> None:
526
+ """Get one section of an entry."""
527
+ state: State = ctx.obj
528
+ _execute(state.env, lambda runtime: runtime.service.get_section(reference, section))
529
+
530
+
531
+ @part_app.command("get")
532
+ def part_get(ctx: typer.Context, reference: str, part_id: str) -> None:
533
+ """Get one document part of an entry by part ID."""
534
+ state: State = ctx.obj
535
+ _execute(state.env, lambda runtime: runtime.service.get_part(reference, part_id))
536
+
537
+
538
+ @table_app.command("get")
539
+ def table_get(ctx: typer.Context, part_id: str) -> None:
540
+ """Get an unstructured table by its part ID."""
541
+ state: State = ctx.obj
542
+ _execute(state.env, lambda runtime: runtime.service.get_table(part_id))
543
+
544
+
545
+ @schema_app.command("get")
546
+ def schema_get(ctx: typer.Context, schema_id: str) -> None:
547
+ """Get an entry, result, or run schema by ID, including dropdown options."""
548
+ state: State = ctx.obj
549
+ _execute(state.env, lambda runtime: runtime.service.get_schema(schema_id))
550
+
551
+
552
+ @schema_app.command("list")
553
+ def schema_list(
554
+ ctx: typer.Context,
555
+ kind: str | None = typer.Option(
556
+ None, "--kind", help="entry, result, or run. Omit to list all three."
557
+ ),
558
+ limit: int = typer.Option(50, "--limit", min=1, max=100, help="Page size, from 1 to 100."),
559
+ cursor: str | None = typer.Option(None, "--cursor", help="next_token from the previous page."),
560
+ ) -> None:
561
+ """List entry, result, and run schemas, following every upstream page up to the limit."""
562
+ state: State = ctx.obj
563
+ _execute(
564
+ state.env,
565
+ lambda runtime: runtime.service.list_schemas(kind=kind, limit=limit, cursor=cursor),
566
+ )
567
+
568
+
569
+ @results_app.command("list")
570
+ def results_list(
571
+ ctx: typer.Context,
572
+ entry: str | None = typer.Option(None),
573
+ schema_id: str | None = typer.Option(None, "--schema"),
574
+ page_size: int = typer.Option(100, min=1, max=100),
575
+ cursor: str | None = typer.Option(None),
576
+ ) -> None:
577
+ """List result records, optionally filtered by entry or schema, one page at a time."""
578
+ state: State = ctx.obj
579
+ _execute(
580
+ state.env,
581
+ lambda runtime: runtime.service.list_results(
582
+ entry=entry, schema_id=schema_id, page_size=page_size, cursor=cursor
583
+ ),
584
+ )
585
+
586
+
587
+ @results_app.command("get")
588
+ def results_get(ctx: typer.Context, result_id: str) -> None:
589
+ """Get one result record by ID."""
590
+ state: State = ctx.obj
591
+ _execute(state.env, lambda runtime: runtime.service.get_result(result_id))
592
+
593
+
594
+ @results_app.command("tables")
595
+ def results_tables(ctx: typer.Context, reference: str) -> None:
596
+ """Discover explicit V2 result-table IDs and assigned schemas on one entry.
597
+
598
+ Each table_id is a v2_structured_table id (strtbl_…). Export it with
599
+ ``export --kind results-table --part TABLE_ID --entry ENTRY``.
600
+ """
601
+ state: State = ctx.obj
602
+ _execute(state.env, lambda runtime: runtime.service.list_result_tables(reference))
603
+
604
+
605
+ @results_app.command("rows")
606
+ def results_rows(
607
+ ctx: typer.Context,
608
+ part_id: str,
609
+ limit: int = typer.Option(50, "--limit", min=1, max=100, help="Page size, from 1 to 100."),
610
+ cursor: str | None = typer.Option(None, "--cursor", help="next_token from the previous page."),
611
+ ) -> None:
612
+ """Read one page of rows from a results table.
613
+
614
+ Calls GET /document-part-results-table/{id}/rows/items. Pass the previous
615
+ next_token with --cursor.
616
+ """
617
+ state: State = ctx.obj
618
+ _execute(
619
+ state.env,
620
+ lambda runtime: runtime.service.list_results_table_rows(
621
+ part_id, limit=limit, cursor=cursor
622
+ ),
623
+ )
624
+
625
+
626
+ @app.command("export")
627
+ def export_data(
628
+ ctx: typer.Context,
629
+ kind: str = typer.Option(..., "--kind", help="table, results-table, or assay-results."),
630
+ output: str = typer.Option(..., "--output", "-o", help="File path to write."),
631
+ file_format: str = typer.Option(..., "--format", help="json or csv."),
632
+ overwrite: bool = typer.Option(
633
+ False, "--overwrite", help="Replace the file if it already exists."
634
+ ),
635
+ part_id: str | None = typer.Option(
636
+ None,
637
+ "--part",
638
+ help=(
639
+ "Table id. A v3_document_part id (docpart_…) comes from `entry inspect`. "
640
+ "A v2_structured_table id (strtbl_…) comes from `results tables ENTRY` "
641
+ "and needs `--entry ENTRY` with `--kind results-table`."
642
+ ),
643
+ ),
644
+ entry: str | None = typer.Option(
645
+ None,
646
+ "--entry",
647
+ help=(
648
+ "Entry ID, display ID, or URL. Assay-results filter. "
649
+ "Also required with a strtbl_ id from `results tables`."
650
+ ),
651
+ ),
652
+ schema_id: str | None = typer.Option(
653
+ None, "--schema", help="Result schema ID. Assay results only."
654
+ ),
655
+ ) -> None:
656
+ """Write a table or assay results to a file and print a summary only.
657
+
658
+ Pages are read internally. The response is the row count, columns, path,
659
+ and SHA-256 checksum, not the rows. An existing file is kept unless
660
+ --overwrite is set. Benchling is only read.
661
+ """
662
+ state: State = ctx.obj
663
+ _execute(
664
+ state.env,
665
+ lambda runtime: export_dataset(
666
+ runtime.service,
667
+ kind=kind,
668
+ path=output,
669
+ file_format=file_format,
670
+ overwrite=overwrite,
671
+ part_id=part_id,
672
+ entry=entry,
673
+ schema_id=schema_id,
674
+ ),
675
+ )
676
+
677
+
678
+ def _read_spec(path: str) -> dict[str, Any]:
679
+ try:
680
+ raw = sys.stdin.read() if path == "-" else Path(path).read_text("utf-8")
681
+ parsed = json.loads(raw)
682
+ except (OSError, json.JSONDecodeError) as exc:
683
+ raise ValidationError(
684
+ "Could not read change specification",
685
+ details={"path": path, "reason": redact_text(str(exc))},
686
+ ) from exc
687
+ if not isinstance(parsed, dict):
688
+ raise ValidationError("Change specification must be a JSON object")
689
+ return parsed
690
+
691
+
692
+ def _parse_column_maps(column_map: list[str]) -> dict[str, str]:
693
+ """Turn repeated ``CSV_COLUMN=FIELD`` options into the planner's column map."""
694
+ mapped: dict[str, str] = {}
695
+ for item in column_map:
696
+ column, separator, field = item.partition("=")
697
+ if not separator or not column.strip() or not field.strip():
698
+ raise ValidationError(
699
+ "Each --map must be CSV_COLUMN=FIELD",
700
+ details={"map": item},
701
+ )
702
+ key = column.strip()
703
+ if key in mapped:
704
+ raise ValidationError(
705
+ "A CSV column was mapped more than once",
706
+ details={"column": key},
707
+ )
708
+ mapped[key] = field.strip()
709
+ return mapped
710
+
711
+
712
+ def _plan_request(
713
+ family: PlanFamily,
714
+ spec: str | None,
715
+ csv_path: str | None,
716
+ id_column: str | None,
717
+ column_map: list[str],
718
+ ) -> dict[str, Any]:
719
+ """Choose the JSON spec or the CSV result-update flags."""
720
+ if csv_path is not None and spec is not None:
721
+ raise ValidationError("Pass either --spec or --csv, not both")
722
+ if csv_path is not None:
723
+ if family != PlanFamily.RESULTS:
724
+ raise ValidationError("CSV result updates require the results family")
725
+ return {
726
+ "operation": "update",
727
+ "csv_path": csv_path,
728
+ "id_column": id_column,
729
+ "column_map": _parse_column_maps(column_map),
730
+ }
731
+ if column_map or id_column is not None:
732
+ raise ValidationError("--id-column and --map require --csv")
733
+ if spec is None:
734
+ raise ValidationError("A change plan needs --spec, or --csv with --id-column and --map")
735
+ return _read_spec(spec)
736
+
737
+
738
+ @changes_app.command("plan")
739
+ def changes_plan(
740
+ ctx: typer.Context,
741
+ entry: str = typer.Option(..., help="Entry ID, display ID, or URL."),
742
+ family: PlanFamily = typer.Option(..., case_sensitive=False),
743
+ spec: str | None = typer.Option(None, "--spec", help="JSON file path, or '-' for stdin."),
744
+ csv_path: str | None = typer.Option(
745
+ None,
746
+ "--csv",
747
+ help="CSV file of result updates. Use with --id-column and --map instead of --spec.",
748
+ ),
749
+ id_column: str | None = typer.Option(
750
+ None,
751
+ "--id-column",
752
+ help="CSV column that holds the result id. Required with --csv.",
753
+ ),
754
+ column_map: list[str] = typer.Option(
755
+ [],
756
+ "--map",
757
+ help="CSV column mapped to a field, as CSV_COLUMN=FIELD. Repeat for each field.",
758
+ ),
759
+ ) -> None:
760
+ """Create a change plan; nothing is written until it is applied.
761
+
762
+ ``--spec`` is a JSON change specification. Result updates can instead read a
763
+ CSV file: ``--id-column`` names the result id, and each ``--map`` names a
764
+ field by display name, system name, or field-definition id.
765
+ """
766
+ state: State = ctx.obj
767
+ try:
768
+ request = _plan_request(family, spec, csv_path, id_column, column_map)
769
+ except BenchlingAgentError as exc:
770
+ _emit(Envelope.failure(exc))
771
+ raise typer.Exit(int(exc.exit_code)) from None
772
+ _execute(
773
+ state.env,
774
+ lambda runtime: runtime.planner.plan(entry, family, request),
775
+ )
776
+
777
+
778
+ @changes_app.command("apply")
779
+ def changes_apply(ctx: typer.Context, plan_id: str) -> None:
780
+ """Apply a previously created plan, re-checking its preconditions first."""
781
+ state: State = ctx.obj
782
+ _execute(state.env, lambda runtime: runtime.planner.apply(plan_id))
783
+
784
+
785
+ @changes_app.command("status")
786
+ def changes_status(ctx: typer.Context, plan_id: str) -> None:
787
+ """Show the journal and status of a plan."""
788
+ state: State = ctx.obj
789
+
790
+ async def call(runtime: Runtime) -> dict[str, Any]:
791
+ return await runtime.planner.status(plan_id)
792
+
793
+ _execute(state.env, call)
794
+
795
+
796
+ def _write_stderr_envelope(envelope: Envelope[Any]) -> None:
797
+ """Startup failures belong on stderr. Stdout is the MCP stdio protocol."""
798
+ sys.stderr.write(_json(envelope) + "\n")
799
+ sys.stderr.flush()
800
+
801
+
802
+ @mcp_app.command("serve")
803
+ def mcp_serve(
804
+ allow_writes: list[str] = typer.Option(
805
+ [],
806
+ "--allow-writes",
807
+ metavar="ENV",
808
+ help="Allow apply_changes in this environment; repeatable.",
809
+ ),
810
+ verbose: bool = typer.Option(
811
+ False,
812
+ "--verbose",
813
+ help="Log MCP requests to stderr. Quiet by default so stdio clients stay readable.",
814
+ ),
815
+ ) -> None:
816
+ """Run the MCP server on stdio; every tool call selects its environment."""
817
+ from .mcp_server import run_mcp_server
818
+ from .redact import redact_text
819
+
820
+ try:
821
+ run_mcp_server(writable_envs=set(allow_writes), verbose=verbose)
822
+ except BenchlingAgentError as exc:
823
+ _write_stderr_envelope(Envelope.failure(exc))
824
+ raise typer.Exit(int(exc.exit_code)) from None
825
+ except Exception as exc:
826
+ error = UpstreamError(
827
+ "MCP server failed to start",
828
+ details={"type": type(exc).__name__, "reason": redact_text(str(exc))},
829
+ )
830
+ _write_stderr_envelope(Envelope.failure(error))
831
+ raise typer.Exit(int(error.exit_code)) from None
832
+
833
+
834
+ def main() -> None:
835
+ """Console-script entry point."""
836
+ app()
837
+
838
+
839
+ if __name__ == "__main__":
840
+ main()