codev-mcp 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.
codev_mcp/server.py ADDED
@@ -0,0 +1,966 @@
1
+ """MCP server exposing CODE V to a coding agent.
2
+
3
+ CODE V is not started when the server starts. The first tool call that needs
4
+ the engine launches it (and takes a licence seat); ``stop_session`` releases it.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ from dataclasses import asdict
11
+ from pathlib import Path
12
+ from typing import Any, Literal
13
+
14
+ from mcp.server.mcpserver import Image, MCPServer
15
+
16
+ from mcp.types import ToolAnnotations
17
+ from pydantic import BaseModel, Field
18
+
19
+ from codev_mcp import (analyses, build_data, doctor, edits, montecarlo, plots, reference, settings, snapshots,
20
+ sysdata, toldata)
21
+ from codev_mcp import tolerance as tolerancing
22
+ from codev_mcp import optimize as optimizer
23
+ from codev_mcp.engine import CodeVEngine
24
+
25
+ INSTRUCTIONS = """\
26
+ Tools for driving a CODE V optical design session.
27
+
28
+ Every tool returns an envelope with `ok`, `errors` and `warnings`. CODE V
29
+ often accepts a command and only prints a warning, so a call that returned is
30
+ not proof it did what you meant: check `ok`, read `warnings`, and confirm an
31
+ edit by reading the value back with `evaluate` or `get_surface_table`.
32
+
33
+ Commands are CODE V command-line syntax; separate several with `;`. Values are
34
+ read with database items in parentheses, e.g. `(EFL)`, `(THI S2)`, `(GLA S1)`.
35
+ Surface 0 is the object and the last surface is the image.
36
+
37
+ To optimize, use `optimize` with structured constraints rather than raw AUT text.
38
+ Tolerancing: `list_tolerances`, `set_tolerances` and `delete_tolerances` manage the lens's
39
+ tolerances and compensators; `tolerance_analysis` (TOR) gives sensitivities and expected
40
+ as-built performance; `monte_carlo` (TOLMONTE) gives the spread over random builds and yield.
41
+ Read and change fields, wavelengths and the aperture with `get_system_data`, `set_fields`,
42
+ `set_wavelengths` and `set_aperture`.
43
+ To change the lens prefer `set_surface`, `set_variables`, `insert_surface`,
44
+ `delete_surface` and `set_stop`, which confirm each change by reading it back,
45
+ over raw commands. `list_variables` shows what optimization would vary.
46
+ Take a `save_snapshot` before risky changes; long commands snapshot automatically.
47
+
48
+ Use `plot` to look at the design: `layout` shows element shapes, edge
49
+ thicknesses and ray paths that the numbers alone do not, and `ray_fan` or
50
+ `field_curves` show how the aberrations are balanced.
51
+
52
+ For image quality prefer `get_rms_spot`, `get_wavefront_error`, `get_mtf` and
53
+ `get_field_aberrations` (distortion and field curves),
54
+ which return numbers, over parsing listing text from SPO, WAV or MTF.
55
+
56
+ To work in the user's own CODE V window (they see every step), call `attach_to_window`;
57
+ `detach_from_window` ends the connection and leaves the window open.
58
+
59
+ CODE V is stopped after a period without tool calls to free the licence seat
60
+ (see `session_status`); the next call restarts it and restores the lens. If a
61
+ result carries `session_notice`, read it.
62
+
63
+ If something does not work (CODE V will not start, files go missing), call
64
+ `diagnose`. If `search_manual` or `lookup_glass` say the reference data is not
65
+ built, `build_reference_data` builds it in a few minutes without a licence.
66
+
67
+ Use `run_command` for anything that finishes in seconds. Use
68
+ `start_long_command` then `poll_long_command` for optimization (AUT),
69
+ tolerancing (TOR) and other long runs.
70
+ """
71
+
72
+ def _read_only() -> ToolAnnotations:
73
+ """Reads only: no change to the lens, files or session state."""
74
+ return ToolAnnotations(read_only_hint=True, open_world_hint=False)
75
+
76
+
77
+ def _changes(destructive: bool, idempotent: bool) -> ToolAnnotations:
78
+ """Changes something. Destructive means it can overwrite or discard the
79
+ lens, a file or a running session; otherwise it only adds or starts."""
80
+ return ToolAnnotations(read_only_hint=False, destructive_hint=destructive,
81
+ idempotent_hint=idempotent, open_world_hint=False)
82
+
83
+
84
+ mcp = MCPServer("codev", instructions=INSTRUCTIONS)
85
+ engine = CodeVEngine()
86
+
87
+
88
+ def _snapshot_before_idle_stop(ops: Any) -> str | None:
89
+ """Idle timeout hook: snapshot the lens so it can come back; None keeps the seat."""
90
+ label = snapshots.AUTO_PREFIX + "idle-" + snapshots.auto_label()[len(snapshots.AUTO_PREFIX):]
91
+ r = snapshots.save_in(engine, ops, label, "taken before releasing the licence after idle time", True)
92
+ return r.get("label") if r.get("ok", True) else None
93
+
94
+
95
+ engine.on_idle_stop = _snapshot_before_idle_stop
96
+ engine.on_restart = lambda ops, label: snapshots.restore_in(engine, ops, label)
97
+
98
+
99
+ # -- session --------------------------------------------------------------
100
+
101
+
102
+ @mcp.tool(annotations=_read_only())
103
+ def session_status() -> dict[str, Any]:
104
+ """Report whether a CODE V session is running, and the idle timeout. Never starts one.
105
+
106
+ After `idle_timeout_minutes` without a tool call, CODE V is stopped to free
107
+ the licence seat (never during a long command). The lens is snapshotted
108
+ first and restored automatically by the next tool call, whose result then
109
+ carries a `session_notice`.
110
+ """
111
+ codev_dir = settings.codev_dir()
112
+ return {
113
+ "ok": True,
114
+ "mode": engine.mode,
115
+ "attached_window": engine.attached_window,
116
+ "running": engine.running,
117
+ "progid": engine.progid,
118
+ "starting_directory": engine.start_dir,
119
+ **engine.idle_status(),
120
+ "settings": {
121
+ "idle_timeout_minutes": settings.idle_minutes()[0],
122
+ "data_folder": str(settings.data_dir()),
123
+ "codev_install_folder": str(codev_dir) if codev_dir else None,
124
+ "codev_install_folder_source": "setting" if codev_dir else "COM registration",
125
+ },
126
+ "warnings": settings.warnings(),
127
+ }
128
+
129
+
130
+ @mcp.tool(annotations=_changes(destructive=False, idempotent=True))
131
+ def start_session() -> dict[str, Any]:
132
+ """Start CODE V (takes a licence seat) and report its version.
133
+
134
+ Other tools start it on demand, so this is only needed to check the
135
+ connection or licence up front.
136
+ """
137
+ return engine.start()
138
+
139
+
140
+ @mcp.tool(annotations=_changes(destructive=True, idempotent=True))
141
+ def stop_session() -> dict[str, Any]:
142
+ """Stop the background CODE V session and release the licence (unsaved lens changes are lost).
143
+
144
+ While attached to a window, this only ends the connection; the window stays open.
145
+ """
146
+ return engine.stop()
147
+
148
+
149
+ @mcp.tool(annotations=_changes(destructive=False, idempotent=True))
150
+ def attach_to_window(pid: int = 0) -> dict[str, Any]:
151
+ """Drive an open CODE V window instead of a hidden background session.
152
+
153
+ `pid` is the window's PID UI (shown by `eva (pid ui)` in its command
154
+ window); 0 attaches to the first open window. Every tool then acts on
155
+ that window and its current lens, so the user sees each command run, and
156
+ the window's own version and licence are used. Refused while a background
157
+ session is running (stop it first). The idle timeout does not apply.
158
+ detach_from_window (or stop_session) ends the connection and leaves the
159
+ window open.
160
+ """
161
+ return engine.attach(pid)
162
+
163
+
164
+ @mcp.tool(annotations=_changes(destructive=False, idempotent=True))
165
+ def detach_from_window() -> dict[str, Any]:
166
+ """End the connection to the attached CODE V window. The window stays open; later tool calls
167
+ use a background session again."""
168
+ return engine.detach()
169
+
170
+
171
+ # -- commands and values ----------------------------------------------------
172
+
173
+
174
+ @mcp.tool(annotations=_changes(destructive=True, idempotent=False))
175
+ def run_command(command: str, timeout_s: float = 120.0) -> dict[str, Any]:
176
+ """Run CODE V command-line text and return its listing output.
177
+
178
+ Several commands may be joined with `;`. `ok` is false if CODE V raised
179
+ an error while it ran.
180
+ """
181
+ return engine.command(command, timeout_s)
182
+
183
+
184
+ @mcp.tool(annotations=_read_only())
185
+ def evaluate(expression: str) -> dict[str, Any]:
186
+ """Evaluate a CODE V expression, e.g. `(EFL)`, `(THI S3)`, `(RDY S1)*2`.
187
+
188
+ Returns a number when the result is numeric, otherwise text.
189
+ """
190
+ return engine.evaluate(expression)
191
+
192
+
193
+ # -- lens -----------------------------------------------------------------
194
+
195
+
196
+ @mcp.tool(annotations=_changes(destructive=True, idempotent=True))
197
+ def open_lens(path: str) -> dict[str, Any]:
198
+ """Restore a lens file and read back its title and first-order data.
199
+
200
+ `path` is a file path or a CODE V library reference such as
201
+ `cv_lens:cooke1`. The current lens is replaced.
202
+ """
203
+ target = path if ":" in path and not os.path.isabs(path) else f'"{path}"'
204
+ result = engine.command(f"res {target}")
205
+ if result["ok"]:
206
+ result["summary"] = _summary_values()
207
+ return result
208
+
209
+
210
+ @mcp.tool(annotations=_changes(destructive=True, idempotent=True))
211
+ def save_lens(path: str) -> dict[str, Any]:
212
+ """Save the current lens to `path` (a .len file), overwriting any file already there.
213
+
214
+ Use an absolute path. For a restorable copy inside this session, prefer `save_snapshot`.
215
+ """
216
+ return engine.command(f'sav "{path}"')
217
+
218
+
219
+ @mcp.tool(annotations=_read_only())
220
+ def get_system_summary() -> dict[str, Any]:
221
+ """Title, focal length, f-number, counts, wavelengths and field angles."""
222
+ counts = engine.counts()
223
+ if not counts["ok"]:
224
+ return counts
225
+ exprs = {
226
+ "title": "(TIT)",
227
+ "efl": "(EFL)",
228
+ "fno": "(FNO)",
229
+ "epd": "(EPD)",
230
+ "overall_length": "(OAL)",
231
+ }
232
+ for w in range(1, counts["wavelengths"] + 1):
233
+ exprs[f"wavelength_nm_{w}"] = f"(WL W{w})"
234
+ for f in range(1, counts["fields"] + 1):
235
+ exprs[f"field_y_angle_{f}"] = f"(YAN F{f})"
236
+ result = engine.evaluate_many(exprs)
237
+ result["counts"] = {k: counts[k] for k in ("surfaces", "fields", "wavelengths", "zooms", "stop_surface")}
238
+ return result
239
+
240
+
241
+ @mcp.tool(annotations=_read_only())
242
+ def get_surface_table() -> dict[str, Any]:
243
+ """Radius, thickness, glass and semi-diameter for every surface.
244
+
245
+ Surface 0 is the object and the last row is the image. A radius of 1e18
246
+ means flat, a thickness of 1e10 means infinite, and an empty glass is air.
247
+ Semi-diameters come from a ray trace: where it fails (a ray missing a
248
+ surface, total internal reflection) that value is null and
249
+ `semi_diameter_unavailable` says why; the rest of the table is unaffected.
250
+ """
251
+ counts = engine.counts()
252
+ if not counts["ok"]:
253
+ return counts
254
+ n = counts["surfaces"]
255
+ names = ["SO" if s == 0 else ("SI" if s == n - 1 else f"S{s}") for s in range(n)]
256
+ exprs: dict[str, str] = {}
257
+ for s, name in enumerate(names):
258
+ exprs[f"{s}.radius"] = f"(RDY {name})"
259
+ exprs[f"{s}.thickness"] = f"(THI {name})"
260
+ exprs[f"{s}.glass"] = f"(GLA {name})"
261
+ result = engine.evaluate_many(exprs)
262
+ values = result.pop("values", {})
263
+
264
+ def semi_diameters(ops: Any) -> dict:
265
+ sds, problems = {}, {}
266
+ for s, name in enumerate(names):
267
+ value, errors, _ = ops.soft(lambda name=name: ops.eva(f"(SD {name})"))
268
+ sds[s] = value if not errors else None
269
+ if errors:
270
+ problems[s] = errors[0].split(": ", 1)[-1]
271
+ return {"sds": sds, "problems": problems}
272
+
273
+ sd = engine.with_ops(semi_diameters)
274
+ rows = []
275
+ for s in range(n):
276
+ rows.append(
277
+ {
278
+ "surface": s,
279
+ "is_stop": s == counts["stop_surface"],
280
+ "radius": values.get(f"{s}.radius"),
281
+ "thickness": values.get(f"{s}.thickness"),
282
+ "glass": values.get(f"{s}.glass"),
283
+ "semi_diameter": sd.get("sds", {}).get(s),
284
+ }
285
+ )
286
+ result["surfaces"] = rows
287
+ if sd.get("problems"):
288
+ result["semi_diameter_unavailable"] = {str(k): v for k, v in sd["problems"].items()}
289
+ return result
290
+
291
+
292
+ # -- system data ----------------------------------------------------------------
293
+
294
+
295
+ @mcp.tool(annotations=_read_only())
296
+ def get_system_data() -> dict[str, Any]:
297
+ """Fields, wavelengths and aperture: everything set_fields, set_wavelengths and set_aperture change.
298
+
299
+ Fields with their type (angle, object_height, image_height,
300
+ real_image_height), x and y values, weights and vignetting factors;
301
+ wavelengths in nm with weights and the reference; the aperture with which
302
+ of EPD/FNO/NA/NAO is fixed and the current value of each; units, object
303
+ distance, and whether the system is afocal.
304
+ """
305
+ return sysdata.get_system_data(engine)
306
+
307
+
308
+ @mcp.tool(annotations=_changes(destructive=True, idempotent=True))
309
+ def set_fields(
310
+ y: list[float],
311
+ field_type: Literal["angle", "object_height", "image_height", "real_image_height"] = "angle",
312
+ x: list[float] | None = None,
313
+ weights: list[float] | None = None,
314
+ vignetting: Literal["recompute", "clear", "keep"] = "recompute",
315
+ ) -> dict[str, Any]:
316
+ """Replace all fields; confirmed by read-back.
317
+
318
+ `y` (and optionally `x`) give one value per field, up to 25, in degrees
319
+ for angle fields or lens units for heights. Vignetting factors are stored
320
+ per field number and do not follow a change of fields, so by default they
321
+ are recomputed from the apertures (SET VIG); 'clear' sets them to zero,
322
+ 'keep' leaves them (only if you will set them yourself). Object heights
323
+ are refused when the object is at infinity.
324
+ """
325
+ return sysdata.set_fields(engine, field_type, y, x, weights, vignetting)
326
+
327
+
328
+ @mcp.tool(annotations=_changes(destructive=True, idempotent=True))
329
+ def set_wavelengths(
330
+ nm: list[float],
331
+ weights: list[int] | None = None,
332
+ reference: int | None = None,
333
+ ) -> dict[str, Any]:
334
+ """Replace all wavelengths (nm, up to 21, red to blue) with optional integer weights and the
335
+ reference wavelength number; confirmed by read-back. Solves may change with the reference.
336
+ """
337
+ return sysdata.set_wavelengths(engine, nm, weights, reference)
338
+
339
+
340
+ @mcp.tool(annotations=_changes(destructive=True, idempotent=True))
341
+ def set_aperture(kind: Literal["epd", "fno", "na", "nao"], value: float) -> dict[str, Any]:
342
+ """Fix the aperture by entrance pupil diameter, image f-number, image NA or object NA.
343
+
344
+ The chosen one is held fixed and the others follow as the lens changes.
345
+ Confirmed by read-back, with all four values before and after. Object NA
346
+ is refused when the object is at infinity.
347
+ """
348
+ return sysdata.set_aperture(engine, kind, value)
349
+
350
+
351
+ # -- edits --------------------------------------------------------------------
352
+
353
+
354
+ class VariableChange(BaseModel):
355
+ surface: int = Field(description="Surface number (0 is the object).")
356
+ parameter: Literal["radius", "thickness", "glass"]
357
+ vary: bool = Field(description="True to make it an optimization variable, false to freeze it.")
358
+
359
+
360
+ @mcp.tool(annotations=_changes(destructive=True, idempotent=True))
361
+ def set_surface(
362
+ surface: int,
363
+ radius: float | None = None,
364
+ thickness: float | None = None,
365
+ glass: str | None = None,
366
+ clear_aperture: float | None = None,
367
+ release_solves: bool = False,
368
+ ) -> dict[str, Any]:
369
+ """Change a surface's radius, thickness, glass or clear aperture, and confirm it.
370
+
371
+ Give only the fields to change. `radius` 0 means flat. `glass` is a
372
+ catalog name such as `NBK7_SCHOTT`, or `AIR`. Every change is read back;
373
+ one that did not stick is reported as a failure and later fields are not
374
+ applied. A thickness or curvature held by a solve (e.g. PIM on the last
375
+ thickness) is refused unless `release_solves` is true, which removes the
376
+ solve first. Returns before/after values and the new EFL.
377
+ """
378
+ return edits.set_surface(engine, surface, radius, thickness, glass, clear_aperture, release_solves)
379
+
380
+
381
+ @mcp.tool(annotations=_changes(destructive=True, idempotent=True))
382
+ def set_variables(changes: list[VariableChange], release_solves: bool = False) -> dict[str, Any]:
383
+ """Make radii, thicknesses or glasses variable for optimization, or freeze them.
384
+
385
+ Each change is confirmed from the lens listing. Varying a value held by a
386
+ solve (e.g. the PIM image thickness) would delete the solve, so the whole
387
+ request is refused unless `release_solves` is true. Making a glass
388
+ variable replaces it with a fictitious glass model.
389
+ """
390
+ return edits.set_variables(engine, [c.model_dump() for c in changes], release_solves)
391
+
392
+
393
+ @mcp.tool(annotations=_read_only())
394
+ def list_variables() -> dict[str, Any]:
395
+ """Current optimization variables, couplings and solves. Everything else is frozen."""
396
+ return edits.list_variables(engine)
397
+
398
+
399
+ @mcp.tool(annotations=_changes(destructive=False, idempotent=False))
400
+ def insert_surface(
401
+ at: int,
402
+ radius: float | None = None,
403
+ thickness: float | None = None,
404
+ glass: str | None = None,
405
+ ) -> dict[str, Any]:
406
+ """Insert a surface before current surface `at`; later surfaces renumber up by one.
407
+
408
+ Without other arguments the new surface is flat, air and zero thickness.
409
+ """
410
+ return edits.insert_surface(engine, at, radius, thickness, glass)
411
+
412
+
413
+ @mcp.tool(annotations=_changes(destructive=True, idempotent=False))
414
+ def delete_surface(surface: int) -> dict[str, Any]:
415
+ """Delete a surface (not the object or image); later surfaces renumber down by one."""
416
+ return edits.delete_surface(engine, surface)
417
+
418
+
419
+ @mcp.tool(annotations=_changes(destructive=True, idempotent=True))
420
+ def set_stop(surface: int) -> dict[str, Any]:
421
+ """Move the aperture stop to `surface` (not the object or image), confirmed by read-back.
422
+
423
+ Returns the old and new stop surface and the first-order data afterwards.
424
+ """
425
+ return edits.set_stop(engine, surface)
426
+
427
+
428
+ # -- snapshots ----------------------------------------------------------------
429
+
430
+
431
+ @mcp.tool(annotations=_changes(destructive=False, idempotent=False))
432
+ def save_snapshot(label: str | None = None, note: str | None = None, overwrite: bool = False) -> dict[str, Any]:
433
+ """Save the current lens under a label so it can be restored later.
434
+
435
+ Take one before a risky change. Without a label one is generated
436
+ (`snap-001`, ...). Snapshots persist across server restarts.
437
+ """
438
+ return snapshots.save_snapshot(engine, label, note, overwrite)
439
+
440
+
441
+ @mcp.tool(annotations=_changes(destructive=True, idempotent=True))
442
+ def restore_snapshot(label: str) -> dict[str, Any]:
443
+ """Replace the current lens with a snapshot, and verify it matches what was saved.
444
+
445
+ Unsaved changes to the current lens are lost; snapshot it first if needed.
446
+ """
447
+ return snapshots.restore_snapshot(engine, label)
448
+
449
+
450
+ @mcp.tool(annotations=_read_only())
451
+ def list_snapshots() -> dict[str, Any]:
452
+ """Saved snapshots, oldest first, with title, EFL and surface count. Never starts CODE V.
453
+
454
+ Labels starting `auto-` were taken automatically before long commands;
455
+ the newest 20 are kept.
456
+ """
457
+ return snapshots.list_snapshots(engine)
458
+
459
+
460
+ @mcp.tool(annotations=_changes(destructive=True, idempotent=True))
461
+ def delete_snapshot(label: str) -> dict[str, Any]:
462
+ """Delete a saved snapshot and its .len file. This cannot be undone."""
463
+ return snapshots.delete_snapshot(engine, label)
464
+
465
+
466
+ # -- analyses -----------------------------------------------------------------
467
+
468
+
469
+ @mcp.tool(annotations=_read_only())
470
+ def get_rms_spot(zoom: int = 1, fields: list[int] | None = None) -> dict[str, Any]:
471
+ """RMS spot diameter per field, in lens units (polychromatic, nominal focus).
472
+
473
+ `fields` is a list of field numbers; omit it for all fields.
474
+ """
475
+ return analyses.rms_spot(engine, zoom, fields)
476
+
477
+
478
+ @mcp.tool(annotations=_read_only())
479
+ def get_wavefront_error(
480
+ zoom: int = 1,
481
+ wavelength: int = 0,
482
+ nrd: int = 0,
483
+ best_focus: bool = False,
484
+ fields: list[int] | None = None,
485
+ ) -> dict[str, Any]:
486
+ """RMS wavefront error (waves) and Strehl ratio per field.
487
+
488
+ `wavelength` is a wavelength number, or 0 for polychromatic. `nrd` is rays
489
+ across the pupil diameter (0 uses CODE V's default of 20). With
490
+ `best_focus`, each field is evaluated at its own best focus and
491
+ `focus_shift` reports where that is.
492
+
493
+ Two Strehl values: `strehl_marechal` comes from the RMS error and is null
494
+ above 0.15 waves, where that approximation fails; `strehl_psf` is measured
495
+ from the PSF, is valid at any aberration level, and is given at nominal
496
+ focus only.
497
+ """
498
+ return analyses.wavefront_error(engine, zoom, wavelength, nrd, best_focus, fields)
499
+
500
+
501
+ @mcp.tool(annotations=_read_only())
502
+ def get_field_aberrations(zoom: int = 1) -> dict[str, Any]:
503
+ """Distortion and astigmatic field curves across the field, from CODE V's FIE.
504
+
505
+ Rows at every 10% of the maximum field give distortion (%), the sagittal
506
+ (X) and tangential (Y) focus positions relative to the image surface, the
507
+ same measured from the on-axis focus (the field curves), and the
508
+ astigmatic difference. Read `sign_convention`: negative focus values lie
509
+ in front of the image surface, on the lens side. Reference wavelength only.
510
+ """
511
+ return analyses.field_aberrations(engine, zoom)
512
+
513
+
514
+ @mcp.tool(annotations=_read_only())
515
+ def get_mtf(
516
+ frequencies: list[float],
517
+ zoom: int = 1,
518
+ fields: list[int] | None = None,
519
+ diffraction: bool = True,
520
+ nrd: int = 0,
521
+ ) -> dict[str, Any]:
522
+ """MTF modulation per field and spatial frequency, at azimuths 0 and 90.
523
+
524
+ `frequencies` are in cycles/mm at the image. For fields along Y,
525
+ azimuth 0 is radial and 90 is tangential. Each row also gives the
526
+ diffraction-limit modulation at that frequency. Set `diffraction` false
527
+ for geometrical MTF. `nrd` 0 uses CODE V's default of 60.
528
+ """
529
+ return analyses.mtf(engine, frequencies, zoom, fields, diffraction, nrd)
530
+
531
+
532
+ # -- plots --------------------------------------------------------------------
533
+
534
+
535
+ @mcp.tool(structured_output=False, annotations=_changes(destructive=False, idempotent=False)) # images are content items, not JSON
536
+ def plot(
537
+ kind: Literal["layout", "ray_fan", "field_curves", "spot", "mtf", "psf"],
538
+ settings: str | None = None,
539
+ max_pixels: int = 1600,
540
+ ) -> list[Any]:
541
+ """Render a CODE V plot of the current lens and return it as an image.
542
+
543
+ - `layout`: 2D lens drawing with ray bundles (check element shapes,
544
+ edge thickness, clearances, vignetting)
545
+ - `ray_fan`: transverse ray aberration fans per field and wavelength
546
+ - `field_curves`: astigmatic field curves, distortion and lateral colour
547
+ - `spot`: spot diagrams per field
548
+ - `mtf`: MTF versus frequency per field
549
+ - `psf`: point spread function, one image per field
550
+
551
+ `settings` is optional option sub-commands placed before GO, e.g.
552
+ `MFR 100` for MTF or `NRD 41` for spot. Full-size PNGs are kept on disk
553
+ (paths in the summary); the returned images are scaled to `max_pixels`
554
+ on the long side. The first item is a JSON summary; check its `ok`. No
555
+ images are returned when `ok` is false.
556
+ """
557
+ result = plots.render(engine, kind, settings, max_pixels)
558
+ images = result.pop("images", [])
559
+ result["images"] = [info for _, info in images]
560
+ if not result["ok"]:
561
+ # A failed run may still draw a default plot; do not show it as the answer.
562
+ return [result]
563
+ return [result, *(Image(data=data, format="png") for data, _ in images)]
564
+
565
+
566
+ # -- reference (no engine, no licence) ---------------------------------------
567
+
568
+
569
+ @mcp.tool(annotations=_read_only())
570
+ def reference_status() -> dict[str, Any]:
571
+ """Whether the local manual and glass reference data is built, and what it holds.
572
+
573
+ While or after `build_reference_data` runs in this server, `build` reports it.
574
+ """
575
+ out = reference.status()
576
+ if build_data.background.status()["state"] != "not started":
577
+ out["build"] = build_data.background.status()
578
+ return out
579
+
580
+
581
+ @mcp.tool(annotations=_changes(destructive=False, idempotent=True))
582
+ def build_reference_data(codev_dir: str | None = None, rebuild: bool = False,
583
+ wait_seconds: float = 0) -> dict[str, Any]:
584
+ """Build the local manual and glass reference data from the user's CODE V install.
585
+
586
+ Indexes the CODE V help for `search_manual` and loads the glass catalogs for
587
+ `lookup_glass` and `search_glass`. Uses no CODE V session and no licence
588
+ seat; the data stays on this machine. It takes a few minutes, so this
589
+ starts the build in the background and returns: call again (or
590
+ `reference_status`) to follow it, optionally with `wait_seconds` (up to
591
+ 60) to wait for it to finish. Does nothing if the data is already built,
592
+ unless `rebuild` is true (after a CODE V update, for instance).
593
+
594
+ `codev_dir` is the CODE V install folder; by default it comes from the
595
+ CODE V install folder setting, else from CODE V's COM registration.
596
+ """
597
+ bg = build_data.background
598
+ if bg.running:
599
+ bg.wait(min(max(wait_seconds, 0), 60))
600
+ return {"ok": True, **bg.status(), "started": False}
601
+ current = reference.status()
602
+ if current.get("built") and not rebuild and bg.status()["state"] != "failed":
603
+ return {"ok": True, "state": "already built", "started": False,
604
+ "built_at": current.get("built_at"), "database": current.get("database"),
605
+ "note": "Pass rebuild=true to build it again."}
606
+ install = Path(codev_dir).expanduser() if codev_dir else reference.find_install_dir()
607
+ if install is None or not install.is_dir():
608
+ return {"ok": False, "started": False,
609
+ "error": (f"CODE V install folder {install} not found. " if install else
610
+ "Could not find the CODE V install folder from CODE V's COM registration. ")
611
+ + "Pass codev_dir, or set the CODE V install folder setting (CODEV_DIR)."}
612
+ started = bg.start(install, reference.build_path())
613
+ bg.wait(min(max(wait_seconds, 0), 60))
614
+ out = {"ok": True, **bg.status(), "started": started.get("started", False)}
615
+ if out["state"] == "failed":
616
+ out["ok"] = False
617
+ return out
618
+
619
+
620
+ @mcp.tool(annotations=_read_only())
621
+ def diagnose() -> dict[str, Any]:
622
+ """Check this codev-mcp install and say how to fix what is wrong. Never starts CODE V.
623
+
624
+ Checks Python and packages, which CODE V install the COM registration
625
+ points at (and stale registrations), whether this process's AppData is
626
+ redirected (as inside the Claude desktop app) and the folders are visible to
627
+ CODE V, the reference data, leftover background CODE V processes, and the
628
+ settings. Each check is PASS, INFO, WARN or FAIL, with a remedy for the
629
+ last two. To check that CODE V itself starts and a licence is available,
630
+ call `start_session`.
631
+ """
632
+ checks = [asdict(c) for c in doctor.run(engine=False)]
633
+ failed = [c["name"] for c in checks if c["status"] == "FAIL"]
634
+ warned = [c["name"] for c in checks if c["status"] == "WARN"]
635
+ return {"ok": not failed, "failed": failed, "warned": warned, "checks": checks}
636
+
637
+
638
+ @mcp.tool(annotations=_read_only())
639
+ def search_manual(query: str, section: str | None = None, limit: int = 8) -> dict[str, Any]:
640
+ """Full-text search of the CODE V help (commands, options, macro functions).
641
+
642
+ Returns page ids, titles and snippets; read a page with `read_manual_page`.
643
+ `section` narrows to one help section, e.g. `optimization`, `tolerancing`,
644
+ `macroplus`, `lens_system`, `api` (see `reference_status`). Works without
645
+ a CODE V session.
646
+ """
647
+ return reference.search_manual(query, section, limit)
648
+
649
+
650
+ @mcp.tool(annotations=_read_only())
651
+ def read_manual_page(page_id: int, offset: int = 0, max_chars: int = 6000) -> dict[str, Any]:
652
+ """Text of one help page. Long pages come in chunks; pass `next_offset` to continue."""
653
+ return reference.read_manual_page(page_id, offset, max_chars)
654
+
655
+
656
+ @mcp.tool(annotations=_read_only())
657
+ def lookup_glass(name: str, catalog: str | None = None) -> dict[str, Any]:
658
+ """Catalog data for a glass: nd, Vd, transmission range, CTE, properties, availability.
659
+
660
+ Accepts a bare name (`NBK7`) or CODE V's `NAME_CATALOG` form (`NBK7_SCHOTT`).
661
+ Suggests similar names when there is no exact match. Works without a session.
662
+ """
663
+ return reference.lookup_glass(name, catalog)
664
+
665
+
666
+ @mcp.tool(annotations=_read_only())
667
+ def search_glass(
668
+ nd: float,
669
+ vd: float,
670
+ nd_tolerance: float = 0.01,
671
+ vd_tolerance: float = 2.0,
672
+ catalogs: list[str] | None = None,
673
+ limit: int = 15,
674
+ include_discontinued: bool = False,
675
+ ) -> dict[str, Any]:
676
+ """Glasses near a point on the glass map (nd, Vd), nearest first.
677
+
678
+ Use to find substitutes or candidates for a glass swap. `catalogs` limits
679
+ the search, e.g. `["SCHOTT", "OHARA"]`. Discontinued glasses are left out
680
+ unless `include_discontinued` is true; check `availability` before choosing.
681
+ """
682
+ return reference.search_glass(
683
+ nd, vd, nd_tolerance, vd_tolerance, catalogs, limit, include_discontinued
684
+ )
685
+
686
+
687
+ # -- optimization -------------------------------------------------------------
688
+
689
+
690
+ class Constraint(BaseModel):
691
+ quantity: str = Field(description="CODE V constraint keyword, e.g. EFL, BFL, OAL, IMD, DST, CT, ET.")
692
+ qualifiers: str = Field("", description="Optional qualifiers, e.g. 'S3', 'S1..11', 'Z2'.")
693
+ equals: float | None = Field(None, description="Target value (equality constraint).")
694
+ min: float | None = Field(None, description="Lower bound.")
695
+ max: float | None = Field(None, description="Upper bound.")
696
+
697
+
698
+ class ThicknessLimits(BaseModel):
699
+ max_center: float | None = Field(None, description="MXT: maximum element center thickness.")
700
+ min_center: float | None = Field(None, description="MNT: minimum element center thickness.")
701
+ min_edge: float | None = Field(None, description="MNE: minimum element edge thickness.")
702
+ min_air_axial: float | None = Field(None, description="MNA: minimum axial air space.")
703
+ min_air_edge: float | None = Field(None, description="MAE: minimum edge air space.")
704
+
705
+
706
+ @mcp.tool(annotations=_changes(destructive=True, idempotent=False))
707
+ def optimize(
708
+ constraints: list[Constraint] | None = None,
709
+ variables: list[VariableChange] | None = None,
710
+ thickness_limits: ThicknessLimits | None = None,
711
+ field_weights: list[float] | None = None,
712
+ error_function: Literal["ray", "wavefront"] = "ray",
713
+ cycles: int = 25,
714
+ wait_s: float = 180.0,
715
+ release_solves: bool = False,
716
+ min_improvement: float | None = None,
717
+ ) -> dict[str, Any]:
718
+ """Run CODE V's optimization (AUT) from structured settings and report the result.
719
+
720
+ `variables` (optional) are applied first, as with set_variables; otherwise
721
+ the lens's current variables are used. `constraints` hold targets or
722
+ bounds, e.g. {"quantity": "EFL", "equals": 50} or {"quantity": "OAL",
723
+ "qualifiers": "S1..6", "max": 20}. `thickness_limits` set the general
724
+ thickness constraints, `field_weights` one weight per field (default
725
+ equal), `error_function` "ray" (transverse ray aberrations, the default)
726
+ or "wavefront" (wavefront variance). The lens is snapshotted first.
727
+
728
+ Returns the error function after the run (total, aberration and
729
+ constraint parts, from CODE V's database), the per-cycle history, every
730
+ variable before and after, and each constraint's achieved value and
731
+ whether it was met (equality within 1e-4 relative, with the deviation).
732
+ `stopped_because` is AUT's closing message: by default it stops once
733
+ cycles gain under 5% (`min_improvement` sets that fraction) or after
734
+ `cycles`; `hint` says when another run looks worthwhile. If the run
735
+ outlasts `wait_s`, the result says so; call get_optimization_result later.
736
+ """
737
+ return optimizer.run(
738
+ engine, wait_s,
739
+ variables=[v.model_dump() for v in variables] if variables else None,
740
+ constraints=[c.model_dump() for c in constraints] if constraints else None,
741
+ thickness_limits=thickness_limits.model_dump() if thickness_limits else None,
742
+ field_weights=field_weights, error_function=error_function, cycles=cycles,
743
+ release_solves=release_solves, min_improvement=min_improvement,
744
+ )
745
+
746
+
747
+ @mcp.tool(annotations=_read_only())
748
+ def get_optimization_result() -> dict[str, Any]:
749
+ """Result of the last optimize run: still executing, or the full report as optimize returns it."""
750
+ return optimizer.result(engine)
751
+
752
+
753
+ # -- tolerancing ---------------------------------------------------------------
754
+
755
+
756
+ class SurfaceRange(BaseModel):
757
+ first: int = Field(description="First surface.")
758
+ last: int = Field(description="Last surface (inclusive).")
759
+
760
+
761
+ QUALIFIERS_HELP = ("Qualifiers, part of the tolerance's identity: R (e.g. CODE V's default cemented rolls "
762
+ "RLX/RLY Si..j R), Zk (one zoom position), Ck (coupling), L'abc' (label), V or F (variable or "
763
+ "frozen for TOR's inverse mode). Copy them from list_tolerances to address an existing row.")
764
+
765
+
766
+ class ToleranceEntry(BaseModel):
767
+ type: str = Field(description="CODE V tolerance code: DLR radius, DLF power (fringes), CYD/CYN/IRR "
768
+ "irregularity (fringes), DLT thickness, DLN index, DLV V-number (fraction), TRX/TRY surface "
769
+ "tilt (TIR, lens units), DSX/DSY group decenter and BTX/BTY group tilt (radians), RLX/RLY "
770
+ "roll; group types need end_surface. For compensators, e.g. DLZ (focus) on the image surface.")
771
+ surface: int = Field(description="Surface the tolerance applies to (first of a range).")
772
+ end_surface: int | None = Field(default=None, description="Last surface, for element or group tolerances.")
773
+ qualifiers: str | None = Field(default=None, description=QUALIFIERS_HELP)
774
+ value: float | None = Field(default=None, description="Size (plus and minus) in the type's units (see type; "
775
+ "list_tolerances gives units per row). Omit for CODE V's default. For a compensator, "
776
+ "its allowed range.")
777
+
778
+
779
+ class ToleranceRef(BaseModel):
780
+ type: str | None = Field(default=None, description="Tolerance code; omit to match every type on the surfaces.")
781
+ surface: int
782
+ end_surface: int | None = None
783
+ qualifiers: str | None = Field(default=None, description=QUALIFIERS_HELP)
784
+
785
+
786
+ class CompensatorVariable(BaseModel):
787
+ surface: int = Field(description="Surface number.")
788
+ parameter: Literal["radius", "thickness", "glass"]
789
+
790
+
791
+ @mcp.tool(annotations=_read_only())
792
+ def list_tolerances() -> dict[str, Any]:
793
+ """Tolerances and compensators stored in the lens (from CODE V's TLI listing).
794
+
795
+ Each row: index, type, surface (and end_surface for ranges), value, and
796
+ `variable` (TOR's inverse mode may resize it; otherwise frozen).
797
+ """
798
+ return toldata.list_tolerances(engine)
799
+
800
+
801
+ @mcp.tool(annotations=_changes(destructive=True, idempotent=True))
802
+ def set_tolerances(
803
+ tolerances: list[ToleranceEntry] | None = None,
804
+ compensators: list[ToleranceEntry] | None = None,
805
+ defaults: SurfaceRange | None = None,
806
+ ) -> dict[str, Any]:
807
+ """Add or change tolerances and compensators in the lens, confirmed by read-back.
808
+
809
+ `defaults` first generates CODE V's standard set for a centred system on
810
+ those surfaces (DLR, DLF, CYD/CYN, DLT, DLN, DLV, TRX/TRY, group
811
+ DSX/DSY and BTX/BTY, and RLX/RLY with R on cemented groups);
812
+ `tolerances` then add or overwrite single entries. An entry changes the
813
+ existing row only when type, surfaces and qualifiers all match, otherwise
814
+ it adds a new one (`notes` flags a likely duplicate). All or nothing: if
815
+ any command is rejected or any read-back differs, the lens is put back.
816
+
817
+ Compensators are what TOR may adjust (e.g. DLZ on the image surface for
818
+ focus). Monte Carlo does not use them: give `monte_carlo` its own.
819
+ """
820
+ return toldata.set_tolerances(engine, defaults.model_dump() if defaults else None,
821
+ [t.model_dump() for t in tolerances or []],
822
+ [c.model_dump() for c in compensators or []])
823
+
824
+
825
+ @mcp.tool(annotations=_changes(destructive=True, idempotent=True))
826
+ def delete_tolerances(
827
+ tolerances: list[ToleranceRef] | None = None,
828
+ compensators: list[ToleranceRef] | None = None,
829
+ everything: bool = False,
830
+ ) -> dict[str, Any]:
831
+ """Delete tolerances or compensators from the lens, confirmed by read-back.
832
+
833
+ A ref without `type` deletes every tolerance (or compensator) on those
834
+ surfaces; with `type`, only the row whose qualifiers match. `everything`
835
+ deletes all tolerances and compensators. All or nothing, as set_tolerances.
836
+ """
837
+ return toldata.delete_tolerances(engine, [t.model_dump() for t in tolerances or []],
838
+ [c.model_dump() for c in compensators or []], everything)
839
+
840
+
841
+ @mcp.tool(annotations=_read_only())
842
+ def tolerance_analysis(
843
+ criterion: Literal["rms", "mtf"] = "rms",
844
+ frequency: float | None = None,
845
+ azimuth: Literal["tan", "rad"] = "tan",
846
+ mode: Literal["sensitivity", "inverse"] = "sensitivity",
847
+ degradation: float | None = None,
848
+ top: int = 10,
849
+ wait_s: float = 300.0,
850
+ ) -> dict[str, Any]:
851
+ """Tolerance sensitivity and expected as-built performance, from CODE V's TOR.
852
+
853
+ `criterion` "rms" (polychromatic RMS wavefront, waves) or "mtf" (needs
854
+ `frequency` in cycles/mm and `azimuth`). `mode` "sensitivity" evaluates
855
+ the lens's tolerances as they are (TOR's default set if it has none);
856
+ "inverse" asks TOR to size each variable tolerance so it alone degrades
857
+ performance by `degradation` (default 0.01): a way to draft a tolerance
858
+ budget, which you then enter with `set_tolerances`. The lens's tolerances
859
+ and compensators are left as they were.
860
+
861
+ Per field: nominal value, probable change, cumulative probability table
862
+ (50/84.1/97.7/99.9%), the value with tolerances at 97.7%
863
+ (`with_tolerances_97_7`), compensator range, and the `top` tolerances
864
+ ranked by their effect (value, change for plus and minus errors,
865
+ compensator moves). Also names the worst field.
866
+ """
867
+ return tolerancing.run(engine, criterion, frequency, azimuth, top, wait_s, mode, degradation)
868
+
869
+
870
+ @mcp.tool(annotations=_changes(destructive=False, idempotent=False))
871
+ def monte_carlo(
872
+ trials: int = 100,
873
+ metric: Literal["spot", "mtf", "strehl", "encircled_energy"] = "spot",
874
+ frequency: float | None = None,
875
+ azimuth: Literal["tan", "rad"] = "tan",
876
+ percent: float | None = None,
877
+ compensators: list[CompensatorVariable] | None = None,
878
+ threshold: float | None = None,
879
+ wait_s: float = 240.0,
880
+ ) -> dict[str, Any]:
881
+ """Monte Carlo tolerancing (CODE V's TOLMONTE): performance over random builds, and yield.
882
+
883
+ Each trial perturbs the lens by all its tolerances at once (add them with
884
+ `set_tolerances` first), refocuses with `compensators` (default: the
885
+ back focus, the thickness before the image; [] for none) and evaluates
886
+ `metric` per field: "spot" (RMS spot diameter), "mtf" (needs `frequency`
887
+ in cycles/mm, `azimuth`), "strehl", or "encircled_energy" (diameter at
888
+ `percent`, default 80). With `threshold`, reports the fraction of builds
889
+ that meet it per field and on all fields at once (yield).
890
+
891
+ Runs on a copy; the session's lens is put back afterwards. Takes roughly
892
+ 0.5 s per trial for a triplet. If it is still running after `wait_s`, call
893
+ `get_monte_carlo_result`.
894
+ """
895
+ return montecarlo.start(engine, trials, metric, frequency, azimuth, percent,
896
+ [c.model_dump() for c in compensators] if compensators is not None else None,
897
+ threshold, wait_s)
898
+
899
+
900
+ @mcp.tool(annotations=_changes(destructive=False, idempotent=False))
901
+ def get_monte_carlo_result(wait_s: float = 240.0) -> dict[str, Any]:
902
+ """Wait for a running monte_carlo and return its report (as monte_carlo does)."""
903
+ return montecarlo.result(engine, wait_s)
904
+
905
+
906
+ # -- long-running commands ----------------------------------------------------
907
+
908
+
909
+ @mcp.tool(annotations=_changes(destructive=True, idempotent=False))
910
+ def start_long_command(command: str, snapshot: bool = True) -> dict[str, Any]:
911
+ """Start a long-running command (e.g. `AUT; ...; GO`) without waiting.
912
+
913
+ Follow with `poll_long_command` until `executing` is false. By default the
914
+ lens is snapshotted first (label in `snapshot`), so an optimization that
915
+ goes wrong can be undone with `restore_snapshot`; the command is not
916
+ started if that snapshot fails.
917
+ """
918
+ snap = None
919
+ if snapshot:
920
+ snap = snapshots.save_snapshot(engine, snapshots.auto_label(), f"before: {command[:120]}", True)
921
+ if not snap["ok"]:
922
+ return {**snap, "ok": False, "note": "Command not started because the snapshot failed."}
923
+ result = engine.async_start(command)
924
+ if snap:
925
+ result["snapshot"] = snap["label"]
926
+ return result
927
+
928
+
929
+ @mcp.tool(annotations=_read_only())
930
+ def poll_long_command(wait_s: float = 5.0) -> dict[str, Any]:
931
+ """Wait up to `wait_s` seconds for the long command, then report.
932
+
933
+ Returns `executing: true` while it runs, or the listing output when done.
934
+ """
935
+ return engine.async_poll(int(max(0.0, min(wait_s, 30.0)) * 1000))
936
+
937
+
938
+ @mcp.tool(annotations=_changes(destructive=False, idempotent=True))
939
+ def stop_long_command() -> dict[str, Any]:
940
+ """Ask CODE V to halt the running long command, then poll until it reports stopped.
941
+
942
+ The lens is left as the command had it when it stopped; restore the
943
+ automatic snapshot taken at the start to undo it.
944
+ """
945
+ return engine.async_stop()
946
+
947
+
948
+ def _summary_values() -> dict[str, Any]:
949
+ return engine.evaluate_many(
950
+ {"title": "(TIT)", "efl": "(EFL)", "fno": "(FNO)", "image_surface": "(NUM S)"}
951
+ ).get("values", {})
952
+
953
+
954
+ def main() -> None:
955
+ try:
956
+ mcp.run()
957
+ finally:
958
+ # Release the licence when the client disconnects. Done here rather
959
+ # than in atexit, which runs after the COM worker thread is gone.
960
+ engine.shutdown()
961
+ if engine.running:
962
+ engine.stop()
963
+
964
+
965
+ if __name__ == "__main__":
966
+ main()