reaper-mcp
CLAUDE.md42 starsChanged 5 days agoMITView on GitHub
An MCP (Model Context Protocol) server that enables AI agents (Claude Code, etc.) to control a live REAPER DAW session in real-time -- including track management, FX control, parameter adjustment, metering, frequency analysis, MIDI editing, and media item manipulation. REAPER's Lua scripting environment is sandboxed -- no sockets, no HTTP, no stdin/stdout. The only reliable cross-process communication is file-based JSON IPC: Bridge directory: {REAPER_RESOURCE_PATH}/Scripts/mcp_bridge_data/ (override with REAPER_RESOURCE_PATH env var) Round-trip latency: ~50-150ms -- fast enough for iterative AI mixing decisions.
- Installs packages
In this repository12 other files it gives its agents.
- knowledge/CLAUDE.mdCLAUDE.md
- reaper/CLAUDE.mdCLAUDE.md
- changelog-highlightSkill
- critiqueSkill
- editingSkill
- learn-pluginSkill
- make-pluginSkill
- masteringSkill
- mixerSkill
- mix-memorySkill
- new-extensionSkill
- teachSkill
The file
We split this CLAUDE.md into the rules it gives an agent
11 rules. About 0 are common, 2 are distinctive, and 9 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
9
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 219
Every tool that takes a trackIndex (except media item, MIDI, item/take, track-template, measure_track_alignment and verify_edit tools) …
- Very specific: line 366
Every point tool takes an optional automationItemIndex to work on one automation item's (pool's) points instead of the underlying envelope.
- Very specific: line 639
Undo: every edit by these tools is one undo point labelled MCP: …, so undo_project reverts exactly that edit.
- Very specific: line 646
Validate, then write: every input (track/item/take/FX index, file, color, shape, path) is checked before the first write.
- Very specific: line 672
Creating envelopes: Use create_track_envelope before adding points.
- Very specific: line 690
Support pagination: Add offset and limit parameters so the client can request data in chunks.
- Distinctive: line 694
When adding new tools that could return large datasets, always implement both a summary path and a paginated path.
- Very specific: line 748
Important: Always use z.coerce.number() instead of z.number() for numeric parameters.
- Very specific: line 817
Audio loading: always soundfile (analysis.load_audio).
- Distinctive: line 821
Auto-restart: If the sidecar crashes, one restart is attempted automatically.
- Very specific: line 822
Script refresh: every sidecar spawn first copies the build's server.py and modules over the installed ones, so an update (which never …
≈ “Common” is an estimate: at least 1 in 5 of the 29,248 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
REAPER MCP Server
An MCP (Model Context Protocol) server that enables AI agents (Claude Code, etc.) to control a live REAPER DAW session in real-time -- including track management, FX control, parameter adjustment, metering, frequency analysis, MIDI editing, and media item manipulation.
Quick Start
pnpm install # Install dependencies
pnpm nx run-many --target=build # Build everything
pnpm nx run-many --target=lint # Lint everything
pnpm nx run-many --target=test # Test everythingArchitecture Overview
Claude Code <--stdio--> MCP Server (TypeScript) <--JSON files--> Lua Bridge (REAPER) <--ReaScript API--> REAPER DAW
| |
newline-delimited JSON-RPC gmem[] shared memory
| |
Python Sidecar (long-lived) JSFX FFT Analyzer
Audiobox Aesthetics modelWhy File-Based IPC?
REAPER's Lua scripting environment is sandboxed -- no sockets, no HTTP, no stdin/stdout. The only reliable cross-process communication is file-based JSON IPC:
- MCP Server writes
command_{uuid}.jsonto bridge directory - Lua bridge polls directory every ~30ms via
reaper.defer(), reads command, executes ReaScript API - Lua bridge writes
response_{uuid}.jsonwith results - MCP Server polls for response, returns to client
Bridge directory: {REAPER_RESOURCE_PATH}/Scripts/mcp_bridge_data/ (override with REAPER_RESOURCE_PATH env var)
Round-trip latency: ~50-150ms -- fast enough for iterative AI mixing decisions.
Project Structure
This is an Nx monorepo with pnpm workspaces.
reaper-mcp/
apps/reaper-mcp-server/ # Main MCP server application (TypeScript, esbuild)
src/
main.ts # CLI entry point: serve | setup | setup-sidecar | install-skills | init | doctor | status | flags
terminal-ui.ts # The look of every CLI message (init, setup, telemetry, doctor, status, install-skills): `createUi()` gives the palette helpers (bold, dim, cmd, link, ok/warn/fail, mark, heading, gradient) and `banner(subtitle, version)` (gradient REAPER MCP logo + waveform on a terminal ≥ 80 columns, one plain line elsewhere). Colour is only rendering: strip the codes and you get the plain text, which is what a pipe, NO_COLOR and the CI snapshots see. New CLI output reuses it, never hand-written `\x1b[`
instance.ts / instance-cli.ts # `reaper-mcp instance create|start|stop|connect|list|remove`: a second REAPER with its own resource folder (`~/.reaper-mcp/instances/<name>/REAPER`, reaper.ini copied with ONE web surface on its own port and `loadlastproj=0`, the bridge installed by running `setup` with `REAPER_RESOURCE_PATH`/`REAPER_WEB_PORT` set), so an agent edits, renders and measures there while the person works in theirs; nothing in the bridge changes (its folder follows the resource path). Plugin caches, `UserPlugins`, `FXChains`… are symlinked; folders `setup` writes into (`Effects/`, `Effects/reaper-mcp-generated/`, `presets/`) are real folders of per-entry links minus what setup owns (`SPLIT_DIRS`), so the instance's setup never writes through a link into the person's folder (a test and a live checksum check it). `reapack.ini` is copied in (ReaPack loads from the shared UserPlugins and otherwise opens its first-run "Manage repositories" window on every new instance; never `ReaPack/registry.db`, which lists what the main folder installed). macOS: a private REAPER.app copy per instance (own bundle id, `LSUIElement` unless `--visible`, ad-hoc signed; refreshed when REAPER's binary changes), started with `open -n -g -a`, stopped with a normal osascript quit. `create` also writes `Scripts/mcp_instance.conf` (`name=<n>`, next to mcp_bridge.lua): the bridge publishes it as `instance` in the status feed (the page header names it and the tab title carries it, `pageTitle()`; `?demo&instance=background` draws it), and it is the only REAPER that obeys the page request `quit-<token>` (File: Quit, action 40004, which asks about unsaved changes itself). `stop` uses it off macOS: the CLI reads the control token from the instance's status feed over its web port and sends the request, so the REAPER a person works in can never be quit this way; `doctor` (an Instances row, only when instances exist) and `status` list each instance and whether its bridge answers (`instanceLines()`). `connect` registers a `reaper-<name>` server carrying the instance's env (harnesses.ts `ServerSpec`). Guide: docs/guides/second-reaper.md
harnesses.ts # init: the supported harnesses (Claude Code, Codex CLI, Gemini CLI, Cursor): detect what is installed, register the server through each one's own `mcp add` (Cursor: mcp.json), read/stale-check what is registered, `--harness`/`--all` parsing; skills go to ~/.claude (Claude Code) or the shared ~/.agents (the others)
claude-assets.ts # install-skills: copies the skills, agents and knowledge shipped in the npm package into ~/.claude (hash manifest, never overwrites edits)
server.ts # McpServer creation, tool registration
tool-annotations.ts # title + readOnlyHint/destructiveHint/openWorldHint for every core tool, set by name after registration (the directory requires them); a tool whose name breaks the pattern is added to the sets there
flags.ts # Feature flags on the server: the install id as targeting key, overrides from ~/.config/reaper-mcp/flags.json + REAPER_MCP_FLAGS, `createServerFlags()`, `evaluateServerFlag()`, and the `reaper-mcp flags list|set|reset` command (docs/FEATURE-FLAGS.md)
bridge.ts # File-based IPC: sendCommand(), isBridgeRunning(), etc.
bridge-repair.ts # serve: bring REAPER's files (bridge, JSFX, page, autostart block) up to this release once per release (npm installs)
notices.ts # One-time notices for the user, appended to the first tool result (updated bridge, newer release)
update-check.ts # serve (npm installs): ask npm at most once a day for a newer release, notice at most once a day
sidecar-offer.ts # End of setup: offer the Python sidecar (audio tools fail without it)
setup-health.ts # Startup span: REAPER running?, heartbeat age range, autostart, sidecar installed (usage telemetry)
install-info.ts # Startup span: install method (npx, npm_global, clone, other), npx pin (from _npx/<hash>/package.json), newer release known, update via bridge page or CLI (last-update.json, left by update.ts) (usage telemetry)
sidecar.ts # Python subprocess lifecycle + JSON-RPC client (getSidecarClient())
setup-sidecar.ts # setup-sidecar CLI command: component picker (TTY) or flags, Python check, venv, deps, weights, add-ons
tools/
project.ts # get_project_info; undo/redo, save, render settings + render, project settings (logic in reaper/mcp_project_lib.lua)
tracks.ts # list_tracks, get_track_properties, set_track_property
fx.ts # add_fx, remove_fx, get/set_fx_parameter, set_fx_enabled, set_fx_offline
meters.ts # read_track_meters, read_track_spectrum
transport.ts # play, stop, record, get_transport_state, set_cursor_position
discovery.ts # list_available_fx, search_fx
presets.ts # get_fx_preset_list, set_fx_preset
snapshots.ts # snapshot_save, snapshot_restore, snapshot_list, snapshot_delete, snapshot_edit
routing.ts # get_track_routing
structure.ts # add/delete/move track, folders, name/color, groups; send/hardware-output setters
analysis.ts # read_track_lufs, read_track_correlation, read_track_crest, measure_tracks
midi.ts # 14 MIDI editing tools (notes, CC, items, analysis, batch edit)
media.ts # 11 media item editing tools (properties, batch, split, move, trim, stretch)
selection.ts # get/set_selected_tracks, set_selected_items, get/set_time_selection
actions.ts # search_actions, get_action, run_action (logic in reaper/mcp_actions_lib.lua)
items.ts # insert_audio_file, takes, take FX, item color/fades (logic in reaper/mcp_items_lib.lua)
arrange.ts # copy_media_items, insert/remove_time, copy_section, process_items (logic in reaper/mcp_arrange_lib.lua)
fx-housekeeping.ts # move/copy/rename_fx, .RfxChain save/load, track templates (logic in reaper/mcp_items_lib.lua)
markers.ts # list_markers, list_regions, add_marker, add_region, delete_marker, delete_region, edit_marker, edit_region
tempo.ts # get_tempo_map, add/edit/delete_tempo_marker, set_project_tempo
envelopes.ts # envelope points (read/insert/edit/delete, dB on volume envelopes) + automation items (logic in reaper/mcp_envelopes_lib.lua)
aesthetics.ts # analyze_track_aesthetics (requires Python sidecar)
offline.ts # analyze_track_offline, analyze_audio_file, measure_track_alignment, verify_edit (sidecar, no model)
transients.ts # detect_transients, create_transient_automation (sidecar onsets → envelope pulses, e.g. lighting)
composition.ts # quantize_midi, transform_midi, import_midi_file (SMF parsed in smf.ts), detect_key (key.ts), detect_chords (chords.ts; logic in reaper/mcp_midi_lib.lua)
mixcheck.ts # analyze_loudness_curve, analyze_stereo_bands, measure_masking, separate_stems (sidecar)
plan.ts # run_plan (multi-op plan executor; logic in reaper/mcp_plan_lib.lua)
recording.ts # record setup (inputs, monitoring, punch), fixed lanes, comp_lanes (logic in reaper/mcp_recording_lib.lua)
mixing.ts # automation mode, FX modulation + pins, monitoring FX, freeze, render in place, stretch markers, quantize_audio (logic in reaper/mcp_mixing_lib.lua)
jsfx.ts # write_jsfx: lint + inline the toolkit + write a generated plugin (logic in src/jsfx/)
plugin-build.ts # report_plugin_build: how a /make-plugin run ended (closed values, usage telemetry)
align.ts # align_audio_to_guide (onset pairing in src/align.ts; markers written by align_stretch in reaper/mcp_mixing_lib.lua)
sidecar/ # Python sidecar for semantic audio analysis (opt-in)
server.py # JSON-RPC server (Meta Audiobox Aesthetics, CC-BY 4.0)
verify.py # verify_edit: delay/gain/polarity-compensated null + discontinuity (click) check, ok/warn/fail; with timeScale != 1 also pitch drift, tone (line 1.5 dB, provisional) and transient checks (warn only; a pitch move matching `1200*log2(timeScale)` within 35 cents is a plain speed change, reported as info together with the tone shift it causes; below 0.9× also a dropout check, the deepest dip of the loudness under the reference's, warn from 12 dB, provisional)
mixcheck.py # Loudness curve, stereo correlation per band, masking between tracks
separation.py # Stem separation with Demucs (opt-in: setup-sidecar --with-separation)
requirements.txt # Pinned Python deps
requirements-separation.txt # Demucs, installed only by --with-separation
chords.py # Chord recognition with lv-chordia (opt-in: setup-sidecar --with-chords)
requirements-chords.txt # lv-chordia, installed only by --with-chords
tests/test_server.py # pytest unit tests for the sidecar
plugins/reaper-mcp/ # The Claude plugin (directory listing): plugin.json, .mcp.json (pinned npx launcher), README with the privacy policy; `REAPER_MCP_DISTRIBUTION=plugin` makes telemetry opt-in and lets `serve` install the bridge on first start. `scripts/pin-plugin.mjs` pins it to a published release; see docs/PLUGIN-DIRECTORY.md (a local server can't be listed as a connector or .mcpb)
libs/extension-api/ # The API extensions are written against (types, manifest check, VST3 state helpers); see docs/EXTENSIONS.md
libs/feature-flags/ # Feature flags (LoreKit parity): hand-authored registry (src/registry.ts, empty until a flag gates something), zod schema, FNV-1a bucketing for percentage rollouts and A/B tests, pure resolver, OpenFeature provider + OTel hook (src/server.ts, server only); `src/index.ts` is browser-safe and what the page imports. Generated: src/generated/ + generated/, by scripts/gen-feature-flags.mjs (--check fails on drift). See docs/FEATURE-FLAGS.md
extensions/vital/ # Opt-in extension: read/edit Vital patches (settings, mod matrix, LFOs, wavetables); built to dist/index.mjs
extensions/helix/ # Opt-in extension: build/edit/validate Helix .hlx presets (donor + real blocks, snapshots), checked import into Helix Native; knowledge/ holds the Helix docs
libs/protocol/ # Shared TypeScript types (compiled with tsc)
src/
index.ts # Re-exports commands + responses
commands.ts # BridgeCommand, CommandType, per-command param interfaces
responses.ts # BridgeResponse, ProjectInfo, TrackInfo, FxInfo, etc.
apps/bridge-ui/ # Bridge status page (React → one self-contained mcp_bridge.html)
src/main.tsx # Entry: renders app/App.tsx, registers the service worker; mcp_bridge.html is translate="no" (a translator breaks React's DOM swaps), lifted here for the docs and changelog pages
src/app/ # The page shell: App, Header, Notices, Offline, BridgeBoundary (keeps a render error in the bridge view or offline screen from blanking the page; reports it as page_error) + the hooks that poll the bridge
src/components/ # Shared UI with no bridge knowledge: Combobox (+ .Grouped), Toggle, Notice, Mark, ResizeHandle, Markdown, Icon.*
src/features/<feature>/ # One folder per area: log, stats, timeline, settings, developer, measurements, edit-views, plugins, snapshots
# Each folder's index.ts exports a composite, namespaced component (Log.Rows, Log.Details,
# Measurement.Loudness, EditView.Section, Snapshots.SaveForm, Plugins.Details, Settings.LoreKit,
# Stats.Sparkline) plus its public functions; code outside a folder imports only its index
src/lib/ # Pure logic + small hooks (flags.ts / flag-store.ts: feature flags, with `app/useFlag.ts`; the Developer drawer (`?developer=true`, developer mode) lists them and shares forced variants with the server through the bridge): status (feed parsing), commands, log, timeline, sessions, search, format, url-state, analytics
src/demo/ # ?demo's fake bridge and the fixed examples the stories draw (examples.ts, feed.ts);
# demo-calls.ts: one demo call per logged command (DEMO_CALLS, typed by LoggedCommand)
src/styles.css # Root stylesheet: CSS variables (tokens), base element styles and global utility classes only
src/styles/ # CSS modules shared across features: drawer, list (segmented tabs, chips, rows), chart (measure card, readouts, legends, bars)
# Every component's own styles: <Name>.module.css beside it (styles.x, joined with cx() from lib/cx.ts)
src/test/stories.test.tsx # Runs every story's play function as a vitest test (jsdom)
.storybook/ # Storybook (React + Vite): pnpm storybook, nx build-storybook bridge-ui
mcp_bridge.html # The page's HTML template (Vite entry)
vite.config.ts # Vite + React Compiler, inlined into one dist/apps/bridge-ui/mcp_bridge.html (vite-plugin-singlefile)
build-config.mjs # Build-time constants (version, LoreKit, Dash0) + the React Compiler's Babel options, shared by Vite, vitest and Storybook
vite-reaper-dev.mjs # pnpm dev:bridge's REAPER side: /_/ proxied over one socket, reaper/ installed on save
.claude/skills/ # Mix skills (one dir per skill, each with SKILL.md), symlinked into ~/.claude/skills by scripts/sync-symlinks.sh (clone) or copied by `reaper-mcp install-skills` (npm)
mixer/SKILL.md # /mixer — executes mixes (live session, reads/writes memory)
critique/SKILL.md # /critique — read-only analysis ("roast my mix")
mastering/SKILL.md # /mastering — mix-bus mastering to a LUFS target
editing/SKILL.md # /editing — MIDI, arrangement, comping, A/B variants in fixed lanes
teach/SKILL.md # /teach — beginner mode (slash-only): explains each change, links the REAPER concept, how to do it by hand, bridge page link (knowledge/reference/teaching.md)
learn-plugin/SKILL.md # /learn-plugin — research + live-probe a plugin via plugin-researcher, ask only the gaps (LoreKit)
make-plugin/SKILL.md # /make-plugin — make the user a plugin (JSFX + shared UI toolkit): spec, write_jsfx, load, measure, iterate; examples/ holds four
new-extension/SKILL.md # /new-extension — build an extension for a plugin's internals: probe its state, write tools + tests, prove them live
mix-memory/SKILL.md # /mix-memory — recall / consolidate / promote memory
changelog-highlight/ # /changelog-highlight — maintainer only (.repo-only: not linked or packaged): a What's new highlight with media
.claude/agents/ # Subagents, symlinked into ~/.claude/agents by scripts/sync-symlinks.sh (clone) or copied by `reaper-mcp install-skills` (npm)
plugin-researcher.md # Web research + scratch-track probing → user::plugins:: record; used by /learn-plugin, /mixer, /mastering
knowledge/ # Knowledge base + memory; symlinked into ~/.claude/knowledge (clone) or copied by `install-skills` (npm)
genres/ # Genre mixing conventions (targets, frequency balance, dynamics)
workflows/ # Step-by-step mixing workflows (gain-staging, vocal-chain, etc.)
reference/ # Reference material (frequencies, metering, compression, perceived loudness, memory-protocol)
# reaper-concepts.md: the REAPER concepts /teach links (checked by teach-knowledge.test.ts); teaching.md: explain mode's rhythm
# Balance/EQ decisions use perceived values only (LU, kDb), never raw dBFS: reference/perceived-loudness.md
# Plugin knowledge + process lessons live in LoreKit, scope project::reaper-mcp
scripts/
reapack-index.mjs # Generate the ReaPack index.xml (bridge scripts, JSFX, status page) from reaper/; the release job attaches it to the GitHub release (releases/latest/download/index.xml). ReaPack puts JSFX in Effects/reaper-mcp/Meters/ and scripts in Scripts/reaper-mcp/MCP Bridge/, so the bridge resolves JSFX in both folders (Meters/ first) and the autostart block prefers that script path over Scripts/mcp_bridge.lua; `reaper-mcp setup` from an npm install leaves the files to ReaPack once it installed the bridge (from a clone it still copies them and warns that ReaPack's copy wins; see DEVELOPMENT.md)
prepare-npm-package.mjs # Assemble the npm package in dist/apps/reaper-mcp-server (the root README with its install section swapped for `apps/reaper-mcp-server/NPM_INSTALL.md` and absolute image/link URLs via `src/npm-readme.mjs`, LICENSE, status page, version); run by the release job
sync-symlinks.sh # Symlink .claude/skills/*/ (skill dirs), .claude/agents/*.md + knowledge/ into ~/.claude, and skills + agents also into ~/.agents for Codex/Gemini/Cursor (`--no-agents` skips that; clone install; an npm install copies them with `install-skills`)
gen-feature-flags.mjs # Generate libs/feature-flags' typed keys + manifest from its registry (`--check` fails on drift; `pnpm nx run feature-flags:generate`)
ext-call.mjs # Call any tool on a fresh `reaper-mcp serve` (so a new extension can be tried without restarting Claude Code): --list [prefix] | <tool> [json]
plugin-list.mjs # Rebuild docs/PLUGINS.md's built-in plugin table from LoreKit (logic: apps/bridge-ui/src/features/plugins/plugin-list.mjs)
reaper/ # Files installed INTO REAPER (copied by setup command)
mcp_tracks_lib.lua # Pure track-structure + routing logic (wasmoon-tested), loaded by the bridge
mcp_bridge.lua # Persistent Lua bridge (defer loop, JSON IPC, 131 handlers)
mcp_snapshot_lib.lua # Shared library for snapshot action scripts
mcp_plan_lib.lua # run_plan executor (pure Lua, takes the API as an argument; unit-tested via wasmoon)
mcp_actions_lib.lua # Action proxy + selection setters (pure Lua, unit-tested via wasmoon)
mcp_project_lib.lua # Project ops, tempo map + marker editing (pure Lua, unit-tested via wasmoon)
mcp_envelopes_lib.lua # Envelopes, points (dB through the envelope's scaling) and pooled automation items (pure Lua, unit-tested via wasmoon)
mcp_render_lib.lua # Track renders for the analysis tools: render cache, one stem pass for several tracks, focus hand-back on macOS (pure Lua, unit-tested via wasmoon)
mcp_mixing_lib.lua # Automation mode, FX modulation/pins, monitoring FX, freeze, apply FX, stretch markers + audio quantize (pure Lua, unit-tested via wasmoon)
mcp_midi_lib.lua # Quantize, transform, MIDI file import, pitch-class profile, chord grid (pure Lua, unit-tested via wasmoon)
mcp_items_lib.lua # Items, takes, take FX, FX move/copy/rename, FX chains, track templates (pure Lua, unit-tested via wasmoon)
mcp_recording_lib.lua # Record inputs/monitoring/modes, punch, fixed lanes and comping (pure Lua, unit-tested via wasmoon)
mcp_arrange_lib.lua # Copy items, insert/remove time, copy a section, normalize/reverse/glue (pure Lua, unit-tested via wasmoon)
mcp_fxstate_lib.lua # Read/replace one VST3's saved state in the track chunk, via files in the bridge folder (internal: get_fx_state / set_fx_state)
mcp_extensions_lib.lua # extension_call: runs a Lua command from an installed extension's handlers.lua (internal)
mcp_edit_views_lib.lua # Status-page results: measurements, waveforms and before/after edit views (tested through the bridge)
mcp_snapshots_ui_lib.lua # Status-page Snapshots view: list, restore and save requests (tested through the bridge)
mcp_prefs_lib.lua # the read-only LoreKit token shared through ~/.config/reaper-mcp/lorekit.json (never the lk_rw_ one) (ExtState lorekit_tokens / tokens_req) and the feature-flag overrides in flags.json (flag_overrides / flags_req; the page's Developer drawer, the CLI and the server share them); prefs-lib.test.ts
mcp_snapshot_next.lua # Action: restore next snapshot (keybind for A/B testing)
mcp_snapshot_prev.lua # Action: restore previous snapshot (keybind for A/B testing)
mcp_snapshot_quick_save.lua # Action: quick save, named by the date and time
# The 3 snapshot actions are listed in reaper-kb.ini by setup (REAPER closed),
# else registered by the bridge on start (register_actions in mcp_snapshots_ui_lib.lua)
mcp_analyzer.jsfx # Real-time FFT analyzer (JSFX, writes to gmem[])
mcp_midi_emitter.jsfx # Real-time MIDI emitter (JSFX, reads from gmem[] ring buffer)
mcp_ui.jsfx-inc # The @gfx UI toolkit every generated plugin inlines (ring knob, toggle, choice, meter, per-band `ui_fthresh`/`ui_fband` drag, a playable `ui_keyboard` (`ui_kpoll`), plugin-name header with Mix/Output bars (`ui_hbar`), frequency graph with band handles and per-band threshold lines, gain-reduction meter, transfer curve, Advanced drawer over the core, value box on double-click, Cmd/Ctrl/Alt-click reset, About dialog from the credit, per-plugin accent via ui_theme(), cached gradient+grain background); ui_-prefixed, no science literals, UI state set once (@init re-runs on Play)
mcp_gain_trace.jsfx # Live pre/post gain trace (pumping/ducking meter: p5/p1/std as params, gmem MCPGainTrace)
install.sh # Manual install helper scriptWhere mix knowledge lives
knowledge/(genres, workflows, reference) — curated markdown read on demand by the mix skills; symlinked into~/.claude/knowledgein a clone, copied there byinstall-skillsfrom an npm install.- Plugin knowledge and process lessons live in LoreKit, scope
project::reaper-mcp— one record per plugin (tagsplugin-knowledge,category::…,preference::…,fx::…) and lessons (loop::mixing-lessons), in two layers: the built-in layer (keysplugins::<vendor>/<plugin>/mixing-lessons::<slug>, owned by thereaper-mcpLoreKit org, taglayer::built-in, read by everyone through the server'slist_builtin_knowledge/get_builtin_knowledgetools) and each user's own layer on top (keysuser::plugins::…/user::mixing-lessons::…, taglayer::user, via the user's own LoreKitmemory.*). The user's record wins. The skills only ever writeuser::keys; the maintainer moves records into the built-in layer with/mix-memory publish. docs/PLUGINS.mdlists every built-in plugin record (table between<!-- plugin-list:start/end -->, rebuilt bynode scripts/plugin-list.mjs, never by hand). A publisher's/mix-memory publish(and/learn-plugin, which offers to publish) rebuild it in the clone; thePlugin listworkflow rebuilds it onmainafter everyPlugin contributionsrun and daily (direct publishes from the bridge page). Contract:knowledge/reference/memory-protocol.md.
Workspace Packages
| Package | Location | Build | Purpose |
@mthines/reaper-mcp | / (root) | -- | Workspace root, scripts |
@mthines/reaper-mcp-server | apps/reaper-mcp-server | @nx/esbuild (ESM bundle) | MCP server application |
@mthines/reaper-bridge-ui | apps/bridge-ui | Vite + React Compiler → single HTML | Bridge status page served by REAPER's web interface |
@reaper-mcp/protocol | libs/protocol | @nx/js:tsc | Shared command/response types |
@reaper-mcp/feature-flags | libs/feature-flags | none (bundled into its consumers) | Flag registry, bucketing, OpenFeature provider; server and page both import it |
MCP Tools (192 total)
Every tool that takes a trackIndex (except media item, MIDI, item/take, track-template, measure_track_alignment and verify_edit tools) accepts -1 for the master track; track references (track, from, to) also accept an exact name, a "{GUID}", or "master".
Project & Tracks (5)
| Tool | File | Description |
get_project_info | tools/project.ts | Project name, tempo, time sig, sample rate, transport state |
list_tracks | tools/tracks.ts | All tracks with volume, pan, mute/solo, arm, phase, FX count, routing; optional parent (folder index/name → its descendants), nameContains, compact, offset/limit (then returns {total, hasMore, tracks}) |
get_track_properties | tools/tracks.ts | Detailed single track info + full FX chain list |
set_track_property | tools/tracks.ts | Set volume (dB), pan, mute, solo, recordArm, phase, input, playOffsetMs (track playback offset, ±500 ms) |
set_multiple_track_properties | tools/batch.ts | Batch set properties on multiple tracks in one call |
Track Structure (6)
| Tool | File | Description |
add_track | tools/structure.ts | Insert a track (optional name, position) |
delete_track | tools/structure.ts | Delete a track (never the master) |
move_track | tools/structure.ts | Move a track to a new position; keeps the user's selection |
set_track_folder | tools/structure.ts | Folder parent / last-in-folder / normal; collapse state |
set_track_info | tools/structure.ts | Name, color (#RRGGBB/none), channel count, master/parent send |
set_track_group | tools/structure.ts | Group (1-64) membership roles, incl. VCA lead/follow |
FX Management (9)
| Tool | File | Description |
add_fx | tools/fx.ts | Add FX by name (partial match: "ReaEQ", "VST: Pro-Q 3") |
remove_fx | tools/fx.ts | Remove FX from chain by index |
get_fx_parameters | tools/fx.ts | List all FX params with current values and ranges |
analyze_fx | tools/fx.ts | Analyze FX parameters with filtering and pagination |
set_fx_parameter | tools/fx.ts | Set FX parameter (normalized 0.0-1.0) |
set_fx_enabled | tools/fx.ts | Enable or disable (bypass) an FX plugin |
set_fx_offline | tools/fx.ts | Set FX online/offline (offline = no CPU, preserves settings) |
setup_fx_chain | tools/batch.ts | Batch add multiple FX with initial parameters in one call |
set_multiple_fx_parameters | tools/batch.ts | Batch set params across multiple FX/tracks in one call |
Transport (5)
| Tool | File | Description |
play | tools/transport.ts | Start playback |
stop | tools/transport.ts | Stop playback/recording |
record | tools/transport.ts | Start recording; refused when no track is armed (REAPER would open a blocking dialog) |
get_transport_state | tools/transport.ts | Play/record/pause status, cursor positions, tempo, time sig |
set_cursor_position | tools/transport.ts | Move edit cursor to position in seconds |
MIDI Editing Tools (14)
| Tool | File | Description |
create_midi_item | tools/midi.ts | Create an empty MIDI item on a track at a given time range (seconds) |
list_midi_items | tools/midi.ts | List all MIDI items on a track with position, length, note/CC counts |
get_midi_notes | tools/midi.ts | Get MIDI notes with pagination (offset/limit). Use analyze_midi first for large items. |
analyze_midi | tools/midi.ts | Analyze MIDI item: per-pitch velocity stats, histogram, machine gun detection. Efficient for large items. |
insert_midi_note | tools/midi.ts | Insert a single note (pitch 0-127, velocity 1-127, position/duration in beats) |
insert_midi_notes | tools/midi.ts | Batch insert multiple notes via JSON array string |
edit_midi_note | tools/midi.ts | Edit an existing note by index (partial updates: only provided fields change) |
edit_midi_notes | tools/midi.ts | Batch edit multiple notes via JSON array string. Much faster than repeated edit_midi_note calls. |
delete_midi_note | tools/midi.ts | Delete a note by index |
get_midi_cc | tools/midi.ts | Get CC events, optionally filtered by CC number |
insert_midi_cc | tools/midi.ts | Insert a CC event (cc 0-127, value 0-127, position in beats) |
delete_midi_cc | tools/midi.ts | Delete a CC event by index |
get_midi_item_properties | tools/midi.ts | Get MIDI item properties (position, length, note/CC count, mute, loop) |
set_midi_item_properties | tools/midi.ts | Set MIDI item properties (position, length, mute, loop source) |
Composition (6)
| Tool | File | Description |
quantize_midi | tools/composition.ts | Snap notes to the project grid: grid (beats), strength, swing, window, lengths keep/quantize; all notes or a selection (indexes, pitch range, channel) |
transform_midi | tools/composition.ts | Transpose (refused out of 0-127), velocity set/scale/add + clamp, humanize (seeded), length set/scale/legato |
import_midi_file | tools/composition.ts | Import a .mid (type 0/1, ≤5 MB, ≤20000 notes) without REAPER's dialog: merged onto a track or one new named track per file track; file tempo reported, not applied |
transcribe_voice_sketch | tools/voice-sketch.ts | Voice recording → detected notes, tempo/key and a generated band arrangement; optional MIDI + sampled stems. See usage and limits |
detect_key | tools/composition.ts | Key from a track's MIDI notes (drums skipped) or the track's audio (read before track FX and fader, rendered when it can't be) / an audio file (sidecar chroma): key, confidence, relative, top 3, 12-bin chroma; itemIndex reads one item's range |
detect_chords | tools/composition.ts | Chords per bar or beat (project tempo map; a file by bpm or windows) from MIDI notes or the track's audio (read before FX, rendered when it can't be) / a file (sidecar chroma per segment, or the opt-in chord model --with-chords, engine auto/model/template): key, progression, spans with roman numeral, slash bass (MIDI or model) and bassMidi for a bass line; itemIndex, paginated |
Live MIDI Output (3)
| Tool | File | Description |
send_midi_cc | tools/midi.ts | Send a CC event in real-time to a track's MIDI output (auto-inserts mcp_midi_emitter.jsfx) |
send_midi_pc | tools/midi.ts | Send a program change (optionally preceded by bank select CC0 + CC32) |
send_midi_note | tools/midi.ts | Send a note-on; if durationMs provided, schedules note-off automatically |
Media Item Editing Tools (11)
| Tool | File | Description |
list_media_items | tools/media.ts | List all items on a track (position, length, name, item volume, takeVolume, totalGainDb, MIDI/audio type) |
get_media_item_properties | tools/media.ts | Detailed item properties (fades, play rate, pitch, source file, lock state, item volume plus the active take's takeVolume / takePolarityInverted / takePan and totalGainDb, the level the item plays) |
set_media_item_properties | tools/media.ts | Set item properties (position, length, volume dB, takeVolume dB, takePan, takePolarityInverted, pitch, preservePitch, mute, fades, play rate, locked, loopSource; take/lock/loop fields checked first, logic in reaper/mcp_items_lib.lua) |
set_media_items_properties | tools/media.ts | Batch set properties on multiple items via JSON array string; same fields, an item with a bad value is skipped and reported in errors. |
split_media_item | tools/media.ts | Split an item at a position (seconds), returns left/right item info |
delete_media_item | tools/media.ts | Delete an item from a track |
move_media_item | tools/media.ts | Move an item to a new position and/or a different track |
trim_media_item | tools/media.ts | Trim item edges (positive=trim inward, negative=extend) |
add_stretch_marker | tools/media.ts | Add a stretch marker for time-stretching audio |
get_stretch_markers | tools/media.ts | List stretch markers with positions and source positions |
delete_stretch_marker | tools/media.ts | Delete a stretch marker by index |
Arrangement Tools (5)
| Tool | File | Description |
copy_media_items | tools/arrange.ts | Copy/repeat items keeping their spacing (times, position, trackIndex); fresh GUIDs, MIDI unpooled unless pooled |
insert_time | tools/arrange.ts | Open time across the project: items, markers, regions, tempo, envelope points and automation items after it move; spanning items split |
remove_time | tools/arrange.ts | Cut a range out of the project and close the gap; crossing items trimmed, regions shrink, the tempo after the cut kept |
copy_section | tools/arrange.ts | Copy a region (or start/end) to a position: items trimmed to it plus automation (points, and pooled copies of automation items inside it), optional insert and tracks |
process_items | tools/arrange.ts | normalize (item gain to a peak/true-peak/LUFS/RMS target), reverse (toggles), glue (whole items); selection kept |
Selection & Navigation Tools (6)
| Tool | File | Description |
get_selected_tracks | tools/selection.ts | Get currently selected tracks with indices and names (master as -1) |
set_selected_tracks | tools/selection.ts | Select tracks by index, name or GUID (replace or add); all resolved first, an unknown one changes nothing |
get_selected_items | tools/selection.ts | The items selected now: {trackIndex, itemIndex}, track name, position, length, mute; paged (offset/limit, {total, hasMore, items}) |
set_selected_items | tools/selection.ts | Select media items by {trackIndex, itemIndex} (replace or add) |
get_time_selection | tools/selection.ts | Get time/loop selection start, end, length in seconds |
set_time_selection | tools/selection.ts | Set the time selection range (start/end in seconds) |
Markers & Regions Tools (8)
| Tool | File | Description |
list_markers | tools/markers.ts | List all project markers (index, name, position, color) |
list_regions | tools/markers.ts | List all regions (index, name, start/end, color) |
add_marker | tools/markers.ts | Add a marker at position with optional name/color |
add_region | tools/markers.ts | Add a region with start/end, optional name/color |
delete_marker | tools/markers.ts | Delete a marker by index |
delete_region | tools/markers.ts | Delete a region by index |
edit_marker | tools/markers.ts | Rename, move or recolor a marker by index; unknown index changes nothing |
edit_region | tools/markers.ts | Rename, move/resize or recolor a region by index; end must stay after start |
Tempo Map Tools (5)
| Tool | File | Description |
get_tempo_map | tools/tempo.ts | All tempo/time sig changes (position, BPM, time sig, linear flag) |
add_tempo_marker | tools/tempo.ts | Add a tempo/time sig marker at a position (seconds); returns the updated map |
edit_tempo_marker | tools/tempo.ts | Edit a tempo marker by index (position, BPM, time sig, linear); unspecified fields kept |
delete_tempo_marker | tools/tempo.ts | Delete a tempo marker by index |
set_project_tempo | tools/tempo.ts | Set the tempo at the project start: project BPM with no markers, else the marker at 0 (added when the first marker is later) |
Envelope / Automation Tools (14)
Every point tool takes an optional automationItemIndex to work on one automation item's (pool's) points instead of the underlying envelope.
| Tool | File | Description |
create_track_envelope | tools/envelopes.ts | Create/show an envelope on a track (Volume, Pan, Mute, Width, Trim Volume via native actions, selection kept; FX parameter; or a send's Volume/Pan/Mute with sendIndex, starting at the send's current value); created: false when it existed |
get_track_envelopes | tools/envelopes.ts | List envelopes on a track (name, point and automation item counts, active/visible/armed); send envelopes carry send (index, destination track) |
get_envelope_points | tools/envelopes.ts | Get automation points with pagination (time, raw value, db on volume envelopes, shape, tension) |
insert_envelope_point | tools/envelopes.ts | Insert an automation point (value or db) with shape/tension |
insert_envelope_points | tools/envelopes.ts | Batch insert multiple automation points (JSON array) |
edit_envelope_points | tools/envelopes.ts | Edit points by index (time, value/db, shape, tension); all validated before any write |
delete_envelope_point | tools/envelopes.ts | Delete an automation point by index; returns the deleted point |
clear_envelope | tools/envelopes.ts | Delete ALL points from an envelope (or an item's pool) |
remove_envelope_points | tools/envelopes.ts | Delete automation points in a time range |
set_envelope_properties | tools/envelopes.ts | Set envelope active/visible/armed state |
list_automation_items | tools/envelopes.ts | Automation items on an envelope: index, poolId, pool name, position, length, loop, point count |
insert_automation_item | tools/envelopes.ts | New pool from points (seconds from the item start), a pooled instance of poolId (any track), or captureEnvelope; returns pooledWith |
set_automation_item | tools/envelopes.ts | Move/resize an item; start offset, play rate, baseline, amplitude, loop, pool name |
delete_automation_item | tools/envelopes.ts | Delete one item (preservePoints keeps them on the envelope); other selections kept |
FX Discovery & Presets (4)
| Tool | File | Description |
list_available_fx | tools/discovery.ts | Discover all installed plugins (VST, VST3, JS, CLAP, AU) via REAPER's EnumInstalledFX (6.37+) |
search_fx | tools/discovery.ts | Fuzzy search installed plugins by name |
get_fx_preset_list | tools/presets.ts | List available presets for an FX |
set_fx_preset | tools/presets.ts | Load a preset by name |
Snapshots (5)
| Tool | File | Description |
snapshot_save | tools/snapshots.ts | Save mixer state to .reaper-mcp/snapshots/ (v2: volumes, pans, FX params, sends); trackIndices scopes it, fullChunk stores exact track chunks, stretchMarkers keeps the stretch markers of the audio items on the captured tracks (flat strings, logic in mcp_mixing_lib.lua: capture_stretch_markers / restore_stretch_markers; REAPER refused SetTrackStateChunk on tracks whose items carry Melodyne take FX, so markers do not ride on the chunk) |
snapshot_restore | tools/snapshots.ts | Restore a saved snapshot (FX params only if plugin name matches); saved stretch markers are put back after the tracks, items found by GUID, else by track, position and length |
snapshot_list | tools/snapshots.ts | List project-scoped snapshots (falls back to global for unsaved projects) |
snapshot_delete | tools/snapshots.ts | Delete a saved snapshot by name |
snapshot_edit | tools/snapshots.ts | Rename a snapshot and/or change its description; the mixer state is copied unchanged, a name another snapshot's file uses is refused |
Routing (5)
| Tool | File | Description |
get_track_routing | tools/routing.ts | Sends, receives (index, mode, channels), hardware outputs, master send, parent/folder info |
add_send | tools/structure.ts | Track → track send: level, pan, mute, mode, channels (sidechain into 3/4 widens the destination) |
set_send | tools/structure.ts | Edit a send, receive or hardware output by index |
remove_send | tools/structure.ts | Remove a send, receive or hardware output by index |
add_hardware_output | tools/structure.ts | Route a track to an audio interface output (stereo or mono) |
Metering & Analysis (6)
| Tool | File | Description |
read_track_meters | tools/meters.ts | Peak/RMS L/R in dB |
read_track_spectrum | tools/meters.ts | 1/3-octave bands, 25 Hz–16 kHz, raw db + K-weighted kDb (judge on kDb; table in knowledge/reference/perceived-loudness.md); auto-inserts JSFX analyzer; raw FFT bins with includeBins |
read_track_lufs | tools/analysis.ts | Integrated/short-term/momentary LUFS + true peak |
read_track_correlation | tools/analysis.ts | Stereo correlation, width, mid/side levels |
read_track_crest | tools/analysis.ts | Crest factor (peak-to-RMS ratio) |
measure_tracks | tools/analysis.ts | Play, collect LUFS/crest/correlation/spectrum for 1–8 tracks in one call, stop, then remove the meters it inserted (keepMeters keeps them). A metric that returned no data goes to the track's errors instead of zeros (TS-composed; cleanup via internal remove_mcp_meters) |
Offline & Perceptual Audio Analysis (7) — Requires Python Sidecar
| Tool | File | Description |
analyze_track_aesthetics | tools/aesthetics.ts | Perceptual quality scores via Meta Audiobox Aesthetics (CC-BY 4.0): Production Quality, Production Complexity, Content Enjoyment, Content Usefulness (all 0-10). Bounces a 30 s clip (default) of a track or the master (-1), normalizes it to normalizeLufs (default -18, false = as rendered) so level doesn't skew the scores, calls Python sidecar. Noise floor: knowledge/reference/aesthetics-scoring.md. Requires setup-sidecar. |
analyze_track_offline | tools/offline.ts | Render a track or the master once (up to 900 s, no playback) and analyze it: integrated LUFS (BS.1770 gated), LRA (EBU 3342), true peak, sample peak, crest, per-section loudness, band balance, resonance and sibilance hints; with referencePath, loudness and tonal-balance deltas against that file |
analyze_audio_file | tools/offline.ts | The same analysis for an audio file on disk (reference song, bounce, stem); no REAPER involved |
measure_track_alignment | tools/offline.ts | Render two tracks over the same window (≤30 s) and cross-correlate: delay (ms, samples), polarity, correlation, and absolute suggestedPlayOffsetMs / suggestedPhase for set_track_property (include the track's current offset and polarity) |
verify_edit | tools/offline.ts | Check an edit's result against the audio from before it (a reference track or a bounce of the same range, ≤60 s): delay/gain/polarity-compensated null (residual dB) and a discontinuity (click) check, each with ok/warn/fail; expect: "changed" reports the residual without a verdict, timeScale ≠ 1 (a stretch, as a playback rate) skips the null and runs pitch drift (cents), tone (dB) and transient checks instead, warn only (a plain speed change, where the pitch moved as the speed alone predicts, is info, not warn); slow-downs below 0.9× add a dropout check (deepest loudness dip against the warped reference, warn from 12 dB, provisional: one vocal phrase). Logic in sidecar/verify.py. Thresholds come from the issue 81 experiment (6 sources, 12 edits each); the tone check misses phase-vocoder smearing and the transient check is blind on drums |
detect_transients | tools/transients.ts | Hits in a track (its own audio before FX and fader when ≤120 s, else rendered, ≤900 s) or an audio file (MP3 too; filePosition maps it to project time): time, strength 0..1, dominant band (low/mid/high), peakDb, plus tempo, per-band counts and per-section density; filter by band/bands/sensitivity/minGapMs/minStrength, paginated |
create_transient_automation | tools/transients.ts | Detect, then write one pulse per hit (attack, hold, exponential/linear decay, scaled by strength) onto an existing envelope — e.g. lighting that flashes on the kicks. Replaces the range's points (REAPER keeps an envelope's last point on a range delete; it becomes the first pulse point), dryRun returns the points. TS-composed over remove_envelope_points / insert_envelope_points |
detect_vocal_pitch | tools/pitch.ts | Sung notes of a vocal track (own audio, before FX) or file: per note time range, sung pitch (fractional MIDI), nearest scale note, offsetCents / shiftCents, plus key used, averageOffsetCents, voicedShare. Sidecar pitch.py: SwiftF0 when installed (pip install "swift-f0[audio]" in the sidecar venv), else YIN; one shift per note keeps vibrato. Read-only |
correct_vocal_pitch | tools/pitch.ts | Detect, then split the vocal item at each off note and set that piece's pitch (semitones, REAPER's own engine) with a few ms of fade; dryRun, strength, maxShiftCents; refuses items that already have a pitch set. TS-composed over split_media_item / set_media_item_properties, each edit its own undo point. Prototype |
Recording & Comping (6)
| Tool | File | Description |
get_record_setup | tools/recording.ts | Global record mode (normal / time-selection or item auto-punch) with punch range and record path; armed tracks (or all, max 64) with input label, monitoring, record mode; the audio and MIDI inputs |
set_track_record | tools/recording.ts | Arm, record input (audio channel/stereo, midi device/channel, none), monitoring (off/on/auto), record mode, monitor-items for up to 64 tracks; all checked first, one undo point |
set_record_mode | tools/recording.ts | Global record mode, punch range (time-selection mode) and record path |
get_track_lanes | tools/recording.ts | Fixed lanes: on/off, each lane's name, playing state (exclusive/layered/off) and items (100 per lane) |
set_track_lanes | tools/recording.ts | Fixed lanes on/off, lane count, names, which lane plays alone or which lanes play layered |
comp_lanes | tools/recording.ts | Comp from lanes: {start, end, lane} ranges (max 200, no overlaps) copied onto a new exclusive comp lane with crossfades; a range a lane has no audio for is refused with the gap |
Mixing Depth (16)
| Tool | File | Description |
set_automation_mode | tools/mixing.ts | Tracks' automation mode (trim, read, touch, write, latch, latch_preview) and/or the global override (none/bypass); returns before and after |
get_fx_param_modulation | tools/mixing.ts | One parameter's modulation (baseline, LFO, audio control signal, link), or every modulated parameter of an FX |
set_fx_param_modulation | tools/mixing.ts | LFO (shape, speed, strength, phase, tempo sync), audio follower (channel, attack/release, dB range) and/or parameter link; only given fields change, all validated first |
get_fx_pins | tools/mixing.ts | Each input/output pin's track channels (1-based) and the track's channel count |
set_fx_pins | tools/mixing.ts | Connect pins to channels (e.g. a sidechain on 3/4); widens the track to the highest channel used, never narrows it |
list_monitoring_fx | tools/mixing.ts | The monitoring FX chain (heard in the monitors, never rendered; global, not in the project) |
add_monitoring_fx | tools/mixing.ts | Add a monitoring FX, with optional normalized parameters |
set_monitoring_fx | tools/mixing.ts | Bypass, offline or set parameters of a monitoring FX |
remove_monitoring_fx | tools/mixing.ts | Remove a monitoring FX |
freeze_tracks | tools/mixing.ts | Freeze tracks to stereo/mono/multichannel (native actions 41223/40901/40877), selection kept; not the master |
unfreeze_tracks | tools/mixing.ts | Restore one freeze layer (41644); refuses a track that is not frozen |
apply_fx_to_items | tools/mixing.ts | Render in place: track + take FX to a new active take (40209/40361/41993); the old take stays |
add_stretch_markers | tools/mixing.ts | Many stretch markers on an audio item in one call and one undo point |
edit_stretch_markers | tools/mixing.ts | Edit existing markers by index in one call and one undo point: position (item seconds), sourcePosition, slope (-1..1); all edits checked against the whole list first (out of order, repeated or out of range refuses everything) |
align_audio_to_guide | tools/align.ts | Vocal alignment: onsets of a guide item and 1-8 doubles (sidecar transients, source files), paired in order within maxShiftMs (align.ts), then a stretch marker per hit moves the double onto the guide; strength, dryRun, protectConsonants (high-band hits keep a rigid consonantMs tail); per double the offset before/after (avg/max ms); a guide with stretch markers is refused (TS-composed over get_media_item_properties + the align_audio_to_guide bridge command) |
quantize_audio | tools/mixing.ts | Hits from the sidecar (transients), then stretch markers moved toward the grid (strength, window, swing); returns the timing offset before/after (TS-composed over get_media_item_properties + the quantize_audio bridge command) |
Mix Checks (4) — Requires Python Sidecar
Each takes a track (rendered post-FX, -1 = master) or a file path; measure_masking takes 2-8 tracks.
| Tool | File | Description |
analyze_loudness_curve | tools/mixcheck.ts | Short-term and momentary LUFS over time (≤240 points each, every point its slice's loudest), integrated, true peak, LRA, PLR, loudest/quietest 3 s windows, and with targetLufs the spans over target + toleranceLu; times in project time for a track, file seconds for a path |
analyze_stereo_bands | tools/mixcheck.ts | Correlation per band (low <120 Hz, lowMid, mid, high 2-8 kHz, air): overall, worst, out-of-phase share, side-to-mid dB, a 60-point series; flags a wide/out-of-phase low end or any band below 0 |
measure_masking | tools/mixcheck.ts | Renders 2-8 tracks over the same range (≤60 s) and scores each pair per K-weighted third-octave band (both loud there and within ~6 dB); pairs with their worst bands, top conflicts with which track to cut (the one the band matters less to) |
separate_stems | tools/mixcheck.ts | Demucs (htdemucs 4 stems, htdemucs_6s adds guitar/piano) to 32-bit float WAVs in outDir (default <project media>/Stems/<name>-<time>), ≤600 s; insertTracks adds them under a new, muted folder (they sum back to the source) in one undo point via the internal insert_stem_tracks (after a folder source's last child, lined up with the range). Needs setup-sidecar --with-separation (pre-downloads htdemucs; the first htdemucs_6s call downloads ~80 MB) |
Plan Executor (1)
| Tool | File | Description |
run_plan | tools/plan.ts | Execute an ordered list of ops in one bridge call and one undo block, all-or-nothing, with $refs, dryRun, idempotencyKey, and an optional snapshotBefore |
Built-in Mix Knowledge (3)
| Tool | File | Description |
list_builtin_knowledge | tools/knowledge.ts | List (summaries, tag filter) or full-text search the built-in plugin records and mixing lessons |
get_builtin_knowledge | tools/knowledge.ts | Read one built-in record by key (plugins::… / mixing-lessons::…) |
report_plugin_research | tools/plugin-research.ts | The plugin-researcher's last call: how the run went (outcome, caller, batch, category, style, format, parameter range, counts) on the tool's span for usage telemetry, timed from its [MCP] plugin-research <TAG> scratch track (add_track / run_plan note it, in memory). Never the plugin's name, nor a combination that singles one out |
TS-only (no bridge command): JSON-RPC to LoreKit with a bundled public read-only lk_ro_ token
(BUILTIN_LOREKIT_TOKEN, scoped to project::reaper-mcp + the reaper-mcp org; override with
REAPER_MCP_LOREKIT_TOKEN / REAPER_MCP_LOREKIT_URL). Non-lk_ro_ tokens are refused, rows are
filtered to tag layer::built-in, responses are cached 10 min. Scope the token with LoreKit's
orgs_only tenancy ("Selected orgs only") so it never sees its owner's personal rows; under any
other tenancy it does, and the owning account must keep nothing private in that scope.
Plugin Authoring (2)
/make-plugin writes the user a real plugin: a JSFX file that works on its own afterwards (no bridge, no server, no
browser), with its UI drawn by the shared @gfx toolkit reaper/mcp_ui.jsfx-inc. See docs/PLUGIN-AUTHORING.md.
| Tool | File | Description |
write_jsfx | tools/jsfx.ts | Write a plugin to Effects/reaper-mcp-generated/<slug>.jsfx: lints the source (src/jsfx/lint.ts), inlines the toolkit (src/jsfx/inline.ts, so the file is self-contained), bumps the version, keeps the old file in ~/.config/reaper-mcp/jsfx-history/. An existing slider is never renumbered or re-ranged without breaking: true (saved automation would break). Optional presets (≤8, values checked against each slider, one bad value refuses the call) go into REAPER's own preset file presets/js-reaper-mcp-generated_<slug>_jsfx.ini (src/jsfx/presets.ts), merged so the user's own presets are kept. Optional accent (auto = from the slug, a name, or #rrggbb; kept as // accent: in the file, a later write without it keeps it; bad input refuses the call; src/jsfx/accent.ts). desc: gets (reaper-mcp) appended once (DEVELOPER_SUFFIX); slug, file and preset paths are unchanged. TS-only: loading uses add_fx |
report_plugin_build | tools/plugin-build.ts | The skill's last call: outcome (shipped / compile_failed / checks_failed / abandoned), rounds, checks passed, the example it started from. Closed values and capped counts only, like report_plugin_research |
Toolkit v1.3 adds graph widgets (ui_freqgraph, ui_fhandle, ui_grmeter, ui_transfer, ui_keyboard, ui_tall), a plugin-name header on every plugin and activity-driven redraw (ui_boot(2)); the lint refuses unknown ui_ calls and wrong argument counts (unknown-ui-call, ui-arity, table UI_API kept equal to the toolkit by a test). Per-band controls: ui_fthresh (a threshold line per band, drag a hovered band up/down, Shift-drag = gain, wheel = ratio) and ui_bandknob (knobs follow the selected band). Header bars: ui_header(mix_idx, out_idx) puts the plugin's own Mix and Output in the top right as slim horizontal bars level with the plugin name (always visible; the examples use it). ui_fband gives each band a level line to drag (like ui_fthresh), and ui_keyboard is playable, read in @block with ui_kpoll(). The About dialog lists the control gestures. Before/after on the graph: ui_gshow + ui_gfeed2 (the input trace). Four shipped examples (multiband-compressor is the graph one, with a threshold, ratio and gain per band). Memory map: 0..1023 core, 1024+ graph data, ui_mem 2048 for plugin buffers.
Telemetry: both set closed values on the tool's span (reaper.jsfx.*, reaper.plugin_build.*, all in the allow-list in
telemetry-consent.ts); lint findings count in reaper.jsfx.lint.findings by rule id, graph widgets in reaper.jsfx.graphs (a count). Never the plugin's name, the request,
its source or a control label. Generated plugins themselves contain no telemetry.
Actions Proxy (3)
| Tool | File | Description |
search_actions | tools/actions.ts | Search REAPER's ~6k actions (native, SWS, scripts, Custom: macros) inside REAPER; returns id, stable namedId, name, toggle state, shortcuts |
get_action | tools/actions.ts | One action's details; a Custom: macro's steps by name, or a script's path (from reaper-kb.ini) |
run_action | tools/actions.ts | Run an action by id, named id or exact name in an undo block; returns the toggle state after. Dialog actions need allowDialog; quit/close/open project are always refused |
Project Operations (9)
| Tool | File | Description |
undo_project | tools/project.ts | Undo the last undo point; reports its label and the next undo/redo labels |
redo_project | tools/project.ts | Redo the last undone point; reports its label |
save_project | tools/project.ts | Save in place, or write a copy to an absolute .rpp path (the open project keeps its path; savedAsCopy). Never opens a dialog: a never-saved project without path is refused |
get_render_settings | tools/project.ts | Output dir, file pattern, format + bit depth/bitrate, source, bounds, normalize/limit, dither, metadata, region matrix, and the resolved target files |
set_render_settings | tools/project.ts | Set any render setting: format/secondaryFormat (wav/aiff/flac/mp3/ogg/opus, secondary also none), source (master, stems, master_and_stems, selected_via_master, selected_items, selected_items_via_master, region_matrix + regionMatrix), bitDepth/mp3Bitrate, dither, normalize/limit, metadata; all validated before any write, one undo point |
render_project | tools/project.ts | Render with the current settings (synchronous action 42230), optionally for tracks (selected for the render, selection restored); returns each file's length, LUFS-I, true peak and peak; refuses to overwrite existing targets unless overwrite |
render_versions | tools/project.ts | Render up to 16 versions in one call (e.g. full, instrumental, TV): each mutes its tracks, renders to <pattern>-<name>, and mutes and pattern are restored even when one fails; all targets checked before the first render |
get_project_settings | tools/project.ts | Sample rate (+ forced flag), title, author, notes, repeat, metronome |
set_project_settings | tools/project.ts | Set any of those; metronome is a global REAPER option (not undoable, not stored in the project) |
Items & Takes (10)
| Tool | File | Description |
insert_audio_file | tools/items.ts | Insert an audio file onto a track as a new item at a position (default: edit cursor); the item is the file's length |
list_takes | tools/items.ts | An item's takes: name, active, MIDI/audio, source file, take FX count |
set_active_take | tools/items.ts | Make one take the active (playing) take |
get_take_fx | tools/items.ts | List a take's FX (default: active take); with fxIndex, that FX's parameters |
add_take_fx | tools/items.ts | Add an FX to a take's FX chain by name |
remove_take_fx | tools/items.ts | Remove one FX from a take's FX chain |
set_take_fx_parameter | tools/items.ts | Set one take FX parameter and return the value REAPER reads back |
get_item_appearance | tools/items.ts | Item color ("#RRGGBB" or "none") and fade lengths, shapes (0-6) and curves |
set_item_color | tools/items.ts | Set an item's color, or "none" for the track default |
set_item_fades | tools/items.ts | Set fade-in/out lengths, shapes and curves (only the fields given change) |
FX Housekeeping (9)
| Tool | File | Description |
move_fx | tools/fx-housekeeping.ts | Move one FX within its chain or to another track |
copy_fx | tools/fx-housekeeping.ts | Copy one FX (with settings) within its chain or onto another track |
rename_fx | tools/fx-housekeeping.ts | Rename an FX instance (REAPER 6.37+); "" restores the plugin name |
save_fx_chain | tools/fx-housekeeping.ts | Save a track's FX chain as <resource>/FXChains/<name>.RfxChain |
load_fx_chain | tools/fx-housekeeping.ts | Load an .RfxChain onto a track (append or replace), fresh FXIDs |
list_fx_chains | tools/fx-housekeeping.ts | List saved .RfxChain names (FXChains folder and subfolders) |
save_track_template | tools/fx-housekeeping.ts | Save a track as <resource>/TrackTemplates/<name>.RTrackTemplate (items only with includeItems) |
insert_track_template | tools/fx-housekeeping.ts | Insert the track(s) of a template at a position, fresh GUIDs |
list_track_templates | tools/fx-housekeeping.ts | List saved .RTrackTemplate names |
Progressive Discovery (3)
| Tool | File | Description |
list_tool_categories | tools/categories.ts | List all tool categories with descriptions and tool names (compact — avoids loading all 192 schemas) |
enable_tool_category | tools/categories.ts | Get full tool list for a category; signals intent to use that category |
disable_tool_category | tools/categories.ts | Semantic context-budget hint that a category is no longer needed |
Categories: project, tracks, fx, transport, midi, media, arrange, selection, markers, tempo, envelopes, analysis, discovery, snapshots, routing, plan, actions, takes, fx_files, knowledge, recording, plugin_authoring
Tool profiles (profile.ts): REAPER_MCP_PROFILE (full default, minimal, mixing, music, analysis, or a comma list of profiles, categories and extension names) skips registering the core tools outside the chosen categories (every profile stays under 128 tools; profile.test.ts checks), and list_tool_categories shows only those. Tools in no core category (extensions, the category tools) are never blocked; loadExtensions skips an extension the profile does not name. A new category goes in a profile's list only when it belongs there.
MIDI Editing Concepts
- Positions and durations are in beats (quarter notes) from item start:
1.0= quarter note,0.5= eighth note,0.25= sixteenth note - Pitch: MIDI note number 0-127 where 60 = C4 (Middle C), 48 = C3, 72 = C5
- Velocity: 1-127 (64 = medium, 100 = strong, 127 = maximum)
- Channel: 0-15 (default 0; channel 9 = drums in General MIDI)
- Batch operations (
insert_midi_notes,edit_midi_notes): Pass a JSON array of note objects for efficient multi-note operations - The Lua bridge includes a fallback JSON array parser for REAPER versions without
CF_Json_Parse - Undo: a MIDI API edit (
MIDI_SetNote,MIDI_InsertNote, …) leaves the item unmarked, so REAPER folds it into the previous MIDI undo point. Every MIDI write callsMarkTrackItemsDirty(track, item)beforeUndo_EndBlock(seen in REAPER 7.40) - Composition (
mcp_midi_lib.lua): quantize snaps to the project's beats, not the item start; swing pushes every second grid line later. Humanize is reproducible fromseed.detect_keycorrelates the 12-bin profile with the Krumhansl-Kessler key profiles (key.ts); confidence is the gap to the best key that is not the relative key, scaled down for a flat profile and by the best key's correlation.detect_chordsmatches each bar's/beat's profile (cosine) against root × quality templates (triads preferred, in-key chords +0.03), holds the previous chord unless a new one wins by 0.03, and merges equal neighbours (chords.ts); the grid comes from the internal_chord_grid(bars/beats viaTimeMap_GetMeasureInfo, MIDI profiles and the lowest note held ≥ ¼ of the segment) - A MIDI or arrangement write that fails half way is undone (an import leaves no new tracks). The failed block is closed under its own
… (failed — reverting)label and undone only when that label is on top, so a failure that wrote nothing never undoes an earlier edit, the same rule asrun_plan.
Media Item Editing Concepts
- Positions and lengths are in seconds (absolute project time)
- Volume is in dB (0 = unity gain); internally converted to/from linear scale. An item plays its own gain plus its active take's gain (
takeVolume): readtotalGainDb, nevervolumealone - Trim:
trimStartmoves the left edge (adjusts start offset),trimEndmoves the right edge - Move: Validates destination track upfront; moves to new track first, then adjusts position
- Stretch markers: Define time-stretch points mapping item position to source audio position
Arrangement Concepts
- Logic lives in
reaper/mcp_arrange_lib.lua(pure Lua over an injected API, unit-tested via wasmoon inarrange-lib.test.tsagainst__fixtures__/fake_timeline.lua); the bridge handlers decodeitems/tracks(JSON strings) and passreaperin. - Time edits are done by hand, not with REAPER's ripple actions, so the result never depends on the user's ripple or "move envelope points with items" options. Tempo markers change first; markers, envelopes and items are then set from absolute times read before any change (a beat-timebase item would otherwise follow the tempo edit on its own).
- remove_time keeps the tempo after the cut: the last tempo marker inside the range moves to the cut's start (unless one sits on its end). Automation items fully inside are deleted (selected alone and removed with action 42086, the user's other selected items kept); ones crossing an edge are trimmed like media items (
automationItemsTrimmed: the part after the cut moves to its start with a later start offset, a tail inside the cut is dropped); one spanning the whole cut cannot lose its middle, so it stays and is counted (automationItemsKept). - Tempo ramps across a time edit keep their timing: a linear marker whose ramp runs across the edit point would change slope once its end moves, shifting every beat before the edit. insert_time ends the ramp at the position with a marker at its tempo there and holds that tempo through the opened time (
tempoMarkersAdded: 2); remove_time pins the ramp before the cut 1 ms short of it and starts the tempo after the cut where it stood at the cut's end, ramping on as before. - Normalize measures what the item plays (
CalculateNormalizationover its take's start offset and length) and sets item gain (D_VOL), so the take gain and source stay untouched. Reverse (41051, a toggle: a reversed take plays forward again) and glue (40362, ignoring the time selection; 41588 would glue only inside it) run on the named items only, then put the user's selection back; a glued item is selected when one of its sources was. - run_plan ops
copy_items,insert_time,remove_time:copy_itemsnames items by index in the project as it is before the plan, so it is refused after an op that adds tracks or moves items (add_track,copy_items,insert_time,remove_time).
Plan Executor Concepts (run_plan)
- Use it for any multi-step edit: one LLM turn and one bridge round trip instead of N sequential tool calls.
- Op types:
add_track,set_track(volume dB, pan, mute, solo, recordArm, phase, input, name),add_fx(optionalparams,enabled,position),set_fx_params,add_send(volume dB, pan, mute),graft_fxchain,select_tracks(tracks,mode),run_action(action,section,allowDialog— same resolution and safety rules as therun_actiontool, checked in the validate pass), and the arrangement opscopy_items,insert_time,remove_time(same parameters as the tools). Onlyrun_actionops may follow arun_action: targets resolve before anything runs, and an action can add, delete or reorder tracks. - Targets: tracks by 0-based index, exact name (then case-insensitive),
"{GUID}", or a"$ref"bound by an earlieradd_track/add_fxviaas: "$name". A digit string matches a track name first, then the index. FX by index, unique name substring, or$ref. A numeric FX index means the slot when that op runs, so afteradd_fxwithposition: 0the older FX have moved up one; use a name or anasref to pin a specific FX. Validation checks FX refs against each track's chain as earlier ops (add_fx,graft_fxchain) change it. - Two passes: every target is resolved before anything is written; an unknown/ambiguous track or an undefined
$refrejects the whole plan. If an op fails mid-apply, the undo block is closed and undone (only when the top undo entry is the plan's own), so no partial edit remains. dryRun: truereturns the resolved op list,conflicts, andwarnings(e.g. an FX name not found in the installed-FX list) without writing.idempotencyKey: the bridge remembers the last 100 applied keys; re-sending one returns{ alreadyApplied: true, result }. The TS tool also uses a 120 s timeout so a slow apply is not reported as failed and retried.graft_fxchaincopies a source<FXCHAINblock (from a track viafrom, or a base64 track chunk viafromChunk) onto the target, replacing the target's FX chain while keeping its items, envelopes, and sends. FXIDs are regenerated. It does not copy sends: sends live asAUXRECVlines on the receiving track and are outside the FX chain. Input FX (<FXCHAIN_REC) are not copied either.- No SWS needed: the ops travel as a JSON string that
mcp_plan_lib.luadecodes with its own small JSON decoder (SWS has noCF_Json_Parse; it is used only if present). Malformed JSON rejects the plan and writes nothing.
Actions Proxy Concepts
- Ids: native actions have fixed numeric ids (
40001). Custom actions, scripts and extension (SWS) actions get session-specific numbers; their stable handle is the named id ("_aee8…","_SWS_…") — store and pass that. A digit string is a command id; anything else is a named id (leading_optional) or an exact, unique action name. - Sections:
main(default),midi_editor(needs an open MIDI editor),midi_event_list. The inline MIDI editor and media explorer have no command entry point. - Selection first: most actions act on the selected tracks/items. Use
set_selected_tracks/set_selected_items, or in one undo steprun_planwithselect_tracksthenrun_action. - Safety: an action whose name ends in
...opens a modal dialog that blocks REAPER's main thread (and with it the bridge) until a person closes it, so it is refused unlessallowDialog: true. AnyFile: Save…action on a never-saved project counts as a dialog (REAPER asks for a path). Quit, close/open/new project, new or closed project tabs, switching tabs (native and SWS) and opening another project (SWS Resources slots, associated item projects) are always refused (REAPER names some with aFile:prefix and some without, e.g. "Close current project tab"; both are matched). A Custom: macro is judged by every step it runs, nested macros included (steps are read fromreaper-kb.ini).search_actions,get_actionandrun_plan's dry run flag all of this (opensDialog,denied). A ReaScript can still open its own prompt — the gate only sees action names. - Search runs in Lua: enumerating all ~6k main-section actions takes a few ms in REAPER; only matches (up to
limit, max 100) cross the bridge, with thetotalcount.
Project Operations Concepts
- No dialogs:
save_projectwithoutpathon a never-saved project is refused (REAPER would open Save As) — the same rulerun_actionapplies toFile: Save….render_projectrefuses when a target file exists (REAPER would ask to overwrite) unlessoverwrite: true, which deletes those files first, and whenboundsistime_selectionwith no time selection. - Render formats:
formatandsecondaryFormat(a second file from the same render;nonedisables it) take wav/aiff/flac/mp3/ogg/opus, with REAPER's default options except the bit depth or MP3 bitratebitDepth/mp3Bitrateset.render_projectrefuses when either is another encoder (seen live: a template's video secondary format left a modal dialog open) — setsecondaryFormat: "none". - Render source and encodings (probed in REAPER 7.40):
sourcemaps toRENDER_SETTINGS(master 0, master_and_stems 1, stems 3 = stems of the selected tracks, selected_via_master 128, region_matrix 8, which needs region bounds, selected_items 32, selected_items_via_master 64; 2 renders nothing in REAPER 7). Bit depth lives in theRENDER_FORMATblob (wavevaw+int16 bits, 32-bit int is 0x21 and float 0x20; aiffffia; flaccalf+int32 bits+compression), MP3 bitrate at bytes 4 and 24 ofl3pm. Normalize target and limit ceiling are given in dB and stored linear (RENDER_NORMALIZE_TARGET,RENDER_BRICKWALL); REAPER hits both exactly. - Render analysis: each rendered file (up to 16) is measured with
CalculateNormalization(target 0 dB, so the gain is the level): LUFS-I, true peak, sample peak;analyze: falseskips it. - Render metadata:
metadatafields (title, artist, album, genre, year, isrc, comment, description) write the matching ID3/INFO/VORBIS/AXML/BWF keys ofRENDER_METADATA;metadataRawsets anySCHEME:KEY; an empty value removes the key. Setting metadata turns on embedding (RENDER_SETTINGS&512) unlessembedMetadata: false. - Render versions:
render_versionsmutes each version's tracks on top of the current mutes and renders to the version's pattern; mutes and the pattern are always restored (the selection is never touched). Use it for instrumental / a cappella / TV mixes instead of muting by hand. - Render is synchronous: action 42230 blocks REAPER (and the bridge) until the render finishes. Keep renders short (a time selection or custom bounds).
targetsinget_render_settingsare the files REAPER will write (RENDER_TARGETS). - Undo: every edit by these tools is one undo point labelled
MCP: …, soundo_projectreverts exactly that edit. Repeat and metronome changes are not undoable in REAPER. - Validation first: invalid input (unknown marker/region/tempo index, BPM <= 0, unsupported format, end <= start) is refused before anything is written.
- Tempo indexes are
get_tempo_mapindexes; a map withtempoMarkerCount: 0holds only the project tempo, set it withset_project_tempo. Adding a marker where one already is replaces it (replacedExisting: true). REAPER can silently keep the start marker on delete;delete_tempo_markerthen returns an error instead of a false success.set_project_temponever usesSetCurrentBPMwith markers present (it inserts a marker at the edit cursor).
Items, Takes & FX Files Concepts
- Logic lives in
reaper/mcp_items_lib.lua(pure Lua over an injected API and file system, unit-tested via wasmoon initems-lib.test.ts); the bridge handlers only passreaper,mcp_plan_lib.luaand a smallio-based file system in. - Validate, then write: every input (track/item/take/FX index, file, color, shape, path) is checked before the first write; a refused call changes nothing and says why. Each write is one undo point.
- Takes:
takeIndexis optional on take FX tools and defaults to the active take. Take FX are separate from track FX. - Fade shapes: 0 linear, 1 fast start, 2 fast end, 3 fast start (steep), 4 fast end (steep), 5 slow start/end, 6 slow start/end (steep); curves are -1..1.
- Files stay inside REAPER's resource folder:
save_fx_chain/save_track_templatetake a name (subfolders allowed) underFXChains/orTrackTemplates/; absolute paths, drive letters and..are refused, and an existing file is only replaced withoverwrite: true. Loads also accept an absolute path with the right extension. - Chunks, like
graft_fxchain: loading a chain or inserting a template edits track state chunks withmcp_plan_lib.lua's helpers, regenerating FXIDs (and TRACKID/item GUIDs for templates). A saved template drops receives (AUXRECV) and folder state (ISBUS), which depend on the surrounding tracks.
Recording & Comping Concepts
- Logic lives in
reaper/mcp_recording_lib.lua(pure Lua over an injected API, unit-tested via wasmoon inrecording-lib.test.ts). - Inputs travel as objects, never raw
I_RECINPUTnumbers:{kind:"audio", channel (1-based), stereo},{kind:"midi", device ("all", "vkb" or an index), channel (0 = all)},{kind:"none"}. An audio channel the device does not have is refused; with no audio device open (0 inputs) it is a warning instead. Answers carry a label ("In 3/4", "MIDI: all MIDI inputs, all channels"). - Punch:
set_record_modetime_selectionrecords only inside the time selection (punchStart/punchEndset it);selected_itemspunches on the selected items. Global toggles 40252/40076/40253. - Fixed lanes (REAPER 7):
C_LANEPLAYS1 = exclusive (the others go silent), 2 = layered. Turning lanes off puts every item on one lane, all playing (warned;undo_projectrestores). REAPER can drop the names of empty lanes, so name lanes once takes are on them. - Comping copies item chunks (GUIDs stripped), trims each copy to its range (take start offset moved by the play rate), extends the left part by the crossfade as far as its source reaches, and keeps the source fades at real item edges. Source lanes stay untouched and silent. A failure after the first write undoes the whole comp (
reaper.comp.undonelog).
Mixing Depth Concepts
- Aligning to a guide (
align_audio_to_guide): the pairing is a monotonic match (dynamic programming) of the guide's hits (project time) to the double's (source time → project time), a pair never further apart thanmaxShiftMs, a hit left alone costingmaxShiftMs. Hits come from each item's source file, so take FX and existing stretch markers are not heard: the double's markers are replaced (re-running is idempotent), a guide that has some is refused.align_stretchskips a hit whose move would cross the previous marker, anchors both item ends, andstrengthscales each hit's move; consonant tails areextrapairs (same shift as their hit, not counted in the offsets).edit_stretch_markersrewrites the whole marker list in order after checking every edit, so a marker's index is the oneget_stretch_markerslists. - Logic lives in
reaper/mcp_mixing_lib.lua(pure Lua over an injected API, unit-tested via wasmoon inmixing-lib.test.ts); the bridge handlers decode the nested JSON params and passreaperin. - Modulation goes through
TrackFX_Get/SetNamedConfigParmkeysparam.N.{mod,lfo,acs,plink}.*(REAPER 6.37+). Reads fail until a parameter has modulation; an unknown key's write fails, so every write is checked and the whole edit is one undo point (seen live: undo removes it). - Pins are bit masks per pin (
TrackFX_Get/SetPinMappings, low and high 32 channels). ReaComp has 4 inputs; pins 2/3 (0-based) are its sidechain and default to channels 3/4. - Freeze and apply FX are native actions on the selection: the lib selects the targets, runs the action, then restores the selection. Both block REAPER while they render (
LONG_RUNNING). A freeze adds a<FREEZEblock to the track chunk per layer; that is howunfreeze_tracksknows a track is frozen. - Quantize: hits arrive in source seconds and map to item positions as
(source - startOffset) / playRate. Each hit moves toward its nearest grid line (with swing) when withinwindow × (1 + swing) × grid / 2(as quantize_midi); hits at the item edges, crossing a neighbour or landing on a line another hit took are skipped. Existing stretch markers are replaced, and anchors at 0 and the item end keep its length. A stretch marker's position is take time at play rate 1 (seen live: source = start offset + position), so the lib multiplies item seconds by the play rate on the way in and divides on the way out; the tools speak item seconds. No hit inside the item is refused, so the item's own markers are never wiped. - Monitoring FX live on the master at index
0x1000000 + i(TrackFX_GetRecCount). They are global to REAPER, not saved with the project.
Envelope / Automation Concepts
- Creating envelopes: Use
create_track_envelopebefore adding points. Built-in envelopes useenvelopeName("Volume", "Pan", "Mute", "Width", "Trim Volume"). FX parameter envelopes usefxIndex+paramIndex. - Logic lives in
reaper/mcp_envelopes_lib.lua(pure Lua over an injected API, unit-tested via wasmoon inenvelopes-lib.test.ts); the bridge handlers only passreaperin. - Envelope values: give
dbon volume envelopes (Volume, Trim Volume, Send Volume). REAPER's own Volume envelope is fader-scaled (716.2 = 0 dB, not 1.0);dbis converted with the envelope's scaling mode (ScaleToEnvelopeMode). Rawvalue: Pan -1.0 to 1.0 in REAPER's envelope sign (positive is left: a track or send panned 50% left starts its pan envelope at +0.5), Mute 0 or 1, FX parameters 0..1. - Automation items: instances of one pool share their points, so editing one edits every instance; pool ids are project-wide, so pools reach across tracks. Point calls use the item index with
0x10000000(one loop iteration = the pool's own points), exceptSetEnvelopePointEx, which ignores a flagged index (REAPER 7.40) and takes the plain one. A new pool'sD_POOL_QNLENis set to the item's length, since REAPER can make it shorter and drops pool points past it without an error; a point at the item end is kept 1 ms inside, and points outside an item are refused. - Section levels (opinionated): pooled automation items on the Volume envelope, one pool per section type, never item gain (
knowledge/workflows/section-levels.md). - Vocal alignment and stretch checks:
align_audio_to_guidethenverify_edit(timeScale= the playback rate); what the pitch, tone and dropout checks mean and when to hand an edit to the user's ear is inknowledge/workflows/vocal-alignment.md(the/editingskill loads it). - Transient-driven automation (lighting):
create_transient_automationfrom a track render (a warped item's file is read without its stretch markers), onto a new muted track's plugin envelope (knowledge/workflows/transient-lighting.md). - Point shapes: 0=linear, 1=square, 2=slow start/end, 3=fast start, 4=fast end, 5=bezier
- Workflow:
create_track_envelope→insert_envelope_point/insert_envelope_points→ optionallyset_envelope_propertiesto arm for writing - Batch operations (
insert_envelope_points): Pass a JSON array of point objects for efficient multi-point automation curves - SWS extension:
set_envelope_propertiesworks best with SWS installed; falls back to state chunk editing without it
Large Response Handling
MCP tool responses must stay within token limits. When a tool could return unbounded data (e.g., all notes in a large MIDI item), apply these patterns:
- Provide an analysis/summary tool: Compute aggregated stats server-side (in Lua) rather than dumping raw data for the AI to process. Example:
analyze_midireturns per-pitch velocity stats, histograms, and machine gun detection — everything Claude would compute anyway — in ~2KB instead of 475KB of raw notes. - Support pagination: Add
offsetandlimitparameters so the client can request data in chunks. Example:get_midi_noteswithoffset=0, limit=100returns the first 100 notes and includeshasMore: trueandtotal: 2044. - Prefer summary-first workflows: Tool descriptions should guide the AI to use the summary tool first, then paginate raw data only when needed for targeted edits.
When adding new tools that could return large datasets, always implement both a summary path and a paginated path. The summary tool should return everything the AI typically needs to make decisions in a single call.
Build System
- Nx 20 with inferred targets via
@nx/eslint/pluginand@nx/vite/plugin - esbuild bundles the server app into
dist/apps/reaper-mcp-server/main.js(ESM, Node 20) - tsc compiles the protocol library to
dist/libs/protocol/ reaper/directory is copied as build assets so thesetupcommand can install bridge files- Nx Cloud enabled for remote caching
Nx Targets
| Target | Inferred By | Description |
build | project.json (explicit) | Build with esbuild (server) or tsc (protocol) |
lint | @nx/eslint/plugin | ESLint with typescript-eslint + Nx module boundaries |
test | @nx/vite/plugin | Vitest (watch: false, passWithNoTests: true) |
typecheck | @nx/vite/plugin | tsc --noEmit |
serve | project.json (explicit) | Run the built server (reaper-mcp-server); for bridge-ui, @nx/vite/plugin infers serve/dev/preview from vite.config.ts, but the page's dev server is pnpm dev:bridge |
Common Commands
pnpm nx build reaper-mcp-server # Build server (bundles protocol dep)
pnpm nx build protocol # Build protocol library only
pnpm nx lint reaper-mcp-server # Lint server
pnpm nx test reaper-mcp-server # Test server
pnpm nx run-many --target=build # Build all
pnpm nx run-many --target=lint # Lint all
pnpm nx run-many --target=test # Test all
pnpm nx run-many --target=build,lint,test # All targets at once
pnpm nx affected --target=build # Build only affected by changesTypeScript Configuration
- Root
tsconfig.base.jsondefines shared settings (ES2022, ESM, strict, bundler resolution) - Path alias:
@reaper-mcp/protocol->libs/protocol/src/index.ts - Each package has its own
tsconfig.jsonextending the base - The server's tsconfig has
referencesto protocol for project references
Adding New MCP Tools
To add a new tool, touch these 8 places:
libs/protocol/src/commands.ts-- Add command type toCommandTypeunion, add params interfacelibs/protocol/src/responses.ts-- Add response data interface if neededapps/reaper-mcp-server/src/tools/-- Create or extend a tool file, register withserver.tool()apps/reaper-mcp-server/src/cli.ts-- Add tool name toMCP_TOOL_NAMESarray (used byensureClaudeSettings()to auto-allow tools)apps/reaper-mcp-server/src/tools/categories.ts-- Add tool name to a category inTOOL_CATEGORIES(the bridge-coverage test fails on an uncategorized tool)reaper/mcp_bridge.lua-- Add handler function in thehandlerstableapps/bridge-ui/src/demo/demo-calls.ts-- Add the command toDEMO_CALLS, so?demologs it: the params an agent would send, or'example'when an example insrc/demo/examples.tsdraws it (a measurement or edit view). The map is aRecord<LoggedCommand, …>, so typecheck fails until it is there. A tool the server composes and logs itself withlogToolResult()goes inLoggedTool(libs/protocol/src/commands.ts) firstapps/bridge-ui/src/features/log/tools.ts-- Add the command toTOOLS: a plaintitle("Delete a track") and adidsentence ("deleted the track “Old Vox”") that the bridge page's drawer leads with. Also aRecord<LoggedCommand, …>. How the drawer shows a call (summary, card, legend, zoom) is in.claude/rules/bridge-drawer.md
Important: Always use z.coerce.number() instead of z.number() for numeric parameters. MCP clients may pass numbers as strings (e.g. "39" instead of 39), and z.coerce handles the conversion automatically.
Tool Registration Pattern
// In tools/example.ts
import { z } from 'zod/v4';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { sendCommand } from '../bridge.js';
export function registerExampleTools(server: McpServer): void {
server.tool(
'tool_name',
'Description of what this tool does',
{ paramName: z.coerce.number().describe('What this param means') },
async ({ paramName }) => {
const response = await sendCommand('command_type', { paramName });
if (!response.success) {
return { content: [{ type: 'text', text: `Error: ${response.error}` }], isError: true };
}
return { content: [{ type: 'text', text: JSON.stringify(response.data, null, 2) }] };
},
);
}A successful write's reply also gets a last text block, Bridge page (before/after view): <url>, added by the tool wrapper (page-link.ts) from the _page the bridge returns; tools need do nothing for it.
Then register in server.ts:
import { registerExampleTools } from './tools/example.js';
// ... inside createServer()
registerExampleTools(server);Lua Handler Pattern
-- In mcp_bridge.lua, add to the handlers table:
handlers["command_type"] = function(params)
-- Use ReaScript API
local result = reaper.SomeApiCall(params.paramName)
return { someField = result }
endPython Sidecar (Semantic Audio Analysis)
An optional long-lived Python subprocess for AI-powered perceptual audio analysis (analyze_track_aesthetics) and offline signal analysis (analyze_track_offline, analyze_audio_file, measure_track_alignment).
Sidecar Architecture
MCP Server (Node.js)
|
| newline-delimited JSON-RPC 2.0 over stdin/stdout
v
Python sidecar (long-lived child process)
|
| loads model once at startup; inference per request
v
Audiobox Aesthetics predictor (CC-BY 4.0)Key Design Points
- Opt-in: The sidecar is installed separately via
setup-sidecar.pnpm installandpnpm nx buildnever touch Python. - Lazy spawn: The sidecar process spawns on the first sidecar tool call, not at server startup; the aesthetics model loads only on the first
analyzerequest. - JSON-RPC methods:
analyze(aesthetics, with optionalnormalizeLufs),analyze_audio(loudness/spectrum/reference,sidecar/analysis.py),align(cross-correlation delay + polarity),verify_edit(sidecar/verify.py: compensated null + discontinuity check on an edit's result),loudness_curve/stereo_bands/masking(sidecar/mixcheck.py),separate(Demucs,sidecar/separation.py: model loaded once per process, CUDA/MPS/CPU with a CPU fallback,REAPER_MCP_SEPARATION_DEVICEoverrides; a separation call gets its own timeout, ~90 s + 3 s per audio second),transients(per-band spectral-flux onsets: low <150 Hz, mid, high >4 kHz, each band scaled to its own 99th percentile so a kick counts as much as a hat; dominant band by mean per-bin log rise; tempo from the onset autocorrelation),chroma(12-bin pitch-class energy, per segment for chords),chords/chords_status(lv-chordia,sidecar/chords.py, opt-in: Harte-labelled segments in file seconds; a range is cut to a temp WAV first; the TS side maps the labels onto the bar/beat grid by largest overlap inchords.tsand takes the key from the chords' tones weighted by duration). - Audio loading: always
soundfile(analysis.load_audio). torchaudio 2.9+ removedinfo()and movedload()to torchcodec, so never calltorchaudio.load/torchaudio.info;torchaudio.functional(filters, resampling) is fine. - Loudness:
analysis.pyimplements ITU-R BS.1770-4 (K-weighting, 400 ms blocks, -70/-10 gates, channels summed) and EBU 3342 LRA;tests/test_analysis.pychecks them against the EBU 3341/3342 reference signals. - Lifecycle: Sidecar receives SIGTERM when the MCP server receives SIGINT/SIGTERM. Managed via
getSidecarClient().shutdown()inmain.ts. - One request at a time:
sidecar.tsqueues requests, so a timeout counts only that request's work; one that waitedQUEUE_WAIT_MS(5 min) behind an earlier request (a long separation) is refused as busy (error.type=busy) and the sidecar keeps running. - Auto-restart: If the sidecar crashes, one restart is attempted automatically. If restart fails, the tool returns a clear error.
- Script refresh: every sidecar spawn first copies the build's
server.pyand modules over the installed ones, so an update (which never re-runssetup-sidecar) cannot leave an oldserver.pywithout the new methods. - Install location: Venv at
~/.reaper-mcp/sidecar-venv/, scripts at~/.reaper-mcp/sidecar/(server.pyplusSIDECAR_MODULESinsetup-sidecar.ts, e.g.analysis.py— add a new module there). - PYTHON_BIN env var: Override the Python interpreter used by
setup-sidecar. Without it,setup-sidecarandreaper-mcp doctorusepython3; on Windows they fall back throughpython3,python,py(resolvePythonBin) becausepython3is often the Microsoft Store stub.
Source Files
| File | Purpose |
apps/reaper-mcp-server/sidecar/server.py | Python sidecar JSON-RPC server (source) |
apps/reaper-mcp-server/sidecar/analysis.py | Loudness (BS.1770, LRA, true peak), spectrum hints, reference comparison, alignment, normalization (numpy/torch only) |
apps/reaper-mcp-server/sidecar/requirements.txt | Pinned Python deps |
apps/reaper-mcp-server/src/sidecar.ts | Node.js subprocess lifecycle + JSON-RPC client |
apps/reaper-mcp-server/src/setup-sidecar.ts | setup-sidecar CLI command implementation |
apps/reaper-mcp-server/src/tools/aesthetics.ts | analyze_track_aesthetics tool registration |
apps/reaper-mcp-server/src/tools/offline.ts | analyze_track_offline, analyze_audio_file, measure_track_alignment, verify_edit |
apps/reaper-mcp-server/src/tools/transients.ts | detect_transients, create_transient_automation (pulse generation in pulsePoints()) |
apps/reaper-mcp-server/sidecar/verify.py | Compensated null and discontinuity checks for verify_edit (numpy only; with timeScale != 1 the null is replaced by pitch drift (NSDF tracker, range from the reference), tone (40-mel long-term spectrum) and transient (spectral-flux peakiness, drops only) checks, thresholds from the issue 81 experiment; the click check leaves out the window's first and last maxLagMs, the null twice that) |
apps/reaper-mcp-server/sidecar/mixcheck.py | Loudness curve, per-band stereo correlation, third-octave masking (numpy only) |
apps/reaper-mcp-server/sidecar/separation.py | Demucs stem separation (soundfile I/O, never demucs's torchaudio I/O) |
apps/reaper-mcp-server/src/tools/mixcheck.ts | analyze_loudness_curve, analyze_stereo_bands, measure_masking, separate_stems |
Render Pipeline
The sidecar tools render a track segment to a temp WAV via the render_track_to_wav Lua bridge handler (a track renders as a stem — render mode 3, stems of the selected tracks only, so the target is soloed and made the only selected track; mode 2 lists no target in REAPER 7 and falls back to the master mix, which renders silence for a track that reaches the master only through sends; -1 renders the master mix, mode 0, with every solo cleared; solo and selection are restored after), then pass the path to the sidecar. REAPER can only render through its progress window, which takes focus, so mcp_render_lib.lua renders as rarely as possible: a cache hands the same render out again (per track and range) until the project changes (any bridge command that writes, REAPER's own GetProjectStateChangeCount, a 10 min TTL or a missing file), render_tracks_to_wav renders several tracks that do not feed each other (no folder or send between them) in one stem pass (the files are told apart by $tracknumber in the pattern and RENDER_TARGETS; a naming it cannot predict falls back to one render per track before anything is rendered), and on macOS the app that had focus is brought back afterwards when REAPER's render window now has it (lsappinfo + open -b; someone who switched apps meanwhile is left alone; restoreFocus: false opts out). The bridge's cache owns its files (results carry cacheOwned: true): tools call discardRender() (src/render.ts), which deletes only a file the cache does not own, so never unlink a render yourself. fresh: true skips the cache.
Dry reads (dry: true, RenderOptions in render.ts; REAPER_MCP_DRY_READ=0 turns it off): tools that only need a track's own audio (detect_transients, create_transient_automation, detect_key, detect_chords) ask the bridge to read it with an audio accessor (dry_read in mcp_render_lib.lua) instead of rendering: item audio as it plays (stretch markers, rate, item volume and fades, take FX, the track's polarity and playback offset applied) before track FX, pan and fader, written as a 24-bit stereo WAV, no dialog, no focus change. Checked live against real renders: exact (≤1 LSB) on plain, trimmed, rate-changed, stretch-marked and take-FX items, with offset and polarity. Eligible: a normal track, ≤120 s, at least one audio item and no MIDI item in the range, take FX only REAPER's own (JS:, Cockos; a third-party take FX such as Melodyne made the accessor return silence, seen live), not a folder parent, no audio arriving by send, and no junction (the accessor cannot hear a folder's children, sends or instruments). Anything else falls back to the real render (result dry: false). verify_edit always renders both sides: an edit made with track FX or the fader only exists in a render. Cached under its own |dry key. Post-FX tools (LUFS, masking, spectrum, aesthetics, separation, alignment) keep real renders.
REAPER 7.40 accessor quirks (found live; dry_read / dry_eligible work around them): (1) a read that crosses an item's end gets that item's source played on past the end, up to the read's end, so dry_read silences every frame no item covers (silence_outside); (2) where one item ends and another plays on right after it (a split, a crossfade, an overlap) that run-on is audio of a different, random level each read, even for reads cut at the item boundary, so a range with such a junction (an item ending between start - 0.5 s and stop with another item playing within 5.5 s after it, JUNCTION_MARGIN / JUNCTION_REACH) is rendered. Reads that start after the junction or end before it are exact. A render started in the middle of an item with a playback offset has an empty delay line (its first |offset| s are silent), which a dry read does not copy.
The render_track_to_wav Lua handler uses Main_OnCommand(42230) which is synchronous — it blocks the defer loop during render (~0.5-1s for a short clip; a 4-minute folder track took ~55 s, so offline.ts scales the timeout with the range). This is expected behavior documented in the handler.
Future Phases
The sidecar architecture admits new JSON-RPC methods easily — future phases (CLAP, MERT, Demucs, Parakeet, Essentia) just add new methods to server.py and new tools in TypeScript. The IPC channel and subprocess lifecycle are shared infrastructure.
Extensions
Opt-in add-ons for things that don't belong in core (one synth, one workflow): docs/EXTENSIONS.md has the manifest, the
API, the trust model and the Vital extension. In short: reaper-mcp serve loads every folder in ~/.reaper-mcp/extensions/
(extensions.ts), each registers tools as <name>_<tool> through ExtensionApi (libs/extension-api), and reaches REAPER
with api.bridge() (core commands), api.call() (its own Lua, via the internal extension_call) and api.fxState
(VST3 state). A broken extension is skipped, never fatal. Extension tools are not core tools: they are not in MCP_TOOL_NAMES,
the tool count or TOOL_CATEGORIES (each registers its own category at load).
- Boundary: a
type:extensionproject may depend only ontype:extension-api(eslint). Never import core into one. - Internal commands
get_fx_state,set_fx_state,extension_callare bridge commands, not MCP tools. Saved state moves asfxstate_*files in the bridge folder, never in the command JSON. - VST3 state: after changing a state's size fix its two length fields and give the FX a new
FXID, or REAPER silently keeps the old state (libs/extension-api/src/vst3-state.ts,fx-state.ts).
Spectrum Analysis (JSFX + gmem)
The JSFX analyzer (mcp_analyzer.jsfx) runs in REAPER's audio thread:
- Performs configurable FFT (512-8192 bins, default 4096)
- Writes magnitude spectrum to
gmem[]under namespaceMCPAnalyzer - gmem layout: one 4100-value block per track at
(trackIndex + 1) * 4100(master = 0; the bridge sets the slot on slider4):[bin_count, peak_dB, rms_dB, bin[0], bin[1], ...], bins in frequency order (fft_permuteafterfft_real) - The "MCP Meters" container holding the meters is force-enabled on every read: REAPER 7.40 creates it bypassed when it is a track's only FX
- Lua bridge reads via
reaper.gmem_attach("MCPAnalyzer")+reaper.gmem_read() - Auto-inserted by
read_track_spectrumtool, passes audio through unmodified
Live MIDI Output (JSFX + gmem ring buffer)
The MIDI emitter (mcp_midi_emitter.jsfx) uses a 16-slot ring buffer — the reverse direction of the analyzers:
- Lua bridge writes 3-byte events; JSFX reads and emits via
midisend()in@block - Namespace
MCPMidiEmitter; gmem layout:[write_head, read_head, slot0_status, slot0_d1, slot0_d2, ...] write_midi_to_ring(status, d1, d2)inmcp_bridge.luais the single write path — use it for all MIDI event types- Deferred note-off (
send_midi_notewithdurationMs) uses the same ring path; no separate code path - Auto-inserted by all three live MIDI tools via
ensure_jsfx_on_track(track, MCP_MIDI_EMITTER_FX_NAME)
Bridge Status Page (REAPER web interface)
reaper-mcp setup installs mcp_bridge.html into {REAPER_RESOURCE_PATH}/reaper_www_root/ and enables
REAPER's web interface by adding csurf_N=HTTP 0 8099 '' 'mcp_bridge.html' 0 '' to reaper.ini (port via
REAPER_WEB_PORT; an existing HTTP surface is kept). It only edits reaper.ini while REAPER is closed — REAPER
rewrites it from memory on exit. On start the bridge opens the page as a small Chromium --app window (falls back to
the default browser; toggle OPEN_UI_ON_START) and only uses the ReaScript console when the web interface is missing.
?demo previews the page with fake data: a fake bridge whose log holds a call of every command (DEMO_CALLS) and every
example, with new calls drawn from them.
Developing the page or the bridge: run pnpm dev:bridge (Vite's dev server on apps/bridge-ui/vite.config.ts, plus
vite-reaper-dev.mjs) and open http://localhost:8098/mcp_bridge.html, never REAPER's own :8099 page. Without
REAPER, open http://localhost:8098/mcp_bridge.html?demo (every tool and view in the log). It prints both URLs on start.
- Vite hot-reloads components on save (React Fast Refresh), and reloads the page for anything else.
- It proxies
/_/*to REAPER over one keep-alive socket (http.Agent,maxSockets: 1) and never aborts an upstream request. Aborting closes the socket from the client side, the one close REAPER's web server never frees (see Stuck sockets below); a browser talking to REAPER directly hangs up on every reload, idle drop, and devtools refresh. This is why it is a middleware of its own, not Vite'sserver.proxy, which passes each client hang-up on to REAPER. - A saved
reaper/file listed inREAPER_ASSETS(cli.ts, read as text) is copied into REAPER: Lua intoScripts/, then the running bridge is asked to restart with the token from its status feed; JSFX intoEffects/reaper-mcp/, where it loads only when the plugin is re-added. - Production (
nx build bridge-ui), dev, vitest and Storybook all compile with the React Compiler and read the same constants frombuild-config.mjs; Storybook inheritsvite.config.tsand drops only the single-file and REAPER plugins. - React Compiler: write plain components, no
useMemo/useCallback/memofor speed.eslint-plugin-react-hooks(recommended) enforces the Rules of React it relies on: no state set in an effect body (derive it while rendering), no ref read or written while rendering,useEffectEventfor an effect's latest-value callback. A component the compiler cannot handle fails the build and tests (panicThreshold: 'all_errors'inbuild-config.mjs); known triggers are a conditional (?:,&&,?.) inside atryblock (usefetchText()fromsrc/lib/fetch-text.ts), a variable incremented inside a callback, anda && "x"lists inside JSX attributes (build them beforereturn). - Overrides:
BRIDGE_DEV_PORT(default 8098; when it is taken the dev server takes the next free port, never REAPER's, and prints the URL),REAPER_WEB_PORT(8099),REAPER_RESOURCE_PATH.
# correct: the page talks to the dev server; REAPER sees one connection all session
pnpm dev:bridge # then open http://localhost:8098/mcp_bridge.html
# incorrect: reloading REAPER's page or scripting it with curl leaks one REAPER socket per hang-up
open http://localhost:8099/mcp_bridge.html; curl http://127.0.0.1:8099/_/GET/EXTSTATE/MCPBridge/status- Dedupe: every page poll is
SET/EXTSTATE/MCPBridge/ui_seen/<ms>;GET/EXTSTATE/MCPBridge/status; the bridge skips opening a window whenui_seenis under 6s old (the page keeps pinging every 2s while hidden). - Stuck sockets: REAPER's web server never frees a socket whose client hung up first (curl, Chrome dropping an idle
connection); it stays in CLOSE_WAIT/CLOSED, and near 100 the server stops answering until REAPER restarts. The
bridge counts them every 30 s (
web_watchinmcp_bridge.lua:lsofin the background intomcp_bridge_data/web_sockets, macOS/Linux) and publishesstatus.web = { stuck, limit }; the page warns from 50% (webSocketLevel()insrc/lib/status.ts) and the bridge prints one console line at 90%. Test scripts that hit the web server reuse one connection (onecurlwith several URLs), or each request leaks a socket. - The bridge publishes JSON to non-persistent ExtState
MCPBridge/status(in memory, no disk IO): counters, defer-loop timing, and the last 50 commands (nseq, type, handler ms, ok, error). Throttled to ≤5 Hz and only when something changed, plus a 1s liveness tick._-prefixed internal commands are excluded. - The page polls
/_/GET/EXTSTATE/MCPBridge/statusevery 500 ms (paused while the tab is hidden), keeps its log in the browser (the bridge's newest 2000, more as older segments load), and renders entirely outside REAPER — no gfx/ImGui redraw on the main thread. - Persistence: every logged command is appended to
<bridge dir>/history_log.jsonland the timeline is saved tohistory.json(every 30s and on exit); both reload on start and are pruned to 7 days, andncontinues across restarts (also saved inhistory.json). The newest 2000 commands stay in memory and inhistory_log.jsonl(which holds exactly them); when it outgrows that, the oldest 500 rotate into a segment filehistory_log_<first n>_<last n>_<last t>.jsonl(a segment goes once its newest entry is past the 7 days). The memory part is published as ExtStateMCPBridge/log(newest first, witholder= segments exist) only on request: the page writesMCPBridge/log_want/<ts>on open, after a bridge restart, and when the 50-entry window skipped entries; the bridge answers once withreqechoing it, and the page keeps only the answer to its latest request. Older commands load one segment per request, on demand: the end of the Calls list is a sentinel (IntersectionObserver rooted in the list, a screenful ahead) that asks while the range or selected span reaches further back than the page holds (needOlderinLog.tsx), showing a loading row; the page writesMCPBridge/log_older/<id>-<oldest n it holds>and readsMCPBridge/log_page({req, entries, more});useBridgeFeedkeeps the cursor andloading. The page holds at mostLOG_MAX(10,000) entries. - Timeline: per-10s buckets for the last hour (sparse,
[id, total, errors, slow, sumMs]) in ExtStateMCPBridge/history(≤ 1 Hz), and 1m (24h) + 10m (7d) tiers inMCPBridge/history_long(≤ every 10s, polled every 10s). The page draws each range (5m–7d, a listbox combo box) from the finest tier covering it (timelineBars()); dragging across bars selects a span that filters the log views, leaving the range unchanged. Without a span the Calls and Tools views (and their counts) show the range too; older matches end the list with a button that widens the range to the next one that includes them. - URL state: navigation state lives in the query string via
useUrlState(key, default, { validate })insrc/lib/url-state.ts(a History API port of LoreKit web's hook: JSON values, text bare (?release=0.78.2) unless it would read back as a number or flag, a value equal to the default is dropped, changes in one tick become one history entry), so Back/Forward step through it and a link or reload reopens it. Params:view,range,span(dragged timeline span),filter(all/errors),q(search; replaces, never pushes, written to the URL 300 ms after typing pauses viadebounceMswhile the page updates at once; each view keeps its own search, so switching views never carries one over),agent,entry(open command byn),sort(Tools),settings,developer(Developer drawer open),changelog(What's new open) andrelease(the release a version click links to: scrolled to and highlighted), on the docs pagegallery+card(a guide gallery's full screen view, by title and card name; opening and closing push, moving between cards replaces), and on Pluginscoverage,inProject,plugin(open plugin by FX name). Opening, closing or switching a drawer by click (a row, "Previous call") pushes; ↑/↓ between rows replaces.viewandrangedefault to the last pick in localStorage, so the bridge's baremcp_bridge.htmlopens where you left off. Use it for any new state a viewer would want to go back to or share (tabs, filters, an open drawer); keep transient UI (hover, drag, copied flags) and per-viewer preferences (grouping, tokens) inuseState/localStorage. Give each param avalidateguard so a stale or hand-edited link falls back to the default, and keep keys unique across views. - Command palette and shortcuts (
src/features/command/, rules in.claude/rules/command-palette.md): ⌘K opens the palette,?the shortcut sheet,gthenc/t/a/p/sgo to Calls/Tools/Sessions/Plugins/Snapshots,/fpjkcact in the view. Every view and action registers withuseCommand(palette entry); only frequent ones get a key. A new view, tab or action adds its command in the same change. - Search (
parseQuery()/matchesQuery()insrc/lib/search.ts): space-separated terms, all must match. A word matches the command name, error or params text;key:valuematches one param exactly (trackIndex:6is not 16; quote values with spaces,fxName:"VST3: Pro-Q 3"). Selecting text in a command's Params offers Filter (the whole param when the selection is on one"key": valueline,termFromSelection()), which adds the term toqwith a push. - Measurement results: the bridge keeps a compact result
r(built inreaper/mcp_edit_views_lib.lua, which keepsmcp_bridge.luaunder Lua's 200-locals limit) on meters/LUFS/correlation/crest/spectrum entries (RESULT_FIELDS, 48 spectrum bands) and, forrender_track_to_wav, a waveform read from the WAV before the server deletes it (wav_waveform(): 120 min/max slices, peak/RMS dBFS, clipped sample count; drawn on a dB scale to −48).render_tracks_to_wavkeeps one coarser waveform per track (≤8 tracks, 60 slices, read within a 1 s budget, the rest counted asmore), drawn asWaveforms: one lane per track on a shared axis, the previous call's lane of the same name dashed.src/features/measurements/draws them (one component per kind), colored by value (amber from −6 dB, red at 0), with the previous call on the same track ghosted (dashed/hollow) and its headline value and change in a "Previous call" line. Add a measuring command inRESULT_FIELDS,MEASUREMENTS(src/lib/commands.ts), aMeasurementkind and an example insrc/demo/examples.tstogether. Sidecar tools the server composes itself (analyze_track_offline,analyze_audio_file,measure_track_alignment,analyze_track_aesthetics, and the mix checks) never pass through a bridge handler, so the server logs each result with the internal_log_resultcommand (apps/reaper-mcp-server/src/tool-log.ts, fire-and-forget;rtravels as a JSON string), which the bridge records as an entry for that tool (record_tool_result()). Their compactris built byofflineSummary()/alignmentSummary()/aestheticsSummary()and drawn as theoffline/alignment/aestheticsmeasurements; the mix checks bycurveSummary()/stereoBandsSummary()/maskingSummary()/stemsSummary()ascurve(the short-term line against the target, spans over it shaded),stereo(correlation per band on −1…+1),masking(a pairs × bands heat map) andstems(each stem's LUFS, speed, inserted tracks). - Edit views: writes and listings also keep an
r(M.summaryinmcp_edit_views_lib.lua), drawn bysrc/features/edit-views/(EditViews.tsx, one view per kind inviews/) fromeditViewOf()(edit-views.ts). A write reads the state it touches before its handler runs (M.before) and again after, so the drawer shows before → after: track and FX parameter changes (the plugin's own readout; faders and pan dots show their value on hover,HoverTip), the automation window an edit touched (padded 25%, at least 4 s; automation items drawn as blocks tinted by pool with their name and shared curve, moved/deleted items and a changed pool's old curve dashed, items the call left unchanged dimmed), MIDI notes as a piano roll (first 256,morecounts the rest; added notes solid, removed dashed),analyze_midivelocity per pitch, markers/regions/tempo/items on one timeline,list_tracksas a mixer,set_selected_itemsas item lanes (items selected now solid, selected before dashed, the rest dimmed;picked/wasPickedper lane), andrun_plan's ops; also FX chains (add/remove/move/copy/bypass/offline/rename/preset,get_track_properties: slots marked added/moved/changed/removed by FX GUID), item edits as one lane per touched track with the items before dashed, track structure edits on the mixer (tracks diffed by GUID), routing (a signal-flow diagram — receives wired in on the left, sends and hardware outs out on the right, wires as thick as their level; hovering a name or wire shows its level and pan and marks its row, hovering a row lights its wire — over rows grouped under Receives from / Sends to / Hardware outputs with level bars, the old level ghosted), the time selection and edit cursor, MIDI CC as a stepped lane in beats (the automation view, unitcc), andget_fx_parametersas readout bars;render_project/render_versionsas a render result (one row per file, ≤8: mini waveform fromPCM_Source_GetPeaks, tapered to silence at both ends, hover for time and peak, LUFS-I against the normalize target, true peak against the limit ceiling, length; versions grouped with their muted tracks; format, source and target as readouts); and arrangement edits (op, thespanthey opened, cut or copied from hatched or outlined, where they copiedto, a lane for up to 4 touched tracks plusmoreTracks, normalized items with their gain as a 7th item field); FX modulation (LFO path, audio-follower band, link, the old baseline ghosted), FX pins as a patch (track channels wired into the plugin's input pins and out of its output pins, only connected ones drawn; new wires lit, disconnected dashed, added channels marked; hovering a pin or channel names its wiring), stretch markers andquantize_audio(grid lines, hits before dashed, offset before → after), freeze / automation mode / apply FX as change rows, record setup as one row per armed track (input, monitoring, record mode; the old value struck through, ≤32 plusmore) under the global mode and punch range, and fixed lanes as one row per lane (≤32 plusmore) with which lanes play and, forcomp_lanes, each comp part tinted by the take it came from. List diffs sharelistDiff()inedit-views.ts. Lists are capped so an entry stays a few KB. Add a command inM.summary,KIND_OF(edit-views.ts) and an example insrc/demo/examples.tstogether; behaviour tests run the real bridge in wasmoon (bridge-status.test.ts, "edit views in the log"). - Short windows (≤ 640px tall, an app window docked beside REAPER): the log is the page. Stats, timeline and footer
hide; the header's Rebuild & reload, Settings and GitHub fold into a ⋯ menu (
HeaderMenu, dotted when a rebuild is available) with a Stats & timeline toggle (mcp-bridge-overviewin localStorage). The log's toolbar is one row: a grouped combo box (Combobox.Grouped, LoreKit's Combobox in headed groups: View, Show, Agent, Actions) and the search box. CSS switches it:@media (max-height: 640px). - Narrow drawer: the drawer is resizable, so its content answers to its own width with container queries
(
.drawer-bodyand.measureareinline-sizecontainers), never@media. Under ~300px readouts go two a row, the mixer drops its pan column, and what gives way stays reachable (the ISO timestamp is the When row's tooltip, marker labels that would collide —fittingLabels()inedit-views.ts— show on hover; on item and selection views, where markers are only context, every marker name waits for hover). Under ~460px mixer and route rows drop their added/moved/changed word for a coloured edge plus one legend (ChangeLegend), so names stay readable. Structure edits in a big project draw a 64-row window around the change (from). Check new views at ~300px with theirNarrowstory. - Components: a feature's parts nest under its main component (
Object.assign(LogView, { Rows, Details, … })in the folder'sindex.ts), or under a plain object when there is no main one (EditView.Section,Icon.Gear). Add a new part to its folder's namespace, and import a feature from itsindex.tsonly, never its files (inside a folder, files import each other directly; an index importing a sibling feature's index is fine, a cycle is not). - Styles: CSS modules (Vite, in the page build, Storybook and vitest alike). A component imports its
own
<Name>.module.cssasstylesand any other module as<name>Styles(chartStyles,drawerStyles), and joins classes withcx(styles.row, selected && styles.rowSelected). State that picks a colour or a variant is a data attribute styled from the module, never a class built from a string:data-outcome,data-zone,data-change,data-tone,data-state,data-coverage,data-kind,data-speed,data-align(as.row:where([data-outcome="error"]), so a variant weighs what a one-class modifier would and a later.rowSelectedstill wins).src/styles.csskeeps only tokens, base element styles and utilities used everywhere (mono,muted,count,btn/btn-sm/icon-btn/link-btn,sdot/hue-N,kdot,tone-*); add to it only what is truly global. A module styles only its own classes: to restyle another component's part, give that part a class of your own (cx(chartStyles.evFill, styles.offAlignFill)) or reach a global with:global(.mono). Order is the cascade:main.tsx(and.storybook/preview.tsx) imports the root sheet, then the sharedstyles/modules, then each component brings its own, so a component's class wins a tie with a shared one. - Storybook (
pnpm storybook, port 6006;nx build-storybook bridge-ui→dist/storybook/bridge-ui): every component insrc/components/andsrc/features/has a sibling<Name>.stories.tsx, written against the namespace (component: Measurement.Loudness) (aDefaultstory with every state side by side, and aPlaygroundwith controls); behaviour lives in<Name>.test.stories.tsx(title…/Tests,tags: ['test']) as play functions.src/test/stories.test.tsxruns every story and play function in vitest (composeStories, jsdom), so the stories are the components' tests: assert what a viewer sees and can do (roles, names, text), never CSS classes or internal state. Stories draw fixed data:src/demo/examples.ts(measurements, edit views, drawer, Snapshots states;measuredExamples()/editExamples()per kind) andexampleFeed()insrc/demo/feed.ts(the?demobridge on a frozen clock and seeded dice).examples.test.tsfails when a measuring command or an edit view kind has no example. - Slow (≥100 ms) / very slow (≥500 ms) marks skip commands that are slow by nature (renders, plugin loads, project
IO,
run_plan/run_action):LONG_RUNNINGinsrc/lib/commands.tsandmcp_bridge.lua, kept equal bystatus.test.ts. - Installable PWA:
apps/bridge-ui/public/(manifest, service worker, icons) is copied next to the page; every file ismcp_bridge*and the service worker is scoped to/mcp_bridgeso REAPER's other web remotes are untouched. - Sessions: each
reaper-mcp serveprocess tags every command with flat top-levelsessionId/sessionDir/sessionClient(from Claude Code'sCLAUDE_CODE_SESSION_ID/CLAUDE_PROJECT_DIR, elsepid-<n>/ cwd — no hook needed) and pings_sessionevery 20s plus a goodbye on exit (apps/reaper-mcp-server/src/session.ts). The bridge keeps the last hour of sessions in the status; the page shows connected agents, per-session chips, and Calls / Tools / Sessions views. Entries also carrys(session) andp(params JSON, truncated to 400 chars). - Settings the page writes via
/_/SET/EXTSTATE[PERSIST]/MCPBridge/<key>/<0|1>, echoed back instatus.settings:cfg_paused(in-memory: every non-_command fails until resumed or REAPER restarts),cfg_readonly(persistent: onlyget_/list_/read_/analyze_/search_/measure_+ transport/navigation pass —readonly_allows(), mirrored bycommandKind()insrc/lib/commands.ts),cfg_open_on_start(persistent, overridesOPEN_UI_ON_START),cfg_autostart(persistent, default on: read at REAPER's launch by the blocksetupwrites at the top ofScripts/__startup.lua—AUTOSTART_BLOCK/ensureBridgeAutostart()incli.ts— which runsmcp_bridge.luaas its own action unless it is"0"; the bridge only echoes it assettings.autostart). Desktop error notifications are page-side (Notification API + localStorage). status.health(re-checked every 10s): SWS present, JSFX installed inEffects/reaper-mcp/(or itsMeters/folder, where ReaPack puts them),autostartwhenScripts/__startup.luaholds the startup block (the Settings toggle explains how to add it when not), andoutdatedwhen the installedmcp_bridge.luadiffers from the running copy (setup ran; restart the script). Tested in wasmoon bybridge-status.test.ts.- One-click update and restart (
status.control): the page checks GitHub's latest release, or npm's for an npm install (cached 6h in localStorage,src/lib/update.ts) and offers Update; the outdated notice offers Restart bridge. The page writes/_/SET/EXTSTATE/MCPBridge/request/<update|restart>-<token>; the token is random per bridge run and only readable from the status feed (REAPER's web server sends no CORS headers), so other sites can fire the request but never with a valid token. Update runs<clone>/scripts/update.sh(stashes uncommitted changes onmain,git pull --ff-only,git stash apply, theninstall.sh; a conflicting apply is reset and the work stays in the named stash; refuses uncommitted changes offmain;scripts/test-update-clone.sh) detached, with the clone path, or for an npm installmode=npmwith the node and CLI paths, fromScripts/mcp_update.conf(written bysetup; never on Windows). The bridge starts withset_action_options(1)(REAPER 7.03+), so re-runningmcp_bridge.luastops it; restart switches toset_action_options(3)and re-runs its own action, and REAPER relaunches the installed copy. It restarts itself after a successful update; a developer rebuild reloads the page whenstartedAtchanges (or once when the update is done, if the bridge script didn't change). What's new (?changelog=true,src/features/changelog/): a drawer listing the GitHub releases (one request,releases?per_page=100, only once it opens, cached 6h in localStorage), each release's## What's Changedlines parsed as conventional commits and grouped New / Fixes / Faster / Docs / Under the hood (changelog.ts), betas behind a per-viewer toggle. Its top card offers the update (the sameupdaterequest, or the clone and npm commands when the bridge can't run it). A newer stable release shows an Update available pill in the header that opens it; the notice's What's new link, the ⋯ menu, the palette (help-whats-new), the footer version and, for 30 s after the page reloads onto an updated version, a See what's new toast (UpdateToasts, once: the update leaves the old version in sessionStoragemcp-bridge-updated-from) open it too. Opening it closes Settings. Highlights (highlights.ts,HighlightCard.tsx): hand-made entries over a release's notes, one house-style card each (16:10 stage, title, sentence, "Try it"; click to enlarge) with an animation (.mp4/animated SVG + poster), graphic (.svg) or screenshot (.webp). Data:apps/bridge-ui/changelog/highlights.json+media/, read frommainon GitHub (so a newer release shows its highlights before the update) or the working tree under the dev server; matched to a release byprorversion. Written by the repo-only/changelog-highlightskill withapps/bridge-ui/scripts/changelog-capture.mjs(records/captures?demo);highlights-files.test.tschecks every entry, media size and SVG safety. Developer mode (settings.dev):setupwritesdev=1for a clone with uncommitted changes, a branch other thanmainor unpushed commits (isDevClone()incli.ts); the Settings toggle (cfg_dev, persistent) overrides it. In dev mode the release notice is hidden and, once source files are newer than the last install (a detachedfind -newer mcp_update.confevery 5s,control.changed), the header shows Rebuild & reload (requestrebuild-<token>):update.sh --rebuildbuilds the working tree as it is (--skip-nx-cache) and runssetup, no git involved. - Missing sidecar: a sidecar tool that fails because the Python sidecar (or one part) is not installed answers the agent with
sidecarNotInstalledMessage()(sidecar-hint.ts: what is wrong, that the user runs the command, do not retry), andinstrumentToolHandlerslogs a one-linesidecarMissingLog()entry on the page (the early checks never reach the bridge). The page turns it into a notice and a drawer fix (features/sidecar/,lib/sidecar.ts:missingSidecar()/isSidecarMissing()mirror the server's regex). Install sendssidecar/sidecarsep/sidecarchords/sidecarlite(request/<action>-<token>); the bridge runsnode <cli> setup-sidecar --yes [--with-separation|--with-chords|--without-aesthetics]detached (sidecar_jobinmcp_bridge.lua,sidecar.log/sidecar.exit) and publishescontrol.canInstallSidecar+control.sidecar({kind, state, log}). Needs the CLI frommcp_update.conf(npm install, or a built clone); not on Windows. This and the update are background jobs: one pattern, one set of shared components (jobToastand friends incomponents/JobToast.tsx), documented in.claude/rules/background-jobs.md. A new job follows it. - Plugins tab: the bridge publishes every installed FX (native
EnumInstalledFX, REAPER 6.37+; the same listlist_available_fxreturns) to ExtStateMCPBridge/installedas{v, supported, fx:[{n,t}]}, re-enumerated every 60s and republished only on change (.jsfx-inclibraries are skipped). FX in the open project (track, master, input and take FX, by original name viafx_name) go to ExtStateMCPBridge/usedas{v, fx:[{n,c}]}, recounted when the project state changes; the page pollsusedevery 5s andinstalledevery 30s. Rows group by creator (record vendor, else REAPER's(Vendor)suffix), project plugins first, with Teach prompts per row, per creator and for all. Plugin records come straight from LoreKit's REST API (GET /memories, which allows browser origins — the server's/mcpendpoint does not): the built-in layer with the public token, whichbuild-config.mjsreads out oftools/knowledge.tsat build time, and the viewer's ownuser::records only with their ownlk_ro_token from Settings (kept in~/.config/reaper-mcp/lorekit.jsonby the bridge; thelk_rw_publish token stays in localStorage, as REAPER's web port answers anyone who reaches it,reaper/mcp_prefs_lib.lua, so the dev server, REAPER's page and an installed app share it; localStorage is the offline copy). Records link into LoreKit by row id. The tab stays hidden until the bridge has published its list. Contribute N (with a token, when you haveuser::records) opens GitHub's new-file page with them as one file underknowledge/contributions/(format and checks:apps/bridge-ui/src/features/plugins/plugin-contributions.mjs), so GitHub forks and opens the PR. Theplugin-contributionsworkflow (pull_request_target, never runs PR code) comments what would be published; the maintainer'spublish-to-lorekitlabel writes them to the built-in layer with secretLOREKIT_PUBLISH_TOKEN(lk_rw_, a writer in thereaper-mcporg) and closes the PR. Files a maintainer commits straight tomainare published by running the workflow by hand (workflow_dispatch, jobpublish-main, optionaldry_run): it publishes every file in the folder and removes them in one bot commit. Records too long for the URL open with a paste prompt (PASTE_HEREinsrc/features/plugins/contribute.ts) and are on the clipboard. Client:src/features/plugins/lorekit.ts, hook:src/features/plugins/useKnowledge.ts, matching:src/features/plugins/plugins.ts. Members of thereaper-mcpLoreKit org can skip GitHub: anlk_rw_token under Settings → Publish to built-in (localStorage, separate from the read token) adds a Publish to built-in button to their own records. It runs the sameparseContributionchecks,POST /memorieswithorg: reaper-mcp, then soft-archives theuser::copy (opt-out checkbox). LoreKit enforces write membership; add a publisher by inviting them to the org as a member. With that token the header's Contribute N becomes Publish N to built-in: one inline confirm, then each record in turn (publishAll(), carries on past a failure, offers Retry for the failed). Settings links non-members to ask on Discord or through thecontributor-requestGitHub issue form (.github/ISSUE_TEMPLATE/contributor-request.yml). Logic:publishRecord()insrc/features/plugins/lorekit.ts;?demofakes it. One plugin installed in several formats (same title and vendor, e.g.VST3i:/CLAPi:/VSTi: Vital (Vital Audio)) is one row (PluginRow.variants, VST3 preferred for the Teach prompt), counting the instances of every format. - Snapshots tab (
view=snapshots, shown whenstatus.control.snapshots): lists the project's snapshots, loads one with a click or Shift+1–9(A/B/C while listening) and saves the current mix (name + optional description; a name that saves to an existing file asks to replace it; a blank name saves under the date and time,timeSnapshotName(), the same name the quick-save action gives). Each row renames (name + description,snapshot_edit) or deletes (inline confirm,snapshot_delete). While the view is open the page pings ExtStatesnap_seen/<ms>and readssnapshotsonce a second; the bridge re-reads the folder about once a second while pinged (a file is decoded again only when its size changed) and rewritessnapshotsonly when the list, the current snapshot or a result changed. Requests:snap_req/<id>-<token>-<op>-<hex field>[-<hex field>…]with the per-run control token (restore/delete: name; save: name, description; edit: name, new name, description); the bridge runs it as an ordinarysnapshot_restore/_save/_delete/_editcommand through the dispatcher (run_command()), so it is logged (entrysrc: "page"), one undo point, and refused while read-only or paused, then answers insnapshots.result(echoingid). A successful restore from anywhere becomescurrent(ExtStateMCP_Snapshots/current_name, which the next/prev actions continue from). Logic:reaper/mcp_snapshots_ui_lib.lua; page:src/features/snapshots/(snapshots.ts,useSnapshots.ts,SnapshotsView.tsx); tests:bridge-snapshots.test.ts(wasmoon),snapshots.test.ts.snapshot_savewrites metadata (name, description, timestamp, trackCount, scoped, fullChunk) ahead ofmixerState. - Usage statistics:
src/lib/analytics.tsis the only module that imports@dash0/sdk-web(pinned); components calltrack()/trackView()with a typedTrackEvent. Events are listed inapps/bridge-ui/tracking-plan.yaml; add an event there and inTrackEventtogether, never with names, search text, tokens or paths. The destination is the server'sDEFAULT_DESTINATION(read bybuild-config.mjsfromtelemetry-consent.ts), servicereaper-mcp-bridge-ui. On by default, off via Settings → Privacy, GPC/DNT, or?demo; fetch/xhr tracing stays off (the page polls the bridge). The hosted site's docs (/,/docs/<guide>) and/changelogare measured separately (startSiteAnalytics(), servicereaper-mcp-site,site.*events undersite:in the tracking plan): page views, errors, fetch, rage clicks,site.click(one global click listener,clickCapture(): a control is covered by its markup, a name and adata-testidcontainer, never a tracker call;data-capture="off"opts out) and session replay (inputs masked; rrweb is imported behind__HOSTED__, so the page REAPER serves never bundles it). Off with GPC/DNT; the demo at/stays silent. - Hosted build (public demo + changelog on Vercel,
*.vercel.app):vercel.jsonrunsscripts/snapshot-releases.mjs(GitHub releases into the gitignoredchangelog/releases.snapshot.json) thenBRIDGE_HOSTED=1 nx build bridge-ui.__HOSTED__makes the page always the demo (demo-mode.ts), bakes the releases andhighlights.jsonin (no GitHub call from a visitor's browser) and copieschangelog/beside the page for the media./is the docs front page (a guide is/docs/<slug>;/docsredirects to/),/demois the demo (vercel.jsonrewrites; an old root link carrying the bridge page's state, such as/?view=tools, moves to/demoinmain.tsxvialegacyDemoAddress()),/changelog(=?page=changelog,Changelog.PageRoutefrommain.tsx, no bridge polling) the changelog as a page;?release=0.79.1or#release-0.79.1opens one release. A new release needs a redeploy to show (deploy hook or push). Share pictures: a link to the site unfurls with a 1200x630 picture per kind of page (bridge demo at /demo, docs at / and /docs/<guide>, changelog). Crawlers never run the page, sohostedShare()invite.config.tswrites one HTML copy per kind with its ownog:/twitter:tags (src/lib/share-meta.ts;vercel.jsonrewrites/,/docs/<guide>and/changelogto their copy). The pictures are drawn byapps/bridge-ui/scripts/og-images.mjsand committed inapps/bridge-ui/share/: re-run it after a design change. A single guide shares the docs picture, not its own. WithoutBRIDGE_HOSTEDthe build is exactly the REAPER page. - Guides for musicians (
docs/guides/*.md,apps/bridge-ui/src/features/docs/): plain-language pages with a video each, served on the hosted site at/docs(/docs/<slug>.mdis the raw file,/llms.txtand/llms-full.txtare generated) and rendered by GitHub as they are. A guide is one.mdwith frontmatter (title,summary,sectionstart|safe|mix|create|yours|know,order, optionalyoutubeid,poster,duration);docs/guides/README.mdhas the rules.hostedDocs()invite.config.tscopies them beside the hosted page (a bad guide fails the hosted build) and serves them from the working tree underpnpm dev:bridge; the REAPER page never bundles them.Markdowntakes adocoption for them (relative images,> say:/> your-call:callouts,::: details,::: gallerycarousels, heading ids). The video loads from youtube-nocookie.com only after a click.docs.test.tschecks every guide (links, images, recipe template, no emoji). A new or changed user-facing feature gets its guide edited in the same change. - Payload shapes live in
apps/bridge-ui/src/lib/status.ts(BridgeStatus) andsrc/lib/timeline.ts(BridgeHistory,LongHistory) andpublish_status()/publish_history()/publish_log()inmcp_bridge.lua— change both together.
Platform-Specific Paths
The bridge auto-detects REAPER's resource path:
- macOS:
~/Library/Application Support/REAPER - Windows:
%APPDATA%/REAPER - Linux:
~/.config/REAPER
Override with REAPER_RESOURCE_PATH environment variable.
Module Boundaries
ESLint enforces dependency rules via @nx/enforce-module-boundaries:
type:appprojects can only depend ontype:libprojectstype:libprojects can only depend on othertype:libprojects- The server app depends on the protocol library, not the other way around
Testing
- Framework: Vitest with
globals: true,environment: 'node' - Server tests:
apps/reaper-mcp-server/vitest.config.ts(has@reaper-mcp/protocolalias) - Protocol tests:
libs/protocol/vitest.config.ts - Test behaviour, never implementation: every test asserts what a caller can observe — the tool's response
to the agent, the error it returns, the state REAPER ends up in (through the fake API), the status feed, what the
page renders. Never assert private helpers, internal call order, how many times a function ran, or the exact
shape of intermediate data. A test should survive a refactor that keeps the behaviour and fail when the behaviour
breaks; if a rename or restructure breaks it, it was testing implementation.
- Drive the code through its public entry point (a registered tool, a bridge command, an exported pure function) with real inputs, and assert the outcome.
- Mock only at the boundary you can't run (REAPER, the file system, network, the sidecar). Mocking
sendCommand()is for feeding the tool a bridge response, not for asserting it was called with particular arguments — assert what the tool returned instead. - Name tests after the behaviour (
"refuses an unknown marker index and changes nothing"), not the function.
- Test files:
tools/*.test.ts(tool responses withsendCommand()stubbed),*-lib.test.tsandbridge-*.test.ts(the real Lua libraries and bridge running in wasmoon against a fakereaperAPI); in the bridge page,*.test.stories.tsxplay functions (what a viewer sees and does, run bysrc/test/stories.test.tsx) and*.test.tsnext to the pure modules insrc/lib/andsrc/features/*/(bridge and LoreKit payloads, URLs) - Bridge page in a real browser:
node apps/bridge-ui/e2e/drawer-widths.mjs(afterpnpm nx build bridge-ui) opens every command ine2e/fixtures/status.json, a status feed recorded from the real bridge, in the built page at the narrowest (320 px), default and widest drawer, and fails on anything drawn outside the drawer or a console error. CI runs it. Add an entry to the fixture when you add a view (record it by running the commands through the wasmoon bridge and savingMCPBridge/status). - Sidecar tests in CI: the
sidecarjob runstest_analysis.py,test_mixcheck.py,test_verify.py(and the chord and voice-sketch tests) with CPU torch (Demucs and the aesthetics model are not installed there). - Validate changes with tests: Always write small, simple, and effective tests to validate your changes. Prefer focused tests that check one behaviour well. If modifying existing code, add or update tests to cover the change before considering it complete.
Running the MCP Server
Two ways in: clone the fork and run the one-command installer (below), or npm install -g @mthines/reaper-mcp then reaper-mcp setup && reaper-mcp init (no clone; the release job publishes it with provenance, scripts/prepare-npm-package.mjs assembles the package).
# Full setup from a fresh clone (deps, build, link CLI, bridge, symlinks, config)
./scripts/install.sh
# The installer runs these underlying steps (each runnable on its own):
pnpm nx build reaper-mcp-server # build
( cd dist/apps/reaper-mcp-server && pnpm link --global ) # put `reaper-mcp` on PATH
reaper-mcp setup # Lua bridge + JSFX into REAPER
scripts/sync-symlinks.sh # skills + agents + knowledge → ~/.claude
reaper-mcp init # tool allow-list + .mcp.json (copy-free)
# Start MCP server (stdio mode — what Claude Code runs)
reaper-mcp serve
# Diagnostics
reaper-mcp doctor # Verify all components configured correctly
reaper-mcp status # Quick bridge connectivity check
# Test with MCP Inspector
npx @modelcontextprotocol/inspector node dist/apps/reaper-mcp-server/main.jsCLI Commands Reference
| Command | Description |
serve (default) | Start MCP server in stdio mode for Claude Code |
setup | Install Lua bridge + JSFX analyzers into REAPER, then (at a terminal) ask to run init and doctor: Enter, Enter. --yes/-y does all three without asking (scripts, agents); without a terminal and without --yes it stops after the install. --verbose lists every file. Ends by offering the Python sidecar (sidecar-offer.ts: one question in a terminal, default no; one line without a terminal) |
setup-sidecar | Install the Python sidecar (opt-in, Python 3.10+, venv at ~/.reaper-mcp/sidecar-venv/). In a terminal it shows a picker: core analysis (required), Audiobox Aesthetics weights (831 MB, default on), stem separation (Demucs, ~110 MB), chord model (lv-chordia, ~135 MB), each with what it enables, why and its size. No prompt without a TTY, in CI, with --yes/-y/--non-interactive or with any component flag: --all, --with-separation, --with-chords, --without-aesthetics (defaults: core + aesthetics). --list [--json] prints the components and what is installed. An existing install gets only the missing picked parts; the scripts are always refreshed. |
instance | A second REAPER for the agent to work in while you work in yours: create <name> [--port N] [--visible], start <name> [project.rpp], connect <name> [--harness …] (adds the reaper-<name> MCP server), stop <name> (every OS: osascript on macOS, else the bridge's quit request), list, remove <name> (refused while its bridge answers). Starts empty, never reopens the last project. See instance.ts and docs/guides/second-reaper.md |
extension | Manage opt-in extensions: list, add <name|folder|git-url>, link <folder>, remove <name>, new <name> (see docs/EXTENSIONS.md) |
install-skills | Copy the mix skills, agents and knowledge shipped in the npm package into ~/.claude (never overwrites files the user edited or owns, skips symlinked folders; a clone uses scripts/sync-symlinks.sh). --dry-run previews. Skills and agents also go into the shared ~/.agents when a non-Claude harness is installed (never the knowledge, which the skills read from ~/.claude/knowledge); --harness claude,codex picks. init runs it for an npm install |
init | Connect the AI harnesses: detects Claude Code, Codex CLI, Gemini CLI and Cursor, registers the server in each one found by absolute path (claude mcp add --scope user, codex mcp add, gemini mcp add --scope user, Cursor's ~/.cursor/mcp.json; an entry whose node or main.js no longer exists is replaced) and prints the install hint for the ones missing. --harness claude,codex or --all picks by hand. Claude Code also gets the REAPER tool allow-list in ~/.claude/settings.json, and in a clone a .mcp.json (copy-free). From an npm install it then runs install-skills. doctor shows which harnesses are connected |
update | Update to the latest release (--bridge, which the bridge page uses, exits 3 when nothing newer exists; 1 = download failed, 2 = setup failed). An npm install runs npm install -g @mthines/reaper-mcp@<latest>, then setup --yes in a fresh process (update.ts; nothing when npm names nothing newer, --force reinstalls). It cross-checks GitHub's latest release: when npm has nothing newer than this install but GitHub does (a proxy or security tool such as Aikido hiding versions, or a publish still landing) it fails with the reason and the clone-install hint (exit 1), never "nothing newer"; when npm offers something newer it installs that and then says GitHub's newer one is not reachable yet; after the download it reads the installed version and stops when it is not the target; a clone runs scripts/update.sh. setup writes mcp_update.conf (mode=npm, node, cli) so the bridge page's Update button runs it detached; the page then shows a toast (Sonner, app/UpdateToasts.tsx): downloading, then ready with a Reload button, never an automatic reload, then a 30 s See what's new toast on the reloaded page. The page's "update available" check offers an npm install the newer of npm's and GitHub's release, so a version npm hides still shows up and the failed update says why (a failure reads as an error toast with the reason and, for npm, a link to the clone install in docs/guides/install.md). When the bridge runs from ReaPack's folder (control.reapack), the notice and What's new card name ReaPack's Synchronize packages for the REAPER side instead of npm/clone commands |
flags | Feature flags on this install: list (every flag, how it resolves, why), set <key> <variant> (force one, written to ~/.config/reaper-mcp/flags.json: visible to you only), reset [key]. REAPER_MCP_FLAGS (JSON) overrides for one run. See docs/FEATURE-FLAGS.md |
doctor | Verify all components are configured correctly (includes 4 sidecar sub-checks; an Instances row lists second REAPERs made with instance create, none when there are none) |
status | Check if Lua bridge is running in REAPER; one line per instance after it |
Skills + knowledge are wired by
scripts/sync-symlinks.sh(symlinks into~/.claude) in a clone, and byreaper-mcp install-skills(a copy) from an npm install — the repo is the source of truth.
Claude Code MCP Config
{
"mcpServers": {
"reaper": {
"command": "node",
"args": ["/path/to/reaper-mcp/dist/apps/reaper-mcp-server/main.js", "serve"]
}
}
}Generated by reaper-mcp init in a clone (an npm install registers the server at user scope
instead, with claude mcp add): it runs your clone's built main.js by absolute
path, so it works without the reaper-mcp command on PATH.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

