Skip to main content
Glama

MNE-MCP

CI License: MIT Python 3.12+ MCP

English | 简体中文

A Model Context Protocol (MCP) server that gives AI assistants direct, conversational access to MNE-Python for analyzing human neurophysiology data — EEG, MEG, sEEG, ECoG, and fNIRS.

Describe your analysis in plain language — MNE-MCP loads your recording, runs the MNE pipeline (filtering, ICA, epoching, ERP/ERF averaging, time-frequency, source-level work via code), saves the figures, and explains the results.

Works in Claude Code, Codex, PsyClaw and opencode. Pairs with bundled Agent Skills — mne-analyst, mne-mcp-guard, plus a skeptical analysis suite (mne-methodology-critic + per-category skills) for reliable, archived workflows.


Why an MCP for MNE-Python?

MNE analysis is stateful and visual — unlike a one-shot statistics batch job:

  • You load a Raw recording once, then filter → re-reference → fit ICA → epoch → average → time-frequency, each step mutating large in-memory objects. MNE-MCP keeps one persistent session so recordings never get re-loaded between steps.

  • Every decision is driven by looking (PSD, sensor maps, ICA components, ERPs). Every plotting tool saves a PNG the assistant can read and interpret.

  • MNE has a large Python API. MNE-MCP gives you 41 structured tools spanning the common pipeline and advanced analysis (source localization, connectivity, decoding), plus an mne_run_code escape hatch that reaches the entire MNE API in the same live session.

  • Defaults (line frequency, montage, filter band, rejection threshold, ICA settings, epoch window, dirs, timeout) are user-configurable via an interactive mne-mcp configure wizard.


Related MCP server: Smart Terminal MCP

Requirements

  • Python 3.12+ (no package upper-version gate; full-test baseline: 3.12)

  • Git

  • Claude Code, Codex, PsyClaw, opencode, or another MCP client

Cross-platform: unlike a closed engine, MNE-Python is pure Python, so analysis tools work on Windows, macOS, and Linux.


Installation

Looking for the separate native C++ preview? See MNE-CPP MCP installation and capabilities. It now includes explicit native-runtime setup and companion-skill registration; it is not a replacement for the MNE-Python analysis backend described here.

Install with your agent

Send this to a coding agent with terminal access:

Follow https://github.com/Exekiel179/MNE-MCP/blob/v0.4.4/INSTALL_AGENT.md to install MNE-MCP and all companion skills in my existing MNE environment, configure my current client, and verify the result.

The agent checks the environment, installs missing MNE/core libraries when needed, installs the lightweight interface and all 14 skills, and registers the selected client. A client restart is required. See the installation guide for environment checks and verification.

Manual installation

Activate your existing Python 3.12+ MNE environment, then install the lightweight interface:

python -m pip install mne-mcp
mne-mcp setup

The installation creates the mne-mcp command (mne-mcp.exe on Windows). python -m mne_mcp setup remains an equivalent diagnostic invocation.

Release downloads: latest release. For a downloaded source archive, extract it and use python -m pip install . in that directory. Setup defaults to all four clients, including their skills. To configure only PsyClaw, use mne-mcp setup --clients psyclaw; claude, codex and opencode are also supported (comma-separated). Restart clients after setup; PsyClaw supports /reload. MNE and scientific libraries are user-managed; installing this package does not install them. See installation instructions for dependencies and troubleshooting.

Configuration

Repair or reconfigure

To update an existing installation, run python -m pip install --upgrade mne-mcp. Run mne-mcp setup --clients codex in the same MNE environment. Setup registers that exact interpreter and installs the bundled skills for the selected clients. Existing configuration and skill files are backed up before updates.

PsyClaw verification

PsyClaw registration writes ~/.psyclaw/mcp/mne.json; all 14 skills and references go to ~/.psyclaw/skills. Setup checks a real MCP handshake, tool discovery and mne_check_status, including a second check of the saved PsyClaw command.

mne-mcp verify --client psyclaw

This checks the saved command without modifying registration. connected and mne_available are separate: the lightweight server can connect without MNE installed. After /reload, ask PsyClaw to list tools for server mne and call mne_check_status. Project .psyclaw/mcp/*.json entries with the same id override user configuration. The setup check does not claim your already-running chat has reloaded.

Environment variables (optional .env)

MNE_MCP_TIMEOUT=300          # per-operation timeout (s); raise for ICA / TFR / large files
MNE_MCP_RESULTS_DIR=...      # where figures + exported objects are saved
MNE_MCP_DATA_DIR=...         # default directory mne_list_files scans

Configure analysis defaults (interactive wizard)

Set the defaults the structured tools fall back to — mains line frequency (50/60 Hz), default montage, filter band, EEG rejection threshold, ICA method/components, epoch window, directories, and timeout:

mne-mcp configure            # interactive prompts (Enter keeps current value)
mne-mcp configure --show     # print current defaults
mne-mcp configure --reset    # back to built-in defaults
mne-mcp configure --set line_freq=60 default_montage=biosemi64 reject_eeg_uv=120   # non-interactive

Defaults are saved to ~/.mne-mcp/config.json (override path with MNE_MCP_CONFIG). Precedence at runtime: environment variable > config file > built-in. View the active config in-session with the mne_get_config tool. Restart the MCP server for changes to take effect.

Skills

Setup installs all 14 skills into the selected client's skill directory, including their references. Claude also receives the methodology-review subagent. Other clients use the methodology-critic skill. Rerun setup after updating the package.


Usage

Just describe what you want:

加载 sub-01_raw.fif,看一下功率谱
对 raw 做 1–40 Hz 带通、50 Hz 陷波,然后跑 ICA 去眼电
Epoch around the 'target' trigger, -0.2 to 0.8 s, average it, and show the ERP topomaps at 100/200/300 ms

The assistant will:

  1. Check capabilities (mne_check_status)

  2. Load your recording into the persistent session

  3. Run the pipeline step by step, showing figures as PNGs

  4. Interpret each result in plain language

  5. Archive figures + the equivalent MNE code to mne_result/


Output

Every plotting tool saves a PNG to the results dir and returns its path:

> Figure: `C:\...\mne-mcp\results\psd_01.png`

With the mne-analyst skill installed, results and the exact MNE code that produced them are archived to mne_result/ in your working directory (sequence-numbered), so the analysis is fully reproducible.


Available Tools (41)

Status & Session (7)

mne_check_status · mne_session_info · mne_describe · mne_get_info · mne_reset_session · mne_run_code · mne_get_config

Data IO (2)

mne_list_files · mne_load_raw

Preprocessing (7)

mne_filter · mne_resample · mne_crop · mne_set_montage · mne_set_reference · mne_mark_bad_channels · mne_interpolate_bads

Visualization (3)

mne_plot_psd · mne_plot_raw · mne_plot_sensors

ICA (4)

mne_fit_ica · mne_plot_ica_components · mne_plot_ica_sources · mne_apply_ica

Events / Epochs / ERP (7)

mne_find_events · mne_events_from_annotations · mne_make_epochs · mne_plot_epochs_image · mne_average_evoked · mne_plot_evoked · mne_plot_topomap

Time-frequency (2)

mne_compute_tfr (Morlet/multitaper, custom cycles, ITC, trial power, baseline) · mne_tfr_morlet

Advanced analysis (8)

mne_decode (MVPA) · mne_connectivity · mne_compute_connectivity (bands, pairs, estimators) · mne_compute_noise_cov · mne_make_forward · mne_apply_inverse · mne_plot_source_estimate

mne_decoding_group_test provides participant-level max-T or cluster-corrected inference. Decoding reports separate numerical evidence, methods, interpretation, limitations and a results draft requiring scientific review. The code escape hatch is not equivalent to validated structured coverage of every MNE API.

Export (1)

mne_save

Anything still not covered — BIDS, custom statistics, beamformers, autoreject — is reachable through mne_run_code in the same live session. See TOOLS_REFERENCE.md for full parameter details. Advanced dependencies are checked per feature and are not bundled.


Development

# Compile check
python -m compileall src/mne_mcp

# Run tests
pytest

# CLI commands
mne-mcp status            # Check environment
mne-mcp setup --clients codex # Register in Codex + install skills

License

MIT — see LICENSE

Documentation

Available Tools

41 tools
mne_apply_icaMne Apply IcaB

Remove ICA components from an instrument in place. exclude = comma-separated component indices to drop (e.g. '0,3'); if omitted, uses the ICA object's current exclude list.

Inputs: exclude, ica_name, inst_name. Returns: result

mne_apply_inverseMne Apply InverseA

Estimate cortical sources from an Evoked using a forward model and noise covariance. method: 'dSPM' (default), 'MNE', 'sLORETA', 'eLORETA'. Stores the source estimate (stc) and reports the peak activation time. Pair with mne_make_forward + mne_compute_noise_cov.

Inputs: snr, method, cov_name, fwd_name, +2 more. Returns: result

mne_average_evokedMne Average EvokedB

Average Epochs into an Evoked (ERP/ERF) response. condition = an event_id name to average just that condition (else averages all). Stored under evoked_name.

Inputs: condition, epochs_name, evoked_name. Returns: result

mne_check_statusMne Check StatusA

Check MNE MCP capabilities: MNE-Python version, scikit-learn (needed for ICA), numpy/scipy/matplotlib versions, and runtime directories. Call this first.

Inputs: no named parameters. Returns: result

mne_compute_connectivityMne Compute ConnectivityA
Destructive

Bivariate across-trial connectivity with a params JSON object: multiple bands, ordered channel-name pairs, picks, epoch-relative time window, multitaper/fourier/cwt_morlet estimation and smoothing/cycles. Preserves signed, directed and complex values. Stores an MNE Connectivity object; optional first-30-edge heatmap (CWT time mean, complex magnitude only for display). Requires mne-connectivity. Not Granger/PAC.

Inputs: params (required). Returns: result

mne_compute_noise_covMne Compute Noise CovB

Compute a noise covariance matrix from the Epochs baseline (data up to tmax seconds, default 0). Needed before building an inverse operator for source localization.

Inputs: name, tmax, cov_name. Returns: result

mne_compute_tfrMne Compute TfrA
Destructive

Compute Morlet or multitaper Epochs power with explicit frequencies, scalar/per-frequency n_cycles, channel picks, decimation, trial retention, optional ITC and power baseline normalization. Pass a params JSON object. Averaged trial power is total power, not strictly induced power. ITC requires average=true. Returns output names, shape, optional figure paths and reproducible code. Input epochs are unchanged.

Inputs: params (required). Returns: result

mne_connectivityMne ConnectivityA

Spectral connectivity between channels over Epochs in a frequency band. method: 'coh', 'plv', 'wpli', 'pli', 'imcoh', etc. Returns an ordered-edge heatmap without forcing symmetry. Use mne_compute_connectivity for multi-band, channel-pair and estimator parameters. Requires mne-connectivity.

Inputs: fmax, fmin, method, con_name, +1 more. Returns: result

mne_cropMne CropB

Crop a Raw/Epochs/Evoked object to the time window [tmin, tmax] seconds, in place.

Inputs: name, tmax, tmin. Returns: result

mne_decodeMne DecodeA

Time-resolved decoding (MVPA): train a classifier at each time point to discriminate two conditions, with cross-validation. cond_a/cond_b are event_id names (e.g. 'target','standard'). Supports stratified, stratified_group or leave_one_group_out CV. groups must align with ALL retained input epochs before condition filtering. Saves mean scores under name, per-fold scores under name_folds and split diagnostics under name_details. method='sliding' returns (time,), 'generalizing' returns (train_time, test_time). Optional tmin/tmax crop a copy in seconds. C>0, class_weight=null|'balanced' and max_iter configure fold-local logistic regression. Choose them before CV or use nested CV via mne_run_code for tuning. Reference lines are not significance. Requires scikit-learn.

Inputs: C, cv, name, plot, +14 more. Returns: result

mne_decoding_group_testMne Decoding Group TestA

Group-level sign-flip inference on mne_decode mean scores, one per independent subject. Requires score_names, unique subject_ids, independent_subjects=true and explicit null_value. Never pass CV folds or repeated runs as subjects. Supports ROC AUC/balanced accuracy, matching time grids and methods. max_t: two-sided pointwise FWER across the whole curve/matrix; cluster: cluster-mass FWER with time or train-time/test-time lattice adjacency. Requires symmetric subject effects under the null. Not single-subject label shuffling or population prevalence. Stores statistic, corrected p values or cluster p values, mask, H0 and diagnostics.

Inputs: params (required). Returns: result

mne_describeMne DescribeB

Show a detailed summary of one named session object (channels, sfreq, montage, bads, etc.).

Inputs: name (required). Returns: result

mne_events_from_annotationsMne Events From AnnotationsA

Convert a Raw object's annotations into an events array + event_id map (for EDF/BrainVision/EEGLAB data).

Inputs: raw_name, events_name. Returns: result

mne_filterMne FilterA

Band-pass / high-pass / low-pass and/or notch filter a Raw/Epochs/Evoked object in place. l_freq=high-pass edge, h_freq=low-pass edge (either may be null), notch=line-noise frequency (e.g. 50 or 60). picks optional ('eeg', 'meg', or null).

Inputs: name, notch, picks, h_freq, +1 more. Returns: result

mne_find_eventsMne Find EventsA

Find stimulus/trigger events on a stim channel of a Raw object. Stores them under events_name.

Inputs: raw_name, events_name, stim_channel. Returns: result

mne_fit_icaMne Fit IcaA

Fit Independent Component Analysis on a (preferably 1 Hz high-pass filtered) Raw/Epochs object for artifact removal. n_components can be an int, a float (variance fraction), or null. method: 'fastica' (default), 'infomax', 'picard'. Stored under ica_name (default 'ica'). Requires scikit-learn.

Inputs: name, method, ica_name, n_components, +1 more. Returns: result

mne_get_configMne Get ConfigA

Show the configured default analysis parameters (line frequency, default montage, filter band, rejection threshold, ICA method/components, epoch window, dirs, timeout) that the structured tools fall back to when a parameter is omitted. Users change these by running mne-mcp configure in a terminal.

Inputs: no named parameters. Returns: result

mne_get_infoMne Get InfoA

Show the full channel list and measurement info for a named session object.

Inputs: name (required). Returns: result

mne_interpolate_badsMne Interpolate BadsB

Interpolate currently-marked bad channels using spherical splines (requires a montage).

Inputs: name, reset_bads. Returns: result

mne_list_filesMne List FilesA

List neurophysiology data files (.fif, .edf, .bdf, .vhdr, .set, .cnt, .egi/.mff, .ds, .snirf, …) under a directory. Defaults to MNE_MCP_DATA_DIR / current dir. Optionally pass a glob pattern.

Inputs: pattern, directory. Returns: result

mne_load_rawMne Load RawA

Load a raw recording from disk into the session. Auto-detects the format by extension (FIF/EDF/BDF/BrainVision/EEGLAB/CNT/EGI/…). Stores it under name (default raw). Set preload=False for very large files.

Inputs: path (required), name, preload. Returns: result

mne_make_epochsMne Make EpochsA

Segment a Raw object into Epochs around events. tmin/tmax in seconds relative to the event; baseline 'default' = (None, 0); event_id like 'target:1,standard:2' to name/select conditions; reject_eeg = peak-to-peak EEG rejection threshold in volts (e.g. 100e-6). Prefer JSON event_id={label: code} and baseline=[start, end] or null; legacy strings remain supported. reject/flat map channel types to SI thresholds; reject={} disables configured rejection. Do not combine reject with reject_eeg. Stored under epochs_name.

Inputs: flat, tmax, tmin, picks, +10 more. Returns: result

mne_make_forwardMne Make ForwardA

Build a template-head (fsaverage) EEG forward model for the named object's montage. Downloads the fsaverage template once (~ tens of MB). Use for EEG source localization without an individual MRI. Stored under fwd_name.

Inputs: name, fwd_name. Returns: result

mne_mark_bad_channelsMne Mark Bad ChannelsB

Mark channels as bad (comma-separated names, e.g. 'Fp1,T7'). By default appends to existing bads; set replace=true to overwrite.

Inputs: bads, name, replace. Returns: result

mne_plot_epochs_imageMne Plot Epochs ImageA

Plot an ERP image (epochs × time heatmap) for an Epochs object. Returns PNG path(s).

Inputs: name, picks. Returns: result

mne_plot_evokedMne Plot EvokedB

Plot an Evoked response. style: 'joint' (butterfly + topomaps, default), 'topo', or 'butterfly'. Returns PNG path.

Inputs: name, style. Returns: result

mne_plot_ica_componentsMne Plot Ica ComponentsA

Plot ICA component scalp topographies (to identify eye/heart/muscle artifacts). Returns PNG path(s).

Inputs: ica_name. Returns: result

mne_plot_ica_sourcesMne Plot Ica SourcesB

Plot ICA component time courses for an instrument (raw/epochs). Returns a PNG path.

Inputs: ica_name, inst_name. Returns: result

mne_plot_psdMne Plot PsdB

Plot the power spectral density of a Raw/Epochs/Evoked object. Returns a PNG path.

Inputs: fmax, fmin, name, picks. Returns: result

mne_plot_rawMne Plot RawC

Plot raw signal traces (a window of channels over time). Returns a PNG path.

Inputs: name, start, duration, n_channels. Returns: result

mne_plot_sensorsMne Plot SensorsB

Plot the sensor/electrode layout (kind='topomap' 2D or '3d'). Returns a PNG path.

Inputs: kind, name, show_names. Returns: result

mne_plot_source_estimateMne Plot Source EstimateA

Render a source estimate (stc) as a cortical activation map (PNG) at its peak time or a given time. hemi: 'both' / 'lh' / 'rh'. Requires PyVista with off-screen rendering; if 3D rendering is unavailable the estimate is still computed and can be inspected via mne_run_code.

Inputs: hemi, time, stc_name. Returns: result

mne_plot_topomapMne Plot TopomapA

Plot scalp topographies of an Evoked at given times. times='auto', 'peaks', or comma-separated seconds (e.g. '0.1,0.2,0.3'). Returns PNG path.

Inputs: name, times. Returns: result

mne_resampleMne ResampleB

Resample a Raw/Epochs object to a new sampling frequency (Hz), in place.

Inputs: name, sfreq. Returns: result

mne_reset_sessionMne Reset SessionA

Clear all loaded objects and figures from the session, starting fresh. Irreversible.

Inputs: no named parameters. Returns: result

mne_run_codeMne Run CodeA

Execute arbitrary Python/MNE code in the persistent session namespace. Pre-bound names: mne, np, pd, plt, plus every object you have loaded (e.g. raw, epochs, evoked, ica). Like a notebook cell: the value of a final expression is returned, stdout is captured, and any matplotlib figures are saved as PNG (paths returned). Use this for anything the structured tools do not cover.

Inputs: code (required). Returns: result

mne_saveMne SaveB

Save a session object to disk. MNE naming rules: Raw → '_raw.fif', Epochs → '-epo.fif', Evoked → '*-ave.fif'. Other formats follow the object's .save() support.

Inputs: name (required), path (required), overwrite. Returns: result

mne_session_infoMne Session InfoA

List every object currently held in the persistent analysis session (raw recordings, epochs, evoked, ICA, events, arrays) with a one-line summary. Use this to see what is loaded before operating on it.

Inputs: no named parameters. Returns: result

mne_set_montageMne Set MontageA

Apply a standard electrode montage (e.g. 'standard_1020', 'standard_1005', 'biosemi64', 'GSN-HydroCel-128') to set channel positions. Needed before topographic plots and interpolation. If montage is omitted, uses the configured default (set via mne-mcp configure).

Inputs: name, montage. Returns: result

mne_set_referenceMne Set ReferenceB

Set the EEG reference. Use 'average' for average reference, 'REST', or a comma-separated list of channel names (e.g. 'TP9,TP10').

Inputs: name, ref_channels. Returns: result

mne_tfr_morletMne Tfr MorletC

Compute Morlet-wavelet time-frequency power on Epochs and plot it. fmin/fmax = frequency range (Hz), n_freqs = number of frequencies. Stored under tfr_name. Returns PNG path.

Inputs: fmax, fmin, n_freqs, tfr_name, +1 more. Returns: result

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    B3.1/5.0

    Scored across 41 tools

    Disambiguation2/5

    Several tool pairs overlap heavily: mne_compute_connectivity/mne_connectivity, mne_compute_tfr/mne_tfr_morlet, and mne_describe/mne_get_info all have very similar purposes despite detailed caveats. An agent could easily select the wrong one, especially when the names differ only by verb prefix or not at all.

    Naming Consistency3/5

    Most tools follow the readable mne_<verb>_<object> pattern, but there are notable exceptions like mne_connectivity, mne_tfr_morlet, mne_decode, and mne_decoding_group_test that break the convention. The consistent mne_ prefix helps, but the mix of verb-first and noun-first names reduces predictability.

    Tool Count2/5

    With 41 tools, this is well above the 25-tool threshold and feels heavy for an MCP surface, even for a broad neuroimaging domain. Several overlapping connectivity/TFR/plotting tools could be consolidated, and mne_run_code already provides an escape hatch for unusual cases.

    Completeness4/5

    The tool set covers the full MNE analysis lifecycle: loading, preprocessing, epoching, averaging, ICA, TFR, connectivity, source localization, decoding, plotting, and saving. Minor gaps exist, such as dedicated tools for loading saved Epochs/Evoked objects or removing individual session objects, but these are workaroundable via mne_run_code.

    Maintenance

    ActivityMaintained
    ResponsivenessLimited data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      C
      maintenance
      A Model Context Protocol server that provides AI agents with a unified interface for real-time EEG acquisition, replay, processing, visualization, recording, and stimulation from over 66 BrainFlow boards.
      47
      49 PyPI
      3
      BSD 3-Clause
    • A
      license
      Not graded
      quality
      C
      maintenance
      An MCP server that gives AI agents a unified interface to clinical/research EEG workflows: signal processing, source imaging, persistent dataset/EHR storage, and web visualization.
      61 PyPI
      1
      BSD 3-Clause