Skip to main content
Glama

Napari MCP Server

Tests codecov PyPI version Python 3.10+ License: BSD-3-Clause

MCP server for remote control of napari viewers via Model Context Protocol (MCP). Perfect for AI-assisted microscopy analysis with Claude Desktop and other LLM applications.

https://github.com/user-attachments/assets/d261674c-9875-4671-8c60-a7f49d6f1b84

๐Ÿš€ Quick Start (3 Steps)

1. Install the Package

pip install napari-mcp

2. Auto-Configure Your AI Application

# For Claude Desktop
napari-mcp-install install claude-desktop

# Include a napari GUI backend in the uv environment
napari-mcp-install install claude-desktop --backend pyqt6

# For other applications (Claude Code, Cursor, Cline, etc.)
napari-mcp-install install --help  # See all options

3. Restart Your Application & Start Using

Restart your AI app and you're ready! Try asking:

"Can you call session_information() to show my napari session details?"

โ†’ See Full Documentation for detailed guides

Related MCP server: Gemini MCP Server

๐Ÿ”Œ Using as a napari Plugin

napari-mcp can also be used as a napari plugin for direct integration with a running napari session:

  1. Start napari normally: napari

  2. Open the widget: Plugins โ†’ napari-mcp: MCP Server Control

  3. Click "Start Server" to expose your current session to AI assistants

  4. Connect your AI app using the standard installer: napari-mcp-install install <app>

This mode enables AI assistants to control your current napari session rather than starting a new viewer. Perfect for integrating with existing workflows!

โ†’ See Plugin Guide for detailed instructions

๐ŸŽฏ What Can You Do?

Basic Image Analysis

"Load the image from ./data/sample.tif and apply a viridis colormap"
"Create point annotations at coordinates [[100,100], [200,200]]"
"Take a screenshot and save it"

Advanced Workflows

"Execute this code to create a filtered version:
from scipy import ndimage
filtered = ndimage.gaussian_filter(viewer.layers[0].data, sigma=2)
viewer.add_image(filtered, name='filtered')"

"Install scikit-image and segment the cells in this microscopy image"

3D/4D Navigation

"Switch to 3D display mode"
"Navigate to time point 5, Z-slice 10"
"Create a rotating animation of this volume"

Automated Workflows

Want to automate image processing with Python scripts? Use any LLM (OpenAI, Anthropic, etc.) with napari MCP:

โ†’ See Python Integration Examples for batch processing and workflow automation

๐Ÿค– Supported AI Applications

Application

Command

Status

Claude Desktop

napari-mcp-install install claude-desktop

โœ… Full Support

Claude Code

napari-mcp-install install claude-code

โœ… Full Support

Cursor IDE

napari-mcp-install install cursor

โœ… Full Support

Cline (VS Code)

napari-mcp-install install cline-vscode

โœ… Full Support

Cline (Cursor)

napari-mcp-install install cline-cursor

โœ… Full Support

Gemini CLI

napari-mcp-install install gemini

โœ… Full Support

Codex CLI

napari-mcp-install install codex

โœ… Full Support

โ†’ See Integration Guides for application-specific instructions

๐Ÿ›  Available MCP Tools

The server exposes 16 tools for complete napari control:

Core Functions

  • Session Management: init_viewer, close_viewer, session_information

  • Layer Operations: add_layer, list_layers, get_layer, remove_layer, set_layer_properties, reorder_layer, apply_to_layers, save_layer_data

  • Viewer Controls: configure_viewer

  • Utilities: screenshot, execute_code, install_packages, read_output

โš ๏ธ Security Notice

!!! warning "Code Execution Capabilities" This server includes powerful tools that allow arbitrary code execution:

- **`execute_code()`** - Runs Python code in the server environment
- **`install_packages()`** - Installs packages via pip

The bridge server binds to `127.0.0.1` (localhost only) with no authentication.
Any local process can invoke these tools.

**Use only with trusted AI assistants on local networks.**
Never expose to public internet without proper sandboxing.

๐Ÿ“– Documentation

๐Ÿงช Development Setup


# Clone repository
git clone https://github.com/royerlab/napari-mcp.git
cd napari-mcp

# Install with development dependencies
pip install -e ".[dev]"

# Run tests
pytest -m "not realgui"  # Skip GUI tests
pytest --cov=src --cov-report=html  # With coverage

๐Ÿค Contributing

Contributions are welcome! Please:

  1. Fork the repository

  2. Create a feature branch (git checkout -b feature/amazing-feature)

  3. Make your changes with tests

  4. Run pre-commit hooks: pre-commit run --all-files

  5. Commit changes (git commit -m 'Add amazing feature')

  6. Push to branch (git push origin feature/amazing-feature)

  7. Open a Pull Request

๐Ÿ“‹ Architecture

  • state.py โ€” ServerState holding all mutable state (viewer, locks, execution namespace)

  • server.py โ€” create_server(state) factory; tools defined as closures over state

  • qt_helpers.py โ€” Qt application and viewer lifecycle management

  • output.py โ€” Output truncation utility

  • bridge_server.py โ€” Plugin bridge server (overrides 3 tools for Qt thread safety)

  • viewer_protocol.py โ€” ViewerProtocol for typed viewer backends

  • cli/ โ€” napari-mcp-install CLI for configuring AI applications

Key features:

  • Thread-safe: All napari operations are serialized

  • Non-blocking: Qt event loop runs asynchronously

  • Stateful: Maintains viewer state across tool calls

  • Extensible: Easy to add new tools

๐Ÿ“š Resources

๐Ÿ“„ License

BSD-3-Clause License - see LICENSE file for details.

๐Ÿ™ Acknowledgments


Built with โค๏ธ for the microscopy and AI communities

Available Tools

16 tools
add_layerA

Add a layer to the viewer.

Parameters

layer_type : str One of: "image", "labels", "points", "shapes", "vectors", "tracks", "surface". path : str, optional File path (for image/labels). data : list, optional Inline data (coordinates, shape vertices, etc.). data_var : str, optional Name of a variable in the execute_code namespace. name : str, optional Layer name. Defaults to variable name or filename. colormap : str, optional Colormap name (image only). blending : str, optional Blending mode (image only). channel_axis : int, optional Channel axis (image only). size : float, optional Point size in pixels (points only, default 10). shape_type : str, optional Shape type: "rectangle", "ellipse", "line", "path", "polygon" (shapes only, default "rectangle"). edge_color : str, optional Edge color (shapes/vectors only). face_color : str, optional Face color (shapes only). edge_width : float, optional Edge width in pixels (shapes/vectors only).

Inputs: layer_type (required), path, data, data_var, +9 more. Returns: object

apply_to_layersA

Apply property changes to multiple layers matching a filter.

Parameters

filter_type : str, optional Layer type name to match (e.g., "Image", "Labels", "Points"). filter_pattern : str, optional Glob pattern matched against layer names (e.g., "seg_*"). properties : dict, optional Properties to set on matched layers. Supported keys: visible, opacity, colormap, blending, contrast_limits, gamma, new_name (renames by appending a suffix is NOT supported โ€” use set_layer_properties individually).

Inputs: filter_type, filter_pattern, properties. Returns: object

close_viewerA

Close the viewer window and clear all layers.

Inputs: no named parameters. Returns: object

configure_viewerA

Configure viewer display: camera, dimensions, and grid.

All parameters are optional โ€” set any combination in one call.

Parameters

reset_view : bool, default False If True, reset the camera to fit all data. center : list[float], optional Camera center position. zoom : float, optional Camera zoom factor (must be > 0). angles : list[float], optional Camera angles as [azimuth, elevation, roll] in degrees. ndisplay : int, optional Number of displayed dimensions (2 or 3). dims_axis : int, optional Axis index for slider position (use with dims_value). dims_value : int, optional Step value for the given axis. grid : bool, optional Enable or disable grid view.

Inputs: reset_view, center, zoom, angles, +4 more. Returns: object

execute_codeA

Execute arbitrary Python code in the server's interpreter.

Similar to napari's console. The execution namespace persists across calls and includes 'viewer', 'napari', and 'np'.

Parameters

code : str Python code string. The value of the last expression (if any) is returned as 'result_repr'. line_limit : int, default=30 Maximum number of output lines to return. Use -1 for unlimited output. Warning: Using -1 may consume a large number of tokens.

Note

In standalone mode, code execution runs synchronously on the main thread (required for Qt/napari operations) and has no timeout. In bridge mode, a 600-second timeout is enforced.

Inputs: code (required), line_limit. Returns: object

get_layerA

Get detailed info about a layer, optionally including data.

Always returns metadata (shape, dtype, scale, translate, type-specific properties). When include_data=True or slicing is provided, also returns statistics and/or raw data values.

Parameters

name : str Layer name (exact match). include_data : bool, default False If True, include data statistics (min/max/mean/std) and, for small layers, inline data values. slicing : str, optional Numpy-style index string, e.g. "0, :5, :5". Implies include_data=True. max_elements : int, default 1000 Maximum number of data elements to return inline. Larger data is stored and an output_id returned for read_output.

Inputs: name (required), include_data, slicing, max_elements. Returns: object

init_viewerA

Create or return the napari viewer, with viewer detection.

When detect_only=True, reports available viewers (local and external) without creating or modifying anything.

Parameters

title : str, optional Optional window title (only for local viewer). width : int, optional Optional initial canvas width (only for local viewer). height : int, optional Optional initial canvas height (only for local viewer). port : int, optional If provided, attempt to connect to an external napari-mcp bridge on this port (default is taken from NAPARI_MCP_BRIDGE_PORT or 9999). detect_only : bool, default=False If True, only detect available viewers without initialising.

Inputs: title, width, height, port, +1 more. Returns: object

install_packagesA

Install Python packages using pip.

Parameters

packages : list of str List of package specifiers (e.g., "scikit-image", "torch==2.3.1"). upgrade : bool, optional If True, pass --upgrade flag. no_deps : bool, optional If True, pass --no-deps flag. index_url : str, optional Custom index URL. extra_index_url : str, optional Extra index URL. pre : bool, optional Allow pre-releases (--pre flag). line_limit : int, default=30 Maximum number of output lines to return. Use -1 for unlimited output. timeout : int, default=240 Timeout for pip install in seconds.

Inputs: packages (required), upgrade, no_deps, index_url, +4 more. Returns: object

list_layersC

Return a list of layers with key properties.

Inputs: no named parameters. Returns: result

read_outputA

Read stored tool output with optional line range.

Parameters

output_id : str Unique ID of the stored output. start : int, default=0 Starting line number (0-indexed). end : int, default=-1 Ending line number (exclusive). If -1, read to end.

Inputs: output_id (required), start, end. Returns: object

remove_layerC

Remove a layer by name.

Inputs: name (required). Returns: object

reorder_layerA

Reorder a layer by name.

Provide exactly one of:

  • index: absolute target index

  • before: move before this layer name

  • after: move after this layer name

Inputs: name (required), index, before, after. Returns: object

save_layer_dataA

Save a layer's data to a file.

Parameters

name : str Layer name. path : str Output file path. Format is inferred from extension unless format is specified. Supported: .tiff, .png, .npy, .csv (points/tabular only). format : str, optional Explicit format override (e.g., "npy", "tiff").

Inputs: name (required), path (required), format. Returns: object

screenshotA

Take a screenshot, or a timelapse series by sweeping a dims axis.

For a single screenshot, call with no axis/slice_range. For a timelapse, provide both axis and slice_range.

Parameters

canvas_only : bool, default True If True, only capture the canvas area. save_path : str, optional Save single screenshot to this file path (returns metadata). axis : int, optional Dims axis to sweep for timelapse (e.g., temporal axis). slice_range : str, optional Python-like slice string, e.g. "1:5", ":6", "::2". Required when axis is provided. interpolate_to_fit : bool, default False If True, downsample timelapse frames to fit ~1.3 MB total. save_dir : str, optional Save timelapse frames as frame_NNNN.png in this directory.

Inputs: canvas_only, save_path, axis, slice_range, +2 more. Returns: result

session_informationA

Get comprehensive information about the current napari session.

Inputs: no named parameters. Returns: object

set_layer_propertiesA

Set properties on a layer by name.

Parameters

name : str Layer name (exact match). visible, opacity, colormap, blending, contrast_limits, gamma Standard layer rendering properties. new_name : str, optional Rename the layer. active : bool, optional If True, make this the selected/active layer. Setting to False has no effect (use viewer selection directly).

Inputs: name (required), visible, opacity, colormap, +5 more. Returns: object

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelogโ€ฆ

    TDQS

    A3.7/5.0

    Scored across 16 tools

    Disambiguation5/5

    Each tool targets a distinct operation or query. Add/remove/reorder layers are clearly separate; set_layer_properties and apply_to_layers differ in scope; execute_code and read_output serve different purposes. No overlapping tools.

    Naming Consistency5/5

    All tools use consistent snake_case with a verb_noun pattern (e.g., add_layer, list_layers, close_viewer). No mixed conventions or irregular naming.

    Tool Count5/5

    16 tools is well-scoped for the napari viewer domain. Each tool serves a clear purpose without redundancy or unnecessary sprawl.

    Completeness4/5

    Core workflows (viewer lifecycle, layer manipulation, data I/O, code execution) are covered. Minor gaps exist, such as no dedicated file import for non-image layers, but these can be addressed via execute_code.

    Maintenance

    ActivityInactive
    ResponsivenessLimited data

    Related MCP Connectors

    Related MCP Servers