Skip to main content
Glama
README.md
# SpikeSort Studio — Offline Sorter, rebuilt for humans + AI agents

A modern, open spike sorting app inspired by Plexon Offline Sorter, built on **SpikeInterface**,
and designed from day 1 to be driven by **any AI agent via MCP** — Claude, Codex, Grok, Muse, Cursor, etc.

> Humans curate in the browser. Agents sort via MCP. Same core, same project files, same audit log.

## Why this exists
Offline Sorter is trusted (1,700+ papers) but: Windows-only, closed, pre-Neuropixels, no API, no agent access.
Modern labs use Neuropixels / HD-MEA / tetrodes, Kilosort4 / MountainSort5, and now want an agent to:
*"load this session, run Kilosort4, show me bad units, merge 12+18, export to NWB"*
— without clicking 200 times. This app makes that a first-class workflow, not a hack.

## Two interfaces, one engine

```
┌─────────────────┐     ┌──────────────────┐     ┌─────────────────────┐
│  Web UI         │     │  MCP Server      │     │  Python API / CLI   │
│  (Offline Sorter│────▶│  FastMCP         │────▶│  spikesort.core     │
│   -like)        │     │  stdio + HTTP    │     │  SpikeInterface     │
└─────────────────┘     └──────────────────┘     └─────────────────────┘
 Timeline | Waveforms | PCA/Feature space | ISI | ACG | QC table
```

### Web UI (human curation, like OFS)
- **Timeline View:** continuous trace + raster, time segments (named, colored, toggleable)
- **Waveform View:** overlaid waveforms, mean ± SD template, overlapping-spike highlight
- **Feature Space:** 2D/3D PCA / peak / valley / energy / FWHM — lasso, box, template sort
- **Cluster Views:** Clusters vs Time, Templates vs Time, Sort Quality vs Time (drift tracking)
- **QC Panel:** SNR, ISI violations, presence ratio, amplitude cutoff, isolation distance, L-ratio,
  firing rate, amplitude — sortable table, auto-curation suggestions
- **Curation:** merge / split / label (good / mua / noise / artifact), invalidate waveforms, undo history
- **Batch & Scan:** parameter scan for a sorter, batch mode across sessions/channels

### MCP Server (agent curation)
Any MCP client can connect — no vendor lock-in:

| Client | Transport | Config |
|---|---|---|
| Claude Desktop / Claude Code | stdio | `configs/claude_desktop_config.json` |
| Muse | streamable-http | `http://127.0.0.1:8001/mcp` |
| Codex / Cursor / Windsurf | stdio or http | `configs/mcp.json` |
| Grok / custom agent | stdio or http | same |

**14 MCP tools** (see `docs/MCP_TOOLS.md`):
`list_recordings`, `load_recording`, `inspect_recording`, `preprocess_recording`,
`list_sorters`, `run_sorting`, `get_sorting_summary`, `compute_quality_metrics`,
`list_units`, `get_unit_detail`, `merge_units`, `split_unit`, `label_units`,
`export_sorting`

Plus 2 prompts: `sort_session_end_to_end`, `curate_with_qc_rules`
And resources: `spikesort://recordings`, `spikesort://sortings/{id}/summary`

### Core engine (SpikeInterface)
- **Formats:** NWB, SpikeGLX, OpenEphys, Blackrock, Intan, Plexon PLX/PL2, Neuroscope,
  EDF, BrainVision, MEArec synthetic, raw binary — via SpikeInterface extractors
- **Preprocessing:** bandpass 300–6000 Hz, common median/average reference, whitening,
  bad-channel detection/removal, phase shift, artifact removal
- **Sorters:** Kilosort4 (GPU, Neuropixels default), Kilosort2/3, MountainSort5 (CPU, no GPU),
  SpykingCircus2, Tridesclous2, HerdingSpikes, IronClust — whatever `installed_sorters()` finds
- **Post:** SortingAnalyzer — waveforms, templates, PCA, spike amplitudes, unit locations
- **Export:** NWB, Phy (for manual curation), CSV/NPY spike times, MATLAB .mat, NeuroExplorer .nex (planned)

## Quick start

```bash
cd spike-sorter-app
pip install -e ".[all]"        # or: pip install spikeinterface[mcp,web]
# 1) Demo with synthetic data (no real recording needed)
python examples/make_synthetic_demo.py
python -m spikesort.cli demo

# 2) Web UI
uvicorn spikesort.api:app --reload --port 8000   # http://localhost:8000

# 3) MCP — stdio (Claude Desktop / Codex)
python -m spikesort.mcp_server
# MCP — HTTP (Muse / remote agents)
python -m spikesort.mcp_server --transport streamable-http --port 8001
# -> http://127.0.0.1:8001/mcp
```

Try it with your agent — paste this prompt:
> Use SpikeSort: load the demo recording, preprocess with bandpass + CMR,
> run mountainsort5, compute quality metrics, list units with ISI violations > 0.02,
> label those as noise, merge any pair the auto-merge suggests, and export to Phy.

## Project layout
```
src/spikesort/core.py       # SpikeInterface wrapper, project/session store (no UI deps)
src/spikesort/mcp_server.py # FastMCP server — all agent tools
src/spikesort/api.py        # FastAPI backend for the web UI
src/spikesort/cli.py        # CLI: demo, sort, serve
web/index.html              # Single-file OFS-like UI (waveform canvas, PCA, QC table)
configs/                    # Ready-to-paste MCP configs per client
examples/                   # Synthetic demo + agent prompt examples
docs/DESIGN.md              # Full architecture & roadmap
docs/MCP_TOOLS.md           # Tool schemas, safety model
```

## Safety model for agents
- Agents work on a **copy / branch** of a sorting by default; merges/labels are logged, undoable.
- Destructive ops (`label_units`, `merge_units`) return a preview first if `dry_run=true`.
- Every agent action writes to `project/audit_log.jsonl` — who, when, tool, args, before/after.
- File access is scoped to the project folder you open — no arbitrary filesystem access.

## Roadmap
- [x] v0.1 Scaffold: core + MCP (14 tools) + FastAPI + web UI skeleton + synthetic demo
- [ ] v0.2 Real-file E2E: SpikeGLX + NWB load, Kilosort4 + MountainSort5 verified, Phy export round-trip
- [ ] v0.3 Curation parity with OFS: template sort, scan mode, time-segment sorting, .nex export
- [ ] v0.4 Drift / motion correction view, sorter comparison (agreement matrix), auto-curation models
- [ ] v0.5 Desktop packaging (Tauri/Electron wrapper) + MCP Registry listing (like Data Figure Studio)
- [ ] v1.0 Multi-session batch, cloud GPU sorting job queue

## Name — open decision
Working name: **SpikeSort Studio**. Alternatives: SortLab AI, SpikeStudio, OpenSorter.
Pick one before GitHub / domain / MCP Registry — same lesson as AgentToolsAtlas / GoFigure.

License: MIT (proposed)