diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..a54e519 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,44 @@ +# Changelog + +All notable changes to this project are recorded here. +Format follows [Keep a Changelog](https://keepachangelog.com/); versions follow +[Semantic Versioning](https://semver.org/). + +## [Unreleased] + +## [0.1.0] - 2026-08-31 + +First packaged release. + +### Added +- Installable package `confocal-mcp` with a `confocal-mcp` console entry point + (`mcp_server.server_loop:main`). MCP client config becomes + `{"command": "confocal-mcp"}` after `pip install` / `uv tool install` / + `pipx install`. +- Optional dependency groups: `camera` (harvesters, genicam, opencv), `sdk` + (pywin32), `harness` (anthropic, python-dotenv), `all`. A core install + (server + mock stage) pulls no hardware dependencies and runs anywhere. +- `CONFOCAL_MCP_DATA_DIR` environment variable. Without it, runtime data + (captures, move/frame history, saved positions) is written under the current + working directory instead of next to the installed package + (`acquisition/paths.py`). +- `mcp_server.__version__`, resolved from installed package metadata. +- MIT license. + +### Changed +- The camera stack (`cv2` + `harvesters`) is imported lazily in + `loop_tools._get_camera()`, so `import mcp_server.loop_tools` works on a + core-only install - matching the existing lazy import of `nis_sdk`. +- `BaumerGenICam.capture()` dispatches on the camera's declared `PixelFormat` + (BGR8 / RGB8 / Mono8 / Bayer*) instead of assuming BayerRG8, which crashed + whenever the camera was left in a 3-channel format. +- `requirements.txt` is now `-e .[all]`; exact pins live in `pyproject.toml`. + +--- + +The MCP surface itself - `get_pos`, `move` (XY only), `get_image`, +`get_move_history`, with `backend` = `mock` | `sdk` and a `confirm=True` gate on +anything that touches real hardware - predates this changelog. See `README.md`. + +[Unreleased]: https://github.com/BioNanomics/microscope-agent/compare/v0.1.0...HEAD +[0.1.0]: https://github.com/BioNanomics/microscope-agent/releases/tag/v0.1.0 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..4e91e61 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 BioNanomics + +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/README.md b/README.md index 6f0cc44..ec86f72 100644 --- a/README.md +++ b/README.md @@ -45,29 +45,63 @@ No NIS-Elements involved anywhere - the camera is reached directly via GenICam/GenTL, and the stage via the Ti2 ActiveX SDK, both independent of whether NIS-Elements software is even running. -## Setup +## Install + +This is a normal installable package (`confocal-mcp`) with a console entry +point. Dependencies are split into groups so a machine only pulls what it needs: + +| Group | Pulls in | For | +|---|---|---| +| *(core)* | `mcp`, `Pillow`, `PyYAML` | the MCP server against the **mock** stage | +| `camera` | `harvesters`, `genicam`, `opencv-python` | real Baumer camera capture | +| `sdk` | `pywin32` | real Ti2 stage control (Windows) | +| `harness` | `anthropic`, `python-dotenv` | the standalone Claude loops in `harness/` | +| `all` | everything above | a full workstation | + +The real hardware backends are imported lazily, so a core-only install runs +fine anywhere (CI, a laptop) - it just can't touch hardware. + +### From a source checkout ``` python -m venv .venv -.venv\Scripts\pip install -r requirements.txt +.venv\Scripts\pip install -e ".[camera,sdk]" # real hardware +.venv\Scripts\pip install -r requirements.txt # == -e ".[all]" +``` + +### As a standalone tool (isolated, no repo checkout) + +``` +uv tool install "git+https://github.com/BioNanomics/microscope-agent[camera,sdk]" +# or: pipx install "git+https://github.com/BioNanomics/microscope-agent[camera,sdk]" ``` -One extra step on a new machine: `acquisition/backends/nis_sdk.py` -imports `NkTi2Ax`, the Nikon Ti2 SDK's generated Python bindings - this -file is machine-generated (via `pywin32`'s `gencache`/`makepy` against -the installed SDK), not pip-installable, and isn't included in this -repo. If it doesn't already exist in `.venv/Lib/site-packages/`, either -let it regenerate against an installed Ti2 SDK, or copy it from another -working `.venv` on the same machine. +### Real stage backend (one extra step) + +`acquisition/backends/nis_sdk.py` imports `NkTi2Ax`, the Nikon Ti2 SDK's +generated Python bindings - machine-generated (via `pywin32`'s +`gencache`/`makepy` against the installed SDK), not pip-installable, and not in +this repo. If it isn't already in `site-packages/`, let it regenerate against an +installed Ti2 SDK, or copy it from another working environment on the same +machine. Not needed for `backend="mock"`. ## Run ``` -python -m mcp_server.server_loop +confocal-mcp # installed console script +python -m mcp_server.server_loop # 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" } } } ``` -Then point an MCP client (Claude Desktop's `claude_desktop_config.json`, -or a project-level `.mcp.json` for Claude Code) at this command. +Data (captures, move/frame history logs) is written under the current working +directory when the server runs from an installed package - launch it from a +stable location. ## Harness loop (`harness/agent.py`) @@ -121,4 +155,14 @@ work found and fixed in `nis_mock.py`. - **Camera**: Baumer VCXU-23C via GenICam/GenTL (`baumer_genicam.py`) - a separate industrial camera, not the confocal N-SPARC detector. Only one application can hold it open at a time - close Baumer Camera - Explorer (or any other GenICam consumer) before running this. \ No newline at end of file + Explorer (or any other GenICam consumer) before running this. + +## Versioning + +Versions follow [SemVer](https://semver.org/); see `CHANGELOG.md`. The current +version is importable as `mcp_server.__version__` (from installed package +metadata). + +## License + +MIT - see `LICENSE`. \ No newline at end of file diff --git a/acquisition/backends/baumer_genicam.py b/acquisition/backends/baumer_genicam.py index da0a88c..763465f 100644 --- a/acquisition/backends/baumer_genicam.py +++ b/acquisition/backends/baumer_genicam.py @@ -36,9 +36,12 @@ from harvesters.core import Harvester from PIL import Image +from acquisition.paths import captures_dir + # Same directory nis_mock.MockNIS.capture() writes to, so frames from -# either backend land in one place. -CAPTURE_DIR = Path(__file__).resolve().parent.parent.parent / "data" / "captures" +# either backend land in one place. Anchored to the working directory - see +# acquisition/paths.py. +CAPTURE_DIR = captures_dir() # GenTL producer folders confirmed present on the microscope PC, # 2026-08-10. Checked in addition to GENICAM_GENTL64_PATH (not instead diff --git a/acquisition/backends/nis_mock.py b/acquisition/backends/nis_mock.py index c31076c..3ee2d89 100644 --- a/acquisition/backends/nis_mock.py +++ b/acquisition/backends/nis_mock.py @@ -23,6 +23,8 @@ from PIL import Image +from acquisition.paths import captures_dir as _captures_dir, data_root as _data_root + # Stage travel limits from the Nikon Ti2-E spec (see docs/microscope-notes.md), # converted from mm to microns to match the units used by the NIS API. X_LIMIT_UM = 57_000.0 @@ -45,10 +47,10 @@ Z_MOVE_DELAY_SEC = 0.05 # Sample frame copied by capture() to simulate a real image capture. Falls -# back to a generated placeholder if this isn't present - data/ is -# gitignored, so a fresh clone of the repo won't have it until fetched. -SAMPLE_FRAME_PATH = Path(__file__).resolve().parent.parent.parent / "data" / "analysis" / "nd2_sample" / "frame_0.png" -CAPTURE_DIR = Path(__file__).resolve().parent.parent.parent / "data" / "captures" +# back to a generated placeholder if this isn't present (it usually isn't - +# it's a dev-only asset under the gitignored data/ tree). +SAMPLE_FRAME_PATH = _data_root() / "data" / "analysis" / "nd2_sample" / "frame_0.png" +CAPTURE_DIR = _captures_dir() class _MockContext: diff --git a/acquisition/orchestration/stage_positions.py b/acquisition/orchestration/stage_positions.py index 0c8f2bc..1a9efd6 100644 --- a/acquisition/orchestration/stage_positions.py +++ b/acquisition/orchestration/stage_positions.py @@ -20,6 +20,8 @@ import yaml # PyYAML - reads a protocol file's `positions:` list +from acquisition.paths import data_root as _data_root + # Stage travel limits (see nis_mock.py / docs/microscope-notes.md's hardware # spec) - imported unconditionally since nis_mock.py has no hardware # dependency of its own, so these constants are always available regardless @@ -45,7 +47,7 @@ file=sys.stderr, ) -POSITIONS_FILE = Path(__file__).resolve().parent.parent.parent / "protocols" / "stage_positions.json" +POSITIONS_FILE = _data_root() / "protocols" / "stage_positions.json" # ── Backend design ──────────────────────────────────────────────────────── # StagePositionManager can drive the stage through either of two backends, diff --git a/acquisition/paths.py b/acquisition/paths.py new file mode 100644 index 0000000..b1001e1 --- /dev/null +++ b/acquisition/paths.py @@ -0,0 +1,32 @@ +# paths.py +# ------------------------------------------------------------ +# Where the server writes runtime data (captured frames, move/frame history +# logs). Anchored to the *working directory*, not to __file__ - once this is +# installed as a package, __file__ lives in site-packages and must never be +# written to. +# +# CONFOCAL_MCP_DATA_DIR if set, the base directory to use +# (unset) the current working directory +# +# Resolved once at import time, from wherever the server process was launched - +# so launch it from a stable location (or set the env var). +# ------------------------------------------------------------ + +import os +from pathlib import Path + + +def data_root() -> Path: + """Base directory for all runtime data. See module docstring.""" + env = os.environ.get("CONFOCAL_MCP_DATA_DIR") + return Path(env).expanduser().resolve() if env else Path.cwd() + + +def captures_dir() -> Path: + """Directory for saved full-resolution captures.""" + return data_root() / "data" / "captures" + + +def logs_dir() -> Path: + """Directory for append-only history logs (move_history, frame_history).""" + return data_root() / "logs" diff --git a/mcp_server/__init__.py b/mcp_server/__init__.py index e69de29..5e4127f 100644 --- a/mcp_server/__init__.py +++ b/mcp_server/__init__.py @@ -0,0 +1,6 @@ +from importlib.metadata import PackageNotFoundError, version + +try: + __version__ = version("confocal-mcp") +except PackageNotFoundError: # running from a source tree that was never installed + __version__ = "0.0.0+unknown" diff --git a/mcp_server/loop_tools.py b/mcp_server/loop_tools.py index c2b3d2a..9a030a1 100644 --- a/mcp_server/loop_tools.py +++ b/mcp_server/loop_tools.py @@ -106,17 +106,21 @@ from PIL import Image as _PILImage -from acquisition.backends.baumer_genicam import BaumerGenICam from acquisition.orchestration.stage_positions import to_plain_float +from acquisition.paths import logs_dir as _logs_dir from mcp.server.mcpserver import Image as MCPImage +# acquisition.backends.baumer_genicam is imported lazily inside _get_camera() +# (it pulls in cv2 + harvesters, the "camera" optional-dependency group) - the +# mock stage path must stay importable on a core-only install, same reason +# _get_backend() imports nis_sdk lazily. + # Long-edge size for the JPEG preview embedded in get_image()'s MCP # response - see that function for why this exists. PREVIEW_MAX_DIMENSION = 1024 -REPO_ROOT = Path(__file__).resolve().parent.parent -MOVE_HISTORY_PATH = REPO_ROOT / "logs" / "move_history.jsonl" -FRAME_HISTORY_PATH = REPO_ROOT / "logs" / "frame_history.jsonl" +MOVE_HISTORY_PATH = _logs_dir() / "move_history.jsonl" +FRAME_HISTORY_PATH = _logs_dir() / "frame_history.jsonl" def _get_backend(backend: str): @@ -163,14 +167,21 @@ def _require_confirm_for_sdk(backend: str, confirm: bool) -> None: # acquisition - see that class's __init__). A camera can only be held # open by one process at a time, so this also means: close any other # GenICam consumer (Baumer Camera Explorer, etc.) before the first call. -_camera: "BaumerGenICam | None" = None +_camera = None # type: ignore[var-annotated] # acquisition.backends.baumer_genicam.BaumerGenICam | None _camera_lock = threading.Lock() -def _get_camera() -> BaumerGenICam: +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 + core-only install (no cv2 / harvesters) - only get_image() actually needs + the camera stack. + """ global _camera with _camera_lock: if _camera is None: + from acquisition.backends.baumer_genicam import BaumerGenICam _camera = BaumerGenICam() return _camera diff --git a/mcp_server/server_loop.py b/mcp_server/server_loop.py index 3c624ce..4e8250d 100644 --- a/mcp_server/server_loop.py +++ b/mcp_server/server_loop.py @@ -4,15 +4,14 @@ # functions (get_image, get_pos, move, get_move_history) - kept # deliberately minimal, 4 tools total, by explicit team direction. # -# Run (from the repo root, with .venv activated): -# python -m mcp_server.server_loop +# Run, either way: +# confocal-mcp (installed console script - see pyproject.toml) +# python -m mcp_server.server_loop (from a source checkout) +# +# Point an MCP client at whichever form you use, e.g.: +# { "mcpServers": { "confocal": { "command": "confocal-mcp" } } } # ------------------------------------------------------------ -import sys -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) - from mcp.server.mcpserver import MCPServer from mcp_server import loop_tools as tools @@ -25,5 +24,10 @@ mcp.add_tool(tools.get_move_history) -if __name__ == "__main__": +def main() -> None: + """Console entry point (``confocal-mcp``): serve the 4 tools over stdio.""" mcp.run(transport="stdio") + + +if __name__ == "__main__": + main() diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..5a7cf24 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,56 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "confocal-mcp" +version = "0.1.0" +description = "MCP server for driving a Nikon Ti2-E stage and a Baumer GenICam camera" +readme = "README.md" +requires-python = ">=3.11" +license = "MIT" +license-files = ["LICENSE"] +authors = [{ name = "Qurratul Ain Quais", email = "qurratul.quais@gmail.com" }] +keywords = ["mcp", "microscopy", "nikon-ti2", "genicam", "automation"] + +# Core: enough to run the MCP server against the mock stage. The real +# hardware backends are imported lazily, so their heavy / platform-specific +# dependencies live in the optional groups below. +dependencies = [ + "mcp==2.0.0", + "Pillow==12.3.0", + "PyYAML==6.0.3", +] + +[project.optional-dependencies] +# Real camera capture (Baumer VCXU-23C via GenICam / harvesters). +camera = [ + "harvesters==1.4.3", + "genicam==1.5.1", + "opencv-python==5.0.0.93", +] +# Real stage control (Nikon Ti2 ActiveX SDK). Windows only. +# NOTE: also needs the machine-generated `NkTi2Ax` bindings, which are not +# pip-installable - see the README ("Real stage backend"). +sdk = [ + "pywin32==312", +] +# The standalone Claude harness loops in harness/ (not the MCP server). +harness = [ + "anthropic==1.0.0", + "python-dotenv==1.2.3", +] +# Everything, for a full workstation install. +all = [ + "confocal-mcp[camera,sdk,harness]", +] + +[project.scripts] +confocal-mcp = "mcp_server.server_loop:main" + +[project.urls] +Homepage = "https://github.com/BioNanomics/microscope-agent" +Repository = "https://github.com/BioNanomics/microscope-agent" + +[tool.hatch.build.targets.wheel] +packages = ["mcp_server", "acquisition", "harness"] diff --git a/requirements.txt b/requirements.txt index 9171858..cb4aa73 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,19 +1,11 @@ -# microscope-agent dependencies -# Minimal MCP surface for real microscope control: get_image, get_pos, -# move, get_move_history - see mcp_server/loop_tools.py. - -mcp==2.0.0 - -# --- Camera capture (Baumer GenICam VCXU-23C) --- -harvesters==1.4.3 -genicam==1.5.1 -opencv-python==5.0.0.93 # Bayer demosaicing only -Pillow==12.3.0 - -# --- Stage position/move (Ti2 ActiveX SDK + saved-position files) --- -pywin32==312 -PyYAML==6.0.3 - -# --- Harness loop (harness/agent.py): calls Claude directly, no MCP client --- -anthropic==1.0.0 -python-dotenv==1.2.3 +# Dev install: the package plus every optional dependency group. +# Dependencies (with exact pins) are declared in pyproject.toml. +# +# python -m venv .venv +# .venv\Scripts\pip install -r requirements.txt +# +# For a smaller install, pick groups directly instead, e.g.: +# pip install -e ".[camera,sdk]" # real hardware, no harness +# pip install -e . # mock only + +-e .[all]