eeg-mcp

v0.2.0
io.github.AImplifier/eeg-mcp Checked 5 days ago Published 1 month ago

Real-time EEG: BrainFlow streaming, wall-clock replay, online DSP, recording, and stimulation.

These tools were reported by the server itself during our smoke test (tools/list), not copied from the README.

list_boards List Boards

List every board BrainFlow can acquire from, with ids and sampling rates. Start here when you do not know what hardware is available. Two entries need no hardware at all: ``SYNTHETIC_BOARD`` generates a signal for development, and ``PLAYBACK_FILE_BOARD`` replays a BrainFlow CSV.

start_stream Start Stream

Open a board and begin buffering EEG in the background. Data flows into a ring buffer from a background thread as soon as this returns, so a subsequent read_window will have samples waiting. The session keeps running until stop_stream is called.

ParameterTypeDescription
session_id *stringName you will pass to every later call for this stream.
boardstringBoard name ('synthetic', 'cyton', 'muse_2', ...) or numeric id. Call list_boards to see the options. Use 'lsl' to attach to an *existing* LSL outlet instead of having BrainFlow open the device itself…
channelsOptional subset of EEG row indices (BrainFlow rows, or LSL channel indices when board='lsl'). Defaults to all.
paramsConnection settings for the chosen board. For BrainFlow boards: {"serial_port": "COM3"} for a Cyton, {"mac_address": "..."} for a Muse, or {"file": "rec.csv", "master_board": "cyton"} for PLAYBACK_FIL…

stop_stream Stop Stream

Stop a stream and release the board, serial ports, and LSL outlets. Always call this when finished. A board left prepared can block the next process from acquiring the device.

ParameterTypeDescription
session_id *stringThe stream to stop.

list_sessions List Sessions

List all active stream and replay sessions with a one-line summary each.

stream_status Stream Status

Health and timing report for a session. The fields that matter for closed-loop work: ``throughput_ratio`` below 1.0 means the producer is not keeping up and samples are being dropped; ``filters.group_delay_sec`` is how far behind real time a filtered feature is; ``last_error`` explains a stopped producer. For an LSL session, ``connection`` reports whether the underlying BLE bridge is currently attached, and how many times it has silently reconnected -- check ``get_events(origin="annotation")`` for the ``source_reconnected`` records, which carry each gap's length.

ParameterTypeDescription
session_id *stringThe session to report on.

read_window Read Window

Read the most recent samples from the buffer. Returns filtered signal when a filter chain is set (see set_filters), otherwise raw. Long windows are decimated to ``max_samples`` per channel so the response stays readable -- for numeric work prefer get_band_power or get_psd, which compute on the full-resolution data.

ParameterTypeDescription
session_id *stringThe session to read from.
channelsChannel names to include. Defaults to all.
filteredbooleanReturn the filtered buffer if a chain is set. False for raw.
include_databooleanWhether to return the sample arrays at all.
max_samplesintegerDecimation cap per channel. Set include_data=False to skip the samples entirely and get only summary statistics.
secondsnumberHow much recent signal to return.

get_channels Get Channels

List the channels a session is producing, with their buffer index.

ParameterTypeDescription
session_id *stringThe session to inspect.

inspect_recording Inspect Recording

Open a recording and describe it without starting playback. Use this before start_replay to see how long the file is, what channels it has, and which annotations will be re-emitted as events during replay.

ParameterTypeDescription
path *stringAbsolute path, or a filename inside the configured recordings dir. EDF/BDF/GDF/SET/FIF and anything else MNE reads; also BrainFlow CSV.
boardRequired only for BrainFlow CSV, which has no header describing its layout (e.g. 'cyton', 'synthetic').
max_eventsintegerCap on how many of the file's events to list.

start_replay Start Replay

Replay a recording against a wall clock, re-emitting its events. This is the safe way to build a real-time pipeline: the session behaves exactly like a live stream -- same buffering, same chunked delivery, same tools -- so code developed here runs unchanged against hardware. The recording's annotations arrive in the event log at their original timings.

ParameterTypeDescription
path *stringAbsolute path, or a filename inside the configured recordings dir.
session_id *stringName you will pass to every later call for this session.
boardRequired only for BrainFlow CSV files.
loopbooleanRestart from the beginning on reaching the end, emitting a 'replay_loop' event each time. Good for long-running rehearsals.
picksMNE channel selection, e.g. 'eeg' or 'mag'. Defaults to EEG.
speednumberPlayback rate. 1.0 is true recording rate; 2.0 is twice as fast; 0.5 is half. Faster-than-real-time is useful for testing a pipeline over a long recording, but stops being a realistic latency test.
start_secnumberOffset into the recording to begin from.
use_stim_channelbooleanAlso extract events from a hardware trigger channel, not just annotations.

replay_control Replay Control

Pause, resume, seek, or change the speed of a replay session.

ParameterTypeDescription
action *stringOne of 'pause', 'resume', 'seek', 'speed', 'status'.
session_id *stringA session created by start_replay.
position_secTarget position, required for action='seek'.
speedNew playback rate, required for action='speed'.

list_recording_events List Recording Events

List all events present in a replay session's source file. Distinct from get_events: this is the *complete* event list from the file, including events that have not been reached yet. get_events returns only what has actually been emitted so far.

ParameterTypeDescription
session_id *stringA session created by start_replay.
max_eventsintegerCap on the number returned.

set_filters Set Filters

Install a stateful online filter chain on a running stream. The chain filters continuously in the background as samples arrive, carrying filter state across chunk boundaries. This matters: filtering each query window independently would inject a transient at every boundary and corrupt any phase-sensitive measure. Filtered output goes to a second buffer, so raw signal remains available via read_window(filtered=False). These are causal filters -- there is no zero-phase option, because that needs future samples. Check ``group_delay_sec`` in the response to know how far behind real time your fil…

ParameterTypeDescription
session_id *stringThe session to filter.
bandpass_highLow-pass corner in Hz. None to skip the bandpass.
bandpass_lowHigh-pass corner in Hz. None to skip the bandpass.
filtersAdvanced -- an explicit stage list that overrides the arguments above, e.g. [{"kind": "highpass", "low": 0.5}, {"kind": "notch", "low": 60, "quality": 30}]. Kinds: bandpass, bandstop, highpass, lowpas…
notch_freqMains frequency to notch out (50 in most of the world, 60 in the Americas). None to skip.
orderintegerButterworth order for the bandpass. 4 is a sensible default.

clear_filters Clear Filters

Remove the filter chain; reads return raw signal again.

ParameterTypeDescription
session_id *stringThe session to clear filters on.

get_band_power Get Band Power

Band power over the most recent window, per channel and averaged. The workhorse feature for neurofeedback and closed-loop triggering. Prefer the ``_rel`` (relative) values for thresholds: they are largely immune to impedance drift, so a threshold set at the start of a session still means the same thing an hour later.

ParameterTypeDescription
session_id *stringThe session to analyse.
bandsBand names to compute. Defaults to delta, theta, alpha, beta, gamma.
channelsChannel names to include. Defaults to all.
filteredbooleanUse the filtered buffer when a chain is set.
relativebooleanAlso return each band as a fraction of total power.
secondsnumberWindow length. 2 s is a reasonable default; shorter windows are noisier, longer ones respond more slowly.

get_psd Get Psd

Power spectral density over the most recent window. Use when band power is too coarse -- to find a peak alpha frequency, confirm a stimulation artifact, or check whether a notch actually removed the mains.

ParameterTypeDescription
session_id *stringThe session to analyse.
channelsChannel names to include. Defaults to all.
filteredbooleanUse the filtered buffer when a chain is set.
fmaxnumberHighest frequency to return.
max_binsintegerCap on returned frequency bins, to keep the response readable.
secondsnumberWindow length. Longer gives finer frequency resolution.

check_signal_quality Check Signal Quality

Per-channel health check: amplitude, flat/railed detection, line noise. Call this before trusting any real-time feature, and definitely before driving stimulation from one. A flat or railed electrode poisons an average reference and a band-power threshold without changing anything you would notice in the feature value itself.

ParameterTypeDescription
session_id *stringThe session to check.
line_freqnumberMains frequency to test for (50 or 60).
secondsnumberWindow length to assess.

log_event Log Event

Record an event against the stream's clock. For anything the server did not generate itself: a task onset, a subject report, an experimenter note. Stimulation commands are logged automatically by send_stim_event, so do not log those by hand.

ParameterTypeDescription
label *stringEvent name, e.g. 'trial_start' or 'eyes_closed'.
session_id *stringThe session to annotate.
durationnumberEvent duration in seconds. 0 for an instantaneous event.
mark_in_streambooleanAlso punch the value into the acquisition stream's own marker channel, so the recording carries the event independently.
payloadAny extra structured detail to keep with the event.
valuenumberNumeric code. Also written to the board's marker channel when mark_in_stream is set; BrainFlow reserves 0, so use a nonzero value.

get_events Get Events

Read the session's event log. Everything lands here on one clock: board markers, annotations re-emitted by a replay, stimulation commands we dispatched, and manual notes. That is what makes a closed-loop run reconstructible afterwards without joining clocks.

ParameterTypeDescription
session_id *stringThe session to read.
labelFilter to one event label.
last_secondsOnly events from the last N seconds. None for all.
limitintegerMaximum events to return, most recent first-truncated.
originFilter by 'marker' (live board), 'annotation' (from a replayed file), 'stim' (dispatched by us), or 'manual' (logged by hand).

get_epoch_around_event Get Epoch Around Event

Extract the signal window around an event that already occurred. Online epoching: use it to inspect the response to the most recent stimulus, or to verify that a stimulation artifact lands where you expect. The event must still be inside the ring buffer -- for a default 60 s buffer, that means within the last minute.

ParameterTypeDescription
session_id *stringThe session to read from.
filteredbooleanUse the filtered buffer when a chain is set.
labelEvent label to find. None takes the most recent event of any kind.
max_samplesintegerDecimation cap per channel.
occurrenceintegerWhich matching event; -1 is the most recent, -2 the one before it, 0 the earliest still in the log.
tmaxnumberWindow end relative to the event, in seconds.
tminnumberWindow start relative to the event, in seconds (negative = before).

clear_events Clear Events

Empty the session's event log without stopping the stream. Useful between blocks of an experiment. The signal buffer is untouched.

ParameterTypeDescription
session_id *stringThe session whose log to clear.

attach_marker_stream Attach Marker Stream

Fold an external LSL marker stream into this session's event log. The reverse of attach_stim_backend(backend="lsl"): that publishes markers for other software to consume; this consumes markers *from* other software -- PsychoPy is the common case, but anything that timestamps its own events over LSL works the same way. Each marker lands with origin='marker' at the sample index nearest its own LSL timestamp in the raw buffer, the same "one event log, one clock" treatment a board's own marker channel gets. Only one marker stream can be attached per session; attaching again replaces the previous…

ParameterTypeDescription
session_id *stringThe session to annotate.
nameResolve by outlet name instead, to pick one of several.
resolve_timeoutnumberSeconds to wait for the outlet before failing.
stream_typestringLSL type to resolve by. 'Markers' matches what PsychoPy and most LSL marker outlets (including this server's own attach_stim_backend(backend="lsl")) declare by convention.

detach_marker_stream Detach Marker Stream

Stop listening for external markers on this session.

ParameterTypeDescription
session_id *stringThe session to detach from.

list_stim_backends List Stim Backends

List stimulation targets, their options, and which ones drive hardware. Software backends ('log', 'lsl', 'brainflow_marker') are always available. Hardware backends ('serial_ttl', 'tms', 'tes', 'template_serial') require the server to have been started with EEG_MCP_ALLOW_HARDWARE_STIM=1, and must be armed before each session of use.

attach_stim_backend Attach Stim Backend

Bind a stimulation target to a session and open its transport. Start with backend='log' to rehearse a protocol with no output at all, then switch once the timing looks right.

ParameterTypeDescription
session_id *stringThe session to attach to.
backendstringOne of the names from list_stim_backends.
make_defaultbooleanUse this backend when send_stim_event omits one.
optionsBackend-specific settings. For serial backends: {"port": "COM3"}. For templated devices (tms, tes, template_serial), the commands from your device manual, e.g. {"port": "COM3", "templates": {"fire": "…

detach_stim_backend Detach Stim Backend

Close and remove a stimulation backend from a session.

ParameterTypeDescription
backend *stringThe attached backend's name.
session_id *stringThe session to detach from.

arm_stim Arm Stim

Permit hardware stimulation for a bounded window. Arming expires deliberately: an agent that stalls mid-protocol should not be able to resume and fire a stimulator minutes later without a fresh, explicit decision. Re-arm as needed, or disarm the moment a block ends.

ParameterTypeDescription
session_id *stringThe session whose backend to arm.
backendWhich attached backend. Defaults to the session default.
ttl_secnumberHow long the arming lasts, in seconds.

disarm_stim Disarm Stim

Revoke permission to stimulate. Takes effect immediately.

ParameterTypeDescription
session_id *stringThe session whose backend to disarm.
backendWhich attached backend. Defaults to the session default.

send_stim_event Send Stim Event

Deliver one stimulation command, and log it against the EEG clock. The event is written to the session log whether the transport succeeds or fails -- a failed stimulation attempt matters just as much to the record. When the acquisition source supports markers, the same event is also punched into the stream itself so the recording is self-describing.

ParameterTypeDescription
label *stringEvent name, e.g. 'tms_pulse' or 'cue_left'.
session_id *stringThe session to stimulate within.
also_mark_sourcebooleanAlso write the code into the acquisition stream's own marker channel.
backendWhich attached backend to use. Defaults to the session default.
duration_msnumberPulse width or stimulation duration.
intensityPhysical dose for hardware backends -- %MSO for TMS, mA for tES. Clamped against the configured ceiling; ignored by software backends.
kindstring'marker' (event code only), 'pulse' (code then clear after duration_ms), 'train', 'ramp', or 'custom'. Backends advertise which kinds they support via list_stim_backends.
paramsExtra fields made available to command templates.
targetCoil, montage or channel identifier, for the record.
unitUnit label for intensity, for the record.
valuenumberNumeric code for marker streams and trigger lines. Nonzero.

send_stim_train Send Stim Train

Deliver a regular train of pulses, blocking until it completes. For rTMS bursts and repeated cues. The call holds until the train finishes, so it is capped at 1000 pulses and 60 seconds total; build longer protocols from several calls so there are decision points in between. Every pulse is logged individually, so the event log reconstructs the exact delivered timing rather than the intended timing.

ParameterTypeDescription
interval_ms *numberInter-pulse interval. For rTMS this is 1000/frequency.
label *stringBase event name; pulses are logged as '<label>_<n>'.
n_pulses *integerHow many pulses to deliver.
session_id *stringThe session to stimulate within.
backendWhich attached backend. Defaults to the session default.
duration_msnumberPulse width.
intensityPhysical dose per pulse, clamped against the ceiling.
valuenumberNumeric code for each pulse.

stim_status Stim Status

Report attached stimulation backends, arming state, and dispatch counts.

ParameterTypeDescription
session_id *stringThe session to report on.

start_monitor Start Monitor

Open a live browser view of a running session and return its URL. Serves a rolling traces view with event markers, band power and per-channel quality, refreshing continuously. This is the tool for "let me watch the recording" -- a static plot cannot answer whether the signal is good *now*. With ``allow_control`` (the default) the page also carries transport buttons: play/pause, restart, skip, speed, stop, mark an event, and save a report. Pass ``allow_control=false`` for a strictly read-only view, e.g. when showing the screen to someone who should not be able to alter the run. The page is b…

ParameterTypeDescription
session_id *stringThe running session to display.
allow_controlbooleanEnable the transport buttons and the control endpoint.
portintegerTCP port on loopback. 0 lets the OS choose a free one.
refresh_msintegerRedraw interval. 500 ms is smooth without loading the server.
window_secnumberSeconds of signal shown at once. Adjustable in the page too.

stop_monitor Stop Monitor

Close a session's live monitor and free its port.

ParameterTypeDescription
session_id *stringThe session whose monitor to stop.

list_monitors List Monitors

List live monitors currently serving, with their URLs.

plot_stream Plot Stream

Render the recent signal as a standalone HTML file and return its path. A frozen snapshot, unlike start_monitor -- use it to keep a record, attach to a note, or share. The file inlines everything and needs no internet.

ParameterTypeDescription
session_id *stringThe session to plot.
channelsChannel names to include. Defaults to all.
filteredbooleanDraw the filtered signal when a chain is set.
secondsnumberHow much recent signal to draw.
show_eventsbooleanOverlay event markers on the traces.

plot_spectrum Plot Spectrum

Render the power spectrum and band composition as a standalone HTML file.

ParameterTypeDescription
session_id *stringThe session to analyse.
channelsChannel names to include. Defaults to all.
filteredbooleanUse the filtered signal when a chain is set.
fmaxnumberHighest frequency to draw.
secondsnumberWindow length. Longer gives finer frequency resolution.

export_report Export Report

Write a full review page: traces, spectrum, quality, and the event log. The one artefact to keep from a session. Everything is inlined, so it opens on any machine, needs no internet, and still renders years from now.

ParameterTypeDescription
session_id *stringThe session to report on.
include_spectrumbooleanAdd the PSD and band-power sections.
notesFree text to record at the top -- indication, montage, observations.
secondsnumberWindow of signal to include in the traces and spectrum.

start_recording Start Recording

Begin writing the live signal to disk, continuously. Call this as soon as the session starts if you intend to keep the data. The ring buffer only holds the last minute or so, so anything not recorded is gone -- a session streamed for an hour without recording leaves nothing but whatever reports you exported. The raw, unfiltered signal is written. Filter settings are stored alongside it so a filtered view is reproducible; the amplifier's actual output is not reconstructible from anything else.

ParameterTypeDescription
session_id *stringThe running session to record.
datasetStudy or collection name that groups recordings together.
nameExplicit filename stem, overriding the BIDS-style name built from subject/session/task/run.
notesFree text kept with the recording.
runRun number within the task, e.g. '01'.
session_labelVisit or session label, e.g. '01' or 'baseline'.
subjectParticipant identifier, e.g. 'sub-04' or a study code. Becomes the subject row in the metadata store. Avoid direct identifiers.
taskWhat the participant is doing, e.g. 'rest', 'motor-imagery'.

stop_recording Stop Recording

Finish the recording, write the ``.fif``, and register it for analysis. The event log becomes annotations inside the file, and -- unless you pass ``register=false`` -- a row is inserted into the metadata store with the subject, task, run and provenance, so neuro-mcp can find and open it.

ParameterTypeDescription
session_id *stringThe session whose recording to finish.
keep_sidecarbooleanKeep the raw crash-recovery files after conversion. Normally removed once the .fif is safely written.
registerbooleanInsert the recording into the metadata database.

recording_status Recording Status

Report whether a session is recording, and how much has been written.

ParameterTypeDescription
session_id *stringThe session to check.

list_recordings List Recordings

List recordings in eeg-mcp's own metadata store, newest first. This store belongs to eeg-mcp alone. Analysis tools read from it -- the schema is compatible with neuro-mcp's, so it can open this database and understand every row -- but nothing else writes to it.

ParameterTypeDescription
limitintegerMaximum number to return.
subjectOnly recordings for this participant identifier.

recover_recording Recover Recording

Finish a recording whose process died before it could be closed. Samples are appended to disk as they arrive and the header is written up front, precisely so an interrupted session is not lost. Point this at the orphaned ``.eegmcp.json`` header to convert what was captured into a ``.fif``. Events are not recoverable -- they lived in memory -- so the resulting file carries signal without annotations.

ParameterTypeDescription
header_path *stringPath to the ``<stem>.eegmcp.json`` left behind.
keep_sidecarbooleanKeep the raw files after conversion.

list_processors List Processors

List real-time processors available to attach, and where they came from. Built-ins are always present. Your own appear here once the **server** environment points at them -- via the ``eeg_mcp.processors`` entry point, ``EEG_MCP_PLUGINS``, or ``EEG_MCP_PLUGIN_DIR``. They cannot be loaded from a tool call, because importing a module executes it and that would make arbitrary code execution reachable from a model.

attach_processor Attach Processor

Attach a processor to a session. A ``streaming`` processor runs inside the acquisition loop on every chunk, so it reacts within one poll interval without an agent round-trip -- that is how closed-loop logic gets fast. The cost is that slow code stalls acquisition; ``processor_status`` reports each one's mean and worst-case time so you can see whether yours is affordable. Non-streaming processors do nothing until you call ``run_processor``.

ParameterTypeDescription
processor *stringName from list_processors.
session_id *stringThe session to attach to.
paramsProcessor-specific settings; see its ``params`` in the listing.

detach_processor Detach Processor

Remove a processor from a session and release its state.

ParameterTypeDescription
processor *stringThe attached processor's name.
session_id *stringThe session to detach from.

processor_status Processor Status

Report attached processors, their health, and their cost. ``mean_ms`` and ``max_ms`` are the numbers to watch for a streaming processor: if ``max_ms`` approaches the poll interval (50 ms by default) it is starving acquisition, which shows up as ``throughput_ratio`` below 1.0 in stream_status. A processor that raises 10 times is disabled automatically rather than being retried forever inside the producer loop.

ParameterTypeDescription
session_id *stringThe session to report on.

get_processor_output Get Processor Output

Read a streaming processor's recent outputs.

ParameterTypeDescription
processor *stringThe attached processor's name.
session_id *stringThe session to read from.
limitintegerHow many recent outputs to return, newest last.

run_processor Run Processor

Run a processor once on the most recent window, on demand. Works for both modes: for a non-streaming processor this is the only way to execute it, and for a streaming one it is a way to get an answer right now rather than waiting for its next scheduled output.

ParameterTypeDescription
processor *stringThe attached processor's name.
session_id *stringThe session to read from.
filteredOverride the processor's declared preference for filtered or raw signal.
secondsnumberWindow length to pass in.

reset_processors Reset Processors

Clear accumulated processor state and outputs, without detaching them. Useful between experimental blocks, and after a replay seek, so a rolling window does not straddle the discontinuity.

ParameterTypeDescription
session_id *stringThe session whose processors to reset.

get_tokens Get Tokens

Read discrete tokens from a tokenizing processor. For feeding EEG into sequence models. Returns both the grouped tokens (one group per window) and a flat sequence, plus the vocabulary size and the channel/band layout each position corresponds to. Works with any attached processor exposing ``token_history`` -- the built-in ``band_tokenizer`` is a starting point, and your own tokenizer plugs in the same way.

ParameterTypeDescription
session_id *stringThe session to read from.
limitintegerHow many recent token groups to return.
processorstringThe tokenizing processor's name.