From 43e2c94b6defb9917631f820fea3ef4102f6d3d3 Mon Sep 17 00:00:00 2001 From: Qurratul Ain Quais Date: Fri, 16 Oct 2026 21:05:06 -0400 Subject: [PATCH 01/12] NIS bridge: disable capture and ND calls (they crashed NIS from the worker thread) Capture faulted nis_ar.exe in Qt5Core.dll on 2026-10-16. The bridge now does status, XY moves and objective changes only; capture and ND runs are started in NIS by hand. The three MCP tools are no longer registered. --- acquisition/nis_bridge/bridge_job.py | 17 +++++++++++++++++ docs/nis-bridge.md | 17 ++++++++++++++++- mcp_server/server_nis.py | 5 ++--- tests/test_nis_bridge.py | 12 +++++++++++- tests/test_small_gaps.py | 4 ++-- 5 files changed, 48 insertions(+), 7 deletions(-) diff --git a/acquisition/nis_bridge/bridge_job.py b/acquisition/nis_bridge/bridge_job.py index 4f6be7f..ffc0d4f 100644 --- a/acquisition/nis_bridge/bridge_job.py +++ b/acquisition/nis_bridge/bridge_job.py @@ -72,6 +72,11 @@ VERSION = 1 MAX_STEP_UM = 1000.0 ALLOWED_MAGNIFICATIONS = (4, 10) +# Capture, ImageSaveAs, CloseCurrentDocument and the ND calls open or close +# NIS windows. Called from the worker thread they crashed nis_ar.exe +# (Qt5Core.dll, 0xc0000409, 2026-10-16). Off until they run on NIS's main +# thread: capture and ND runs are started by hand in NIS meanwhile. +UI_CALLS_ENABLED = False # "4x" / "10x" as a whole magnification - not the 4x inside "14x" or "40x" _MAG = re.compile(r"(? dict: # 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 _refuse_ui_call(self, what: str) -> dict | None: + if not UI_CALLS_ENABLED: + return {"error": f"{what} is disabled: it crashes NIS when called from the bridge's " + "worker thread. Start it in NIS itself."} + return None + def capture(self, path: str) -> dict: + if (r := self._refuse_ui_call("capture")): + return r if (r := self._refuse_if_stopped("capture")): return r if not path.lower().endswith(".nd2"): @@ -227,6 +240,8 @@ def capture(self, path: str) -> dict: "path": path, "saved": os.path.exists(path)} def nd_run(self, experiment: str) -> dict: + if (r := self._refuse_ui_call("ND run")): + return r if (r := self._refuse_if_stopped("ND run")): return r if self.m.ND_IsInExperimentCapture(): @@ -242,6 +257,8 @@ def nd_run(self, experiment: str) -> dict: def nd_finish(self) -> dict: # Always allowed, e-stop or not: it only ends a run early. + if (r := self._refuse_ui_call("ND finish")): + return r rc = self.m.ND_FinishExperiment() return {"rc": rc, "nd_running": bool(self.m.ND_IsInExperimentCapture())} diff --git a/docs/nis-bridge.md b/docs/nis-bridge.md index af4a46c..cdb9ec2 100644 --- a/docs/nis-bridge.md +++ b/docs/nis-bridge.md @@ -6,7 +6,7 @@ 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.** +**Status: status, XY moves and objective changes work on the scope. Capture and ND runs are disabled (they crash NIS, 2026-10-16).** 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 @@ -139,6 +139,21 @@ before changing anything. field differs per objective, but check it with a capture at each. - Steps 6-10 not run yet. +## Results on the microscope (2026-10-16): capture crashes NIS + +- Step 6 (`capture`) killed NIS: `nis_ar.exe` faulted in `Qt5Core.dll` + (exception 0xc0000409) at the moment of the call. `Capture`, + `ImageSaveAs` and `CloseCurrentDocument` open and close NIS windows, which + Qt only allows on the UI thread. No file was saved. Reads, moves and + objective changes from the worker thread are fine. +- **Decision (keep it simple):** the bridge does status, XY moves and + objective changes only. `/capture`, `/nd/run` and `/nd/finish` now answer + "disabled" (`UI_CALLS_ENABLED = False` in `bridge_job.py`) and the three MCP + tools are not registered. Capture and ND runs are started by hand in NIS; + Claude then reads the saved `.nd2`. Steps 6-10 are therefore not run. +- To bring them back, they would have to run on NIS's main thread (a short + JOBS job that takes one queued request per run). Not planned. + ## Safety rules (enforced in code) - Motion and acquisition answer **POST** only, so a browser cannot trigger them. diff --git a/mcp_server/server_nis.py b/mcp_server/server_nis.py index 05909e2..09dbfb0 100644 --- a/mcp_server/server_nis.py +++ b/mcp_server/server_nis.py @@ -23,9 +23,8 @@ 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) +# nis_capture / nis_run_experiment / nis_finish_experiment stay out until the bridge can +# run them on NIS's main thread (they crashed NIS from the worker thread, 2026-10-16). mcp.add_tool(loop_tools.estop) # the same e-stop, reachable from this server too diff --git a/tests/test_nis_bridge.py b/tests/test_nis_bridge.py index 966be66..f247933 100644 --- a/tests/test_nis_bridge.py +++ b/tests/test_nis_bridge.py @@ -125,6 +125,7 @@ def estop_file(tmp_path, monkeypatch): @pytest.fixture def bridge(estop_file, monkeypatch): + monkeypatch.setattr(bj, "UI_CALLS_ENABLED", True) # the plumbing is tested; the real default is off nis = FakeNIS() stop, ready, port = threading.Event(), threading.Event(), [] t = threading.Thread(target=bj.serve, args=(bj.Bridge(bj.Macro(nis)),), @@ -295,7 +296,6 @@ async def names(): 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"} @@ -442,3 +442,13 @@ def test_a_second_bridge_cannot_share_the_port(bridge): port = int(url.rsplit(":", 1)[1]) with pytest.raises(OSError): bj.serve(bj.Bridge(bj.Macro(FakeNIS())), port=port) + + +def test_ui_calls_are_off_by_default(estop_file): + assert bj.UI_CALLS_ENABLED is False + nis = FakeNIS() + b = bj.Bridge(bj.Macro(nis)) + assert "disabled" in b.capture("x.nd2")["error"] + assert "disabled" in b.nd_run("exp")["error"] + assert "disabled" in b.nd_finish()["error"] + assert not nis.calls diff --git a/tests/test_small_gaps.py b/tests/test_small_gaps.py index 878ef74..e67c5b4 100644 --- a/tests/test_small_gaps.py +++ b/tests/test_small_gaps.py @@ -62,8 +62,8 @@ 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"} + assert names == {"nis_status", "nis_move_relative", "nis_change_objective", + "nis_list_optical_configs", "estop"} def test_package_version_falls_back_when_not_installed(monkeypatch): From 2b180ef5c6bd7e80acdceb52c0a7f0ae0c72540e Mon Sep 17 00:00:00 2001 From: Qurratul Ain Quais Date: Thu, 29 Oct 2026 17:41:45 -0400 Subject: [PATCH 02/12] NIS bridge: run capture and ND calls on NIS's main thread via a Win32 timer --- acquisition/nis_bridge/bridge_job.py | 139 ++++++++++++++++++++------- docs/nis-bridge.md | 23 +++-- mcp_server/server_nis.py | 5 +- tests/test_nis_bridge.py | 79 +++++++++++++-- tests/test_nis_events_monitor.py | 6 +- tests/test_small_gaps.py | 4 +- 6 files changed, 199 insertions(+), 57 deletions(-) diff --git a/acquisition/nis_bridge/bridge_job.py b/acquisition/nis_bridge/bridge_job.py index ffc0d4f..436dff0 100644 --- a/acquisition/nis_bridge/bridge_job.py +++ b/acquisition/nis_bridge/bridge_job.py @@ -72,11 +72,8 @@ VERSION = 1 MAX_STEP_UM = 1000.0 ALLOWED_MAGNIFICATIONS = (4, 10) -# Capture, ImageSaveAs, CloseCurrentDocument and the ND calls open or close -# NIS windows. Called from the worker thread they crashed nis_ar.exe -# (Qt5Core.dll, 0xc0000409, 2026-10-16). Off until they run on NIS's main -# thread: capture and ND runs are started by hand in NIS meanwhile. -UI_CALLS_ENABLED = False +UI_TICK_MS = 50 # how often NIS's main thread looks for queued UI calls +UI_CALL_TIMEOUT_S = 600.0 # give up waiting for the main thread after this long # "4x" / "10x" as a whole magnification - not the 4x inside "14x" or "40x" _MAG = re.compile(r"(? bool: return True # cannot tell -> treat as engaged, like estop.py +class MainThread: + """Runs calls on NIS's main (UI) thread. + + Capture, ImageSaveAs, CloseCurrentDocument and the ND calls open or close + NIS windows. Called from the worker thread they crashed nis_ar.exe + (Qt5Core.dll, 0xc0000409, 2026-10-16). run() is the one place our code + is on the main thread, so it calls install(), which registers a Win32 + thread timer there. NIS's own message loop then calls _tick on the main + thread every UI_TICK_MS, and _tick runs what the worker queued with + call(). If install() was never called, call() refuses. + """ + + def __init__(self, tick_ms: int = UI_TICK_MS): + self.tick_ms = tick_ms + self.installed = False + self._jobs = queue.Queue() + self._busy = False # a call is running: do not re-enter from a nested message loop + self._timer_proc = None # keep the ctypes callback alive + self.main_thread_id = None + + def install(self) -> None: + """Call from the main thread only (JOBS run()).""" + from ctypes import wintypes + user32 = ct.windll.user32 + proc_type = ct.WINFUNCTYPE(None, wintypes.HWND, wintypes.UINT, ct.c_size_t, wintypes.DWORD) + self._timer_proc = proc_type(lambda hwnd, msg, tid, tick: self._tick()) + user32.SetTimer.argtypes = [wintypes.HWND, ct.c_size_t, wintypes.UINT, proc_type] + user32.SetTimer.restype = ct.c_size_t + if not user32.SetTimer(None, 0, self.tick_ms, self._timer_proc): + raise OSError("SetTimer failed") + self.main_thread_id = threading.get_ident() + self.installed = True + + def _tick(self) -> None: + if self._busy: + return + self._busy = True + try: + while True: + try: + fn, box, cancelled = self._jobs.get_nowait() + except queue.Empty: + return + if cancelled.is_set(): # the caller timed out: do not start it late + continue + try: + box.put(fn()) + except Exception as e: + box.put({"error": f"{type(e).__name__}: {e}"}) + finally: + self._busy = False + + def call(self, fn, timeout_s: float = UI_CALL_TIMEOUT_S) -> dict: + if not self.installed: + return {"error": "no NIS main-thread hook: this call crashes NIS from the worker thread"} + box, cancelled = queue.Queue(), threading.Event() + self._jobs.put((fn, box, cancelled)) + try: + return box.get(timeout=timeout_s) + except queue.Empty: + cancelled.set() + return {"error": f"NIS's main thread did not run the call within {timeout_s:.0f} s"} + + class Bridge: """The operations, as plain methods returning JSON-able dicts.""" - def __init__(self, macro: Macro): + def __init__(self, macro: Macro, ui: MainThread | None = None): self.m = macro + self.ui = ui or MainThread() # not installed: UI calls are refused def status(self) -> dict: x, y, z = ct.c_double(), ct.c_double(), ct.c_double() @@ -218,49 +280,49 @@ def optical_configs(self) -> dict: # 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 _refuse_ui_call(self, what: str) -> dict | None: - if not UI_CALLS_ENABLED: - return {"error": f"{what} is disabled: it crashes NIS when called from the bridge's " - "worker thread. Start it in NIS itself."} - return None - def capture(self, path: str) -> dict: - if (r := self._refuse_ui_call("capture")): - return r 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 on_main_thread() -> dict: + if _estop_engaged(): # re-check: the call may have waited in the queue + return {"error": "e-stop engaged - capture refused", "estop_engaged": True} + 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)} + return self.ui.call(on_main_thread) def nd_run(self, experiment: str) -> dict: - if (r := self._refuse_ui_call("ND run")): - return r 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 on_main_thread() -> dict: + if _estop_engaged(): + return {"error": "e-stop engaged - ND run refused", "estop_engaged": True} + 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())} + return self.ui.call(on_main_thread) def nd_finish(self) -> dict: # Always allowed, e-stop or not: it only ends a run early. - if (r := self._refuse_ui_call("ND finish")): - return r - rc = self.m.ND_FinishExperiment() - return {"rc": rc, "nd_running": bool(self.m.ND_IsInExperimentCapture())} + def on_main_thread() -> dict: + rc = self.m.ND_FinishExperiment() + return {"rc": rc, "nd_running": bool(self.m.ND_IsInExperimentCapture())} + return self.ui.call(on_main_thread) # Routes: (method, path) -> function(bridge, body) -> dict @@ -367,5 +429,10 @@ def run(imgs: "tuple[limjob.Image]", Job: "limjob.JobParam", macro: "limjob.Macr 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", + ui = MainThread() + try: + ui.install() # run() is on NIS's main thread: hook it for UI calls + except Exception as e: + print(f"NIS bridge: no main-thread hook ({type(e).__name__}: {e}); capture and ND calls refused") + threading.Thread(target=serve, args=(Bridge(Macro(), ui),), name="nis-bridge", daemon=True).start() diff --git a/docs/nis-bridge.md b/docs/nis-bridge.md index cdb9ec2..7486667 100644 --- a/docs/nis-bridge.md +++ b/docs/nis-bridge.md @@ -6,7 +6,7 @@ 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: status, XY moves and objective changes work on the scope. Capture and ND runs are disabled (they crash NIS, 2026-10-16).** +**Status: status, XY moves and objective changes work on the scope. Capture and ND runs now run on NIS's main thread (a Win32 timer hooked in `run()`); this is untested on the scope. Run step 6 first.** 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 @@ -146,13 +146,20 @@ before changing anything. `ImageSaveAs` and `CloseCurrentDocument` open and close NIS windows, which Qt only allows on the UI thread. No file was saved. Reads, moves and objective changes from the worker thread are fine. -- **Decision (keep it simple):** the bridge does status, XY moves and - objective changes only. `/capture`, `/nd/run` and `/nd/finish` now answer - "disabled" (`UI_CALLS_ENABLED = False` in `bridge_job.py`) and the three MCP - tools are not registered. Capture and ND runs are started by hand in NIS; - Claude then reads the saved `.nd2`. Steps 6-10 are therefore not run. -- To bring them back, they would have to run on NIS's main thread (a short - JOBS job that takes one queued request per run). Not planned. +- **Fix (untested on the scope):** `run()` executes on NIS's main thread, so it + registers a Win32 thread timer there (`MainThread.install()` in + `bridge_job.py`). NIS's own message loop calls the timer every 50 ms, and + the callback runs the queued `Capture`/`ImageSaveAs`/`CloseCurrentDocument` + and ND calls on the UI thread. Status, moves and objective changes stay on + the worker thread. A queued call that the main thread has not started + within 10 min is cancelled, not run late, and the e-stop is checked again + on the main thread just before the call starts. +- **To verify:** step 6 (`capture`) first. If NIS still faults, or the timer + never fires (the call reports "did not run"), the hook is wrong and the + calls stay refused until it is fixed. If `Capture` blocks NIS's UI for the + exposure, that is expected. Steps 7-10 (ND) follow only after step 6 passes. +- The bridge job prints "no main-thread hook" and refuses these calls if the + timer cannot be registered. ## Safety rules (enforced in code) diff --git a/mcp_server/server_nis.py b/mcp_server/server_nis.py index 09dbfb0..05909e2 100644 --- a/mcp_server/server_nis.py +++ b/mcp_server/server_nis.py @@ -23,8 +23,9 @@ 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) -# nis_capture / nis_run_experiment / nis_finish_experiment stay out until the bridge can -# run them on NIS's main thread (they crashed NIS from the worker thread, 2026-10-16). +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 diff --git a/tests/test_nis_bridge.py b/tests/test_nis_bridge.py index f247933..a46fada 100644 --- a/tests/test_nis_bridge.py +++ b/tests/test_nis_bridge.py @@ -11,6 +11,7 @@ import socket import sys import threading +import time import urllib.request import pytest @@ -33,6 +34,7 @@ def __init__(self): self.nd_running = False self.load_rc = 1 self.calls = [] + self.threads = {} # call name -> id of the thread that made it self.last_saved = None f = self._fn self.StgGetPosXY = f("StgGetPosXY", lambda px, py: self._set(px, self.x, py, self.y)) @@ -58,6 +60,7 @@ def __init__(self): def _fn(self, name, impl): def call(*args): self.calls.append(name) + self.threads[name] = threading.get_ident() return impl(*args) return call @@ -123,12 +126,33 @@ def estop_file(tmp_path, monkeypatch): return path +class FakeMainThread(bj.MainThread): + """Plays NIS's message loop: one thread that calls _tick, as the Win32 timer does.""" + + def __init__(self): + super().__init__(tick_ms=5) + self.installed = True + self._stop = threading.Event() + self.thread = threading.Thread(target=self._pump, daemon=True) + self.thread.start() + self.main_thread_id = self.thread.ident + + def _pump(self): + while not self._stop.is_set(): + self._tick() + time.sleep(0.005) + + def close(self): + self._stop.set() + self.thread.join(5) + + @pytest.fixture def bridge(estop_file, monkeypatch): - monkeypatch.setattr(bj, "UI_CALLS_ENABLED", True) # the plumbing is tested; the real default is off nis = FakeNIS() + ui = FakeMainThread() stop, ready, port = threading.Event(), threading.Event(), [] - t = threading.Thread(target=bj.serve, args=(bj.Bridge(bj.Macro(nis)),), + t = threading.Thread(target=bj.serve, args=(bj.Bridge(bj.Macro(nis), ui),), kwargs=dict(port=0, stop=stop, on_ready=lambda p: (port.append(p), ready.set())), daemon=True) @@ -136,9 +160,11 @@ def bridge(estop_file, monkeypatch): assert ready.wait(5) url = f"http://127.0.0.1:{port[0]}" monkeypatch.setenv("CONFOCAL_NIS_BRIDGE_URL", url) + nis.ui = ui yield nis, url, client_mod.NISBridge(url) stop.set() t.join(5) + ui.close() def raw(url, method, path, body=None): @@ -237,6 +263,7 @@ def test_capture_saves_nd2_and_never_overwrites(bridge, tmp_path): target = tmp_path / "check.nd2" r = c.capture(str(target)) assert r["saved"] is True and nis.last_saved == str(target) + assert nis.threads["Capture"] == nis.threads["ImageSaveAs"] == nis.ui.thread.ident assert "already exists" in c.capture(str(target))["error"] assert "nd2" in c.capture(str(tmp_path / "x.tif"))["error"] @@ -296,6 +323,7 @@ async def names(): 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"} @@ -444,11 +472,46 @@ def test_a_second_bridge_cannot_share_the_port(bridge): bj.serve(bj.Bridge(bj.Macro(FakeNIS())), port=port) -def test_ui_calls_are_off_by_default(estop_file): - assert bj.UI_CALLS_ENABLED is False +def test_ui_calls_run_on_the_main_thread_and_moves_do_not(bridge): + nis, url, c = bridge + c.move_relative(10, 0) + c.nd_run("exp") + c.nd_finish() + worker = nis.threads["StgMoveXY"] + assert worker != nis.ui.thread.ident + for name in ("ND_LoadExperiment", "ND_RunExperiment", "ND_FinishExperiment"): + assert nis.threads[name] == nis.ui.thread.ident + + +def test_ui_calls_are_refused_when_the_main_thread_is_not_hooked(estop_file): nis = FakeNIS() - b = bj.Bridge(bj.Macro(nis)) - assert "disabled" in b.capture("x.nd2")["error"] - assert "disabled" in b.nd_run("exp")["error"] - assert "disabled" in b.nd_finish()["error"] + b = bj.Bridge(bj.Macro(nis)) # MainThread never installed + assert "main-thread hook" in b.capture("x.nd2")["error"] + assert "main-thread hook" in b.nd_run("exp")["error"] + assert "main-thread hook" in b.nd_finish()["error"] assert not nis.calls + + +def test_a_call_the_main_thread_never_ran_is_cancelled_not_run_late(estop_file): + ui = bj.MainThread() + ui.installed = True # hooked, but nothing pumps it + ran = [] + r = ui.call(lambda: ran.append(1) or {}, timeout_s=0.05) + assert "did not run" in r["error"] + ui._tick() # the pump finally wakes up + assert not ran + + +def test_estop_pressed_while_a_capture_waits_stops_it(estop_file): + nis = FakeNIS() + ui = bj.MainThread() + ui.installed = True + b = bj.Bridge(bj.Macro(nis), ui) + box = [] + t = threading.Thread(target=lambda: box.append(b.capture("y.nd2")), daemon=True) + t.start() + time.sleep(0.1) # queued, not yet run + estop_file.write_text("x") + ui._tick() + t.join(5) + assert box[0]["estop_engaged"] is True and "Capture" not in nis.calls diff --git a/tests/test_nis_events_monitor.py b/tests/test_nis_events_monitor.py index d049b08..520de72 100644 --- a/tests/test_nis_events_monitor.py +++ b/tests/test_nis_events_monitor.py @@ -29,13 +29,17 @@ def fake_serve(bridge_obj): release.wait(5) monkeypatch.setattr(bj, "Macro", lambda: "macro") - monkeypatch.setattr(bj, "Bridge", lambda m: ("bridge", m)) + hooked = [] + monkeypatch.setattr(bj, "MainThread", lambda: type("UI", (), {"install": lambda self: hooked.append( + threading.current_thread())})()) + monkeypatch.setattr(bj, "Bridge", lambda m, ui: ("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") + assert hooked == [threading.current_thread()] # the main-thread hook is installed from run()'s thread release.set() diff --git a/tests/test_small_gaps.py b/tests/test_small_gaps.py index e67c5b4..878ef74 100644 --- a/tests/test_small_gaps.py +++ b/tests/test_small_gaps.py @@ -62,8 +62,8 @@ 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_list_optical_configs", "estop"} + 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): From 264148e5c1f43206e7b0bb9d7608566caec8a1c5 Mon Sep 17 00:00:00 2001 From: Qurratul Ain Quais Date: Fri, 30 Oct 2026 16:36:00 -0400 Subject: [PATCH 03/12] mcp_server: split into baumer_ti2/ and nis/ with descriptive file names --- .github/workflows/ci.yml | 2 +- CHANGELOG.md | 8 +++++ README.md | 34 +++++++++---------- acquisition/backends/baumer_genicam.py | 4 +-- acquisition/backends/nis_sdk.py | 4 +-- acquisition/calibration/ti2_inventory.py | 2 +- acquisition/orchestration/stage_positions.py | 2 +- docs/mcp_harness.md | 26 +++++++------- docs/nis-bridge.md | 10 +++--- eaa_integration/README.md | 16 ++++----- eaa_integration/REMOVAL.md | 4 +-- eaa_integration/run_session.py | 6 ++-- harness/agent.py | 22 ++++++------ harness/context.py | 2 +- harness/mcp_agent.py | 20 +++++------ mcp_server/baumer_ti2/__init__.py | 5 +++ .../baumer_ti2_server.py} | 15 ++++---- .../baumer_ti2_tools.py} | 8 ++--- mcp_server/nis/__init__.py | 5 +++ .../{server_nis.py => nis/nis_server.py} | 18 +++++----- mcp_server/{ => nis}/nis_tools.py | 6 ++-- pyproject.toml | 7 ++-- tests/conftest.py | 2 +- ...loop_tools.py => test_baumer_ti2_tools.py} | 2 +- ..._mock.py => test_baumer_ti2_tools_mock.py} | 12 +++---- tests/test_harness_gate.py | 10 +++--- tests/test_harness_loops.py | 8 ++--- tests/test_mcp_server.py | 4 +-- tests/test_nis_bridge.py | 4 +-- tests/test_nis_events_monitor.py | 2 +- tests/test_small_gaps.py | 26 +++++++------- tests/test_timelapse_gaps.py | 12 +++---- timelapse/__init__.py | 4 +-- timelapse/scheduler.py | 6 ++-- 34 files changed, 171 insertions(+), 147 deletions(-) create mode 100644 mcp_server/baumer_ti2/__init__.py rename mcp_server/{server_loop.py => baumer_ti2/baumer_ti2_server.py} (58%) rename mcp_server/{loop_tools.py => baumer_ti2/baumer_ti2_tools.py} (99%) create mode 100644 mcp_server/nis/__init__.py rename mcp_server/{server_nis.py => nis/nis_server.py} (60%) rename mcp_server/{ => nis}/nis_tools.py (96%) rename tests/{test_loop_tools.py => test_baumer_ti2_tools.py} (99%) rename tests/{test_loop_tools_mock.py => test_baumer_ti2_tools_mock.py} (67%) 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..4d52f18 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,14 @@ Format follows [Keep a Changelog](https://keepachangelog.com/); versions follow ## [Unreleased] +### 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. + ### 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..75fdeff 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,29 +69,29 @@ 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 bridge (`nis-mcp`) - not yet tested on the scope 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 +`127.0.0.1:8766`. The `nis-mcp` server talks to it and adds a +confirm gate, the e-stop and a capture-folder rule. `baumer_ti2_server` 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 +nis-mcp # the MCP server (old name: confocal-mcp-nis) +python -m mcp_server.nis.nis_server # same, from a source checkout ``` MCP client config for a source checkout (adjust the path to this repo's venv): ```json -{ "mcpServers": { "confocal-nis": { +{ "mcpServers": { "nis": { "command": "D:\\path\\to\\microscope-agent\\.venv\\Scripts\\python.exe", - "args": ["-m", "mcp_server.server_nis"], + "args": ["-m", "mcp_server.nis.nis_server"], "cwd": "D:\\path\\to\\microscope-agent" } } } ``` @@ -148,15 +148,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 +164,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 +180,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 +203,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_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/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/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 index 7486667..48bf51d 100644 --- a/docs/nis-bridge.md +++ b/docs/nis-bridge.md @@ -9,7 +9,7 @@ those available to our code and to an MCP client. **Status: status, XY moves and objective changes work on the scope. Capture and ND runs now run on NIS's main thread (a Win32 timer hooked in `run()`); this is untested on the scope. Run step 6 first.** 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 +`mcp_server/baumer_ti2/baumer_ti2_tools.py`), so it also needs sign-off before it is used for real work. ## How it fits together @@ -18,7 +18,7 @@ for real work. MCP client (Claude) │ stdio ▼ -mcp_server/server_nis.py confirm gate, capture-folder rule, estop tool +mcp_server/nis/nis_server.py confirm gate, capture-folder rule, estop tool │ acquisition/backends/nis_bridge.py e-stop checked before sending │ HTTP, 127.0.0.1:8766 @@ -34,8 +34,8 @@ 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`. +`baumer_ti2_server.py` and its tools are unchanged. The NIS tools are a +separate server, `nis-mcp`. ## What was already verified (2026-09-29) @@ -90,7 +90,7 @@ first surprise. Press the STOP panel if anything moves unexpectedly. | 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`. | +| 11 | MCP | Add `nis-mcp` 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 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/__init__.py b/mcp_server/nis/__init__.py new file mode 100644 index 0000000..c928f18 --- /dev/null +++ b/mcp_server/nis/__init__.py @@ -0,0 +1,5 @@ +"""MCP server for NIS-Elements, reached through the bridge job running inside NIS. + +nis_server.py registers the tools; nis_tools.py implements them. +Run with `nis-mcp` or `python -m mcp_server.nis.nis_server`. +""" diff --git a/mcp_server/server_nis.py b/mcp_server/nis/nis_server.py similarity index 60% rename from mcp_server/server_nis.py rename to mcp_server/nis/nis_server.py index 05909e2..9a89421 100644 --- a/mcp_server/server_nis.py +++ b/mcp_server/nis/nis_server.py @@ -1,21 +1,23 @@ -# server_nis.py +# nis_server.py # ------------------------------------------------------------ # MCP server for driving the microscope through NIS-Elements (see -# nis_tools.py). Separate from server_loop.py on purpose: that server's +# nis_tools.py). Separate from baumer_ti2_server.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) +# nis-mcp (installed console script; the old name +# confocal-mcp-nis still works) +# python -m mcp_server.nis.nis_server (from a source checkout) # -# { "mcpServers": { "confocal-nis": { "command": "confocal-mcp-nis" } } } +# { "mcpServers": { "nis": { "command": "nis-mcp" } } } # ------------------------------------------------------------ from mcp.server.mcpserver import MCPServer from acquisition import estop, nis_monitor -from mcp_server import loop_tools, nis_tools +from mcp_server.baumer_ti2 import baumer_ti2_tools +from mcp_server.nis import nis_tools mcp = MCPServer("ConfocalOrchestrator-NIS") @@ -26,11 +28,11 @@ 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 +mcp.add_tool(baumer_ti2_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.""" + """Console entry point (``nis-mcp``): serve the NIS tools over stdio.""" estop.launch_panel() nis_monitor.launch() # live view of what this server does mcp.run(transport="stdio") diff --git a/mcp_server/nis_tools.py b/mcp_server/nis/nis_tools.py similarity index 96% rename from mcp_server/nis_tools.py rename to mcp_server/nis/nis_tools.py index 8c68960..b3ead4b 100644 --- a/mcp_server/nis_tools.py +++ b/mcp_server/nis/nis_tools.py @@ -3,14 +3,14 @@ # 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 +# server, mcp_server/nis/nis_server.py - kept apart from baumer_ti2_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 +# WHAT THIS ADDS over baumer_ti2_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: +# SAFETY, same shape as baumer_ti2_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 diff --git a/pyproject.toml b/pyproject.toml index ddf67b1..ea4264b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -69,8 +69,11 @@ 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" +nis-mcp = "mcp_server.nis.nis_server:main" +# Old names, kept so existing MCP client configs keep working. +confocal-mcp = "mcp_server.baumer_ti2.baumer_ti2_server:main" +confocal-mcp-nis = "mcp_server.nis.nis_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_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..8fe33dc 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 @@ -25,7 +25,7 @@ def _server_params(data_dir: Path, frame: Path) -> StdioServerParameters: "CONFOCAL_MOCK_FRAME_PATH": str(frame), "CONFOCAL_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 index a46fada..c808812 100644 --- a/tests/test_nis_bridge.py +++ b/tests/test_nis_bridge.py @@ -19,7 +19,7 @@ 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 +from mcp_server.nis import nis_tools class FakeNIS: @@ -318,7 +318,7 @@ def test_nis_server_exposes_exactly_the_nis_tools(tmp_path): 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) + params = StdioServerParameters(command=sys.executable, args=["-m", "mcp_server.nis.nis_server"], env=env) async with Client(stdio_client(params)) as client: return {t.name for t in (await client.list_tools()).tools} diff --git a/tests/test_nis_events_monitor.py b/tests/test_nis_events_monitor.py index 520de72..c339679 100644 --- a/tests/test_nis_events_monitor.py +++ b/tests/test_nis_events_monitor.py @@ -11,7 +11,7 @@ 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 mcp_server.nis 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) diff --git a/tests/test_small_gaps.py b/tests/test_small_gaps.py index 878ef74..8f6d142 100644 --- a/tests/test_small_gaps.py +++ b/tests/test_small_gaps.py @@ -20,7 +20,7 @@ from acquisition.nis_bridge import bridge_job as bj from acquisition.orchestration import stage_positions, worm_follow from harness import context -from mcp_server import nis_tools +from mcp_server.nis 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) @@ -29,25 +29,25 @@ # ---- MCP server entry points ------------------------------------------------------- def test_nis_server_main_opens_the_panel_and_monitor_then_serves(monkeypatch): - from mcp_server import server_nis + from mcp_server.nis import nis_server 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() + monkeypatch.setattr(nis_server.estop, "launch_panel", lambda: calls.append("panel")) + monkeypatch.setattr(nis_server.nis_monitor, "launch", lambda: calls.append("monitor")) + monkeypatch.setattr(nis_server.mcp, "run", lambda transport: calls.append(("run", transport))) + nis_server.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"]) +@pytest.mark.parametrize("module", ["mcp_server.baumer_ti2.baumer_ti2_server", "mcp_server.nis.nis_server"]) def test_server_modules_start_when_run_with_dash_m(module, monkeypatch): from mcp.server.mcpserver import MCPServer ran = [] @@ -60,8 +60,8 @@ def test_server_modules_start_when_run_with_dash_m(module, monkeypatch): 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())} + from mcp_server.nis import nis_server + names = {t.name for t in asyncio.run(nis_server.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"} 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, From 75bf2849986ab524783b5f10d298bb332a55398a Mon Sep 17 00:00:00 2001 From: Qurratul Ain Quais Date: Fri, 30 Oct 2026 17:34:08 -0400 Subject: [PATCH 04/12] docs: NIS bridge results on the scope 2026-10-29 (capture works on the main thread) --- README.md | 2 +- docs/nis-bridge.md | 33 ++++++++++++++++++++++++++++++++- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 75fdeff..8040080 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ 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 (`nis-mcp`) - not yet tested on the scope +## NIS bridge (`nis-mcp`) - status, moves, objective and capture tested on the scope; ND runs not yet 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 diff --git a/docs/nis-bridge.md b/docs/nis-bridge.md index 48bf51d..d021a97 100644 --- a/docs/nis-bridge.md +++ b/docs/nis-bridge.md @@ -6,7 +6,7 @@ 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: status, XY moves and objective changes work on the scope. Capture and ND runs now run on NIS's main thread (a Win32 timer hooked in `run()`); this is untested on the scope. Run step 6 first.** +**Status: status, optical-config listing, XY moves, objective changes and capture work on the scope (2026-10-29). Capture runs on NIS's main thread and NIS no longer crashes. ND runs (steps 7-9) are not yet tested.** 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/baumer_ti2/baumer_ti2_tools.py`), so it also needs sign-off before it is used @@ -161,6 +161,37 @@ before changing anything. - The bridge job prints "no main-thread hook" and refuses these calls if the timer cannot be registered. +## Results on the microscope (2026-10-29): main-thread hook + +Bridge job pasted fresh into NIS (JOBS job `NISMCPTest`); its log showed +`NIS bridge v1 listening on 127.0.0.1:8766, pid 28168` and no "no +main-thread hook" warning. Calls went through the MCP tool functions in +`mcp_server/nis/nis_tools.py`, in-process, with `confirm=True` where needed. +Checks on the NIS screen were made by the operator. + +| Step | Call | Time | Result | Evidence | +|---|---|---|---|---| +| 1 | `nis_status` | 18:15:39 | **pass** | XY (0, 0), Z 3594.22 and the 20x matched NIS; turret 0-based (0 = 4x … 5 = S Plan Fluor 20xC) | +| - | `nis_list_optical_configs` | 18:16:59 | **pass** | 14 configs, same as NIS's saved list | +| 2 | `nis_move_relative(100, 0)`, `(-100, 0)` | 20:20:41, 20:21:21 | **pass** | Repeated with a pause: NIS showed X 0.100 mm, then 0.000 mm; Y unchanged. Event log `move ok`, 0.1 s each | +| 5 | `nis_change_objective` 20x → 4x → 10x | 20:21:49, 20:23:30 | **pass** | Nosepiece 2 → 0 → 1, `arrived: true` both times, NIS status bar followed | +| 6 | `nis_capture("bridge_check_2026-10-29.nd2")` | 21:05:03 → 21:05:44 | **pass** | **NIS did not crash**; event log `capture ok`, 41.3 s; file saved (6.5 MB, 3 × 1024 × 1024, GFP/RFP/TD); `nis_status` answered afterwards, NIS responding | +| 7-9 | ND run, status during run, finish | - | **not run** | Needs the template's settings first | + +Notes: + +- The laser was off for the capture, so the image is dark (max 62 of 65535). + The active optical configuration was a GFP/RFP/TD one, not DIC_10x: the + bridge cannot read or set it, so select it in NIS before a real capture. +- `Capture`, `ImageSaveAs` and `CloseCurrentDocument` all returned 0 although + the file was saved, so 0 is not a failure code for these calls. +- `ChangeObjective` (`rc_calibration`) returned 0 both times, but NIS's + objective name had already followed the turret. **Open question:** the + capture's pixel size is 0.215 µm, small for the 10x at 1024 × 1024 unless a + scan zoom was set. Check whether NIS saved the 10x calibration. +- Activating an AX optical configuration in NIS can turn the turret to that + configuration's objective. + ## Safety rules (enforced in code) - Motion and acquisition answer **POST** only, so a browser cannot trigger them. From 22ffa3e0eedf529b3c16d78b29b52c03ac438557 Mon Sep 17 00:00:00 2001 From: Qurratul Ain Quais Date: Fri, 30 Oct 2026 17:51:52 -0400 Subject: [PATCH 05/12] Extract the NIS-Elements MCP server into packages/nis-elements-mcp; old modules forward to it --- .github/workflows/ci.yml | 3 + CHANGELOG.md | 10 + README.md | 2 +- acquisition/_nis_settings.py | 21 + acquisition/backends/nis_bridge.py | 166 +------ acquisition/backends/nis_sdk.py | 2 +- acquisition/calibration/nis_port_probe.py | 2 +- acquisition/estop.py | 213 +-------- acquisition/estop_panel.py | 177 +------ acquisition/nis_bridge/bridge_job.py | 446 +----------------- acquisition/nis_events.py | 107 +---- acquisition/nis_monitor.py | 200 +------- docs/nis-bridge.md | 14 +- mcp_server/nis/__init__.py | 5 +- mcp_server/nis/nis_server.py | 47 +- mcp_server/nis/nis_tools.py | 137 +----- packages/nis-elements-mcp/README.md | 7 + packages/nis-elements-mcp/pyproject.toml | 25 + .../src/nis_elements_mcp/__init__.py | 8 + .../src/nis_elements_mcp/estop.py | 210 +++++++++ .../src/nis_elements_mcp/estop_panel.py | 174 +++++++ .../src/nis_elements_mcp/nis_bridge_client.py | 163 +++++++ .../src/nis_elements_mcp/nis_bridge_job.py | 440 +++++++++++++++++ .../src/nis_elements_mcp/nis_events.py | 101 ++++ .../src/nis_elements_mcp/nis_monitor.py | 197 ++++++++ .../src/nis_elements_mcp/nis_server.py | 38 ++ .../src/nis_elements_mcp/nis_tools.py | 176 +++++++ .../src/nis_elements_mcp/testing.py | 191 ++++++++ packages/nis-elements-mcp/tests/conftest.py | 8 + .../nis-elements-mcp/tests}/test_estop.py | 4 +- .../tests}/test_estop_panel.py | 8 +- .../tests}/test_nis_bridge.py | 181 +------ .../tests}/test_nis_events_monitor.py | 31 +- pyproject.toml | 8 +- tests/test_calibration.py | 2 +- tests/test_hardware_scripts.py | 1 + tests/test_small_gaps.py | 6 +- 37 files changed, 1935 insertions(+), 1596 deletions(-) create mode 100644 acquisition/_nis_settings.py create mode 100644 packages/nis-elements-mcp/README.md create mode 100644 packages/nis-elements-mcp/pyproject.toml create mode 100644 packages/nis-elements-mcp/src/nis_elements_mcp/__init__.py create mode 100644 packages/nis-elements-mcp/src/nis_elements_mcp/estop.py create mode 100644 packages/nis-elements-mcp/src/nis_elements_mcp/estop_panel.py create mode 100644 packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_client.py create mode 100644 packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_job.py create mode 100644 packages/nis-elements-mcp/src/nis_elements_mcp/nis_events.py create mode 100644 packages/nis-elements-mcp/src/nis_elements_mcp/nis_monitor.py create mode 100644 packages/nis-elements-mcp/src/nis_elements_mcp/nis_server.py create mode 100644 packages/nis-elements-mcp/src/nis_elements_mcp/nis_tools.py create mode 100644 packages/nis-elements-mcp/src/nis_elements_mcp/testing.py create mode 100644 packages/nis-elements-mcp/tests/conftest.py rename {tests => packages/nis-elements-mcp/tests}/test_estop.py (97%) rename {tests => packages/nis-elements-mcp/tests}/test_estop_panel.py (97%) rename {tests => packages/nis-elements-mcp/tests}/test_nis_bridge.py (70%) rename {tests => packages/nis-elements-mcp/tests}/test_nis_events_monitor.py (88%) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8936754..6d9a716 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -27,6 +27,9 @@ jobs: python -m pytest -v tests --cov=acquisition --cov=harness --cov=mcp_server --cov=timelapse --cov=analysis --cov-report=term-missing --cov-fail-under=90 + # The NIS-Elements MCP package (packages/nis-elements-mcp) has its own + # tests; the install above already pulled the package in. + - run: python -m pytest -v packages/nis-elements-mcp/tests # 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.) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d52f18..9ac459d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,16 @@ Format follows [Keep a Changelog](https://keepachangelog.com/); versions follow (`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. ### Added - `analysis/worm_short.py` - C. elegans Short from an AML18 time-lapse diff --git a/README.md b/README.md index 8040080..8c54326 100644 --- a/README.md +++ b/README.md @@ -73,7 +73,7 @@ python -m timelapse.frame_audit FRAME_DIR --timestamps times.csv --around 25h -- 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 +(`packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_job.py`) serves NIS macro calls on `127.0.0.1:8766`. The `nis-mcp` server talks to it and adds a confirm gate, the e-stop and a capture-folder rule. `baumer_ti2_server` is unchanged. Setup, safety rules and the on-scope test plan: diff --git a/acquisition/_nis_settings.py b/acquisition/_nis_settings.py new file mode 100644 index 0000000..d716211 --- /dev/null +++ b/acquisition/_nis_settings.py @@ -0,0 +1,21 @@ +# _nis_settings.py +# ------------------------------------------------------------ +# This repo's settings for the nis-elements-mcp package +# (packages/nis-elements-mcp). The package keeps its event log and +# captures under NIS_LOG_DIR / NIS_CAPTURE_DIR (default ~/nis-mcp/...); +# this repo keeps them where they always were: logs/nis and +# data/NIS/captures under the data folder (acquisition/paths.py). +# +# The forwarders that lead into the package (acquisition/nis_*.py, +# acquisition/backends/nis_bridge.py, mcp_server/nis/) import this first. +# A variable that is already set wins, so an MCP client config can still +# point them elsewhere. Child processes (the monitor window) inherit them. +# ------------------------------------------------------------ + +import os + +from acquisition import paths + +os.environ.setdefault("NIS_LOG_DIR", str(paths.logs_dir() / "nis")) +os.environ.setdefault("NIS_CAPTURE_DIR", os.environ.get("CONFOCAL_NIS_CAPTURE_DIR") + or str(paths.data_root() / "data" / "NIS" / "captures")) diff --git a/acquisition/backends/nis_bridge.py b/acquisition/backends/nis_bridge.py index 8d725c3..c38fcd8 100644 --- a/acquisition/backends/nis_bridge.py +++ b/acquisition/backends/nis_bridge.py @@ -1,163 +1,19 @@ # 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). +# Moved to the nis-elements-mcp package: nis_elements_mcp.nis_bridge_client +# (packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_client.py). +# This old name stays so existing imports and `python -m acquisition.backends.nis_bridge` +# keep working. It is the same module object, not a copy, so settings +# and test patches made through either name reach the same code. # ------------------------------------------------------------ -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)) +from acquisition import _nis_settings # noqa: F401 (this repo's log and capture folders) if __name__ == "__main__": - main() + import runpy + runpy.run_module("nis_elements_mcp.nis_bridge_client", run_name="__main__") +else: + from nis_elements_mcp import nis_bridge_client as _impl + sys.modules[__name__] = _impl diff --git a/acquisition/backends/nis_sdk.py b/acquisition/backends/nis_sdk.py index cdf6eff..26f52e4 100644 --- a/acquisition/backends/nis_sdk.py +++ b/acquisition/backends/nis_sdk.py @@ -194,7 +194,7 @@ def XY_Move(self, x: float, y: float) -> None: # E-STOP FIRST, before range checks, before anything. This is the # lowest point every XY move passes through, which is the only # place a stop can be effective against a caller that is already - # misbehaving - see acquisition/estop.py's header for the incident + # misbehaving - see nis_elements_mcp/estop.py's header for the incident # this exists because of. estop.check() before = self.XY_GetPosition() diff --git a/acquisition/calibration/nis_port_probe.py b/acquisition/calibration/nis_port_probe.py index 26a0b4b..10c6603 100644 --- a/acquisition/calibration/nis_port_probe.py +++ b/acquisition/calibration/nis_port_probe.py @@ -15,7 +15,7 @@ # 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); +# moves while the e-stop file exists (same file nis_elements_mcp/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 diff --git a/acquisition/estop.py b/acquisition/estop.py index 45ef17b..d54907b 100644 --- a/acquisition/estop.py +++ b/acquisition/estop.py @@ -1,210 +1,17 @@ # estop.py # ------------------------------------------------------------ -# Emergency stop for every process that can move this microscope. -# -# python -m acquisition.estop engage # STOP EVERYTHING, NOW -# python -m acquisition.estop status -# python -m acquisition.estop release # deliberate, separate action -# -# WHY THIS EXISTS. On 2026-09-21 a mosaic raster with a bad focus plane -# began driving Z toward the sample. Stopping it took several minutes and -# three separate interventions, because every mechanism available was the -# wrong shape: -# -# * stopping the background SHELL left its python CHILD running, still -# issuing moves - the process list, not the task list, was the truth -# * a tool call the operator REJECTED had already spawned its process, -# which kept looping Z moves regardless of the rejection -# * a "STOP file" checked once per mosaic tile is not a stop; between -# checks it still issued dozens of moves -# * the Ti2 SDK has NO abort/halt command (searched: only ZESCAPE, which -# is a retract, not a stop), so there is nothing to "cancel" with -# -# The lesson is that an e-stop must sit BELOW whatever is misbehaving. So -# this is enforced inside nis_sdk's move primitives themselves: no caller, -# no matter how confused, can move an axis while the stop is engaged, -# because the check happens after the caller has already decided to move. -# -# WHY A FILE. It must work across processes that do not know about each -# other - that was the whole failure. A file is visible to every process, -# survives the death of whoever set it, needs no server or port, and can -# be set by a human from any shell (or by creating the file by hand) when -# the agent itself is the thing malfunctioning. -# -# WHY A FIXED PATH, NOT data_root(). data_root() resolves relative to the -# working directory, and an MCP server launched by a desktop client gets a -# different cwd than a terminal. Two processes would then disagree about -# where the e-stop lives, which is precisely the failure this must not -# have. ESTOP_PATH is absolute and identical for every process on the -# machine. -# -# 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 -# refused move and a clear message, which is recoverable; the cost of -# failing open is a driven objective. -# -# WHAT IT DOES NOT DO: it cannot stop a move the controller has already -# accepted. A move in flight runs to its end; the stop takes effect at the -# next move. move_xy splits long moves into HOP_UM hops, so an XY move -# stops within one hop (measured: 0.54 s, <= 4 mm). -# -# WHY NO HALT. engage() used to also write the current position back as -# the target, to freeze an axis mid-travel. estop_inflight_test showed -# that is worse than nothing: position reads are cached for the whole move -# (XY and Z), so the "current" position is the START, and the write queues -# behind the move. A 1 mm Z move ran to its end, then the halt drove Z all -# the way back - a second move, issued by the stop. Never add it back. +# Moved to the nis-elements-mcp package: nis_elements_mcp.estop +# (packages/nis-elements-mcp/src/nis_elements_mcp/estop.py). +# This old name stays so existing imports and `python -m acquisition.estop` +# keep working. It is the same module object, not a copy, so settings +# and test patches made through either name reach the same code. # ------------------------------------------------------------ -from __future__ import annotations - -import argparse -import datetime -import json -import os -import subprocess import sys -from pathlib import Path - -#: 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")) - - -#: 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" - - -class EStopEngaged(RuntimeError): - """Raised by any motion primitive while the e-stop is engaged.""" - - -def is_engaged() -> bool: - """True if motion is currently forbidden. - - Any error resolving the state counts as engaged - see FAIL SAFE. - """ - try: - return ESTOP_PATH.exists() - except OSError: - return True - - -def details() -> dict | None: - """Who engaged the stop, when, and why - or None if it is clear.""" - try: - if not ESTOP_PATH.exists(): - return None - return json.loads(ESTOP_PATH.read_text(encoding="utf-8")) - except (OSError, ValueError): - # Present but unreadable still means engaged; say so without a reason. - return {"reason": "(e-stop file present but unreadable)"} - - -def check() -> None: - """Raise EStopEngaged if motion is forbidden. Called by every move.""" - if is_engaged(): - info = details() or {} - raise EStopEngaged( - "E-STOP ENGAGED - motion refused. " - f"engaged_at={info.get('engaged_at', '?')} " - f"by={info.get('by', '?')} reason={info.get('reason', '?')}. " - f"Release with: python -m acquisition.estop release " - f"(or delete {ESTOP_PATH})" - ) - - -def engage(reason: str = "manual") -> dict: - """Forbid all motion immediately. Sets the flag and nothing else. - - It never commands the stage - see WHY NO HALT in the module header. - """ - info = { - "engaged_at": datetime.datetime.now().isoformat(timespec="seconds"), - "by": f"pid {os.getpid()}", - "reason": reason, - } - ESTOP_PATH.parent.mkdir(parents=True, exist_ok=True) - ESTOP_PATH.write_text(json.dumps(info, indent=2), encoding="utf-8") - return info - - -def release() -> None: - """Allow motion again. Deliberately a separate, explicit action.""" - try: - ESTOP_PATH.unlink() - except FileNotFoundError: - pass - - - -def panel_running() -> bool: - """True if a STOP panel is already on screen (Windows only).""" - if sys.platform != "win32": - return False - import ctypes - k32 = ctypes.windll.kernel32 - h = k32.OpenMutexW(0x00100000, False, PANEL_MUTEX) # SYNCHRONIZE - if h: - k32.CloseHandle(h) - return True - return False - - -def launch_panel() -> None: - """Put the STOP panel on screen unless one is already there. - - Called when a process first connects to the real stage, so the button - appears however a run was started - MCP server, mosaic, timelapse, a - one-liner. The 2026-09-21 run was started from a terminal, where no - panel existed; a safety control you have to remember to start is one - you will not have. - - 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. - """ - if os.environ.get("CONFOCAL_NO_ESTOP_PANEL"): - return - try: - if panel_running(): - return - flags = getattr(subprocess, "CREATE_NO_WINDOW", 0) | getattr(subprocess, "DETACHED_PROCESS", 0) - subprocess.Popen([sys.executable, "-m", "acquisition.estop_panel"], - stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, creationflags=flags) - except Exception as exc: - print(f"[estop] could not start the STOP panel ({exc}). " - f"Stop manually with: python -m acquisition.estop engage", file=sys.stderr) - - -def main() -> None: - ap = argparse.ArgumentParser(description="Emergency stop for microscope motion.") - ap.add_argument("action", choices=("engage", "release", "status")) - ap.add_argument("--reason", default="manual") - args = ap.parse_args() - - if args.action == "engage": - info = engage(args.reason) - print("E-STOP ENGAGED") - for k, v in info.items(): - print(f" {k}: {v}") - print(f"\nflag file: {ESTOP_PATH}") - print("All motion is now refused. Release with: python -m acquisition.estop release") - elif args.action == "release": - release() - print(f"e-stop released - motion permitted again ({ESTOP_PATH} removed)") - else: - if is_engaged(): - print("ENGAGED - motion is refused") - for k, v in (details() or {}).items(): - print(f" {k}: {v}") - sys.exit(2) - print(f"clear - motion permitted (no {ESTOP_PATH})") - if __name__ == "__main__": - main() + import runpy + runpy.run_module("nis_elements_mcp.estop", run_name="__main__") +else: + from nis_elements_mcp import estop as _impl + sys.modules[__name__] = _impl diff --git a/acquisition/estop_panel.py b/acquisition/estop_panel.py index 0718b49..e0b53c4 100644 --- a/acquisition/estop_panel.py +++ b/acquisition/estop_panel.py @@ -1,174 +1,17 @@ # estop_panel.py # ------------------------------------------------------------ -# An always-on-top STOP button for the microscope. -# -# python -m acquisition.estop_panel -# -# Small, borderless, stays above other windows, drag it anywhere. One big -# button. Hitting it engages acquisition.estop, which every motion -# primitive checks before it moves - see that module's header. -# -# WHY A WINDOW AND NOT JUST THE CLI: during the 2026-09-21 incident the -# stage was moving while the operator hunted for a terminal, typed a -# command, and waited for python to start. Seconds matter and typing does -# not scale under stress. A button that is already on screen costs one -# click, with no target to find and nothing to remember. -# -# WHY IT POLLS THE FLAG FILE rather than tracking its own state: the stop -# can also be engaged from a terminal, from the MCP tool, by another -# process, or by a human creating the file. The panel must show what is -# actually true, not what it last did - a panel reading "CLEAR" while the -# stop is engaged elsewhere would be worse than no panel. -# -# WHY RELEASE IS DELIBERATELY AWKWARD: the release control is small, -# visually quiet, and asks for confirmation, while STOP is huge and -# instant. The asymmetry is the point - the cost of an accidental stop is -# a few seconds, the cost of an accidental release is an unguarded -# microscope. Engaging is also idempotent, so panic-clicking is harmless. -# -# ONE PANEL. It opens by itself whenever a process connects to the stage -# (estop.launch_panel), so many processes ask for it. The first takes the -# PANEL_MUTEX; any later copy sees it and exits without drawing. -# -# TKINTER because it ships with CPython: a safety control that depends on -# `pip install` is a safety control that is missing on the day it matters. +# Moved to the nis-elements-mcp package: nis_elements_mcp.estop_panel +# (packages/nis-elements-mcp/src/nis_elements_mcp/estop_panel.py). +# This old name stays so existing imports and `python -m acquisition.estop_panel` +# keep working. It is the same module object, not a copy, so settings +# and test patches made through either name reach the same code. # ------------------------------------------------------------ -from __future__ import annotations - -import argparse import sys -import tkinter as tk -from tkinter import messagebox - -from acquisition import estop - -POLL_MS = 300 - -_RED, _RED_DARK = "#c62828", "#8e0000" -_GREEN, _GREY = "#2e7d32", "#9e9e9e" -_BG = "#1b1b1b" - - -class Panel: - def __init__(self, root: tk.Tk, topmost: bool = True, borderless: bool = True): - self.root = root - root.title("E-STOP") - root.configure(bg=_BG) - root.resizable(False, False) - if topmost: - root.attributes("-topmost", True) - if borderless: - # No title bar - it would be most of a window this small, and - # the drag handler below replaces the only thing it was for. - root.overrideredirect(True) - root.geometry("+40+40") - - self.button = tk.Button( - root, text="STOP", font=("Segoe UI", 26, "bold"), - bg=_RED, fg="white", activebackground=_RED_DARK, activeforeground="white", - relief="raised", bd=3, width=8, height=1, cursor="hand2", - command=self.on_stop) - self.button.pack(padx=8, pady=(8, 4)) - - self.status = tk.Label(root, text="checking...", font=("Segoe UI", 9, "bold"), - bg=_BG, fg=_GREY) - self.status.pack() - - bar = tk.Frame(root, bg=_BG) - bar.pack(fill="x", padx=8, pady=(2, 6)) - # Quiet, small, and confirmed - see the header on asymmetry. - self.release_btn = tk.Button(bar, text="release", font=("Segoe UI", 8), - bg="#2a2a2a", fg="#bbb", relief="flat", - cursor="hand2", command=self.on_release) - self.release_btn.pack(side="left") - tk.Button(bar, text="✕", font=("Segoe UI", 8), bg="#2a2a2a", fg="#bbb", - relief="flat", cursor="hand2", command=root.destroy).pack(side="right") - - # Drag from anywhere on the background, since there is no title bar. - for w in (root, self.status, bar): - w.bind("", self._press) - w.bind("", self._drag) - self._dx = self._dy = 0 - - self._last = None - self.tick() - - def _press(self, e) -> None: - self._dx, self._dy = e.x_root - self.root.winfo_x(), e.y_root - self.root.winfo_y() - - def _drag(self, e) -> None: - self.root.geometry(f"+{e.x_root - self._dx}+{e.y_root - self._dy}") - - def on_stop(self) -> None: - # Engage first and report afterwards: the flag write is what makes - # the microscope safe, and it must not wait behind a dialog. - try: - estop.engage("STOP button") - except Exception as exc: - messagebox.showerror("E-STOP", f"Could not engage:\n{exc}") - self.refresh(force=True) - - def on_release(self) -> None: - if not estop.is_engaged(): - return - if messagebox.askyesno("Release e-stop", - "Allow the microscope to move again?\n\n" - "Only do this once you know why it stopped."): - estop.release() - self.refresh(force=True) - - def refresh(self, force: bool = False) -> None: - engaged = estop.is_engaged() - if engaged == self._last and not force: - return - self._last = engaged - if engaged: - self.status.configure(text="ENGAGED - motion refused", fg=_RED) - self.button.configure(text="STOPPED", bg=_RED_DARK) - self.release_btn.configure(state="normal") - else: - self.status.configure(text="clear - motion permitted", fg=_GREEN) - self.button.configure(text="STOP", bg=_RED) - self.release_btn.configure(state="disabled") - - def tick(self) -> None: - self.refresh() - self.root.after(POLL_MS, self.tick) - - -_mutex = None # kept for the life of the process; Windows frees it on exit - - -def _claim_single_instance() -> bool: - """Take the panel mutex; False if another panel already holds it.""" - global _mutex - if sys.platform != "win32": - return True - import ctypes - k32 = ctypes.windll.kernel32 - k32.CreateMutexW.restype = ctypes.c_void_p - _mutex = k32.CreateMutexW(None, False, estop.PANEL_MUTEX) - return k32.GetLastError() != 183 # ERROR_ALREADY_EXISTS - - -def main() -> None: - ap = argparse.ArgumentParser(description=__doc__) - ap.add_argument("--no-topmost", action="store_true") - ap.add_argument("--titlebar", action="store_true", help="keep a normal window frame") - args = ap.parse_args() - if not _claim_single_instance(): - print("a STOP panel is already open", file=sys.stderr) - return - try: - root = tk.Tk() - except tk.TclError as exc: - print(f"no display available for the e-stop panel ({exc}). " - f"Use: python -m acquisition.estop engage", file=sys.stderr) - raise SystemExit(1) - Panel(root, topmost=not args.no_topmost, borderless=not args.titlebar) - root.mainloop() - if __name__ == "__main__": - main() + import runpy + runpy.run_module("nis_elements_mcp.estop_panel", run_name="__main__") +else: + from nis_elements_mcp import estop_panel as _impl + sys.modules[__name__] = _impl diff --git a/acquisition/nis_bridge/bridge_job.py b/acquisition/nis_bridge/bridge_job.py index 436dff0..1e27d9e 100644 --- a/acquisition/nis_bridge/bridge_job.py +++ b/acquisition/nis_bridge/bridge_job.py @@ -1,438 +1,20 @@ -# 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. +# Moved to the nis-elements-mcp package: nis_elements_mcp.nis_bridge_job +# (packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_job.py). +# This old name stays so existing imports and `python -m acquisition.nis_bridge.bridge_job` +# keep working. It is the same module object, not a copy, so settings +# and test patches made through either name reach the same code. # -# 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 +# DO NOT PASTE THIS FILE INTO NIS. Paste the package file instead: +# packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_job.py # ------------------------------------------------------------ -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) -UI_TICK_MS = 50 # how often NIS's main thread looks for queued UI calls -UI_CALL_TIMEOUT_S = 600.0 # give up waiting for the main thread after this long -# "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 MainThread: - """Runs calls on NIS's main (UI) thread. - - Capture, ImageSaveAs, CloseCurrentDocument and the ND calls open or close - NIS windows. Called from the worker thread they crashed nis_ar.exe - (Qt5Core.dll, 0xc0000409, 2026-10-16). run() is the one place our code - is on the main thread, so it calls install(), which registers a Win32 - thread timer there. NIS's own message loop then calls _tick on the main - thread every UI_TICK_MS, and _tick runs what the worker queued with - call(). If install() was never called, call() refuses. - """ - - def __init__(self, tick_ms: int = UI_TICK_MS): - self.tick_ms = tick_ms - self.installed = False - self._jobs = queue.Queue() - self._busy = False # a call is running: do not re-enter from a nested message loop - self._timer_proc = None # keep the ctypes callback alive - self.main_thread_id = None - - def install(self) -> None: - """Call from the main thread only (JOBS run()).""" - from ctypes import wintypes - user32 = ct.windll.user32 - proc_type = ct.WINFUNCTYPE(None, wintypes.HWND, wintypes.UINT, ct.c_size_t, wintypes.DWORD) - self._timer_proc = proc_type(lambda hwnd, msg, tid, tick: self._tick()) - user32.SetTimer.argtypes = [wintypes.HWND, ct.c_size_t, wintypes.UINT, proc_type] - user32.SetTimer.restype = ct.c_size_t - if not user32.SetTimer(None, 0, self.tick_ms, self._timer_proc): - raise OSError("SetTimer failed") - self.main_thread_id = threading.get_ident() - self.installed = True - - def _tick(self) -> None: - if self._busy: - return - self._busy = True - try: - while True: - try: - fn, box, cancelled = self._jobs.get_nowait() - except queue.Empty: - return - if cancelled.is_set(): # the caller timed out: do not start it late - continue - try: - box.put(fn()) - except Exception as e: - box.put({"error": f"{type(e).__name__}: {e}"}) - finally: - self._busy = False - - def call(self, fn, timeout_s: float = UI_CALL_TIMEOUT_S) -> dict: - if not self.installed: - return {"error": "no NIS main-thread hook: this call crashes NIS from the worker thread"} - box, cancelled = queue.Queue(), threading.Event() - self._jobs.put((fn, box, cancelled)) - try: - return box.get(timeout=timeout_s) - except queue.Empty: - cancelled.set() - return {"error": f"NIS's main thread did not run the call within {timeout_s:.0f} s"} - - -class Bridge: - """The operations, as plain methods returning JSON-able dicts.""" - - def __init__(self, macro: Macro, ui: MainThread | None = None): - self.m = macro - self.ui = ui or MainThread() # not installed: UI calls are refused - - 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"} - - def on_main_thread() -> dict: - if _estop_engaged(): # re-check: the call may have waited in the queue - return {"error": "e-stop engaged - capture refused", "estop_engaged": True} - 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)} - return self.ui.call(on_main_thread) - - def nd_run(self, experiment: str) -> dict: - if (r := self._refuse_if_stopped("ND run")): - return r - - def on_main_thread() -> dict: - if _estop_engaged(): - return {"error": "e-stop engaged - ND run refused", "estop_engaged": True} - 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())} - return self.ui.call(on_main_thread) - - def nd_finish(self) -> dict: - # Always allowed, e-stop or not: it only ends a run early. - def on_main_thread() -> dict: - rc = self.m.ND_FinishExperiment() - return {"rc": rc, "nd_running": bool(self.m.ND_IsInExperimentCapture())} - return self.ui.call(on_main_thread) - - -# 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") +import sys -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.""" - ui = MainThread() - try: - ui.install() # run() is on NIS's main thread: hook it for UI calls - except Exception as e: - print(f"NIS bridge: no main-thread hook ({type(e).__name__}: {e}); capture and ND calls refused") - threading.Thread(target=serve, args=(Bridge(Macro(), ui),), name="nis-bridge", - daemon=True).start() +if __name__ == "__main__": + import runpy + runpy.run_module("nis_elements_mcp.nis_bridge_job", run_name="__main__") +else: + from nis_elements_mcp import nis_bridge_job as _impl + sys.modules[__name__] = _impl diff --git a/acquisition/nis_events.py b/acquisition/nis_events.py index db939ee..8574116 100644 --- a/acquisition/nis_events.py +++ b/acquisition/nis_events.py @@ -1,100 +1,19 @@ # 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. +# Moved to the nis-elements-mcp package: nis_elements_mcp.nis_events +# (packages/nis-elements-mcp/src/nis_elements_mcp/nis_events.py). +# This old name stays so existing imports and `python -m acquisition.nis_events` +# keep working. It is the same module object, not a copy, so settings +# and test patches made through either name reach the same code. # ------------------------------------------------------------ -from __future__ import annotations +import sys -import datetime -import json -from pathlib import Path +from acquisition import _nis_settings # noqa: F401 (this repo's log and capture folders) -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 "?" +if __name__ == "__main__": + import runpy + runpy.run_module("nis_elements_mcp.nis_events", run_name="__main__") +else: + from nis_elements_mcp import nis_events as _impl + sys.modules[__name__] = _impl diff --git a/acquisition/nis_monitor.py b/acquisition/nis_monitor.py index 29afb69..358ad91 100644 --- a/acquisition/nis_monitor.py +++ b/acquisition/nis_monitor.py @@ -1,197 +1,19 @@ # 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. +# Moved to the nis-elements-mcp package: nis_elements_mcp.nis_monitor +# (packages/nis-elements-mcp/src/nis_elements_mcp/nis_monitor.py). +# This old name stays so existing imports and `python -m acquisition.nis_monitor` +# keep working. It is the same module object, not a copy, so settings +# and test patches made through either name reach the same code. # ------------------------------------------------------------ -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 +from acquisition import _nis_settings # noqa: F401 (this repo's log and capture folders) if __name__ == "__main__": - main() + import runpy + runpy.run_module("nis_elements_mcp.nis_monitor", run_name="__main__") +else: + from nis_elements_mcp import nis_monitor as _impl + sys.modules[__name__] = _impl diff --git a/docs/nis-bridge.md b/docs/nis-bridge.md index d021a97..124a692 100644 --- a/docs/nis-bridge.md +++ b/docs/nis-bridge.md @@ -14,16 +14,20 @@ for real work. ## How it fits together +All of these files are in the `nis-elements-mcp` package, +`packages/nis-elements-mcp/src/nis_elements_mcp/`. The old paths in +`acquisition/` and `mcp_server/nis/` forward to them. + ``` MCP client (Claude) │ stdio ▼ -mcp_server/nis/nis_server.py confirm gate, capture-folder rule, estop tool +nis_server.py / nis_tools.py confirm gate, capture-folder rule, estop tool │ -acquisition/backends/nis_bridge.py e-stop checked before sending +nis_bridge_client.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 +nis_bridge_job.py JOBS Python task, runs inside nis_ar.exe │ ctypes ▼ g5_regprocs.dll (NIS macro functions: StgMoveXY, Stg_SetNosepiecePosition, Capture, ND_RunExperiment, ...) @@ -51,7 +55,9 @@ separate server, `nis-mcp`. 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 + `packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_job.py` + (not `acquisition/nis_bridge/bridge_job.py`, which only forwards to it), + 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 `. diff --git a/mcp_server/nis/__init__.py b/mcp_server/nis/__init__.py index c928f18..31c9a2b 100644 --- a/mcp_server/nis/__init__.py +++ b/mcp_server/nis/__init__.py @@ -1,5 +1,6 @@ """MCP server for NIS-Elements, reached through the bridge job running inside NIS. -nis_server.py registers the tools; nis_tools.py implements them. -Run with `nis-mcp` or `python -m mcp_server.nis.nis_server`. +The code lives in the nis-elements-mcp package (packages/nis-elements-mcp); +nis_server.py and nis_tools.py here forward to it, with this repo's log and +capture folders. Run with `confocal-mcp-nis` or `python -m mcp_server.nis.nis_server`. """ diff --git a/mcp_server/nis/nis_server.py b/mcp_server/nis/nis_server.py index 9a89421..9a499a5 100644 --- a/mcp_server/nis/nis_server.py +++ b/mcp_server/nis/nis_server.py @@ -1,42 +1,19 @@ # nis_server.py # ------------------------------------------------------------ -# MCP server for driving the microscope through NIS-Elements (see -# nis_tools.py). Separate from baumer_ti2_server.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: -# nis-mcp (installed console script; the old name -# confocal-mcp-nis still works) -# python -m mcp_server.nis.nis_server (from a source checkout) -# -# { "mcpServers": { "nis": { "command": "nis-mcp" } } } +# Moved to the nis-elements-mcp package: nis_elements_mcp.nis_server +# (packages/nis-elements-mcp/src/nis_elements_mcp/nis_server.py). +# This old name stays so existing imports and `python -m mcp_server.nis.nis_server` +# keep working. It is the same module object, not a copy, so settings +# and test patches made through either name reach the same code. # ------------------------------------------------------------ -from mcp.server.mcpserver import MCPServer - -from acquisition import estop, nis_monitor -from mcp_server.baumer_ti2 import baumer_ti2_tools -from mcp_server.nis import 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(baumer_ti2_tools.estop) # the same e-stop, reachable from this server too - - -def main() -> None: - """Console entry point (``nis-mcp``): serve the NIS tools over stdio.""" - estop.launch_panel() - nis_monitor.launch() # live view of what this server does - mcp.run(transport="stdio") +import sys +from acquisition import _nis_settings # noqa: F401 (this repo's log and capture folders) if __name__ == "__main__": - main() + import runpy + runpy.run_module("nis_elements_mcp.nis_server", run_name="__main__") +else: + from nis_elements_mcp import nis_server as _impl + sys.modules[__name__] = _impl diff --git a/mcp_server/nis/nis_tools.py b/mcp_server/nis/nis_tools.py index b3ead4b..08a5557 100644 --- a/mcp_server/nis/nis_tools.py +++ b/mcp_server/nis/nis_tools.py @@ -1,130 +1,19 @@ # 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/nis/nis_server.py - kept apart from baumer_ti2_tools.py, which -# by team direction has exactly its agreed tools and no NIS-Elements. -# -# WHAT THIS ADDS over baumer_ti2_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 baumer_ti2_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 +# Moved to the nis-elements-mcp package: nis_elements_mcp.nis_tools +# (packages/nis-elements-mcp/src/nis_elements_mcp/nis_tools.py). +# This old name stays so existing imports and `python -m mcp_server.nis.nis_tools` +# keep working. It is the same module object, not a copy, so settings +# and test patches made through either name reach the same code. # ------------------------------------------------------------ -from __future__ import annotations +import sys -import json -import os -import re -from pathlib import Path +from acquisition import _nis_settings # noqa: F401 (this repo's log and capture folders) -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()) +if __name__ == "__main__": + import runpy + runpy.run_module("nis_elements_mcp.nis_tools", run_name="__main__") +else: + from nis_elements_mcp import nis_tools as _impl + sys.modules[__name__] = _impl diff --git a/packages/nis-elements-mcp/README.md b/packages/nis-elements-mcp/README.md new file mode 100644 index 0000000..aca6ba5 --- /dev/null +++ b/packages/nis-elements-mcp/README.md @@ -0,0 +1,7 @@ +# nis-elements-mcp + +Drive a Nikon NIS-Elements microscope from an MCP client (such as Claude +Code), through a small bridge job that runs inside NIS-Elements. + +Work in progress: setup, safety rules, settings and install instructions +follow in version 0.1.0. diff --git a/packages/nis-elements-mcp/pyproject.toml b/packages/nis-elements-mcp/pyproject.toml new file mode 100644 index 0000000..d76a64c --- /dev/null +++ b/packages/nis-elements-mcp/pyproject.toml @@ -0,0 +1,25 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "nis-elements-mcp" +version = "0.1.0" +description = "MCP server that drives a Nikon NIS-Elements microscope through a bridge job running inside NIS" +readme = "README.md" +requires-python = ">=3.11" +dependencies = [ + "mcp>=2.0,<3", +] + +[project.optional-dependencies] +test = ["pytest>=8"] + +[project.scripts] +nis-mcp = "nis_elements_mcp.nis_server:main" + +[tool.hatch.build.targets.wheel] +packages = ["src/nis_elements_mcp"] + +[tool.pytest.ini_options] +testpaths = ["tests"] diff --git a/packages/nis-elements-mcp/src/nis_elements_mcp/__init__.py b/packages/nis-elements-mcp/src/nis_elements_mcp/__init__.py new file mode 100644 index 0000000..709563c --- /dev/null +++ b/packages/nis-elements-mcp/src/nis_elements_mcp/__init__.py @@ -0,0 +1,8 @@ +"""Drive a Nikon NIS-Elements microscope from an MCP client, through a bridge job running inside NIS.""" + +from importlib.metadata import PackageNotFoundError, version + +try: + __version__ = version("nis-elements-mcp") +except PackageNotFoundError: # running from a source tree that was never installed + __version__ = "0.0.0+unknown" diff --git a/packages/nis-elements-mcp/src/nis_elements_mcp/estop.py b/packages/nis-elements-mcp/src/nis_elements_mcp/estop.py new file mode 100644 index 0000000..f01b695 --- /dev/null +++ b/packages/nis-elements-mcp/src/nis_elements_mcp/estop.py @@ -0,0 +1,210 @@ +# estop.py +# ------------------------------------------------------------ +# Emergency stop for every process that can move this microscope. +# +# python -m nis_elements_mcp.estop engage # STOP EVERYTHING, NOW +# python -m nis_elements_mcp.estop status +# python -m nis_elements_mcp.estop release # deliberate, separate action +# +# WHY THIS EXISTS. On 2026-09-21 a mosaic raster with a bad focus plane +# began driving Z toward the sample. Stopping it took several minutes and +# three separate interventions, because every mechanism available was the +# wrong shape: +# +# * stopping the background SHELL left its python CHILD running, still +# issuing moves - the process list, not the task list, was the truth +# * a tool call the operator REJECTED had already spawned its process, +# which kept looping Z moves regardless of the rejection +# * a "STOP file" checked once per mosaic tile is not a stop; between +# checks it still issued dozens of moves +# * the Ti2 SDK has NO abort/halt command (searched: only ZESCAPE, which +# is a retract, not a stop), so there is nothing to "cancel" with +# +# The lesson is that an e-stop must sit BELOW whatever is misbehaving. So +# this is enforced inside nis_sdk's move primitives themselves: no caller, +# no matter how confused, can move an axis while the stop is engaged, +# because the check happens after the caller has already decided to move. +# +# WHY A FILE. It must work across processes that do not know about each +# other - that was the whole failure. A file is visible to every process, +# survives the death of whoever set it, needs no server or port, and can +# be set by a human from any shell (or by creating the file by hand) when +# the agent itself is the thing malfunctioning. +# +# WHY A FIXED PATH, NOT data_root(). data_root() resolves relative to the +# working directory, and an MCP server launched by a desktop client gets a +# different cwd than a terminal. Two processes would then disagree about +# where the e-stop lives, which is precisely the failure this must not +# have. ESTOP_PATH is absolute and identical for every process on the +# machine. +# +# 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 +# refused move and a clear message, which is recoverable; the cost of +# failing open is a driven objective. +# +# WHAT IT DOES NOT DO: it cannot stop a move the controller has already +# accepted. A move in flight runs to its end; the stop takes effect at the +# next move. move_xy splits long moves into HOP_UM hops, so an XY move +# stops within one hop (measured: 0.54 s, <= 4 mm). +# +# WHY NO HALT. engage() used to also write the current position back as +# the target, to freeze an axis mid-travel. estop_inflight_test showed +# that is worse than nothing: position reads are cached for the whole move +# (XY and Z), so the "current" position is the START, and the write queues +# behind the move. A 1 mm Z move ran to its end, then the halt drove Z all +# the way back - a second move, issued by the stop. Never add it back. +# ------------------------------------------------------------ + +from __future__ import annotations + +import argparse +import datetime +import json +import os +import subprocess +import sys +from pathlib import Path + +#: 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")) + + +#: 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" + + +class EStopEngaged(RuntimeError): + """Raised by any motion primitive while the e-stop is engaged.""" + + +def is_engaged() -> bool: + """True if motion is currently forbidden. + + Any error resolving the state counts as engaged - see FAIL SAFE. + """ + try: + return ESTOP_PATH.exists() + except OSError: + return True + + +def details() -> dict | None: + """Who engaged the stop, when, and why - or None if it is clear.""" + try: + if not ESTOP_PATH.exists(): + return None + return json.loads(ESTOP_PATH.read_text(encoding="utf-8")) + except (OSError, ValueError): + # Present but unreadable still means engaged; say so without a reason. + return {"reason": "(e-stop file present but unreadable)"} + + +def check() -> None: + """Raise EStopEngaged if motion is forbidden. Called by every move.""" + if is_engaged(): + info = details() or {} + raise EStopEngaged( + "E-STOP ENGAGED - motion refused. " + f"engaged_at={info.get('engaged_at', '?')} " + f"by={info.get('by', '?')} reason={info.get('reason', '?')}. " + f"Release with: python -m nis_elements_mcp.estop release " + f"(or delete {ESTOP_PATH})" + ) + + +def engage(reason: str = "manual") -> dict: + """Forbid all motion immediately. Sets the flag and nothing else. + + It never commands the stage - see WHY NO HALT in the module header. + """ + info = { + "engaged_at": datetime.datetime.now().isoformat(timespec="seconds"), + "by": f"pid {os.getpid()}", + "reason": reason, + } + ESTOP_PATH.parent.mkdir(parents=True, exist_ok=True) + ESTOP_PATH.write_text(json.dumps(info, indent=2), encoding="utf-8") + return info + + +def release() -> None: + """Allow motion again. Deliberately a separate, explicit action.""" + try: + ESTOP_PATH.unlink() + except FileNotFoundError: + pass + + + +def panel_running() -> bool: + """True if a STOP panel is already on screen (Windows only).""" + if sys.platform != "win32": + return False + import ctypes + k32 = ctypes.windll.kernel32 + h = k32.OpenMutexW(0x00100000, False, PANEL_MUTEX) # SYNCHRONIZE + if h: + k32.CloseHandle(h) + return True + return False + + +def launch_panel() -> None: + """Put the STOP panel on screen unless one is already there. + + Called when a process first connects to the real stage, so the button + appears however a run was started - MCP server, mosaic, timelapse, a + one-liner. The 2026-09-21 run was started from a terminal, where no + panel existed; a safety control you have to remember to start is one + you will not have. + + 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. + """ + if os.environ.get("CONFOCAL_NO_ESTOP_PANEL"): + return + try: + if panel_running(): + return + flags = getattr(subprocess, "CREATE_NO_WINDOW", 0) | getattr(subprocess, "DETACHED_PROCESS", 0) + subprocess.Popen([sys.executable, "-m", "nis_elements_mcp.estop_panel"], + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, creationflags=flags) + except Exception as exc: + print(f"[estop] could not start the STOP panel ({exc}). " + f"Stop manually with: python -m nis_elements_mcp.estop engage", file=sys.stderr) + + +def main() -> None: + ap = argparse.ArgumentParser(description="Emergency stop for microscope motion.") + ap.add_argument("action", choices=("engage", "release", "status")) + ap.add_argument("--reason", default="manual") + args = ap.parse_args() + + if args.action == "engage": + info = engage(args.reason) + print("E-STOP ENGAGED") + for k, v in info.items(): + print(f" {k}: {v}") + print(f"\nflag file: {ESTOP_PATH}") + print("All motion is now refused. Release with: python -m nis_elements_mcp.estop release") + elif args.action == "release": + release() + print(f"e-stop released - motion permitted again ({ESTOP_PATH} removed)") + else: + if is_engaged(): + print("ENGAGED - motion is refused") + for k, v in (details() or {}).items(): + print(f" {k}: {v}") + sys.exit(2) + print(f"clear - motion permitted (no {ESTOP_PATH})") + + +if __name__ == "__main__": + main() diff --git a/packages/nis-elements-mcp/src/nis_elements_mcp/estop_panel.py b/packages/nis-elements-mcp/src/nis_elements_mcp/estop_panel.py new file mode 100644 index 0000000..8b849cf --- /dev/null +++ b/packages/nis-elements-mcp/src/nis_elements_mcp/estop_panel.py @@ -0,0 +1,174 @@ +# estop_panel.py +# ------------------------------------------------------------ +# An always-on-top STOP button for the microscope. +# +# python -m nis_elements_mcp.estop_panel +# +# Small, borderless, stays above other windows, drag it anywhere. One big +# button. Hitting it engages nis_elements_mcp.estop, which every motion +# primitive checks before it moves - see that module's header. +# +# WHY A WINDOW AND NOT JUST THE CLI: during the 2026-09-21 incident the +# stage was moving while the operator hunted for a terminal, typed a +# command, and waited for python to start. Seconds matter and typing does +# not scale under stress. A button that is already on screen costs one +# click, with no target to find and nothing to remember. +# +# WHY IT POLLS THE FLAG FILE rather than tracking its own state: the stop +# can also be engaged from a terminal, from the MCP tool, by another +# process, or by a human creating the file. The panel must show what is +# actually true, not what it last did - a panel reading "CLEAR" while the +# stop is engaged elsewhere would be worse than no panel. +# +# WHY RELEASE IS DELIBERATELY AWKWARD: the release control is small, +# visually quiet, and asks for confirmation, while STOP is huge and +# instant. The asymmetry is the point - the cost of an accidental stop is +# a few seconds, the cost of an accidental release is an unguarded +# microscope. Engaging is also idempotent, so panic-clicking is harmless. +# +# ONE PANEL. It opens by itself whenever a process connects to the stage +# (estop.launch_panel), so many processes ask for it. The first takes the +# PANEL_MUTEX; any later copy sees it and exits without drawing. +# +# TKINTER because it ships with CPython: a safety control that depends on +# `pip install` is a safety control that is missing on the day it matters. +# ------------------------------------------------------------ + +from __future__ import annotations + +import argparse +import sys +import tkinter as tk +from tkinter import messagebox + +from nis_elements_mcp import estop + +POLL_MS = 300 + +_RED, _RED_DARK = "#c62828", "#8e0000" +_GREEN, _GREY = "#2e7d32", "#9e9e9e" +_BG = "#1b1b1b" + + +class Panel: + def __init__(self, root: tk.Tk, topmost: bool = True, borderless: bool = True): + self.root = root + root.title("E-STOP") + root.configure(bg=_BG) + root.resizable(False, False) + if topmost: + root.attributes("-topmost", True) + if borderless: + # No title bar - it would be most of a window this small, and + # the drag handler below replaces the only thing it was for. + root.overrideredirect(True) + root.geometry("+40+40") + + self.button = tk.Button( + root, text="STOP", font=("Segoe UI", 26, "bold"), + bg=_RED, fg="white", activebackground=_RED_DARK, activeforeground="white", + relief="raised", bd=3, width=8, height=1, cursor="hand2", + command=self.on_stop) + self.button.pack(padx=8, pady=(8, 4)) + + self.status = tk.Label(root, text="checking...", font=("Segoe UI", 9, "bold"), + bg=_BG, fg=_GREY) + self.status.pack() + + bar = tk.Frame(root, bg=_BG) + bar.pack(fill="x", padx=8, pady=(2, 6)) + # Quiet, small, and confirmed - see the header on asymmetry. + self.release_btn = tk.Button(bar, text="release", font=("Segoe UI", 8), + bg="#2a2a2a", fg="#bbb", relief="flat", + cursor="hand2", command=self.on_release) + self.release_btn.pack(side="left") + tk.Button(bar, text="✕", font=("Segoe UI", 8), bg="#2a2a2a", fg="#bbb", + relief="flat", cursor="hand2", command=root.destroy).pack(side="right") + + # Drag from anywhere on the background, since there is no title bar. + for w in (root, self.status, bar): + w.bind("", self._press) + w.bind("", self._drag) + self._dx = self._dy = 0 + + self._last = None + self.tick() + + def _press(self, e) -> None: + self._dx, self._dy = e.x_root - self.root.winfo_x(), e.y_root - self.root.winfo_y() + + def _drag(self, e) -> None: + self.root.geometry(f"+{e.x_root - self._dx}+{e.y_root - self._dy}") + + def on_stop(self) -> None: + # Engage first and report afterwards: the flag write is what makes + # the microscope safe, and it must not wait behind a dialog. + try: + estop.engage("STOP button") + except Exception as exc: + messagebox.showerror("E-STOP", f"Could not engage:\n{exc}") + self.refresh(force=True) + + def on_release(self) -> None: + if not estop.is_engaged(): + return + if messagebox.askyesno("Release e-stop", + "Allow the microscope to move again?\n\n" + "Only do this once you know why it stopped."): + estop.release() + self.refresh(force=True) + + def refresh(self, force: bool = False) -> None: + engaged = estop.is_engaged() + if engaged == self._last and not force: + return + self._last = engaged + if engaged: + self.status.configure(text="ENGAGED - motion refused", fg=_RED) + self.button.configure(text="STOPPED", bg=_RED_DARK) + self.release_btn.configure(state="normal") + else: + self.status.configure(text="clear - motion permitted", fg=_GREEN) + self.button.configure(text="STOP", bg=_RED) + self.release_btn.configure(state="disabled") + + def tick(self) -> None: + self.refresh() + self.root.after(POLL_MS, self.tick) + + +_mutex = None # kept for the life of the process; Windows frees it on exit + + +def _claim_single_instance() -> bool: + """Take the panel mutex; False if another panel already holds it.""" + global _mutex + if sys.platform != "win32": + return True + import ctypes + k32 = ctypes.windll.kernel32 + k32.CreateMutexW.restype = ctypes.c_void_p + _mutex = k32.CreateMutexW(None, False, estop.PANEL_MUTEX) + return k32.GetLastError() != 183 # ERROR_ALREADY_EXISTS + + +def main() -> None: + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--no-topmost", action="store_true") + ap.add_argument("--titlebar", action="store_true", help="keep a normal window frame") + args = ap.parse_args() + if not _claim_single_instance(): + print("a STOP panel is already open", file=sys.stderr) + return + try: + root = tk.Tk() + except tk.TclError as exc: + print(f"no display available for the e-stop panel ({exc}). " + f"Use: python -m nis_elements_mcp.estop engage", file=sys.stderr) + raise SystemExit(1) + Panel(root, topmost=not args.no_topmost, borderless=not args.titlebar) + root.mainloop() + + +if __name__ == "__main__": + main() diff --git a/packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_client.py b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_client.py new file mode 100644 index 0000000..586c550 --- /dev/null +++ b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_client.py @@ -0,0 +1,163 @@ +# nis_bridge.py +# ------------------------------------------------------------ +# Client for the NIS bridge (nis_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 nis_elements_mcp.nis_bridge_client status +# python -m nis_elements_mcp.nis_bridge_client move 100 0 +# python -m nis_elements_mcp.nis_bridge_client objective "Plan Fluor 10x Ph1 DLL" +# python -m nis_elements_mcp.nis_bridge_client optconfs +# python -m nis_elements_mcp.nis_bridge_client capture D:\...\check.nd2 +# python -m nis_elements_mcp.nis_bridge_client nd-run "C. elegans 3h" +# python -m nis_elements_mcp.nis_bridge_client nd-finish +# python -m nis_elements_mcp.nis_bridge_client 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 +# (nis_events.py), which `python -m nis_elements_mcp.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 nis_elements_mcp 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/packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_job.py b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_job.py new file mode 100644 index 0000000..c4915eb --- /dev/null +++ b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_job.py @@ -0,0 +1,440 @@ +# 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 nis_bridge_client.py (and +# through it the NIS MCP server) talks to. This file must stay standalone: +# NIS's own Python has only the standard library, so nothing here may +# import from nis_elements_mcp. +# +# 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 nis_elements_mcp.nis_bridge_client 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 +# 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) +UI_TICK_MS = 50 # how often NIS's main thread looks for queued UI calls +UI_CALL_TIMEOUT_S = 600.0 # give up waiting for the main thread after this long +# "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 MainThread: + """Runs calls on NIS's main (UI) thread. + + Capture, ImageSaveAs, CloseCurrentDocument and the ND calls open or close + NIS windows. Called from the worker thread they crashed nis_ar.exe + (Qt5Core.dll, 0xc0000409, 2026-10-16). run() is the one place our code + is on the main thread, so it calls install(), which registers a Win32 + thread timer there. NIS's own message loop then calls _tick on the main + thread every UI_TICK_MS, and _tick runs what the worker queued with + call(). If install() was never called, call() refuses. + """ + + def __init__(self, tick_ms: int = UI_TICK_MS): + self.tick_ms = tick_ms + self.installed = False + self._jobs = queue.Queue() + self._busy = False # a call is running: do not re-enter from a nested message loop + self._timer_proc = None # keep the ctypes callback alive + self.main_thread_id = None + + def install(self) -> None: + """Call from the main thread only (JOBS run()).""" + from ctypes import wintypes + user32 = ct.windll.user32 + proc_type = ct.WINFUNCTYPE(None, wintypes.HWND, wintypes.UINT, ct.c_size_t, wintypes.DWORD) + self._timer_proc = proc_type(lambda hwnd, msg, tid, tick: self._tick()) + user32.SetTimer.argtypes = [wintypes.HWND, ct.c_size_t, wintypes.UINT, proc_type] + user32.SetTimer.restype = ct.c_size_t + if not user32.SetTimer(None, 0, self.tick_ms, self._timer_proc): + raise OSError("SetTimer failed") + self.main_thread_id = threading.get_ident() + self.installed = True + + def _tick(self) -> None: + if self._busy: + return + self._busy = True + try: + while True: + try: + fn, box, cancelled = self._jobs.get_nowait() + except queue.Empty: + return + if cancelled.is_set(): # the caller timed out: do not start it late + continue + try: + box.put(fn()) + except Exception as e: + box.put({"error": f"{type(e).__name__}: {e}"}) + finally: + self._busy = False + + def call(self, fn, timeout_s: float = UI_CALL_TIMEOUT_S) -> dict: + if not self.installed: + return {"error": "no NIS main-thread hook: this call crashes NIS from the worker thread"} + box, cancelled = queue.Queue(), threading.Event() + self._jobs.put((fn, box, cancelled)) + try: + return box.get(timeout=timeout_s) + except queue.Empty: + cancelled.set() + return {"error": f"NIS's main thread did not run the call within {timeout_s:.0f} s"} + + +class Bridge: + """The operations, as plain methods returning JSON-able dicts.""" + + def __init__(self, macro: Macro, ui: MainThread | None = None): + self.m = macro + self.ui = ui or MainThread() # not installed: UI calls are refused + + 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"} + + def on_main_thread() -> dict: + if _estop_engaged(): # re-check: the call may have waited in the queue + return {"error": "e-stop engaged - capture refused", "estop_engaged": True} + 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)} + return self.ui.call(on_main_thread) + + def nd_run(self, experiment: str) -> dict: + if (r := self._refuse_if_stopped("ND run")): + return r + + def on_main_thread() -> dict: + if _estop_engaged(): + return {"error": "e-stop engaged - ND run refused", "estop_engaged": True} + 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())} + return self.ui.call(on_main_thread) + + def nd_finish(self) -> dict: + # Always allowed, e-stop or not: it only ends a run early. + def on_main_thread() -> dict: + rc = self.m.ND_FinishExperiment() + return {"rc": rc, "nd_running": bool(self.m.ND_IsInExperimentCapture())} + return self.ui.call(on_main_thread) + + +# 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.""" + ui = MainThread() + try: + ui.install() # run() is on NIS's main thread: hook it for UI calls + except Exception as e: + print(f"NIS bridge: no main-thread hook ({type(e).__name__}: {e}); capture and ND calls refused") + threading.Thread(target=serve, args=(Bridge(Macro(), ui),), name="nis-bridge", + daemon=True).start() diff --git a/packages/nis-elements-mcp/src/nis_elements_mcp/nis_events.py b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_events.py new file mode 100644 index 0000000..816ff9f --- /dev/null +++ b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_events.py @@ -0,0 +1,101 @@ +# nis_events.py +# ------------------------------------------------------------ +# The NIS event log: one JSON line per thing done through the NIS bridge, +# appended to /events-YYYY-MM-DD.jsonl (default +# ~/nis-mcp/logs). Whoever drives the bridge +# (the NIS MCP server, a script, the command line) writes here, and +# 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 +import os +from pathlib import Path + +PHASES = ("start", "ok", "failed", "refused", "error") + + +def events_dir() -> Path: + """NIS_LOG_DIR, else ~/nis-mcp/logs. Read on every call, so a change takes effect at once.""" + return Path(os.environ.get("NIS_LOG_DIR") or Path.home() / "nis-mcp" / "logs") + + +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/packages/nis-elements-mcp/src/nis_elements_mcp/nis_monitor.py b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_monitor.py new file mode 100644 index 0000000..b1ef6d8 --- /dev/null +++ b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_monitor.py @@ -0,0 +1,197 @@ +# nis_monitor.py +# ------------------------------------------------------------ +# Live terminal view of the NIS bridge. Run it in its own window: +# +# python -m nis_elements_mcp.nis_monitor # refresh every 1 s, Ctrl+C to leave +# python -m nis_elements_mcp.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, 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 nis_elements_mcp import estop, nis_events +from nis_elements_mcp.nis_bridge_client 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", "nis_elements_mcp.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 nis_elements_mcp.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/packages/nis-elements-mcp/src/nis_elements_mcp/nis_server.py b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_server.py new file mode 100644 index 0000000..ceb88e5 --- /dev/null +++ b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_server.py @@ -0,0 +1,38 @@ +# nis_server.py +# ------------------------------------------------------------ +# MCP server for driving the microscope through NIS-Elements (see +# nis_tools.py). Needs the NIS bridge job (nis_bridge_job.py) running +# inside NIS. +# +# Run, either way: +# nis-mcp (installed console script) +# python -m nis_elements_mcp.nis_server +# +# { "mcpServers": { "nis": { "command": "nis-mcp" } } } +# ------------------------------------------------------------ + +from mcp.server.mcpserver import MCPServer + +from nis_elements_mcp import estop, nis_monitor, 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(nis_tools.estop) + + +def main() -> None: + """Console entry point (``nis-mcp``): 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/packages/nis-elements-mcp/src/nis_elements_mcp/nis_tools.py b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_tools.py new file mode 100644 index 0000000..9250ad9 --- /dev/null +++ b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_tools.py @@ -0,0 +1,176 @@ +# nis_tools.py +# ------------------------------------------------------------ +# MCP tools that drive the microscope THROUGH NIS-Elements, via the NIS +# bridge (nis_bridge_job.py, running as a JOBS task; client in +# nis_bridge_client.py). Served by nis_server.py. +# +# WHAT THEY DO: read the stage, objective and ND state; move XY; change +# objective; capture with the optical configuration active in NIS; run +# and end ND experiments saved in NIS; and the e-stop. +# +# SAFETY: +# * every tool that moves or acquires requires confirm=True +# (PermissionError otherwise) +# * 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 nis_elements_mcp import estop as _estop +from nis_elements_mcp.nis_bridge_client import NISBridge + + +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: NIS_CAPTURE_DIR, else ~/nis-mcp/captures.""" + d = Path(os.environ.get("NIS_CAPTURE_DIR") or Path.home() / "nis-mcp" / "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()) + + +def estop(action: str = "status", reason: str = "requested via MCP") -> dict: + """EMERGENCY STOP: immediately forbid all microscope motion. + + Call this the moment anything looks wrong - an unexpected move, a + position that doesn't match what you asked for, a stage that seems to + be travelling when it shouldn't be, or an instruction from the + operator to stop. It is cheap, it is instant, and a needless stop + costs nothing but a release. Do not deliberate: stop first, diagnose + afterwards. + + Once engaged, EVERY motion primitive refuses - not just this session's, + but every process on the machine that checks the same e-stop file, + including the bridge inside NIS-Elements. The flag lives in a file, so + it outlives whatever set it and cannot be lost by a process dying. It + cannot stop a move already in flight: that move runs to its end, and + every move after it is refused. An ND experiment that is running can + still be ended with nis_finish_experiment. + + action: "engage" to stop everything, or "status" to report the current + state. RELEASE IS DELIBERATELY NOT AVAILABLE HERE - a stop that the + agent can lift by itself is not a safety device. A human clears it + from a terminal with `python -m nis_elements_mcp.estop release`. + + Returns the resulting state. This tool never needs confirm=True: a + stop is always safe to perform, and requiring a confirmation step for + an emergency control would defeat its purpose. + """ + if action == "engage": + info = _estop.engage(reason) + return { + "engaged": True, + "detail": info, + "release_with": "python -m nis_elements_mcp.estop release", + "note": "All motion is now refused for every process on this machine.", + } + if action == "status": + return { + "engaged": _estop.is_engaged(), + "detail": _estop.details(), + "flag_file": str(_estop.ESTOP_PATH), + } + raise ValueError( + f"Unknown estop action {action!r}. Use 'engage' to stop motion, or " + "'status' to check. Releasing is a human action performed at a " + "terminal: python -m nis_elements_mcp.estop release" + ) diff --git a/packages/nis-elements-mcp/src/nis_elements_mcp/testing.py b/packages/nis-elements-mcp/src/nis_elements_mcp/testing.py new file mode 100644 index 0000000..689752a --- /dev/null +++ b/packages/nis-elements-mcp/src/nis_elements_mcp/testing.py @@ -0,0 +1,191 @@ +# testing.py +# ------------------------------------------------------------ +# A mock NIS for tests, no microscope needed: FakeNIS stands in for +# g5_regprocs.dll (same function names, records every call), and the +# `bridge` fixture runs the real bridge job's HTTP server and request queue +# on it, on a free port, with the client pointed at it. +# +# Use it from any project's tests (needs pytest): +# +# from nis_elements_mcp.testing import bridge, estop_file # noqa: F401 (fixtures) +# +# def test_my_script_moves(bridge): +# nis, url, client = bridge +# client.move_relative(100, 0) +# assert nis.x == 200.0 +# ------------------------------------------------------------ + +from __future__ import annotations + +import json +import threading +import time +import urllib.error +import urllib.request + +import pytest + +from nis_elements_mcp import estop, nis_events +from nis_elements_mcp import nis_bridge_client as client_mod +from nis_elements_mcp import nis_bridge_job as bj + + +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 λD 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.threads = {} # call name -> id of the thread that made it + 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) + self.threads[name] = threading.get_ident() + 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 + + +class FakeMainThread(bj.MainThread): + """Plays NIS's message loop: one thread that calls _tick, as the Win32 timer does.""" + + def __init__(self): + super().__init__(tick_ms=5) + self.installed = True + self._stop = threading.Event() + self.thread = threading.Thread(target=self._pump, daemon=True) + self.thread.start() + self.main_thread_id = self.thread.ident + + def _pump(self): + while not self._stop.is_set(): + self._tick() + time.sleep(0.005) + + def close(self): + self._stop.set() + self.thread.join(5) + + +@pytest.fixture +def bridge(estop_file, monkeypatch): + nis = FakeNIS() + ui = FakeMainThread() + stop, ready, port = threading.Event(), threading.Event(), [] + t = threading.Thread(target=bj.serve, args=(bj.Bridge(bj.Macro(nis), ui),), + 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) + nis.ui = ui + yield nis, url, client_mod.NISBridge(url) + stop.set() + t.join(5) + ui.close() + + +@pytest.fixture +def events_log(tmp_path, monkeypatch): + monkeypatch.setattr(nis_events, "events_dir", lambda: tmp_path / "events") + return nis_events.events_path() + + +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()) diff --git a/packages/nis-elements-mcp/tests/conftest.py b/packages/nis-elements-mcp/tests/conftest.py new file mode 100644 index 0000000..f331725 --- /dev/null +++ b/packages/nis-elements-mcp/tests/conftest.py @@ -0,0 +1,8 @@ +# Tests never write logs or captures into the user's ~/nis-mcp: point both +# folders at a throwaway directory before any test runs. +import os +import tempfile + +_TMP = tempfile.mkdtemp(prefix="nis-mcp-tests-") +os.environ["NIS_LOG_DIR"] = os.path.join(_TMP, "logs") +os.environ["NIS_CAPTURE_DIR"] = os.path.join(_TMP, "captures") diff --git a/tests/test_estop.py b/packages/nis-elements-mcp/tests/test_estop.py similarity index 97% rename from tests/test_estop.py rename to packages/nis-elements-mcp/tests/test_estop.py index 526f0cf..fe8e646 100644 --- a/tests/test_estop.py +++ b/packages/nis-elements-mcp/tests/test_estop.py @@ -3,7 +3,7 @@ import pytest -from acquisition import estop +from nis_elements_mcp import estop @pytest.fixture @@ -76,7 +76,7 @@ def test_launch_panel_starts_detached_process(monkeypatch): monkeypatch.setattr(estop, "panel_running", lambda: False) monkeypatch.setattr(estop.subprocess, "Popen", lambda *a, **k: opened.append(a[0])) estop.launch_panel() - assert opened[0][-2:] == ["-m", "acquisition.estop_panel"] + assert opened[0][-2:] == ["-m", "nis_elements_mcp.estop_panel"] def test_launch_panel_failure_goes_to_stderr(monkeypatch, capsys): diff --git a/tests/test_estop_panel.py b/packages/nis-elements-mcp/tests/test_estop_panel.py similarity index 97% rename from tests/test_estop_panel.py rename to packages/nis-elements-mcp/tests/test_estop_panel.py index ac06650..4f8886b 100644 --- a/tests/test_estop_panel.py +++ b/packages/nis-elements-mcp/tests/test_estop_panel.py @@ -9,7 +9,7 @@ import pytest -from acquisition import estop, nis_monitor +from nis_elements_mcp import estop, nis_monitor class Widget: @@ -85,12 +85,12 @@ def panel_mod(monkeypatch, tmp_path): monkeypatch.setitem(sys.modules, "tkinter", tk) monkeypatch.setitem(sys.modules, "tkinter.messagebox", mb) monkeypatch.setattr(estop, "ESTOP_PATH", tmp_path / "ESTOP") - sys.modules.pop("acquisition.estop_panel", None) - mod = importlib.import_module("acquisition.estop_panel") + sys.modules.pop("nis_elements_mcp.estop_panel", None) + mod = importlib.import_module("nis_elements_mcp.estop_panel") mod.real_claim = mod._claim_single_instance # the tests of the mutex use this monkeypatch.setattr(mod, "_claim_single_instance", lambda: True) # a real mutex would outlive the test yield mod, asked - sys.modules.pop("acquisition.estop_panel", None) + sys.modules.pop("nis_elements_mcp.estop_panel", None) def make_panel(mod, **kw): diff --git a/tests/test_nis_bridge.py b/packages/nis-elements-mcp/tests/test_nis_bridge.py similarity index 70% rename from tests/test_nis_bridge.py rename to packages/nis-elements-mcp/tests/test_nis_bridge.py index c808812..cfea2e1 100644 --- a/tests/test_nis_bridge.py +++ b/packages/nis-elements-mcp/tests/test_nis_bridge.py @@ -16,165 +16,12 @@ 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.nis 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.threads = {} # call name -> id of the thread that made it - 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) - self.threads[name] = threading.get_ident() - 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 - - -class FakeMainThread(bj.MainThread): - """Plays NIS's message loop: one thread that calls _tick, as the Win32 timer does.""" - - def __init__(self): - super().__init__(tick_ms=5) - self.installed = True - self._stop = threading.Event() - self.thread = threading.Thread(target=self._pump, daemon=True) - self.thread.start() - self.main_thread_id = self.thread.ident - - def _pump(self): - while not self._stop.is_set(): - self._tick() - time.sleep(0.005) - - def close(self): - self._stop.set() - self.thread.join(5) - - -@pytest.fixture -def bridge(estop_file, monkeypatch): - nis = FakeNIS() - ui = FakeMainThread() - stop, ready, port = threading.Event(), threading.Event(), [] - t = threading.Thread(target=bj.serve, args=(bj.Bridge(bj.Macro(nis), ui),), - 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) - nis.ui = ui - yield nis, url, client_mod.NISBridge(url) - stop.set() - t.join(5) - ui.close() - - -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()) +from nis_elements_mcp import estop, nis_events, nis_monitor as monitor +from nis_elements_mcp import nis_bridge_client as client_mod +from nis_elements_mcp import nis_bridge_job as bj +from nis_elements_mcp import nis_tools +from nis_elements_mcp.testing import (FakeMainThread, FakeNIS, bridge, estop_file, # noqa: F401 (fixtures) + events_log, raw) # ---- bridge behaviour ------------------------------------------------- @@ -303,7 +150,7 @@ def test_tools_need_confirm(bridge): 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")) + monkeypatch.setenv("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", ""): @@ -317,8 +164,8 @@ def test_nis_server_exposes_exactly_the_nis_tools(tmp_path): 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.nis.nis_server"], env=env) + NIS_LOG_DIR=str(tmp_path / "logs"), NIS_CAPTURE_DIR=str(tmp_path / "caps")) + params = StdioServerParameters(command=sys.executable, args=["-m", "nis_elements_mcp.nis_server"], env=env) async with Client(stdio_client(params)) as client: return {t.name for t in (await client.list_tools()).tools} @@ -338,7 +185,7 @@ def test_idle_bridge_stops_itself(estop_file): 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")) + monkeypatch.setenv("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 @@ -362,12 +209,6 @@ def test_tool_raises_when_the_turret_does_not_arrive(bridge, monkeypatch): # ---- 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 @@ -447,7 +288,7 @@ def test_monitor_opens_once_when_the_server_starts(monkeypatch): 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"] + assert opened and opened[0][-2:] == ["-m", "nis_elements_mcp.nis_monitor"] opened.clear() monkeypatch.setattr(monitor, "monitor_running", lambda: True) # already on screen monitor.launch() diff --git a/tests/test_nis_events_monitor.py b/packages/nis-elements-mcp/tests/test_nis_events_monitor.py similarity index 88% rename from tests/test_nis_events_monitor.py rename to packages/nis-elements-mcp/tests/test_nis_events_monitor.py index c339679..8aaffab 100644 --- a/tests/test_nis_events_monitor.py +++ b/packages/nis-elements-mcp/tests/test_nis_events_monitor.py @@ -8,11 +8,11 @@ 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.nis import nis_tools -from tests.test_nis_bridge import bridge, estop_file, events_log, raw # noqa: F401 (fixtures) +from nis_elements_mcp import nis_events, nis_monitor as monitor +from nis_elements_mcp import nis_bridge_client as client_mod +from nis_elements_mcp import nis_bridge_job as bj +from nis_elements_mcp import nis_tools +from nis_elements_mcp.testing import bridge, estop_file, events_log, raw # noqa: F401 (fixtures) NOW = datetime.datetime(2026, 10, 15, 14, 0, 0) @@ -77,11 +77,24 @@ def test_checked_passes_good_answers_and_raises_on_failures(): 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) +def test_capture_folder_defaults_under_home_nis_mcp(tmp_path, monkeypatch): + monkeypatch.delenv("NIS_CAPTURE_DIR", raising=False) + monkeypatch.setattr(nis_tools.Path, "home", lambda: tmp_path) d = nis_tools.capture_dir() - assert d == tmp_path / "data" / "NIS" / "captures" and d.is_dir() + assert d == tmp_path / "nis-mcp" / "captures" and d.is_dir() + + +def test_capture_folder_follows_nis_capture_dir(tmp_path, monkeypatch): + monkeypatch.setenv("NIS_CAPTURE_DIR", str(tmp_path / "mine")) + assert nis_tools.capture_dir() == tmp_path / "mine" + + +def test_event_log_folder_follows_nis_log_dir(tmp_path, monkeypatch): + monkeypatch.setenv("NIS_LOG_DIR", str(tmp_path / "logs")) + assert nis_events.events_dir() == tmp_path / "logs" + monkeypatch.delenv("NIS_LOG_DIR") + monkeypatch.setattr(nis_events.Path, "home", lambda: tmp_path) + assert nis_events.events_dir() == tmp_path / "nis-mcp" / "logs" # ---- event log ------------------------------------------------------------- diff --git a/pyproject.toml b/pyproject.toml index ea4264b..0dc794e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -21,6 +21,8 @@ dependencies = [ "Pillow==12.3.0", "PyYAML==6.0.3", "numpy==2.4.6", + # The NIS-Elements MCP server, from this repo's own folder (never from an index). + "nis-elements-mcp @ {root:uri}/packages/nis-elements-mcp", ] [project.optional-dependencies] @@ -70,7 +72,8 @@ all = [ [project.scripts] baumer-ti2-mcp = "mcp_server.baumer_ti2.baumer_ti2_server:main" -nis-mcp = "mcp_server.nis.nis_server:main" +# nis-mcp comes from the nis-elements-mcp package (default folders under ~/nis-mcp); +# confocal-mcp-nis runs the same server with this repo's log and capture folders. # Old names, kept so existing MCP client configs keep working. confocal-mcp = "mcp_server.baumer_ti2.baumer_ti2_server:main" confocal-mcp-nis = "mcp_server.nis.nis_server:main" @@ -79,6 +82,9 @@ confocal-mcp-nis = "mcp_server.nis.nis_server:main" Homepage = "https://github.com/BioNanomics/microscope-agent" Repository = "https://github.com/BioNanomics/microscope-agent" +[tool.hatch.metadata] +allow-direct-references = true + [tool.hatch.build.targets.wheel] packages = ["mcp_server", "acquisition", "harness", "timelapse"] diff --git a/tests/test_calibration.py b/tests/test_calibration.py index cc1735b..9f679bb 100644 --- a/tests/test_calibration.py +++ b/tests/test_calibration.py @@ -13,7 +13,7 @@ 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 +from nis_elements_mcp.testing import FakeNIS def make_setting(name, control, value=1, lower=0, higher=10, unit="u", enabled=True, long_name=None): diff --git a/tests/test_hardware_scripts.py b/tests/test_hardware_scripts.py index 081a7fe..8545836 100644 --- a/tests/test_hardware_scripts.py +++ b/tests/test_hardware_scripts.py @@ -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_small_gaps.py b/tests/test_small_gaps.py index 8f6d142..a3dbeeb 100644 --- a/tests/test_small_gaps.py +++ b/tests/test_small_gaps.py @@ -23,7 +23,7 @@ from mcp_server.nis 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) +from nis_elements_mcp.testing import FakeNIS, bridge, estop_file, raw # noqa: F401 (fixtures) # ---- MCP server entry points ------------------------------------------------------- @@ -54,6 +54,7 @@ def test_server_modules_start_when_run_with_dash_m(module, monkeypatch): 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"] @@ -134,6 +135,7 @@ def test_cli_prints_the_bridge_answer(bridge, monkeypatch, capsys): def test_cli_module_runs_as_a_script(bridge, monkeypatch, capsys): nis, url, c = bridge monkeypatch.setattr(sys, "argv", ["nis_bridge", "--url", url, "status"]) + monkeypatch.delitem(sys.modules, 'acquisition.backends.nis_bridge', raising=False) # run it as a fresh `python -m` would runpy.run_module("acquisition.backends.nis_bridge", run_name="__main__") assert "xy_um" in capsys.readouterr().out @@ -209,6 +211,7 @@ def test_monitor_probe_is_false_off_windows(monkeypatch): 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"]) + monkeypatch.delitem(sys.modules, 'acquisition.nis_monitor', raising=False) # run it as a fresh `python -m` would runpy.run_module("acquisition.nis_monitor", run_name="__main__") assert "bridge:" in capsys.readouterr().out @@ -294,5 +297,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__") From ce3d1bcf00bbdbaf5b4b3f02e30d37c9e089b8d2 Mon Sep 17 00:00:00 2001 From: Qurratul Ain Quais Date: Fri, 30 Oct 2026 18:05:43 -0400 Subject: [PATCH 06/12] nis-elements-mcp: NIS_* settings, client-side limits, e-stop at ~/.nis-mcp/ESTOP --- CHANGELOG.md | 10 +++ acquisition/_nis_settings.py | 74 +++++++++++++--- acquisition/calibration/nis_port_probe.py | 2 +- acquisition/estop.py | 2 + acquisition/estop_panel.py | 2 + docs/nis-bridge.md | 21 +++-- .../src/nis_elements_mcp/estop.py | 11 +-- .../src/nis_elements_mcp/nis_bridge_client.py | 56 +++++++++--- .../src/nis_elements_mcp/nis_bridge_job.py | 47 +++++++--- .../src/nis_elements_mcp/nis_events.py | 5 +- .../src/nis_elements_mcp/nis_monitor.py | 11 ++- .../src/nis_elements_mcp/nis_server.py | 2 +- .../src/nis_elements_mcp/nis_tools.py | 19 +++-- .../src/nis_elements_mcp/settings.py | 76 +++++++++++++++++ .../src/nis_elements_mcp/testing.py | 3 +- packages/nis-elements-mcp/tests/test_estop.py | 8 +- .../nis-elements-mcp/tests/test_nis_bridge.py | 6 +- .../tests/test_nis_events_monitor.py | 5 +- .../nis-elements-mcp/tests/test_settings.py | 85 +++++++++++++++++++ tests/test_hardware_scripts.py | 2 +- tests/test_mcp_server.py | 2 +- tests/test_nis_settings.py | 52 ++++++++++++ tests/test_small_gaps.py | 4 +- 23 files changed, 430 insertions(+), 75 deletions(-) create mode 100644 packages/nis-elements-mcp/src/nis_elements_mcp/settings.py create mode 100644 packages/nis-elements-mcp/tests/test_settings.py create mode 100644 tests/test_nis_settings.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 9ac459d..62419b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,16 @@ Format follows [Keep a Changelog](https://keepachangelog.com/); versions follow 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. ### Added - `analysis/worm_short.py` - C. elegans Short from an AML18 time-lapse diff --git a/acquisition/_nis_settings.py b/acquisition/_nis_settings.py index d716211..4c2a7a1 100644 --- a/acquisition/_nis_settings.py +++ b/acquisition/_nis_settings.py @@ -1,21 +1,75 @@ # _nis_settings.py # ------------------------------------------------------------ # This repo's settings for the nis-elements-mcp package -# (packages/nis-elements-mcp). The package keeps its event log and -# captures under NIS_LOG_DIR / NIS_CAPTURE_DIR (default ~/nis-mcp/...); -# this repo keeps them where they always were: logs/nis and -# data/NIS/captures under the data folder (acquisition/paths.py). -# -# The forwarders that lead into the package (acquisition/nis_*.py, +# (packages/nis-elements-mcp, see its settings.py). The forwarders that +# lead into the package (acquisition/estop*.py, acquisition/nis_*.py, # acquisition/backends/nis_bridge.py, mcp_server/nis/) import this first. # A variable that is already set wins, so an MCP client config can still -# point them elsewhere. Child processes (the monitor window) inherit them. +# override any of them. Child processes (STOP panel, monitor) inherit them. +# +# * Logs and captures stay where they always were: logs/nis and +# data/NIS/captures under the data folder (acquisition/paths.py). +# * The e-stop is the package default, ~/.nis-mcp/ESTOP, because the +# bridge job inside NIS uses that default and cannot see this repo's +# settings. A stop still engaged in the old file (~/.confocal-mcp/ESTOP, +# before 2026-10-30) is moved there, so a switch never loses a stop. +# * The old CONFOCAL_* names of the package's switches still work. # ------------------------------------------------------------ import os +import sys +from pathlib import Path +from urllib.parse import urlsplit from acquisition import paths +from nis_elements_mcp import settings + + +def use_repo_folders() -> None: + """Logs in logs/nis and captures in data/NIS/captures, unless already set.""" + os.environ.setdefault("NIS_LOG_DIR", str(paths.logs_dir() / "nis")) + os.environ.setdefault("NIS_CAPTURE_DIR", os.environ.get("CONFOCAL_NIS_CAPTURE_DIR") + or str(paths.data_root() / "data" / "NIS" / "captures")) + + +use_repo_folders() + + +def use_old_names() -> None: + """Honour the switches' names from before the package (CONFOCAL_*).""" + for old, new in (("CONFOCAL_NO_ESTOP_PANEL", "NIS_NO_ESTOP_PANEL"), + ("CONFOCAL_NO_NIS_MONITOR", "NIS_NO_MONITOR")): + if os.environ.get(old): + os.environ.setdefault(new, os.environ[old]) + if os.environ.get("CONFOCAL_NIS_BRIDGE_URL"): + url = urlsplit(os.environ["CONFOCAL_NIS_BRIDGE_URL"]) + os.environ.setdefault("NIS_BRIDGE_HOST", url.hostname or "127.0.0.1") + os.environ.setdefault("NIS_BRIDGE_PORT", str(url.port or 8766)) + + +use_old_names() + +OLD_ESTOP_FILE = Path.home() / ".confocal-mcp" / "ESTOP" + + +def carry_over_old_estop(old: Path = OLD_ESTOP_FILE) -> None: + """Move a stop engaged in the old e-stop file to the current one. + + If the old file cannot be removed it stays, and the stop is engaged + again on the next start: failing towards stopped, never towards moving. + """ + try: + if not old.exists(): + return + new = settings.estop_file() + if not new.exists(): + new.parent.mkdir(parents=True, exist_ok=True) + new.write_bytes(old.read_bytes()) + old.unlink() + print(f"[estop] moved the engaged e-stop from {old} to {new}", file=sys.stderr) + except OSError as exc: + print(f"[estop] could not move the old e-stop file {old} ({exc}); " + f"delete it by hand once {settings.estop_file()} is engaged", file=sys.stderr) + -os.environ.setdefault("NIS_LOG_DIR", str(paths.logs_dir() / "nis")) -os.environ.setdefault("NIS_CAPTURE_DIR", os.environ.get("CONFOCAL_NIS_CAPTURE_DIR") - or str(paths.data_root() / "data" / "NIS" / "captures")) +carry_over_old_estop() diff --git a/acquisition/calibration/nis_port_probe.py b/acquisition/calibration/nis_port_probe.py index 10c6603..f5653cf 100644 --- a/acquisition/calibration/nis_port_probe.py +++ b/acquisition/calibration/nis_port_probe.py @@ -21,7 +21,7 @@ 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" +ESTOP = os.environ.get("NIS_ESTOP_FILE") or os.path.join(os.path.expanduser("~"), ".nis-mcp", "ESTOP") ALLOWED_OBJECTIVES = ("4x", "10x") nis = ct.cdll.g5_regprocs diff --git a/acquisition/estop.py b/acquisition/estop.py index d54907b..804704e 100644 --- a/acquisition/estop.py +++ b/acquisition/estop.py @@ -9,6 +9,8 @@ import sys +from acquisition import _nis_settings # noqa: F401 (this repo's settings; moves an old e-stop) + if __name__ == "__main__": import runpy runpy.run_module("nis_elements_mcp.estop", run_name="__main__") diff --git a/acquisition/estop_panel.py b/acquisition/estop_panel.py index e0b53c4..2aa5cfa 100644 --- a/acquisition/estop_panel.py +++ b/acquisition/estop_panel.py @@ -9,6 +9,8 @@ import sys +from acquisition import _nis_settings # noqa: F401 (this repo's settings; moves an old e-stop) + if __name__ == "__main__": import runpy runpy.run_module("nis_elements_mcp.estop_panel", run_name="__main__") diff --git a/docs/nis-bridge.md b/docs/nis-bridge.md index 124a692..cef61ad 100644 --- a/docs/nis-bridge.md +++ b/docs/nis-bridge.md @@ -201,12 +201,23 @@ Notes: ## 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. +- The **e-stop** is checked in the client and again in the bridge. Both use + `~/.nis-mcp/ESTOP` (`NIS_ESTOP_FILE`), the same file the Ti2 code here + uses. Ending an ND run is always allowed. +- XY moves are **relative, at most 1000 µm per axis** per call + (`NIS_MAX_STEP_UM`). **Z is never moved.** +- Objective changes are limited to **4× and 10×**, the long working distances + (`NIS_ALLOWED_OBJECTIVES`). +- ND runs can be limited to named experiments (`NIS_ALLOWED_EXPERIMENTS`). +- The client checks these limits before sending; the bridge inside NIS checks + the step and objective limits again with its own settings (NIS's + environment, or the defaults at the top of `nis_bridge_job.py`). The + stricter one wins. - 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, + (`NIS_CAPTURE_DIR`; this repo uses `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. + +All settings and their defaults are listed in +`packages/nis-elements-mcp/src/nis_elements_mcp/settings.py`. diff --git a/packages/nis-elements-mcp/src/nis_elements_mcp/estop.py b/packages/nis-elements-mcp/src/nis_elements_mcp/estop.py index f01b695..11692c2 100644 --- a/packages/nis-elements-mcp/src/nis_elements_mcp/estop.py +++ b/packages/nis-elements-mcp/src/nis_elements_mcp/estop.py @@ -67,15 +67,16 @@ import sys from pathlib import Path +from nis_elements_mcp import settings + #: 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 = settings.estop_file() # NIS_ESTOP_FILE, else ~/.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 +166,9 @@ 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 turns it off. """ - if os.environ.get("CONFOCAL_NO_ESTOP_PANEL"): + if settings.estop_panel_disabled(): return try: if panel_running(): diff --git a/packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_client.py b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_client.py index 586c550..42f4ddd 100644 --- a/packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_client.py +++ b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_client.py @@ -23,23 +23,24 @@ # (nis_events.py), which `python -m nis_elements_mcp.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). +# NIS_BRIDGE_HOST / NIS_BRIDGE_PORT set the address (default +# http://127.0.0.1:8766). The XY step limit, the objective allow-list and +# the ND experiment allow-list (settings.py) are checked here before +# anything is sent, and the bridge checks its own copy of the first two. # ------------------------------------------------------------ from __future__ import annotations import argparse import json -import os import sys import time import urllib.error import urllib.request -from nis_elements_mcp import estop, nis_events +from nis_elements_mcp import estop, nis_events, settings +from nis_elements_mcp.nis_bridge_job import magnification -DEFAULT_URL = "http://127.0.0.1:8766" class BridgeUnavailable(RuntimeError): @@ -48,7 +49,7 @@ class BridgeUnavailable(RuntimeError): 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.url = (url or settings.bridge_url()).rstrip("/") self.timeout_s = timeout_s def _call(self, method: str, path: str, body: dict | None = None, @@ -99,11 +100,13 @@ def optical_configs(self) -> dict: # 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})) + lambda: _step_refusal(dx_um, dy_um) + or 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})) + lambda: _objective_refusal(name) + or self._call("POST", "/objective", {"name": name})) def capture(self, path: str) -> dict: return self._act("capture", {"path": path}, @@ -113,8 +116,9 @@ 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)) + lambda: _experiment_refusal(experiment) + or self._call("POST", "/nd/run", {"experiment": experiment}, + timeout_s=timeout_s)) # Always allowed: these only end things def nd_finish(self) -> dict: @@ -124,14 +128,40 @@ def shutdown(self) -> dict: return self._act("shutdown", {}, lambda: self._call("POST", "/shutdown"), guarded=False) +# The limits from settings.py, checked before a request leaves this process. +# Each returns the refusal, shaped like the bridge's own, or None. + +def _step_refusal(dx_um: float, dy_um: float) -> dict | None: + limit = settings.max_step_um() + if max(abs(dx_um), abs(dy_um)) > limit: + return {"error": f"step over {limit:g} um refused (NIS_MAX_STEP_UM)"} + return None + + +def _objective_refusal(name: str) -> dict | None: + allowed = settings.allowed_magnifications() + if magnification(name) not in allowed: + listed = "/".join(f"{m:g}x" for m in allowed) + return {"error": f"only {listed} objectives are allowed (NIS_ALLOWED_OBJECTIVES), got {name!r}"} + return None + + +def _experiment_refusal(experiment: str) -> dict | None: + allowed = settings.allowed_experiments() + if allowed is not None and experiment not in allowed: + return {"error": f"ND experiment {experiment!r} is not in NIS_ALLOWED_EXPERIMENTS " + f"({', '.join(allowed)})"} + return None + + 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})") + ap.add_argument("--url", help="bridge address (default from NIS_BRIDGE_HOST/PORT, else http://127.0.0.1:8766)") 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 = sub.add_parser("move", help="relative XY move in um (max NIS_MAX_STEP_UM per axis, default 1000)") 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 = sub.add_parser("objective", help="exact name as listed by status (NIS_ALLOWED_OBJECTIVES, default 4x/10x)") 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") diff --git a/packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_job.py b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_job.py index c4915eb..332cd2f 100644 --- a/packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_job.py +++ b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_job.py @@ -56,8 +56,8 @@ # * nothing moves or starts while the e-stop file exists (the same file # 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 +# * objective changes only to ALLOWED_MAGNIFICATIONS (default 4x/10x, +# whose working distances of 20 and 4 mm cannot reach the dish) # * serves on 127.0.0.1 only # ------------------------------------------------------------ import ctypes as ct @@ -70,16 +70,43 @@ import time from pathlib import Path -PORT = 8766 # 8765 is the plain port probe (nis_port_probe.py) +# Settings. Inside NIS they come from NIS's own environment, which is +# usually empty, so the defaults apply. To change one, set the variable +# (NIS_BRIDGE_PORT, NIS_MAX_STEP_UM, NIS_ALLOWED_OBJECTIVES, NIS_ESTOP_FILE) +# before starting NIS, or edit the default here before pasting the file. +# The client side (settings.py) uses the same names and defaults. +DEFAULT_HOST = "127.0.0.1" +DEFAULT_PORT = 8766 # 8765 is the plain port probe (nis_port_probe.py) +DEFAULT_MAX_STEP_UM = 1000.0 +DEFAULT_ALLOWED_OBJECTIVES = "4,10" # long working distances: they cannot reach the dish VERSION = 1 -MAX_STEP_UM = 1000.0 -ALLOWED_MAGNIFICATIONS = (4, 10) UI_TICK_MS = 50 # how often NIS's main thread looks for queued UI calls UI_CALL_TIMEOUT_S = 600.0 # give up waiting for the main thread after this long # "4x" / "10x" as a whole magnification - not the 4x inside "14x" or "40x" _MAG = re.compile(r"(? "tuple[float, ...]": + """'4,10' or '4x, 10x' -> (4.0, 10.0).""" + return tuple(float(p.strip().rstrip("xX")) for p in text.split(",") if p.strip()) + + +def magnification(name: str) -> "float | None": + """The one magnification in an objective name ('PLAN APO 10x' -> 10.0), else None.""" + mags = {float(m) for m in _MAG.findall(name)} + return mags.pop() if len(mags) == 1 else None + + +def estop_file() -> Path: + """NIS_ESTOP_FILE, else ~/.nis-mcp/ESTOP: absolute, the same for every process.""" + return Path(os.environ.get("NIS_ESTOP_FILE", "").strip() or Path.home() / ".nis-mcp" / "ESTOP") + + +PORT = int(os.environ.get("NIS_BRIDGE_PORT", "").strip() or DEFAULT_PORT) +MAX_STEP_UM = float(os.environ.get("NIS_MAX_STEP_UM", "").strip() or DEFAULT_MAX_STEP_UM) +ALLOWED_MAGNIFICATIONS = parse_magnifications(os.environ.get("NIS_ALLOWED_OBJECTIVES", "").strip() + or DEFAULT_ALLOWED_OBJECTIVES) +ESTOP = estop_file() IDLE_STOP_S = 4 * 3600.0 # end the job if nothing has asked for this long TURRET_SETTLE_S = 25.0 # how long to wait for the nosepiece to arrive @@ -237,9 +264,9 @@ def move(self, dx: float, dy: float) -> dict: 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}"} + if magnification(name) not in ALLOWED_MAGNIFICATIONS: + allowed = "/".join(f"{m:g}x" for m in ALLOWED_MAGNIFICATIONS) + return {"error": f"only {allowed} 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 diff --git a/packages/nis-elements-mcp/src/nis_elements_mcp/nis_events.py b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_events.py index 816ff9f..5a579f3 100644 --- a/packages/nis-elements-mcp/src/nis_elements_mcp/nis_events.py +++ b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_events.py @@ -21,15 +21,16 @@ import datetime import json -import os from pathlib import Path +from nis_elements_mcp import settings + PHASES = ("start", "ok", "failed", "refused", "error") def events_dir() -> Path: """NIS_LOG_DIR, else ~/nis-mcp/logs. Read on every call, so a change takes effect at once.""" - return Path(os.environ.get("NIS_LOG_DIR") or Path.home() / "nis-mcp" / "logs") + return settings.log_dir() def events_path(day: datetime.date | None = None) -> Path: diff --git a/packages/nis-elements-mcp/src/nis_elements_mcp/nis_monitor.py b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_monitor.py index b1ef6d8..23267a7 100644 --- a/packages/nis-elements-mcp/src/nis_elements_mcp/nis_monitor.py +++ b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_monitor.py @@ -13,7 +13,7 @@ # 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. +# NIS_NO_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 @@ -33,11 +33,10 @@ import urllib.error import urllib.request -from nis_elements_mcp import estop, nis_events -from nis_elements_mcp.nis_bridge_client import DEFAULT_URL +from nis_elements_mcp import estop, nis_events, settings ON_WINDOWS = sys.platform == "win32" -MONITOR_MUTEX = r"Local\confocal-mcp-nis-monitor" +MONITOR_MUTEX = r"Local\nis-mcp-monitor" STATUS_TIMEOUT_S = 2.0 EVENTS_KEPT = 200 @@ -65,7 +64,7 @@ def launch() -> None: 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: + if settings.monitor_disabled() or not ON_WINDOWS: return try: if monitor_running(): @@ -157,7 +156,7 @@ def render(link: str, status: dict | None, events: list[dict], estop_text: str, 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("--url", default=settings.bridge_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() diff --git a/packages/nis-elements-mcp/src/nis_elements_mcp/nis_server.py b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_server.py index ceb88e5..1b047b3 100644 --- a/packages/nis-elements-mcp/src/nis_elements_mcp/nis_server.py +++ b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_server.py @@ -15,7 +15,7 @@ from nis_elements_mcp import estop, nis_monitor, nis_tools -mcp = MCPServer("ConfocalOrchestrator-NIS") +mcp = MCPServer("NIS-Elements") mcp.add_tool(nis_tools.nis_status) mcp.add_tool(nis_tools.nis_move_relative) diff --git a/packages/nis-elements-mcp/src/nis_elements_mcp/nis_tools.py b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_tools.py index 9250ad9..4d67405 100644 --- a/packages/nis-elements-mcp/src/nis_elements_mcp/nis_tools.py +++ b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_tools.py @@ -13,8 +13,10 @@ # (PermissionError otherwise) # * 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 +# * XY moves are relative and capped (NIS_MAX_STEP_UM, default 1 mm); +# there is no Z tool +# * objective changes only to NIS_ALLOWED_OBJECTIVES (default 4x/10x) +# * ND runs only of NIS_ALLOWED_EXPERIMENTS, if that is set # * 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 @@ -24,11 +26,11 @@ from __future__ import annotations import json -import os import re from pathlib import Path from nis_elements_mcp import estop as _estop +from nis_elements_mcp import settings from nis_elements_mcp.nis_bridge_client import NISBridge @@ -57,7 +59,7 @@ def _checked(result: dict) -> dict: def capture_dir() -> Path: """Where nis_capture writes: NIS_CAPTURE_DIR, else ~/nis-mcp/captures.""" - d = Path(os.environ.get("NIS_CAPTURE_DIR") or Path.home() / "nis-mcp" / "captures") + d = settings.capture_dir() d.mkdir(parents=True, exist_ok=True) return d @@ -72,7 +74,8 @@ def nis_status() -> dict: 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 + through NIS-Elements. At most 1000 um per axis per call (or the + NIS_MAX_STEP_UM setting). 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") @@ -83,7 +86,8 @@ 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 + the sample), unless NIS_ALLOWED_OBJECTIVES says otherwise. Returns + the objective and nosepiece position before and after. Requires confirm=True.""" _require_confirm(confirm, "nis_change_objective") return _checked(_bridge().change_objective(name)) @@ -117,7 +121,8 @@ def nis_run_experiment(experiment: str, confirm: bool = False) -> dict: 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.""" + running, or if NIS_ALLOWED_EXPERIMENTS is set and does not list it. + Requires confirm=True.""" _require_confirm(confirm, "nis_run_experiment") return _checked(_bridge().nd_run(experiment)) diff --git a/packages/nis-elements-mcp/src/nis_elements_mcp/settings.py b/packages/nis-elements-mcp/src/nis_elements_mcp/settings.py new file mode 100644 index 0000000..81d208f --- /dev/null +++ b/packages/nis-elements-mcp/src/nis_elements_mcp/settings.py @@ -0,0 +1,76 @@ +# settings.py +# ------------------------------------------------------------ +# Every setting nis-elements-mcp reads. All come from environment +# variables, so an MCP client config sets them per project, e.g. +# +# claude mcp add nis -e NIS_CAPTURE_DIR=D:\data\captures -- nis-mcp +# +# Each is read when it is needed, not once at import, except the e-stop +# file (estop.ESTOP_PATH), which every process must agree on from start. +# +# NIS_BRIDGE_HOST bridge address 127.0.0.1 +# NIS_BRIDGE_PORT bridge port 8766 +# NIS_CAPTURE_DIR where nis_capture saves ~/nis-mcp/captures +# NIS_LOG_DIR event log folder ~/nis-mcp/logs +# NIS_ESTOP_FILE e-stop flag file ~/.nis-mcp/ESTOP +# NIS_ALLOWED_OBJECTIVES magnifications allowed 4,10 +# NIS_ALLOWED_EXPERIMENTS ND experiment names allowed (empty = any saved one) +# NIS_MAX_STEP_UM largest XY step per call 1000 +# NIS_NO_ESTOP_PANEL 1 = do not open the STOP window +# NIS_NO_MONITOR 1 = do not open the monitor window +# +# The bridge job inside NIS (nis_bridge_job.py) reads the same names from +# NIS's own environment, with the same defaults; the client and the bridge +# both enforce the limits, so the stricter of the two wins. +# ------------------------------------------------------------ + +from __future__ import annotations + +import os +from pathlib import Path + +from nis_elements_mcp import nis_bridge_job as _job + + +def _env(name: str) -> str: + return os.environ.get(name, "").strip() + + +def bridge_url() -> str: + host = _env("NIS_BRIDGE_HOST") or _job.DEFAULT_HOST + port = _env("NIS_BRIDGE_PORT") or _job.DEFAULT_PORT + return f"http://{host}:{port}" + + +def capture_dir() -> Path: + return Path(_env("NIS_CAPTURE_DIR") or Path.home() / "nis-mcp" / "captures") + + +def log_dir() -> Path: + return Path(_env("NIS_LOG_DIR") or Path.home() / "nis-mcp" / "logs") + + +def estop_file() -> Path: + return _job.estop_file() + + +def allowed_magnifications() -> tuple[float, ...]: + return _job.parse_magnifications(_env("NIS_ALLOWED_OBJECTIVES") or _job.DEFAULT_ALLOWED_OBJECTIVES) + + +def allowed_experiments() -> list[str] | None: + """The names listed in NIS_ALLOWED_EXPERIMENTS (comma-separated), or None for any.""" + names = [n.strip() for n in _env("NIS_ALLOWED_EXPERIMENTS").split(",") if n.strip()] + return names or None + + +def max_step_um() -> float: + return float(_env("NIS_MAX_STEP_UM") or _job.DEFAULT_MAX_STEP_UM) + + +def estop_panel_disabled() -> bool: + return bool(_env("NIS_NO_ESTOP_PANEL")) + + +def monitor_disabled() -> bool: + return bool(_env("NIS_NO_MONITOR")) diff --git a/packages/nis-elements-mcp/src/nis_elements_mcp/testing.py b/packages/nis-elements-mcp/src/nis_elements_mcp/testing.py index 689752a..8217566 100644 --- a/packages/nis-elements-mcp/src/nis_elements_mcp/testing.py +++ b/packages/nis-elements-mcp/src/nis_elements_mcp/testing.py @@ -167,7 +167,8 @@ def bridge(estop_file, monkeypatch): t.start() assert ready.wait(5) url = f"http://127.0.0.1:{port[0]}" - monkeypatch.setenv("CONFOCAL_NIS_BRIDGE_URL", url) + monkeypatch.setenv("NIS_BRIDGE_HOST", "127.0.0.1") + monkeypatch.setenv("NIS_BRIDGE_PORT", str(port[0])) nis.ui = ui yield nis, url, client_mod.NISBridge(url) stop.set() diff --git a/packages/nis-elements-mcp/tests/test_estop.py b/packages/nis-elements-mcp/tests/test_estop.py index fe8e646..7b93b5c 100644 --- a/packages/nis-elements-mcp/tests/test_estop.py +++ b/packages/nis-elements-mcp/tests/test_estop.py @@ -62,9 +62,9 @@ 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("CONFOCAL_NO_ESTOP_PANEL") + monkeypatch.delenv("NIS_NO_ESTOP_PANEL") monkeypatch.setattr(estop, "panel_running", lambda: True) estop.launch_panel() assert opened == [] @@ -72,7 +72,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 +83,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/packages/nis-elements-mcp/tests/test_nis_bridge.py b/packages/nis-elements-mcp/tests/test_nis_bridge.py index cfea2e1..cb8d57c 100644 --- a/packages/nis-elements-mcp/tests/test_nis_bridge.py +++ b/packages/nis-elements-mcp/tests/test_nis_bridge.py @@ -163,7 +163,7 @@ def test_nis_server_exposes_exactly_the_nis_tools(tmp_path): 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", + env = dict(os.environ, NIS_NO_ESTOP_PANEL="1", NIS_NO_MONITOR="1", NIS_LOG_DIR=str(tmp_path / "logs"), NIS_CAPTURE_DIR=str(tmp_path / "caps")) params = StdioServerParameters(command=sys.executable, args=["-m", "nis_elements_mcp.nis_server"], env=env) async with Client(stdio_client(params)) as client: @@ -284,7 +284,7 @@ def test_monitor_says_busy_when_the_bridge_connects_but_does_not_answer(): 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.delenv("NIS_NO_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() @@ -293,7 +293,7 @@ def test_monitor_opens_once_when_the_server_starts(monkeypatch): 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 + monkeypatch.setenv("NIS_NO_MONITOR", "1") # switched off monitor.launch() assert opened == [] diff --git a/packages/nis-elements-mcp/tests/test_nis_events_monitor.py b/packages/nis-elements-mcp/tests/test_nis_events_monitor.py index 8aaffab..a65da82 100644 --- a/packages/nis-elements-mcp/tests/test_nis_events_monitor.py +++ b/packages/nis-elements-mcp/tests/test_nis_events_monitor.py @@ -62,7 +62,6 @@ def test_optical_configs_are_get_only_and_not_logged(bridge, events_log): 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 @@ -192,7 +191,7 @@ def read(self): 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.delenv("NIS_NO_MONITOR", raising=False) monkeypatch.setattr(monitor, "ON_WINDOWS", False) monitor.launch() assert opened == [] @@ -203,7 +202,7 @@ def boom(*a, **k): raise OSError("no console") monkeypatch.setattr(monitor.subprocess, "Popen", boom) - monkeypatch.delenv("CONFOCAL_NO_NIS_MONITOR", raising=False) + monkeypatch.delenv("NIS_NO_MONITOR", raising=False) monkeypatch.setattr(monitor, "ON_WINDOWS", True) monkeypatch.setattr(monitor, "monitor_running", lambda: False) monitor.launch() diff --git a/packages/nis-elements-mcp/tests/test_settings.py b/packages/nis-elements-mcp/tests/test_settings.py new file mode 100644 index 0000000..022fd5b --- /dev/null +++ b/packages/nis-elements-mcp/tests/test_settings.py @@ -0,0 +1,85 @@ +# The NIS_* settings: defaults, overrides, and the limits the client +# enforces before a request reaches NIS. +import pytest + +from nis_elements_mcp import nis_bridge_job as bj +from nis_elements_mcp import nis_tools, settings +from nis_elements_mcp.testing import bridge, estop_file # noqa: F401 (fixtures) + +SETTINGS = ("NIS_BRIDGE_HOST", "NIS_BRIDGE_PORT", "NIS_ESTOP_FILE", "NIS_ALLOWED_OBJECTIVES", + "NIS_ALLOWED_EXPERIMENTS", "NIS_MAX_STEP_UM", "NIS_NO_ESTOP_PANEL", "NIS_NO_MONITOR") + + +@pytest.fixture +def clean_env(monkeypatch, tmp_path): + for name in SETTINGS: + monkeypatch.delenv(name, raising=False) + monkeypatch.setattr(settings.Path, "home", lambda: tmp_path) + return tmp_path + + +def test_defaults(clean_env): + assert settings.bridge_url() == "http://127.0.0.1:8766" + assert settings.estop_file() == clean_env / ".nis-mcp" / "ESTOP" + assert settings.allowed_magnifications() == (4.0, 10.0) + assert settings.allowed_experiments() is None + assert settings.max_step_um() == 1000.0 + assert not settings.estop_panel_disabled() and not settings.monitor_disabled() + + +def test_overrides(clean_env, monkeypatch): + monkeypatch.setenv("NIS_BRIDGE_HOST", "10.0.0.5") + monkeypatch.setenv("NIS_BRIDGE_PORT", "9000") + monkeypatch.setenv("NIS_ESTOP_FILE", str(clean_env / "stop")) + monkeypatch.setenv("NIS_ALLOWED_OBJECTIVES", "4x, 10X, 20") + monkeypatch.setenv("NIS_ALLOWED_EXPERIMENTS", " Embryo 2h , Worm stack ") + monkeypatch.setenv("NIS_MAX_STEP_UM", "250") + monkeypatch.setenv("NIS_NO_ESTOP_PANEL", "1") + monkeypatch.setenv("NIS_NO_MONITOR", "1") + assert settings.bridge_url() == "http://10.0.0.5:9000" + assert settings.estop_file() == clean_env / "stop" + assert settings.allowed_magnifications() == (4.0, 10.0, 20.0) + assert settings.allowed_experiments() == ["Embryo 2h", "Worm stack"] + assert settings.max_step_um() == 250.0 + assert settings.estop_panel_disabled() and settings.monitor_disabled() + + +def test_magnification_is_read_from_the_objective_name(): + assert bj.magnification("PLAN APO λD 10x OFN25 DIC N1") == 10.0 + assert bj.magnification("Plan Apo 60x Oil") == 60.0 + assert bj.magnification("Plan Fluor 14x") == 14.0 # not the 4x inside it + assert bj.magnification("no magnification") is None + assert bj.magnification("4x or 10x") is None # ambiguous: refused + + +def test_a_step_over_the_limit_is_refused_before_it_is_sent(bridge, monkeypatch): + nis, url, c = bridge + monkeypatch.setenv("NIS_MAX_STEP_UM", "200") + assert "NIS_MAX_STEP_UM" in c.move_relative(250, 0)["error"] + assert c.move_relative(150, 0)["after_um"] == [250.0, 200.0] + assert nis.moved() == ["StgMoveXY"] # only the allowed step reached NIS + + +def test_an_objective_outside_the_allow_list_is_refused_before_it_is_sent(bridge, monkeypatch): + nis, url, c = bridge + monkeypatch.setenv("NIS_ALLOWED_OBJECTIVES", "10") + with pytest.raises(RuntimeError, match="NIS_ALLOWED_OBJECTIVES"): + nis_tools.nis_change_objective(nis.objectives[1], confirm=True) # the 4x + assert nis.moved() == [] + assert nis_tools.nis_change_objective("Plan Fluor 10x Ph1 DLL", confirm=True)["arrived"] is True + + +def test_the_bridge_keeps_its_own_objective_limit(bridge, monkeypatch): + nis, url, c = bridge + monkeypatch.setenv("NIS_ALLOWED_OBJECTIVES", "4,10,60") # the client would allow 60x ... + assert "only 4x/10x" in c.change_objective("Plan Apo 60x Oil")["error"] # ... the bridge does not + assert nis.moved() == [] + + +def test_only_listed_experiments_run_when_the_list_is_set(bridge, monkeypatch): + nis, url, c = bridge + monkeypatch.setenv("NIS_ALLOWED_EXPERIMENTS", "Embryo 2h,Worm stack") + with pytest.raises(RuntimeError, match="NIS_ALLOWED_EXPERIMENTS"): + nis_tools.nis_run_experiment("Something else", confirm=True) + assert "ND_LoadExperiment" not in nis.calls + assert nis_tools.nis_run_experiment("Worm stack", confirm=True)["nd_running"] is True diff --git a/tests/test_hardware_scripts.py b/tests/test_hardware_scripts.py index 8545836..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() diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 8fe33dc..1da8164 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -23,7 +23,7 @@ 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.baumer_ti2.baumer_ti2_server"], env=env) diff --git a/tests/test_nis_settings.py b/tests/test_nis_settings.py new file mode 100644 index 0000000..dcbb9eb --- /dev/null +++ b/tests/test_nis_settings.py @@ -0,0 +1,52 @@ +# This repo's settings for the nis-elements-mcp package (acquisition/_nis_settings.py). +from acquisition import _nis_settings +from nis_elements_mcp import settings + + +def _unset(monkeypatch, *names): + for name in names: + monkeypatch.setenv(name, "") # recorded first, so the undo removes what the call sets + monkeypatch.delenv(name) + + +def test_logs_and_captures_stay_in_this_repos_data_folder(tmp_path, monkeypatch): + _unset(monkeypatch, "NIS_LOG_DIR", "NIS_CAPTURE_DIR", "CONFOCAL_NIS_CAPTURE_DIR") + monkeypatch.setattr(_nis_settings.paths, "logs_dir", lambda: tmp_path / "logs") + monkeypatch.setattr(_nis_settings.paths, "data_root", lambda: tmp_path) + _nis_settings.use_repo_folders() + assert settings.log_dir() == tmp_path / "logs" / "nis" + assert settings.capture_dir() == tmp_path / "data" / "NIS" / "captures" + + +def test_a_stop_engaged_in_the_old_file_is_moved_not_lost(tmp_path, monkeypatch): + old, new = tmp_path / "old" / "ESTOP", tmp_path / "new" / "ESTOP" + old.parent.mkdir() + old.write_text('{"reason": "pressed before the switch"}') + monkeypatch.setenv("NIS_ESTOP_FILE", str(new)) + _nis_settings.carry_over_old_estop(old) + assert not old.exists() and "pressed before the switch" in new.read_text() + + +def test_an_engaged_new_file_is_kept_and_the_old_one_dropped(tmp_path, monkeypatch): + old, new = tmp_path / "ESTOP.old", tmp_path / "ESTOP" + old.write_text("old") + new.write_text("new") + monkeypatch.setenv("NIS_ESTOP_FILE", str(new)) + _nis_settings.carry_over_old_estop(old) + assert not old.exists() and new.read_text() == "new" + + +def test_nothing_happens_without_an_old_file(tmp_path, monkeypatch): + monkeypatch.setenv("NIS_ESTOP_FILE", str(tmp_path / "ESTOP")) + _nis_settings.carry_over_old_estop(tmp_path / "missing") + assert not (tmp_path / "ESTOP").exists() + + +def test_old_switch_names_still_work(monkeypatch): + _unset(monkeypatch, "NIS_NO_ESTOP_PANEL", "NIS_NO_MONITOR", "NIS_BRIDGE_HOST", "NIS_BRIDGE_PORT") + monkeypatch.setenv("CONFOCAL_NO_ESTOP_PANEL", "1") + monkeypatch.setenv("CONFOCAL_NO_NIS_MONITOR", "1") + monkeypatch.setenv("CONFOCAL_NIS_BRIDGE_URL", "http://127.0.0.1:9001") + _nis_settings.use_old_names() + assert settings.estop_panel_disabled() and settings.monitor_disabled() + assert settings.bridge_url() == "http://127.0.0.1:9001" diff --git a/tests/test_small_gaps.py b/tests/test_small_gaps.py index a3dbeeb..1d400f6 100644 --- a/tests/test_small_gaps.py +++ b/tests/test_small_gaps.py @@ -118,7 +118,7 @@ def run_cli(monkeypatch, *argv): 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") + monkeypatch.setenv("NIS_BRIDGE_PORT", "9") with pytest.raises(SystemExit, match="not reachable"): run_cli(monkeypatch, "status") estop_file.write_text("{}") @@ -209,7 +209,7 @@ def test_monitor_probe_is_false_off_windows(monkeypatch): 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.setenv("NIS_BRIDGE_PORT", "9") monkeypatch.setattr(sys, "argv", ["nis_monitor", "--once"]) monkeypatch.delitem(sys.modules, 'acquisition.nis_monitor', raising=False) # run it as a fresh `python -m` would runpy.run_module("acquisition.nis_monitor", run_name="__main__") From 731406d125925330f9e91090072714dad1d69944 Mon Sep 17 00:00:00 2001 From: Qurratul Ain Quais Date: Fri, 30 Oct 2026 18:14:50 -0400 Subject: [PATCH 07/12] nis-elements-mcp 0.1.0: README, CHANGELOG, MIT license, commands, standalone CI on Windows and Ubuntu --- .github/workflows/ci.yml | 26 ++- CHANGELOG.md | 5 + README.md | 20 +- packages/nis-elements-mcp/CHANGELOG.md | 32 ++++ packages/nis-elements-mcp/LICENSE | 21 ++ packages/nis-elements-mcp/README.md | 180 +++++++++++++++++- packages/nis-elements-mcp/pyproject.toml | 14 +- .../src/nis_elements_mcp/nis_bridge_client.py | 34 ++-- .../nis-elements-mcp/tests/test_job_file.py | 22 +++ 9 files changed, 327 insertions(+), 27 deletions(-) create mode 100644 packages/nis-elements-mcp/CHANGELOG.md create mode 100644 packages/nis-elements-mcp/LICENSE create mode 100644 packages/nis-elements-mcp/tests/test_job_file.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6d9a716..0e7d1dc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -27,10 +27,30 @@ jobs: python -m pytest -v tests --cov=acquisition --cov=harness --cov=mcp_server --cov=timelapse --cov=analysis --cov-report=term-missing --cov-fail-under=90 - # The NIS-Elements MCP package (packages/nis-elements-mcp) has its own - # tests; the install above already pulled the package in. - - run: python -m pytest -v packages/nis-elements-mcp/tests # 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.baumer_ti2.baumer_ti2_server, timelapse.scheduler" + + # The NIS-Elements MCP package on its own: installed (not editable) into a + # runner that has nothing else from this repo, on the OS it is used on + # (Windows) and on Linux. Its tests run against the installed copy. + nis-elements-mcp: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [windows-latest, ubuntu-latest] + python-version: ["3.11", "3.13"] + defaults: + run: + working-directory: packages/nis-elements-mcp + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + - run: pip install ".[test]" + - run: python -m pytest -v + # The installed commands exist and the bridge job file ships with the package. + - run: nis-mcp-bridge job-file + - run: nis-mcp-estop status diff --git a/CHANGELOG.md b/CHANGELOG.md index 62419b9..36aa272 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,11 @@ Format follows [Keep a Changelog](https://keepachangelog.com/); versions follow 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. ### Added - `analysis/worm_short.py` - C. elegans Short from an AML18 time-lapse diff --git a/README.md b/README.md index 8c54326..b203706 100644 --- a/README.md +++ b/README.md @@ -72,18 +72,22 @@ python -m timelapse.frame_audit FRAME_DIR --timestamps times.csv --around 25h -- ## NIS bridge (`nis-mcp`) - status, moves, objective and capture tested on the scope; ND runs not yet 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 -(`packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_job.py`) serves NIS macro calls on -`127.0.0.1:8766`. The `nis-mcp` server talks to it and adds a -confirm gate, the e-stop and a capture-folder rule. `baumer_ti2_server` is -unchanged. Setup, safety rules and the on-scope test plan: +lasers and saved ND experiments. It is its own package, +[`packages/nis-elements-mcp`](packages/nis-elements-mcp/README.md), which any +project can install; this repo depends on it from that folder. A JOBS Python +task inside NIS (`nis-mcp-bridge job-file` prints which file to paste) serves +NIS macro calls on `127.0.0.1:8766`. The server talks to it and adds a +confirm gate, limits, the e-stop and a capture-folder rule. +`baumer_ti2_server` is unchanged. On-scope test plan and results: [docs/nis-bridge.md](docs/nis-bridge.md). ``` -python -m acquisition.backends.nis_bridge status # by hand, while the bridge job runs +confocal-mcp-nis # the MCP server, with this repo's folders (logs/nis, data/NIS/captures) +python -m mcp_server.nis.nis_server # same, from a source checkout +nis-mcp # the package's server, default folders under ~/nis-mcp +python -m acquisition.backends.nis_bridge status # by hand, while the bridge job runs (or: nis-mcp-bridge status) +python -m acquisition.backends.nis_bridge shutdown # the only safe way to stop the bridge job python -m acquisition.nis_monitor # live view: status + every action (logs/nis/) -nis-mcp # the MCP server (old name: confocal-mcp-nis) -python -m mcp_server.nis.nis_server # same, from a source checkout ``` MCP client config for a source checkout (adjust the path to this repo's venv): diff --git a/packages/nis-elements-mcp/CHANGELOG.md b/packages/nis-elements-mcp/CHANGELOG.md new file mode 100644 index 0000000..7c1bb65 --- /dev/null +++ b/packages/nis-elements-mcp/CHANGELOG.md @@ -0,0 +1,32 @@ +# Changelog + +All notable changes to nis-elements-mcp are recorded here. +Format follows [Keep a Changelog](https://keepachangelog.com/); versions follow +[Semantic Versioning](https://semver.org/). + +## [0.1.0] - 2026-10-30 + +First release, extracted from the microscope-agent project. + +### Added +- MCP server `nis-mcp` with the tools `nis_status`, `nis_list_optical_configs`, + `nis_move_relative`, `nis_change_objective`, `nis_capture`, + `nis_run_experiment`, `nis_finish_experiment` and `estop`. +- Bridge job `nis_bridge_job.py` for a NIS-Elements JOBS Python task (standard + library only). Capture and ND calls run on NIS's main thread through a + Win32 timer; called from a worker thread they crashed NIS. +- Commands `nis-mcp-bridge` (by-hand client, `job-file`, `shutdown`), + `nis-mcp-estop` and `nis-mcp-monitor`. +- E-stop flag file checked by the client and by the bridge, with an + always-on-top STOP window. +- Event log and live monitor of every action sent through the bridge. +- Settings from `NIS_*` environment variables, including allow-lists for + objectives and ND experiments and an XY step limit, checked by the client + and again by the bridge. +- `nis_elements_mcp.testing`: a fake NIS and a pytest fixture for tests + without a microscope. + +### Known limits +- ND runs (`nis_run_experiment`, `nis_finish_experiment`) are not yet checked + on a microscope. +- The optical configuration cannot be selected through the bridge. diff --git a/packages/nis-elements-mcp/LICENSE b/packages/nis-elements-mcp/LICENSE new file mode 100644 index 0000000..0137d61 --- /dev/null +++ b/packages/nis-elements-mcp/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Qurratul Ain Quais + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/nis-elements-mcp/README.md b/packages/nis-elements-mcp/README.md index aca6ba5..6cd2630 100644 --- a/packages/nis-elements-mcp/README.md +++ b/packages/nis-elements-mcp/README.md @@ -1,7 +1,179 @@ # nis-elements-mcp -Drive a Nikon NIS-Elements microscope from an MCP client (such as Claude -Code), through a small bridge job that runs inside NIS-Elements. +Drive a Nikon microscope through **NIS-Elements** from an MCP client such as +Claude Code: read the stage and objective, move XY, change objective, capture +an image, and run ND experiments you saved in NIS, with an emergency stop and +hard safety limits. -Work in progress: setup, safety rules, settings and install instructions -follow in version 0.1.0. +NIS-Elements has no outside automation interface, so a small **bridge job** +runs inside NIS (as a JOBS Python task) and answers requests on +`127.0.0.1:8766`. The MCP server talks to that bridge. + +``` +MCP client (Claude Code) + │ stdio + ▼ +nis-mcp MCP server: confirm gate, limits, e-stop, event log + │ HTTP, 127.0.0.1:8766 + ▼ +nis_bridge_job.py JOBS Python task, runs inside nis_ar.exe + │ ctypes + ▼ +NIS macro functions StgMoveXY, Capture, ND_RunExperiment, ... +``` + +Tested on NIS-Elements AR with a Nikon Ti2 stand and an AX confocal (status, +optical configurations, XY moves, objective changes and capture). ND runs are +implemented and covered by tests but not yet checked on a microscope. + +## Requirements + +- Windows, with NIS-Elements and its **JOBS** module (Python task). +- Python 3.11 or newer on the same PC, for the MCP server. +- The bridge job itself needs nothing installed inside NIS: it uses only the + Python standard library. + +## Install into a project + +From the project folder, in PowerShell: + +```powershell +python -m venv .nis-mcp-env +.nis-mcp-env\Scripts\pip install "git+https://github.com/BioNanomics/microscope-agent#subdirectory=packages/nis-elements-mcp" +claude mcp add nis --scope local -- "$PWD\.nis-mcp-env\Scripts\nis-mcp.exe" +``` + +- If `python -m venv` or `pip install` fails with "The filename or extension + is too long" (WinError 206), the project folder's path is too deep for + Windows' 260-character limit: use a shorter folder, or turn on long paths + in Windows. +- Instead of the git URL you can give a local path, e.g. + `.nis-mcp-env\Scripts\pip install D:\path\to\microscope-agent\packages\nis-elements-mcp`. +- The full path (`$PWD\...`) makes the server start whatever folder Claude is + launched from. +- Pass settings with `-e`, before the `--`: + ```powershell + claude mcp add nis --scope local -e NIS_CAPTURE_DIR=D:\data\nis\captures -e NIS_LOG_DIR=D:\data\nis\logs -- "$PWD\.nis-mcp-env\Scripts\nis-mcp.exe" + ``` +- With [uv](https://docs.astral.sh/uv/), one line installs and registers it: + ```powershell + claude mcp add nis --scope local -- uvx --from "git+https://github.com/BioNanomics/microscope-agent#subdirectory=packages/nis-elements-mcp" nis-mcp + ``` + +## Set up the bridge in NIS + +1. Switch on the microscope stand, then start NIS-Elements. +2. Find the file to paste: + ```powershell + .nis-mcp-env\Scripts\nis-mcp-bridge job-file + ``` +3. In NIS, open **JOBS**, create a job with one **Python** task, replace the + task's code with the whole of that file, and 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 `. The job window + closes at once; the bridge keeps serving in the background. +5. Check it: `.nis-mcp-env\Scripts\nis-mcp-bridge status`. + +**Stop the bridge only with** +```powershell +.nis-mcp-env\Scripts\nis-mcp-bridge shutdown +``` +**Never press the JOBS Abort button**: a Python task cannot be interrupted +and NIS freezes. The job also ends by itself after 4 hours with no request. + +After upgrading this package, paste the job file into NIS again. + +## Tools + +| Tool | What it does | Needs `confirm=True` | +|---|---|---| +| `nis_status` | XY and Z position, objective, turret, ND run state, e-stop | no | +| `nis_list_optical_configs` | names of the optical configurations in NIS | no | +| `nis_move_relative(dx_um, dy_um)` | relative XY move | yes | +| `nis_change_objective(name)` | turn the turret to an allowed objective | yes | +| `nis_capture(filename)` | capture with the optical configuration active in NIS, save as `.nd2` in the capture folder | yes | +| `nis_run_experiment(experiment)` | run an ND experiment saved in NIS's ND Acquisition window | yes | +| `nis_finish_experiment()` | end the running ND experiment after its current loop | no | +| `estop(action)` | `engage` or `status`; release is not possible from the MCP client | no | + +The bridge cannot select an optical configuration (doing so froze NIS): +choose it in NIS before `nis_capture`. Activating an optical configuration in +NIS may also turn the turret to that configuration's objective. + +## Safety rules + +- Everything that moves or acquires needs **`confirm=True`**. +- **E-stop**: a flag file (`~/.nis-mcp/ESTOP`). While it exists, every move, + objective change, capture and ND run is refused, by the client and again by + the bridge inside NIS. Ending an ND run is always allowed. A STOP window + opens when the server starts. From a terminal: + ```powershell + .nis-mcp-env\Scripts\nis-mcp-estop engage + .nis-mcp-env\Scripts\nis-mcp-estop status + .nis-mcp-env\Scripts\nis-mcp-estop release # a person does this, never the MCP client + ``` +- XY moves are **relative**, at most **1000 µm per axis** per call. +- **Z is never moved.** There is no Z tool. +- Objective changes only to **4x and 10x** by default: their long working + distances cannot reach the sample. +- ND runs can be limited to named experiments. +- The client checks the limits before sending; the bridge checks the step + and objective limits again with its own settings. The stricter one wins. +- Captures go only into the capture folder, by plain file name, and never + overwrite a file. +- Motion and acquisition answer HTTP POST only, and the bridge listens on + 127.0.0.1 only. +- Laser power and saved ND experiments are never changed. + +## Settings + +All settings are environment variables, read by the MCP server (pass them +with `claude mcp add -e NAME=value`): + +| Variable | Meaning | Default | +|---|---|---| +| `NIS_BRIDGE_HOST` | bridge address | `127.0.0.1` | +| `NIS_BRIDGE_PORT` | bridge port | `8766` | +| `NIS_CAPTURE_DIR` | where `nis_capture` saves | `~/nis-mcp/captures` | +| `NIS_LOG_DIR` | event log folder | `~/nis-mcp/logs` | +| `NIS_ESTOP_FILE` | e-stop flag file | `~/.nis-mcp/ESTOP` | +| `NIS_ALLOWED_OBJECTIVES` | magnifications allowed, comma-separated | `4,10` | +| `NIS_ALLOWED_EXPERIMENTS` | ND experiment names allowed, comma-separated | empty: any saved one | +| `NIS_MAX_STEP_UM` | largest XY step per call, µm | `1000` | +| `NIS_NO_ESTOP_PANEL` | `1`: do not open the STOP window | off | +| `NIS_NO_MONITOR` | `1`: do not open the monitor window | off | + +The bridge job inside NIS reads `NIS_BRIDGE_PORT`, `NIS_ESTOP_FILE`, +`NIS_MAX_STEP_UM` and `NIS_ALLOWED_OBJECTIVES` from NIS's own environment, +which is usually empty, so it uses the same defaults. To change them there, +set the variables before starting NIS, or edit the defaults at the top of +the job file before pasting it. `NIS_ESTOP_FILE` must point to the same file +on both sides. + +## Watch what it does + +`nis-mcp-monitor` shows the stage, objective, ND state and e-stop, above a +live list of every action sent through the bridge. It opens by itself when +the server starts. Each action is also written to +`/events-.jsonl`. + +## Testing without a microscope + +`nis_elements_mcp.testing` has a fake NIS and a pytest fixture that runs the +real bridge on it, on a free port: + +```python +from nis_elements_mcp.testing import bridge, estop_file # noqa: F401 (fixtures) + +def test_my_script_moves(bridge): + nis, url, client = bridge + client.move_relative(100, 0) + assert nis.x == 200.0 +``` + +To run this package's own tests: `pip install -e ".[test]"`, then `pytest`. + +## License + +MIT, see [LICENSE](LICENSE). diff --git a/packages/nis-elements-mcp/pyproject.toml b/packages/nis-elements-mcp/pyproject.toml index d76a64c..40e0a5e 100644 --- a/packages/nis-elements-mcp/pyproject.toml +++ b/packages/nis-elements-mcp/pyproject.toml @@ -7,7 +7,16 @@ name = "nis-elements-mcp" version = "0.1.0" description = "MCP server that drives a Nikon NIS-Elements microscope through a bridge job running inside NIS" readme = "README.md" +license = "MIT" +license-files = ["LICENSE"] +authors = [{ name = "Qurratul Ain Quais" }] requires-python = ">=3.11" +keywords = ["mcp", "microscopy", "nikon", "nis-elements"] +classifiers = [ + "Programming Language :: Python :: 3", + "Operating System :: Microsoft :: Windows", + "Topic :: Scientific/Engineering :: Image Processing", +] dependencies = [ "mcp>=2.0,<3", ] @@ -16,7 +25,10 @@ dependencies = [ test = ["pytest>=8"] [project.scripts] -nis-mcp = "nis_elements_mcp.nis_server:main" +nis-mcp = "nis_elements_mcp.nis_server:main" # the MCP server +nis-mcp-bridge = "nis_elements_mcp.nis_bridge_client:main" # talk to the bridge by hand; job-file, shutdown +nis-mcp-estop = "nis_elements_mcp.estop:main" # engage / status / release +nis-mcp-monitor = "nis_elements_mcp.nis_monitor:main" # live view of the bridge [tool.hatch.build.targets.wheel] packages = ["src/nis_elements_mcp"] diff --git a/packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_client.py b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_client.py index 42f4ddd..9bc2136 100644 --- a/packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_client.py +++ b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_client.py @@ -1,18 +1,19 @@ -# nis_bridge.py +# nis_bridge_client.py # ------------------------------------------------------------ # Client for the NIS bridge (nis_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: +# hand (`nis-mcp-bridge`, or `python -m nis_elements_mcp.nis_bridge_client`): # -# python -m nis_elements_mcp.nis_bridge_client status -# python -m nis_elements_mcp.nis_bridge_client move 100 0 -# python -m nis_elements_mcp.nis_bridge_client objective "Plan Fluor 10x Ph1 DLL" -# python -m nis_elements_mcp.nis_bridge_client optconfs -# python -m nis_elements_mcp.nis_bridge_client capture D:\...\check.nd2 -# python -m nis_elements_mcp.nis_bridge_client nd-run "C. elegans 3h" -# python -m nis_elements_mcp.nis_bridge_client nd-finish -# python -m nis_elements_mcp.nis_bridge_client shutdown +# nis-mcp-bridge job-file # where the file to paste into NIS is +# nis-mcp-bridge status +# nis-mcp-bridge move 100 0 +# nis-mcp-bridge objective "Plan Fluor 10x Ph1 DLL" +# nis-mcp-bridge optconfs +# nis-mcp-bridge capture D:\...\check.nd2 +# nis-mcp-bridge nd-run "C. elegans 3h" +# nis-mcp-bridge nd-finish +# nis-mcp-bridge shutdown # the ONLY safe way to stop the bridge job # # 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 @@ -20,7 +21,7 @@ # shutting the bridge down are always allowed - they only end things. # # Every action here is also written to the NIS event log -# (nis_events.py), which `python -m nis_elements_mcp.nis_monitor` +# (nis_events.py), which `nis-mcp-monitor` # shows live. Status reads are not logged (the monitor polls them). # # NIS_BRIDGE_HOST / NIS_BRIDGE_PORT set the address (default @@ -37,8 +38,10 @@ import time import urllib.error import urllib.request +from pathlib import Path from nis_elements_mcp import estop, nis_events, settings +from nis_elements_mcp import nis_bridge_job from nis_elements_mcp.nis_bridge_job import magnification @@ -154,6 +157,11 @@ def _experiment_refusal(experiment: str) -> dict | None: return None +def job_file() -> Path: + """The bridge job to paste into a NIS JOBS Python task (nis_bridge_job.py).""" + return Path(nis_bridge_job.__file__).resolve() + + def main() -> None: ap = argparse.ArgumentParser(description="Talk to the NIS bridge job by hand.") ap.add_argument("--url", help="bridge address (default from NIS_BRIDGE_HOST/PORT, else http://127.0.0.1:8766)") @@ -170,7 +178,11 @@ def main() -> None: 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") + sub.add_parser("job-file", help="print the path of the file to paste into the NIS JOBS task") a = ap.parse_args() + if a.cmd == "job-file": + print(job_file()) + return b = NISBridge(a.url) try: diff --git a/packages/nis-elements-mcp/tests/test_job_file.py b/packages/nis-elements-mcp/tests/test_job_file.py new file mode 100644 index 0000000..bc77eed --- /dev/null +++ b/packages/nis-elements-mcp/tests/test_job_file.py @@ -0,0 +1,22 @@ +# `nis-mcp-bridge job-file`: where the file to paste into NIS is. Works with no bridge running. +import ast +import sys + +from nis_elements_mcp import nis_bridge_client as client_mod + + +def test_job_file_prints_the_bridge_job_path(monkeypatch, capsys): + monkeypatch.setenv("NIS_BRIDGE_PORT", "9") # nothing listens there: not needed + monkeypatch.setattr(sys, "argv", ["nis-mcp-bridge", "job-file"]) + client_mod.main() + path = capsys.readouterr().out.strip() + assert path.endswith("nis_bridge_job.py") and path == str(client_mod.job_file()) + + +def test_the_job_file_imports_only_the_standard_library(): + # NIS's own Python has nothing else installed, so the pasted file must stand alone. + tree = ast.parse(client_mod.job_file().read_text(encoding="utf-8")) + imported = {(n.module or "").split(".")[0] for n in ast.walk(tree) if isinstance(n, ast.ImportFrom)} + imported |= {a.name.split(".")[0] for n in ast.walk(tree) if isinstance(n, ast.Import) for a in n.names} + allowed = set(sys.stdlib_module_names) | {"__future__", "limjob"} # limjob is NIS's own + assert imported <= allowed, imported - allowed From 1d822cb3e2c9502a5e41cac1ed4ef4d315c3e32d Mon Sep 17 00:00:00 2001 From: Qurratul Ain Quais Date: Fri, 30 Oct 2026 18:29:40 -0400 Subject: [PATCH 08/12] Remove the old acquisition/nis_bridge forwarder: one bridge job file only --- CHANGELOG.md | 6 ++++++ acquisition/nis_bridge/__init__.py | 0 acquisition/nis_bridge/bridge_job.py | 20 -------------------- docs/nis-bridge.md | 1 - tests/test_small_gaps.py | 2 +- 5 files changed, 7 insertions(+), 22 deletions(-) delete mode 100644 acquisition/nis_bridge/__init__.py delete mode 100644 acquisition/nis_bridge/bridge_job.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 36aa272..8f30077 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,12 @@ Format follows [Keep a Changelog](https://keepachangelog.com/); versions follow `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/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 1e27d9e..0000000 --- a/acquisition/nis_bridge/bridge_job.py +++ /dev/null @@ -1,20 +0,0 @@ -# bridge_job.py -# ------------------------------------------------------------ -# Moved to the nis-elements-mcp package: nis_elements_mcp.nis_bridge_job -# (packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_job.py). -# This old name stays so existing imports and `python -m acquisition.nis_bridge.bridge_job` -# keep working. It is the same module object, not a copy, so settings -# and test patches made through either name reach the same code. -# -# DO NOT PASTE THIS FILE INTO NIS. Paste the package file instead: -# packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_job.py -# ------------------------------------------------------------ - -import sys - -if __name__ == "__main__": - import runpy - runpy.run_module("nis_elements_mcp.nis_bridge_job", run_name="__main__") -else: - from nis_elements_mcp import nis_bridge_job as _impl - sys.modules[__name__] = _impl diff --git a/docs/nis-bridge.md b/docs/nis-bridge.md index cef61ad..89b0ce7 100644 --- a/docs/nis-bridge.md +++ b/docs/nis-bridge.md @@ -56,7 +56,6 @@ separate server, `nis-mcp`. 2. In NIS, open **JOBS** and create a job with one **Python** task. 3. Replace the task's code with the whole of `packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_job.py` - (not `acquisition/nis_bridge/bridge_job.py`, which only forwards to it), then save the job, for example as `NIS bridge`. 4. Run the job. Its log shows diff --git a/tests/test_small_gaps.py b/tests/test_small_gaps.py index 1d400f6..d53a3d9 100644 --- a/tests/test_small_gaps.py +++ b/tests/test_small_gaps.py @@ -17,7 +17,7 @@ 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 nis_elements_mcp import nis_bridge_job as bj from acquisition.orchestration import stage_positions, worm_follow from harness import context from mcp_server.nis import nis_tools From 9434107bbc777de434085ea1c29a9956c4617f66 Mon Sep 17 00:00:00 2001 From: Qurratul Ain Quais Date: Fri, 30 Oct 2026 19:24:49 -0400 Subject: [PATCH 09/12] nis-elements-mcp: ND_LoadExperiment's return code is reported, not checked (it has none) --- packages/nis-elements-mcp/README.md | 5 +++++ .../src/nis_elements_mcp/nis_bridge_job.py | 7 +++++-- .../src/nis_elements_mcp/nis_tools.py | 11 +++++++---- .../src/nis_elements_mcp/testing.py | 2 +- .../nis-elements-mcp/tests/test_nis_bridge.py | 15 +++++++-------- 5 files changed, 25 insertions(+), 15 deletions(-) diff --git a/packages/nis-elements-mcp/README.md b/packages/nis-elements-mcp/README.md index 6cd2630..71e0a14 100644 --- a/packages/nis-elements-mcp/README.md +++ b/packages/nis-elements-mcp/README.md @@ -97,6 +97,11 @@ After upgrading this package, paste the job file into NIS again. | `nis_finish_experiment()` | end the running ND experiment after its current loop | no | | `estop(action)` | `engage` or `status`; release is not possible from the MCP client | no | +NIS does not report whether `nis_run_experiment` found the saved name +(`ND_LoadExperiment` has no return value): if the name is wrong, NIS runs +whatever the ND Acquisition window currently holds. Check the name, and set +`NIS_ALLOWED_EXPERIMENTS` to the names you mean to run. + The bridge cannot select an optical configuration (doing so froze NIS): choose it in NIS before `nis_capture`. Activating an optical configuration in NIS may also turn the turret to that configuration's objective. diff --git a/packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_job.py b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_job.py index 332cd2f..551be67 100644 --- a/packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_job.py +++ b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_job.py @@ -336,9 +336,12 @@ def on_main_thread() -> dict: return {"error": "e-stop engaged - ND run refused", "estop_engaged": True} if self.m.ND_IsInExperimentCapture(): return {"error": "an ND experiment is already running"} + # ND_LoadExperiment and ND_RunExperiment have no documented return + # value (NIS macro reference), and on the scope ND_LoadExperiment + # returned 0 for a template that does load (2026-10-30). So the + # codes are reported, not checked: NIS runs whatever the ND + # Acquisition window holds after the load. 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, diff --git a/packages/nis-elements-mcp/src/nis_elements_mcp/nis_tools.py b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_tools.py index 4d67405..18d5284 100644 --- a/packages/nis-elements-mcp/src/nis_elements_mcp/nis_tools.py +++ b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_tools.py @@ -119,10 +119,13 @@ def nis_capture(filename: str, confirm: bool = False) -> dict: 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, or if NIS_ALLOWED_EXPERIMENTS is set and does not list it. - Requires confirm=True.""" + saved settings (time loop, Z, channels, save-to-file path). NIS does + not report whether the name was found: if it was not, NIS runs + whatever the ND Acquisition window currently holds - so check that + window, or the name, with the operator first. The call may not return + until the experiment ends. Refused if one is already running, or if + NIS_ALLOWED_EXPERIMENTS is set and does not list it. Requires + confirm=True.""" _require_confirm(confirm, "nis_run_experiment") return _checked(_bridge().nd_run(experiment)) diff --git a/packages/nis-elements-mcp/src/nis_elements_mcp/testing.py b/packages/nis-elements-mcp/src/nis_elements_mcp/testing.py index 8217566..9696378 100644 --- a/packages/nis-elements-mcp/src/nis_elements_mcp/testing.py +++ b/packages/nis-elements-mcp/src/nis_elements_mcp/testing.py @@ -40,7 +40,7 @@ def __init__(self): 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.load_rc = 0 # what the real ND_LoadExperiment returned (it has no documented value) self.calls = [] self.threads = {} # call name -> id of the thread that made it self.last_saved = None diff --git a/packages/nis-elements-mcp/tests/test_nis_bridge.py b/packages/nis-elements-mcp/tests/test_nis_bridge.py index cb8d57c..f07d2b2 100644 --- a/packages/nis-elements-mcp/tests/test_nis_bridge.py +++ b/packages/nis-elements-mcp/tests/test_nis_bridge.py @@ -115,12 +115,11 @@ def test_capture_saves_nd2_and_never_overwrites(bridge, tmp_path): assert "nd2" in c.capture(str(tmp_path / "x.tif"))["error"] -def test_nd_run_refuses_second_run_and_reports_load_failure(bridge): +def test_nd_run_reports_the_load_code_and_refuses_a_second_run(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 + r = c.nd_run("C. elegans 3h") # load returns 0, as on the scope: not a failure + assert r["rc_load"] == 0 and r["nd_running"] is True + assert nis.calls.index("ND_LoadExperiment") < nis.calls.index("ND_RunExperiment") assert "already running" in c.nd_run("C. elegans 3h")["error"] @@ -193,9 +192,9 @@ def test_tools_raise_on_bridge_refusals_and_failures(bridge, tmp_path, monkeypat 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) + nis.nd_running = True + with pytest.raises(RuntimeError, match="already running"): # a refusal raises + nis_tools.nis_run_experiment("second", confirm=True) def test_tool_raises_when_the_turret_does_not_arrive(bridge, monkeypatch): From 27bce7bcc89674e6e3498017a4cfc54d6990e1b8 Mon Sep 17 00:00:00 2001 From: Qurratul Ain Quais Date: Fri, 30 Oct 2026 19:36:32 -0400 Subject: [PATCH 10/12] nis-elements-mcp README: numbered setup steps and known limits from the scope tests --- packages/nis-elements-mcp/CHANGELOG.md | 9 +- packages/nis-elements-mcp/README.md | 125 +++++++++++++++++-------- 2 files changed, 94 insertions(+), 40 deletions(-) diff --git a/packages/nis-elements-mcp/CHANGELOG.md b/packages/nis-elements-mcp/CHANGELOG.md index 7c1bb65..8a0b13c 100644 --- a/packages/nis-elements-mcp/CHANGELOG.md +++ b/packages/nis-elements-mcp/CHANGELOG.md @@ -26,7 +26,12 @@ First release, extracted from the microscope-agent project. - `nis_elements_mcp.testing`: a fake NIS and a pytest fixture for tests without a microscope. +### Fixed +- `ND_LoadExperiment`'s return code is reported, not treated as a failure: + it has no documented value and returned 0 for a template that loads. + ### Known limits -- ND runs (`nis_run_experiment`, `nis_finish_experiment`) are not yet checked - on a microscope. +- An ND run blocks the bridge until it ends, so `nis_finish_experiment` + cannot end a run early yet (checked on the microscope 2026-10-30). - The optical configuration cannot be selected through the bridge. +- The STOP and monitor windows close when the MCP client disconnects. diff --git a/packages/nis-elements-mcp/README.md b/packages/nis-elements-mcp/README.md index 71e0a14..357fa14 100644 --- a/packages/nis-elements-mcp/README.md +++ b/packages/nis-elements-mcp/README.md @@ -22,67 +22,101 @@ nis_bridge_job.py JOBS Python task, runs inside nis_ar.exe NIS macro functions StgMoveXY, Capture, ND_RunExperiment, ... ``` -Tested on NIS-Elements AR with a Nikon Ti2 stand and an AX confocal (status, -optical configurations, XY moves, objective changes and capture). ND runs are -implemented and covered by tests but not yet checked on a microscope. +Tested on NIS-Elements AR with a Nikon Ti2 stand and an AX confocal: status, +optical configurations, XY moves, objective changes, capture, the e-stop and +ND runs. Ending an ND run early is not yet possible (see Known limits). ## Requirements - Windows, with NIS-Elements and its **JOBS** module (Python task). - Python 3.11 or newer on the same PC, for the MCP server. -- The bridge job itself needs nothing installed inside NIS: it uses only the - Python standard library. +- Claude Code, if you want to use it from Claude. +- The bridge job needs nothing installed inside NIS: it uses only the Python + standard library. -## Install into a project +## Setup, step by step -From the project folder, in PowerShell: +Run the commands in **PowerShell**, in your project's folder. + +### Step 1. Create a Python environment for the server ```powershell python -m venv .nis-mcp-env +``` + +> If this fails with "The filename or extension is too long" (WinError 206), +> your project folder's path is too deep for Windows' 260-character limit. +> Use a shorter folder, or turn on long paths in Windows. + +### Step 2. Install the package + +```powershell .nis-mcp-env\Scripts\pip install "git+https://github.com/BioNanomics/microscope-agent#subdirectory=packages/nis-elements-mcp" +``` + +> From a local copy instead of GitHub: +> `.nis-mcp-env\Scripts\pip install D:\path\to\microscope-agent\packages\nis-elements-mcp` + +### Step 3. Register the server with Claude Code + +```powershell claude mcp add nis --scope local -- "$PWD\.nis-mcp-env\Scripts\nis-mcp.exe" ``` -- If `python -m venv` or `pip install` fails with "The filename or extension - is too long" (WinError 206), the project folder's path is too deep for - Windows' 260-character limit: use a shorter folder, or turn on long paths - in Windows. -- Instead of the git URL you can give a local path, e.g. - `.nis-mcp-env\Scripts\pip install D:\path\to\microscope-agent\packages\nis-elements-mcp`. -- The full path (`$PWD\...`) makes the server start whatever folder Claude is - launched from. -- Pass settings with `-e`, before the `--`: - ```powershell - claude mcp add nis --scope local -e NIS_CAPTURE_DIR=D:\data\nis\captures -e NIS_LOG_DIR=D:\data\nis\logs -- "$PWD\.nis-mcp-env\Scripts\nis-mcp.exe" - ``` -- With [uv](https://docs.astral.sh/uv/), one line installs and registers it: - ```powershell - claude mcp add nis --scope local -- uvx --from "git+https://github.com/BioNanomics/microscope-agent#subdirectory=packages/nis-elements-mcp" nis-mcp - ``` +> - `$PWD\...` puts in the full path, so the server starts whatever folder +> Claude is launched from. +> - To choose your own folders or limits, add `-e NAME=value` before the `--` +> (all names are in [Settings](#settings)): +> ```powershell +> claude mcp add nis --scope local -e NIS_CAPTURE_DIR=D:\data\nis\captures -e NIS_LOG_DIR=D:\data\nis\logs -- "$PWD\.nis-mcp-env\Scripts\nis-mcp.exe" +> ``` +> - With [uv](https://docs.astral.sh/uv/), one line replaces Steps 1 to 3: +> ```powershell +> claude mcp add nis --scope local -- uvx --from "git+https://github.com/BioNanomics/microscope-agent#subdirectory=packages/nis-elements-mcp" nis-mcp +> ``` + +### Step 4. Start the microscope and NIS -## Set up the bridge in NIS +Switch on the microscope stand first, then start NIS-Elements. -1. Switch on the microscope stand, then start NIS-Elements. -2. Find the file to paste: +### Step 5. Put the bridge job into NIS (once, and again after each upgrade) + +1. Print the path of the file to paste: ```powershell .nis-mcp-env\Scripts\nis-mcp-bridge job-file ``` -3. In NIS, open **JOBS**, create a job with one **Python** task, replace the - task's code with the whole of that file, and 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 `. The job window - closes at once; the bridge keeps serving in the background. -5. Check it: `.nis-mcp-env\Scripts\nis-mcp-bridge status`. - -**Stop the bridge only with** +2. Open that file in a text editor and copy all of it. Its first line is + `# IMPORTANT: 'limjob' must be imported like this (not from nor as)`. +3. In NIS, open **JOBS** and create a job with one **Python** task. +4. Replace the task's code with what you copied (Ctrl+A, Ctrl+V). +5. Save the job, for example as `NIS bridge`. + +### Step 6. Run the bridge and check it + +1. Run the job in NIS. The job window closes at once; the bridge keeps + running in the background. +2. Check that it answers: + ```powershell + .nis-mcp-env\Scripts\nis-mcp-bridge status + ``` + You should see the stage position and the objectives on the turret. + +### Step 7. Use it from Claude + +Start a **new** Claude Code session in the project folder (a server added +in Step 3 appears in new sessions only), and ask, for example, "What is the +microscope's status?". A red STOP window and a monitor window open when the +server starts. + +### When you are done: stop the bridge + ```powershell .nis-mcp-env\Scripts\nis-mcp-bridge shutdown ``` -**Never press the JOBS Abort button**: a Python task cannot be interrupted -and NIS freezes. The job also ends by itself after 4 hours with no request. -After upgrading this package, paste the job file into NIS again. +**Never press the JOBS Abort button**: a Python task cannot be interrupted +and NIS freezes. The bridge also stops by itself after 4 hours with no +request. ## Tools @@ -179,6 +213,21 @@ def test_my_script_moves(bridge): To run this package's own tests: `pip install -e ".[test]"`, then `pytest`. +## Known limits + +1. **An ND run blocks the bridge until it ends.** `nis_run_experiment` + returns only when the run is over, and nothing else (not even + `nis_status` or `nis_finish_experiment`) is answered meanwhile. Ending a + run early from MCP is therefore not possible yet; use NIS's own **Finish** + button in the ND Progress window. +2. **The optical configuration cannot be selected** through the bridge: + choose it in NIS before `nis_capture`. +3. **NIS does not report whether a saved ND experiment was found** (see + Tools); set `NIS_ALLOWED_EXPERIMENTS`. +4. **The STOP and monitor windows close when the MCP client disconnects.** + The e-stop itself (the flag file) keeps working; open the STOP window by + hand with `.nis-mcp-env\Scripts\pythonw -m nis_elements_mcp.estop_panel`. + ## License MIT, see [LICENSE](LICENSE). From c7974c141757868b937717ba53ce0224802442b7 Mon Sep 17 00:00:00 2001 From: Qurratul Ain Quais Date: Fri, 30 Oct 2026 19:52:21 -0400 Subject: [PATCH 11/12] nis-elements-mcp README: not affiliated with Nikon, no Nikon code, trademark notice --- packages/nis-elements-mcp/README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/packages/nis-elements-mcp/README.md b/packages/nis-elements-mcp/README.md index 357fa14..d50b3a2 100644 --- a/packages/nis-elements-mcp/README.md +++ b/packages/nis-elements-mcp/README.md @@ -231,3 +231,8 @@ To run this package's own tests: `pip install -e ".[test]"`, then `pytest`. ## License MIT, see [LICENSE](LICENSE). + +This project is not affiliated with, endorsed by, or supported by Nikon. +It contains no Nikon code: the bridge calls NIS-Elements' own macro +functions on a PC where NIS-Elements is already installed and licensed. +Nikon and NIS-Elements are trademarks of Nikon Corporation. From a471ca7c1313a56779938a2ed7c2641faa698866 Mon Sep 17 00:00:00 2001 From: Qurratul Ain Quais Date: Mon, 2 Nov 2026 22:58:52 -0500 Subject: [PATCH 12/12] Remove everything NIS-Elements: it now lives in the nis-elements-mcp repo The nis-elements-mcp package moved, with its history, to BioNanomics/nis-elements-mcp (bridge/). Removed here: packages/, mcp_server/nis/, the NIS forwarders in acquisition/, nis_port_probe.py, docs/nis-bridge.md, the NIS tests, the confocal-mcp-nis command and the package's CI job. acquisition/estop.py and estop_panel.py are real modules again, with their tests, and keep the shared e-stop file (~/.nis-mcp/ESTOP) and panel mutex, so one STOP still stops the Ti2 scripts and NIS together. nis_sdk.py and nis_mock.py stay: they drive the Ti2 stage, not NIS-Elements. --- .github/workflows/ci.yml | 23 - CHANGELOG.md | 15 + README.md | 34 +- acquisition/_nis_settings.py | 75 --- acquisition/backends/nis_bridge.py | 19 - acquisition/backends/nis_sdk.py | 2 +- acquisition/calibration/nis_port_probe.py | 117 ----- acquisition/estop.py | 220 +++++++- acquisition/estop_panel.py | 177 ++++++- acquisition/nis_events.py | 19 - acquisition/nis_monitor.py | 19 - docs/nis-bridge.md | 222 --------- mcp_server/nis/__init__.py | 6 - mcp_server/nis/nis_server.py | 19 - mcp_server/nis/nis_tools.py | 19 - packages/nis-elements-mcp/CHANGELOG.md | 37 -- packages/nis-elements-mcp/LICENSE | 21 - packages/nis-elements-mcp/README.md | 238 --------- packages/nis-elements-mcp/pyproject.toml | 37 -- .../src/nis_elements_mcp/__init__.py | 8 - .../src/nis_elements_mcp/estop.py | 211 -------- .../src/nis_elements_mcp/estop_panel.py | 174 ------- .../src/nis_elements_mcp/nis_bridge_client.py | 205 -------- .../src/nis_elements_mcp/nis_bridge_job.py | 470 ------------------ .../src/nis_elements_mcp/nis_events.py | 102 ---- .../src/nis_elements_mcp/nis_monitor.py | 196 -------- .../src/nis_elements_mcp/nis_server.py | 38 -- .../src/nis_elements_mcp/nis_tools.py | 184 ------- .../src/nis_elements_mcp/settings.py | 76 --- .../src/nis_elements_mcp/testing.py | 192 ------- packages/nis-elements-mcp/tests/conftest.py | 8 - .../nis-elements-mcp/tests/test_job_file.py | 22 - .../nis-elements-mcp/tests/test_nis_bridge.py | 357 ------------- .../tests/test_nis_events_monitor.py | 218 -------- .../nis-elements-mcp/tests/test_settings.py | 85 ---- pyproject.toml | 10 +- tests/test_calibration.py | 84 ---- .../tests => tests}/test_estop.py | 7 +- .../tests => tests}/test_estop_panel.py | 71 +-- tests/test_nis_settings.py | 52 -- tests/test_small_gaps.py | 184 +------ 41 files changed, 416 insertions(+), 3857 deletions(-) delete mode 100644 acquisition/_nis_settings.py delete mode 100644 acquisition/backends/nis_bridge.py delete mode 100644 acquisition/calibration/nis_port_probe.py delete mode 100644 acquisition/nis_events.py delete mode 100644 acquisition/nis_monitor.py delete mode 100644 docs/nis-bridge.md delete mode 100644 mcp_server/nis/__init__.py delete mode 100644 mcp_server/nis/nis_server.py delete mode 100644 mcp_server/nis/nis_tools.py delete mode 100644 packages/nis-elements-mcp/CHANGELOG.md delete mode 100644 packages/nis-elements-mcp/LICENSE delete mode 100644 packages/nis-elements-mcp/README.md delete mode 100644 packages/nis-elements-mcp/pyproject.toml delete mode 100644 packages/nis-elements-mcp/src/nis_elements_mcp/__init__.py delete mode 100644 packages/nis-elements-mcp/src/nis_elements_mcp/estop.py delete mode 100644 packages/nis-elements-mcp/src/nis_elements_mcp/estop_panel.py delete mode 100644 packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_client.py delete mode 100644 packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_job.py delete mode 100644 packages/nis-elements-mcp/src/nis_elements_mcp/nis_events.py delete mode 100644 packages/nis-elements-mcp/src/nis_elements_mcp/nis_monitor.py delete mode 100644 packages/nis-elements-mcp/src/nis_elements_mcp/nis_server.py delete mode 100644 packages/nis-elements-mcp/src/nis_elements_mcp/nis_tools.py delete mode 100644 packages/nis-elements-mcp/src/nis_elements_mcp/settings.py delete mode 100644 packages/nis-elements-mcp/src/nis_elements_mcp/testing.py delete mode 100644 packages/nis-elements-mcp/tests/conftest.py delete mode 100644 packages/nis-elements-mcp/tests/test_job_file.py delete mode 100644 packages/nis-elements-mcp/tests/test_nis_bridge.py delete mode 100644 packages/nis-elements-mcp/tests/test_nis_events_monitor.py delete mode 100644 packages/nis-elements-mcp/tests/test_settings.py rename {packages/nis-elements-mcp/tests => tests}/test_estop.py (92%) rename {packages/nis-elements-mcp/tests => tests}/test_estop_panel.py (70%) delete mode 100644 tests/test_nis_settings.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0e7d1dc..8936754 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,26 +31,3 @@ jobs: # 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.baumer_ti2.baumer_ti2_server, timelapse.scheduler" - - # The NIS-Elements MCP package on its own: installed (not editable) into a - # runner that has nothing else from this repo, on the OS it is used on - # (Windows) and on Linux. Its tests run against the installed copy. - nis-elements-mcp: - runs-on: ${{ matrix.os }} - strategy: - matrix: - os: [windows-latest, ubuntu-latest] - python-version: ["3.11", "3.13"] - defaults: - run: - working-directory: packages/nis-elements-mcp - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 - with: - python-version: ${{ matrix.python-version }} - - run: pip install ".[test]" - - run: python -m pytest -v - # The installed commands exist and the bridge job file ships with the package. - - run: nis-mcp-bridge job-file - - run: nis-mcp-estop status diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f30077..e376e42 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,21 @@ 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`; diff --git a/README.md b/README.md index b203706..f5673e5 100644 --- a/README.md +++ b/README.md @@ -69,35 +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 (`nis-mcp`) - status, moves, objective and capture tested on the scope; ND runs not yet +## NIS-Elements -A separate MCP server for what only NIS-Elements can do: the AX confocal -lasers and saved ND experiments. It is its own package, -[`packages/nis-elements-mcp`](packages/nis-elements-mcp/README.md), which any -project can install; this repo depends on it from that folder. A JOBS Python -task inside NIS (`nis-mcp-bridge job-file` prints which file to paste) serves -NIS macro calls on `127.0.0.1:8766`. The server talks to it and adds a -confirm gate, limits, the e-stop and a capture-folder rule. -`baumer_ti2_server` is unchanged. On-scope test plan and results: -[docs/nis-bridge.md](docs/nis-bridge.md). - -``` -confocal-mcp-nis # the MCP server, with this repo's folders (logs/nis, data/NIS/captures) -python -m mcp_server.nis.nis_server # same, from a source checkout -nis-mcp # the package's server, default folders under ~/nis-mcp -python -m acquisition.backends.nis_bridge status # by hand, while the bridge job runs (or: nis-mcp-bridge status) -python -m acquisition.backends.nis_bridge shutdown # the only safe way to stop the bridge job -python -m acquisition.nis_monitor # live view: status + every action (logs/nis/) -``` - -MCP client config for a source checkout (adjust the path to this repo's venv): - -```json -{ "mcpServers": { "nis": { - "command": "D:\\path\\to\\microscope-agent\\.venv\\Scripts\\python.exe", - "args": ["-m", "mcp_server.nis.nis_server"], - "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 diff --git a/acquisition/_nis_settings.py b/acquisition/_nis_settings.py deleted file mode 100644 index 4c2a7a1..0000000 --- a/acquisition/_nis_settings.py +++ /dev/null @@ -1,75 +0,0 @@ -# _nis_settings.py -# ------------------------------------------------------------ -# This repo's settings for the nis-elements-mcp package -# (packages/nis-elements-mcp, see its settings.py). The forwarders that -# lead into the package (acquisition/estop*.py, acquisition/nis_*.py, -# acquisition/backends/nis_bridge.py, mcp_server/nis/) import this first. -# A variable that is already set wins, so an MCP client config can still -# override any of them. Child processes (STOP panel, monitor) inherit them. -# -# * Logs and captures stay where they always were: logs/nis and -# data/NIS/captures under the data folder (acquisition/paths.py). -# * The e-stop is the package default, ~/.nis-mcp/ESTOP, because the -# bridge job inside NIS uses that default and cannot see this repo's -# settings. A stop still engaged in the old file (~/.confocal-mcp/ESTOP, -# before 2026-10-30) is moved there, so a switch never loses a stop. -# * The old CONFOCAL_* names of the package's switches still work. -# ------------------------------------------------------------ - -import os -import sys -from pathlib import Path -from urllib.parse import urlsplit - -from acquisition import paths -from nis_elements_mcp import settings - - -def use_repo_folders() -> None: - """Logs in logs/nis and captures in data/NIS/captures, unless already set.""" - os.environ.setdefault("NIS_LOG_DIR", str(paths.logs_dir() / "nis")) - os.environ.setdefault("NIS_CAPTURE_DIR", os.environ.get("CONFOCAL_NIS_CAPTURE_DIR") - or str(paths.data_root() / "data" / "NIS" / "captures")) - - -use_repo_folders() - - -def use_old_names() -> None: - """Honour the switches' names from before the package (CONFOCAL_*).""" - for old, new in (("CONFOCAL_NO_ESTOP_PANEL", "NIS_NO_ESTOP_PANEL"), - ("CONFOCAL_NO_NIS_MONITOR", "NIS_NO_MONITOR")): - if os.environ.get(old): - os.environ.setdefault(new, os.environ[old]) - if os.environ.get("CONFOCAL_NIS_BRIDGE_URL"): - url = urlsplit(os.environ["CONFOCAL_NIS_BRIDGE_URL"]) - os.environ.setdefault("NIS_BRIDGE_HOST", url.hostname or "127.0.0.1") - os.environ.setdefault("NIS_BRIDGE_PORT", str(url.port or 8766)) - - -use_old_names() - -OLD_ESTOP_FILE = Path.home() / ".confocal-mcp" / "ESTOP" - - -def carry_over_old_estop(old: Path = OLD_ESTOP_FILE) -> None: - """Move a stop engaged in the old e-stop file to the current one. - - If the old file cannot be removed it stays, and the stop is engaged - again on the next start: failing towards stopped, never towards moving. - """ - try: - if not old.exists(): - return - new = settings.estop_file() - if not new.exists(): - new.parent.mkdir(parents=True, exist_ok=True) - new.write_bytes(old.read_bytes()) - old.unlink() - print(f"[estop] moved the engaged e-stop from {old} to {new}", file=sys.stderr) - except OSError as exc: - print(f"[estop] could not move the old e-stop file {old} ({exc}); " - f"delete it by hand once {settings.estop_file()} is engaged", file=sys.stderr) - - -carry_over_old_estop() diff --git a/acquisition/backends/nis_bridge.py b/acquisition/backends/nis_bridge.py deleted file mode 100644 index c38fcd8..0000000 --- a/acquisition/backends/nis_bridge.py +++ /dev/null @@ -1,19 +0,0 @@ -# nis_bridge.py -# ------------------------------------------------------------ -# Moved to the nis-elements-mcp package: nis_elements_mcp.nis_bridge_client -# (packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_client.py). -# This old name stays so existing imports and `python -m acquisition.backends.nis_bridge` -# keep working. It is the same module object, not a copy, so settings -# and test patches made through either name reach the same code. -# ------------------------------------------------------------ - -import sys - -from acquisition import _nis_settings # noqa: F401 (this repo's log and capture folders) - -if __name__ == "__main__": - import runpy - runpy.run_module("nis_elements_mcp.nis_bridge_client", run_name="__main__") -else: - from nis_elements_mcp import nis_bridge_client as _impl - sys.modules[__name__] = _impl diff --git a/acquisition/backends/nis_sdk.py b/acquisition/backends/nis_sdk.py index 26f52e4..cdf6eff 100644 --- a/acquisition/backends/nis_sdk.py +++ b/acquisition/backends/nis_sdk.py @@ -194,7 +194,7 @@ def XY_Move(self, x: float, y: float) -> None: # E-STOP FIRST, before range checks, before anything. This is the # lowest point every XY move passes through, which is the only # place a stop can be effective against a caller that is already - # misbehaving - see nis_elements_mcp/estop.py's header for the incident + # misbehaving - see acquisition/estop.py's header for the incident # this exists because of. estop.check() before = self.XY_GetPosition() diff --git a/acquisition/calibration/nis_port_probe.py b/acquisition/calibration/nis_port_probe.py deleted file mode 100644 index f5653cf..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 nis_elements_mcp/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 = os.environ.get("NIS_ESTOP_FILE") or os.path.join(os.path.expanduser("~"), ".nis-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/estop.py b/acquisition/estop.py index 804704e..1944e9b 100644 --- a/acquisition/estop.py +++ b/acquisition/estop.py @@ -1,19 +1,217 @@ # estop.py # ------------------------------------------------------------ -# Moved to the nis-elements-mcp package: nis_elements_mcp.estop -# (packages/nis-elements-mcp/src/nis_elements_mcp/estop.py). -# This old name stays so existing imports and `python -m acquisition.estop` -# keep working. It is the same module object, not a copy, so settings -# and test patches made through either name reach the same code. +# Emergency stop for every process that can move this microscope. +# +# python -m acquisition.estop engage # STOP EVERYTHING, NOW +# python -m acquisition.estop status +# python -m acquisition.estop release # deliberate, separate action +# +# WHY THIS EXISTS. On 2026-09-21 a mosaic raster with a bad focus plane +# began driving Z toward the sample. Stopping it took several minutes and +# three separate interventions, because every mechanism available was the +# wrong shape: +# +# * stopping the background SHELL left its python CHILD running, still +# issuing moves - the process list, not the task list, was the truth +# * a tool call the operator REJECTED had already spawned its process, +# which kept looping Z moves regardless of the rejection +# * a "STOP file" checked once per mosaic tile is not a stop; between +# checks it still issued dozens of moves +# * the Ti2 SDK has NO abort/halt command (searched: only ZESCAPE, which +# is a retract, not a stop), so there is nothing to "cancel" with +# +# The lesson is that an e-stop must sit BELOW whatever is misbehaving. So +# this is enforced inside nis_sdk's move primitives themselves: no caller, +# no matter how confused, can move an axis while the stop is engaged, +# because the check happens after the caller has already decided to move. +# +# WHY A FILE. It must work across processes that do not know about each +# other - that was the whole failure. A file is visible to every process, +# survives the death of whoever set it, needs no server or port, and can +# be set by a human from any shell (or by creating the file by hand) when +# the agent itself is the thing malfunctioning. +# +# WHY A FIXED PATH, NOT data_root(). data_root() resolves relative to the +# working directory, and an MCP server launched by a desktop client gets a +# different cwd than a terminal. Two processes would then disagree about +# where the e-stop lives, which is precisely the failure this must not +# 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 +# refused move and a clear message, which is recoverable; the cost of +# failing open is a driven objective. +# +# WHAT IT DOES NOT DO: it cannot stop a move the controller has already +# accepted. A move in flight runs to its end; the stop takes effect at the +# next move. move_xy splits long moves into HOP_UM hops, so an XY move +# stops within one hop (measured: 0.54 s, <= 4 mm). +# +# WHY NO HALT. engage() used to also write the current position back as +# the target, to freeze an axis mid-travel. estop_inflight_test showed +# that is worse than nothing: position reads are cached for the whole move +# (XY and Z), so the "current" position is the START, and the write queues +# behind the move. A 1 mm Z move ran to its end, then the halt drove Z all +# the way back - a second move, issued by the stop. Never add it back. # ------------------------------------------------------------ +from __future__ import annotations + +import argparse +import datetime +import json +import os +import subprocess import sys +from pathlib import Path + +#: Absolute and machine-wide. Never derive this from the working +#: directory - see the module header. +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\nis-mcp-estop-panel" + + +class EStopEngaged(RuntimeError): + """Raised by any motion primitive while the e-stop is engaged.""" + + +def is_engaged() -> bool: + """True if motion is currently forbidden. + + Any error resolving the state counts as engaged - see FAIL SAFE. + """ + try: + return ESTOP_PATH.exists() + except OSError: + return True + + +def details() -> dict | None: + """Who engaged the stop, when, and why - or None if it is clear.""" + try: + if not ESTOP_PATH.exists(): + return None + return json.loads(ESTOP_PATH.read_text(encoding="utf-8")) + except (OSError, ValueError): + # Present but unreadable still means engaged; say so without a reason. + return {"reason": "(e-stop file present but unreadable)"} + + +def check() -> None: + """Raise EStopEngaged if motion is forbidden. Called by every move.""" + if is_engaged(): + info = details() or {} + raise EStopEngaged( + "E-STOP ENGAGED - motion refused. " + f"engaged_at={info.get('engaged_at', '?')} " + f"by={info.get('by', '?')} reason={info.get('reason', '?')}. " + f"Release with: python -m acquisition.estop release " + f"(or delete {ESTOP_PATH})" + ) + + +def engage(reason: str = "manual") -> dict: + """Forbid all motion immediately. Sets the flag and nothing else. + + It never commands the stage - see WHY NO HALT in the module header. + """ + info = { + "engaged_at": datetime.datetime.now().isoformat(timespec="seconds"), + "by": f"pid {os.getpid()}", + "reason": reason, + } + ESTOP_PATH.parent.mkdir(parents=True, exist_ok=True) + ESTOP_PATH.write_text(json.dumps(info, indent=2), encoding="utf-8") + return info + + +def release() -> None: + """Allow motion again. Deliberately a separate, explicit action.""" + try: + ESTOP_PATH.unlink() + except FileNotFoundError: + pass + + + +def panel_running() -> bool: + """True if a STOP panel is already on screen (Windows only).""" + if sys.platform != "win32": + return False + import ctypes + k32 = ctypes.windll.kernel32 + h = k32.OpenMutexW(0x00100000, False, PANEL_MUTEX) # SYNCHRONIZE + if h: + k32.CloseHandle(h) + return True + return False + + +def launch_panel() -> None: + """Put the STOP panel on screen unless one is already there. + + Called when a process first connects to the real stage, so the button + appears however a run was started - MCP server, mosaic, timelapse, a + one-liner. The 2026-09-21 run was started from a terminal, where no + panel existed; a safety control you have to remember to start is one + you will not have. + + 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. NIS_NO_ESTOP_PANEL=1 (or the older + CONFOCAL_NO_ESTOP_PANEL=1) turns it off. + """ + if any(os.environ.get(n, "").strip() for n in ("NIS_NO_ESTOP_PANEL", "CONFOCAL_NO_ESTOP_PANEL")): + return + try: + if panel_running(): + return + flags = getattr(subprocess, "CREATE_NO_WINDOW", 0) | getattr(subprocess, "DETACHED_PROCESS", 0) + subprocess.Popen([sys.executable, "-m", "acquisition.estop_panel"], + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, creationflags=flags) + except Exception as exc: + print(f"[estop] could not start the STOP panel ({exc}). " + f"Stop manually with: python -m acquisition.estop engage", file=sys.stderr) + + +def main() -> None: + ap = argparse.ArgumentParser(description="Emergency stop for microscope motion.") + ap.add_argument("action", choices=("engage", "release", "status")) + ap.add_argument("--reason", default="manual") + args = ap.parse_args() + + if args.action == "engage": + info = engage(args.reason) + print("E-STOP ENGAGED") + for k, v in info.items(): + print(f" {k}: {v}") + print(f"\nflag file: {ESTOP_PATH}") + print("All motion is now refused. Release with: python -m acquisition.estop release") + elif args.action == "release": + release() + print(f"e-stop released - motion permitted again ({ESTOP_PATH} removed)") + else: + if is_engaged(): + print("ENGAGED - motion is refused") + for k, v in (details() or {}).items(): + print(f" {k}: {v}") + sys.exit(2) + print(f"clear - motion permitted (no {ESTOP_PATH})") -from acquisition import _nis_settings # noqa: F401 (this repo's settings; moves an old e-stop) if __name__ == "__main__": - import runpy - runpy.run_module("nis_elements_mcp.estop", run_name="__main__") -else: - from nis_elements_mcp import estop as _impl - sys.modules[__name__] = _impl + main() diff --git a/acquisition/estop_panel.py b/acquisition/estop_panel.py index 2aa5cfa..0718b49 100644 --- a/acquisition/estop_panel.py +++ b/acquisition/estop_panel.py @@ -1,19 +1,174 @@ # estop_panel.py # ------------------------------------------------------------ -# Moved to the nis-elements-mcp package: nis_elements_mcp.estop_panel -# (packages/nis-elements-mcp/src/nis_elements_mcp/estop_panel.py). -# This old name stays so existing imports and `python -m acquisition.estop_panel` -# keep working. It is the same module object, not a copy, so settings -# and test patches made through either name reach the same code. +# An always-on-top STOP button for the microscope. +# +# python -m acquisition.estop_panel +# +# Small, borderless, stays above other windows, drag it anywhere. One big +# button. Hitting it engages acquisition.estop, which every motion +# primitive checks before it moves - see that module's header. +# +# WHY A WINDOW AND NOT JUST THE CLI: during the 2026-09-21 incident the +# stage was moving while the operator hunted for a terminal, typed a +# command, and waited for python to start. Seconds matter and typing does +# not scale under stress. A button that is already on screen costs one +# click, with no target to find and nothing to remember. +# +# WHY IT POLLS THE FLAG FILE rather than tracking its own state: the stop +# can also be engaged from a terminal, from the MCP tool, by another +# process, or by a human creating the file. The panel must show what is +# actually true, not what it last did - a panel reading "CLEAR" while the +# stop is engaged elsewhere would be worse than no panel. +# +# WHY RELEASE IS DELIBERATELY AWKWARD: the release control is small, +# visually quiet, and asks for confirmation, while STOP is huge and +# instant. The asymmetry is the point - the cost of an accidental stop is +# a few seconds, the cost of an accidental release is an unguarded +# microscope. Engaging is also idempotent, so panic-clicking is harmless. +# +# ONE PANEL. It opens by itself whenever a process connects to the stage +# (estop.launch_panel), so many processes ask for it. The first takes the +# PANEL_MUTEX; any later copy sees it and exits without drawing. +# +# TKINTER because it ships with CPython: a safety control that depends on +# `pip install` is a safety control that is missing on the day it matters. # ------------------------------------------------------------ +from __future__ import annotations + +import argparse import sys +import tkinter as tk +from tkinter import messagebox + +from acquisition import estop + +POLL_MS = 300 + +_RED, _RED_DARK = "#c62828", "#8e0000" +_GREEN, _GREY = "#2e7d32", "#9e9e9e" +_BG = "#1b1b1b" + + +class Panel: + def __init__(self, root: tk.Tk, topmost: bool = True, borderless: bool = True): + self.root = root + root.title("E-STOP") + root.configure(bg=_BG) + root.resizable(False, False) + if topmost: + root.attributes("-topmost", True) + if borderless: + # No title bar - it would be most of a window this small, and + # the drag handler below replaces the only thing it was for. + root.overrideredirect(True) + root.geometry("+40+40") + + self.button = tk.Button( + root, text="STOP", font=("Segoe UI", 26, "bold"), + bg=_RED, fg="white", activebackground=_RED_DARK, activeforeground="white", + relief="raised", bd=3, width=8, height=1, cursor="hand2", + command=self.on_stop) + self.button.pack(padx=8, pady=(8, 4)) + + self.status = tk.Label(root, text="checking...", font=("Segoe UI", 9, "bold"), + bg=_BG, fg=_GREY) + self.status.pack() + + bar = tk.Frame(root, bg=_BG) + bar.pack(fill="x", padx=8, pady=(2, 6)) + # Quiet, small, and confirmed - see the header on asymmetry. + self.release_btn = tk.Button(bar, text="release", font=("Segoe UI", 8), + bg="#2a2a2a", fg="#bbb", relief="flat", + cursor="hand2", command=self.on_release) + self.release_btn.pack(side="left") + tk.Button(bar, text="✕", font=("Segoe UI", 8), bg="#2a2a2a", fg="#bbb", + relief="flat", cursor="hand2", command=root.destroy).pack(side="right") + + # Drag from anywhere on the background, since there is no title bar. + for w in (root, self.status, bar): + w.bind("", self._press) + w.bind("", self._drag) + self._dx = self._dy = 0 + + self._last = None + self.tick() + + def _press(self, e) -> None: + self._dx, self._dy = e.x_root - self.root.winfo_x(), e.y_root - self.root.winfo_y() + + def _drag(self, e) -> None: + self.root.geometry(f"+{e.x_root - self._dx}+{e.y_root - self._dy}") + + def on_stop(self) -> None: + # Engage first and report afterwards: the flag write is what makes + # the microscope safe, and it must not wait behind a dialog. + try: + estop.engage("STOP button") + except Exception as exc: + messagebox.showerror("E-STOP", f"Could not engage:\n{exc}") + self.refresh(force=True) + + def on_release(self) -> None: + if not estop.is_engaged(): + return + if messagebox.askyesno("Release e-stop", + "Allow the microscope to move again?\n\n" + "Only do this once you know why it stopped."): + estop.release() + self.refresh(force=True) + + def refresh(self, force: bool = False) -> None: + engaged = estop.is_engaged() + if engaged == self._last and not force: + return + self._last = engaged + if engaged: + self.status.configure(text="ENGAGED - motion refused", fg=_RED) + self.button.configure(text="STOPPED", bg=_RED_DARK) + self.release_btn.configure(state="normal") + else: + self.status.configure(text="clear - motion permitted", fg=_GREEN) + self.button.configure(text="STOP", bg=_RED) + self.release_btn.configure(state="disabled") + + def tick(self) -> None: + self.refresh() + self.root.after(POLL_MS, self.tick) + + +_mutex = None # kept for the life of the process; Windows frees it on exit + + +def _claim_single_instance() -> bool: + """Take the panel mutex; False if another panel already holds it.""" + global _mutex + if sys.platform != "win32": + return True + import ctypes + k32 = ctypes.windll.kernel32 + k32.CreateMutexW.restype = ctypes.c_void_p + _mutex = k32.CreateMutexW(None, False, estop.PANEL_MUTEX) + return k32.GetLastError() != 183 # ERROR_ALREADY_EXISTS + + +def main() -> None: + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--no-topmost", action="store_true") + ap.add_argument("--titlebar", action="store_true", help="keep a normal window frame") + args = ap.parse_args() + if not _claim_single_instance(): + print("a STOP panel is already open", file=sys.stderr) + return + try: + root = tk.Tk() + except tk.TclError as exc: + print(f"no display available for the e-stop panel ({exc}). " + f"Use: python -m acquisition.estop engage", file=sys.stderr) + raise SystemExit(1) + Panel(root, topmost=not args.no_topmost, borderless=not args.titlebar) + root.mainloop() -from acquisition import _nis_settings # noqa: F401 (this repo's settings; moves an old e-stop) if __name__ == "__main__": - import runpy - runpy.run_module("nis_elements_mcp.estop_panel", run_name="__main__") -else: - from nis_elements_mcp import estop_panel as _impl - sys.modules[__name__] = _impl + main() diff --git a/acquisition/nis_events.py b/acquisition/nis_events.py deleted file mode 100644 index 8574116..0000000 --- a/acquisition/nis_events.py +++ /dev/null @@ -1,19 +0,0 @@ -# nis_events.py -# ------------------------------------------------------------ -# Moved to the nis-elements-mcp package: nis_elements_mcp.nis_events -# (packages/nis-elements-mcp/src/nis_elements_mcp/nis_events.py). -# This old name stays so existing imports and `python -m acquisition.nis_events` -# keep working. It is the same module object, not a copy, so settings -# and test patches made through either name reach the same code. -# ------------------------------------------------------------ - -import sys - -from acquisition import _nis_settings # noqa: F401 (this repo's log and capture folders) - -if __name__ == "__main__": - import runpy - runpy.run_module("nis_elements_mcp.nis_events", run_name="__main__") -else: - from nis_elements_mcp import nis_events as _impl - sys.modules[__name__] = _impl diff --git a/acquisition/nis_monitor.py b/acquisition/nis_monitor.py deleted file mode 100644 index 358ad91..0000000 --- a/acquisition/nis_monitor.py +++ /dev/null @@ -1,19 +0,0 @@ -# nis_monitor.py -# ------------------------------------------------------------ -# Moved to the nis-elements-mcp package: nis_elements_mcp.nis_monitor -# (packages/nis-elements-mcp/src/nis_elements_mcp/nis_monitor.py). -# This old name stays so existing imports and `python -m acquisition.nis_monitor` -# keep working. It is the same module object, not a copy, so settings -# and test patches made through either name reach the same code. -# ------------------------------------------------------------ - -import sys - -from acquisition import _nis_settings # noqa: F401 (this repo's log and capture folders) - -if __name__ == "__main__": - import runpy - runpy.run_module("nis_elements_mcp.nis_monitor", run_name="__main__") -else: - from nis_elements_mcp import nis_monitor as _impl - sys.modules[__name__] = _impl diff --git a/docs/nis-bridge.md b/docs/nis-bridge.md deleted file mode 100644 index 89b0ce7..0000000 --- a/docs/nis-bridge.md +++ /dev/null @@ -1,222 +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: status, optical-config listing, XY moves, objective changes and capture work on the scope (2026-10-29). Capture runs on NIS's main thread and NIS no longer crashes. ND runs (steps 7-9) are not yet tested.** -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/baumer_ti2/baumer_ti2_tools.py`), so it also needs sign-off before it is used -for real work. - -## How it fits together - -All of these files are in the `nis-elements-mcp` package, -`packages/nis-elements-mcp/src/nis_elements_mcp/`. The old paths in -`acquisition/` and `mcp_server/nis/` forward to them. - -``` -MCP client (Claude) - │ stdio - ▼ -nis_server.py / nis_tools.py confirm gate, capture-folder rule, estop tool - │ -nis_bridge_client.py e-stop checked before sending - │ HTTP, 127.0.0.1:8766 - ▼ -nis_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. - -`baumer_ti2_server.py` and its tools are unchanged. The NIS tools are a -separate server, `nis-mcp`. - -## 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 - `packages/nis-elements-mcp/src/nis_elements_mcp/nis_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 `nis-mcp` 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. - -## Results on the microscope (2026-10-16): capture crashes NIS - -- Step 6 (`capture`) killed NIS: `nis_ar.exe` faulted in `Qt5Core.dll` - (exception 0xc0000409) at the moment of the call. `Capture`, - `ImageSaveAs` and `CloseCurrentDocument` open and close NIS windows, which - Qt only allows on the UI thread. No file was saved. Reads, moves and - objective changes from the worker thread are fine. -- **Fix (untested on the scope):** `run()` executes on NIS's main thread, so it - registers a Win32 thread timer there (`MainThread.install()` in - `bridge_job.py`). NIS's own message loop calls the timer every 50 ms, and - the callback runs the queued `Capture`/`ImageSaveAs`/`CloseCurrentDocument` - and ND calls on the UI thread. Status, moves and objective changes stay on - the worker thread. A queued call that the main thread has not started - within 10 min is cancelled, not run late, and the e-stop is checked again - on the main thread just before the call starts. -- **To verify:** step 6 (`capture`) first. If NIS still faults, or the timer - never fires (the call reports "did not run"), the hook is wrong and the - calls stay refused until it is fixed. If `Capture` blocks NIS's UI for the - exposure, that is expected. Steps 7-10 (ND) follow only after step 6 passes. -- The bridge job prints "no main-thread hook" and refuses these calls if the - timer cannot be registered. - -## Results on the microscope (2026-10-29): main-thread hook - -Bridge job pasted fresh into NIS (JOBS job `NISMCPTest`); its log showed -`NIS bridge v1 listening on 127.0.0.1:8766, pid 28168` and no "no -main-thread hook" warning. Calls went through the MCP tool functions in -`mcp_server/nis/nis_tools.py`, in-process, with `confirm=True` where needed. -Checks on the NIS screen were made by the operator. - -| Step | Call | Time | Result | Evidence | -|---|---|---|---|---| -| 1 | `nis_status` | 18:15:39 | **pass** | XY (0, 0), Z 3594.22 and the 20x matched NIS; turret 0-based (0 = 4x … 5 = S Plan Fluor 20xC) | -| - | `nis_list_optical_configs` | 18:16:59 | **pass** | 14 configs, same as NIS's saved list | -| 2 | `nis_move_relative(100, 0)`, `(-100, 0)` | 20:20:41, 20:21:21 | **pass** | Repeated with a pause: NIS showed X 0.100 mm, then 0.000 mm; Y unchanged. Event log `move ok`, 0.1 s each | -| 5 | `nis_change_objective` 20x → 4x → 10x | 20:21:49, 20:23:30 | **pass** | Nosepiece 2 → 0 → 1, `arrived: true` both times, NIS status bar followed | -| 6 | `nis_capture("bridge_check_2026-10-29.nd2")` | 21:05:03 → 21:05:44 | **pass** | **NIS did not crash**; event log `capture ok`, 41.3 s; file saved (6.5 MB, 3 × 1024 × 1024, GFP/RFP/TD); `nis_status` answered afterwards, NIS responding | -| 7-9 | ND run, status during run, finish | - | **not run** | Needs the template's settings first | - -Notes: - -- The laser was off for the capture, so the image is dark (max 62 of 65535). - The active optical configuration was a GFP/RFP/TD one, not DIC_10x: the - bridge cannot read or set it, so select it in NIS before a real capture. -- `Capture`, `ImageSaveAs` and `CloseCurrentDocument` all returned 0 although - the file was saved, so 0 is not a failure code for these calls. -- `ChangeObjective` (`rc_calibration`) returned 0 both times, but NIS's - objective name had already followed the turret. **Open question:** the - capture's pixel size is 0.215 µm, small for the 10x at 1024 × 1024 unless a - scan zoom was set. Check whether NIS saved the 10x calibration. -- Activating an AX optical configuration in NIS can turn the turret to that - configuration's objective. - -## 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. Both use - `~/.nis-mcp/ESTOP` (`NIS_ESTOP_FILE`), the same file the Ti2 code here - uses. Ending an ND run is always allowed. -- XY moves are **relative, at most 1000 µm per axis** per call - (`NIS_MAX_STEP_UM`). **Z is never moved.** -- Objective changes are limited to **4× and 10×**, the long working distances - (`NIS_ALLOWED_OBJECTIVES`). -- ND runs can be limited to named experiments (`NIS_ALLOWED_EXPERIMENTS`). -- The client checks these limits before sending; the bridge inside NIS checks - the step and objective limits again with its own settings (NIS's - environment, or the defaults at the top of `nis_bridge_job.py`). The - stricter one wins. -- MCP tools that move or acquire need **`confirm=True`**. -- `nis_capture` saves only into the capture folder - (`NIS_CAPTURE_DIR`; this repo uses `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. - -All settings and their defaults are listed in -`packages/nis-elements-mcp/src/nis_elements_mcp/settings.py`. diff --git a/mcp_server/nis/__init__.py b/mcp_server/nis/__init__.py deleted file mode 100644 index 31c9a2b..0000000 --- a/mcp_server/nis/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -"""MCP server for NIS-Elements, reached through the bridge job running inside NIS. - -The code lives in the nis-elements-mcp package (packages/nis-elements-mcp); -nis_server.py and nis_tools.py here forward to it, with this repo's log and -capture folders. Run with `confocal-mcp-nis` or `python -m mcp_server.nis.nis_server`. -""" diff --git a/mcp_server/nis/nis_server.py b/mcp_server/nis/nis_server.py deleted file mode 100644 index 9a499a5..0000000 --- a/mcp_server/nis/nis_server.py +++ /dev/null @@ -1,19 +0,0 @@ -# nis_server.py -# ------------------------------------------------------------ -# Moved to the nis-elements-mcp package: nis_elements_mcp.nis_server -# (packages/nis-elements-mcp/src/nis_elements_mcp/nis_server.py). -# This old name stays so existing imports and `python -m mcp_server.nis.nis_server` -# keep working. It is the same module object, not a copy, so settings -# and test patches made through either name reach the same code. -# ------------------------------------------------------------ - -import sys - -from acquisition import _nis_settings # noqa: F401 (this repo's log and capture folders) - -if __name__ == "__main__": - import runpy - runpy.run_module("nis_elements_mcp.nis_server", run_name="__main__") -else: - from nis_elements_mcp import nis_server as _impl - sys.modules[__name__] = _impl diff --git a/mcp_server/nis/nis_tools.py b/mcp_server/nis/nis_tools.py deleted file mode 100644 index 08a5557..0000000 --- a/mcp_server/nis/nis_tools.py +++ /dev/null @@ -1,19 +0,0 @@ -# nis_tools.py -# ------------------------------------------------------------ -# Moved to the nis-elements-mcp package: nis_elements_mcp.nis_tools -# (packages/nis-elements-mcp/src/nis_elements_mcp/nis_tools.py). -# This old name stays so existing imports and `python -m mcp_server.nis.nis_tools` -# keep working. It is the same module object, not a copy, so settings -# and test patches made through either name reach the same code. -# ------------------------------------------------------------ - -import sys - -from acquisition import _nis_settings # noqa: F401 (this repo's log and capture folders) - -if __name__ == "__main__": - import runpy - runpy.run_module("nis_elements_mcp.nis_tools", run_name="__main__") -else: - from nis_elements_mcp import nis_tools as _impl - sys.modules[__name__] = _impl diff --git a/packages/nis-elements-mcp/CHANGELOG.md b/packages/nis-elements-mcp/CHANGELOG.md deleted file mode 100644 index 8a0b13c..0000000 --- a/packages/nis-elements-mcp/CHANGELOG.md +++ /dev/null @@ -1,37 +0,0 @@ -# Changelog - -All notable changes to nis-elements-mcp are recorded here. -Format follows [Keep a Changelog](https://keepachangelog.com/); versions follow -[Semantic Versioning](https://semver.org/). - -## [0.1.0] - 2026-10-30 - -First release, extracted from the microscope-agent project. - -### Added -- MCP server `nis-mcp` with the tools `nis_status`, `nis_list_optical_configs`, - `nis_move_relative`, `nis_change_objective`, `nis_capture`, - `nis_run_experiment`, `nis_finish_experiment` and `estop`. -- Bridge job `nis_bridge_job.py` for a NIS-Elements JOBS Python task (standard - library only). Capture and ND calls run on NIS's main thread through a - Win32 timer; called from a worker thread they crashed NIS. -- Commands `nis-mcp-bridge` (by-hand client, `job-file`, `shutdown`), - `nis-mcp-estop` and `nis-mcp-monitor`. -- E-stop flag file checked by the client and by the bridge, with an - always-on-top STOP window. -- Event log and live monitor of every action sent through the bridge. -- Settings from `NIS_*` environment variables, including allow-lists for - objectives and ND experiments and an XY step limit, checked by the client - and again by the bridge. -- `nis_elements_mcp.testing`: a fake NIS and a pytest fixture for tests - without a microscope. - -### Fixed -- `ND_LoadExperiment`'s return code is reported, not treated as a failure: - it has no documented value and returned 0 for a template that loads. - -### Known limits -- An ND run blocks the bridge until it ends, so `nis_finish_experiment` - cannot end a run early yet (checked on the microscope 2026-10-30). -- The optical configuration cannot be selected through the bridge. -- The STOP and monitor windows close when the MCP client disconnects. diff --git a/packages/nis-elements-mcp/LICENSE b/packages/nis-elements-mcp/LICENSE deleted file mode 100644 index 0137d61..0000000 --- a/packages/nis-elements-mcp/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2026 Qurratul Ain Quais - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/packages/nis-elements-mcp/README.md b/packages/nis-elements-mcp/README.md deleted file mode 100644 index d50b3a2..0000000 --- a/packages/nis-elements-mcp/README.md +++ /dev/null @@ -1,238 +0,0 @@ -# nis-elements-mcp - -Drive a Nikon microscope through **NIS-Elements** from an MCP client such as -Claude Code: read the stage and objective, move XY, change objective, capture -an image, and run ND experiments you saved in NIS, with an emergency stop and -hard safety limits. - -NIS-Elements has no outside automation interface, so a small **bridge job** -runs inside NIS (as a JOBS Python task) and answers requests on -`127.0.0.1:8766`. The MCP server talks to that bridge. - -``` -MCP client (Claude Code) - │ stdio - ▼ -nis-mcp MCP server: confirm gate, limits, e-stop, event log - │ HTTP, 127.0.0.1:8766 - ▼ -nis_bridge_job.py JOBS Python task, runs inside nis_ar.exe - │ ctypes - ▼ -NIS macro functions StgMoveXY, Capture, ND_RunExperiment, ... -``` - -Tested on NIS-Elements AR with a Nikon Ti2 stand and an AX confocal: status, -optical configurations, XY moves, objective changes, capture, the e-stop and -ND runs. Ending an ND run early is not yet possible (see Known limits). - -## Requirements - -- Windows, with NIS-Elements and its **JOBS** module (Python task). -- Python 3.11 or newer on the same PC, for the MCP server. -- Claude Code, if you want to use it from Claude. -- The bridge job needs nothing installed inside NIS: it uses only the Python - standard library. - -## Setup, step by step - -Run the commands in **PowerShell**, in your project's folder. - -### Step 1. Create a Python environment for the server - -```powershell -python -m venv .nis-mcp-env -``` - -> If this fails with "The filename or extension is too long" (WinError 206), -> your project folder's path is too deep for Windows' 260-character limit. -> Use a shorter folder, or turn on long paths in Windows. - -### Step 2. Install the package - -```powershell -.nis-mcp-env\Scripts\pip install "git+https://github.com/BioNanomics/microscope-agent#subdirectory=packages/nis-elements-mcp" -``` - -> From a local copy instead of GitHub: -> `.nis-mcp-env\Scripts\pip install D:\path\to\microscope-agent\packages\nis-elements-mcp` - -### Step 3. Register the server with Claude Code - -```powershell -claude mcp add nis --scope local -- "$PWD\.nis-mcp-env\Scripts\nis-mcp.exe" -``` - -> - `$PWD\...` puts in the full path, so the server starts whatever folder -> Claude is launched from. -> - To choose your own folders or limits, add `-e NAME=value` before the `--` -> (all names are in [Settings](#settings)): -> ```powershell -> claude mcp add nis --scope local -e NIS_CAPTURE_DIR=D:\data\nis\captures -e NIS_LOG_DIR=D:\data\nis\logs -- "$PWD\.nis-mcp-env\Scripts\nis-mcp.exe" -> ``` -> - With [uv](https://docs.astral.sh/uv/), one line replaces Steps 1 to 3: -> ```powershell -> claude mcp add nis --scope local -- uvx --from "git+https://github.com/BioNanomics/microscope-agent#subdirectory=packages/nis-elements-mcp" nis-mcp -> ``` - -### Step 4. Start the microscope and NIS - -Switch on the microscope stand first, then start NIS-Elements. - -### Step 5. Put the bridge job into NIS (once, and again after each upgrade) - -1. Print the path of the file to paste: - ```powershell - .nis-mcp-env\Scripts\nis-mcp-bridge job-file - ``` -2. Open that file in a text editor and copy all of it. Its first line is - `# IMPORTANT: 'limjob' must be imported like this (not from nor as)`. -3. In NIS, open **JOBS** and create a job with one **Python** task. -4. Replace the task's code with what you copied (Ctrl+A, Ctrl+V). -5. Save the job, for example as `NIS bridge`. - -### Step 6. Run the bridge and check it - -1. Run the job in NIS. The job window closes at once; the bridge keeps - running in the background. -2. Check that it answers: - ```powershell - .nis-mcp-env\Scripts\nis-mcp-bridge status - ``` - You should see the stage position and the objectives on the turret. - -### Step 7. Use it from Claude - -Start a **new** Claude Code session in the project folder (a server added -in Step 3 appears in new sessions only), and ask, for example, "What is the -microscope's status?". A red STOP window and a monitor window open when the -server starts. - -### When you are done: stop the bridge - -```powershell -.nis-mcp-env\Scripts\nis-mcp-bridge shutdown -``` - -**Never press the JOBS Abort button**: a Python task cannot be interrupted -and NIS freezes. The bridge also stops by itself after 4 hours with no -request. - -## Tools - -| Tool | What it does | Needs `confirm=True` | -|---|---|---| -| `nis_status` | XY and Z position, objective, turret, ND run state, e-stop | no | -| `nis_list_optical_configs` | names of the optical configurations in NIS | no | -| `nis_move_relative(dx_um, dy_um)` | relative XY move | yes | -| `nis_change_objective(name)` | turn the turret to an allowed objective | yes | -| `nis_capture(filename)` | capture with the optical configuration active in NIS, save as `.nd2` in the capture folder | yes | -| `nis_run_experiment(experiment)` | run an ND experiment saved in NIS's ND Acquisition window | yes | -| `nis_finish_experiment()` | end the running ND experiment after its current loop | no | -| `estop(action)` | `engage` or `status`; release is not possible from the MCP client | no | - -NIS does not report whether `nis_run_experiment` found the saved name -(`ND_LoadExperiment` has no return value): if the name is wrong, NIS runs -whatever the ND Acquisition window currently holds. Check the name, and set -`NIS_ALLOWED_EXPERIMENTS` to the names you mean to run. - -The bridge cannot select an optical configuration (doing so froze NIS): -choose it in NIS before `nis_capture`. Activating an optical configuration in -NIS may also turn the turret to that configuration's objective. - -## Safety rules - -- Everything that moves or acquires needs **`confirm=True`**. -- **E-stop**: a flag file (`~/.nis-mcp/ESTOP`). While it exists, every move, - objective change, capture and ND run is refused, by the client and again by - the bridge inside NIS. Ending an ND run is always allowed. A STOP window - opens when the server starts. From a terminal: - ```powershell - .nis-mcp-env\Scripts\nis-mcp-estop engage - .nis-mcp-env\Scripts\nis-mcp-estop status - .nis-mcp-env\Scripts\nis-mcp-estop release # a person does this, never the MCP client - ``` -- XY moves are **relative**, at most **1000 µm per axis** per call. -- **Z is never moved.** There is no Z tool. -- Objective changes only to **4x and 10x** by default: their long working - distances cannot reach the sample. -- ND runs can be limited to named experiments. -- The client checks the limits before sending; the bridge checks the step - and objective limits again with its own settings. The stricter one wins. -- Captures go only into the capture folder, by plain file name, and never - overwrite a file. -- Motion and acquisition answer HTTP POST only, and the bridge listens on - 127.0.0.1 only. -- Laser power and saved ND experiments are never changed. - -## Settings - -All settings are environment variables, read by the MCP server (pass them -with `claude mcp add -e NAME=value`): - -| Variable | Meaning | Default | -|---|---|---| -| `NIS_BRIDGE_HOST` | bridge address | `127.0.0.1` | -| `NIS_BRIDGE_PORT` | bridge port | `8766` | -| `NIS_CAPTURE_DIR` | where `nis_capture` saves | `~/nis-mcp/captures` | -| `NIS_LOG_DIR` | event log folder | `~/nis-mcp/logs` | -| `NIS_ESTOP_FILE` | e-stop flag file | `~/.nis-mcp/ESTOP` | -| `NIS_ALLOWED_OBJECTIVES` | magnifications allowed, comma-separated | `4,10` | -| `NIS_ALLOWED_EXPERIMENTS` | ND experiment names allowed, comma-separated | empty: any saved one | -| `NIS_MAX_STEP_UM` | largest XY step per call, µm | `1000` | -| `NIS_NO_ESTOP_PANEL` | `1`: do not open the STOP window | off | -| `NIS_NO_MONITOR` | `1`: do not open the monitor window | off | - -The bridge job inside NIS reads `NIS_BRIDGE_PORT`, `NIS_ESTOP_FILE`, -`NIS_MAX_STEP_UM` and `NIS_ALLOWED_OBJECTIVES` from NIS's own environment, -which is usually empty, so it uses the same defaults. To change them there, -set the variables before starting NIS, or edit the defaults at the top of -the job file before pasting it. `NIS_ESTOP_FILE` must point to the same file -on both sides. - -## Watch what it does - -`nis-mcp-monitor` shows the stage, objective, ND state and e-stop, above a -live list of every action sent through the bridge. It opens by itself when -the server starts. Each action is also written to -`/events-.jsonl`. - -## Testing without a microscope - -`nis_elements_mcp.testing` has a fake NIS and a pytest fixture that runs the -real bridge on it, on a free port: - -```python -from nis_elements_mcp.testing import bridge, estop_file # noqa: F401 (fixtures) - -def test_my_script_moves(bridge): - nis, url, client = bridge - client.move_relative(100, 0) - assert nis.x == 200.0 -``` - -To run this package's own tests: `pip install -e ".[test]"`, then `pytest`. - -## Known limits - -1. **An ND run blocks the bridge until it ends.** `nis_run_experiment` - returns only when the run is over, and nothing else (not even - `nis_status` or `nis_finish_experiment`) is answered meanwhile. Ending a - run early from MCP is therefore not possible yet; use NIS's own **Finish** - button in the ND Progress window. -2. **The optical configuration cannot be selected** through the bridge: - choose it in NIS before `nis_capture`. -3. **NIS does not report whether a saved ND experiment was found** (see - Tools); set `NIS_ALLOWED_EXPERIMENTS`. -4. **The STOP and monitor windows close when the MCP client disconnects.** - The e-stop itself (the flag file) keeps working; open the STOP window by - hand with `.nis-mcp-env\Scripts\pythonw -m nis_elements_mcp.estop_panel`. - -## License - -MIT, see [LICENSE](LICENSE). - -This project is not affiliated with, endorsed by, or supported by Nikon. -It contains no Nikon code: the bridge calls NIS-Elements' own macro -functions on a PC where NIS-Elements is already installed and licensed. -Nikon and NIS-Elements are trademarks of Nikon Corporation. diff --git a/packages/nis-elements-mcp/pyproject.toml b/packages/nis-elements-mcp/pyproject.toml deleted file mode 100644 index 40e0a5e..0000000 --- a/packages/nis-elements-mcp/pyproject.toml +++ /dev/null @@ -1,37 +0,0 @@ -[build-system] -requires = ["hatchling"] -build-backend = "hatchling.build" - -[project] -name = "nis-elements-mcp" -version = "0.1.0" -description = "MCP server that drives a Nikon NIS-Elements microscope through a bridge job running inside NIS" -readme = "README.md" -license = "MIT" -license-files = ["LICENSE"] -authors = [{ name = "Qurratul Ain Quais" }] -requires-python = ">=3.11" -keywords = ["mcp", "microscopy", "nikon", "nis-elements"] -classifiers = [ - "Programming Language :: Python :: 3", - "Operating System :: Microsoft :: Windows", - "Topic :: Scientific/Engineering :: Image Processing", -] -dependencies = [ - "mcp>=2.0,<3", -] - -[project.optional-dependencies] -test = ["pytest>=8"] - -[project.scripts] -nis-mcp = "nis_elements_mcp.nis_server:main" # the MCP server -nis-mcp-bridge = "nis_elements_mcp.nis_bridge_client:main" # talk to the bridge by hand; job-file, shutdown -nis-mcp-estop = "nis_elements_mcp.estop:main" # engage / status / release -nis-mcp-monitor = "nis_elements_mcp.nis_monitor:main" # live view of the bridge - -[tool.hatch.build.targets.wheel] -packages = ["src/nis_elements_mcp"] - -[tool.pytest.ini_options] -testpaths = ["tests"] diff --git a/packages/nis-elements-mcp/src/nis_elements_mcp/__init__.py b/packages/nis-elements-mcp/src/nis_elements_mcp/__init__.py deleted file mode 100644 index 709563c..0000000 --- a/packages/nis-elements-mcp/src/nis_elements_mcp/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -"""Drive a Nikon NIS-Elements microscope from an MCP client, through a bridge job running inside NIS.""" - -from importlib.metadata import PackageNotFoundError, version - -try: - __version__ = version("nis-elements-mcp") -except PackageNotFoundError: # running from a source tree that was never installed - __version__ = "0.0.0+unknown" diff --git a/packages/nis-elements-mcp/src/nis_elements_mcp/estop.py b/packages/nis-elements-mcp/src/nis_elements_mcp/estop.py deleted file mode 100644 index 11692c2..0000000 --- a/packages/nis-elements-mcp/src/nis_elements_mcp/estop.py +++ /dev/null @@ -1,211 +0,0 @@ -# estop.py -# ------------------------------------------------------------ -# Emergency stop for every process that can move this microscope. -# -# python -m nis_elements_mcp.estop engage # STOP EVERYTHING, NOW -# python -m nis_elements_mcp.estop status -# python -m nis_elements_mcp.estop release # deliberate, separate action -# -# WHY THIS EXISTS. On 2026-09-21 a mosaic raster with a bad focus plane -# began driving Z toward the sample. Stopping it took several minutes and -# three separate interventions, because every mechanism available was the -# wrong shape: -# -# * stopping the background SHELL left its python CHILD running, still -# issuing moves - the process list, not the task list, was the truth -# * a tool call the operator REJECTED had already spawned its process, -# which kept looping Z moves regardless of the rejection -# * a "STOP file" checked once per mosaic tile is not a stop; between -# checks it still issued dozens of moves -# * the Ti2 SDK has NO abort/halt command (searched: only ZESCAPE, which -# is a retract, not a stop), so there is nothing to "cancel" with -# -# The lesson is that an e-stop must sit BELOW whatever is misbehaving. So -# this is enforced inside nis_sdk's move primitives themselves: no caller, -# no matter how confused, can move an axis while the stop is engaged, -# because the check happens after the caller has already decided to move. -# -# WHY A FILE. It must work across processes that do not know about each -# other - that was the whole failure. A file is visible to every process, -# survives the death of whoever set it, needs no server or port, and can -# be set by a human from any shell (or by creating the file by hand) when -# the agent itself is the thing malfunctioning. -# -# WHY A FIXED PATH, NOT data_root(). data_root() resolves relative to the -# working directory, and an MCP server launched by a desktop client gets a -# different cwd than a terminal. Two processes would then disagree about -# where the e-stop lives, which is precisely the failure this must not -# have. ESTOP_PATH is absolute and identical for every process on the -# machine. -# -# 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 -# refused move and a clear message, which is recoverable; the cost of -# failing open is a driven objective. -# -# WHAT IT DOES NOT DO: it cannot stop a move the controller has already -# accepted. A move in flight runs to its end; the stop takes effect at the -# next move. move_xy splits long moves into HOP_UM hops, so an XY move -# stops within one hop (measured: 0.54 s, <= 4 mm). -# -# WHY NO HALT. engage() used to also write the current position back as -# the target, to freeze an axis mid-travel. estop_inflight_test showed -# that is worse than nothing: position reads are cached for the whole move -# (XY and Z), so the "current" position is the START, and the write queues -# behind the move. A 1 mm Z move ran to its end, then the halt drove Z all -# the way back - a second move, issued by the stop. Never add it back. -# ------------------------------------------------------------ - -from __future__ import annotations - -import argparse -import datetime -import json -import os -import subprocess -import sys -from pathlib import Path - -from nis_elements_mcp import settings - -#: Absolute and machine-wide. Never derive this from the working -#: directory - see the module header. -ESTOP_PATH: Path = settings.estop_file() # NIS_ESTOP_FILE, else ~/.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\nis-mcp-estop-panel" - - -class EStopEngaged(RuntimeError): - """Raised by any motion primitive while the e-stop is engaged.""" - - -def is_engaged() -> bool: - """True if motion is currently forbidden. - - Any error resolving the state counts as engaged - see FAIL SAFE. - """ - try: - return ESTOP_PATH.exists() - except OSError: - return True - - -def details() -> dict | None: - """Who engaged the stop, when, and why - or None if it is clear.""" - try: - if not ESTOP_PATH.exists(): - return None - return json.loads(ESTOP_PATH.read_text(encoding="utf-8")) - except (OSError, ValueError): - # Present but unreadable still means engaged; say so without a reason. - return {"reason": "(e-stop file present but unreadable)"} - - -def check() -> None: - """Raise EStopEngaged if motion is forbidden. Called by every move.""" - if is_engaged(): - info = details() or {} - raise EStopEngaged( - "E-STOP ENGAGED - motion refused. " - f"engaged_at={info.get('engaged_at', '?')} " - f"by={info.get('by', '?')} reason={info.get('reason', '?')}. " - f"Release with: python -m nis_elements_mcp.estop release " - f"(or delete {ESTOP_PATH})" - ) - - -def engage(reason: str = "manual") -> dict: - """Forbid all motion immediately. Sets the flag and nothing else. - - It never commands the stage - see WHY NO HALT in the module header. - """ - info = { - "engaged_at": datetime.datetime.now().isoformat(timespec="seconds"), - "by": f"pid {os.getpid()}", - "reason": reason, - } - ESTOP_PATH.parent.mkdir(parents=True, exist_ok=True) - ESTOP_PATH.write_text(json.dumps(info, indent=2), encoding="utf-8") - return info - - -def release() -> None: - """Allow motion again. Deliberately a separate, explicit action.""" - try: - ESTOP_PATH.unlink() - except FileNotFoundError: - pass - - - -def panel_running() -> bool: - """True if a STOP panel is already on screen (Windows only).""" - if sys.platform != "win32": - return False - import ctypes - k32 = ctypes.windll.kernel32 - h = k32.OpenMutexW(0x00100000, False, PANEL_MUTEX) # SYNCHRONIZE - if h: - k32.CloseHandle(h) - return True - return False - - -def launch_panel() -> None: - """Put the STOP panel on screen unless one is already there. - - Called when a process first connects to the real stage, so the button - appears however a run was started - MCP server, mosaic, timelapse, a - one-liner. The 2026-09-21 run was started from a terminal, where no - panel existed; a safety control you have to remember to start is one - you will not have. - - 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. NIS_NO_ESTOP_PANEL=1 turns it off. - """ - if settings.estop_panel_disabled(): - return - try: - if panel_running(): - return - flags = getattr(subprocess, "CREATE_NO_WINDOW", 0) | getattr(subprocess, "DETACHED_PROCESS", 0) - subprocess.Popen([sys.executable, "-m", "nis_elements_mcp.estop_panel"], - stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, creationflags=flags) - except Exception as exc: - print(f"[estop] could not start the STOP panel ({exc}). " - f"Stop manually with: python -m nis_elements_mcp.estop engage", file=sys.stderr) - - -def main() -> None: - ap = argparse.ArgumentParser(description="Emergency stop for microscope motion.") - ap.add_argument("action", choices=("engage", "release", "status")) - ap.add_argument("--reason", default="manual") - args = ap.parse_args() - - if args.action == "engage": - info = engage(args.reason) - print("E-STOP ENGAGED") - for k, v in info.items(): - print(f" {k}: {v}") - print(f"\nflag file: {ESTOP_PATH}") - print("All motion is now refused. Release with: python -m nis_elements_mcp.estop release") - elif args.action == "release": - release() - print(f"e-stop released - motion permitted again ({ESTOP_PATH} removed)") - else: - if is_engaged(): - print("ENGAGED - motion is refused") - for k, v in (details() or {}).items(): - print(f" {k}: {v}") - sys.exit(2) - print(f"clear - motion permitted (no {ESTOP_PATH})") - - -if __name__ == "__main__": - main() diff --git a/packages/nis-elements-mcp/src/nis_elements_mcp/estop_panel.py b/packages/nis-elements-mcp/src/nis_elements_mcp/estop_panel.py deleted file mode 100644 index 8b849cf..0000000 --- a/packages/nis-elements-mcp/src/nis_elements_mcp/estop_panel.py +++ /dev/null @@ -1,174 +0,0 @@ -# estop_panel.py -# ------------------------------------------------------------ -# An always-on-top STOP button for the microscope. -# -# python -m nis_elements_mcp.estop_panel -# -# Small, borderless, stays above other windows, drag it anywhere. One big -# button. Hitting it engages nis_elements_mcp.estop, which every motion -# primitive checks before it moves - see that module's header. -# -# WHY A WINDOW AND NOT JUST THE CLI: during the 2026-09-21 incident the -# stage was moving while the operator hunted for a terminal, typed a -# command, and waited for python to start. Seconds matter and typing does -# not scale under stress. A button that is already on screen costs one -# click, with no target to find and nothing to remember. -# -# WHY IT POLLS THE FLAG FILE rather than tracking its own state: the stop -# can also be engaged from a terminal, from the MCP tool, by another -# process, or by a human creating the file. The panel must show what is -# actually true, not what it last did - a panel reading "CLEAR" while the -# stop is engaged elsewhere would be worse than no panel. -# -# WHY RELEASE IS DELIBERATELY AWKWARD: the release control is small, -# visually quiet, and asks for confirmation, while STOP is huge and -# instant. The asymmetry is the point - the cost of an accidental stop is -# a few seconds, the cost of an accidental release is an unguarded -# microscope. Engaging is also idempotent, so panic-clicking is harmless. -# -# ONE PANEL. It opens by itself whenever a process connects to the stage -# (estop.launch_panel), so many processes ask for it. The first takes the -# PANEL_MUTEX; any later copy sees it and exits without drawing. -# -# TKINTER because it ships with CPython: a safety control that depends on -# `pip install` is a safety control that is missing on the day it matters. -# ------------------------------------------------------------ - -from __future__ import annotations - -import argparse -import sys -import tkinter as tk -from tkinter import messagebox - -from nis_elements_mcp import estop - -POLL_MS = 300 - -_RED, _RED_DARK = "#c62828", "#8e0000" -_GREEN, _GREY = "#2e7d32", "#9e9e9e" -_BG = "#1b1b1b" - - -class Panel: - def __init__(self, root: tk.Tk, topmost: bool = True, borderless: bool = True): - self.root = root - root.title("E-STOP") - root.configure(bg=_BG) - root.resizable(False, False) - if topmost: - root.attributes("-topmost", True) - if borderless: - # No title bar - it would be most of a window this small, and - # the drag handler below replaces the only thing it was for. - root.overrideredirect(True) - root.geometry("+40+40") - - self.button = tk.Button( - root, text="STOP", font=("Segoe UI", 26, "bold"), - bg=_RED, fg="white", activebackground=_RED_DARK, activeforeground="white", - relief="raised", bd=3, width=8, height=1, cursor="hand2", - command=self.on_stop) - self.button.pack(padx=8, pady=(8, 4)) - - self.status = tk.Label(root, text="checking...", font=("Segoe UI", 9, "bold"), - bg=_BG, fg=_GREY) - self.status.pack() - - bar = tk.Frame(root, bg=_BG) - bar.pack(fill="x", padx=8, pady=(2, 6)) - # Quiet, small, and confirmed - see the header on asymmetry. - self.release_btn = tk.Button(bar, text="release", font=("Segoe UI", 8), - bg="#2a2a2a", fg="#bbb", relief="flat", - cursor="hand2", command=self.on_release) - self.release_btn.pack(side="left") - tk.Button(bar, text="✕", font=("Segoe UI", 8), bg="#2a2a2a", fg="#bbb", - relief="flat", cursor="hand2", command=root.destroy).pack(side="right") - - # Drag from anywhere on the background, since there is no title bar. - for w in (root, self.status, bar): - w.bind("", self._press) - w.bind("", self._drag) - self._dx = self._dy = 0 - - self._last = None - self.tick() - - def _press(self, e) -> None: - self._dx, self._dy = e.x_root - self.root.winfo_x(), e.y_root - self.root.winfo_y() - - def _drag(self, e) -> None: - self.root.geometry(f"+{e.x_root - self._dx}+{e.y_root - self._dy}") - - def on_stop(self) -> None: - # Engage first and report afterwards: the flag write is what makes - # the microscope safe, and it must not wait behind a dialog. - try: - estop.engage("STOP button") - except Exception as exc: - messagebox.showerror("E-STOP", f"Could not engage:\n{exc}") - self.refresh(force=True) - - def on_release(self) -> None: - if not estop.is_engaged(): - return - if messagebox.askyesno("Release e-stop", - "Allow the microscope to move again?\n\n" - "Only do this once you know why it stopped."): - estop.release() - self.refresh(force=True) - - def refresh(self, force: bool = False) -> None: - engaged = estop.is_engaged() - if engaged == self._last and not force: - return - self._last = engaged - if engaged: - self.status.configure(text="ENGAGED - motion refused", fg=_RED) - self.button.configure(text="STOPPED", bg=_RED_DARK) - self.release_btn.configure(state="normal") - else: - self.status.configure(text="clear - motion permitted", fg=_GREEN) - self.button.configure(text="STOP", bg=_RED) - self.release_btn.configure(state="disabled") - - def tick(self) -> None: - self.refresh() - self.root.after(POLL_MS, self.tick) - - -_mutex = None # kept for the life of the process; Windows frees it on exit - - -def _claim_single_instance() -> bool: - """Take the panel mutex; False if another panel already holds it.""" - global _mutex - if sys.platform != "win32": - return True - import ctypes - k32 = ctypes.windll.kernel32 - k32.CreateMutexW.restype = ctypes.c_void_p - _mutex = k32.CreateMutexW(None, False, estop.PANEL_MUTEX) - return k32.GetLastError() != 183 # ERROR_ALREADY_EXISTS - - -def main() -> None: - ap = argparse.ArgumentParser(description=__doc__) - ap.add_argument("--no-topmost", action="store_true") - ap.add_argument("--titlebar", action="store_true", help="keep a normal window frame") - args = ap.parse_args() - if not _claim_single_instance(): - print("a STOP panel is already open", file=sys.stderr) - return - try: - root = tk.Tk() - except tk.TclError as exc: - print(f"no display available for the e-stop panel ({exc}). " - f"Use: python -m nis_elements_mcp.estop engage", file=sys.stderr) - raise SystemExit(1) - Panel(root, topmost=not args.no_topmost, borderless=not args.titlebar) - root.mainloop() - - -if __name__ == "__main__": - main() diff --git a/packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_client.py b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_client.py deleted file mode 100644 index 9bc2136..0000000 --- a/packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_client.py +++ /dev/null @@ -1,205 +0,0 @@ -# nis_bridge_client.py -# ------------------------------------------------------------ -# Client for the NIS bridge (nis_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 (`nis-mcp-bridge`, or `python -m nis_elements_mcp.nis_bridge_client`): -# -# nis-mcp-bridge job-file # where the file to paste into NIS is -# nis-mcp-bridge status -# nis-mcp-bridge move 100 0 -# nis-mcp-bridge objective "Plan Fluor 10x Ph1 DLL" -# nis-mcp-bridge optconfs -# nis-mcp-bridge capture D:\...\check.nd2 -# nis-mcp-bridge nd-run "C. elegans 3h" -# nis-mcp-bridge nd-finish -# nis-mcp-bridge shutdown # the ONLY safe way to stop the bridge job -# -# 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 -# (nis_events.py), which `nis-mcp-monitor` -# shows live. Status reads are not logged (the monitor polls them). -# -# NIS_BRIDGE_HOST / NIS_BRIDGE_PORT set the address (default -# http://127.0.0.1:8766). The XY step limit, the objective allow-list and -# the ND experiment allow-list (settings.py) are checked here before -# anything is sent, and the bridge checks its own copy of the first two. -# ------------------------------------------------------------ - -from __future__ import annotations - -import argparse -import json -import sys -import time -import urllib.error -import urllib.request -from pathlib import Path - -from nis_elements_mcp import estop, nis_events, settings -from nis_elements_mcp import nis_bridge_job -from nis_elements_mcp.nis_bridge_job import magnification - - - -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 settings.bridge_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: _step_refusal(dx_um, dy_um) - or self._call("POST", "/move", {"dx": dx_um, "dy": dy_um})) - - def change_objective(self, name: str) -> dict: - return self._act("objective", {"name": name}, - lambda: _objective_refusal(name) - or 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: _experiment_refusal(experiment) - or 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) - - -# The limits from settings.py, checked before a request leaves this process. -# Each returns the refusal, shaped like the bridge's own, or None. - -def _step_refusal(dx_um: float, dy_um: float) -> dict | None: - limit = settings.max_step_um() - if max(abs(dx_um), abs(dy_um)) > limit: - return {"error": f"step over {limit:g} um refused (NIS_MAX_STEP_UM)"} - return None - - -def _objective_refusal(name: str) -> dict | None: - allowed = settings.allowed_magnifications() - if magnification(name) not in allowed: - listed = "/".join(f"{m:g}x" for m in allowed) - return {"error": f"only {listed} objectives are allowed (NIS_ALLOWED_OBJECTIVES), got {name!r}"} - return None - - -def _experiment_refusal(experiment: str) -> dict | None: - allowed = settings.allowed_experiments() - if allowed is not None and experiment not in allowed: - return {"error": f"ND experiment {experiment!r} is not in NIS_ALLOWED_EXPERIMENTS " - f"({', '.join(allowed)})"} - return None - - -def job_file() -> Path: - """The bridge job to paste into a NIS JOBS Python task (nis_bridge_job.py).""" - return Path(nis_bridge_job.__file__).resolve() - - -def main() -> None: - ap = argparse.ArgumentParser(description="Talk to the NIS bridge job by hand.") - ap.add_argument("--url", help="bridge address (default from NIS_BRIDGE_HOST/PORT, else http://127.0.0.1:8766)") - sub = ap.add_subparsers(dest="cmd", required=True) - sub.add_parser("status") - m = sub.add_parser("move", help="relative XY move in um (max NIS_MAX_STEP_UM per axis, default 1000)") - m.add_argument("dx", type=float); m.add_argument("dy", type=float) - o = sub.add_parser("objective", help="exact name as listed by status (NIS_ALLOWED_OBJECTIVES, default 4x/10x)") - 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") - sub.add_parser("job-file", help="print the path of the file to paste into the NIS JOBS task") - a = ap.parse_args() - if a.cmd == "job-file": - print(job_file()) - return - - 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/packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_job.py b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_job.py deleted file mode 100644 index 551be67..0000000 --- a/packages/nis-elements-mcp/src/nis_elements_mcp/nis_bridge_job.py +++ /dev/null @@ -1,470 +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 nis_bridge_client.py (and -# through it the NIS MCP server) talks to. This file must stay standalone: -# NIS's own Python has only the standard library, so nothing here may -# import from nis_elements_mcp. -# -# 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 nis_elements_mcp.nis_bridge_client 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 -# estop.py uses) -# * XY moves are relative and capped at MAX_STEP_UM; Z is never moved -# * objective changes only to ALLOWED_MAGNIFICATIONS (default 4x/10x, -# whose 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 - -# Settings. Inside NIS they come from NIS's own environment, which is -# usually empty, so the defaults apply. To change one, set the variable -# (NIS_BRIDGE_PORT, NIS_MAX_STEP_UM, NIS_ALLOWED_OBJECTIVES, NIS_ESTOP_FILE) -# before starting NIS, or edit the default here before pasting the file. -# The client side (settings.py) uses the same names and defaults. -DEFAULT_HOST = "127.0.0.1" -DEFAULT_PORT = 8766 # 8765 is the plain port probe (nis_port_probe.py) -DEFAULT_MAX_STEP_UM = 1000.0 -DEFAULT_ALLOWED_OBJECTIVES = "4,10" # long working distances: they cannot reach the dish -VERSION = 1 -UI_TICK_MS = 50 # how often NIS's main thread looks for queued UI calls -UI_CALL_TIMEOUT_S = 600.0 # give up waiting for the main thread after this long -# "4x" / "10x" as a whole magnification - not the 4x inside "14x" or "40x" -_MAG = re.compile(r"(? "tuple[float, ...]": - """'4,10' or '4x, 10x' -> (4.0, 10.0).""" - return tuple(float(p.strip().rstrip("xX")) for p in text.split(",") if p.strip()) - - -def magnification(name: str) -> "float | None": - """The one magnification in an objective name ('PLAN APO 10x' -> 10.0), else None.""" - mags = {float(m) for m in _MAG.findall(name)} - return mags.pop() if len(mags) == 1 else None - - -def estop_file() -> Path: - """NIS_ESTOP_FILE, else ~/.nis-mcp/ESTOP: absolute, the same for every process.""" - return Path(os.environ.get("NIS_ESTOP_FILE", "").strip() or Path.home() / ".nis-mcp" / "ESTOP") - - -PORT = int(os.environ.get("NIS_BRIDGE_PORT", "").strip() or DEFAULT_PORT) -MAX_STEP_UM = float(os.environ.get("NIS_MAX_STEP_UM", "").strip() or DEFAULT_MAX_STEP_UM) -ALLOWED_MAGNIFICATIONS = parse_magnifications(os.environ.get("NIS_ALLOWED_OBJECTIVES", "").strip() - or DEFAULT_ALLOWED_OBJECTIVES) -ESTOP = estop_file() - -IDLE_STOP_S = 4 * 3600.0 # end the job if nothing has asked for this long -TURRET_SETTLE_S = 25.0 # how long to wait for the nosepiece to arrive -TURRET_POLL_S = 0.25 -MOVE_RELATIVE = 1 # StgMoveXY 'relative' argument -ND2_ALL_LAYERS = 14 # ImageSaveAs ImType: all layers (ND2 file) -QUERYSAVE_NO = 2 # CloseCurrentDocument: close without asking - - -class Macro: - """ctypes view of the NIS macro functions this bridge uses.""" - - SIGNATURES = { - "StgGetPosXY": [ct.POINTER(ct.c_double), ct.POINTER(ct.c_double)], - "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], - "Stg_SetNosepiecePosition": [ct.c_int], - "ChangeObjective": [ct.c_wchar_p], - "GetOptConfCount": [], - "GetOptConfName": [ct.c_int, ct.c_wchar_p, ct.c_int], - "Capture": [], - "ImageSaveAs": [ct.c_wchar_p, ct.c_int, ct.c_int], - "CloseCurrentDocument": [ct.c_int], - "ND_LoadExperiment": [ct.c_wchar_p], - "ND_RunExperiment": [ct.c_int], - "ND_IsInExperimentCapture": [], - "ND_FinishExperiment": [], - } - - def __init__(self, dll=None): - self.dll = dll if dll is not None else ct.cdll.g5_regprocs - for name, args in self.SIGNATURES.items(): - fn = getattr(self.dll, name) - fn.argtypes, fn.restype = args, ct.c_int - - def __getattr__(self, name): - return getattr(self.dll, name) - - -def _estop_engaged() -> bool: - try: - return ESTOP.exists() - except OSError: - return True # cannot tell -> treat as engaged, like estop.py - - -class MainThread: - """Runs calls on NIS's main (UI) thread. - - Capture, ImageSaveAs, CloseCurrentDocument and the ND calls open or close - NIS windows. Called from the worker thread they crashed nis_ar.exe - (Qt5Core.dll, 0xc0000409, 2026-10-16). run() is the one place our code - is on the main thread, so it calls install(), which registers a Win32 - thread timer there. NIS's own message loop then calls _tick on the main - thread every UI_TICK_MS, and _tick runs what the worker queued with - call(). If install() was never called, call() refuses. - """ - - def __init__(self, tick_ms: int = UI_TICK_MS): - self.tick_ms = tick_ms - self.installed = False - self._jobs = queue.Queue() - self._busy = False # a call is running: do not re-enter from a nested message loop - self._timer_proc = None # keep the ctypes callback alive - self.main_thread_id = None - - def install(self) -> None: - """Call from the main thread only (JOBS run()).""" - from ctypes import wintypes - user32 = ct.windll.user32 - proc_type = ct.WINFUNCTYPE(None, wintypes.HWND, wintypes.UINT, ct.c_size_t, wintypes.DWORD) - self._timer_proc = proc_type(lambda hwnd, msg, tid, tick: self._tick()) - user32.SetTimer.argtypes = [wintypes.HWND, ct.c_size_t, wintypes.UINT, proc_type] - user32.SetTimer.restype = ct.c_size_t - if not user32.SetTimer(None, 0, self.tick_ms, self._timer_proc): - raise OSError("SetTimer failed") - self.main_thread_id = threading.get_ident() - self.installed = True - - def _tick(self) -> None: - if self._busy: - return - self._busy = True - try: - while True: - try: - fn, box, cancelled = self._jobs.get_nowait() - except queue.Empty: - return - if cancelled.is_set(): # the caller timed out: do not start it late - continue - try: - box.put(fn()) - except Exception as e: - box.put({"error": f"{type(e).__name__}: {e}"}) - finally: - self._busy = False - - def call(self, fn, timeout_s: float = UI_CALL_TIMEOUT_S) -> dict: - if not self.installed: - return {"error": "no NIS main-thread hook: this call crashes NIS from the worker thread"} - box, cancelled = queue.Queue(), threading.Event() - self._jobs.put((fn, box, cancelled)) - try: - return box.get(timeout=timeout_s) - except queue.Empty: - cancelled.set() - return {"error": f"NIS's main thread did not run the call within {timeout_s:.0f} s"} - - -class Bridge: - """The operations, as plain methods returning JSON-able dicts.""" - - def __init__(self, macro: Macro, ui: MainThread | None = None): - self.m = macro - self.ui = ui or MainThread() # not installed: UI calls are refused - - 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 - if magnification(name) not in ALLOWED_MAGNIFICATIONS: - allowed = "/".join(f"{m:g}x" for m in ALLOWED_MAGNIFICATIONS) - return {"error": f"only {allowed} 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"} - - def on_main_thread() -> dict: - if _estop_engaged(): # re-check: the call may have waited in the queue - return {"error": "e-stop engaged - capture refused", "estop_engaged": True} - 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)} - return self.ui.call(on_main_thread) - - def nd_run(self, experiment: str) -> dict: - if (r := self._refuse_if_stopped("ND run")): - return r - - def on_main_thread() -> dict: - if _estop_engaged(): - return {"error": "e-stop engaged - ND run refused", "estop_engaged": True} - if self.m.ND_IsInExperimentCapture(): - return {"error": "an ND experiment is already running"} - # ND_LoadExperiment and ND_RunExperiment have no documented return - # value (NIS macro reference), and on the scope ND_LoadExperiment - # returned 0 for a template that does load (2026-10-30). So the - # codes are reported, not checked: NIS runs whatever the ND - # Acquisition window holds after the load. - rc_load = self.m.ND_LoadExperiment(experiment) - 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())} - return self.ui.call(on_main_thread) - - def nd_finish(self) -> dict: - # Always allowed, e-stop or not: it only ends a run early. - def on_main_thread() -> dict: - rc = self.m.ND_FinishExperiment() - return {"rc": rc, "nd_running": bool(self.m.ND_IsInExperimentCapture())} - return self.ui.call(on_main_thread) - - -# 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.""" - ui = MainThread() - try: - ui.install() # run() is on NIS's main thread: hook it for UI calls - except Exception as e: - print(f"NIS bridge: no main-thread hook ({type(e).__name__}: {e}); capture and ND calls refused") - threading.Thread(target=serve, args=(Bridge(Macro(), ui),), name="nis-bridge", - daemon=True).start() diff --git a/packages/nis-elements-mcp/src/nis_elements_mcp/nis_events.py b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_events.py deleted file mode 100644 index 5a579f3..0000000 --- a/packages/nis-elements-mcp/src/nis_elements_mcp/nis_events.py +++ /dev/null @@ -1,102 +0,0 @@ -# nis_events.py -# ------------------------------------------------------------ -# The NIS event log: one JSON line per thing done through the NIS bridge, -# appended to /events-YYYY-MM-DD.jsonl (default -# ~/nis-mcp/logs). Whoever drives the bridge -# (the NIS MCP server, a script, the command line) writes here, and -# 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 nis_elements_mcp import settings - -PHASES = ("start", "ok", "failed", "refused", "error") - - -def events_dir() -> Path: - """NIS_LOG_DIR, else ~/nis-mcp/logs. Read on every call, so a change takes effect at once.""" - return settings.log_dir() - - -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/packages/nis-elements-mcp/src/nis_elements_mcp/nis_monitor.py b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_monitor.py deleted file mode 100644 index 23267a7..0000000 --- a/packages/nis-elements-mcp/src/nis_elements_mcp/nis_monitor.py +++ /dev/null @@ -1,196 +0,0 @@ -# nis_monitor.py -# ------------------------------------------------------------ -# Live terminal view of the NIS bridge. Run it in its own window: -# -# python -m nis_elements_mcp.nis_monitor # refresh every 1 s, Ctrl+C to leave -# python -m nis_elements_mcp.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, 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. -# NIS_NO_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 nis_elements_mcp import estop, nis_events, settings - -ON_WINDOWS = sys.platform == "win32" -MONITOR_MUTEX = r"Local\nis-mcp-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 settings.monitor_disabled() or not ON_WINDOWS: - return - try: - if monitor_running(): - return - subprocess.Popen([sys.executable, "-m", "nis_elements_mcp.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 nis_elements_mcp.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=settings.bridge_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/packages/nis-elements-mcp/src/nis_elements_mcp/nis_server.py b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_server.py deleted file mode 100644 index 1b047b3..0000000 --- a/packages/nis-elements-mcp/src/nis_elements_mcp/nis_server.py +++ /dev/null @@ -1,38 +0,0 @@ -# nis_server.py -# ------------------------------------------------------------ -# MCP server for driving the microscope through NIS-Elements (see -# nis_tools.py). Needs the NIS bridge job (nis_bridge_job.py) running -# inside NIS. -# -# Run, either way: -# nis-mcp (installed console script) -# python -m nis_elements_mcp.nis_server -# -# { "mcpServers": { "nis": { "command": "nis-mcp" } } } -# ------------------------------------------------------------ - -from mcp.server.mcpserver import MCPServer - -from nis_elements_mcp import estop, nis_monitor, nis_tools - -mcp = MCPServer("NIS-Elements") - -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(nis_tools.estop) - - -def main() -> None: - """Console entry point (``nis-mcp``): 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/packages/nis-elements-mcp/src/nis_elements_mcp/nis_tools.py b/packages/nis-elements-mcp/src/nis_elements_mcp/nis_tools.py deleted file mode 100644 index 18d5284..0000000 --- a/packages/nis-elements-mcp/src/nis_elements_mcp/nis_tools.py +++ /dev/null @@ -1,184 +0,0 @@ -# nis_tools.py -# ------------------------------------------------------------ -# MCP tools that drive the microscope THROUGH NIS-Elements, via the NIS -# bridge (nis_bridge_job.py, running as a JOBS task; client in -# nis_bridge_client.py). Served by nis_server.py. -# -# WHAT THEY DO: read the stage, objective and ND state; move XY; change -# objective; capture with the optical configuration active in NIS; run -# and end ND experiments saved in NIS; and the e-stop. -# -# SAFETY: -# * every tool that moves or acquires requires confirm=True -# (PermissionError otherwise) -# * 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 (NIS_MAX_STEP_UM, default 1 mm); -# there is no Z tool -# * objective changes only to NIS_ALLOWED_OBJECTIVES (default 4x/10x) -# * ND runs only of NIS_ALLOWED_EXPERIMENTS, if that is set -# * 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 re -from pathlib import Path - -from nis_elements_mcp import estop as _estop -from nis_elements_mcp import settings -from nis_elements_mcp.nis_bridge_client import NISBridge - - -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: NIS_CAPTURE_DIR, else ~/nis-mcp/captures.""" - d = settings.capture_dir() - 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 (or the - NIS_MAX_STEP_UM setting). 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), unless NIS_ALLOWED_OBJECTIVES says otherwise. 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, Z, channels, save-to-file path). NIS does - not report whether the name was found: if it was not, NIS runs - whatever the ND Acquisition window currently holds - so check that - window, or the name, with the operator first. The call may not return - until the experiment ends. Refused if one is already running, or if - NIS_ALLOWED_EXPERIMENTS is set and does not list it. 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()) - - -def estop(action: str = "status", reason: str = "requested via MCP") -> dict: - """EMERGENCY STOP: immediately forbid all microscope motion. - - Call this the moment anything looks wrong - an unexpected move, a - position that doesn't match what you asked for, a stage that seems to - be travelling when it shouldn't be, or an instruction from the - operator to stop. It is cheap, it is instant, and a needless stop - costs nothing but a release. Do not deliberate: stop first, diagnose - afterwards. - - Once engaged, EVERY motion primitive refuses - not just this session's, - but every process on the machine that checks the same e-stop file, - including the bridge inside NIS-Elements. The flag lives in a file, so - it outlives whatever set it and cannot be lost by a process dying. It - cannot stop a move already in flight: that move runs to its end, and - every move after it is refused. An ND experiment that is running can - still be ended with nis_finish_experiment. - - action: "engage" to stop everything, or "status" to report the current - state. RELEASE IS DELIBERATELY NOT AVAILABLE HERE - a stop that the - agent can lift by itself is not a safety device. A human clears it - from a terminal with `python -m nis_elements_mcp.estop release`. - - Returns the resulting state. This tool never needs confirm=True: a - stop is always safe to perform, and requiring a confirmation step for - an emergency control would defeat its purpose. - """ - if action == "engage": - info = _estop.engage(reason) - return { - "engaged": True, - "detail": info, - "release_with": "python -m nis_elements_mcp.estop release", - "note": "All motion is now refused for every process on this machine.", - } - if action == "status": - return { - "engaged": _estop.is_engaged(), - "detail": _estop.details(), - "flag_file": str(_estop.ESTOP_PATH), - } - raise ValueError( - f"Unknown estop action {action!r}. Use 'engage' to stop motion, or " - "'status' to check. Releasing is a human action performed at a " - "terminal: python -m nis_elements_mcp.estop release" - ) diff --git a/packages/nis-elements-mcp/src/nis_elements_mcp/settings.py b/packages/nis-elements-mcp/src/nis_elements_mcp/settings.py deleted file mode 100644 index 81d208f..0000000 --- a/packages/nis-elements-mcp/src/nis_elements_mcp/settings.py +++ /dev/null @@ -1,76 +0,0 @@ -# settings.py -# ------------------------------------------------------------ -# Every setting nis-elements-mcp reads. All come from environment -# variables, so an MCP client config sets them per project, e.g. -# -# claude mcp add nis -e NIS_CAPTURE_DIR=D:\data\captures -- nis-mcp -# -# Each is read when it is needed, not once at import, except the e-stop -# file (estop.ESTOP_PATH), which every process must agree on from start. -# -# NIS_BRIDGE_HOST bridge address 127.0.0.1 -# NIS_BRIDGE_PORT bridge port 8766 -# NIS_CAPTURE_DIR where nis_capture saves ~/nis-mcp/captures -# NIS_LOG_DIR event log folder ~/nis-mcp/logs -# NIS_ESTOP_FILE e-stop flag file ~/.nis-mcp/ESTOP -# NIS_ALLOWED_OBJECTIVES magnifications allowed 4,10 -# NIS_ALLOWED_EXPERIMENTS ND experiment names allowed (empty = any saved one) -# NIS_MAX_STEP_UM largest XY step per call 1000 -# NIS_NO_ESTOP_PANEL 1 = do not open the STOP window -# NIS_NO_MONITOR 1 = do not open the monitor window -# -# The bridge job inside NIS (nis_bridge_job.py) reads the same names from -# NIS's own environment, with the same defaults; the client and the bridge -# both enforce the limits, so the stricter of the two wins. -# ------------------------------------------------------------ - -from __future__ import annotations - -import os -from pathlib import Path - -from nis_elements_mcp import nis_bridge_job as _job - - -def _env(name: str) -> str: - return os.environ.get(name, "").strip() - - -def bridge_url() -> str: - host = _env("NIS_BRIDGE_HOST") or _job.DEFAULT_HOST - port = _env("NIS_BRIDGE_PORT") or _job.DEFAULT_PORT - return f"http://{host}:{port}" - - -def capture_dir() -> Path: - return Path(_env("NIS_CAPTURE_DIR") or Path.home() / "nis-mcp" / "captures") - - -def log_dir() -> Path: - return Path(_env("NIS_LOG_DIR") or Path.home() / "nis-mcp" / "logs") - - -def estop_file() -> Path: - return _job.estop_file() - - -def allowed_magnifications() -> tuple[float, ...]: - return _job.parse_magnifications(_env("NIS_ALLOWED_OBJECTIVES") or _job.DEFAULT_ALLOWED_OBJECTIVES) - - -def allowed_experiments() -> list[str] | None: - """The names listed in NIS_ALLOWED_EXPERIMENTS (comma-separated), or None for any.""" - names = [n.strip() for n in _env("NIS_ALLOWED_EXPERIMENTS").split(",") if n.strip()] - return names or None - - -def max_step_um() -> float: - return float(_env("NIS_MAX_STEP_UM") or _job.DEFAULT_MAX_STEP_UM) - - -def estop_panel_disabled() -> bool: - return bool(_env("NIS_NO_ESTOP_PANEL")) - - -def monitor_disabled() -> bool: - return bool(_env("NIS_NO_MONITOR")) diff --git a/packages/nis-elements-mcp/src/nis_elements_mcp/testing.py b/packages/nis-elements-mcp/src/nis_elements_mcp/testing.py deleted file mode 100644 index 9696378..0000000 --- a/packages/nis-elements-mcp/src/nis_elements_mcp/testing.py +++ /dev/null @@ -1,192 +0,0 @@ -# testing.py -# ------------------------------------------------------------ -# A mock NIS for tests, no microscope needed: FakeNIS stands in for -# g5_regprocs.dll (same function names, records every call), and the -# `bridge` fixture runs the real bridge job's HTTP server and request queue -# on it, on a free port, with the client pointed at it. -# -# Use it from any project's tests (needs pytest): -# -# from nis_elements_mcp.testing import bridge, estop_file # noqa: F401 (fixtures) -# -# def test_my_script_moves(bridge): -# nis, url, client = bridge -# client.move_relative(100, 0) -# assert nis.x == 200.0 -# ------------------------------------------------------------ - -from __future__ import annotations - -import json -import threading -import time -import urllib.error -import urllib.request - -import pytest - -from nis_elements_mcp import estop, nis_events -from nis_elements_mcp import nis_bridge_client as client_mod -from nis_elements_mcp import nis_bridge_job as bj - - -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 λD 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 = 0 # what the real ND_LoadExperiment returned (it has no documented value) - self.calls = [] - self.threads = {} # call name -> id of the thread that made it - 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) - self.threads[name] = threading.get_ident() - 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 - - -class FakeMainThread(bj.MainThread): - """Plays NIS's message loop: one thread that calls _tick, as the Win32 timer does.""" - - def __init__(self): - super().__init__(tick_ms=5) - self.installed = True - self._stop = threading.Event() - self.thread = threading.Thread(target=self._pump, daemon=True) - self.thread.start() - self.main_thread_id = self.thread.ident - - def _pump(self): - while not self._stop.is_set(): - self._tick() - time.sleep(0.005) - - def close(self): - self._stop.set() - self.thread.join(5) - - -@pytest.fixture -def bridge(estop_file, monkeypatch): - nis = FakeNIS() - ui = FakeMainThread() - stop, ready, port = threading.Event(), threading.Event(), [] - t = threading.Thread(target=bj.serve, args=(bj.Bridge(bj.Macro(nis), ui),), - 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("NIS_BRIDGE_HOST", "127.0.0.1") - monkeypatch.setenv("NIS_BRIDGE_PORT", str(port[0])) - nis.ui = ui - yield nis, url, client_mod.NISBridge(url) - stop.set() - t.join(5) - ui.close() - - -@pytest.fixture -def events_log(tmp_path, monkeypatch): - monkeypatch.setattr(nis_events, "events_dir", lambda: tmp_path / "events") - return nis_events.events_path() - - -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()) diff --git a/packages/nis-elements-mcp/tests/conftest.py b/packages/nis-elements-mcp/tests/conftest.py deleted file mode 100644 index f331725..0000000 --- a/packages/nis-elements-mcp/tests/conftest.py +++ /dev/null @@ -1,8 +0,0 @@ -# Tests never write logs or captures into the user's ~/nis-mcp: point both -# folders at a throwaway directory before any test runs. -import os -import tempfile - -_TMP = tempfile.mkdtemp(prefix="nis-mcp-tests-") -os.environ["NIS_LOG_DIR"] = os.path.join(_TMP, "logs") -os.environ["NIS_CAPTURE_DIR"] = os.path.join(_TMP, "captures") diff --git a/packages/nis-elements-mcp/tests/test_job_file.py b/packages/nis-elements-mcp/tests/test_job_file.py deleted file mode 100644 index bc77eed..0000000 --- a/packages/nis-elements-mcp/tests/test_job_file.py +++ /dev/null @@ -1,22 +0,0 @@ -# `nis-mcp-bridge job-file`: where the file to paste into NIS is. Works with no bridge running. -import ast -import sys - -from nis_elements_mcp import nis_bridge_client as client_mod - - -def test_job_file_prints_the_bridge_job_path(monkeypatch, capsys): - monkeypatch.setenv("NIS_BRIDGE_PORT", "9") # nothing listens there: not needed - monkeypatch.setattr(sys, "argv", ["nis-mcp-bridge", "job-file"]) - client_mod.main() - path = capsys.readouterr().out.strip() - assert path.endswith("nis_bridge_job.py") and path == str(client_mod.job_file()) - - -def test_the_job_file_imports_only_the_standard_library(): - # NIS's own Python has nothing else installed, so the pasted file must stand alone. - tree = ast.parse(client_mod.job_file().read_text(encoding="utf-8")) - imported = {(n.module or "").split(".")[0] for n in ast.walk(tree) if isinstance(n, ast.ImportFrom)} - imported |= {a.name.split(".")[0] for n in ast.walk(tree) if isinstance(n, ast.Import) for a in n.names} - allowed = set(sys.stdlib_module_names) | {"__future__", "limjob"} # limjob is NIS's own - assert imported <= allowed, imported - allowed diff --git a/packages/nis-elements-mcp/tests/test_nis_bridge.py b/packages/nis-elements-mcp/tests/test_nis_bridge.py deleted file mode 100644 index f07d2b2..0000000 --- a/packages/nis-elements-mcp/tests/test_nis_bridge.py +++ /dev/null @@ -1,357 +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 time -import urllib.request - -import pytest - -from nis_elements_mcp import estop, nis_events, nis_monitor as monitor -from nis_elements_mcp import nis_bridge_client as client_mod -from nis_elements_mcp import nis_bridge_job as bj -from nis_elements_mcp import nis_tools -from nis_elements_mcp.testing import (FakeMainThread, FakeNIS, bridge, estop_file, # noqa: F401 (fixtures) - events_log, raw) - - -# ---- 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 nis.threads["Capture"] == nis.threads["ImageSaveAs"] == nis.ui.thread.ident - assert "already exists" in c.capture(str(target))["error"] - assert "nd2" in c.capture(str(tmp_path / "x.tif"))["error"] - - -def test_nd_run_reports_the_load_code_and_refuses_a_second_run(bridge): - nis, url, c = bridge - r = c.nd_run("C. elegans 3h") # load returns 0, as on the scope: not a failure - assert r["rc_load"] == 0 and r["nd_running"] is True - assert nis.calls.index("ND_LoadExperiment") < nis.calls.index("ND_RunExperiment") - 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("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, NIS_NO_ESTOP_PANEL="1", NIS_NO_MONITOR="1", - NIS_LOG_DIR=str(tmp_path / "logs"), NIS_CAPTURE_DIR=str(tmp_path / "caps")) - params = StdioServerParameters(command=sys.executable, args=["-m", "nis_elements_mcp.nis_server"], 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("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.nd_running = True - with pytest.raises(RuntimeError, match="already running"): # a refusal raises - nis_tools.nis_run_experiment("second", 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 --------------------------------------- - -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("NIS_NO_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", "nis_elements_mcp.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("NIS_NO_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) - - -def test_ui_calls_run_on_the_main_thread_and_moves_do_not(bridge): - nis, url, c = bridge - c.move_relative(10, 0) - c.nd_run("exp") - c.nd_finish() - worker = nis.threads["StgMoveXY"] - assert worker != nis.ui.thread.ident - for name in ("ND_LoadExperiment", "ND_RunExperiment", "ND_FinishExperiment"): - assert nis.threads[name] == nis.ui.thread.ident - - -def test_ui_calls_are_refused_when_the_main_thread_is_not_hooked(estop_file): - nis = FakeNIS() - b = bj.Bridge(bj.Macro(nis)) # MainThread never installed - assert "main-thread hook" in b.capture("x.nd2")["error"] - assert "main-thread hook" in b.nd_run("exp")["error"] - assert "main-thread hook" in b.nd_finish()["error"] - assert not nis.calls - - -def test_a_call_the_main_thread_never_ran_is_cancelled_not_run_late(estop_file): - ui = bj.MainThread() - ui.installed = True # hooked, but nothing pumps it - ran = [] - r = ui.call(lambda: ran.append(1) or {}, timeout_s=0.05) - assert "did not run" in r["error"] - ui._tick() # the pump finally wakes up - assert not ran - - -def test_estop_pressed_while_a_capture_waits_stops_it(estop_file): - nis = FakeNIS() - ui = bj.MainThread() - ui.installed = True - b = bj.Bridge(bj.Macro(nis), ui) - box = [] - t = threading.Thread(target=lambda: box.append(b.capture("y.nd2")), daemon=True) - t.start() - time.sleep(0.1) # queued, not yet run - estop_file.write_text("x") - ui._tick() - t.join(5) - assert box[0]["estop_engaged"] is True and "Capture" not in nis.calls diff --git a/packages/nis-elements-mcp/tests/test_nis_events_monitor.py b/packages/nis-elements-mcp/tests/test_nis_events_monitor.py deleted file mode 100644 index a65da82..0000000 --- a/packages/nis-elements-mcp/tests/test_nis_events_monitor.py +++ /dev/null @@ -1,218 +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 nis_elements_mcp import nis_events, nis_monitor as monitor -from nis_elements_mcp import nis_bridge_client as client_mod -from nis_elements_mcp import nis_bridge_job as bj -from nis_elements_mcp import nis_tools -from nis_elements_mcp.testing 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") - hooked = [] - monkeypatch.setattr(bj, "MainThread", lambda: type("UI", (), {"install": lambda self: hooked.append( - threading.current_thread())})()) - monkeypatch.setattr(bj, "Bridge", lambda m, ui: ("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") - assert hooked == [threading.current_thread()] # the main-thread hook is installed from run()'s thread - 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.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_home_nis_mcp(tmp_path, monkeypatch): - monkeypatch.delenv("NIS_CAPTURE_DIR", raising=False) - monkeypatch.setattr(nis_tools.Path, "home", lambda: tmp_path) - d = nis_tools.capture_dir() - assert d == tmp_path / "nis-mcp" / "captures" and d.is_dir() - - -def test_capture_folder_follows_nis_capture_dir(tmp_path, monkeypatch): - monkeypatch.setenv("NIS_CAPTURE_DIR", str(tmp_path / "mine")) - assert nis_tools.capture_dir() == tmp_path / "mine" - - -def test_event_log_folder_follows_nis_log_dir(tmp_path, monkeypatch): - monkeypatch.setenv("NIS_LOG_DIR", str(tmp_path / "logs")) - assert nis_events.events_dir() == tmp_path / "logs" - monkeypatch.delenv("NIS_LOG_DIR") - monkeypatch.setattr(nis_events.Path, "home", lambda: tmp_path) - assert nis_events.events_dir() == tmp_path / "nis-mcp" / "logs" - - -# ---- 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("NIS_NO_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("NIS_NO_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/packages/nis-elements-mcp/tests/test_settings.py b/packages/nis-elements-mcp/tests/test_settings.py deleted file mode 100644 index 022fd5b..0000000 --- a/packages/nis-elements-mcp/tests/test_settings.py +++ /dev/null @@ -1,85 +0,0 @@ -# The NIS_* settings: defaults, overrides, and the limits the client -# enforces before a request reaches NIS. -import pytest - -from nis_elements_mcp import nis_bridge_job as bj -from nis_elements_mcp import nis_tools, settings -from nis_elements_mcp.testing import bridge, estop_file # noqa: F401 (fixtures) - -SETTINGS = ("NIS_BRIDGE_HOST", "NIS_BRIDGE_PORT", "NIS_ESTOP_FILE", "NIS_ALLOWED_OBJECTIVES", - "NIS_ALLOWED_EXPERIMENTS", "NIS_MAX_STEP_UM", "NIS_NO_ESTOP_PANEL", "NIS_NO_MONITOR") - - -@pytest.fixture -def clean_env(monkeypatch, tmp_path): - for name in SETTINGS: - monkeypatch.delenv(name, raising=False) - monkeypatch.setattr(settings.Path, "home", lambda: tmp_path) - return tmp_path - - -def test_defaults(clean_env): - assert settings.bridge_url() == "http://127.0.0.1:8766" - assert settings.estop_file() == clean_env / ".nis-mcp" / "ESTOP" - assert settings.allowed_magnifications() == (4.0, 10.0) - assert settings.allowed_experiments() is None - assert settings.max_step_um() == 1000.0 - assert not settings.estop_panel_disabled() and not settings.monitor_disabled() - - -def test_overrides(clean_env, monkeypatch): - monkeypatch.setenv("NIS_BRIDGE_HOST", "10.0.0.5") - monkeypatch.setenv("NIS_BRIDGE_PORT", "9000") - monkeypatch.setenv("NIS_ESTOP_FILE", str(clean_env / "stop")) - monkeypatch.setenv("NIS_ALLOWED_OBJECTIVES", "4x, 10X, 20") - monkeypatch.setenv("NIS_ALLOWED_EXPERIMENTS", " Embryo 2h , Worm stack ") - monkeypatch.setenv("NIS_MAX_STEP_UM", "250") - monkeypatch.setenv("NIS_NO_ESTOP_PANEL", "1") - monkeypatch.setenv("NIS_NO_MONITOR", "1") - assert settings.bridge_url() == "http://10.0.0.5:9000" - assert settings.estop_file() == clean_env / "stop" - assert settings.allowed_magnifications() == (4.0, 10.0, 20.0) - assert settings.allowed_experiments() == ["Embryo 2h", "Worm stack"] - assert settings.max_step_um() == 250.0 - assert settings.estop_panel_disabled() and settings.monitor_disabled() - - -def test_magnification_is_read_from_the_objective_name(): - assert bj.magnification("PLAN APO λD 10x OFN25 DIC N1") == 10.0 - assert bj.magnification("Plan Apo 60x Oil") == 60.0 - assert bj.magnification("Plan Fluor 14x") == 14.0 # not the 4x inside it - assert bj.magnification("no magnification") is None - assert bj.magnification("4x or 10x") is None # ambiguous: refused - - -def test_a_step_over_the_limit_is_refused_before_it_is_sent(bridge, monkeypatch): - nis, url, c = bridge - monkeypatch.setenv("NIS_MAX_STEP_UM", "200") - assert "NIS_MAX_STEP_UM" in c.move_relative(250, 0)["error"] - assert c.move_relative(150, 0)["after_um"] == [250.0, 200.0] - assert nis.moved() == ["StgMoveXY"] # only the allowed step reached NIS - - -def test_an_objective_outside_the_allow_list_is_refused_before_it_is_sent(bridge, monkeypatch): - nis, url, c = bridge - monkeypatch.setenv("NIS_ALLOWED_OBJECTIVES", "10") - with pytest.raises(RuntimeError, match="NIS_ALLOWED_OBJECTIVES"): - nis_tools.nis_change_objective(nis.objectives[1], confirm=True) # the 4x - assert nis.moved() == [] - assert nis_tools.nis_change_objective("Plan Fluor 10x Ph1 DLL", confirm=True)["arrived"] is True - - -def test_the_bridge_keeps_its_own_objective_limit(bridge, monkeypatch): - nis, url, c = bridge - monkeypatch.setenv("NIS_ALLOWED_OBJECTIVES", "4,10,60") # the client would allow 60x ... - assert "only 4x/10x" in c.change_objective("Plan Apo 60x Oil")["error"] # ... the bridge does not - assert nis.moved() == [] - - -def test_only_listed_experiments_run_when_the_list_is_set(bridge, monkeypatch): - nis, url, c = bridge - monkeypatch.setenv("NIS_ALLOWED_EXPERIMENTS", "Embryo 2h,Worm stack") - with pytest.raises(RuntimeError, match="NIS_ALLOWED_EXPERIMENTS"): - nis_tools.nis_run_experiment("Something else", confirm=True) - assert "ND_LoadExperiment" not in nis.calls - assert nis_tools.nis_run_experiment("Worm stack", confirm=True)["nd_running"] is True diff --git a/pyproject.toml b/pyproject.toml index 0dc794e..8ac2cbd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -21,8 +21,6 @@ dependencies = [ "Pillow==12.3.0", "PyYAML==6.0.3", "numpy==2.4.6", - # The NIS-Elements MCP server, from this repo's own folder (never from an index). - "nis-elements-mcp @ {root:uri}/packages/nis-elements-mcp", ] [project.optional-dependencies] @@ -72,19 +70,13 @@ all = [ [project.scripts] baumer-ti2-mcp = "mcp_server.baumer_ti2.baumer_ti2_server:main" -# nis-mcp comes from the nis-elements-mcp package (default folders under ~/nis-mcp); -# confocal-mcp-nis runs the same server with this repo's log and capture folders. -# Old names, kept so existing MCP client configs keep working. +# Old name, kept so existing MCP client configs keep working. confocal-mcp = "mcp_server.baumer_ti2.baumer_ti2_server:main" -confocal-mcp-nis = "mcp_server.nis.nis_server:main" [project.urls] Homepage = "https://github.com/BioNanomics/microscope-agent" Repository = "https://github.com/BioNanomics/microscope-agent" -[tool.hatch.metadata] -allow-direct-references = true - [tool.hatch.build.targets.wheel] packages = ["mcp_server", "acquisition", "harness", "timelapse"] diff --git a/tests/test_calibration.py b/tests/test_calibration.py index 9f679bb..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 nis_elements_mcp.testing 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/packages/nis-elements-mcp/tests/test_estop.py b/tests/test_estop.py similarity index 92% rename from packages/nis-elements-mcp/tests/test_estop.py rename to tests/test_estop.py index 7b93b5c..62f1984 100644 --- a/packages/nis-elements-mcp/tests/test_estop.py +++ b/tests/test_estop.py @@ -3,7 +3,7 @@ import pytest -from nis_elements_mcp import estop +from acquisition import estop @pytest.fixture @@ -65,6 +65,9 @@ def test_launch_panel_opt_out_and_already_running(monkeypatch): 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) estop.launch_panel() assert opened == [] @@ -76,7 +79,7 @@ def test_launch_panel_starts_detached_process(monkeypatch): monkeypatch.setattr(estop, "panel_running", lambda: False) monkeypatch.setattr(estop.subprocess, "Popen", lambda *a, **k: opened.append(a[0])) estop.launch_panel() - assert opened[0][-2:] == ["-m", "nis_elements_mcp.estop_panel"] + assert opened[0][-2:] == ["-m", "acquisition.estop_panel"] def test_launch_panel_failure_goes_to_stderr(monkeypatch, capsys): diff --git a/packages/nis-elements-mcp/tests/test_estop_panel.py b/tests/test_estop_panel.py similarity index 70% rename from packages/nis-elements-mcp/tests/test_estop_panel.py rename to tests/test_estop_panel.py index 4f8886b..22f0f1b 100644 --- a/packages/nis-elements-mcp/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 nis_elements_mcp import estop, nis_monitor +from acquisition import estop class Widget: @@ -85,12 +85,12 @@ def panel_mod(monkeypatch, tmp_path): monkeypatch.setitem(sys.modules, "tkinter", tk) monkeypatch.setitem(sys.modules, "tkinter.messagebox", mb) monkeypatch.setattr(estop, "ESTOP_PATH", tmp_path / "ESTOP") - sys.modules.pop("nis_elements_mcp.estop_panel", None) - mod = importlib.import_module("nis_elements_mcp.estop_panel") + sys.modules.pop("acquisition.estop_panel", None) + mod = importlib.import_module("acquisition.estop_panel") mod.real_claim = mod._claim_single_instance # the tests of the mutex use this monkeypatch.setattr(mod, "_claim_single_instance", lambda: True) # a real mutex would outlive the test yield mod, asked - sys.modules.pop("nis_elements_mcp.estop_panel", None) + sys.modules.pop("acquisition.estop_panel", None) def make_panel(mod, **kw): @@ -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_nis_settings.py b/tests/test_nis_settings.py deleted file mode 100644 index dcbb9eb..0000000 --- a/tests/test_nis_settings.py +++ /dev/null @@ -1,52 +0,0 @@ -# This repo's settings for the nis-elements-mcp package (acquisition/_nis_settings.py). -from acquisition import _nis_settings -from nis_elements_mcp import settings - - -def _unset(monkeypatch, *names): - for name in names: - monkeypatch.setenv(name, "") # recorded first, so the undo removes what the call sets - monkeypatch.delenv(name) - - -def test_logs_and_captures_stay_in_this_repos_data_folder(tmp_path, monkeypatch): - _unset(monkeypatch, "NIS_LOG_DIR", "NIS_CAPTURE_DIR", "CONFOCAL_NIS_CAPTURE_DIR") - monkeypatch.setattr(_nis_settings.paths, "logs_dir", lambda: tmp_path / "logs") - monkeypatch.setattr(_nis_settings.paths, "data_root", lambda: tmp_path) - _nis_settings.use_repo_folders() - assert settings.log_dir() == tmp_path / "logs" / "nis" - assert settings.capture_dir() == tmp_path / "data" / "NIS" / "captures" - - -def test_a_stop_engaged_in_the_old_file_is_moved_not_lost(tmp_path, monkeypatch): - old, new = tmp_path / "old" / "ESTOP", tmp_path / "new" / "ESTOP" - old.parent.mkdir() - old.write_text('{"reason": "pressed before the switch"}') - monkeypatch.setenv("NIS_ESTOP_FILE", str(new)) - _nis_settings.carry_over_old_estop(old) - assert not old.exists() and "pressed before the switch" in new.read_text() - - -def test_an_engaged_new_file_is_kept_and_the_old_one_dropped(tmp_path, monkeypatch): - old, new = tmp_path / "ESTOP.old", tmp_path / "ESTOP" - old.write_text("old") - new.write_text("new") - monkeypatch.setenv("NIS_ESTOP_FILE", str(new)) - _nis_settings.carry_over_old_estop(old) - assert not old.exists() and new.read_text() == "new" - - -def test_nothing_happens_without_an_old_file(tmp_path, monkeypatch): - monkeypatch.setenv("NIS_ESTOP_FILE", str(tmp_path / "ESTOP")) - _nis_settings.carry_over_old_estop(tmp_path / "missing") - assert not (tmp_path / "ESTOP").exists() - - -def test_old_switch_names_still_work(monkeypatch): - _unset(monkeypatch, "NIS_NO_ESTOP_PANEL", "NIS_NO_MONITOR", "NIS_BRIDGE_HOST", "NIS_BRIDGE_PORT") - monkeypatch.setenv("CONFOCAL_NO_ESTOP_PANEL", "1") - monkeypatch.setenv("CONFOCAL_NO_NIS_MONITOR", "1") - monkeypatch.setenv("CONFOCAL_NIS_BRIDGE_URL", "http://127.0.0.1:9001") - _nis_settings.use_old_names() - assert settings.estop_panel_disabled() and settings.monitor_disabled() - assert settings.bridge_url() == "http://127.0.0.1:9001" diff --git a/tests/test_small_gaps.py b/tests/test_small_gaps.py index d53a3d9..761d1ed 100644 --- a/tests/test_small_gaps.py +++ b/tests/test_small_gaps.py @@ -1,43 +1,23 @@ # 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 nis_elements_mcp import nis_bridge_job as bj +from acquisition import estop, paths from acquisition.orchestration import stage_positions, worm_follow from harness import context -from mcp_server.nis import nis_tools from tests.fakes import fake_ti2 # noqa: F401 (fixture) from tests.fakes_camera import install_fake_camera_stack -from nis_elements_mcp.testing 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.nis import nis_server - calls = [] - monkeypatch.setattr(nis_server.estop, "launch_panel", lambda: calls.append("panel")) - monkeypatch.setattr(nis_server.nis_monitor, "launch", lambda: calls.append("monitor")) - monkeypatch.setattr(nis_server.mcp, "run", lambda transport: calls.append(("run", transport))) - nis_server.main() - assert calls == ["panel", "monitor", ("run", "stdio")] - - def test_loop_server_main_opens_the_panel_then_serves(monkeypatch): from mcp_server.baumer_ti2 import baumer_ti2_server calls = [] @@ -47,26 +27,17 @@ def test_loop_server_main_opens_the_panel_then_serves(monkeypatch): assert calls == ["panel", ("run", "stdio")] -@pytest.mark.parametrize("module", ["mcp_server.baumer_ti2.baumer_ti2_server", "mcp_server.nis.nis_server"]) -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.nis import nis_server - names = {t.name for t in asyncio.run(nis_server.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 @@ -83,112 +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("NIS_BRIDGE_PORT", "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"]) - monkeypatch.delitem(sys.modules, 'acquisition.backends.nis_bridge', raising=False) # run it as a fresh `python -m` would - 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: @@ -203,19 +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("NIS_BRIDGE_PORT", "9") - monkeypatch.setattr(sys, "argv", ["nis_monitor", "--once"]) - monkeypatch.delitem(sys.modules, 'acquisition.nis_monitor', raising=False) # run it as a fresh `python -m` would - 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) @@ -249,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):