diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 22408a7..8936754 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,4 +30,4 @@ jobs: # The MCP server must import on a core-only install (the camera and # SDK stacks are lazy imports) - fail the build if that regresses. # (tests/test_mcp_server.py goes further and actually runs it.) - - run: python -c "import mcp_server.server_loop, timelapse.scheduler" + - run: python -c "import mcp_server.baumer_ti2.baumer_ti2_server, timelapse.scheduler" diff --git a/CHANGELOG.md b/CHANGELOG.md index b6b070b..e376e42 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,60 @@ Format follows [Keep a Changelog](https://keepachangelog.com/); versions follow ## [Unreleased] +### Removed +- Everything NIS-Elements. The `nis-elements-mcp` package (with its history) + moved to [BioNanomics/nis-elements-mcp](https://github.com/BioNanomics/nis-elements-mcp), + under `bridge/`. Gone from here: `packages/`, `mcp_server/nis/`, + `acquisition/_nis_settings.py`, `acquisition/nis_events.py`, + `acquisition/nis_monitor.py`, `acquisition/backends/nis_bridge.py`, + `acquisition/calibration/nis_port_probe.py`, `docs/nis-bridge.md`, the + `confocal-mcp-nis` command and the package's CI job. `nis_sdk.py` and + `nis_mock.py` stay: they drive the Ti2 stage, not NIS-Elements. +- `acquisition/estop.py` and `acquisition/estop_panel.py` are real modules + again (not forwarders to the package), with their tests in `tests/`. They + keep the same e-stop file (`NIS_ESTOP_FILE`, else `~/.nis-mcp/ESTOP`) and + panel mutex as nis-elements-mcp, so one STOP still stops both. A stop left + in the pre-2026-10-30 file `~/.confocal-mcp/ESTOP` is no longer moved over. + +### Changed +- The two MCP servers now live in folders named after what they drive: + `mcp_server/baumer_ti2/` (`baumer_ti2_server.py`, `baumer_ti2_tools.py`; + was `server_loop.py`, `loop_tools.py`) and `mcp_server/nis/` + (`nis_server.py`, `nis_tools.py`; was `server_nis.py`, `nis_tools.py`). + New commands `baumer-ti2-mcp` and `nis-mcp`; the old `confocal-mcp` and + `confocal-mcp-nis` still work. Tool names are unchanged. +- The NIS-Elements MCP server is now its own package, `nis-elements-mcp`, in + `packages/nis-elements-mcp/` (server, tools, bridge client, bridge job, + e-stop and STOP panel, event log, monitor, and their tests). This repo + depends on it from that folder. The old modules (`acquisition/estop.py`, + `acquisition/nis_*.py`, `acquisition/backends/nis_bridge.py`, + `acquisition/nis_bridge/bridge_job.py`, `mcp_server/nis/`) forward to the + package, so imports and `python -m` commands are unchanged; this repo keeps + its NIS logs and captures in `logs/nis` and `data/NIS/captures`. + **Paste `packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_job.py` + into the NIS JOBS task from now on.** `nis-mcp` now comes from the package. +- `nis-elements-mcp` reads all its settings from `NIS_*` environment variables + (`settings.py`): `NIS_BRIDGE_HOST/PORT`, `NIS_CAPTURE_DIR`, `NIS_LOG_DIR`, + `NIS_ESTOP_FILE`, `NIS_ALLOWED_OBJECTIVES` (default 4,10), + `NIS_ALLOWED_EXPERIMENTS` (new: optional list of ND experiment names), + `NIS_MAX_STEP_UM` (default 1000), `NIS_NO_ESTOP_PANEL`, `NIS_NO_MONITOR`. + The limits are now also checked in the client before a request is sent. + **The e-stop file moved to `~/.nis-mcp/ESTOP`** for every process here and + for the bridge job; a stop engaged in the old `~/.confocal-mcp/ESTOP` is + moved there on first start. The old `CONFOCAL_*` switch names still work + in this repo. `nis_port_probe.py` no longer hard-codes a user path. +- `nis-elements-mcp` 0.1.0 has its own README (setup in NIS, install into + another project, safety rules, settings), CHANGELOG and MIT LICENSE, and the + commands `nis-mcp-bridge` (with `job-file`), `nis-mcp-estop` and + `nis-mcp-monitor`. CI installs the package on its own and tests it on + Windows and Ubuntu. + +### Removed +- `acquisition/nis_bridge/` (the old `bridge_job.py` forwarder). It looked + like the bridge job but failed inside NIS when pasted. The only bridge job + is now `packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_job.py` + (`nis-mcp-bridge job-file` prints the path). + ### Added - `analysis/worm_short.py` - C. elegans Short from an AML18 time-lapse surveyed by `aml18_survey`: neurons-only opening, brightfield with RFP glow, diff --git a/README.md b/README.md index e4bb5cf..f5673e5 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ identifying that specific capture. `backend` is `"mock"` (default, safe, simulated) or `"sdk"` (real hardware - `move()`/`get_image()` require `confirm=True` for anything -that touches real hardware). See `mcp_server/loop_tools.py`'s header +that touches real hardware). See `mcp_server/baumer_ti2/baumer_ti2_tools.py`'s header comment for the full design rationale (why no `get_time()`, why no `stage_revision` yet, etc.). @@ -69,31 +69,13 @@ python -m timelapse.scheduler --backend mock --model-trigger ... # Claude judg python -m timelapse.frame_audit FRAME_DIR --timestamps times.csv --around 25h --window 1h ``` -## NIS bridge (`confocal-mcp-nis`) - not yet tested on the scope +## NIS-Elements -A separate MCP server for what only NIS-Elements can do: the AX confocal -lasers and saved ND experiments. A JOBS Python task inside NIS -(`acquisition/nis_bridge/bridge_job.py`) serves NIS macro calls on -`127.0.0.1:8766`. The `confocal-mcp-nis` server talks to it and adds a -confirm gate, the e-stop and a capture-folder rule. `server_loop` is -unchanged. Setup, safety rules and the on-scope test plan: -[docs/nis-bridge.md](docs/nis-bridge.md). - -``` -python -m acquisition.backends.nis_bridge status # by hand, while the bridge job runs -python -m acquisition.nis_monitor # live view: status + every action (logs/nis/) -confocal-mcp-nis # the MCP server -python -m mcp_server.server_nis # same, from a source checkout -``` - -MCP client config for a source checkout (adjust the path to this repo's venv): - -```json -{ "mcpServers": { "confocal-nis": { - "command": "D:\\path\\to\\microscope-agent\\.venv\\Scripts\\python.exe", - "args": ["-m", "mcp_server.server_nis"], - "cwd": "D:\\path\\to\\microscope-agent" } } } -``` +Not in this repo. The MCP servers for NIS-Elements (the AX confocal lasers, +saved ND experiments) live in +[BioNanomics/nis-elements-mcp](https://github.com/BioNanomics/nis-elements-mcp). +They share this repo's e-stop file (`NIS_ESTOP_FILE`, else `~/.nis-mcp/ESTOP`) +and STOP panel, so one STOP button stops both. ## Tests @@ -148,15 +130,15 @@ machine. Not needed for `backend="mock"`. ## Run ``` -confocal-mcp # installed console script -python -m mcp_server.server_loop # equivalent, from a source checkout +baumer-ti2-mcp # installed console script (old name: confocal-mcp) +python -m mcp_server.baumer_ti2.baumer_ti2_server # equivalent, from a source checkout ``` Point an MCP client at it - Claude Desktop's `claude_desktop_config.json`, or a project-level `.mcp.json` for Claude Code: ```json -{ "mcpServers": { "confocal": { "command": "confocal-mcp" } } } +{ "mcpServers": { "baumer-ti2": { "command": "baumer-ti2-mcp" } } } ``` Data (captures, move/frame history logs, saved positions) is written under the @@ -164,8 +146,8 @@ current working directory - so launch the server from a stable location, or set `CONFOCAL_MCP_DATA_DIR` to pin it explicitly: ```json -{ "mcpServers": { "confocal": { - "command": "confocal-mcp", +{ "mcpServers": { "baumer-ti2": { + "command": "baumer-ti2-mcp", "env": { "CONFOCAL_MCP_DATA_DIR": "D:\\path\\to\\your\\data" } } } } ``` @@ -180,8 +162,8 @@ stderr rather than failing at the first capture. A second, independent way to drive the same tools - a small interactive CLI that calls Claude (Anthropic API) directly with tool use, importing -`mcp_server/loop_tools.py`'s functions in-process rather than going -through `server_loop.py`'s MCP/stdio protocol. `server_loop.py` is +`mcp_server/baumer_ti2/baumer_ti2_tools.py`'s functions in-process rather than going +through `baumer_ti2_server.py`'s MCP/stdio protocol. `baumer_ti2_server.py` is unaffected either way - use whichever fits: MCP for Claude Desktop/Code, this loop for a standalone script. @@ -203,8 +185,8 @@ python -m harness.agent ## MCP client harness (`harness/mcp_agent.py`) A third way to drive the same tools - the real-MCP-protocol counterpart -to `harness/agent.py`. Instead of importing `loop_tools.py` in-process, -this one spawns `server_loop.py` as a separate subprocess and talks to +to `harness/agent.py`. Instead of importing `baumer_ti2_tools.py` in-process, +this one spawns `baumer_ti2_server.py` as a separate subprocess and talks to it exactly the way Claude Desktop/Code do: real MCP over stdio, using the current MCP SDK (`mcp==2.0.0`, protocol version `2026-07-28`). Same `.env`/`ANTHROPIC_API_KEY` setup, same live "y/N" real-hardware approval diff --git a/acquisition/backends/baumer_genicam.py b/acquisition/backends/baumer_genicam.py index c5fb09c..8fbec5c 100644 --- a/acquisition/backends/baumer_genicam.py +++ b/acquisition/backends/baumer_genicam.py @@ -15,8 +15,8 @@ # # 2026-08-17: now the PRIMARY capture path by deliberate decision - the # team decided against capturing through NIS-Elements/Jobs at all (see -# mcp_server/loop_tools.py's header comment), so this module's capture() -# is what mcp_server.loop_tools.get_image() actually calls. Whatever is +# mcp_server/baumer_ti2/baumer_ti2_tools.py's header comment), so this module's capture() +# is what mcp_server.baumer_ti2.baumer_ti2_tools.get_image() actually calls. Whatever is # optically coupled to wherever this camera is physically mounted is # what gets captured - that's a hardware/alignment decision made outside # this code, not something this module controls. diff --git a/acquisition/backends/nis_bridge.py b/acquisition/backends/nis_bridge.py deleted file mode 100644 index 8d725c3..0000000 --- a/acquisition/backends/nis_bridge.py +++ /dev/null @@ -1,163 +0,0 @@ -# nis_bridge.py -# ------------------------------------------------------------ -# Client for the NIS bridge (acquisition/nis_bridge/bridge_job.py), the -# JOBS task that exposes NIS-Elements macro calls on 127.0.0.1:8766 while -# it runs. Used by the NIS MCP server; also a command line for testing by -# hand: -# -# python -m acquisition.backends.nis_bridge status -# python -m acquisition.backends.nis_bridge move 100 0 -# python -m acquisition.backends.nis_bridge objective "Plan Fluor 10x Ph1 DLL" -# python -m acquisition.backends.nis_bridge optconfs -# python -m acquisition.backends.nis_bridge capture D:\...\check.nd2 -# python -m acquisition.backends.nis_bridge nd-run "C. elegans 3h" -# python -m acquisition.backends.nis_bridge nd-finish -# python -m acquisition.backends.nis_bridge shutdown -# -# The e-stop is checked HERE as well as in the bridge: a refused request -# never leaves this process, so a stopped microscope does not depend on -# the NIS side having been updated. Stopping an ND run (nd-finish) and -# shutting the bridge down are always allowed - they only end things. -# -# Every action here is also written to the NIS event log -# (acquisition/nis_events.py), which `python -m acquisition.nis_monitor` -# shows live. Status reads are not logged (the monitor polls them). -# -# CONFOCAL_NIS_BRIDGE_URL overrides the address (default -# http://127.0.0.1:8766). -# ------------------------------------------------------------ - -from __future__ import annotations - -import argparse -import json -import os -import sys -import time -import urllib.error -import urllib.request - -from acquisition import estop, nis_events - -DEFAULT_URL = "http://127.0.0.1:8766" - - -class BridgeUnavailable(RuntimeError): - """The bridge job is not running (or not reachable).""" - - -class NISBridge: - def __init__(self, url: str | None = None, timeout_s: float = 30.0): - self.url = (url or os.environ.get("CONFOCAL_NIS_BRIDGE_URL") or DEFAULT_URL).rstrip("/") - self.timeout_s = timeout_s - - def _call(self, method: str, path: str, body: dict | None = None, - timeout_s: float | None = None) -> dict: - data = json.dumps(body or {}).encode() if method == "POST" else None - req = urllib.request.Request(self.url + path, data=data, method=method, - headers={"Content-Type": "application/json"}) - try: - with urllib.request.urlopen(req, timeout=timeout_s or self.timeout_s) as r: - return json.loads(r.read()) - except urllib.error.HTTPError as e: - try: - return {"http_status": e.code, **json.loads(e.read())} - except ValueError: - return {"http_status": e.code, "error": str(e)} - except (urllib.error.URLError, ConnectionError, TimeoutError) as e: - raise BridgeUnavailable( - f"NIS bridge not reachable at {self.url} ({e}). Is the bridge job " - "running in NIS-Elements? See docs/nis-bridge.md.") from e - - # Read-only - def status(self) -> dict: - return self._call("GET", "/status") - - def _act(self, action: str, params: dict, send, guarded: bool = True) -> dict: - """Run one action and write it to the NIS event log (nis_events.py): - a "start" line, then "ok", "failed", "refused" or "error".""" - nis_events.record(action, "start", params=params) - t0 = time.time() - try: - if guarded: - estop.check() - result = send() - except estop.EStopEngaged as e: - nis_events.record(action, "refused", params=params, message=str(e)) - raise - except BridgeUnavailable as e: - nis_events.record(action, "error", params=params, message=str(e)) - raise - phase = "failed" if "error" in result else "ok" - nis_events.record(action, phase, params=params, result=result, - elapsed_s=round(time.time() - t0, 1)) - return result - - def optical_configs(self) -> dict: - return self._call("GET", "/optconfs") - - # Motion / acquisition: e-stop checked before anything is sent - def move_relative(self, dx_um: float, dy_um: float) -> dict: - return self._act("move", {"dx": dx_um, "dy": dy_um}, - lambda: self._call("POST", "/move", {"dx": dx_um, "dy": dy_um})) - - def change_objective(self, name: str) -> dict: - return self._act("objective", {"name": name}, - lambda: self._call("POST", "/objective", {"name": name})) - - def capture(self, path: str) -> dict: - return self._act("capture", {"path": path}, - lambda: self._call("POST", "/capture", {"path": path}, timeout_s=300)) - - def nd_run(self, experiment: str, timeout_s: float = 7200.0) -> dict: - # ND_RunExperiment may block until the run ends (unverified), so - # the answer can take as long as the run itself. - return self._act("nd_run", {"experiment": experiment}, - lambda: self._call("POST", "/nd/run", {"experiment": experiment}, - timeout_s=timeout_s)) - - # Always allowed: these only end things - def nd_finish(self) -> dict: - return self._act("nd_finish", {}, lambda: self._call("POST", "/nd/finish"), guarded=False) - - def shutdown(self) -> dict: - return self._act("shutdown", {}, lambda: self._call("POST", "/shutdown"), guarded=False) - - -def main() -> None: - ap = argparse.ArgumentParser(description="Talk to the NIS bridge job by hand.") - ap.add_argument("--url", help=f"bridge address (default {DEFAULT_URL})") - sub = ap.add_subparsers(dest="cmd", required=True) - sub.add_parser("status") - m = sub.add_parser("move", help="relative XY move in um (max 1000 per axis)") - m.add_argument("dx", type=float); m.add_argument("dy", type=float) - o = sub.add_parser("objective", help="exact name as listed by status (4x/10x only)") - o.add_argument("name") - sub.add_parser("optconfs", help="list the optical configurations") - c = sub.add_parser("capture", help="capture one image and save it as .nd2") - c.add_argument("path") - r = sub.add_parser("nd-run", help="load a saved ND experiment by name and run it") - r.add_argument("experiment") - sub.add_parser("nd-finish", help="end the running ND experiment after this loop") - sub.add_parser("shutdown", help="stop the bridge job") - a = ap.parse_args() - - b = NISBridge(a.url) - try: - out = {"status": lambda: b.status(), - "move": lambda: b.move_relative(a.dx, a.dy), - "objective": lambda: b.change_objective(a.name), - "optconfs": lambda: b.optical_configs(), - "capture": lambda: b.capture(a.path), - "nd-run": lambda: b.nd_run(a.experiment), - "nd-finish": lambda: b.nd_finish(), - "shutdown": lambda: b.shutdown()}[a.cmd]() - except (estop.EStopEngaged, BridgeUnavailable) as e: - raise SystemExit(str(e)) - # Objective names contain a lambda; a cp1252 Windows console cannot print it. - sys.stdout.reconfigure(encoding="utf-8", errors="replace") - print(json.dumps(out, indent=2, ensure_ascii=False)) - - -if __name__ == "__main__": - main() diff --git a/acquisition/backends/nis_sdk.py b/acquisition/backends/nis_sdk.py index 981a74d..cdf6eff 100644 --- a/acquisition/backends/nis_sdk.py +++ b/acquisition/backends/nis_sdk.py @@ -41,7 +41,7 @@ # So: X/Y properties are in units of 0.1um ("decimicrons"), Z is in units # of 0.01um ("centimicrons"). XY_GetPosition/XY_Move/Z_GetPosition/Z_Move # below convert to/from plain microns at their boundary so callers -# (StagePositionManager, mcp_server/loop_tools.py) never see raw counts. +# (StagePositionManager, mcp_server/baumer_ti2/baumer_ti2_tools.py) never see raw counts. # ------------------------------------------------------------ import queue @@ -170,7 +170,7 @@ class NISSdk: Every instance shares the same underlying COM connection (see _ComThread above) - constructing NISSdk() repeatedly (once per MCP - tool call, as mcp_server/loop_tools.py does) is cheap and does not open a + tool call, as mcp_server/baumer_ti2/baumer_ti2_tools.py does) is cheap and does not open a new connection each time. """ diff --git a/acquisition/calibration/nis_port_probe.py b/acquisition/calibration/nis_port_probe.py deleted file mode 100644 index 26a0b4b..0000000 --- a/acquisition/calibration/nis_port_probe.py +++ /dev/null @@ -1,117 +0,0 @@ -# IMPORTANT: 'limjob' must be imported like this (not from nor as) -import limjob - -# A JOBS Python task that serves a tiny HTTP control API from inside NIS for -# 10 minutes (or until Abort). From a terminal on this PC: -# curl http://127.0.0.1:8765/status -# curl "http://127.0.0.1:8765/move?dx=200&dy=0" relative, um -# curl "http://127.0.0.1:8765/objective?name=" -# -# NIS macro functions are called through ctypes on g5_regprocs.dll, the way -# Nikon's own limpy.macro calls WaitText. Signatures are from the NIS 6.20 -# macro reference (Docs/nis/eng_ar); macro char* is wchar_t* in this build. -# -# NIS calls are made only on the job's own thread (the run() loop); the HTTP -# thread just queues requests, since NIS is not known to be thread-safe. -# -# SAFETY: moves are relative and capped at MAX_STEP_UM per call; nothing -# moves while the e-stop file exists (same file acquisition/estop.py uses); -# Z is never moved; objective changes are limited to 4x and 10x, whose long -# working distances cannot reach the dish. -import ctypes as ct, http.server, json, os, queue, threading, time, urllib.parse - -PORT, RUN_S, MAX_STEP_UM = 8765, 600, 1000.0 -ESTOP = r"C:\Users\AX Confocal\.confocal-mcp\ESTOP" -ALLOWED_OBJECTIVES = ("4x", "10x") - -nis = ct.cdll.g5_regprocs -for fn, args in {"StgGetPosXY": [ct.POINTER(ct.c_double)] * 2, - "StgGetPosZ": [ct.POINTER(ct.c_double), ct.c_int], - "StgMoveXY": [ct.c_double, ct.c_double, ct.c_int], - "Stg_GetNosepiecePosition": [], - "Stg_GetNosepiecePositions": [], - "Stg_GetNosepieceObjectiveName": [ct.c_int, ct.c_wchar_p, ct.c_int], - "GetCurrentObjName": [ct.c_wchar_p], - "ChangeObjective": [ct.c_wchar_p]}.items(): - getattr(nis, fn).argtypes, getattr(nis, fn).restype = args, ct.c_int - - -def status(): - x, y, z = ct.c_double(), ct.c_double(), ct.c_double() - rc_xy = nis.StgGetPosXY(ct.byref(x), ct.byref(y)) - rc_z = nis.StgGetPosZ(ct.byref(z), 0) - cur = ct.create_unicode_buffer(255); nis.GetCurrentObjName(cur) - names = {} - for i in range(0, nis.Stg_GetNosepiecePositions() + 1): # index base unknown: try 0..n - b = ct.create_unicode_buffer(255) - if nis.Stg_GetNosepieceObjectiveName(i, b, 255) == 1 and b.value: - names[i] = b.value - return {"xy_um": [x.value, y.value], "xy_rc": rc_xy, "z_um": z.value, "z_rc": rc_z, - "nosepiece_position": nis.Stg_GetNosepiecePosition(), - "current_objective": cur.value, "nosepiece_objectives": names} - - -def move(dx, dy): - if os.path.exists(ESTOP): - return {"error": "e-stop engaged - not moving"} - if max(abs(dx), abs(dy)) > MAX_STEP_UM: - return {"error": f"step over {MAX_STEP_UM} um refused"} - before = status()["xy_um"] - rc = nis.StgMoveXY(dx, dy, 1) # 1 = MOVE_RELATIVE - return {"rc": rc, "before_um": before, "after_um": status()["xy_um"]} - - -def objective(name): - if os.path.exists(ESTOP): - return {"error": "e-stop engaged - not changing objective"} - if not any(k in name for k in ALLOWED_OBJECTIVES): - return {"error": f"only {ALLOWED_OBJECTIVES} objectives allowed here"} - before = status() - rc = nis.ChangeObjective(name) - after = status() - return {"rc": rc, "before": before["current_objective"], "after": after["current_objective"], - "nosepiece_before": before["nosepiece_position"], - "nosepiece_after": after["nosepiece_position"]} - - -jobs = queue.Queue() - - -class H(http.server.BaseHTTPRequestHandler): - def do_GET(self): - u = urllib.parse.urlparse(self.path); q = dict(urllib.parse.parse_qsl(u.query)) - call = {"/status": lambda: status(), - "/move": lambda: move(float(q.get("dx", 0)), float(q.get("dy", 0))), - "/objective": lambda: objective(q.get("name", ""))}.get(u.path) - if call is None: - out = {"error": "use /status, /move?dx=&dy=, /objective?name="} - else: - box = queue.Queue(); jobs.put((call, box)) - try: - out = box.get(timeout=60) - except queue.Empty: - out = {"error": "timed out waiting for NIS"} - body = (json.dumps(out, indent=1) + "\n").encode() - self.send_response(200); self.send_header("Content-Type", "application/json") - self.end_headers(); self.wfile.write(body) - - -def run(imgs: tuple[limjob.Image], Job: limjob.JobParam, macro: limjob.MacroParam, ctx: limjob.RunContext): - s = http.server.ThreadingHTTPServer(("127.0.0.1", PORT), H) - threading.Thread(target=s.serve_forever, daemon=True).start() - print(f"listening on 127.0.0.1:{PORT}, pid {os.getpid()}") - abort = getattr(ctx, "shouldAbort", lambda: False) - t0 = time.time() - try: - while time.time() - t0 < RUN_S and not abort(): - try: - call, box = jobs.get(timeout=0.2) - except queue.Empty: - continue - try: - box.put(call()) - except Exception as e: - box.put({"error": f"{type(e).__name__}: {e}"}) - finally: - s.shutdown(); s.server_close() - print("server stopped") diff --git a/acquisition/calibration/ti2_inventory.py b/acquisition/calibration/ti2_inventory.py index a099799..f58c844 100644 --- a/acquisition/calibration/ti2_inventory.py +++ b/acquisition/calibration/ti2_inventory.py @@ -115,7 +115,7 @@ def inventory(sdk: Any = None) -> list[dict]: Pass an existing NISSdk to reuse its COM thread; omit it to build one. NISSdk is imported lazily so this module stays importable without pywin32 or the Ti2 SDK installed (same pattern as the lazy backend - imports in mcp_server/loop_tools.py). + imports in mcp_server/baumer_ti2/baumer_ti2_tools.py). """ if sdk is None: from acquisition.backends.nis_sdk import NISSdk diff --git a/acquisition/estop.py b/acquisition/estop.py index 45ef17b..1944e9b 100644 --- a/acquisition/estop.py +++ b/acquisition/estop.py @@ -38,6 +38,12 @@ # have. ESTOP_PATH is absolute and identical for every process on the # machine. # +# ONE STOP FOR THE WHOLE MICROSCOPE. ESTOP_PATH is the same file the +# nis-elements-mcp servers check (NIS_ESTOP_FILE, else ~/.nis-mcp/ESTOP), +# and PANEL_MUTEX is the same name its STOP panel holds. So one STOP button +# stops the Ti2 scripts here and anything driving NIS, and only one panel +# is ever on screen, whichever project opened it. +# # FAIL SAFE: if the state cannot be determined (unreadable directory, odd # filesystem error), check() treats the stop as ENGAGED. An e-stop that # fails open is not a safety device. The cost of the opposite error is a @@ -69,13 +75,13 @@ #: Absolute and machine-wide. Never derive this from the working #: directory - see the module header. -ESTOP_PATH = Path(os.environ.get("CONFOCAL_ESTOP_FILE", - Path.home() / ".confocal-mcp" / "ESTOP")) +ESTOP_PATH: Path = Path(os.environ.get("NIS_ESTOP_FILE", "").strip() + or Path.home() / ".nis-mcp" / "ESTOP") #: Held by the running STOP panel for its whole life, so every process can #: tell whether one is already on screen. Windows frees it if the panel dies. -PANEL_MUTEX = r"Local\confocal-mcp-estop-panel" +PANEL_MUTEX = r"Local\nis-mcp-estop-panel" class EStopEngaged(RuntimeError): @@ -165,9 +171,10 @@ def launch_panel() -> None: Detached, not a child: the panel must outlive this process. Failures go to stderr - never stdout, which is the MCP JSON-RPC channel - and - never stop the caller. CONFOCAL_NO_ESTOP_PANEL=1 turns it off. + never stop the caller. NIS_NO_ESTOP_PANEL=1 (or the older + CONFOCAL_NO_ESTOP_PANEL=1) turns it off. """ - if os.environ.get("CONFOCAL_NO_ESTOP_PANEL"): + if any(os.environ.get(n, "").strip() for n in ("NIS_NO_ESTOP_PANEL", "CONFOCAL_NO_ESTOP_PANEL")): return try: if panel_running(): diff --git a/acquisition/nis_bridge/__init__.py b/acquisition/nis_bridge/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/acquisition/nis_bridge/bridge_job.py b/acquisition/nis_bridge/bridge_job.py deleted file mode 100644 index 4f6be7f..0000000 --- a/acquisition/nis_bridge/bridge_job.py +++ /dev/null @@ -1,354 +0,0 @@ -# IMPORTANT: 'limjob' must be imported like this (not from nor as) -try: - import limjob -except ImportError: # off the microscope (tests): the module is only needed for type hints - limjob = None - -# bridge_job.py -# ------------------------------------------------------------ -# The NIS-Elements side of the NIS bridge: paste this file into a JOBS -# Python task and run the job. While the job runs, NIS answers a small -# JSON-over-HTTP API on 127.0.0.1:8766, which acquisition/backends/ -# nis_bridge.py (and through it the NIS MCP server) talks to. -# -# GET /status positions, objective, ND run state -# POST /move {"dx", "dy"} relative XY move, um -# POST /objective {"name"} Stg_SetNosepiecePosition (turns the turret) then ChangeObjective -# (NIS calibration), allow-listed names only -# GET /optconfs names of the optical configurations (read-only) -# POST /capture {"path"} Capture, save as ND2, close the document -# POST /nd/run {"experiment"} ND_LoadExperiment + ND_RunExperiment(0) -# POST /nd/finish ND_FinishExperiment (stop after this loop) -# POST /shutdown stop serving and end the job -# -# STOPPING THE JOB. Do NOT use the JOBS Abort button: a Python task's -# RunContext (limjob.py) has no abort flag, so Abort cannot interrupt the -# serving loop and NIS freezes waiting for it (seen on the scope -# 2026-10-14). Stop it with -# python -m acquisition.backends.nis_bridge shutdown -# As a backstop the job also ends itself after IDLE_STOP_S with no request. -# -# WHY A BRIDGE AND NOT THE MCP SERVER ITSELF INSIDE NIS. Nothing has to be -# installed into NIS's own Python (Nikon pins its packages), a crash in our -# code cannot take NIS down with it, and the MCP server keeps the e-stop, -# confirm gate and tests it already has. This file only translates HTTP -# requests into NIS macro calls. -# -# HOW NIS IS CALLED. NIS macro functions are exported by g5_regprocs.dll -# and called through ctypes - the way NIS's own limpy.macro calls -# WaitText. Signatures are from the NIS 6.20 macro reference -# (Docs/nis/eng_ar on the microscope PC). A macro char* is wchar_t* in -# this build (limpy passes WaitText's text as c_wchar_p). -# -# THREADING. A JOBS Python task runs on NIS's main thread, and serving there -# froze NIS (2026-10-15). So run() starts serve() on a worker thread and -# returns. NIS is not known to be thread-safe, so every NIS call still runs -# on that one worker thread; the HTTP threads only queue requests and wait -# for the answer. Whether macro calls (Ti2 moves, Capture) are allowed off -# the main thread is UNVERIFIED. A call that takes long (ND_RunExperiment -# may block until the run ends - unverified) delays the requests queued -# behind it. -# -# SAFETY, enforced here as well as in the client: -# * motion and acquisition only on POST, so a browser cannot trigger them -# * nothing moves or starts while the e-stop file exists (the same file -# acquisition/estop.py uses) -# * XY moves are relative and capped at MAX_STEP_UM; Z is never moved -# * objective changes only to 4x/10x names (ALLOWED_MAGNIFICATIONS): -# working distances of 20 and 4 mm cannot reach the dish -# * serves on 127.0.0.1 only -# ------------------------------------------------------------ -import ctypes as ct -import http.server -import json -import os -import queue -import re -import threading -import time -from pathlib import Path - -PORT = 8766 # 8765 is the plain port probe (nis_port_probe.py) -VERSION = 1 -MAX_STEP_UM = 1000.0 -ALLOWED_MAGNIFICATIONS = (4, 10) -# "4x" / "10x" as a whole magnification - not the 4x inside "14x" or "40x" -_MAG = re.compile(r"(? bool: - try: - return ESTOP.exists() - except OSError: - return True # cannot tell -> treat as engaged, like estop.py - - -class Bridge: - """The operations, as plain methods returning JSON-able dicts.""" - - def __init__(self, macro: Macro): - self.m = macro - - def status(self) -> dict: - x, y, z = ct.c_double(), ct.c_double(), ct.c_double() - rc_xy = self.m.StgGetPosXY(ct.byref(x), ct.byref(y)) - rc_z = self.m.StgGetPosZ(ct.byref(z), 0) - cur = ct.create_unicode_buffer(255) - self.m.GetCurrentObjName(cur) - names = {} - for i in range(0, self.m.Stg_GetNosepiecePositions() + 1): # 0-based, checked on the scope 2026-10-13 - b = ct.create_unicode_buffer(255) - if self.m.Stg_GetNosepieceObjectiveName(i, b, 255) == 1 and b.value: - names[str(i)] = b.value - return {"version": VERSION, "pid": os.getpid(), - "xy_um": [x.value, y.value], "xy_rc": rc_xy, - "z_um": z.value, "z_rc": rc_z, - "nosepiece_position": self.m.Stg_GetNosepiecePosition(), - "current_objective": cur.value, "nosepiece_objectives": names, - "nd_running": bool(self.m.ND_IsInExperimentCapture()), - "estop_engaged": _estop_engaged()} - - def _refuse_if_stopped(self, what: str) -> dict | None: - if _estop_engaged(): - return {"error": f"e-stop engaged - {what} refused", "estop_engaged": True} - return None - - def move(self, dx: float, dy: float) -> dict: - if (r := self._refuse_if_stopped("move")): - return r - if max(abs(dx), abs(dy)) > MAX_STEP_UM: - return {"error": f"step over {MAX_STEP_UM} um refused"} - before = self.status()["xy_um"] - rc = self.m.StgMoveXY(float(dx), float(dy), MOVE_RELATIVE) - return {"rc": rc, "before_um": before, "after_um": self.status()["xy_um"]} - - def objective(self, name: str) -> dict: - if (r := self._refuse_if_stopped("objective change")): - return r - mags = {float(m) for m in _MAG.findall(name)} - if len(mags) != 1 or mags.pop() not in ALLOWED_MAGNIFICATIONS: - return {"error": f"only {ALLOWED_MAGNIFICATIONS}x objectives are allowed, got {name!r}"} - before = self.status() - # Two separate things, both needed (seen on the scope 2026-10-13/14): - # Stg_SetNosepiecePosition turns the turret but NIS's objective name - # and calibration stay on the old objective, and ChangeObjective - # updates the name and calibration but leaves the turret where it - # is. So turn the turret, wait for it to arrive, and only then tell - # NIS - never switch the calibration for a turret that did not move. - targets = [int(i) for i, n in before["nosepiece_objectives"].items() if n == name] - if len(targets) != 1: - return {"error": f"{name!r} is not on the nosepiece exactly once", - "nosepiece_objectives": before["nosepiece_objectives"]} - rc = self.m.Stg_SetNosepiecePosition(targets[0]) - deadline = time.time() + TURRET_SETTLE_S - after = self.status() - while rc == 1 and time.time() < deadline and after["nosepiece_position"] != targets[0]: - time.sleep(TURRET_POLL_S) - after = self.status() - rc_calibration = None - if after["nosepiece_position"] == targets[0]: - rc_calibration = self.m.ChangeObjective(name) - after = self.status() - arrived = (after["nosepiece_position"] == targets[0] - and after["current_objective"] == name) - return {"rc": rc, "rc_calibration": rc_calibration, "arrived": arrived, - "before": before["current_objective"], "after": after["current_objective"], - "nosepiece_before": before["nosepiece_position"], - "nosepiece_after": after["nosepiece_position"]} - - def optical_configs(self) -> dict: - names = [] - for i in range(0, self.m.GetOptConfCount() + 1): # index base unverified: try 0..n - b = ct.create_unicode_buffer(255) - self.m.GetOptConfName(i, b, 255) - if b.value and b.value not in names: - names.append(b.value) - return {"optical_configs": names} - - # No select: SelectOptConf called from this worker thread switched the - # devices ("end success" in NIS's log) and then froze NIS's main thread - # until the bridge was shut down (2026-10-15). Set the optical - # configuration in NIS, or find a way to run it on the UI thread first. - - def capture(self, path: str) -> dict: - if (r := self._refuse_if_stopped("capture")): - return r - if not path.lower().endswith(".nd2"): - return {"error": "path must end in .nd2"} - if os.path.exists(path): - return {"error": f"{path} already exists - refusing to overwrite"} - rc_cap = self.m.Capture() - rc_save = self.m.ImageSaveAs(path, ND2_ALL_LAYERS, 0) - rc_close = self.m.CloseCurrentDocument(QUERYSAVE_NO) - return {"rc_capture": rc_cap, "rc_save": rc_save, "rc_close": rc_close, - "path": path, "saved": os.path.exists(path)} - - def nd_run(self, experiment: str) -> dict: - if (r := self._refuse_if_stopped("ND run")): - return r - if self.m.ND_IsInExperimentCapture(): - return {"error": "an ND experiment is already running"} - rc_load = self.m.ND_LoadExperiment(experiment) - if rc_load != 1: - return {"error": f"ND_LoadExperiment({experiment!r}) returned {rc_load}", "rc_load": rc_load} - t0 = time.time() - rc_run = self.m.ND_RunExperiment(0) # 0: save to disk, do not open - return {"rc_load": rc_load, "rc_run": rc_run, - "call_returned_after_s": round(time.time() - t0, 1), - "nd_running": bool(self.m.ND_IsInExperimentCapture())} - - def nd_finish(self) -> dict: - # Always allowed, e-stop or not: it only ends a run early. - rc = self.m.ND_FinishExperiment() - return {"rc": rc, "nd_running": bool(self.m.ND_IsInExperimentCapture())} - - -# Routes: (method, path) -> function(bridge, body) -> dict -ROUTES = { - ("GET", "/status"): lambda b, body: b.status(), - ("POST", "/move"): lambda b, body: b.move(float(body.get("dx", 0)), float(body.get("dy", 0))), - ("POST", "/objective"): lambda b, body: b.objective(str(body.get("name", ""))), - ("GET", "/optconfs"): lambda b, body: b.optical_configs(), - ("POST", "/capture"): lambda b, body: b.capture(str(body.get("path", ""))), - ("POST", "/nd/run"): lambda b, body: b.nd_run(str(body.get("experiment", ""))), - ("POST", "/nd/finish"): lambda b, body: b.nd_finish(), -} - - -def make_handler(jobs: "queue.Queue", stop: threading.Event, timeout_s: float = 7200.0): - class Handler(http.server.BaseHTTPRequestHandler): - def _answer(self, code: int, out: dict) -> None: - body = (json.dumps(out) + "\n").encode() - self.send_response(code) - self.send_header("Content-Type", "application/json") - self.send_header("Content-Length", str(len(body))) - self.end_headers() - self.wfile.write(body) - - def _dispatch(self, method: str) -> None: - path = self.path.split("?")[0] - if method == "POST" and path == "/shutdown": - stop.set() - return self._answer(200, {"stopping": True}) - fn = ROUTES.get((method, path)) - if fn is None: - return self._answer(404, {"error": f"no route {method} {path}", - "routes": [f"{m} {p}" for m, p in ROUTES]}) - try: - n = int(self.headers.get("Content-Length") or 0) - body = json.loads(self.rfile.read(n) or b"{}") if n else {} - except ValueError: - return self._answer(400, {"error": "body is not JSON"}) - box = queue.Queue() - jobs.put((fn, body, box)) - try: - self._answer(200, box.get(timeout=timeout_s)) - except queue.Empty: - self._answer(504, {"error": "timed out waiting for NIS"}) - - def do_GET(self): - self._dispatch("GET") - - def do_POST(self): - self._dispatch("POST") - - def log_message(self, *args): # keep the JOBS log readable - pass - - return Handler - - -def serve(bridge: Bridge, port: int = PORT, should_abort=lambda: False, - stop: threading.Event | None = None, on_ready=None, - idle_stop_s: float | None = None) -> None: - """Serve until /shutdown, should_abort() or `stop` is set, or until no - request has arrived for idle_stop_s (default IDLE_STOP_S). NIS calls run - here, on the calling thread; HTTP requests are handled on others.""" - idle_stop_s = IDLE_STOP_S if idle_stop_s is None else idle_stop_s - last_request = time.time() - jobs = queue.Queue() - stop = stop or threading.Event() - # On Windows SO_REUSEADDR (the default here) lets a second bridge bind the - # same port, so re-running the job started a duplicate whose shutdown had - # to be sent twice (seen 2026-10-15). Without it a second run fails to bind. - http.server.ThreadingHTTPServer.allow_reuse_address = False - srv = http.server.ThreadingHTTPServer(("127.0.0.1", port), make_handler(jobs, stop)) - threading.Thread(target=srv.serve_forever, daemon=True).start() - print(f"NIS bridge v{VERSION} listening on 127.0.0.1:{srv.server_address[1]}, pid {os.getpid()}") - if on_ready: - on_ready(srv.server_address[1]) - try: - while not stop.is_set() and not should_abort(): - try: - fn, body, box = jobs.get(timeout=0.2) - except queue.Empty: - if time.time() - last_request > idle_stop_s: - print(f"NIS bridge idle for {idle_stop_s:.0f} s - stopping") - break - continue - try: - box.put(fn(bridge, body)) - except Exception as e: - box.put({"error": f"{type(e).__name__}: {e}"}) - last_request = time.time() - finally: - srv.shutdown() - srv.server_close() - print("NIS bridge stopped") - - -def run(imgs: "tuple[limjob.Image]", Job: "limjob.JobParam", macro: "limjob.MacroParam", - ctx: "limjob.RunContext"): - """JOBS entry point. Serving on the job's own thread froze NIS (step 0 of - docs/nis-bridge.md, 2026-10-15): a Python task runs on NIS's main thread, - so a loop that never returns blocks the UI. So serve on a worker thread - and return at once; the job shows as finished while the bridge keeps - listening. Stop it with POST /shutdown (or the idle backstop). Whether - NIS macro calls work from a non-main thread is UNVERIFIED: try status - first, then the moves. The hints are the JOBS template's own, as strings - so this file imports off NIS.""" - threading.Thread(target=serve, args=(Bridge(Macro()),), name="nis-bridge", - daemon=True).start() diff --git a/acquisition/nis_events.py b/acquisition/nis_events.py deleted file mode 100644 index db939ee..0000000 --- a/acquisition/nis_events.py +++ /dev/null @@ -1,100 +0,0 @@ -# nis_events.py -# ------------------------------------------------------------ -# The NIS event log: one JSON line per thing done through the NIS bridge, -# appended to logs/nis/events-YYYY-MM-DD.jsonl. Whoever drives the bridge -# (the NIS MCP server, a script, the command line) writes here, and -# acquisition/nis_monitor.py tails the file, so the monitor shows what -# Claude is doing from another process. -# -# One action is logged as a "start" line, then one closing line: "ok", or -# "failed" (the bridge refused it or NIS reported an error), "refused" (the -# client's e-stop check stopped it before anything was sent) or "error" -# (the bridge was not reachable). The start line is what lets the monitor -# say "nd_run has been running for 42 s" while the bridge is busy. -# -# Logging must never get in the way of the microscope, so a failed write -# is swallowed. -# ------------------------------------------------------------ - -from __future__ import annotations - -import datetime -import json -from pathlib import Path - -from acquisition import paths - -PHASES = ("start", "ok", "failed", "refused", "error") - - -def events_dir() -> Path: - return paths.logs_dir() / "nis" - - -def events_path(day: datetime.date | None = None) -> Path: - day = day or datetime.date.today() - return events_dir() / f"events-{day.isoformat()}.jsonl" - - -def record(action: str, phase: str, **fields) -> dict: - """Append one event and return it. Never raises.""" - event = {"ts": datetime.datetime.now().isoformat(timespec="milliseconds"), - "action": action, "phase": phase, **fields} - try: - path = events_path() - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as f: - f.write(json.dumps(event, ensure_ascii=False) + "\n") - except OSError: - pass - return event - - -def read_from(path: Path, offset: int = 0) -> tuple[list[dict], int]: - """Events appended to `path` after byte `offset`, and the new offset. - A half-written last line is left for the next call; a missing file is - an empty log.""" - try: - with path.open("rb") as f: - f.seek(offset) - data = f.read() - except OSError: - return [], offset - end = data.rfind(b"\n") + 1 - events = [] - for line in data[:end].splitlines(): - try: - events.append(json.loads(line)) - except ValueError: - continue - return events, offset + end - - -def summarize(event: dict) -> str: - """One short line of detail for an event, for the monitor.""" - p, r = event.get("params") or {}, event.get("result") or {} - action, phase = event.get("action"), event.get("phase") - if phase == "start": - return " ".join(f"{k}={v}" for k, v in p.items()) - if phase in ("refused", "error"): - return str(event.get("message", "")) - if phase == "failed": - return str(r.get("error", r)) - took = f" ({event['elapsed_s']} s)" if "elapsed_s" in event else "" - if action == "move": - return f"{_xy(r.get('before_um'))} -> {_xy(r.get('after_um'))}{took}" - if action == "objective": - return (f"{r.get('before')} -> {r.get('after')}, arrived={r.get('arrived')}" - f", nosepiece {r.get('nosepiece_before')}->{r.get('nosepiece_after')}{took}") - if action == "capture": - return f"saved={r.get('saved')} {r.get('path', '')}{took}" - if action == "nd_run": - return f"nd_running={r.get('nd_running')}{took}" - return took.strip() - - -def _xy(xy) -> str: - try: - return f"({xy[0]:.1f}, {xy[1]:.1f})" - except (TypeError, IndexError, ValueError): - return "?" diff --git a/acquisition/nis_monitor.py b/acquisition/nis_monitor.py deleted file mode 100644 index 29afb69..0000000 --- a/acquisition/nis_monitor.py +++ /dev/null @@ -1,197 +0,0 @@ -# nis_monitor.py -# ------------------------------------------------------------ -# Live terminal view of the NIS bridge. Run it in its own window: -# -# python -m acquisition.nis_monitor # refresh every 1 s, Ctrl+C to leave -# python -m acquisition.nis_monitor --once # print one snapshot and exit -# -# It shows the stage, objective, ND state and e-stop (polled from the bridge's -# /status) above a scrolling list of what was done through the bridge (the NIS -# event log, acquisition/nis_events.py). It only reads: it never moves -# anything, and it does not log its own status polls. -# -# It also opens by itself in its own console window when the NIS MCP server -# starts (launch(), same pattern as the STOP panel) - you should not have to -# remember it. One window only: a named mutex stops a second copy. -# CONFOCAL_NO_NIS_MONITOR=1 turns the automatic launch off. -# -# While the bridge is busy with one long NIS call (an ND run or a capture -# blocks the bridge's single worker) /status cannot answer, so the monitor -# says so and names the action it is waiting on, from the event log. -# ------------------------------------------------------------ - -from __future__ import annotations - -import argparse -import datetime -import json -import os -import shutil -import subprocess -import sys -import time -import urllib.error -import urllib.request - -from acquisition import estop, nis_events -from acquisition.backends.nis_bridge import DEFAULT_URL - -ON_WINDOWS = sys.platform == "win32" -MONITOR_MUTEX = r"Local\confocal-mcp-nis-monitor" -STATUS_TIMEOUT_S = 2.0 -EVENTS_KEPT = 200 - -RESET, DIM, RED, GREEN, YELLOW = "\x1b[0m", "\x1b[2m", "\x1b[31m", "\x1b[32m", "\x1b[33m" -PHASE_COLOUR = {"start": DIM, "ok": GREEN, "failed": RED, "refused": RED, "error": RED} - - -def monitor_running() -> bool: - """True if a monitor window is already open (Windows only).""" - if sys.platform != "win32": - return False - import ctypes - k32 = ctypes.windll.kernel32 - h = k32.OpenMutexW(0x00100000, False, MONITOR_MUTEX) # SYNCHRONIZE - if h: - k32.CloseHandle(h) - return True - return False - - -def launch() -> None: - """Open the monitor in a new console window unless one is already open. - - Called when the NIS MCP server starts. Detached, so the window outlives - the server; failures go to stderr (stdout is the MCP JSON-RPC channel) - and never stop the caller. - """ - if os.environ.get("CONFOCAL_NO_NIS_MONITOR") or not ON_WINDOWS: - return - try: - if monitor_running(): - return - subprocess.Popen([sys.executable, "-m", "acquisition.nis_monitor"], - stdin=subprocess.DEVNULL, stdout=None, stderr=None, - creationflags=getattr(subprocess, "CREATE_NEW_CONSOLE", 0)) - except Exception as exc: - print(f"[nis_monitor] could not open the monitor window ({exc}). " - f"Start it with: python -m acquisition.nis_monitor", file=sys.stderr) - - -def _hold_mutex(): - """Take the single-instance mutex for this process's life; None if - another monitor already holds it. Windows only.""" - if sys.platform != "win32": - return True - import ctypes - h = ctypes.windll.kernel32.CreateMutexW(None, False, MONITOR_MUTEX) - if ctypes.windll.kernel32.GetLastError() == 183: # ERROR_ALREADY_EXISTS - return None - return h - - -def fetch_status(url: str) -> tuple[str, dict | None]: - """("up", status) / ("busy", None) when the bridge accepts the connection - but does not answer in time / ("down", None) when nothing is listening.""" - try: - with urllib.request.urlopen(url + "/status", timeout=STATUS_TIMEOUT_S) as r: - return "up", json.loads(r.read()) - except TimeoutError: - # urllib lets only a timeout while *reading* the answer through bare: - # the connection was made and NIS did not answer. (A connect that - # times out - Windows retries a closed port for seconds - arrives - # wrapped in URLError, below.) - return "busy", None - except (OSError, ValueError): - return "down", None - - -def pending(events: list[dict]) -> dict | None: - """The latest action that has a "start" line and no closing line yet.""" - open_starts: dict[str, dict] = {} - for e in events: - if e.get("phase") == "start": - open_starts[e["action"]] = e - else: - open_starts.pop(e["action"], None) - return max(open_starts.values(), key=lambda e: e["ts"], default=None) - - -def _short_objective(name: str | None) -> str: - return (name or "?").replace("PLAN APO ", "").replace("λD ", "") - - -def render(link: str, status: dict | None, events: list[dict], estop_text: str, - now: datetime.datetime, width: int = 100, rows: int = 20, - colour: bool = True) -> str: - c = (lambda code, s: f"{code}{s}{RESET}") if colour else (lambda code, s: s) - lines = [c(DIM, "NIS monitor ") + now.strftime("%Y-%m-%d %H:%M:%S")] - bridge = {"up": c(GREEN, "UP"), "down": c(RED, "DOWN (job not running in NIS?)"), - "busy": c(YELLOW, "BUSY (NIS is inside one long call)")}[link] - estop_part = c(RED, estop_text) if estop.is_engaged() else c(GREEN, estop_text) - lines.append(f"bridge: {bridge} e-stop: {estop_part}") - if status: - x, y = status.get("xy_um", [float("nan")] * 2) - lines.append(f"XY {x:.1f}, {y:.1f} um Z {status.get('z_um', float('nan')):.2f} um " - f"objective {_short_objective(status.get('current_objective'))} " - f"[nosepiece {status.get('nosepiece_position')}] " - f"ND run: {'RUNNING' if status.get('nd_running') else 'idle'}") - wait = pending(events) - if wait: - since = datetime.datetime.fromisoformat(wait["ts"]) - secs = max(0, int((now - since).total_seconds())) - detail = nis_events.summarize(wait) - lines.append(c(YELLOW, f"now: {wait['action']} {detail} - {secs} s so far")) - lines.append(c(DIM, "-" * min(width, 100))) - for e in events[-rows:]: - phase = e.get("phase", "?") - stamp = e.get("ts", "")[11:19] - text = f"{stamp} {e.get('action', '?'):<10} {c(PHASE_COLOUR.get(phase, ''), f'{phase:<7}')} " - body = nis_events.summarize(e) - room = max(10, width - len(stamp) - 22) - lines.append(text + (body if len(body) <= room else body[:room - 1] + "…")) - if not events: - lines.append(c(DIM, "(no NIS actions logged today yet)")) - return "\n".join(lines) - - -def main() -> None: - ap = argparse.ArgumentParser(description="Live terminal view of the NIS bridge.") - ap.add_argument("--url", default=os.environ.get("CONFOCAL_NIS_BRIDGE_URL", DEFAULT_URL)) - ap.add_argument("--interval", type=float, default=1.0, help="seconds between refreshes") - ap.add_argument("--once", action="store_true", help="print one snapshot and exit") - a = ap.parse_args() - held = None if a.once else _hold_mutex() # kept for the life of the process - if not a.once and held is None: - raise SystemExit("A NIS monitor is already open.") - url = a.url.rstrip("/") - - sys.stdout.reconfigure(encoding="utf-8", errors="replace") - os.system("") # lets a Windows console read ANSI codes - events: list[dict] = [] - path, offset = nis_events.events_path(), 0 - try: - while True: - today = nis_events.events_path() - if today != path: # past midnight: start the new day's file - path, offset = today, 0 - new, offset = nis_events.read_from(path, offset) - events = (events + new)[-EVENTS_KEPT:] - link, status = fetch_status(url) - estop_text = "ENGAGED" if estop.is_engaged() else "clear" - size = shutil.get_terminal_size((100, 30)) - frame = render(link, status, events, estop_text, datetime.datetime.now(), - width=size.columns, rows=max(5, size.lines - 7), - colour=sys.stdout.isatty()) - if a.once: - print(frame) - return - sys.stdout.write("\x1b[H\x1b[2J" + frame + "\n") - sys.stdout.flush() - time.sleep(a.interval) - except KeyboardInterrupt: - pass - - -if __name__ == "__main__": - main() diff --git a/acquisition/orchestration/stage_positions.py b/acquisition/orchestration/stage_positions.py index c62871f..e38464b 100644 --- a/acquisition/orchestration/stage_positions.py +++ b/acquisition/orchestration/stage_positions.py @@ -38,7 +38,7 @@ except ImportError: from acquisition.backends.nis_mock import MockNIS nis = MockNIS() - # stderr, not stdout - this module is imported (via loop_tools.py) by mcp_server/server_loop.py, + # stderr, not stdout - this module is imported (via baumer_ti2_tools.py) by mcp_server/baumer_ti2/baumer_ti2_server.py, # whose stdout is the MCP stdio JSON-RPC channel; anything else written # there corrupts the protocol stream. print( diff --git a/docs/mcp_harness.md b/docs/mcp_harness.md index 66b28ba..33fa7c6 100644 --- a/docs/mcp_harness.md +++ b/docs/mcp_harness.md @@ -12,7 +12,7 @@ tools with Claude: | | `harness/agent.py` ("Plan B") | `harness/mcp_agent.py` ("Plan A", this doc) | |---|---|---| -| How it calls the tools | Imports `mcp_server/loop_tools.py`'s functions directly, in-process | Talks real MCP protocol to `mcp_server/server_loop.py`, running as a **separate subprocess** | +| How it calls the tools | Imports `mcp_server/baumer_ti2/baumer_ti2_tools.py`'s functions directly, in-process | Talks real MCP protocol to `mcp_server/baumer_ti2/baumer_ti2_server.py`, running as a **separate subprocess** | | Needs the `mcp` SDK client | No | Yes (`mcp.client`) | | Works if the harness and the microscope server run on different machines | No | Yes (with a different transport than stdio - see below) | | Exercises the same server Claude Desktop/Code connect to | No | Yes | @@ -22,7 +22,7 @@ Neither is "the real one" - they're both real, tested implementations, kept side by side on purpose. Pick `agent.py` when you just want the simplest thing that works on one machine. Pick `mcp_agent.py` when you specifically want the MCP protocol boundary - e.g. testing -`server_loop.py` itself, or a future setup where the harness and the +`baumer_ti2_server.py` itself, or a future setup where the harness and the microscope PC aren't the same machine. ## What MCP actually is, briefly @@ -34,16 +34,16 @@ about how you talk to an LLM - that's a completely separate concern. Concretely, in this repo: ``` -harness/mcp_agent.py mcp_server/server_loop.py +harness/mcp_agent.py mcp_server/baumer_ti2/baumer_ti2_server.py (MCP client) <--- stdio ---> (MCP server) | | - | +-- loop_tools.get_image - talks to Claude +-- loop_tools.get_pos - (Anthropic API, +-- loop_tools.move - unrelated to MCP) +-- loop_tools.get_move_history + | +-- baumer_ti2_tools.get_image + talks to Claude +-- baumer_ti2_tools.get_pos + (Anthropic API, +-- baumer_ti2_tools.move + unrelated to MCP) +-- baumer_ti2_tools.get_move_history ``` -`mcp_agent.py` spawns `python -m mcp_server.server_loop` as a child +`mcp_agent.py` spawns `python -m mcp_server.baumer_ti2.baumer_ti2_server` as a child process and exchanges newline-delimited JSON-RPC messages with it over that process's stdin/stdout - the exact same mechanism Claude Desktop/Code use when you configure this project as an MCP server for @@ -75,7 +75,7 @@ implement the same way. The current, correct pattern is the unified from mcp.client import Client from mcp.client.stdio import stdio_client, StdioServerParameters -params = StdioServerParameters(command=sys.executable, args=["-m", "mcp_server.server_loop"]) +params = StdioServerParameters(command=sys.executable, args=["-m", "mcp_server.baumer_ti2.baumer_ti2_server"]) async with Client(stdio_client(params)) as client: print(client.protocol_version) # "2026-07-28" tools = await client.list_tools() @@ -111,7 +111,7 @@ loop has no such dependency. ## The real-hardware approval gate -`loop_tools.get_image()`/`move()` (in `mcp_server/loop_tools.py`) gate +`baumer_ti2_tools.get_image()`/`move()` (in `mcp_server/baumer_ti2/baumer_ti2_tools.py`) gate any real-hardware action behind a `confirm=True` parameter, on the assumption that whatever is calling them already obtained a human's approval. That assumption is true when the caller is Claude @@ -123,7 +123,7 @@ So this file does two things together, and both matter: 1. **`_strip_confirm()`** removes the `"confirm"` property from every tool's `input_schema` before it's shown to Claude - verified directly - against `server_loop.py`'s real `list_tools()` output (see + against `baumer_ti2_server.py`'s real `list_tools()` output (see `_mcp_tools_to_anthropic_tools`'s docstring), not assumed. Claude literally cannot request `confirm=True`; the field doesn't exist in the tool definition it sees. @@ -165,7 +165,7 @@ MCP tool results (`CallToolResult.content`) are typed content blocks - |---|---| | `TextContent(text=...)` | `{"type": "text", "text": ...}` | | `ImageContent(data=..., mime_type=...)` | `{"type": "image", "source": {"type": "base64", "media_type": mime_type, "data": data}}` | -| anything else (audio, resource links, ...) | a text block noting the unsupported type - `loop_tools.py`'s 5 tools never actually produce these, so this is a defensive fallback, not a real code path | +| anything else (audio, resource links, ...) | a text block noting the unsupported type - `baumer_ti2_tools.py`'s 5 tools never actually produce these, so this is a defensive fallback, not a real code path | Conveniently, MCP's `Tool.input_schema` is already plain JSON Schema in the same shape Anthropic's tool `input_schema` expects, so @@ -177,7 +177,7 @@ translation. Building this harness surfaced a real, pre-existing bug: `acquisition/backends/nis_mock.py`'s `XY_Move`/`Z_Move` used a plain -`print(...)` (stdout) to log simulated moves. When `server_loop.py` runs +`print(...)` (stdout) to log simulated moves. When `baumer_ti2_server.py` runs as an MCP stdio server, **stdout is the JSON-RPC channel** - `stage_positions.py` already documented this exact constraint for its own startup message, but `nis_mock.py`'s move logging never followed diff --git a/docs/nis-bridge.md b/docs/nis-bridge.md deleted file mode 100644 index af4a46c..0000000 --- a/docs/nis-bridge.md +++ /dev/null @@ -1,153 +0,0 @@ -# NIS bridge: driving the microscope through NIS-Elements - -The rest of this repo reaches the hardware directly: the Ti2 stand through -its ActiveX SDK and the Baumer camera through GenICam. Some things only -NIS-Elements can do, above all the AX confocal lasers and the ND -experiments set up in its ND Acquisition window. The NIS bridge makes -those available to our code and to an MCP client. - -**Status: built and tested off the microscope, not yet run inside NIS.** -The test plan below is what still has to pass on the scope. Driving -capture through NIS reverses an earlier team decision (see the header of -`mcp_server/loop_tools.py`), so it also needs sign-off before it is used -for real work. - -## How it fits together - -``` -MCP client (Claude) - │ stdio - ▼ -mcp_server/server_nis.py confirm gate, capture-folder rule, estop tool - │ -acquisition/backends/nis_bridge.py e-stop checked before sending - │ HTTP, 127.0.0.1:8766 - ▼ -acquisition/nis_bridge/bridge_job.py JOBS Python task, runs inside nis_ar.exe - │ ctypes - ▼ -g5_regprocs.dll (NIS macro functions: StgMoveXY, Stg_SetNosepiecePosition, Capture, ND_RunExperiment, ...) -``` - -The MCP server stays in this repo's environment. Only `bridge_job.py` -runs inside NIS, and it needs nothing beyond the Python standard library, -so nothing has to be installed into NIS's own Python. If our code fails, -NIS keeps running. - -`server_loop.py` and its tools are unchanged. The NIS tools are a -separate server, `confocal-mcp-nis`. - -## What was already verified (2026-09-29) - -- A JOBS Python task runs inside `nis_ar.exe` itself and can bind a port - that another process on the PC reaches (`nis_port_probe.py`). -- `g5_regprocs.dll` exports the macro functions by name. NIS's own - `limpy.macro` calls `WaitText` this way. Signatures come from the macro - reference in `C:\Program Files\NIS-Elements\Docs\nis\eng_ar`. - -## Setting up the bridge in NIS - -1. **Start conditions.** The Ti2 controller is on, NIS-Elements was started - after it, and the e-stop is clear (`python -m acquisition.estop status`). -2. In NIS, open **JOBS** and create a job with one **Python** task. -3. Replace the task's code with the whole of - `acquisition/nis_bridge/bridge_job.py`, then save the job, for example - as `NIS bridge`. -4. Run the job. Its log shows - `NIS bridge v1 listening on 127.0.0.1:8766, pid `. -5. Stop it with `python -m acquisition.backends.nis_bridge shutdown`. - **Do not use the JOBS Abort button**: a Python task cannot be interrupted - by it and NIS freezes (seen 2026-10-14; `limjob.RunContext` has no abort - flag). The job also ends by itself after 4 h with no request. - -## Live monitor - -`python -m acquisition.nis_monitor` in a second terminal shows the bridge -state (stage, Z, objective, ND run, e-stop) above a scrolling list of every -action sent through the bridge, from any process, so you can watch what -Claude does. Actions are logged to `logs/nis/events-.jsonl` as a -`start` line and then `ok`, `failed`, `refused` or `error`. While one long -call (an ND run, a capture) holds the bridge, the monitor shows BUSY and -names the action and how long it has run. Use it while working through the -test plan below. - -## Test plan for the microscope - -Run each step from a terminal in the repo (`.venv\Scripts\python -m -acquisition.backends.nis_bridge ...`). Write down the output. Stop at the -first surprise. Press the STOP panel if anything moves unexpectedly. - -| # | Step | Command | Pass if | -|---|------|---------|---------| -| 0 | NIS usable while the job runs | click around NIS for 30 s | NIS does not freeze. **If it does, stop here**: JOBS runs Python on the main thread, and the bridge needs a different host. | -| 1 | Read-only status | `status` | `xy_um` and `z_um` match the Ti2 Pad (Z ≈ 4600, not 1.0). `nosepiece_objectives` lists the turret. **Note whether position 1 is the 4×**, i.e. whether the index is 0- or 1-based. | -| 2 | Small move | `move 100 0`, then `move -100 0` | `after_um` changes by +100 then −100 in X, and the Ti2 Pad shows the same. The sign of X on the image is recorded. | -| 3 | Move cap | `move 1500 0` | Refused, and nothing moves. | -| 4 | E-stop | `python -m acquisition.estop engage`, then `move 10 0`, then release | Refused by the client. Then send the same move with `curl -X POST -d "{\"dx\":10}" http://127.0.0.1:8766/move` and check the bridge refuses it too. | -| 5 | Objective | `objective ""`, then back to the 4× | **Does the nosepiece physically turn?** `nosepiece_before/after` go 1 → 2 → 1, and NIS's objective display follows. If only the calibration changes, the bridge needs a nosepiece call instead. | -| 6 | Capture | `capture D:\QurratulAin_ConfocalOrchestratorProject\CelegansAML-18\bridge_check_01.nd2` | The file exists and opens with GFP/RFP/TD (check with `python -m analysis.aml18_survey `). No stray image window is left open in NIS. | -| 7 | Saved ND experiment | In ND Acquisition, set a **2-loop, 1-minute** time-lapse with Save to File and **Save** it as `bridge test`. Then `nd-run "bridge test"`. | The run starts and the file appears. **Record `call_returned_after_s`**: ~0 means the call returns at once, ~60 means it blocks until the run ends. | -| 8 | Status during a run | during step 7, from a second terminal: `status` | Answers with `nd_running: true`, or hangs until the run ends (the blocking case from step 7). | -| 9 | Finish early | run `bridge test` with more loops, then `nd-finish` | The run ends after the current loop, and the file keeps the frames so far. | -| 10 | Shutdown | `shutdown` | The job ends by itself, and `status` then reports the bridge unreachable. | -| 11 | MCP | Add `confocal-mcp-nis` to the MCP client config and ask for `nis_status` | Same answer as step 1. Motion tools refuse without `confirm=True`. | - -If steps 7–8 show that `ND_RunExperiment` blocks, the bridge can still run -experiments, but nothing else can be asked while one is in progress. The -fix is to start runs in a way that returns at once. Record the result -before changing anything. - -## Results on the microscope (2026-10-13) - -- Steps 0-4 and 11 passed. The nosepiece index is **0-based** (4x is 0). -- **Step 5 failed with the first design.** `ChangeObjective` only switches NIS's - calibration label; the turret did not move (Ti2 SDK still read position 1). - `Stg_SetNosepiecePosition` alone turns the turret but leaves NIS's objective - name and calibration on the old objective (2026-10-14), so the bridge now - turns the turret, waits for it, then calls `ChangeObjective`, and reports - `arrived` once position and name both match. **Re-run step 5 with the new job.** -- Steps 6-10 not run yet. - -## Results on the microscope (2026-10-15) - -- **Step 0 failed.** With the first design NIS did not respond while the job - ran. A JOBS Python task runs on NIS's main thread, and the serving loop - never returned. JOBS has no background option (the Python task has no - options besides its code; `ctx` is "currently not implemented"), and - NIS exposes no outside automation interface we could find, so the loop - cannot be moved out of NIS by configuration. -- **Change:** `run()` now starts `serve()` on a worker thread and returns, so - the job finishes at once and NIS stays free. **Unverified:** whether NIS - macro calls work from a non-main thread. Re-run the plan from step 0, then - `status` (read-only), then the moves, and stop at the first odd result. - If calls fail or misbehave off the main thread, the fallback is a short job - that handles one queued request per run, started from a JOBS loop or timer. - -## Results on the microscope (2026-10-15, worker-thread bridge) - -- Step 0 passes: NIS stays responsive; the job window closes at once while - the bridge keeps serving on a worker thread. Reads work off the main thread. -- Steps 1-4 pass: `move 100 0` and back (X 137.5 -> 237.5 -> 137.5), a - 1500 um move refused, and the e-stop refused in both the client and, via - `curl`, the bridge. Moves from the worker thread work. -- **Step 5 passes.** Turret turned 4x -> 10x -> 4x (nosepiece 0 -> 1 -> 0), - `arrived: true` each way. NIS's objective display is the blue text in the - bottom status bar and it follows: `PLAN APO lambdaD 4x OFN25 (8.67 um/px @ 512 x 512)` - and `PLAN APO lambdaD 10x OFN25 DIC N1 (1.72 um/px @ 512 x 512)`; the Ti2 Pad - highlights the matching nosepiece slot. **Open question:** 8.67 / 1.72 is - about 5x, not the 2.5x the magnifications imply. Probably the AX scan - field differs per objective, but check it with a capture at each. -- Steps 6-10 not run yet. - -## Safety rules (enforced in code) - -- Motion and acquisition answer **POST** only, so a browser cannot trigger them. -- The **e-stop** is checked in the client and again in the bridge. Ending an - ND run is always allowed. -- XY moves are **relative, at most 1000 µm per axis** per call. **Z is never moved.** -- Objective changes are limited to **4× and 10×**, the long working distances. -- MCP tools that move or acquire need **`confirm=True`**. -- `nis_capture` saves only into the capture folder - (`CONFOCAL_NIS_CAPTURE_DIR`, else `data/NIS/captures`; ND experiments save wherever their "Save to File" path points, use `data/NIS/nd_runs`), by plain file name, - and never overwrites. -- The bridge listens on **127.0.0.1** only. diff --git a/eaa_integration/README.md b/eaa_integration/README.md index 8984814..378d53d 100644 --- a/eaa_integration/README.md +++ b/eaa_integration/README.md @@ -1,7 +1,7 @@ # EAA integration (isolated) This folder wraps the main project's existing, **unmodified** MCP server -(`../mcp_server/server_loop.py`) as a tool inside +(`../mcp_server/baumer_ti2/baumer_ti2_server.py`) as a tool inside [EAA (Experiment Automation Agents)](https://github.com/AdvancedPhotonSource/EAA). Everything EAA-related lives here - its own venv, its own dependencies, @@ -59,8 +59,8 @@ the terminal just runs the process and prints log lines. `--webui` is opt-in specifically so the already-verified terminal flow keeps working unchanged when you don't pass it. -This spawns `../mcp_server/server_loop.py` as a subprocess, using the -**main project's own `.venv`** (not this folder's) - `server_loop.py` +This spawns `../mcp_server/baumer_ti2/baumer_ti2_server.py` as a subprocess, using the +**main project's own `.venv`** (not this folder's) - `baumer_ti2_server.py` needs `mcp`/`PIL`/`harvesters`/`pywin32`, none of which are installed here. Make sure the main project's `.venv` exists and has its dependencies installed first (`../requirements.txt`). @@ -79,9 +79,9 @@ a child-process tree kill + `os._exit()`. Without that, two things bite on Windows: EAA's `MCPTool.__del__` deadlocks in anyio at interpreter shutdown (the process won't close), and the MCP server - launched through the main venv's redirector `python.exe` - gets orphaned, leaving a stray -`server_loop.py` (and its camera/NIS handles) running. If you ever do +`baumer_ti2_server.py` (and its camera/NIS handles) running. If you ever do find a leftover, `taskkill /F /T /IM python.exe` clears it, or kill just -the `server_loop.py` PID from Task Manager. +the `baumer_ti2_server.py` PID from Task Manager. ## Safety: how this differs from `../harness/agent.py` and `../harness/mcp_agent.py` @@ -95,7 +95,7 @@ through this connection - including harmless mock reads like `get_pos`. Every tool call pauses for a `[y/N]` terminal prompt. Simpler, safer by default, but naggier. If that becomes a problem, the fix is a thin proxy MCP server in this same folder that replicates the selective gate -the other two harnesses already use - not a change to `server_loop.py` +the other two harnesses already use - not a change to `baumer_ti2_server.py` itself. The task manager's system prompt also explicitly tells the model to @@ -128,7 +128,7 @@ will fail loudly instead of quietly widening what the model can touch. - `eaa-core==1.0.0` installs cleanly in its own venv, pulling in its own `mcp==1.29.1` with zero conflict with the main project's `mcp==2.0.0`. -- `MCPTool` successfully spawns `server_loop.py` as a real subprocess +- `MCPTool` successfully spawns `baumer_ti2_server.py` as a real subprocess (via the main project's venv) and connects to it. - `ConfocalTaskManager`'s resolved `assistant_system_message` correctly contains EAA's own default prompt **plus** the appended microscope @@ -138,7 +138,7 @@ will fail loudly instead of quietly widening what the model can touch. - **A full live conversation, with a real `OPENAI_API_KEY` and `gpt-4o-mini`, end to end**: the model correctly chose to call `get_pos(backend="mock")`, the approval prompt fired and was - approved, the real MCP call executed against the real `server_loop.py` + approved, the real MCP call executed against the real `baumer_ti2_server.py` subprocess, and the model gave a correct final answer using the real returned data (`x=0.0, y=0.0, z=0.0`, matching the mock stage's actual state). diff --git a/eaa_integration/REMOVAL.md b/eaa_integration/REMOVAL.md index eb6404e..c92f66d 100644 --- a/eaa_integration/REMOVAL.md +++ b/eaa_integration/REMOVAL.md @@ -14,7 +14,7 @@ pulled in only ever lived in `eaa_integration/.venv/`, which this deletes. No package was ever installed into the main project's `.venv/`, and no line inside `eaa_integration/` references anything outside this folder except a read-only path to the main project's -Python executable and `mcp_server/server_loop.py` (never modified). +Python executable and `mcp_server/baumer_ti2/baumer_ti2_server.py` (never modified). ## 2. Revert the two touch points outside this folder @@ -31,7 +31,7 @@ revert independently of each other: integration and are still needed by the rest of the project - leave those alone.) -- **Nothing else.** `mcp_server/server_loop.py`, `mcp_server/loop_tools.py`, +- **Nothing else.** `mcp_server/baumer_ti2/baumer_ti2_server.py`, `mcp_server/baumer_ti2/baumer_ti2_tools.py`, `requirements.txt`, `README.md`, and every other file outside this folder were never modified to build this integration - there is nothing else to revert. diff --git a/eaa_integration/run_session.py b/eaa_integration/run_session.py index c0c5228..58a7213 100644 --- a/eaa_integration/run_session.py +++ b/eaa_integration/run_session.py @@ -5,7 +5,7 @@ # to fully remove this integration later. # # WHAT THIS DOES: wraps the EXISTING, UNMODIFIED microscope MCP server -# (../mcp_server/server_loop.py) as an EAA tool via MCPTool, and starts +# (../mcp_server/baumer_ti2/baumer_ti2_server.py) as an EAA tool via MCPTool, and starts # an EAA BaseTaskManager terminal chat session on top of it. The MCP # server itself is spawned as a subprocess using the MAIN project's own # .venv (it needs mcp/PIL/harvesters/pywin32, none of which are @@ -101,7 +101,7 @@ # 3. The MCP server is spawned through the main project's *virtualenv* # python.exe, a ~270 KB redirector stub that re-execs the real # interpreter as a child. mcp's stdio client only ever signals the -# stub, orphaning the real server_loop.py (and the camera / NIS SDK +# stub, orphaning the real baumer_ti2_server.py (and the camera / NIS SDK # handles it holds). --webui's HTML server subprocess has the same # shape. taskkill /T walks the whole tree before we go. @@ -262,7 +262,7 @@ def main() -> None: "mcpServers": { "confocal": { "command": str(MAIN_VENV_PYTHON), - "args": ["-m", "mcp_server.server_loop"], + "args": ["-m", "mcp_server.baumer_ti2.baumer_ti2_server"], "cwd": str(MAIN_REPO_ROOT), } } diff --git a/harness/agent.py b/harness/agent.py index f38ed7d..a6f21f7 100644 --- a/harness/agent.py +++ b/harness/agent.py @@ -1,11 +1,11 @@ # agent.py # ------------------------------------------------------------ # Minimal interactive harness loop: calls Claude directly (Anthropic -# API), driving mcp_server/loop_tools.py's 4 functions as tools. This is +# API), driving mcp_server/baumer_ti2/baumer_ti2_tools.py's 4 functions as tools. This is # Plan B from the harness design discussion - it does NOT go through -# mcp_server/server_loop.py's MCP/stdio protocol at all. Since this -# module lives in the same codebase as loop_tools.py, it just imports -# and calls those functions directly as plain Python. server_loop.py is +# mcp_server/baumer_ti2/baumer_ti2_server.py's MCP/stdio protocol at all. Since this +# module lives in the same codebase as baumer_ti2_tools.py, it just imports +# and calls those functions directly as plain Python. baumer_ti2_server.py is # untouched and still works independently for Claude Desktop/Code - this # is a second, separate way to drive the same underlying tool functions, # not a replacement. @@ -17,7 +17,7 @@ # real-hardware action (see next paragraph) - and avoiding a beta SDK # dependency for the first version of this loop. # -# WHY "confirm" IS NOT A MODEL-SETTABLE TOOL PARAMETER HERE: loop_tools' +# WHY "confirm" IS NOT A MODEL-SETTABLE TOOL PARAMETER HERE: baumer_ti2_tools' # get_image()/move() gate real hardware behind confirm=True, on the # assumption that whatever's calling them already got a human's # approval - true when the caller is Claude Desktop/Code (their own @@ -33,7 +33,7 @@ # # WHY backend DEFAULTS TO "mock" IN THE SYSTEM PROMPT: real hardware # should be something the model reaches for deliberately, not a default -# it falls into - matches loop_tools.py's own backend="mock" defaults. +# it falls into - matches baumer_ti2_tools.py's own backend="mock" defaults. # # Run (from the repo root, with .venv activated, ANTHROPIC_API_KEY set # in a .env file at the repo root, in the environment, or via @@ -48,7 +48,7 @@ from dotenv import load_dotenv from harness.context import prune_context_images -from mcp_server import loop_tools +from mcp_server.baumer_ti2 import baumer_ti2_tools load_dotenv() # reads .env (repo root, gitignored) into the process environment @@ -223,7 +223,7 @@ def _execute_tool(name: str, tool_input: dict) -> tuple[list[dict], bool]: if not _confirm_real_hardware_action(name, tool_input): return _text_content("User declined this real-hardware capture. Not executed."), True tool_input["confirm"] = True - metadata, image = loop_tools.get_image(**tool_input) + metadata, image = baumer_ti2_tools.get_image(**tool_input) image_content = image.to_image_content() return [ {"type": "text", "text": json.dumps(metadata)}, @@ -238,17 +238,17 @@ def _execute_tool(name: str, tool_input: dict) -> tuple[list[dict], bool]: ], False if name == "get_pos": - return _text_content(json.dumps(loop_tools.get_pos(**tool_input))), False + return _text_content(json.dumps(baumer_ti2_tools.get_pos(**tool_input))), False if name == "move": if tool_input.get("backend", "mock") == "sdk": if not _confirm_real_hardware_action(name, tool_input): return _text_content("User declined this real-hardware move. Not executed."), True tool_input["confirm"] = True - return _text_content(json.dumps(loop_tools.move(**tool_input))), False + return _text_content(json.dumps(baumer_ti2_tools.move(**tool_input))), False if name == "get_move_history": - return _text_content(json.dumps(loop_tools.get_move_history(**tool_input))), False + return _text_content(json.dumps(baumer_ti2_tools.get_move_history(**tool_input))), False return _text_content(f"Unknown tool: {name}"), True except (ValueError, PermissionError, KeyError) as exc: diff --git a/harness/context.py b/harness/context.py index b25a6b0..b073f1a 100644 --- a/harness/context.py +++ b/harness/context.py @@ -86,7 +86,7 @@ def prune_context_images( Does not mutate `messages` or any message dict in it - always returns new message/content lists, so a caller can keep its own full-fidelity history separately (e.g. for logging or the FrameStore - pattern in mcp_server/loop_tools.py's get_frame()) while only + pattern in mcp_server/baumer_ti2/baumer_ti2_tools.py's get_frame()) while only passing the pruned copy to the model. Raises ValueError if either count is negative. diff --git a/harness/mcp_agent.py b/harness/mcp_agent.py index 2666326..674c694 100644 --- a/harness/mcp_agent.py +++ b/harness/mcp_agent.py @@ -2,15 +2,15 @@ # ------------------------------------------------------------ # Interactive harness loop - Plan A: calls Claude directly (Anthropic # API), but drives tools through a REAL MCP client talking to -# mcp_server/server_loop.py as a separate subprocess over stdio, using +# mcp_server/baumer_ti2/baumer_ti2_server.py as a separate subprocess over stdio, using # the official `mcp` SDK (mcp.client.Client). This is the MCP-protocol -# counterpart to harness/agent.py (Plan B, which imports loop_tools.py's +# counterpart to harness/agent.py (Plan B, which imports baumer_ti2_tools.py's # functions directly, in-process, with no MCP involved at all). # # Both harnesses are independent and permanent - neither replaces the # other. Use this one when the harness and the microscope server should # be separate processes (possibly on separate machines) talking real -# MCP, or when you want to exercise server_loop.py itself, the same +# MCP, or when you want to exercise baumer_ti2_server.py itself, the same # server Claude Desktop/Code connect to. Use agent.py when you want the # simplest possible path with no protocol/subprocess overhead. # @@ -34,19 +34,19 @@ # Client can connect to an in-process MCPServer object directly with no # subprocess or protocol framing at all - but that would just be Plan B # again with extra ceremony. The whole point of Plan A is a real client/ -# server boundary: server_loop.py runs as its own process (the same one +# server boundary: baumer_ti2_server.py runs as its own process (the same one # Claude Desktop/Code would launch), reachable over stdio exactly the # way any external MCP client reaches it. # # WHY "confirm" IS STRIPPED FROM EVERY TOOL SCHEMA BEFORE CLAUDE SEES IT, # AND WHY THE HARNESS INJECTS IT ITSELF: identical reasoning to -# agent.py's header comment - loop_tools.get_image()/move() gate real +# agent.py's header comment - baumer_ti2_tools.get_image()/move() gate real # hardware behind confirm=True on the assumption that a human already # approved the call (true inside Claude Desktop/Code, via their own # permission-prompt UI; NOT automatically true here). _strip_confirm() # removes the "confirm" property from every tool's input_schema (it # always carries a default and is never in "required" - verified -# directly against server_loop.py's actual list_tools() output, not +# directly against baumer_ti2_server.py's actual list_tools() output, not # assumed), so the model cannot request it. _confirm_real_hardware_action() # is the harness's own live terminal gate; only on approval does the # harness add "confirm": True to the arguments dict it sends to @@ -85,7 +85,7 @@ SYSTEM_PROMPT = """\ You are an agent operating a Nikon Ti2-E microscope stage and a Baumer \ -camera through an MCP server (mcp_server/server_loop.py), reached via \ +camera through an MCP server (mcp_server/baumer_ti2/baumer_ti2_server.py), reached via \ tools named get_image, get_pos, move, get_move_history. Safety rules: @@ -155,7 +155,7 @@ async def _confirm_real_hardware_action(tool_name: str, tool_input: dict) -> boo def _mcp_content_to_anthropic_content(mcp_content: list) -> list[dict]: """Convert a CallToolResult's content blocks (TextContent/ImageContent/ ...) to Anthropic tool_result content blocks. Only text and image are - handled - loop_tools.py's 5 tools never return audio/resource blocks. + handled - baumer_ti2_tools.py's 5 tools never return audio/resource blocks. """ blocks = [] for block in mcp_content: @@ -241,10 +241,10 @@ async def main() -> None: server_params = StdioServerParameters( command=sys.executable, - args=["-m", "mcp_server.server_loop"], + args=["-m", "mcp_server.baumer_ti2.baumer_ti2_server"], ) - print("Connecting to mcp_server/server_loop.py over MCP (stdio)...") + print("Connecting to mcp_server/baumer_ti2/baumer_ti2_server.py over MCP (stdio)...") async with Client(stdio_client(server_params)) as mcp_client: print(f"Connected - MCP protocol version: {mcp_client.protocol_version}") mcp_tools = (await mcp_client.list_tools()).tools diff --git a/mcp_server/baumer_ti2/__init__.py b/mcp_server/baumer_ti2/__init__.py new file mode 100644 index 0000000..a7668a8 --- /dev/null +++ b/mcp_server/baumer_ti2/__init__.py @@ -0,0 +1,5 @@ +"""MCP server for the Baumer camera and the Ti2 stage (Nikon Ti2 SDK, no NIS-Elements). + +baumer_ti2_server.py registers the tools; baumer_ti2_tools.py implements them. +Run with `baumer-ti2-mcp` or `python -m mcp_server.baumer_ti2.baumer_ti2_server`. +""" diff --git a/mcp_server/server_loop.py b/mcp_server/baumer_ti2/baumer_ti2_server.py similarity index 58% rename from mcp_server/server_loop.py rename to mcp_server/baumer_ti2/baumer_ti2_server.py index 4845bb9..898ee22 100644 --- a/mcp_server/server_loop.py +++ b/mcp_server/baumer_ti2/baumer_ti2_server.py @@ -1,22 +1,23 @@ -# server_loop.py +# baumer_ti2_server.py # ------------------------------------------------------------ -# Minimal MCP server entry point: registers ONLY loop_tools.py's +# Minimal MCP server entry point: registers ONLY baumer_ti2_tools.py's # functions (get_image, get_pos, move, get_move_history, estop) - kept # deliberately minimal, 5 tools total, by explicit team direction. # # Run, either way: -# confocal-mcp (installed console script - see pyproject.toml) -# python -m mcp_server.server_loop (from a source checkout) +# baumer-ti2-mcp (installed console script - see pyproject.toml; +# the old name confocal-mcp still works) +# python -m mcp_server.baumer_ti2.baumer_ti2_server (from a source checkout) # # Point an MCP client at whichever form you use, e.g.: -# { "mcpServers": { "confocal": { "command": "confocal-mcp" } } } +# { "mcpServers": { "baumer-ti2": { "command": "baumer-ti2-mcp" } } } # ------------------------------------------------------------ from mcp.server.mcpserver import MCPServer from acquisition import estop -from mcp_server import loop_tools as tools +from mcp_server.baumer_ti2 import baumer_ti2_tools as tools mcp = MCPServer("ConfocalOrchestrator-Loop") @@ -28,7 +29,7 @@ def main() -> None: - """Console entry point (``confocal-mcp``): serve the 5 tools over stdio.""" + """Console entry point (``baumer-ti2-mcp``): serve the 5 tools over stdio.""" # The STOP panel, on screen for as long as this server runs. estop.launch_panel() mcp.run(transport="stdio") diff --git a/mcp_server/loop_tools.py b/mcp_server/baumer_ti2/baumer_ti2_tools.py similarity index 99% rename from mcp_server/loop_tools.py rename to mcp_server/baumer_ti2/baumer_ti2_tools.py index 6b92ef0..9699b58 100644 --- a/mcp_server/loop_tools.py +++ b/mcp_server/baumer_ti2/baumer_ti2_tools.py @@ -1,4 +1,4 @@ -# loop_tools.py +# baumer_ti2_tools.py # ------------------------------------------------------------ # Minimal MCP surface for the normal agent control loop: # get_image() - capture + the stage position that goes with it @@ -178,7 +178,7 @@ def _require_confirm_for_sdk(backend: str, confirm: bool) -> None: def _get_camera(): """Return the process-wide BaumerGenICam, constructing it on first use. - The import is deferred to here so `import mcp_server.loop_tools` works on a + The import is deferred to here so `import mcp_server.baumer_ti2.baumer_ti2_tools` works on a core-only install (no cv2 / harvesters) - only get_image() actually needs the camera stack. """ @@ -315,7 +315,7 @@ def get_frame(frame_id: int) -> dict: position, stage_revision, timestamps) by the frame_id get_image() returned for it. - NOT registered as an MCP tool (see server_loop.py) - by explicit team + NOT registered as an MCP tool (see baumer_ti2_server.py) - by explicit team direction the chat-facing surface stays at 5 tools. This is a plain importable function for harness/analysis code that needs to resolve "frame 42" to its full-res file and the position it was captured at, @@ -408,7 +408,7 @@ def move_focus(z: float, backend: str = "mock", confirm: bool = False) -> dict: ACTUAL resulting position - same shape/safety pattern as move(), but for Z. - NOT registered as an MCP tool (see server_loop.py) and NOT added to + NOT registered as an MCP tool (see baumer_ti2_server.py) and NOT added to any chat-facing tool list (harness/agent.py, harness/mcp_agent.py) - by explicit design (see this file's header comment on why move() is XY-only), a blind Z move must never be reachable from a chat prompt: diff --git a/mcp_server/nis_tools.py b/mcp_server/nis_tools.py deleted file mode 100644 index 8c68960..0000000 --- a/mcp_server/nis_tools.py +++ /dev/null @@ -1,130 +0,0 @@ -# nis_tools.py -# ------------------------------------------------------------ -# MCP tools that drive the microscope THROUGH NIS-Elements, via the NIS -# bridge (acquisition/nis_bridge/bridge_job.py, running as a JOBS task; -# client in acquisition/backends/nis_bridge.py). Served by their own -# server, mcp_server/server_nis.py - kept apart from loop_tools.py, which -# by team direction has exactly its agreed tools and no NIS-Elements. -# -# WHAT THIS ADDS over loop_tools: things only NIS can do - the AX laser -# acquisition set up in NIS (capture, saved ND experiments) and NIS's own -# objective change. -# -# SAFETY, same shape as loop_tools: -# * every tool that moves or acquires requires confirm=True -# (PermissionError otherwise), exactly like backend="sdk" there -# * the e-stop is checked in the client before a request is sent, and -# again inside NIS by the bridge -# * XY moves are relative and capped at 1 mm; there is no Z tool -# * objective changes are limited to 4x/10x by the bridge -# * captures are written only under the data folder, by file name - a -# chat prompt cannot choose an arbitrary path -# * nis_finish_experiment and estop never need confirm: they only stop -# * a refusal or failure from the bridge raises, so a client never sees it as success -# ------------------------------------------------------------ - -from __future__ import annotations - -import json -import os -import re -from pathlib import Path - -from acquisition.backends.nis_bridge import NISBridge -from acquisition.paths import data_root - - -def _require_confirm(confirm: bool, what: str) -> None: - if not confirm: - raise PermissionError( - f"{what} drives real microscope hardware through NIS-Elements and " - "requires confirm=True. Refusing to proceed without explicit confirmation.") - - -def _bridge() -> NISBridge: - return NISBridge() - - -def _checked(result: dict) -> dict: - """Turn a refused or failed bridge answer into an MCP tool error. - - The bridge reports refusals (move cap, e-stop, bad name, an ND run - already going) as an ordinary answer with an "error" key; returned as - is, an MCP client sees success. A turret that did not arrive and a - capture that left no file are failures too.""" - if "error" in result or result.get("arrived") is False or result.get("saved") is False: - raise RuntimeError("NIS bridge: " + json.dumps(result, ensure_ascii=False)) - return result - - -def capture_dir() -> Path: - """Where nis_capture writes: CONFOCAL_NIS_CAPTURE_DIR, else /data/NIS/captures.""" - d = Path(os.environ.get("CONFOCAL_NIS_CAPTURE_DIR") or data_root() / "data" / "NIS" / "captures") - d.mkdir(parents=True, exist_ok=True) - return d - - -def nis_status() -> dict: - """Read-only snapshot from NIS-Elements: XY and Z position (um), current - objective, the objective at each nosepiece position, whether an ND - experiment is running, and whether the e-stop is engaged. Safe to call - at any time; needs the NIS bridge job to be running.""" - return _bridge().status() - - -def nis_move_relative(dx_um: float, dy_um: float, confirm: bool = False) -> dict: - """Move the XY stage by (dx_um, dy_um) microns RELATIVE to where it is, - through NIS-Elements. At most 1000 um per axis per call. Returns the - position before and after - treat 'after_um' as ground truth. - Requires confirm=True. Z cannot be moved from here.""" - _require_confirm(confirm, "nis_move_relative") - return _checked(_bridge().move_relative(dx_um, dy_um)) - - -def nis_change_objective(name: str, confirm: bool = False) -> dict: - """Switch objective in NIS-Elements. `name` must be the exact name - nis_status lists under nosepiece_objectives, and only 4x or 10x - objectives are accepted (long working distance - they cannot reach - the sample). Returns the objective and nosepiece position before and - after. Requires confirm=True.""" - _require_confirm(confirm, "nis_change_objective") - return _checked(_bridge().change_objective(name)) - - -def nis_list_optical_configs() -> dict: - """Read-only: the names of the optical configurations defined in - NIS-Elements, named "Group:Configuration". There is no tool to select - one: set it in NIS-Elements before nis_capture.""" - return _bridge().optical_configs() - - -_SAFE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9 _.\-]{0,80}$") - - -def nis_capture(filename: str, confirm: bool = False) -> dict: - """Capture one image with the current NIS-Elements acquisition settings - (the optical configuration active in NIS - lasers, channels, scan) and save it as an ND2 file in the NIS capture - folder. `filename` is a plain name such as "aml18_check" - no folders; - ".nd2" is added if missing and an existing file is never overwritten. - Returns the saved path. Requires confirm=True.""" - _require_confirm(confirm, "nis_capture") - stem = filename[:-4] if filename.lower().endswith(".nd2") else filename - if not _SAFE_NAME.match(stem) or ".." in stem: - raise ValueError("filename must be a plain name (letters, digits, space, _ . -), no folders") - return _checked(_bridge().capture(str(capture_dir() / f"{stem}.nd2"))) - - -def nis_run_experiment(experiment: str, confirm: bool = False) -> dict: - """Start an ND experiment that was set up and SAVED in NIS-Elements' - ND Acquisition window, by its saved name. It runs with exactly the - saved settings (time loop, channels, save-to-file path). The call may - not return until the experiment ends. Refused if one is already - running. Requires confirm=True.""" - _require_confirm(confirm, "nis_run_experiment") - return _checked(_bridge().nd_run(experiment)) - - -def nis_finish_experiment() -> dict: - """End the running ND experiment after its current time loop; NIS saves - the frames captured so far. Never needs confirm - it only stops.""" - return _checked(_bridge().nd_finish()) diff --git a/mcp_server/server_nis.py b/mcp_server/server_nis.py deleted file mode 100644 index 05909e2..0000000 --- a/mcp_server/server_nis.py +++ /dev/null @@ -1,40 +0,0 @@ -# server_nis.py -# ------------------------------------------------------------ -# MCP server for driving the microscope through NIS-Elements (see -# nis_tools.py). Separate from server_loop.py on purpose: that server's -# tool set is fixed by team direction and has no NIS-Elements in it, and -# this one needs the NIS bridge job running inside NIS. -# -# Run, either way: -# confocal-mcp-nis (installed console script) -# python -m mcp_server.server_nis (from a source checkout) -# -# { "mcpServers": { "confocal-nis": { "command": "confocal-mcp-nis" } } } -# ------------------------------------------------------------ - -from mcp.server.mcpserver import MCPServer - -from acquisition import estop, nis_monitor -from mcp_server import loop_tools, nis_tools - -mcp = MCPServer("ConfocalOrchestrator-NIS") - -mcp.add_tool(nis_tools.nis_status) -mcp.add_tool(nis_tools.nis_move_relative) -mcp.add_tool(nis_tools.nis_change_objective) -mcp.add_tool(nis_tools.nis_list_optical_configs) -mcp.add_tool(nis_tools.nis_capture) -mcp.add_tool(nis_tools.nis_run_experiment) -mcp.add_tool(nis_tools.nis_finish_experiment) -mcp.add_tool(loop_tools.estop) # the same e-stop, reachable from this server too - - -def main() -> None: - """Console entry point (``confocal-mcp-nis``): serve the NIS tools over stdio.""" - estop.launch_panel() - nis_monitor.launch() # live view of what this server does - mcp.run(transport="stdio") - - -if __name__ == "__main__": - main() diff --git a/pyproject.toml b/pyproject.toml index ddf67b1..8ac2cbd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -69,8 +69,9 @@ all = [ ] [project.scripts] -confocal-mcp = "mcp_server.server_loop:main" -confocal-mcp-nis = "mcp_server.server_nis:main" +baumer-ti2-mcp = "mcp_server.baumer_ti2.baumer_ti2_server:main" +# Old name, kept so existing MCP client configs keep working. +confocal-mcp = "mcp_server.baumer_ti2.baumer_ti2_server:main" [project.urls] Homepage = "https://github.com/BioNanomics/microscope-agent" diff --git a/tests/conftest.py b/tests/conftest.py index f9ed12b..e0e3c29 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,6 +1,6 @@ # Runtime data (captures, history logs) is anchored to CONFOCAL_MCP_DATA_DIR # at *import* time (acquisition/paths.py), so it must be set before any -# test module imports mcp_server.loop_tools or acquisition.backends.nis_mock. +# test module imports mcp_server.baumer_ti2.baumer_ti2_tools or acquisition.backends.nis_mock. import os import tempfile from pathlib import Path diff --git a/tests/test_loop_tools.py b/tests/test_baumer_ti2_tools.py similarity index 99% rename from tests/test_loop_tools.py rename to tests/test_baumer_ti2_tools.py index 776ed5c..6b49e28 100644 --- a/tests/test_loop_tools.py +++ b/tests/test_baumer_ti2_tools.py @@ -7,7 +7,7 @@ from acquisition import estop from acquisition.backends import nis_mock from acquisition.orchestration import stage_positions -from mcp_server import loop_tools as lt +from mcp_server.baumer_ti2 import baumer_ti2_tools as lt from tests.fakes import fake_ti2 # noqa: F401 (fixture) diff --git a/tests/test_loop_tools_mock.py b/tests/test_baumer_ti2_tools_mock.py similarity index 67% rename from tests/test_loop_tools_mock.py rename to tests/test_baumer_ti2_tools_mock.py index 6dc4ea3..294327d 100644 --- a/tests/test_loop_tools_mock.py +++ b/tests/test_baumer_ti2_tools_mock.py @@ -4,32 +4,32 @@ import pytest from acquisition.backends import nis_mock -from mcp_server import loop_tools +from mcp_server.baumer_ti2 import baumer_ti2_tools def test_get_image_sdk_default_requires_confirm(): with pytest.raises(PermissionError): - loop_tools.get_image() + baumer_ti2_tools.get_image() def test_get_image_mock_returns_metadata_and_preview(write_frame, monkeypatch): frame = write_frame("sample.png") monkeypatch.setattr(nis_mock, "SAMPLE_FRAME_PATH", frame) - metadata, preview = loop_tools.get_image(backend="mock", max_dimension=64) + metadata, preview = baumer_ti2_tools.get_image(backend="mock", max_dimension=64) assert metadata["backend"] == "mock" assert Path(metadata["image"]).exists() assert Path(metadata["image"]).resolve().is_relative_to(Path(os.environ["CONFOCAL_MCP_DATA_DIR"]).resolve()) assert set(metadata["position"]) == {"x", "y", "z"} assert metadata["frame_id"] >= 1 assert preview.to_image_content().mime_type == "image/jpeg" - assert loop_tools.get_frame(metadata["frame_id"])["image"] == metadata["image"] + assert baumer_ti2_tools.get_frame(metadata["frame_id"])["image"] == metadata["image"] def test_get_image_mock_rejects_bad_crop(): with pytest.raises(ValueError): - loop_tools.get_image(backend="mock", crop={"x": 0.8, "y": 0.0, "width": 0.5, "height": 0.5}) + baumer_ti2_tools.get_image(backend="mock", crop={"x": 0.8, "y": 0.0, "width": 0.5, "height": 0.5}) def test_get_image_unknown_backend(): with pytest.raises(ValueError): - loop_tools.get_image(backend="nope") + baumer_ti2_tools.get_image(backend="nope") diff --git a/tests/test_calibration.py b/tests/test_calibration.py index cc1735b..53b8145 100644 --- a/tests/test_calibration.py +++ b/tests/test_calibration.py @@ -1,19 +1,10 @@ -import ctypes -import http.server import json import sys -import threading -import time -import types -import urllib.request -from types import SimpleNamespace as NS import pytest -from acquisition import estop from acquisition.calibration import ti2_config, ti2_inventory from tests.fakes import fake_ti2 # noqa: F401 (fixture) -from tests.test_nis_bridge import FakeNIS def make_setting(name, control, value=1, lower=0, higher=10, unit="u", enabled=True, long_name=None): @@ -227,78 +218,3 @@ def test_config_cli_default_output_path(scope, tmp_path, monkeypatch, capsys): monkeypatch.chdir(tmp_path) run_main(monkeypatch, "save") assert list((tmp_path / "protocols").glob("optical_config_*.json")) - - -# ---- nis_port_probe (runs inside NIS; here against the fake DLL) ----------------- - -@pytest.fixture -def probe(monkeypatch, tmp_path): - dll = FakeNIS() - limjob = types.ModuleType("limjob") # NIS's job API; the probe annotates with its types - limjob.Image = limjob.JobParam = limjob.MacroParam = limjob.RunContext = object - monkeypatch.setitem(sys.modules, "limjob", limjob) - monkeypatch.setattr(ctypes, "cdll", NS(g5_regprocs=dll), raising=False) - sys.modules.pop("acquisition.calibration.nis_port_probe", None) - import importlib - mod = importlib.import_module("acquisition.calibration.nis_port_probe") - monkeypatch.setattr(mod, "ESTOP", str(tmp_path / "ESTOP")) - yield mod, dll - sys.modules.pop("acquisition.calibration.nis_port_probe", None) - - -def test_probe_status(probe): - mod, dll = probe - s = mod.status() - assert s["xy_um"] == [100.0, 200.0] and s["z_um"] == 4619.0 and s["nosepiece_position"] == 1 - assert s["nosepiece_objectives"] == {i: n for i, n in dll.objectives.items()} - - -def test_probe_move_is_capped_and_blocked_by_estop(probe, tmp_path): - mod, dll = probe - r = mod.move(50, -20) - assert r["after_um"] == [150.0, 180.0] - assert "refused" in mod.move(1000.1, 0)["error"] - (tmp_path / "ESTOP").write_text("{}") - assert "e-stop" in mod.move(1, 0)["error"] and "e-stop" in mod.objective("Plan Fluor 10x Ph1 DLL")["error"] - - -def test_probe_objective_allow_list(probe): - mod, dll = probe - assert "allowed" in mod.objective("Plan Apo 60x Oil")["error"] - r = mod.objective("Plan Fluor 10x Ph1 DLL") - assert r["after"] == "Plan Fluor 10x Ph1 DLL" and r["rc"] == 1 - - -def test_probe_serves_the_three_endpoints_from_run(probe, monkeypatch, tmp_path): - mod, dll = probe - servers = [] - - class Rec(http.server.ThreadingHTTPServer): - def __init__(self, *a, **k): - super().__init__(("127.0.0.1", 0), a[1]) - servers.append(self) - - monkeypatch.setattr(mod.http.server, "ThreadingHTTPServer", Rec) - done = threading.Event() - ctx = NS(shouldAbort=lambda: done.is_set()) - t = threading.Thread(target=mod.run, args=((), None, None, ctx), daemon=True) - t.start() - deadline = time.time() + 5 - while not servers and time.time() < deadline: - time.sleep(0.01) - assert servers, "the probe never started its server" - base = f"http://127.0.0.1:{servers[0].server_address[1]}" - - def get(path): - with urllib.request.urlopen(base + path, timeout=5) as r: - return json.loads(r.read()) - - assert get("/status")["xy_um"] == [100.0, 200.0] - assert get("/move?dx=10&dy=0")["after_um"][0] == 110.0 - assert "allowed" in get("/objective?name=Plan%20Apo%2060x%20Oil")["error"] - assert "use /status" in get("/nothing")["error"] - dll.StgGetPosXY = lambda *a: (_ for _ in ()).throw(RuntimeError("dll fell over")) - assert "RuntimeError" in get("/status")["error"] # a failing call is reported, not fatal - done.set() - t.join(5) - assert not t.is_alive() diff --git a/tests/test_estop.py b/tests/test_estop.py index 526f0cf..62f1984 100644 --- a/tests/test_estop.py +++ b/tests/test_estop.py @@ -62,7 +62,10 @@ def test_panel_not_running_off_windows(monkeypatch): def test_launch_panel_opt_out_and_already_running(monkeypatch): opened = [] monkeypatch.setattr(estop.subprocess, "Popen", lambda *a, **k: opened.append(a)) - monkeypatch.setenv("CONFOCAL_NO_ESTOP_PANEL", "1") + monkeypatch.setenv("NIS_NO_ESTOP_PANEL", "1") + estop.launch_panel() + monkeypatch.delenv("NIS_NO_ESTOP_PANEL") + monkeypatch.setenv("CONFOCAL_NO_ESTOP_PANEL", "1") # the older name still works estop.launch_panel() monkeypatch.delenv("CONFOCAL_NO_ESTOP_PANEL") monkeypatch.setattr(estop, "panel_running", lambda: True) @@ -72,7 +75,7 @@ def test_launch_panel_opt_out_and_already_running(monkeypatch): def test_launch_panel_starts_detached_process(monkeypatch): opened = [] - monkeypatch.delenv("CONFOCAL_NO_ESTOP_PANEL", raising=False) + monkeypatch.delenv("NIS_NO_ESTOP_PANEL", raising=False) monkeypatch.setattr(estop, "panel_running", lambda: False) monkeypatch.setattr(estop.subprocess, "Popen", lambda *a, **k: opened.append(a[0])) estop.launch_panel() @@ -83,7 +86,7 @@ def test_launch_panel_failure_goes_to_stderr(monkeypatch, capsys): def boom(*a, **k): raise OSError("nope") - monkeypatch.delenv("CONFOCAL_NO_ESTOP_PANEL", raising=False) + monkeypatch.delenv("NIS_NO_ESTOP_PANEL", raising=False) monkeypatch.setattr(estop, "panel_running", lambda: False) monkeypatch.setattr(estop.subprocess, "Popen", boom) estop.launch_panel() diff --git a/tests/test_estop_panel.py b/tests/test_estop_panel.py index ac06650..22f0f1b 100644 --- a/tests/test_estop_panel.py +++ b/tests/test_estop_panel.py @@ -1,6 +1,6 @@ # The STOP panel against a fake tkinter (no display, no tk needed), plus the -# Windows single-instance mutex paths of the panel and the NIS monitor against -# a fake kernel32, so they run on a Linux CI runner too. +# Windows single-instance mutex paths of the panel and of estop against a +# fake kernel32, so they run on a Linux CI runner too. import ctypes import importlib import sys @@ -9,7 +9,7 @@ import pytest -from acquisition import estop, nis_monitor +from acquisition import estop class Widget: @@ -233,67 +233,10 @@ def no_display(): assert exc.value.code == 1 and "no display available" in capsys.readouterr().err -# ---- Windows mutex probes in estop and nis_monitor ---------------------------------- +# ---- Windows mutex probe in estop --------------------------------------------------- def test_estop_panel_running_reads_the_windows_mutex(monkeypatch): calls = fake_kernel(monkeypatch, exists=True) assert estop.panel_running() is True and ("close", 99) in calls fake_kernel(monkeypatch, exists=False) assert estop.panel_running() is False - - -def test_monitor_running_reads_the_windows_mutex(monkeypatch): - calls = fake_kernel(monkeypatch, exists=True) - assert nis_monitor.monitor_running() is True and ("close", 99) in calls - fake_kernel(monkeypatch, exists=False) - assert nis_monitor.monitor_running() is False - - -def test_monitor_mutex_is_single_instance(monkeypatch): - monkeypatch.setattr(sys, "platform", "linux") - assert nis_monitor._hold_mutex() is True - fake_kernel(monkeypatch, exists=False, last_error=0) - assert nis_monitor._hold_mutex() == 7 - fake_kernel(monkeypatch, exists=True, last_error=183) - assert nis_monitor._hold_mutex() is None - - -def test_monitor_main_refuses_a_second_window(monkeypatch): - monkeypatch.setattr(nis_monitor, "_hold_mutex", lambda: None) - monkeypatch.setattr(sys, "argv", ["nis_monitor"]) - with pytest.raises(SystemExit, match="already open"): - nis_monitor.main() - - -def test_monitor_main_loop_runs_until_interrupted(monkeypatch, tmp_path, capsys): - monkeypatch.setattr(nis_monitor, "_hold_mutex", lambda: 1) - monkeypatch.setattr(nis_monitor.nis_events, "events_dir", lambda: tmp_path / "ev") - monkeypatch.setattr(nis_monitor, "fetch_status", lambda url: ("down", None)) - monkeypatch.setattr(estop, "ESTOP_PATH", tmp_path / "ESTOP") - sleeps = [] - - def sleep(s): - sleeps.append(s) - if len(sleeps) >= 2: - raise KeyboardInterrupt - - monkeypatch.setattr(nis_monitor.time, "sleep", sleep) - monkeypatch.setattr(sys, "argv", ["nis_monitor", "--interval", "0.5"]) - nis_monitor.main() - assert sleeps == [0.5, 0.5] and "NIS monitor" in capsys.readouterr().out - - -def test_monitor_main_starts_a_new_log_after_midnight(monkeypatch, tmp_path, capsys): - import datetime - days = iter([datetime.date(2026, 10, 15), datetime.date(2026, 10, 15), datetime.date(2026, 10, 16), - datetime.date(2026, 10, 16), datetime.date(2026, 10, 16)]) - monkeypatch.setattr(nis_monitor, "_hold_mutex", lambda: 1) - monkeypatch.setattr(nis_monitor.nis_events, "events_dir", lambda: tmp_path / "ev") - monkeypatch.setattr(nis_monitor.nis_events, "events_path", - lambda day=None: tmp_path / f"{next(days).isoformat()}.jsonl") - monkeypatch.setattr(nis_monitor, "fetch_status", lambda url: ("down", None)) - monkeypatch.setattr(estop, "ESTOP_PATH", tmp_path / "ESTOP") - n = [] - monkeypatch.setattr(nis_monitor.time, "sleep", lambda s: (n.append(1), n.__len__() > 1 and (_ for _ in ()).throw(KeyboardInterrupt))[0]) - monkeypatch.setattr(sys, "argv", ["nis_monitor"]) - nis_monitor.main() diff --git a/tests/test_hardware_scripts.py b/tests/test_hardware_scripts.py index 081a7fe..1654a3e 100644 --- a/tests/test_hardware_scripts.py +++ b/tests/test_hardware_scripts.py @@ -191,7 +191,7 @@ def test_read_during_move_script_runs_and_logs_events(scripts, monkeypatch, caps def entry(monkeypatch, tmp_path): monkeypatch.setattr(nis_mock.time, "sleep", lambda s: None) monkeypatch.setattr(estop, "ESTOP_PATH", tmp_path / "ESTOP") - monkeypatch.setenv("CONFOCAL_NO_ESTOP_PANEL", "1") + monkeypatch.setenv("NIS_NO_ESTOP_PANEL", "1") monkeypatch.setenv("CONFOCAL_MCP_DATA_DIR", str(tmp_path)) from acquisition import paths paths.data_root.cache_clear() @@ -218,6 +218,7 @@ def test_nis_sdk_demo(fake_ti2, entry, capsys): def test_estop_cli_entry_point(entry, monkeypatch, capsys): monkeypatch.setattr(sys, "argv", ["estop", "status"]) + monkeypatch.delitem(sys.modules, 'acquisition.estop', raising=False) # run it as a fresh `python -m` would runpy.run_module("acquisition.estop", run_name="__main__") assert "clear" in capsys.readouterr().out diff --git a/tests/test_harness_gate.py b/tests/test_harness_gate.py index 9afaf90..63e1e8a 100644 --- a/tests/test_harness_gate.py +++ b/tests/test_harness_gate.py @@ -17,7 +17,7 @@ import pytest from harness import agent, mcp_agent -from mcp_server import loop_tools +from mcp_server.baumer_ti2 import baumer_ti2_tools class FakeImage: @@ -50,7 +50,7 @@ async def async_gate(name, tool_input): @pytest.fixture def stub_tools(monkeypatch): - """Stub loop_tools so nothing real runs; record kwargs each was called with.""" + """Stub baumer_ti2_tools so nothing real runs; record kwargs each was called with.""" seen = {} def get_image(**kw): @@ -61,8 +61,8 @@ def move(**kw): seen["move"] = kw return {"position": {"x": kw["x"], "y": kw["y"], "z": 0}} - monkeypatch.setattr(loop_tools, "get_image", get_image) - monkeypatch.setattr(loop_tools, "move", move) + monkeypatch.setattr(baumer_ti2_tools, "get_image", get_image) + monkeypatch.setattr(baumer_ti2_tools, "move", move) return seen @@ -83,7 +83,7 @@ def test_agent_tool_schemas_never_expose_confirm(): def test_mcp_agent_strips_confirm_from_real_server_schemas(): - from mcp_server.server_loop import mcp + from mcp_server.baumer_ti2.baumer_ti2_server import mcp mcp_tools = asyncio.run(mcp.list_tools()) assert any("confirm" in t.input_schema.get("properties", {}) for t in mcp_tools), \ "precondition: the server itself does expose confirm (the harness must strip it)" diff --git a/tests/test_harness_loops.py b/tests/test_harness_loops.py index 7361090..ab4c3a3 100644 --- a/tests/test_harness_loops.py +++ b/tests/test_harness_loops.py @@ -16,7 +16,7 @@ from acquisition.backends import nis_mock from acquisition.orchestration import stage_positions from harness import agent, mcp_agent -from mcp_server import loop_tools +from mcp_server.baumer_ti2 import baumer_ti2_tools ROOT = Path(__file__).parent.parent @@ -31,8 +31,8 @@ def text(t): @pytest.fixture(autouse=True) def mock_stage(tmp_path, monkeypatch): - monkeypatch.setattr(loop_tools, "MOVE_HISTORY_PATH", tmp_path / "move.jsonl") - monkeypatch.setattr(loop_tools, "FRAME_HISTORY_PATH", tmp_path / "frame.jsonl") + monkeypatch.setattr(baumer_ti2_tools, "MOVE_HISTORY_PATH", tmp_path / "move.jsonl") + monkeypatch.setattr(baumer_ti2_tools, "FRAME_HISTORY_PATH", tmp_path / "frame.jsonl") monkeypatch.setattr(estop, "ESTOP_PATH", tmp_path / "ESTOP") monkeypatch.setattr(nis_mock.time, "sleep", lambda s: None) monkeypatch.setattr(nis_mock, "CAPTURE_DIR", tmp_path / "caps") @@ -271,7 +271,7 @@ async def turn(client, mcp_client, tools, messages): monkeypatch.setattr(mcp_agent, "run_turn", turn) scripted_input(monkeypatch, ["", "hi", "exit"]) asyncio.run(mcp_agent.main()) - assert seen["params"].args == ["-m", "mcp_server.server_loop"] + assert seen["params"].args == ["-m", "mcp_server.baumer_ti2.baumer_ti2_server"] assert turns[0][0][0]["name"] == "get_pos" and len(turns) == 1 assert "Claude: hello back" in capsys.readouterr().out diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index cb356c1..1da8164 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -1,4 +1,4 @@ -# End-to-end over the real protocol: spawn `python -m mcp_server.server_loop` +# End-to-end over the real protocol: spawn `python -m mcp_server.baumer_ti2.baumer_ti2_server` # as a subprocess (exactly what Claude Desktop/Code and harness/mcp_agent.py # do), talk MCP to it over stdio, and exercise every tool against the mock # backends. No hardware, no model. Guards two things the in-process tests @@ -23,9 +23,9 @@ def _server_params(data_dir: Path, frame: Path) -> StdioServerParameters: env.update({ "CONFOCAL_MCP_DATA_DIR": str(data_dir), "CONFOCAL_MOCK_FRAME_PATH": str(frame), - "CONFOCAL_NO_ESTOP_PANEL": "1", # headless: don't try to open the STOP window + "NIS_NO_ESTOP_PANEL": "1", # headless: don't try to open the STOP window }) - return StdioServerParameters(command=sys.executable, args=["-m", "mcp_server.server_loop"], env=env) + return StdioServerParameters(command=sys.executable, args=["-m", "mcp_server.baumer_ti2.baumer_ti2_server"], env=env) def _text(result) -> dict: diff --git a/tests/test_nis_bridge.py b/tests/test_nis_bridge.py deleted file mode 100644 index 966be66..0000000 --- a/tests/test_nis_bridge.py +++ /dev/null @@ -1,444 +0,0 @@ -# The NIS bridge end to end, without NIS: the real bridge_job HTTP server -# and request queue, the real client and the real MCP tools, with a -# stand-in for g5_regprocs.dll that records every macro call. Covers the -# safety rules (POST-only motion, 1 mm cap, 4x/10x only, e-stop in both -# client and bridge, confirm gate, capture paths); what only NIS can -# answer - that the macro calls do the right thing on the Ti2 - is in -# docs/nis-bridge.md's test plan. -import asyncio -import json -import os -import socket -import sys -import threading -import urllib.request - -import pytest - -from acquisition import estop, nis_events, nis_monitor as monitor -from acquisition.backends import nis_bridge as client_mod -from acquisition.nis_bridge import bridge_job as bj -from mcp_server import nis_tools - - -class FakeNIS: - """Stands in for g5_regprocs.dll: same names, records calls.""" - - def __init__(self): - self.x, self.y, self.z = 100.0, 200.0, 4619.0 - self.objectives = {1: "PLAN APO \u03bbD 4x OFN25", 2: "Plan Fluor 10x Ph1 DLL", - 4: "Plan Apo 60x Oil"} - self.position = 1 - self.label = self.objectives[1] # NIS's objective name: only ChangeObjective moves it - self.nd_running = False - self.load_rc = 1 - self.calls = [] - self.last_saved = None - f = self._fn - self.StgGetPosXY = f("StgGetPosXY", lambda px, py: self._set(px, self.x, py, self.y)) - self.StgGetPosZ = f("StgGetPosZ", lambda pz, dev: self._set(pz, self.z)) - self.StgMoveXY = f("StgMoveXY", self._move) - self.Stg_GetNosepiecePosition = f("Stg_GetNosepiecePosition", lambda: self.position) - self.Stg_GetNosepiecePositions = f("Stg_GetNosepiecePositions", lambda: 6) - self.Stg_GetNosepieceObjectiveName = f("Stg_GetNosepieceObjectiveName", self._name) - self.GetCurrentObjName = f("GetCurrentObjName", self._current) - self.Stg_SetNosepiecePosition = f("Stg_SetNosepiecePosition", self._turn) - self.ChangeObjective = f("ChangeObjective", self._change) - self.opt_confs = ["All Devices", "AX", "EPI"] - self.GetOptConfCount = f("GetOptConfCount", lambda: len(self.opt_confs)) - self.GetOptConfName = f("GetOptConfName", self._conf_name) - self.Capture = f("Capture", lambda: 1) - self.ImageSaveAs = f("ImageSaveAs", self._save) - self.CloseCurrentDocument = f("CloseCurrentDocument", lambda save: 1) - self.ND_LoadExperiment = f("ND_LoadExperiment", lambda name: self.load_rc) - self.ND_RunExperiment = f("ND_RunExperiment", self._run) - self.ND_IsInExperimentCapture = f("ND_IsInExperimentCapture", lambda: int(self.nd_running)) - self.ND_FinishExperiment = f("ND_FinishExperiment", self._finish) - - def _fn(self, name, impl): - def call(*args): - self.calls.append(name) - return impl(*args) - return call - - @staticmethod - def _set(*pairs): - for ptr, value in zip(pairs[::2], pairs[1::2]): - ptr._obj.value = value - return 1 - - def _move(self, dx, dy, relative): - assert relative == bj.MOVE_RELATIVE - self.x += dx; self.y += dy - return 1 - - def _name(self, i, buf, n): - if i in self.objectives: - buf.value = self.objectives[i] - return 1 - return -2 - - def _current(self, buf): - buf.value = self.label - return 1 - - def _change(self, name): - self.label = name # calibration only; the turret stays put - return 1 - - def _turn(self, position): - if position not in self.objectives: - return -2 - self.position = position - return 1 - - def _save(self, path, kind, compression): - assert kind == bj.ND2_ALL_LAYERS - open(path, "wb").close() - self.last_saved = path - return 1 - - def _run(self, open_after): - self.nd_running = True - return 1 - - def _finish(self): - self.nd_running = False - return 1 - - def _conf_name(self, i, buf, n): - buf.value = self.opt_confs[i] if 0 <= i < len(self.opt_confs) else "" - return 1 - - def moved(self): - return [c for c in self.calls if c in ("StgMoveXY", "Stg_SetNosepiecePosition", "ChangeObjective", "Capture", - "ND_RunExperiment")] - - -@pytest.fixture -def estop_file(tmp_path, monkeypatch): - path = tmp_path / "ESTOP" - monkeypatch.setattr(estop, "ESTOP_PATH", path) - monkeypatch.setattr(bj, "ESTOP", path) - return path - - -@pytest.fixture -def bridge(estop_file, monkeypatch): - nis = FakeNIS() - stop, ready, port = threading.Event(), threading.Event(), [] - t = threading.Thread(target=bj.serve, args=(bj.Bridge(bj.Macro(nis)),), - kwargs=dict(port=0, stop=stop, - on_ready=lambda p: (port.append(p), ready.set())), - daemon=True) - t.start() - assert ready.wait(5) - url = f"http://127.0.0.1:{port[0]}" - monkeypatch.setenv("CONFOCAL_NIS_BRIDGE_URL", url) - yield nis, url, client_mod.NISBridge(url) - stop.set() - t.join(5) - - -def raw(url, method, path, body=None): - req = urllib.request.Request(url + path, method=method, - data=json.dumps(body).encode() if body is not None else None) - try: - with urllib.request.urlopen(req, timeout=5) as r: - return r.status, json.loads(r.read()) - except urllib.error.HTTPError as e: - return e.code, json.loads(e.read()) - - -# ---- bridge behaviour ------------------------------------------------- - -def test_status_reports_positions_objectives_and_state(bridge): - nis, url, c = bridge - s = c.status() - assert s["xy_um"] == [100.0, 200.0] and s["z_um"] == 4619.0 - assert s["current_objective"] == nis.objectives[1] - assert s["nosepiece_objectives"] == {str(k): v for k, v in nis.objectives.items()} - assert s["nd_running"] is False and s["estop_engaged"] is False - - -def test_relative_move_and_cap(bridge): - nis, url, c = bridge - r = c.move_relative(150, -50) - assert r["before_um"] == [100.0, 200.0] and r["after_um"] == [250.0, 150.0] - assert "refused" in c.move_relative(1000.1, 0)["error"] - assert (nis.x, nis.y) == (250.0, 150.0) - - -def test_get_cannot_move_or_acquire(bridge): - nis, url, c = bridge - for path in ("/move", "/objective", "/capture", "/nd/run", "/shutdown"): - code, out = raw(url, "GET", path) - assert code == 404 - assert nis.moved() == [] - - -@pytest.mark.parametrize("name,ok", [ - ("Plan Fluor 10x Ph1 DLL", True), - ("Plan Apo 60x Oil", False), - ("CFI 14x", False), - ("Plan Apo 100x Oil", False), -]) -def test_objective_allow_list(bridge, name, ok): - nis, url, c = bridge - if name not in nis.objectives.values(): - nis.objectives[5] = name - r = c.change_objective(name) - assert ("error" not in r) is ok - assert ("Stg_SetNosepiecePosition" in nis.calls) is ok - - -def test_objective_change_reports_nosepiece(bridge): - nis, url, c = bridge - r = c.change_objective("Plan Fluor 10x Ph1 DLL") - assert (r["nosepiece_before"], r["nosepiece_after"]) == (1, 2) - assert r["arrived"] is True and r["after"] == "Plan Fluor 10x Ph1 DLL" - assert nis.position == 2 and nis.label == "Plan Fluor 10x Ph1 DLL" - # turret first, then NIS's calibration - assert nis.calls.index("Stg_SetNosepiecePosition") < nis.calls.index("ChangeObjective") - - -def test_objective_reports_a_turret_that_does_not_arrive(bridge, monkeypatch): - nis, url, c = bridge - monkeypatch.setattr(bj, "TURRET_SETTLE_S", 0.3) - monkeypatch.setattr(bj, "TURRET_POLL_S", 0.05) - nis._turn = lambda position: 1 # accepts the command, never turns - nis.Stg_SetNosepiecePosition = nis._fn("Stg_SetNosepiecePosition", nis._turn) - r = c.change_objective("Plan Fluor 10x Ph1 DLL") - assert r["arrived"] is False and r["nosepiece_after"] == 1 - assert "ChangeObjective" not in nis.calls # no calibration switch for a turret that stayed put - - -def test_estop_blocks_in_bridge_and_client(bridge, estop_file): - nis, url, c = bridge - estop_file.write_text("{}") - # client refuses before sending anything - with pytest.raises(estop.EStopEngaged): - c.move_relative(10, 0) - # a request that bypasses the client is refused inside the bridge - for path, body in (("/move", {"dx": 10}), ("/objective", {"name": "Plan Fluor 10x Ph1 DLL"}), - ("/capture", {"path": str(estop_file.parent / "a.nd2")}), - ("/nd/run", {"experiment": "x"})): - code, out = raw(url, "POST", path, body) - assert out.get("estop_engaged") is True, path - assert nis.moved() == [] - # ending a run is always allowed - nis.nd_running = True - assert c.nd_finish()["nd_running"] is False - - -def test_capture_saves_nd2_and_never_overwrites(bridge, tmp_path): - nis, url, c = bridge - target = tmp_path / "check.nd2" - r = c.capture(str(target)) - assert r["saved"] is True and nis.last_saved == str(target) - assert "already exists" in c.capture(str(target))["error"] - assert "nd2" in c.capture(str(tmp_path / "x.tif"))["error"] - - -def test_nd_run_refuses_second_run_and_reports_load_failure(bridge): - nis, url, c = bridge - nis.load_rc = -2 - assert "ND_LoadExperiment" in c.nd_run("missing")["error"] - nis.load_rc = 1 - assert c.nd_run("C. elegans 3h")["nd_running"] is True - assert "already running" in c.nd_run("C. elegans 3h")["error"] - - -def test_shutdown_stops_the_bridge(bridge): - nis, url, c = bridge - assert c.shutdown() == {"stopping": True} - - -def test_unreachable_bridge_is_a_clear_error(): - with pytest.raises(client_mod.BridgeUnavailable, match="bridge job"): - client_mod.NISBridge("http://127.0.0.1:9", timeout_s=2).status() - - -# ---- MCP tools ---------------------------------------------------------- - -def test_tools_need_confirm(bridge): - nis, url, c = bridge - for call in (lambda: nis_tools.nis_move_relative(10, 0), - lambda: nis_tools.nis_change_objective("Plan Fluor 10x Ph1 DLL"), - lambda: nis_tools.nis_capture("a"), - lambda: nis_tools.nis_run_experiment("x")): - with pytest.raises(PermissionError): - call() - assert nis.moved() == [] - assert nis_tools.nis_move_relative(10, 0, confirm=True)["after_um"] == [110.0, 200.0] - - -def test_capture_tool_writes_only_into_the_capture_folder(bridge, tmp_path, monkeypatch): - nis, url, c = bridge - monkeypatch.setenv("CONFOCAL_NIS_CAPTURE_DIR", str(tmp_path / "caps")) - out = nis_tools.nis_capture("aml18_check", confirm=True) - assert out["path"] == str(tmp_path / "caps" / "aml18_check.nd2") - for bad in ("../evil", "C:\\Windows\\x", "a/b", ""): - with pytest.raises(ValueError): - nis_tools.nis_capture(bad, confirm=True) - - -def test_nis_server_exposes_exactly_the_nis_tools(tmp_path): - from mcp.client import Client - from mcp.client.stdio import StdioServerParameters, stdio_client - - async def names(): - env = dict(os.environ, CONFOCAL_NO_ESTOP_PANEL="1", CONFOCAL_NO_NIS_MONITOR="1", - CONFOCAL_MCP_DATA_DIR=str(tmp_path)) - params = StdioServerParameters(command=sys.executable, args=["-m", "mcp_server.server_nis"], env=env) - async with Client(stdio_client(params)) as client: - return {t.name for t in (await client.list_tools()).tools} - - assert asyncio.run(names()) == {"nis_status", "nis_move_relative", "nis_change_objective", - "nis_capture", "nis_run_experiment", "nis_finish_experiment", - "nis_list_optical_configs", "estop"} - - -def test_idle_bridge_stops_itself(estop_file): - nis = FakeNIS() - t = threading.Thread(target=bj.serve, args=(bj.Bridge(bj.Macro(nis)),), - kwargs=dict(port=0, idle_stop_s=0.5), daemon=True) - t.start() - t.join(5) - assert not t.is_alive() - - -def test_tools_raise_on_bridge_refusals_and_failures(bridge, tmp_path, monkeypatch, estop_file): - nis, url, c = bridge - monkeypatch.setenv("CONFOCAL_NIS_CAPTURE_DIR", str(tmp_path / "caps")) - with pytest.raises(RuntimeError, match="refused"): # move cap - nis_tools.nis_move_relative(1500, 0, confirm=True) - with pytest.raises(RuntimeError, match="allowed"): # objective not on the allow-list - nis_tools.nis_change_objective("Plan Apo 60x Oil", confirm=True) - nis_tools.nis_capture("once", confirm=True) - with pytest.raises(RuntimeError, match="already exists"): # never overwrites - nis_tools.nis_capture("once", confirm=True) - nis.load_rc = -2 - with pytest.raises(RuntimeError, match="ND_LoadExperiment"): - nis_tools.nis_run_experiment("missing", confirm=True) - - -def test_tool_raises_when_the_turret_does_not_arrive(bridge, monkeypatch): - nis, url, c = bridge - monkeypatch.setattr(bj, "TURRET_SETTLE_S", 0.3) - monkeypatch.setattr(bj, "TURRET_POLL_S", 0.05) - nis.Stg_SetNosepiecePosition = nis._fn("Stg_SetNosepiecePosition", lambda position: 1) - with pytest.raises(RuntimeError, match='"arrived": false'): - nis_tools.nis_change_objective("Plan Fluor 10x Ph1 DLL", confirm=True) - - -# ---- event log and live monitor --------------------------------------- - -@pytest.fixture -def events_log(tmp_path, monkeypatch): - monkeypatch.setattr(nis_events, "events_dir", lambda: tmp_path / "events") - return nis_events.events_path() - - -def test_actions_are_logged_start_then_outcome(bridge, events_log, estop_file): - nis, url, c = bridge - c.move_relative(100, 0) # ok - c.move_relative(5000, 0) # the bridge refuses the size: failed - estop_file.write_text("{}") - with pytest.raises(estop.EStopEngaged): - c.move_relative(10, 0) # refused by the client - c.nd_finish() # allowed under e-stop - events, _ = nis_events.read_from(events_log) - assert [(e["action"], e["phase"]) for e in events] == [ - ("move", "start"), ("move", "ok"), ("move", "start"), ("move", "failed"), - ("move", "start"), ("move", "refused"), ("nd_finish", "start"), ("nd_finish", "ok")] - assert events[1]["result"]["after_um"][0] == 200.0 and "elapsed_s" in events[1] - assert "cap" in nis_events.summarize(events[3]) or "refused" in nis_events.summarize(events[3]) - - -def test_status_reads_are_not_logged_and_unreachable_bridge_is_logged(events_log): - c = client_mod.NISBridge("http://127.0.0.1:9", timeout_s=1) - with pytest.raises(client_mod.BridgeUnavailable): - c.move_relative(1, 0) - events, _ = nis_events.read_from(events_log) - assert [(e["action"], e["phase"]) for e in events] == [("move", "start"), ("move", "error")] - - -def test_log_tail_waits_for_a_complete_line(events_log): - nis_events.record("move", "start", params={"dx": 1}) - events, offset = nis_events.read_from(events_log) - assert len(events) == 1 - with events_log.open("a", encoding="utf-8") as f: - f.write('{"action": "move", "pha') # a write in progress - assert nis_events.read_from(events_log, offset) == ([], offset) - with events_log.open("a", encoding="utf-8") as f: - f.write('se": "ok"}\n') - assert [e["phase"] for e in nis_events.read_from(events_log, offset)[0]] == ["ok"] - - -def test_monitor_names_the_call_the_bridge_is_stuck_on(estop_file): - import datetime - now = datetime.datetime(2026, 10, 15, 14, 0, 42) - start = {"ts": "2026-10-15T14:00:00.000", "action": "nd_run", "phase": "start", - "params": {"experiment": "bridge test"}} - assert monitor.pending([start]) == start - assert monitor.pending([start, {**start, "phase": "ok"}]) is None - frame = monitor.render("busy", None, [start], "clear", now, colour=False) - assert "BUSY" in frame and "nd_run" in frame and "42 s so far" in frame - up = monitor.render("up", {"xy_um": [1.0, 2.0], "z_um": 3.0, "nosepiece_position": 0, - "current_objective": "PLAN APO λD 4x OFN25", "nd_running": False}, - [], "clear", now, colour=False) - assert "XY 1.0, 2.0" in up and "4x OFN25" in up and "no NIS actions" in up - - -def test_monitor_status_poll_tells_up_from_down(bridge): - nis, url, c = bridge - link, status = monitor.fetch_status(url) - assert link == "up" and status["xy_um"] == [100.0, 200.0] - with socket.socket() as s: # a port nothing listens on: refused at once - s.bind(("127.0.0.1", 0)) - closed = s.getsockname()[1] - assert monitor.fetch_status(f"http://127.0.0.1:{closed}")[0] == "down" - - -def test_monitor_says_busy_when_the_bridge_connects_but_does_not_answer(): - with socket.socket() as s: # accepts connections, never replies - s.bind(("127.0.0.1", 0)) - s.listen(1) - old, monitor.STATUS_TIMEOUT_S = monitor.STATUS_TIMEOUT_S, 0.5 - try: - assert monitor.fetch_status(f"http://127.0.0.1:{s.getsockname()[1]}")[0] == "busy" - finally: - monitor.STATUS_TIMEOUT_S = old - - -def test_monitor_opens_once_when_the_server_starts(monkeypatch): - opened = [] - monkeypatch.setattr(monitor.subprocess, "Popen", lambda *a, **k: opened.append(a[0])) - monkeypatch.delenv("CONFOCAL_NO_NIS_MONITOR", raising=False) - monkeypatch.setattr(monitor, "monitor_running", lambda: False) - monkeypatch.setattr(monitor, "ON_WINDOWS", True) # the launch is Windows-only; CI runs on Linux - monitor.launch() - assert opened and opened[0][-2:] == ["-m", "acquisition.nis_monitor"] - opened.clear() - monkeypatch.setattr(monitor, "monitor_running", lambda: True) # already on screen - monitor.launch() - monkeypatch.setattr(monitor, "monitor_running", lambda: False) - monkeypatch.setenv("CONFOCAL_NO_NIS_MONITOR", "1") # switched off - monitor.launch() - assert opened == [] - - -def test_optical_configs_can_be_listed_but_not_selected(bridge): - nis, url, c = bridge - assert c.optical_configs()["optical_configs"] == ["All Devices", "AX", "EPI"] - assert nis_tools.nis_list_optical_configs()["optical_configs"] == ["All Devices", "AX", "EPI"] - code, out = raw(url, "POST", "/optconf", {"name": "AX"}) # selecting froze NIS: no route - assert code == 404 and nis.moved() == [] - - -def test_a_second_bridge_cannot_share_the_port(bridge): - nis, url, c = bridge - port = int(url.rsplit(":", 1)[1]) - with pytest.raises(OSError): - bj.serve(bj.Bridge(bj.Macro(FakeNIS())), port=port) diff --git a/tests/test_nis_events_monitor.py b/tests/test_nis_events_monitor.py deleted file mode 100644 index d049b08..0000000 --- a/tests/test_nis_events_monitor.py +++ /dev/null @@ -1,202 +0,0 @@ -# Tests for the NIS worker-thread entry point, optical configs, event log and -# live monitor. Reuses the fake NIS and the bridge fixture from test_nis_bridge. -# No NIS, no Windows and no hardware needed, so they run on the CI runner. - -import datetime -import sys -import threading - -import pytest - -from acquisition import nis_events, nis_monitor as monitor -from acquisition.backends import nis_bridge as client_mod -from acquisition.nis_bridge import bridge_job as bj -from mcp_server import nis_tools -from tests.test_nis_bridge import bridge, estop_file, events_log, raw # noqa: F401 (fixtures) - -NOW = datetime.datetime(2026, 10, 15, 14, 0, 0) - - -# ---- JOBS entry point --------------------------------------------------- - -def test_run_returns_at_once_and_serves_from_a_worker_thread(monkeypatch): - # A JOBS Python task runs on NIS's main thread: run() must not block it. - started, release, seen = threading.Event(), threading.Event(), {} - - def fake_serve(bridge_obj): - seen["thread"], seen["bridge"] = threading.current_thread(), bridge_obj - started.set() - release.wait(5) - - monkeypatch.setattr(bj, "Macro", lambda: "macro") - monkeypatch.setattr(bj, "Bridge", lambda m: ("bridge", m)) - monkeypatch.setattr(bj, "serve", fake_serve) - bj.run((), None, None, None) # returns although fake_serve is still going - assert started.wait(5) - assert seen["thread"] is not threading.main_thread() - assert seen["thread"].daemon and seen["thread"].name == "nis-bridge" - assert seen["bridge"] == ("bridge", "macro") - release.set() - - -# ---- optical configurations ---------------------------------------------- - -def test_optical_configs_skip_blanks_and_duplicates(bridge): - nis, url, c = bridge - nis.opt_confs = ["AX", "", "AX", "EPI"] - assert c.optical_configs()["optical_configs"] == ["AX", "EPI"] - assert nis.moved() == [] - - -def test_optical_configs_are_get_only_and_not_logged(bridge, events_log): - nis, url, c = bridge - code, _ = raw(url, "POST", "/optconfs", {}) - assert code == 404 - c.optical_configs() - assert nis_events.read_from(events_log) == ([], 0) - - -def test_cli_lists_optical_configs(bridge, capsys, monkeypatch): - nis, url, c = bridge - monkeypatch.setenv("CONFOCAL_NIS_BRIDGE_URL", url) - monkeypatch.setattr(sys, "argv", ["nis_bridge", "optconfs"]) - client_mod.main() - assert "All Devices" in capsys.readouterr().out - - -# ---- MCP tool helpers ------------------------------------------------------ - -def test_checked_passes_good_answers_and_raises_on_failures(): - assert nis_tools._checked({"saved": True, "path": "a.nd2"}) == {"saved": True, "path": "a.nd2"} - for bad in ({"error": "refused"}, {"arrived": False}, {"saved": False}): - with pytest.raises(RuntimeError, match="NIS bridge"): - nis_tools._checked(bad) - - -def test_capture_folder_defaults_under_data_nis_captures(tmp_path, monkeypatch): - monkeypatch.delenv("CONFOCAL_NIS_CAPTURE_DIR", raising=False) - monkeypatch.setattr(nis_tools, "data_root", lambda: tmp_path) - d = nis_tools.capture_dir() - assert d == tmp_path / "data" / "NIS" / "captures" and d.is_dir() - - -# ---- event log ------------------------------------------------------------- - -def test_capture_and_nd_run_are_logged(bridge, events_log, tmp_path): - nis, url, c = bridge - c.capture(str(tmp_path / "log.nd2")) - c.nd_run("exp") - events, _ = nis_events.read_from(events_log) - assert [(e["action"], e["phase"]) for e in events] == [ - ("capture", "start"), ("capture", "ok"), ("nd_run", "start"), ("nd_run", "ok")] - - -def test_recording_never_raises_when_the_log_cannot_be_written(tmp_path, monkeypatch): - blocker = tmp_path / "file" - blocker.write_text("x") - monkeypatch.setattr(nis_events, "events_dir", lambda: blocker / "sub") # a folder cannot be made here - e = nis_events.record("move", "start", params={"dx": 1}) - assert e["action"] == "move" and e["phase"] == "start" - - -def test_reading_a_missing_or_damaged_log(tmp_path): - assert nis_events.read_from(tmp_path / "none.jsonl", 7) == ([], 7) - p = tmp_path / "events.jsonl" - p.write_bytes(b'not json\n{"action": "move", "phase": "ok"}\n') - events, offset = nis_events.read_from(p) - assert events == [{"action": "move", "phase": "ok"}] and offset == p.stat().st_size - - -def test_events_go_to_one_file_per_day(events_log): - assert events_log.name == f"events-{datetime.date.today().isoformat()}.jsonl" - assert nis_events.events_path(datetime.date(2026, 10, 15)).name == "events-2026-10-15.jsonl" - - -def test_summarize_each_kind_of_event(): - s = nis_events.summarize - assert s({"action": "move", "phase": "start", "params": {"dx": 1, "dy": 2}}) == "dx=1 dy=2" - assert s({"action": "move", "phase": "refused", "message": "e-stop"}) == "e-stop" - assert s({"action": "move", "phase": "failed", "result": {"error": "too far"}}) == "too far" - assert s({"action": "move", "phase": "ok", "elapsed_s": 1.5, - "result": {"before_um": [1, 2], "after_um": [3.5, 4]}}) == "(1.0, 2.0) -> (3.5, 4.0) (1.5 s)" - assert s({"action": "move", "phase": "ok", "result": {}}) == "? -> ?" - assert "arrived=True" in s({"action": "objective", "phase": "ok", "result": { - "before": "a", "after": "b", "arrived": True, "nosepiece_before": 1, "nosepiece_after": 2}}) - assert s({"action": "capture", "phase": "ok", - "result": {"saved": True, "path": "p.nd2"}}) == "saved=True p.nd2" - assert s({"action": "nd_run", "phase": "ok", "result": {"nd_running": True}}) == "nd_running=True" - assert s({"action": "shutdown", "phase": "ok", "result": {}}) == "" - - -# ---- monitor --------------------------------------------------------------- - -def test_pending_is_the_latest_unclosed_start(): - a = {"ts": "2026-10-15T14:00:00.000", "action": "capture", "phase": "start"} - b = {"ts": "2026-10-15T14:00:05.000", "action": "nd_run", "phase": "start"} - assert monitor.pending([a, b]) == b - assert monitor.pending([a, b, {**b, "phase": "failed"}]) == a - assert monitor.pending([]) is None - - -def test_render_shows_link_state_estop_and_recent_events(estop_file): - ev = [{"ts": f"2026-10-15T13:00:0{i}.000", "action": "move", "phase": "ok", - "result": {"before_um": [0, 0], "after_um": [i, 0]}} for i in range(5)] - down = monitor.render("down", None, ev, "clear", NOW, rows=2, colour=False) - assert "DOWN" in down and "e-stop: clear" in down - assert "13:00:04" in down and "13:00:03" in down and "13:00:02" not in down # only the last `rows` - assert "\x1b[" not in down - estop_file.write_text("{}") - assert "e-stop: ENGAGED" in monitor.render("up", None, [], "ENGAGED", NOW, colour=False) - assert "\x1b[" in monitor.render("up", None, [], "ENGAGED", NOW, colour=True) - - -def test_render_truncates_long_lines(estop_file): - ev = [{"ts": "2026-10-15T13:00:00.000", "action": "capture", "phase": "ok", - "result": {"saved": True, "path": "x" * 300}}] - frame = monitor.render("up", None, ev, "clear", NOW, width=60, colour=False) - assert all(len(line) <= 60 for line in frame.splitlines()) and "…" in frame - - -def test_fetch_status_treats_a_garbled_answer_as_down(monkeypatch): - class Resp: - def __enter__(self): - return self - - def __exit__(self, *a): - return False - - def read(self): - return b"" - - monkeypatch.setattr(monitor.urllib.request, "urlopen", lambda *a, **k: Resp()) - assert monitor.fetch_status("http://x") == ("down", None) - - -def test_monitor_launch_does_nothing_off_windows(monkeypatch): - opened = [] - monkeypatch.setattr(monitor.subprocess, "Popen", lambda *a, **k: opened.append(a)) - monkeypatch.delenv("CONFOCAL_NO_NIS_MONITOR", raising=False) - monkeypatch.setattr(monitor, "ON_WINDOWS", False) - monitor.launch() - assert opened == [] - - -def test_monitor_launch_failure_is_reported_not_raised(monkeypatch, capsys): - def boom(*a, **k): - raise OSError("no console") - - monkeypatch.setattr(monitor.subprocess, "Popen", boom) - monkeypatch.delenv("CONFOCAL_NO_NIS_MONITOR", raising=False) - monkeypatch.setattr(monitor, "ON_WINDOWS", True) - monkeypatch.setattr(monitor, "monitor_running", lambda: False) - monitor.launch() - assert "could not open the monitor window" in capsys.readouterr().err - - -def test_monitor_once_prints_one_snapshot(bridge, events_log, capsys, monkeypatch): - nis, url, c = bridge - c.move_relative(10, 0) - monkeypatch.setattr(sys, "argv", ["nis_monitor", "--once", "--url", url]) - monitor.main() - out = capsys.readouterr().out - assert "bridge: UP" in out and "XY 110.0, 200.0" in out and "move" in out diff --git a/tests/test_small_gaps.py b/tests/test_small_gaps.py index 878ef74..761d1ed 100644 --- a/tests/test_small_gaps.py +++ b/tests/test_small_gaps.py @@ -1,71 +1,43 @@ # The last small branches: server entry points, package version fallback, -# bridge error paths, and a few `python -m` blocks. +# and a few `python -m` blocks. import contextlib -import http.server import importlib -import json -import queue import runpy import sys -import threading import types -import urllib.request -from pathlib import Path from types import SimpleNamespace as NS import pytest -from acquisition import estop, nis_monitor, paths -from acquisition.backends import nis_bridge as client_mod -from acquisition.nis_bridge import bridge_job as bj +from acquisition import estop, paths from acquisition.orchestration import stage_positions, worm_follow from harness import context -from mcp_server import nis_tools from tests.fakes import fake_ti2 # noqa: F401 (fixture) from tests.fakes_camera import install_fake_camera_stack -from tests.test_nis_bridge import FakeNIS, bridge, estop_file, raw # noqa: F401 (fixtures) # ---- MCP server entry points ------------------------------------------------------- -def test_nis_server_main_opens_the_panel_and_monitor_then_serves(monkeypatch): - from mcp_server import server_nis - calls = [] - monkeypatch.setattr(server_nis.estop, "launch_panel", lambda: calls.append("panel")) - monkeypatch.setattr(server_nis.nis_monitor, "launch", lambda: calls.append("monitor")) - monkeypatch.setattr(server_nis.mcp, "run", lambda transport: calls.append(("run", transport))) - server_nis.main() - assert calls == ["panel", "monitor", ("run", "stdio")] - - def test_loop_server_main_opens_the_panel_then_serves(monkeypatch): - from mcp_server import server_loop + from mcp_server.baumer_ti2 import baumer_ti2_server calls = [] - monkeypatch.setattr(server_loop.estop, "launch_panel", lambda: calls.append("panel")) - monkeypatch.setattr(server_loop.mcp, "run", lambda transport: calls.append(("run", transport))) - server_loop.main() + monkeypatch.setattr(baumer_ti2_server.estop, "launch_panel", lambda: calls.append("panel")) + monkeypatch.setattr(baumer_ti2_server.mcp, "run", lambda transport: calls.append(("run", transport))) + baumer_ti2_server.main() assert calls == ["panel", ("run", "stdio")] -@pytest.mark.parametrize("module", ["mcp_server.server_loop", "mcp_server.server_nis"]) -def test_server_modules_start_when_run_with_dash_m(module, monkeypatch): +def test_server_module_starts_when_run_with_dash_m(monkeypatch): + module = "mcp_server.baumer_ti2.baumer_ti2_server" from mcp.server.mcpserver import MCPServer ran = [] monkeypatch.setattr(MCPServer, "run", lambda self, transport: ran.append(transport)) monkeypatch.setattr(estop, "launch_panel", lambda: None) - monkeypatch.setattr(nis_monitor, "launch", lambda: None) + monkeypatch.delitem(sys.modules, module, raising=False) # run it as a fresh `python -m` would runpy.run_module(module, run_name="__main__") assert ran == ["stdio"] -def test_the_nis_server_registers_the_nis_tools_in_process(): - import asyncio - from mcp_server import server_nis - names = {t.name for t in asyncio.run(server_nis.mcp.list_tools())} - assert names == {"nis_status", "nis_move_relative", "nis_change_objective", "nis_capture", - "nis_run_experiment", "nis_finish_experiment", "nis_list_optical_configs", "estop"} - - def test_package_version_falls_back_when_not_installed(monkeypatch): import importlib.metadata as md import mcp_server @@ -82,111 +54,7 @@ def missing(name): importlib.reload(mcp_server) -# ---- NIS tools / client / bridge ----------------------------------------------------- - -def test_status_and_finish_tools_reach_the_bridge(bridge): - nis, url, c = bridge - assert nis_tools.nis_status()["xy_um"] == [100.0, 200.0] - nis.nd_running = True - assert nis_tools.nis_finish_experiment()["nd_running"] is False - - -def test_client_wraps_a_non_json_error_body(tmp_path): - class Handler(http.server.BaseHTTPRequestHandler): - def do_GET(self): - self.send_response(500) - self.end_headers() - self.wfile.write(b"oops") - - def log_message(self, *a): - pass - - srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) - threading.Thread(target=srv.serve_forever, daemon=True).start() - try: - out = client_mod.NISBridge(f"http://127.0.0.1:{srv.server_address[1]}").status() - finally: - srv.shutdown() - srv.server_close() - assert out["http_status"] == 500 and "error" in out - - -def run_cli(monkeypatch, *argv): - monkeypatch.setattr(sys, "argv", ["nis_bridge", *argv]) - client_mod.main() - - -def test_cli_exits_with_the_reason_when_the_bridge_is_down_or_stopped(monkeypatch, estop_file): - monkeypatch.setenv("CONFOCAL_NIS_BRIDGE_URL", "http://127.0.0.1:9") - with pytest.raises(SystemExit, match="not reachable"): - run_cli(monkeypatch, "status") - estop_file.write_text("{}") - with pytest.raises(SystemExit, match="E-STOP"): - run_cli(monkeypatch, "move", "1", "0") - - -def test_cli_prints_the_bridge_answer(bridge, monkeypatch, capsys): - nis, url, c = bridge - run_cli(monkeypatch, "--url", url, "status") - assert json.loads(capsys.readouterr().out)["xy_um"] == [100.0, 200.0] - - -def test_cli_module_runs_as_a_script(bridge, monkeypatch, capsys): - nis, url, c = bridge - monkeypatch.setattr(sys, "argv", ["nis_bridge", "--url", url, "status"]) - runpy.run_module("acquisition.backends.nis_bridge", run_name="__main__") - assert "xy_um" in capsys.readouterr().out - - -def test_bridge_treats_an_unreadable_estop_file_as_engaged(monkeypatch): - class Broken: - def exists(self): - raise PermissionError("denied") - - monkeypatch.setattr(bj, "ESTOP", Broken()) - assert bj._estop_engaged() is True - - -def test_objective_name_must_be_on_the_nosepiece_exactly_once(bridge): - nis, url, c = bridge - nis.objectives[5] = nis.objectives[2] # the same 10x in two positions - r = c.change_objective("Plan Fluor 10x Ph1 DLL") - assert "exactly once" in r["error"] and "Stg_SetNosepiecePosition" not in nis.calls - - -def test_bridge_rejects_a_body_that_is_not_json(bridge): - nis, url, c = bridge - req = urllib.request.Request(url + "/move", data=b"{not json", method="POST") - try: - urllib.request.urlopen(req, timeout=5) - status = 200 - except urllib.error.HTTPError as e: - status, body = e.code, json.loads(e.read()) - assert status == 400 and "not JSON" in body["error"] - assert nis.moved() == [] - - -def test_a_route_that_raises_is_reported_and_the_bridge_survives(bridge, monkeypatch): - nis, url, c = bridge - monkeypatch.setitem(bj.ROUTES, ("GET", "/status"), lambda b, body: 1 / 0) - assert "ZeroDivisionError" in c.status()["error"] - monkeypatch.undo() - assert c.status()["xy_um"] == [100.0, 200.0] - - -def test_a_request_the_worker_never_answers_times_out_with_504(): - jobs, stop = queue.Queue(), threading.Event() # nobody consumes the queue - srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), bj.make_handler(jobs, stop, timeout_s=0.1)) - threading.Thread(target=srv.serve_forever, daemon=True).start() - try: - code, out = raw(f"http://127.0.0.1:{srv.server_address[1]}", "POST", "/move", {"dx": 1}) - finally: - srv.shutdown() - srv.server_close() - assert code == 504 and "timed out" in out["error"] - - -# ---- paths / monitor / context ---------------------------------------------------------- +# ---- paths / context ---------------------------------------------------------- def test_system_dir_check_survives_an_os_error(monkeypatch): class Odd: @@ -201,18 +69,6 @@ def parents(self): assert paths._is_system_dir(Odd()) is False -def test_monitor_probe_is_false_off_windows(monkeypatch): - monkeypatch.setattr(sys, "platform", "linux") - assert nis_monitor.monitor_running() is False - - -def test_monitor_module_prints_one_snapshot_as_a_script(monkeypatch, capsys): - monkeypatch.setenv("CONFOCAL_NIS_BRIDGE_URL", "http://127.0.0.1:9") - monkeypatch.setattr(sys, "argv", ["nis_monitor", "--once"]) - runpy.run_module("acquisition.nis_monitor", run_name="__main__") - assert "bridge:" in capsys.readouterr().out - - def test_strip_images_copies_plain_string_content(): msg = {"role": "user", "content": "just text"} out = context._strip_images(msg) @@ -246,32 +102,7 @@ def value(self): worm_follow.force_camera_autos_off(cam) # no exception -# ---- the NIS port probe's timeout and the calibration/panel scripts ------------------------- - -def test_probe_reports_a_nis_that_never_answers(monkeypatch, tmp_path): - import ctypes - limjob = types.ModuleType("limjob") - limjob.Image = limjob.JobParam = limjob.MacroParam = limjob.RunContext = object - monkeypatch.setitem(sys.modules, "limjob", limjob) - monkeypatch.setattr(ctypes, "cdll", NS(g5_regprocs=FakeNIS()), raising=False) - sys.modules.pop("acquisition.calibration.nis_port_probe", None) - mod = importlib.import_module("acquisition.calibration.nis_port_probe") - - class NeverAnswers(queue.Queue): - def get(self, timeout=None): - raise queue.Empty - - monkeypatch.setattr(mod, "queue", NS(Queue=NeverAnswers, Empty=queue.Empty)) - srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), mod.H) - threading.Thread(target=srv.serve_forever, daemon=True).start() - try: - with urllib.request.urlopen(f"http://127.0.0.1:{srv.server_address[1]}/status", timeout=5) as r: - assert "timed out waiting for NIS" in json.loads(r.read())["error"] - finally: - srv.shutdown() - srv.server_close() - sys.modules.pop("acquisition.calibration.nis_port_probe", None) - +# ---- the calibration/panel scripts ------------------------- @pytest.mark.parametrize("module", ["acquisition.calibration.ti2_config", "acquisition.calibration.ti2_inventory"]) def test_calibration_modules_run_as_scripts(module, monkeypatch, capsys): @@ -294,5 +125,6 @@ def no_display(): monkeypatch.setitem(sys.modules, "tkinter", tk) monkeypatch.setitem(sys.modules, "tkinter.messagebox", tk.messagebox) monkeypatch.setattr(sys, "argv", ["estop_panel"]) + monkeypatch.delitem(sys.modules, 'acquisition.estop_panel', raising=False) # run it as a fresh `python -m` would with contextlib.suppress(SystemExit): # no display -> exit 1; already open -> returns runpy.run_module("acquisition.estop_panel", run_name="__main__") diff --git a/tests/test_timelapse_gaps.py b/tests/test_timelapse_gaps.py index 726fda2..4413ae4 100644 --- a/tests/test_timelapse_gaps.py +++ b/tests/test_timelapse_gaps.py @@ -296,8 +296,8 @@ def test_run_stops_at_the_runtime_cap(tmp_path, write_frame): def test_default_capture_goes_through_get_image(monkeypatch, tmp_path): calls = [] - from mcp_server import loop_tools - monkeypatch.setattr(loop_tools, "get_image", lambda **kw: (calls.append(kw), ({"image": "x.png"}, None))[1]) + from mcp_server.baumer_ti2 import baumer_ti2_tools + monkeypatch.setattr(baumer_ti2_tools, "get_image", lambda **kw: (calls.append(kw), ({"image": "x.png"}, None))[1]) cap = sc._default_capture(sc.TimelapseConfig(backend="mock")) assert cap() == {"image": "x.png"} and calls[0]["confirm"] is False and calls[0]["backend"] == "mock" sc._default_capture(sc.TimelapseConfig(backend="sdk"))() @@ -321,10 +321,10 @@ def test_cli_real_hardware_needs_whole_plan_approval(monkeypatch, capsys): def test_cli_runs_a_short_mock_session(tmp_path, monkeypatch, capsys): - from mcp_server import loop_tools + from mcp_server.baumer_ti2 import baumer_ti2_tools from tests.conftest import make_blob_frame, save_frame frame = save_frame(make_blob_frame(), tmp_path / "f.png") - monkeypatch.setattr(loop_tools, "get_image", lambda **kw: ({"image": str(frame), "frame_id": 1, "position": {}}, None)) + monkeypatch.setattr(baumer_ti2_tools, "get_image", lambda **kw: ({"image": str(frame), "frame_id": 1, "position": {}}, None)) events = tmp_path / "ev.jsonl" assert sc.main(["--max-captures", "2", "--slow", "0.01", "--burst", "0.01", "--events", str(events)]) == 0 assert "done: max_captures; 2 captures" in capsys.readouterr().out and events.exists() @@ -340,10 +340,10 @@ def __init__(self, max_calls): def __call__(self, *a): return None - from mcp_server import loop_tools + from mcp_server.baumer_ti2 import baumer_ti2_tools from tests.conftest import make_blob_frame, save_frame frame = save_frame(make_blob_frame(), tmp_path / "f.png") - monkeypatch.setattr(loop_tools, "get_image", lambda **kw: ({"image": str(frame), "frame_id": 1, "position": {}}, None)) + monkeypatch.setattr(baumer_ti2_tools, "get_image", lambda **kw: ({"image": str(frame), "frame_id": 1, "position": {}}, None)) monkeypatch.setattr(mt, "ModelTrigger", FakeTrigger) sc.main(["--max-captures", "1", "--slow", "0.01", "--burst", "0.01", "--model-trigger", "--model-max-calls", "7", "--events", str(tmp_path / "e.jsonl")]) diff --git a/timelapse/__init__.py b/timelapse/__init__.py index c33957f..2bd6301 100644 --- a/timelapse/__init__.py +++ b/timelapse/__init__.py @@ -8,9 +8,9 @@ # gaps, global intensity jumps and XY shifts, to # separate "filming error" from "biological change" # scheduler.py - the slow-loop / burst-mode acquisition loop that -# drives loop_tools.get_image() using the detector +# drives baumer_ti2_tools.get_image() using the detector # # None of this is an MCP tool. The model-facing surface stays at 5 tools -# (see mcp_server/loop_tools.py's header); this package sits *beside* the +# (see mcp_server/baumer_ti2/baumer_ti2_tools.py's header); this package sits *beside* the # tools and calls get_image() itself. # ------------------------------------------------------------ diff --git a/timelapse/scheduler.py b/timelapse/scheduler.py index c59ccd0..5efa84f 100644 --- a/timelapse/scheduler.py +++ b/timelapse/scheduler.py @@ -105,13 +105,13 @@ def detector(self) -> ChangeDetector: def _default_capture(config: TimelapseConfig) -> CaptureFn: - """Capture via loop_tools.get_image(). For backend='sdk' this supplies + """Capture via baumer_ti2_tools.get_image(). For backend='sdk' this supplies confirm=True - main() has already obtained the one-time human approval for the whole run before this is ever constructed.""" - from mcp_server import loop_tools + from mcp_server.baumer_ti2 import baumer_ti2_tools def capture() -> dict: - metadata, _preview = loop_tools.get_image( + metadata, _preview = baumer_ti2_tools.get_image( backend=config.backend, confirm=(config.backend == "sdk"), max_dimension=config.preview_max_dimension,