Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -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.
70 changes: 57 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`)

Expand Down Expand Up @@ -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.
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`.
7 changes: 5 additions & 2 deletions acquisition/backends/baumer_genicam.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 6 additions & 4 deletions acquisition/backends/nis_mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down
4 changes: 3 additions & 1 deletion acquisition/orchestration/stage_positions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand Down
32 changes: 32 additions & 0 deletions acquisition/paths.py
Original file line number Diff line number Diff line change
@@ -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"
6 changes: 6 additions & 0 deletions mcp_server/__init__.py
Original file line number Diff line number Diff line change
@@ -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"
23 changes: 17 additions & 6 deletions mcp_server/loop_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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

Expand Down
20 changes: 12 additions & 8 deletions mcp_server/server_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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()
56 changes: 56 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -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"]
Loading