agentleFS
mthinesmthines/reaper-mcp/CLAUDE.md

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

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
  1. Very specific:

    Every tool that takes a trackIndex (except media item, MIDI, item/take, track-template, measure_track_alignment and verify_edit tools) …

    line 219
  2. Very specific:

    Every point tool takes an optional automationItemIndex to work on one automation item's (pool's) points instead of the underlying envelope.

    line 366
  3. Very specific:

    Undo: every edit by these tools is one undo point labelled MCP: …, so undo_project reverts exactly that edit.

    line 639
  4. Very specific:

    Validate, then write: every input (track/item/take/FX index, file, color, shape, path) is checked before the first write.

    line 646
  5. Very specific:

    Creating envelopes: Use create_track_envelope before adding points.

    line 672
  6. Very specific:

    Support pagination: Add offset and limit parameters so the client can request data in chunks.

    line 690
  7. Distinctive:

    When adding new tools that could return large datasets, always implement both a summary path and a paginated path.

    line 694
  8. Very specific:

    Important: Always use z.coerce.number() instead of z.number() for numeric parameters.

    line 748
  9. Very specific:

    Audio loading: always soundfile (analysis.load_audio).

    line 817
  10. Distinctive:

    Auto-restart: If the sidecar crashes, one restart is attempted automatically.

    line 821
  11. Very specific:

    Script refresh: every sidecar spawn first copies the build's server.py and modules over the installed ones, so an update (which never …

    line 822

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

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 everything

Architecture 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 model

Why 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:

  1. MCP Server writes command_{uuid}.json to bridge directory
  2. Lua bridge polls directory every ~30ms via reaper.defer(), reads command, executes ReaScript API
  3. Lua bridge writes response_{uuid}.json with results
  4. 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 script

Where mix knowledge lives

  • knowledge/ (genres, workflows, reference) — curated markdown read on demand by the mix skills; symlinked into ~/.claude/knowledge in a clone, copied there by install-skills from an npm install.
  • Plugin knowledge and process lessons live in LoreKit, scope project::reaper-mcp — one record per plugin (tags plugin-knowledge, category::…, preference::…, fx::…) and lessons (loop::mixing-lessons), in two layers: the built-in layer (keys plugins::<vendor>/<plugin> / mixing-lessons::<slug>, owned by the reaper-mcp LoreKit org, tag layer::built-in, read by everyone through the server's list_builtin_knowledge / get_builtin_knowledge tools) and each user's own layer on top (keys user::plugins::… / user::mixing-lessons::…, tag layer::user, via the user's own LoreKit memory.*). The user's record wins. The skills only ever write user:: keys; the maintainer moves records into the built-in layer with /mix-memory publish.
  • docs/PLUGINS.md lists every built-in plugin record (table between <!-- plugin-list:start/end -->, rebuilt by node 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; the Plugin list workflow rebuilds it on main after every Plugin contributions run and daily (direct publishes from the bridge page). Contract: knowledge/reference/memory-protocol.md.

Workspace Packages

PackageLocationBuildPurpose
@mthines/reaper-mcp/ (root)--Workspace root, scripts
@mthines/reaper-mcp-serverapps/reaper-mcp-server@nx/esbuild (ESM bundle)MCP server application
@mthines/reaper-bridge-uiapps/bridge-uiVite + React Compiler → single HTMLBridge status page served by REAPER's web interface
@reaper-mcp/protocollibs/protocol@nx/js:tscShared command/response types
@reaper-mcp/feature-flagslibs/feature-flagsnone (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)

ToolFileDescription
get_project_infotools/project.tsProject name, tempo, time sig, sample rate, transport state
list_trackstools/tracks.tsAll 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_propertiestools/tracks.tsDetailed single track info + full FX chain list
set_track_propertytools/tracks.tsSet volume (dB), pan, mute, solo, recordArm, phase, input, playOffsetMs (track playback offset, ±500 ms)
set_multiple_track_propertiestools/batch.tsBatch set properties on multiple tracks in one call

Track Structure (6)

ToolFileDescription
add_tracktools/structure.tsInsert a track (optional name, position)
delete_tracktools/structure.tsDelete a track (never the master)
move_tracktools/structure.tsMove a track to a new position; keeps the user's selection
set_track_foldertools/structure.tsFolder parent / last-in-folder / normal; collapse state
set_track_infotools/structure.tsName, color (#RRGGBB/none), channel count, master/parent send
set_track_grouptools/structure.tsGroup (1-64) membership roles, incl. VCA lead/follow

FX Management (9)

ToolFileDescription
add_fxtools/fx.tsAdd FX by name (partial match: "ReaEQ", "VST: Pro-Q 3")
remove_fxtools/fx.tsRemove FX from chain by index
get_fx_parameterstools/fx.tsList all FX params with current values and ranges
analyze_fxtools/fx.tsAnalyze FX parameters with filtering and pagination
set_fx_parametertools/fx.tsSet FX parameter (normalized 0.0-1.0)
set_fx_enabledtools/fx.tsEnable or disable (bypass) an FX plugin
set_fx_offlinetools/fx.tsSet FX online/offline (offline = no CPU, preserves settings)
setup_fx_chaintools/batch.tsBatch add multiple FX with initial parameters in one call
set_multiple_fx_parameterstools/batch.tsBatch set params across multiple FX/tracks in one call

Transport (5)

ToolFileDescription
playtools/transport.tsStart playback
stoptools/transport.tsStop playback/recording
recordtools/transport.tsStart recording; refused when no track is armed (REAPER would open a blocking dialog)
get_transport_statetools/transport.tsPlay/record/pause status, cursor positions, tempo, time sig
set_cursor_positiontools/transport.tsMove edit cursor to position in seconds

MIDI Editing Tools (14)

ToolFileDescription
create_midi_itemtools/midi.tsCreate an empty MIDI item on a track at a given time range (seconds)
list_midi_itemstools/midi.tsList all MIDI items on a track with position, length, note/CC counts
get_midi_notestools/midi.tsGet MIDI notes with pagination (offset/limit). Use analyze_midi first for large items.
analyze_miditools/midi.tsAnalyze MIDI item: per-pitch velocity stats, histogram, machine gun detection. Efficient for large items.
insert_midi_notetools/midi.tsInsert a single note (pitch 0-127, velocity 1-127, position/duration in beats)
insert_midi_notestools/midi.tsBatch insert multiple notes via JSON array string
edit_midi_notetools/midi.tsEdit an existing note by index (partial updates: only provided fields change)
edit_midi_notestools/midi.tsBatch edit multiple notes via JSON array string. Much faster than repeated edit_midi_note calls.
delete_midi_notetools/midi.tsDelete a note by index
get_midi_cctools/midi.tsGet CC events, optionally filtered by CC number
insert_midi_cctools/midi.tsInsert a CC event (cc 0-127, value 0-127, position in beats)
delete_midi_cctools/midi.tsDelete a CC event by index
get_midi_item_propertiestools/midi.tsGet MIDI item properties (position, length, note/CC count, mute, loop)
set_midi_item_propertiestools/midi.tsSet MIDI item properties (position, length, mute, loop source)

Composition (6)

ToolFileDescription
quantize_miditools/composition.tsSnap notes to the project grid: grid (beats), strength, swing, window, lengths keep/quantize; all notes or a selection (indexes, pitch range, channel)
transform_miditools/composition.tsTranspose (refused out of 0-127), velocity set/scale/add + clamp, humanize (seeded), length set/scale/legato
import_midi_filetools/composition.tsImport 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_sketchtools/voice-sketch.tsVoice recording → detected notes, tempo/key and a generated band arrangement; optional MIDI + sampled stems. See usage and limits
detect_keytools/composition.tsKey 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_chordstools/composition.tsChords 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)

ToolFileDescription
send_midi_cctools/midi.tsSend a CC event in real-time to a track's MIDI output (auto-inserts mcp_midi_emitter.jsfx)
send_midi_pctools/midi.tsSend a program change (optionally preceded by bank select CC0 + CC32)
send_midi_notetools/midi.tsSend a note-on; if durationMs provided, schedules note-off automatically

Media Item Editing Tools (11)

ToolFileDescription
list_media_itemstools/media.tsList all items on a track (position, length, name, item volume, takeVolume, totalGainDb, MIDI/audio type)
get_media_item_propertiestools/media.tsDetailed 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_propertiestools/media.tsSet 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_propertiestools/media.tsBatch 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_itemtools/media.tsSplit an item at a position (seconds), returns left/right item info
delete_media_itemtools/media.tsDelete an item from a track
move_media_itemtools/media.tsMove an item to a new position and/or a different track
trim_media_itemtools/media.tsTrim item edges (positive=trim inward, negative=extend)
add_stretch_markertools/media.tsAdd a stretch marker for time-stretching audio
get_stretch_markerstools/media.tsList stretch markers with positions and source positions
delete_stretch_markertools/media.tsDelete a stretch marker by index

Arrangement Tools (5)

ToolFileDescription
copy_media_itemstools/arrange.tsCopy/repeat items keeping their spacing (times, position, trackIndex); fresh GUIDs, MIDI unpooled unless pooled
insert_timetools/arrange.tsOpen time across the project: items, markers, regions, tempo, envelope points and automation items after it move; spanning items split
remove_timetools/arrange.tsCut a range out of the project and close the gap; crossing items trimmed, regions shrink, the tempo after the cut kept
copy_sectiontools/arrange.tsCopy 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_itemstools/arrange.tsnormalize (item gain to a peak/true-peak/LUFS/RMS target), reverse (toggles), glue (whole items); selection kept

Selection & Navigation Tools (6)

ToolFileDescription
get_selected_trackstools/selection.tsGet currently selected tracks with indices and names (master as -1)
set_selected_trackstools/selection.tsSelect tracks by index, name or GUID (replace or add); all resolved first, an unknown one changes nothing
get_selected_itemstools/selection.tsThe items selected now: {trackIndex, itemIndex}, track name, position, length, mute; paged (offset/limit, {total, hasMore, items})
set_selected_itemstools/selection.tsSelect media items by {trackIndex, itemIndex} (replace or add)
get_time_selectiontools/selection.tsGet time/loop selection start, end, length in seconds
set_time_selectiontools/selection.tsSet the time selection range (start/end in seconds)

Markers & Regions Tools (8)

ToolFileDescription
list_markerstools/markers.tsList all project markers (index, name, position, color)
list_regionstools/markers.tsList all regions (index, name, start/end, color)
add_markertools/markers.tsAdd a marker at position with optional name/color
add_regiontools/markers.tsAdd a region with start/end, optional name/color
delete_markertools/markers.tsDelete a marker by index
delete_regiontools/markers.tsDelete a region by index
edit_markertools/markers.tsRename, move or recolor a marker by index; unknown index changes nothing
edit_regiontools/markers.tsRename, move/resize or recolor a region by index; end must stay after start

Tempo Map Tools (5)

ToolFileDescription
get_tempo_maptools/tempo.tsAll tempo/time sig changes (position, BPM, time sig, linear flag)
add_tempo_markertools/tempo.tsAdd a tempo/time sig marker at a position (seconds); returns the updated map
edit_tempo_markertools/tempo.tsEdit a tempo marker by index (position, BPM, time sig, linear); unspecified fields kept
delete_tempo_markertools/tempo.tsDelete a tempo marker by index
set_project_tempotools/tempo.tsSet 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.

ToolFileDescription
create_track_envelopetools/envelopes.tsCreate/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_envelopestools/envelopes.tsList envelopes on a track (name, point and automation item counts, active/visible/armed); send envelopes carry send (index, destination track)
get_envelope_pointstools/envelopes.tsGet automation points with pagination (time, raw value, db on volume envelopes, shape, tension)
insert_envelope_pointtools/envelopes.tsInsert an automation point (value or db) with shape/tension
insert_envelope_pointstools/envelopes.tsBatch insert multiple automation points (JSON array)
edit_envelope_pointstools/envelopes.tsEdit points by index (time, value/db, shape, tension); all validated before any write
delete_envelope_pointtools/envelopes.tsDelete an automation point by index; returns the deleted point
clear_envelopetools/envelopes.tsDelete ALL points from an envelope (or an item's pool)
remove_envelope_pointstools/envelopes.tsDelete automation points in a time range
set_envelope_propertiestools/envelopes.tsSet envelope active/visible/armed state
list_automation_itemstools/envelopes.tsAutomation items on an envelope: index, poolId, pool name, position, length, loop, point count
insert_automation_itemtools/envelopes.tsNew pool from points (seconds from the item start), a pooled instance of poolId (any track), or captureEnvelope; returns pooledWith
set_automation_itemtools/envelopes.tsMove/resize an item; start offset, play rate, baseline, amplitude, loop, pool name
delete_automation_itemtools/envelopes.tsDelete one item (preservePoints keeps them on the envelope); other selections kept

FX Discovery & Presets (4)

ToolFileDescription
list_available_fxtools/discovery.tsDiscover all installed plugins (VST, VST3, JS, CLAP, AU) via REAPER's EnumInstalledFX (6.37+)
search_fxtools/discovery.tsFuzzy search installed plugins by name
get_fx_preset_listtools/presets.tsList available presets for an FX
set_fx_presettools/presets.tsLoad a preset by name

Snapshots (5)

ToolFileDescription
snapshot_savetools/snapshots.tsSave 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_restoretools/snapshots.tsRestore 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_listtools/snapshots.tsList project-scoped snapshots (falls back to global for unsaved projects)
snapshot_deletetools/snapshots.tsDelete a saved snapshot by name
snapshot_edittools/snapshots.tsRename a snapshot and/or change its description; the mixer state is copied unchanged, a name another snapshot's file uses is refused

Routing (5)

ToolFileDescription
get_track_routingtools/routing.tsSends, receives (index, mode, channels), hardware outputs, master send, parent/folder info
add_sendtools/structure.tsTrack → track send: level, pan, mute, mode, channels (sidechain into 3/4 widens the destination)
set_sendtools/structure.tsEdit a send, receive or hardware output by index
remove_sendtools/structure.tsRemove a send, receive or hardware output by index
add_hardware_outputtools/structure.tsRoute a track to an audio interface output (stereo or mono)

Metering & Analysis (6)

ToolFileDescription
read_track_meterstools/meters.tsPeak/RMS L/R in dB
read_track_spectrumtools/meters.ts1/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_lufstools/analysis.tsIntegrated/short-term/momentary LUFS + true peak
read_track_correlationtools/analysis.tsStereo correlation, width, mid/side levels
read_track_cresttools/analysis.tsCrest factor (peak-to-RMS ratio)
measure_trackstools/analysis.tsPlay, 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

ToolFileDescription
analyze_track_aestheticstools/aesthetics.tsPerceptual 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_offlinetools/offline.tsRender 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_filetools/offline.tsThe same analysis for an audio file on disk (reference song, bounce, stem); no REAPER involved
measure_track_alignmenttools/offline.tsRender 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_edittools/offline.tsCheck 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_transientstools/transients.tsHits 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_automationtools/transients.tsDetect, 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_pitchtools/pitch.tsSung 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_pitchtools/pitch.tsDetect, 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)

ToolFileDescription
get_record_setuptools/recording.tsGlobal 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_recordtools/recording.tsArm, 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_modetools/recording.tsGlobal record mode, punch range (time-selection mode) and record path
get_track_lanestools/recording.tsFixed lanes: on/off, each lane's name, playing state (exclusive/layered/off) and items (100 per lane)
set_track_lanestools/recording.tsFixed lanes on/off, lane count, names, which lane plays alone or which lanes play layered
comp_lanestools/recording.tsComp 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)

ToolFileDescription
set_automation_modetools/mixing.tsTracks' automation mode (trim, read, touch, write, latch, latch_preview) and/or the global override (none/bypass); returns before and after
get_fx_param_modulationtools/mixing.tsOne parameter's modulation (baseline, LFO, audio control signal, link), or every modulated parameter of an FX
set_fx_param_modulationtools/mixing.tsLFO (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_pinstools/mixing.tsEach input/output pin's track channels (1-based) and the track's channel count
set_fx_pinstools/mixing.tsConnect pins to channels (e.g. a sidechain on 3/4); widens the track to the highest channel used, never narrows it
list_monitoring_fxtools/mixing.tsThe monitoring FX chain (heard in the monitors, never rendered; global, not in the project)
add_monitoring_fxtools/mixing.tsAdd a monitoring FX, with optional normalized parameters
set_monitoring_fxtools/mixing.tsBypass, offline or set parameters of a monitoring FX
remove_monitoring_fxtools/mixing.tsRemove a monitoring FX
freeze_trackstools/mixing.tsFreeze tracks to stereo/mono/multichannel (native actions 41223/40901/40877), selection kept; not the master
unfreeze_trackstools/mixing.tsRestore one freeze layer (41644); refuses a track that is not frozen
apply_fx_to_itemstools/mixing.tsRender in place: track + take FX to a new active take (40209/40361/41993); the old take stays
add_stretch_markerstools/mixing.tsMany stretch markers on an audio item in one call and one undo point
edit_stretch_markerstools/mixing.tsEdit 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_guidetools/align.tsVocal 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_audiotools/mixing.tsHits 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.

ToolFileDescription
analyze_loudness_curvetools/mixcheck.tsShort-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_bandstools/mixcheck.tsCorrelation 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_maskingtools/mixcheck.tsRenders 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_stemstools/mixcheck.tsDemucs (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)

ToolFileDescription
run_plantools/plan.tsExecute 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)

ToolFileDescription
list_builtin_knowledgetools/knowledge.tsList (summaries, tag filter) or full-text search the built-in plugin records and mixing lessons
get_builtin_knowledgetools/knowledge.tsRead one built-in record by key (plugins::… / mixing-lessons::…)
report_plugin_researchtools/plugin-research.tsThe 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.

ToolFileDescription
write_jsfxtools/jsfx.tsWrite 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_buildtools/plugin-build.tsThe 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)

ToolFileDescription
search_actionstools/actions.tsSearch REAPER's ~6k actions (native, SWS, scripts, Custom: macros) inside REAPER; returns id, stable namedId, name, toggle state, shortcuts
get_actiontools/actions.tsOne action's details; a Custom: macro's steps by name, or a script's path (from reaper-kb.ini)
run_actiontools/actions.tsRun 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)

ToolFileDescription
undo_projecttools/project.tsUndo the last undo point; reports its label and the next undo/redo labels
redo_projecttools/project.tsRedo the last undone point; reports its label
save_projecttools/project.tsSave 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_settingstools/project.tsOutput dir, file pattern, format + bit depth/bitrate, source, bounds, normalize/limit, dither, metadata, region matrix, and the resolved target files
set_render_settingstools/project.tsSet 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_projecttools/project.tsRender 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_versionstools/project.tsRender 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_settingstools/project.tsSample rate (+ forced flag), title, author, notes, repeat, metronome
set_project_settingstools/project.tsSet any of those; metronome is a global REAPER option (not undoable, not stored in the project)

Items & Takes (10)

ToolFileDescription
insert_audio_filetools/items.tsInsert an audio file onto a track as a new item at a position (default: edit cursor); the item is the file's length
list_takestools/items.tsAn item's takes: name, active, MIDI/audio, source file, take FX count
set_active_taketools/items.tsMake one take the active (playing) take
get_take_fxtools/items.tsList a take's FX (default: active take); with fxIndex, that FX's parameters
add_take_fxtools/items.tsAdd an FX to a take's FX chain by name
remove_take_fxtools/items.tsRemove one FX from a take's FX chain
set_take_fx_parametertools/items.tsSet one take FX parameter and return the value REAPER reads back
get_item_appearancetools/items.tsItem color ("#RRGGBB" or "none") and fade lengths, shapes (0-6) and curves
set_item_colortools/items.tsSet an item's color, or "none" for the track default
set_item_fadestools/items.tsSet fade-in/out lengths, shapes and curves (only the fields given change)

FX Housekeeping (9)

ToolFileDescription
move_fxtools/fx-housekeeping.tsMove one FX within its chain or to another track
copy_fxtools/fx-housekeeping.tsCopy one FX (with settings) within its chain or onto another track
rename_fxtools/fx-housekeeping.tsRename an FX instance (REAPER 6.37+); "" restores the plugin name
save_fx_chaintools/fx-housekeeping.tsSave a track's FX chain as <resource>/FXChains/<name>.RfxChain
load_fx_chaintools/fx-housekeeping.tsLoad an .RfxChain onto a track (append or replace), fresh FXIDs
list_fx_chainstools/fx-housekeeping.tsList saved .RfxChain names (FXChains folder and subfolders)
save_track_templatetools/fx-housekeeping.tsSave a track as <resource>/TrackTemplates/<name>.RTrackTemplate (items only with includeItems)
insert_track_templatetools/fx-housekeeping.tsInsert the track(s) of a template at a position, fresh GUIDs
list_track_templatestools/fx-housekeeping.tsList saved .RTrackTemplate names

Progressive Discovery (3)

ToolFileDescription
list_tool_categoriestools/categories.tsList all tool categories with descriptions and tool names (compact — avoids loading all 192 schemas)
enable_tool_categorytools/categories.tsGet full tool list for a category; signals intent to use that category
disable_tool_categorytools/categories.tsSemantic 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 calls MarkTrackItemsDirty(track, item) before Undo_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 from seed. detect_key correlates 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_chords matches 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 via TimeMap_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 as run_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): read totalGainDb, never volume alone
  • Trim: trimStart moves the left edge (adjusts start offset), trimEnd moves 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 in arrange-lib.test.ts against __fixtures__/fake_timeline.lua); the bridge handlers decode items/tracks (JSON strings) and pass reaper in.
  • 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 (CalculateNormalization over 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_items names 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 (optional params, 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 the run_action tool, checked in the validate pass), and the arrangement ops copy_items, insert_time, remove_time (same parameters as the tools). Only run_action ops may follow a run_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 earlier add_track/add_fx via as: "$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 after add_fx with position: 0 the older FX have moved up one; use a name or an as ref 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 $ref rejects 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: true returns the resolved op list, conflicts, and warnings (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_fxchain copies a source <FXCHAIN block (from a track via from, or a base64 track chunk via fromChunk) 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 as AUXRECV lines 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.lua decodes with its own small JSON decoder (SWS has no CF_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 step run_plan with select_tracks then run_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 unless allowDialog: true. Any File: 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 a File: 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 from reaper-kb.ini). search_actions, get_action and run_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 the total count.

Project Operations Concepts

  • No dialogs: save_project without path on a never-saved project is refused (REAPER would open Save As) — the same rule run_action applies to File: Save…. render_project refuses when a target file exists (REAPER would ask to overwrite) unless overwrite: true, which deletes those files first, and when bounds is time_selection with no time selection.
  • Render formats: format and secondaryFormat (a second file from the same render; none disables it) take wav/aiff/flac/mp3/ogg/opus, with REAPER's default options except the bit depth or MP3 bitrate bitDepth / mp3Bitrate set. render_project refuses when either is another encoder (seen live: a template's video secondary format left a modal dialog open) — set secondaryFormat: "none".
  • Render source and encodings (probed in REAPER 7.40): source maps to RENDER_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 the RENDER_FORMAT blob (wav evaw+int16 bits, 32-bit int is 0x21 and float 0x20; aiff ffia; flac calf+int32 bits+compression), MP3 bitrate at bytes 4 and 24 of l3pm. 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: false skips it.
  • Render metadata: metadata fields (title, artist, album, genre, year, isrc, comment, description) write the matching ID3/INFO/VORBIS/AXML/BWF keys of RENDER_METADATA; metadataRaw sets any SCHEME:KEY; an empty value removes the key. Setting metadata turns on embedding (RENDER_SETTINGS &512) unless embedMetadata: false.
  • Render versions: render_versions mutes 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). targets in get_render_settings are the files REAPER will write (RENDER_TARGETS).
  • Undo: every edit by these tools is one undo point labelled MCP: …, so undo_project reverts 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_map indexes; a map with tempoMarkerCount: 0 holds only the project tempo, set it with set_project_tempo. Adding a marker where one already is replaces it (replacedExisting: true). REAPER can silently keep the start marker on delete; delete_tempo_marker then returns an error instead of a false success. set_project_tempo never uses SetCurrentBPM with 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 in items-lib.test.ts); the bridge handlers only pass reaper, mcp_plan_lib.lua and a small io-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: takeIndex is 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_template take a name (subfolders allowed) under FXChains/ or TrackTemplates/; absolute paths, drive letters and .. are refused, and an existing file is only replaced with overwrite: 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 with mcp_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 in recording-lib.test.ts).
  • Inputs travel as objects, never raw I_RECINPUT numbers: {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_mode time_selection records only inside the time selection (punchStart/punchEnd set it); selected_items punches on the selected items. Global toggles 40252/40076/40253.
  • Fixed lanes (REAPER 7): C_LANEPLAYS 1 = exclusive (the others go silent), 2 = layered. Turning lanes off puts every item on one lane, all playing (warned; undo_project restores). 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.undone log).

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 than maxShiftMs, a hit left alone costing maxShiftMs. 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_stretch skips a hit whose move would cross the previous marker, anchors both item ends, and strength scales each hit's move; consonant tails are extra pairs (same shift as their hit, not counted in the offsets). edit_stretch_markers rewrites the whole marker list in order after checking every edit, so a marker's index is the one get_stretch_markers lists.
  • Logic lives in reaper/mcp_mixing_lib.lua (pure Lua over an injected API, unit-tested via wasmoon in mixing-lib.test.ts); the bridge handlers decode the nested JSON params and pass reaper in.
  • Modulation goes through TrackFX_Get/SetNamedConfigParm keys param.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 <FREEZE block to the track chunk per layer; that is how unfreeze_tracks knows 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 within window × (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_envelope before adding points. Built-in envelopes use envelopeName ("Volume", "Pan", "Mute", "Width", "Trim Volume"). FX parameter envelopes use fxIndex + paramIndex.
  • Logic lives in reaper/mcp_envelopes_lib.lua (pure Lua over an injected API, unit-tested via wasmoon in envelopes-lib.test.ts); the bridge handlers only pass reaper in.
  • Envelope values: give db on volume envelopes (Volume, Trim Volume, Send Volume). REAPER's own Volume envelope is fader-scaled (716.2 = 0 dB, not 1.0); db is converted with the envelope's scaling mode (ScaleToEnvelopeMode). Raw value: 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), except SetEnvelopePointEx, which ignores a flagged index (REAPER 7.40) and takes the plain one. A new pool's D_POOL_QNLEN is 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_guide then verify_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 in knowledge/workflows/vocal-alignment.md (the /editing skill loads it).
  • Transient-driven automation (lighting): create_transient_automation from 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 → optionally set_envelope_properties to 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_properties works 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:

  1. Provide an analysis/summary tool: Compute aggregated stats server-side (in Lua) rather than dumping raw data for the AI to process. Example: analyze_midi returns per-pitch velocity stats, histograms, and machine gun detection — everything Claude would compute anyway — in ~2KB instead of 475KB of raw notes.
  2. Support pagination: Add offset and limit parameters so the client can request data in chunks. Example: get_midi_notes with offset=0, limit=100 returns the first 100 notes and includes hasMore: true and total: 2044.
  3. 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/plugin and @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 the setup command can install bridge files
  • Nx Cloud enabled for remote caching

Nx Targets

TargetInferred ByDescription
buildproject.json (explicit)Build with esbuild (server) or tsc (protocol)
lint@nx/eslint/pluginESLint with typescript-eslint + Nx module boundaries
test@nx/vite/pluginVitest (watch: false, passWithNoTests: true)
typecheck@nx/vite/plugintsc --noEmit
serveproject.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 changes

TypeScript Configuration

  • Root tsconfig.base.json defines shared settings (ES2022, ESM, strict, bundler resolution)
  • Path alias: @reaper-mcp/protocol -> libs/protocol/src/index.ts
  • Each package has its own tsconfig.json extending the base
  • The server's tsconfig has references to protocol for project references

Adding New MCP Tools

To add a new tool, touch these 8 places:

  1. libs/protocol/src/commands.ts -- Add command type to CommandType union, add params interface
  2. libs/protocol/src/responses.ts -- Add response data interface if needed
  3. apps/reaper-mcp-server/src/tools/ -- Create or extend a tool file, register with server.tool()
  4. apps/reaper-mcp-server/src/cli.ts -- Add tool name to MCP_TOOL_NAMES array (used by ensureClaudeSettings() to auto-allow tools)
  5. apps/reaper-mcp-server/src/tools/categories.ts -- Add tool name to a category in TOOL_CATEGORIES (the bridge-coverage test fails on an uncategorized tool)
  6. reaper/mcp_bridge.lua -- Add handler function in the handlers table
  7. apps/bridge-ui/src/demo/demo-calls.ts -- Add the command to DEMO_CALLS, so ?demo logs it: the params an agent would send, or 'example' when an example in src/demo/examples.ts draws it (a measurement or edit view). The map is a Record<LoggedCommand, …>, so typecheck fails until it is there. A tool the server composes and logs itself with logToolResult() goes in LoggedTool (libs/protocol/src/commands.ts) first
  8. apps/bridge-ui/src/features/log/tools.ts -- Add the command to TOOLS: a plain title ("Delete a track") and a did sentence ("deleted the track “Old Vox”") that the bridge page's drawer leads with. Also a Record<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 }
end

Python 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 install and pnpm nx build never 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 analyze request.
  • JSON-RPC methods: analyze (aesthetics, with optional normalizeLufs), 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_DEVICE overrides; 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 in chords.ts and takes the key from the chords' tones weighted by duration).
  • Audio loading: always soundfile (analysis.load_audio). torchaudio 2.9+ removed info() and moved load() to torchcodec, so never call torchaudio.load/torchaudio.info; torchaudio.functional (filters, resampling) is fine.
  • Loudness: analysis.py implements ITU-R BS.1770-4 (K-weighting, 400 ms blocks, -70/-10 gates, channels summed) and EBU 3342 LRA; tests/test_analysis.py checks them against the EBU 3341/3342 reference signals.
  • Lifecycle: Sidecar receives SIGTERM when the MCP server receives SIGINT/SIGTERM. Managed via getSidecarClient().shutdown() in main.ts.
  • One request at a time: sidecar.ts queues requests, so a timeout counts only that request's work; one that waited QUEUE_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.py and modules over the installed ones, so an update (which never re-runs setup-sidecar) cannot leave an old server.py without the new methods.
  • Install location: Venv at ~/.reaper-mcp/sidecar-venv/, scripts at ~/.reaper-mcp/sidecar/ (server.py plus SIDECAR_MODULES in setup-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-sidecar and reaper-mcp doctor use python3; on Windows they fall back through python3, python, py (resolvePythonBin) because python3 is often the Microsoft Store stub.

Source Files

FilePurpose
apps/reaper-mcp-server/sidecar/server.pyPython sidecar JSON-RPC server (source)
apps/reaper-mcp-server/sidecar/analysis.pyLoudness (BS.1770, LRA, true peak), spectrum hints, reference comparison, alignment, normalization (numpy/torch only)
apps/reaper-mcp-server/sidecar/requirements.txtPinned Python deps
apps/reaper-mcp-server/src/sidecar.tsNode.js subprocess lifecycle + JSON-RPC client
apps/reaper-mcp-server/src/setup-sidecar.tssetup-sidecar CLI command implementation
apps/reaper-mcp-server/src/tools/aesthetics.tsanalyze_track_aesthetics tool registration
apps/reaper-mcp-server/src/tools/offline.tsanalyze_track_offline, analyze_audio_file, measure_track_alignment, verify_edit
apps/reaper-mcp-server/src/tools/transients.tsdetect_transients, create_transient_automation (pulse generation in pulsePoints())
apps/reaper-mcp-server/sidecar/verify.pyCompensated 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.pyLoudness curve, per-band stereo correlation, third-octave masking (numpy only)
apps/reaper-mcp-server/sidecar/separation.pyDemucs stem separation (soundfile I/O, never demucs's torchaudio I/O)
apps/reaper-mcp-server/src/tools/mixcheck.tsanalyze_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:extension project may depend only on type:extension-api (eslint). Never import core into one.
  • Internal commands get_fx_state, set_fx_state, extension_call are bridge commands, not MCP tools. Saved state moves as fxstate_* 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 namespace MCPAnalyzer
  • 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_permute after fft_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_spectrum tool, 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) in mcp_bridge.lua is the single write path — use it for all MIDI event types
  • Deferred note-off (send_midi_note with durationMs) 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's server.proxy, which passes each client hang-up on to REAPER.
  • A saved reaper/ file listed in REAPER_ASSETS (cli.ts, read as text) is copied into REAPER: Lua into Scripts/, then the running bridge is asked to restart with the token from its status feed; JSFX into Effects/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 from build-config.mjs; Storybook inherits vite.config.ts and drops only the single-file and REAPER plugins.
  • React Compiler: write plain components, no useMemo/useCallback/memo for 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, useEffectEvent for an effect's latest-value callback. A component the compiler cannot handle fails the build and tests (panicThreshold: 'all_errors' in build-config.mjs); known triggers are a conditional (?:, &&, ?.) inside a try block (use fetchText() from src/lib/fetch-text.ts), a variable incremented inside a callback, and a && "x" lists inside JSX attributes (build them before return).
  • 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 when ui_seen is 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_watch in mcp_bridge.lua: lsof in the background into mcp_bridge_data/web_sockets, macOS/Linux) and publishes status.web = { stuck, limit }; the page warns from 50% (webSocketLevel() in src/lib/status.ts) and the bridge prints one console line at 90%. Test scripts that hit the web server reuse one connection (one curl with 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 (n seq, 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/status every 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.jsonl and the timeline is saved to history.json (every 30s and on exit); both reload on start and are pruned to 7 days, and n continues across restarts (also saved in history.json). The newest 2000 commands stay in memory and in history_log.jsonl (which holds exactly them); when it outgrows that, the oldest 500 rotate into a segment file history_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 ExtState MCPBridge/log (newest first, with older = segments exist) only on request: the page writes MCPBridge/log_want/<ts> on open, after a bridge restart, and when the 50-entry window skipped entries; the bridge answers once with req echoing 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 (needOlder in Log.tsx), showing a loading row; the page writes MCPBridge/log_older/<id>-<oldest n it holds> and reads MCPBridge/log_page ({req, entries, more}); useBridgeFeed keeps the cursor and loading. The page holds at most LOG_MAX (10,000) entries.
  • Timeline: per-10s buckets for the last hour (sparse, [id, total, errors, slow, sumMs]) in ExtState MCPBridge/history (≤ 1 Hz), and 1m (24h) + 10m (7d) tiers in MCPBridge/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 }) in src/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 via debounceMs while the page updates at once; each view keeps its own search, so switching views never carries one over), agent, entry (open command by n), sort (Tools), settings, developer (Developer drawer open), changelog (What's new open) and release (the release a version click links to: scrolled to and highlighted), on the docs page gallery + card (a guide gallery's full screen view, by title and card name; opening and closing push, moving between cards replaces), and on Plugins coverage, inProject, plugin (open plugin by FX name). Opening, closing or switching a drawer by click (a row, "Previous call") pushes; ↑/↓ between rows replaces. view and range default to the last pick in localStorage, so the bridge's bare mcp_bridge.html opens 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) in useState/localStorage. Give each param a validate guard 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, g then c/t/a/p/s go to Calls/Tools/Sessions/Plugins/Snapshots, / f p j k c act in the view. Every view and action registers with useCommand (palette entry); only frequent ones get a key. A new view, tab or action adds its command in the same change.
  • Search (parseQuery() / matchesQuery() in src/lib/search.ts): space-separated terms, all must match. A word matches the command name, error or params text; key:value matches one param exactly (trackIndex:6 is 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": value line, termFromSelection()), which adds the term to q with a push.
  • Measurement results: the bridge keeps a compact result r (built in reaper/mcp_edit_views_lib.lua, which keeps mcp_bridge.lua under Lua's 200-locals limit) on meters/LUFS/correlation/crest/spectrum entries (RESULT_FIELDS, 48 spectrum bands) and, for render_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_wav keeps one coarser waveform per track (≤8 tracks, 60 slices, read within a 1 s budget, the rest counted as more), drawn as Waveforms: 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 in RESULT_FIELDS, MEASUREMENTS (src/lib/commands.ts), a Measurement kind and an example in src/demo/examples.ts together. 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_result command (apps/reaper-mcp-server/src/tool-log.ts, fire-and-forget; r travels as a JSON string), which the bridge records as an entry for that tool (record_tool_result()). Their compact r is built by offlineSummary() / alignmentSummary() / aestheticsSummary() and drawn as the offline / alignment / aesthetics measurements; the mix checks by curveSummary() / stereoBandsSummary() / maskingSummary() / stemsSummary() as curve (the short-term line against the target, spans over it shaded), stereo (correlation per band on −1…+1), masking (a pairs × bands heat map) and stems (each stem's LUFS, speed, inserted tracks).
  • Edit views: writes and listings also keep an r (M.summary in mcp_edit_views_lib.lua), drawn by src/features/edit-views/ (EditViews.tsx, one view per kind in views/) from editViewOf() (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, more counts the rest; added notes solid, removed dashed), analyze_midi velocity per pitch, markers/regions/tempo/items on one timeline, list_tracks as a mixer, set_selected_items as item lanes (items selected now solid, selected before dashed, the rest dimmed; picked / wasPicked per lane), and run_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, unit cc), and get_fx_parameters as readout bars; render_project / render_versions as a render result (one row per file, ≤8: mini waveform from PCM_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, the span they opened, cut or copied from hatched or outlined, where they copied to, a lane for up to 4 touched tracks plus moreTracks, 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 and quantize_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 plus more) under the global mode and punch range, and fixed lanes as one row per lane (≤32 plus more) with which lanes play and, for comp_lanes, each comp part tinted by the take it came from. List diffs share listDiff() in edit-views.ts. Lists are capped so an entry stays a few KB. Add a command in M.summary, KIND_OF (edit-views.ts) and an example in src/demo/examples.ts together; 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-overview in 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-body and .measure are inline-size containers), 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() in edit-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 their Narrow story.
  • Components: a feature's parts nest under its main component (Object.assign(LogView, { Rows, Details, … }) in the folder's index.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 its index.ts only, 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.css as styles and any other module as <name>Styles (chartStyles, drawerStyles), and joins classes with cx(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 .rowSelected still wins). src/styles.css keeps 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 shared styles/ 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 in src/components/ and src/features/ has a sibling <Name>.stories.tsx, written against the namespace (component: Measurement.Loudness) (a Default story with every state side by side, and a Playground with controls); behaviour lives in <Name>.test.stories.tsx (title …/Tests, tags: ['test']) as play functions. src/test/stories.test.tsx runs 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) and exampleFeed() in src/demo/feed.ts (the ?demo bridge on a frozen clock and seeded dice). examples.test.ts fails 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_RUNNING in src/lib/commands.ts and mcp_bridge.lua, kept equal by status.test.ts.
  • Installable PWA: apps/bridge-ui/public/ (manifest, service worker, icons) is copied next to the page; every file is mcp_bridge* and the service worker is scoped to /mcp_bridge so REAPER's other web remotes are untouched.
  • Sessions: each reaper-mcp serve process tags every command with flat top-level sessionId / sessionDir / sessionClient (from Claude Code's CLAUDE_CODE_SESSION_ID / CLAUDE_PROJECT_DIR, else pid-<n> / cwd — no hook needed) and pings _session every 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 carry s (session) and p (params JSON, truncated to 400 chars).
  • Settings the page writes via /_/SET/EXTSTATE[PERSIST]/MCPBridge/<key>/<0|1>, echoed back in status.settings: cfg_paused (in-memory: every non-_ command fails until resumed or REAPER restarts), cfg_readonly (persistent: only get_/list_/read_/analyze_/search_/measure_ + transport/navigation pass — readonly_allows(), mirrored by commandKind() in src/lib/commands.ts), cfg_open_on_start (persistent, overrides OPEN_UI_ON_START), cfg_autostart (persistent, default on: read at REAPER's launch by the block setup writes at the top of Scripts/__startup.lua — AUTOSTART_BLOCK / ensureBridgeAutostart() in cli.ts — which runs mcp_bridge.lua as its own action unless it is "0"; the bridge only echoes it as settings.autostart). Desktop error notifications are page-side (Notification API + localStorage).
  • status.health (re-checked every 10s): SWS present, JSFX installed in Effects/reaper-mcp/ (or its Meters/ folder, where ReaPack puts them), autostart when Scripts/__startup.lua holds the startup block (the Settings toggle explains how to add it when not), and outdated when the installed mcp_bridge.lua differs from the running copy (setup ran; restart the script). Tested in wasmoon by bridge-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 on main, git pull --ff-only, git stash apply, then install.sh; a conflicting apply is reset and the work stays in the named stash; refuses uncommitted changes off main; scripts/test-update-clone.sh) detached, with the clone path, or for an npm install mode=npm with the node and CLI paths, from Scripts/mcp_update.conf (written by setup; never on Windows). The bridge starts with set_action_options(1) (REAPER 7.03+), so re-running mcp_bridge.lua stops it; restart switches to set_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 when startedAt changes (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 Changed lines 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 same update request, 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 sessionStorage mcp-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 from main on GitHub (so a newer release shows its highlights before the update) or the working tree under the dev server; matched to a release by pr or version. Written by the repo-only /changelog-highlight skill with apps/bridge-ui/scripts/changelog-capture.mjs (records/captures ?demo); highlights-files.test.ts checks every entry, media size and SVG safety. Developer mode (settings.dev): setup writes dev=1 for a clone with uncommitted changes, a branch other than main or unpushed commits (isDevClone() in cli.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 detached find -newer mcp_update.conf every 5s, control.changed), the header shows Rebuild & reload (request rebuild-<token>): update.sh --rebuild builds the working tree as it is (--skip-nx-cache) and runs setup, 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), and instrumentToolHandlers logs a one-line sidecarMissingLog() 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 sends sidecar / sidecarsep / sidecarchords / sidecarlite (request/<action>-<token>); the bridge runs node <cli> setup-sidecar --yes [--with-separation|--with-chords|--without-aesthetics] detached (sidecar_job in mcp_bridge.lua, sidecar.log / sidecar.exit) and publishes control.canInstallSidecar + control.sidecar ({kind, state, log}). Needs the CLI from mcp_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 (jobToast and friends in components/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 list list_available_fx returns) to ExtState MCPBridge/installed as {v, supported, fx:[{n,t}]}, re-enumerated every 60s and republished only on change (.jsfx-inc libraries are skipped). FX in the open project (track, master, input and take FX, by original name via fx_name) go to ExtState MCPBridge/used as {v, fx:[{n,c}]}, recounted when the project state changes; the page polls used every 5s and installed every 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 /mcp endpoint does not): the built-in layer with the public token, which build-config.mjs reads out of tools/knowledge.ts at build time, and the viewer's own user:: records only with their own lk_ro_ token from Settings (kept in ~/.config/reaper-mcp/lorekit.json by the bridge; the lk_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 have user:: records) opens GitHub's new-file page with them as one file under knowledge/contributions/ (format and checks: apps/bridge-ui/src/features/plugins/plugin-contributions.mjs), so GitHub forks and opens the PR. The plugin-contributions workflow (pull_request_target, never runs PR code) comments what would be published; the maintainer's publish-to-lorekit label writes them to the built-in layer with secret LOREKIT_PUBLISH_TOKEN (lk_rw_, a writer in the reaper-mcp org) and closes the PR. Files a maintainer commits straight to main are published by running the workflow by hand (workflow_dispatch, job publish-main, optional dry_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_HERE in src/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 the reaper-mcp LoreKit org can skip GitHub: an lk_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 same parseContribution checks, POST /memories with org: reaper-mcp, then soft-archives the user:: 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 the contributor-request GitHub issue form (.github/ISSUE_TEMPLATE/contributor-request.yml). Logic: publishRecord() in src/features/plugins/lorekit.ts; ?demo fakes 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 when status.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 ExtState snap_seen/<ms> and reads snapshots once 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 rewrites snapshots only 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 ordinary snapshot_restore / _save / _delete / _edit command through the dispatcher (run_command()), so it is logged (entry src: "page"), one undo point, and refused while read-only or paused, then answers in snapshots.result (echoing id). A successful restore from anywhere becomes current (ExtState MCP_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_save writes metadata (name, description, timestamp, trackCount, scoped, fullChunk) ahead of mixerState.
  • Usage statistics: src/lib/analytics.ts is the only module that imports @dash0/sdk-web (pinned); components call track() / trackView() with a typed TrackEvent. Events are listed in apps/bridge-ui/tracking-plan.yaml; add an event there and in TrackEvent together, never with names, search text, tokens or paths. The destination is the server's DEFAULT_DESTINATION (read by build-config.mjs from telemetry-consent.ts), service reaper-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 /changelog are measured separately (startSiteAnalytics(), service reaper-mcp-site, site.* events under site: 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 a data-testid container, 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.json runs scripts/snapshot-releases.mjs (GitHub releases into the gitignored changelog/releases.snapshot.json) then BRIDGE_HOSTED=1 nx build bridge-ui. __HOSTED__ makes the page always the demo (demo-mode.ts), bakes the releases and highlights.json in (no GitHub call from a visitor's browser) and copies changelog/ beside the page for the media. / is the docs front page (a guide is /docs/<slug>; /docs redirects to /), /demo is the demo (vercel.json rewrites; an old root link carrying the bridge page's state, such as /?view=tools, moves to /demo in main.tsx via legacyDemoAddress()), /changelog (= ?page=changelog, Changelog.PageRoute from main.tsx, no bridge polling) the changelog as a page; ?release=0.79.1 or #release-0.79.1 opens 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, so hostedShare() in vite.config.ts writes one HTML copy per kind with its own og:/twitter: tags (src/lib/share-meta.ts; vercel.json rewrites /, /docs/<guide> and /changelog to their copy). The pictures are drawn by apps/bridge-ui/scripts/og-images.mjs and committed in apps/bridge-ui/share/: re-run it after a design change. A single guide shares the docs picture, not its own. Without BRIDGE_HOSTED the 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>.md is the raw file, /llms.txt and /llms-full.txt are generated) and rendered by GitHub as they are. A guide is one .md with frontmatter (title, summary, section start|safe|mix|create|yours|know, order, optional youtube id, poster, duration); docs/guides/README.md has the rules. hostedDocs() in vite.config.ts copies them beside the hosted page (a bad guide fails the hosted build) and serves them from the working tree under pnpm dev:bridge; the REAPER page never bundles them. Markdown takes a doc option for them (relative images, > say: / > your-call: callouts, ::: details, ::: gallery carousels, heading ids). The video loads from youtube-nocookie.com only after a click. docs.test.ts checks 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) and src/lib/timeline.ts (BridgeHistory, LongHistory) and publish_status() / publish_history() / publish_log() in mcp_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:app projects can only depend on type:lib projects
  • type:lib projects can only depend on other type:lib projects
  • 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/protocol alias)
  • 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 with sendCommand() stubbed), *-lib.test.ts and bridge-*.test.ts (the real Lua libraries and bridge running in wasmoon against a fake reaper API); in the bridge page, *.test.stories.tsx play functions (what a viewer sees and does, run by src/test/stories.test.tsx) and *.test.ts next to the pure modules in src/lib/ and src/features/*/ (bridge and LoreKit payloads, URLs)
  • Bridge page in a real browser: node apps/bridge-ui/e2e/drawer-widths.mjs (after pnpm nx build bridge-ui) opens every command in e2e/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 saving MCPBridge/status).
  • Sidecar tests in CI: the sidecar job runs test_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.js

CLI Commands Reference

CommandDescription
serve (default)Start MCP server in stdio mode for Claude Code
setupInstall 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-sidecarInstall 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.
instanceA 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
extensionManage opt-in extensions: list, add <name|folder|git-url>, link <folder>, remove <name>, new <name> (see docs/EXTENSIONS.md)
install-skillsCopy 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
initConnect 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
updateUpdate 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
flagsFeature 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
doctorVerify 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)
statusCheck 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 by reaper-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.

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.