@mthines/reaper-mcp 0.101.1 → 0.103.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/main.js CHANGED
@@ -90,8 +90,8 @@ var GLYPHS = {
90
90
  C: [" \u2588\u2588\u2588\u2588\u2588\u2588\u2557", "\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D", "\u2588\u2588\u2551 ", "\u2588\u2588\u2551 ", "\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557", " \u255A\u2550\u2550\u2550\u2550\u2550\u255D"],
91
91
  " ": [" ", " ", " ", " ", " ", " "]
92
92
  };
93
- function wordmark(text8) {
94
- return [0, 1, 2, 3, 4, 5].map((row) => [...text8].map((ch) => GLYPHS[ch][row]).join(""));
93
+ function wordmark(text9) {
94
+ return [0, 1, 2, 3, 4, 5].map((row) => [...text9].map((ch) => GLYPHS[ch][row]).join(""));
95
95
  }
96
96
  var LOGO_WIDTH = wordmark("REAPER MCP")[0].length;
97
97
  var WAVE = "\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588\u2587\u2586\u2585\u2584\u2583\u2582\u2581\u2582\u2583\u2585\u2587\u2588\u2587\u2585\u2583\u2582\u2581\u2582\u2584\u2586\u2588\u2586\u2584\u2582\u2581";
@@ -122,13 +122,13 @@ function createUi(opts = {}) {
122
122
  ok: (s) => sgr(STATUS_CODE.ok, s),
123
123
  warn: (s) => sgr(STATUS_CODE.warn, s),
124
124
  fail: (s) => sgr(STATUS_CODE.fail, s),
125
- status: (status, text8) => sgr(STATUS_CODE[status], text8),
125
+ status: (status, text9) => sgr(STATUS_CODE[status], text9),
126
126
  mark: (status) => sgr(STATUS_CODE[status], STATUS_MARK[status]),
127
127
  gradient: (s) => spread(s),
128
- heading: (text8, note) => `${sgr("1", text8)}${note ? sgr("2", ` ${note}`) : ""}`,
128
+ heading: (text9, note) => `${sgr("1", text9)}${note ? sgr("2", ` ${note}`) : ""}`,
129
129
  section: (title) => `
130
130
  ${sgr("1", title)}`,
131
- item: (status, text8) => ` ${sgr(STATUS_CODE[status], STATUS_MARK[status])} ${text8}`,
131
+ item: (status, text9) => ` ${sgr(STATUS_CODE[status], STATUS_MARK[status])} ${text9}`,
132
132
  banner: (subtitle, version) => {
133
133
  const plain = `REAPER MCP \u2014 ${subtitle}`;
134
134
  if (!fancy) return plain + "\n";
@@ -617,8 +617,8 @@ function getTraceContext() {
617
617
  return { trace_id: ctx.traceId, span_id: ctx.spanId };
618
618
  }
619
619
  var HOME_DIR = homedir2();
620
- function redactHome(text8) {
621
- return HOME_DIR && HOME_DIR !== "/" ? text8.split(HOME_DIR).join("~") : text8;
620
+ function redactHome(text9) {
621
+ return HOME_DIR && HOME_DIR !== "/" ? text9.split(HOME_DIR).join("~") : text9;
622
622
  }
623
623
  var SEVERITY = {
624
624
  debug: SeverityNumber.DEBUG,
@@ -888,13 +888,13 @@ async function ensureBridgeDir() {
888
888
  var BRIDGE_NOT_RUNNING_PREFIX = "Bridge not running:";
889
889
  var BRIDGE_OUTDATED_PREFIX = "Bridge outdated:";
890
890
  var UNKNOWN_COMMAND_PREFIX = "Unknown command type";
891
- function classifyBridgeError(error7) {
892
- if (error7?.startsWith("Timeout:")) return "timeout";
893
- if (error7?.startsWith(BRIDGE_NOT_RUNNING_PREFIX)) return "bridge_not_running";
894
- if (error7?.startsWith(BRIDGE_OUTDATED_PREFIX)) return "bridge_outdated";
895
- if (error7?.startsWith("Handler error:")) return "handler_crash";
896
- if (error7?.startsWith(UNKNOWN_COMMAND_PREFIX)) return "unknown_command";
897
- if (error7?.startsWith("Internal error:")) return "internal_error";
891
+ function classifyBridgeError(error8) {
892
+ if (error8?.startsWith("Timeout:")) return "timeout";
893
+ if (error8?.startsWith(BRIDGE_NOT_RUNNING_PREFIX)) return "bridge_not_running";
894
+ if (error8?.startsWith(BRIDGE_OUTDATED_PREFIX)) return "bridge_outdated";
895
+ if (error8?.startsWith("Handler error:")) return "handler_crash";
896
+ if (error8?.startsWith(UNKNOWN_COMMAND_PREFIX)) return "unknown_command";
897
+ if (error8?.startsWith("Internal error:")) return "internal_error";
898
898
  return "command_failed";
899
899
  }
900
900
  function isSystemError(type) {
@@ -1293,16 +1293,16 @@ function stopPollers() {
1293
1293
  }
1294
1294
 
1295
1295
  // apps/reaper-mcp-server/src/tool-log.ts
1296
- function logToolResult(command2, params, startedAt, r, error7) {
1297
- if (error7) notePageLogged();
1296
+ function logToolResult(command2, params, startedAt, r, error8) {
1297
+ if (error8) notePageLogged();
1298
1298
  void sendCommand("_log_result", {
1299
1299
  command: command2,
1300
1300
  ms: Date.now() - startedAt,
1301
- ok: error7 ? 0 : 1,
1301
+ ok: error8 ? 0 : 1,
1302
1302
  p: JSON.stringify(params).slice(0, 400),
1303
1303
  // Nested values travel as a JSON string: the bridge's fallback parser only reads flat params
1304
1304
  ...r ? { r: JSON.stringify(r) } : {},
1305
- ...error7 ? { e: error7.slice(0, 300) } : {}
1305
+ ...error8 ? { e: error8.slice(0, 300) } : {}
1306
1306
  }, 2e3).catch(() => {
1307
1307
  });
1308
1308
  }
@@ -1475,12 +1475,12 @@ function sidecarNotInstalledMessage(command2 = SETUP_SIDECAR_COMMAND) {
1475
1475
  }
1476
1476
  var SIDECAR_NOT_INSTALLED_MSG = sidecarNotInstalledMessage();
1477
1477
  var MISSING_LOG_PREFIX = "Python sidecar not installed. Run in a terminal:";
1478
- function sidecarMissingLog(text8) {
1479
- const command2 = text8.match(/reaper-mcp setup-sidecar(?: --[\w-]+)*/)?.[0] ?? SETUP_SIDECAR_COMMAND;
1478
+ function sidecarMissingLog(text9) {
1479
+ const command2 = text9.match(/reaper-mcp setup-sidecar(?: --[\w-]+)*/)?.[0] ?? SETUP_SIDECAR_COMMAND;
1480
1480
  return `${MISSING_LOG_PREFIX} ${command2}`;
1481
1481
  }
1482
- function isSidecarMissing(text8) {
1483
- return /sidecar not installed|needs the Python sidecar|(?:audiobox-aesthetics|Stem separation|chord model|FluidSynth native library)[^.]*(?:is )?not installed/i.test(text8);
1482
+ function isSidecarMissing(text9) {
1483
+ return /sidecar not installed|needs the Python sidecar|(?:audiobox-aesthetics|Stem separation|chord model|FluidSynth native library)[^.]*(?:is )?not installed/i.test(text9);
1484
1484
  }
1485
1485
 
1486
1486
  // apps/reaper-mcp-server/src/server.ts
@@ -1497,9 +1497,9 @@ function withNotices(result) {
1497
1497
  const res = result;
1498
1498
  if (!res || !Array.isArray(res.content)) return result;
1499
1499
  const notices = pending.splice(0);
1500
- const text8 = [NOTICE_HEADING, ...notices.map((n) => `- ${n.text}`)].join("\n");
1500
+ const text9 = [NOTICE_HEADING, ...notices.map((n) => `- ${n.text}`)].join("\n");
1501
1501
  for (const n of notices) n.onDelivered?.();
1502
- return { ...res, content: [...res.content, { type: "text", text: text8 }] };
1502
+ return { ...res, content: [...res.content, { type: "text", text: text9 }] };
1503
1503
  }
1504
1504
 
1505
1505
  // apps/reaper-mcp-server/src/tools/project.ts
@@ -4604,7 +4604,7 @@ var TOOL_CATEGORIES = {
4604
4604
  analysis: {
4605
4605
  name: "analysis",
4606
4606
  description: "Audio metering and analysis: peak/RMS meters, FFT spectrum, LUFS loudness, stereo correlation, crest factor, one-call multi-metric measurement (measure_tracks), perceptual aesthetics scores, offline render-based loudness/LRA/true-peak/spectrum with reference comparison, multi-mic time alignment, checking the result of an edit against the audio from before it (verify_edit), transient detection and transient-driven automation e.g. for lighting, loudness over time, stereo correlation per band, masking between tracks, stem separation (the render-based tools need the Python sidecar; stem separation also its --with-separation install), musical key detection (MIDI notes, or audio via the sidecar)",
4607
- tools: ["read_track_meters", "read_track_spectrum", "read_track_lufs", "read_track_correlation", "read_track_crest", "measure_tracks", "analyze_track_aesthetics", "analyze_track_offline", "analyze_audio_file", "measure_track_alignment", "verify_edit", "detect_transients", "create_transient_automation", "analyze_loudness_curve", "analyze_stereo_bands", "measure_masking", "separate_stems", "detect_key", "detect_chords"]
4607
+ tools: ["read_track_meters", "read_track_spectrum", "read_track_lufs", "read_track_correlation", "read_track_crest", "measure_tracks", "analyze_track_aesthetics", "analyze_track_offline", "analyze_audio_file", "measure_track_alignment", "verify_edit", "detect_transients", "create_transient_automation", "detect_vocal_pitch", "correct_vocal_pitch", "analyze_loudness_curve", "analyze_stereo_bands", "measure_masking", "separate_stems", "detect_key", "detect_chords"]
4608
4608
  },
4609
4609
  discovery: {
4610
4610
  name: "discovery",
@@ -5026,15 +5026,15 @@ function ensureBridgeAutostart(startup) {
5026
5026
  const lines = startup.split(/\r?\n/);
5027
5027
  const begin = lines.indexOf(AUTOSTART_BEGIN);
5028
5028
  const end = begin === -1 ? -1 : lines.indexOf(AUTOSTART_END, begin);
5029
- let text8;
5029
+ let text9;
5030
5030
  if (begin !== -1 && end !== -1) {
5031
- text8 = [...lines.slice(0, begin), ...AUTOSTART_BLOCK, ...lines.slice(end + 1)].join(eol);
5031
+ text9 = [...lines.slice(0, begin), ...AUTOSTART_BLOCK, ...lines.slice(end + 1)].join(eol);
5032
5032
  } else if (startup.trim() === "") {
5033
- text8 = block + eol;
5033
+ text9 = block + eol;
5034
5034
  } else {
5035
- text8 = block + eol + eol + startup;
5035
+ text9 = block + eol + eol + startup;
5036
5036
  }
5037
- return { text: text8, changed: text8 !== startup };
5037
+ return { text: text9, changed: text9 !== startup };
5038
5038
  }
5039
5039
  function readExtState(ini, section, key) {
5040
5040
  let inSection = false;
@@ -5261,6 +5261,8 @@ var MCP_TOOL_NAMES = [
5261
5261
  "measure_track_alignment",
5262
5262
  "verify_edit",
5263
5263
  "detect_transients",
5264
+ "detect_vocal_pitch",
5265
+ "correct_vocal_pitch",
5264
5266
  "create_transient_automation",
5265
5267
  // mixing depth
5266
5268
  "set_automation_mode",
@@ -5357,7 +5359,7 @@ var __dirname = dirname3(fileURLToPath2(import.meta.url));
5357
5359
  var SIDECAR_VENV_PATH = join5(homedir4(), ".reaper-mcp", "sidecar-venv");
5358
5360
  var SIDECAR_DIR = join5(homedir4(), ".reaper-mcp", "sidecar");
5359
5361
  var SIDECAR_SCRIPT_DEST = join5(SIDECAR_DIR, "server.py");
5360
- var SIDECAR_MODULES = ["analysis.py", "mixcheck.py", "separation.py", "chords.py", "voice_sketch.py", "voice_render.py", "verify.py"];
5362
+ var SIDECAR_MODULES = ["analysis.py", "mixcheck.py", "separation.py", "chords.py", "voice_sketch.py", "voice_render.py", "pitch.py", "verify.py"];
5361
5363
  var SEPARATION_MODEL = "htdemucs";
5362
5364
  var MODEL_ID = "facebook/audiobox-aesthetics";
5363
5365
  var AESTHETICS_WEIGHTS_PATH = join5(process.env["HF_HOME"] ? join5(process.env["HF_HOME"], "hub") : join5(homedir4(), ".cache", "huggingface", "hub"), "models--facebook--audiobox-aesthetics");
@@ -5822,6 +5824,9 @@ var SidecarClientImpl = class {
5822
5824
  transients(params) {
5823
5825
  return this.call("transients", { ...params });
5824
5826
  }
5827
+ detectPitch(params) {
5828
+ return this.call("detect_pitch", { ...params });
5829
+ }
5825
5830
  loudnessCurve(params) {
5826
5831
  return this.call("loudness_curve", { ...params });
5827
5832
  }
@@ -6712,29 +6717,211 @@ function registerTransientTools(server) {
6712
6717
  );
6713
6718
  }
6714
6719
 
6715
- // apps/reaper-mcp-server/src/tools/mixcheck.ts
6720
+ // apps/reaper-mcp-server/src/tools/pitch.ts
6716
6721
  import { z as z30 } from "zod/v4";
6722
+ var DEFAULT_TRACK_SECONDS2 = 60;
6723
+ var EDGE_FADE = 4e-3;
6724
+ var EPS = 1e-3;
6725
+ var text3 = (data) => ({ content: [{ type: "text", text: JSON.stringify(data, null, 2) }] });
6726
+ var error3 = (message) => ({ content: [{ type: "text", text: message }], isError: true });
6727
+ var SCALES = ["major", "minor", "harmonic_minor", "major_pentatonic", "minor_pentatonic", "chromatic"];
6728
+ var detectSchema = {
6729
+ trackIndex: z30.coerce.number().int().min(0).optional().describe("Track with the vocal, read from its own items before track FX and fader. Give this or path"),
6730
+ path: z30.string().min(1).optional().describe("Absolute path of an audio file to analyze instead of a track (read as-is)"),
6731
+ filePosition: z30.coerce.number().min(0).optional().describe("With path: project time (seconds) where the file starts, so times come back in project time"),
6732
+ startTime: z30.coerce.number().min(0).optional().describe("Start of the range in project seconds (default 0)"),
6733
+ endTime: z30.coerce.number().min(0).optional().describe(`End of the range in project seconds (default start + ${DEFAULT_TRACK_SECONDS2} s)`),
6734
+ key: z30.string().min(1).optional().default("auto").describe("Tonic of the key: C, F#, Bb \u2026 or auto (found from the notes; check keyConfidence before trusting it)"),
6735
+ scale: z30.enum(SCALES).optional().default("major").describe("Scale (ignored when key is auto: major or minor is found)"),
6736
+ strength: z30.coerce.number().min(0).max(1).optional().default(1).describe("How far onto the note each shift goes: 1 = all the way, 0.5 = half way (default 1)"),
6737
+ maxShiftCents: z30.coerce.number().min(10).max(600).optional().default(200).describe("A note further than this from its target is left alone, as sung on purpose (default 200)"),
6738
+ engine: z30.enum(["auto", "swiftf0", "yin"]).optional().default("auto").describe("Pitch tracker: auto (SwiftF0 when installed, else YIN), swiftf0 or yin"),
6739
+ minNoteMs: z30.coerce.number().min(30).max(1e3).optional().default(80).describe("Shortest note to treat as a note (default 80 ms)")
6740
+ };
6741
+ var round2 = (x, digits = 4) => Math.round(x * 10 ** digits) / 10 ** digits;
6742
+ async function detect2(args) {
6743
+ const sidecar = getSidecarClient();
6744
+ if (!sidecar.isAvailable()) return SIDECAR_NOT_INSTALLED_MSG;
6745
+ const { trackIndex: trackIndex5, path } = args;
6746
+ if (trackIndex5 == null === (path == null)) return "Give exactly one of trackIndex or path";
6747
+ const options = {
6748
+ key: args.key ?? "auto",
6749
+ scale: args.scale ?? "major",
6750
+ strength: args.strength ?? 1,
6751
+ maxShiftCents: args.maxShiftCents ?? 200,
6752
+ engine: args.engine ?? "auto",
6753
+ minNoteMs: args.minNoteMs ?? 80
6754
+ };
6755
+ const position = args.filePosition ?? 0;
6756
+ const start = args.startTime ?? position;
6757
+ const end = args.endTime ?? start + DEFAULT_TRACK_SECONDS2;
6758
+ if (end <= start) return "endTime must be greater than startTime";
6759
+ if (end - start > MAX_OFFLINE_SECONDS) return `Range too long: max ${MAX_OFFLINE_SECONDS} s per call`;
6760
+ let result;
6761
+ let offset;
6762
+ if (path != null) {
6763
+ if (start < position) return `startTime ${start} is before the file starts (filePosition ${position})`;
6764
+ result = await sidecar.detectPitch({ path, startTime: start - position, endTime: end - position, ...options });
6765
+ offset = position;
6766
+ } else {
6767
+ let wav;
6768
+ try {
6769
+ wav = await renderTrack(trackIndex5, start, end, { dry: true });
6770
+ } catch (err) {
6771
+ return err instanceof Error ? err.message : String(err);
6772
+ }
6773
+ try {
6774
+ result = await sidecar.detectPitch({ path: wav.wavPath, ...options });
6775
+ } finally {
6776
+ await discardRender(wav);
6777
+ }
6778
+ offset = start;
6779
+ }
6780
+ const notes = (result["notes"] ?? []).map((n) => ({
6781
+ ...n,
6782
+ start: round2(n.start + offset),
6783
+ end: round2(n.end + offset)
6784
+ }));
6785
+ const { notes: _notes, ...summary } = result;
6786
+ return { start, end, notes, summary };
6787
+ }
6788
+ async function listItems(trackIndex5) {
6789
+ const res = await sendCommand("list_media_items", { trackIndex: trackIndex5 });
6790
+ if (!res.success) return res.error ?? "list_media_items failed";
6791
+ return (res.data.items ?? []).filter((i) => !i.isMidi);
6792
+ }
6793
+ async function isolate(trackIndex5, start, end) {
6794
+ let items = await listItems(trackIndex5);
6795
+ if (typeof items === "string") return items;
6796
+ const holds = (i) => i.position <= start + EPS && i.position + i.length >= end - EPS;
6797
+ let item = items.find(holds);
6798
+ if (!item) return "the note is not inside one item";
6799
+ if (end < item.position + item.length - EPS) {
6800
+ const res = await sendCommand("split_media_item", { trackIndex: trackIndex5, itemIndex: item.itemIndex, position: end });
6801
+ if (!res.success) return res.error ?? "split failed";
6802
+ }
6803
+ if (start > item.position + EPS) {
6804
+ const res = await sendCommand("split_media_item", { trackIndex: trackIndex5, itemIndex: item.itemIndex, position: start });
6805
+ if (!res.success) return res.error ?? "split failed";
6806
+ }
6807
+ items = await listItems(trackIndex5);
6808
+ if (typeof items === "string") return items;
6809
+ item = items.find((i) => Math.abs(i.position - start) < EPS && i.position + i.length <= end + EPS);
6810
+ return item ? item.itemIndex : "could not find the piece after splitting";
6811
+ }
6812
+ var { path: _path, filePosition: _filePosition, ...trackSchema } = {
6813
+ ...detectSchema,
6814
+ trackIndex: z30.coerce.number().int().min(0).describe("Track with the vocal")
6815
+ };
6816
+ function registerPitchTools(server) {
6817
+ server.tool(
6818
+ "detect_vocal_pitch",
6819
+ "Find the sung notes in a vocal track (read from its own items, before track FX and fader) or audio file and say how far each sits from the nearest note of a key: per note its time range in project seconds, the pitch it was sung at (a fractional MIDI number, 60 = C4), the scale note it belongs to, offsetCents (positive = sung flat, needs raising) and shiftCents (what correct_vocal_pitch would apply after strength, the dead zone and maxShiftCents). Also the key used, averageOffsetCents (a singer who is flat or sharp on the whole) and voicedShare. Monophonic: one voice at a time. Read-only. Requires the Python sidecar.",
6820
+ detectSchema,
6821
+ async (args) => {
6822
+ const startedAt = Date.now();
6823
+ try {
6824
+ const d = await detect2(args);
6825
+ if (typeof d === "string") {
6826
+ logToolResult("detect_vocal_pitch", args, startedAt, null, d);
6827
+ return error3(d);
6828
+ }
6829
+ logToolResult("detect_vocal_pitch", args, startedAt, null);
6830
+ return text3({ startTime: d.start, endTime: d.end, ...d.summary, total: d.notes.length, notes: d.notes });
6831
+ } catch (err) {
6832
+ const message = err instanceof Error ? err.message : String(err);
6833
+ logToolResult("detect_vocal_pitch", args, startedAt, null, message);
6834
+ return error3(message);
6835
+ }
6836
+ }
6837
+ );
6838
+ server.tool(
6839
+ "correct_vocal_pitch",
6840
+ "Tune a vocal to a key: detect the sung notes of a track (same options as detect_vocal_pitch), then split its audio item at each note that is off and set that piece's pitch (REAPER's own pitch engine, semitones to the cent) so it lands on the nearest scale note. One shift per note, so vibrato and slides inside a note stay as sung. Pieces get a few ms of fade at the cut. Refuses when an item in the range already has a pitch set (so a second run never doubles the shift). Each edit is its own undo point; use dryRun to see the plan first and run detect_vocal_pitch afterwards to check the result by ear and by number. Requires the Python sidecar.",
6841
+ {
6842
+ ...trackSchema,
6843
+ dryRun: z30.boolean().optional().default(false).describe("Report the planned shifts without touching the project")
6844
+ },
6845
+ async (args) => {
6846
+ const startedAt = Date.now();
6847
+ const log = (e) => logToolResult("correct_vocal_pitch", args, startedAt, null, e);
6848
+ try {
6849
+ const d = await detect2(args);
6850
+ if (typeof d === "string") {
6851
+ log(d);
6852
+ return error3(d);
6853
+ }
6854
+ const todo = d.notes.filter((n) => n.shiftCents !== 0);
6855
+ if (args.dryRun || todo.length === 0) {
6856
+ log();
6857
+ return text3({ dryRun: Boolean(args.dryRun), ...d.summary, total: d.notes.length, toCorrect: todo.length, notes: d.notes });
6858
+ }
6859
+ const items = await listItems(args.trackIndex);
6860
+ if (typeof items === "string") {
6861
+ log(items);
6862
+ return error3(items);
6863
+ }
6864
+ for (const item of items.filter((i) => i.position < d.end && i.position + i.length > d.start)) {
6865
+ const props = await sendCommand("get_media_item_properties", { trackIndex: args.trackIndex, itemIndex: item.itemIndex });
6866
+ const pitch = props.success ? Number(props.data.pitch ?? 0) : 0;
6867
+ if (Math.abs(pitch) > 1e-6) {
6868
+ const message = `An item at ${round2(item.position, 2)} s already has its pitch set to ${pitch} semitones; set it back to 0 first so the shift is not doubled`;
6869
+ log(message);
6870
+ return error3(message);
6871
+ }
6872
+ }
6873
+ const applied = [];
6874
+ const failed = [];
6875
+ for (const note of [...todo].sort((a, b) => b.start - a.start)) {
6876
+ const index = await isolate(args.trackIndex, note.start, note.end);
6877
+ if (typeof index === "string") {
6878
+ failed.push({ start: note.start, reason: index });
6879
+ continue;
6880
+ }
6881
+ const res = await sendCommand("set_media_item_properties", {
6882
+ trackIndex: args.trackIndex,
6883
+ itemIndex: index,
6884
+ pitch: round2(note.shiftCents / 100, 3),
6885
+ fadeInLength: EDGE_FADE,
6886
+ fadeOutLength: EDGE_FADE
6887
+ });
6888
+ if (res.success) applied.push(note);
6889
+ else failed.push({ start: note.start, reason: res.error ?? "set_media_item_properties failed" });
6890
+ }
6891
+ log(failed.length === todo.length ? "no note could be corrected" : void 0);
6892
+ return text3({ ...d.summary, total: d.notes.length, corrected: applied.length, failed, notes: applied.reverse() });
6893
+ } catch (err) {
6894
+ const message = err instanceof Error ? err.message : String(err);
6895
+ log(message);
6896
+ return error3(message);
6897
+ }
6898
+ }
6899
+ );
6900
+ }
6901
+
6902
+ // apps/reaper-mcp-server/src/tools/mixcheck.ts
6903
+ import { z as z31 } from "zod/v4";
6717
6904
  import { homedir as homedir6 } from "node:os";
6718
6905
  import { basename as basename2, extname, join as join7 } from "node:path";
6719
6906
  import { trace as trace6 } from "@opentelemetry/api";
6720
- var DEFAULT_TRACK_SECONDS2 = 180;
6907
+ var DEFAULT_TRACK_SECONDS3 = 180;
6721
6908
  var SEPARATION_TRACK_SECONDS = 60;
6722
6909
  var MAX_MASKING_SECONDS = 60;
6723
6910
  var DEFAULT_MASKING_SECONDS = 20;
6724
6911
  var MAX_MASKING_TRACKS = 8;
6725
6912
  var MAX_SEPARATION_SECONDS = 600;
6726
6913
  var separationTimeoutMs = (seconds2) => 9e4 + seconds2 * 3e3;
6727
- var text3 = (data) => ({ content: [{ type: "text", text: JSON.stringify(data, null, 2) }] });
6728
- var error3 = (message) => ({ content: [{ type: "text", text: message }], isError: true });
6914
+ var text4 = (data) => ({ content: [{ type: "text", text: JSON.stringify(data, null, 2) }] });
6915
+ var error4 = (message) => ({ content: [{ type: "text", text: message }], isError: true });
6729
6916
  var messageOf = (err) => err instanceof Error ? err.message : String(err);
6730
6917
  var round12 = (x) => Math.round(x * 10) / 10;
6731
6918
  var sourceSchema2 = {
6732
- trackIndex: z30.coerce.number().int().min(-1).optional().describe("Track to analyze, rendered post-FX (-1 = master: the whole mix). Give this or path"),
6733
- path: z30.string().min(1).optional().describe("Absolute path of an audio file (WAV/FLAC/AIFF/MP3/OGG) instead of a track, e.g. a reference song"),
6734
- startTime: z30.coerce.number().min(0).optional().describe("Start in seconds (default 0)"),
6735
- endTime: z30.coerce.number().min(0).optional().describe(`End in seconds (track default: startTime + ${DEFAULT_TRACK_SECONDS2}; file default: its end)`)
6919
+ trackIndex: z31.coerce.number().int().min(-1).optional().describe("Track to analyze, rendered post-FX (-1 = master: the whole mix). Give this or path"),
6920
+ path: z31.string().min(1).optional().describe("Absolute path of an audio file (WAV/FLAC/AIFF/MP3/OGG) instead of a track, e.g. a reference song"),
6921
+ startTime: z31.coerce.number().min(0).optional().describe("Start in seconds (default 0)"),
6922
+ endTime: z31.coerce.number().min(0).optional().describe(`End in seconds (track default: startTime + ${DEFAULT_TRACK_SECONDS3}; file default: its end)`)
6736
6923
  };
6737
- async function resolveSource(args, maxSeconds, defaultSeconds = DEFAULT_TRACK_SECONDS2) {
6924
+ async function resolveSource(args, maxSeconds, defaultSeconds = DEFAULT_TRACK_SECONDS3) {
6738
6925
  const { trackIndex: trackIndex5, path, startTime, endTime } = args;
6739
6926
  if (trackIndex5 == null === (path == null)) return "Give either trackIndex or path";
6740
6927
  if (startTime != null && endTime != null && endTime <= startTime) return "endTime must be greater than startTime";
@@ -6782,20 +6969,20 @@ function registerMixcheckTools(server) {
6782
6969
  "Loudness over time of a track (or the master, -1) or an audio file: short-term (3 s) and momentary (400 ms) LUFS as curves (at most 240 points each, every point the loudest moment of its slice), integrated LUFS, true peak, LRA, PLR (true peak minus integrated), the loudest and quietest 3 s windows, and with targetLufs the spans whose short-term loudness goes over target + toleranceLu. Use it to see where a master gets too loud or a section drops away, before and after a change. Rendered once, no playback. Requires the Python sidecar.",
6783
6970
  {
6784
6971
  ...sourceSchema2,
6785
- targetLufs: z30.coerce.number().min(-40).max(0).optional().describe("Report the spans whose short-term loudness is above this (e.g. -14 for streaming)"),
6786
- toleranceLu: z30.coerce.number().min(0).max(6).optional().default(1).describe("LU above targetLufs before a span counts (default 1)")
6972
+ targetLufs: z31.coerce.number().min(-40).max(0).optional().describe("Report the spans whose short-term loudness is above this (e.g. -14 for streaming)"),
6973
+ toleranceLu: z31.coerce.number().min(0).max(6).optional().default(1).describe("LU above targetLufs before a span counts (default 1)")
6787
6974
  },
6788
6975
  async (args) => {
6789
6976
  const startedAt = Date.now();
6790
6977
  const sidecar = getSidecarClient();
6791
- if (!sidecar.isAvailable()) return error3(SIDECAR_NOT_INSTALLED_MSG);
6978
+ if (!sidecar.isAvailable()) return error4(SIDECAR_NOT_INSTALLED_MSG);
6792
6979
  let src;
6793
6980
  try {
6794
6981
  src = await resolveSource(args, MAX_OFFLINE_SECONDS);
6795
6982
  } catch (err) {
6796
- return error3(messageOf(err));
6983
+ return error4(messageOf(err));
6797
6984
  }
6798
- if (typeof src === "string") return error3(src);
6985
+ if (typeof src === "string") return error4(src);
6799
6986
  try {
6800
6987
  const result = await sidecar.loudnessCurve({
6801
6988
  path: src.path,
@@ -6813,10 +7000,10 @@ function registerMixcheckTools(server) {
6813
7000
  if (args.targetLufs != null) data["targetLufs"] = args.targetLufs;
6814
7001
  trace6.getActiveSpan()?.setAttribute("reaper.loudness.over_target_seconds", Number(result["overTargetSeconds"] ?? 0));
6815
7002
  logToolResult("analyze_loudness_curve", args, startedAt, curveSummary(src.name, data));
6816
- return text3(data);
7003
+ return text4(data);
6817
7004
  } catch (err) {
6818
7005
  logToolResult("analyze_loudness_curve", args, startedAt, null, messageOf(err));
6819
- return error3(messageOf(err));
7006
+ return error4(messageOf(err));
6820
7007
  } finally {
6821
7008
  if (src.temp) await discardRender(src.temp);
6822
7009
  }
@@ -6829,14 +7016,14 @@ function registerMixcheckTools(server) {
6829
7016
  async (args) => {
6830
7017
  const startedAt = Date.now();
6831
7018
  const sidecar = getSidecarClient();
6832
- if (!sidecar.isAvailable()) return error3(SIDECAR_NOT_INSTALLED_MSG);
7019
+ if (!sidecar.isAvailable()) return error4(SIDECAR_NOT_INSTALLED_MSG);
6833
7020
  let src;
6834
7021
  try {
6835
7022
  src = await resolveSource(args, MAX_OFFLINE_SECONDS);
6836
7023
  } catch (err) {
6837
- return error3(messageOf(err));
7024
+ return error4(messageOf(err));
6838
7025
  }
6839
- if (typeof src === "string") return error3(src);
7026
+ if (typeof src === "string") return error4(src);
6840
7027
  try {
6841
7028
  const result = await sidecar.stereoBands({ path: src.path, ...src.window });
6842
7029
  const data = {
@@ -6847,10 +7034,10 @@ function registerMixcheckTools(server) {
6847
7034
  const flags = result["flags"] ?? [];
6848
7035
  trace6.getActiveSpan()?.setAttribute("reaper.stereo.flag_count", flags.length);
6849
7036
  logToolResult("analyze_stereo_bands", args, startedAt, stereoBandsSummary(src.name, data));
6850
- return text3(data);
7037
+ return text4(data);
6851
7038
  } catch (err) {
6852
7039
  logToolResult("analyze_stereo_bands", args, startedAt, null, messageOf(err));
6853
- return error3(messageOf(err));
7040
+ return error4(messageOf(err));
6854
7041
  } finally {
6855
7042
  if (src.temp) await discardRender(src.temp);
6856
7043
  }
@@ -6860,16 +7047,16 @@ function registerMixcheckTools(server) {
6860
7047
  "measure_masking",
6861
7048
  `Find where 2-8 tracks compete for the same frequencies: renders each track over the same range (post-FX) and compares their K-weighted third-octave levels (40 Hz-16 kHz). A band scores high when both tracks are loud there and within a few dB of each other. Returns every pair's overall score with its worst bands, and the top conflicts (score >= 0.2) with a suggestion: which track to cut around which frequency (the one the band matters less to). Pick a section where they all play (max ${MAX_MASKING_SECONDS} s). Requires the Python sidecar.`,
6862
7049
  {
6863
- tracks: z30.array(z30.coerce.number().int().min(0)).min(2).max(MAX_MASKING_TRACKS).describe(`Zero-based indexes of 2-${MAX_MASKING_TRACKS} tracks to compare (e.g. kick, bass, keys)`),
6864
- startTime: z30.coerce.number().min(0).describe("Start of the range in seconds"),
6865
- durationSeconds: z30.coerce.number().min(1).max(MAX_MASKING_SECONDS).optional().default(DEFAULT_MASKING_SECONDS).describe(`Length in seconds (default ${DEFAULT_MASKING_SECONDS}, max ${MAX_MASKING_SECONDS})`)
7050
+ tracks: z31.array(z31.coerce.number().int().min(0)).min(2).max(MAX_MASKING_TRACKS).describe(`Zero-based indexes of 2-${MAX_MASKING_TRACKS} tracks to compare (e.g. kick, bass, keys)`),
7051
+ startTime: z31.coerce.number().min(0).describe("Start of the range in seconds"),
7052
+ durationSeconds: z31.coerce.number().min(1).max(MAX_MASKING_SECONDS).optional().default(DEFAULT_MASKING_SECONDS).describe(`Length in seconds (default ${DEFAULT_MASKING_SECONDS}, max ${MAX_MASKING_SECONDS})`)
6866
7053
  },
6867
7054
  async (args) => {
6868
7055
  const { tracks: tracks2, startTime, durationSeconds } = args;
6869
7056
  const startedAt = Date.now();
6870
7057
  const sidecar = getSidecarClient();
6871
- if (!sidecar.isAvailable()) return error3(SIDECAR_NOT_INSTALLED_MSG);
6872
- if (new Set(tracks2).size !== tracks2.length) return error3("tracks must not repeat a track");
7058
+ if (!sidecar.isAvailable()) return error4(SIDECAR_NOT_INSTALLED_MSG);
7059
+ if (new Set(tracks2).size !== tracks2.length) return error4("tracks must not repeat a track");
6873
7060
  const end = startTime + (durationSeconds ?? DEFAULT_MASKING_SECONDS);
6874
7061
  const rendered = [];
6875
7062
  try {
@@ -6896,10 +7083,10 @@ function registerMixcheckTools(server) {
6896
7083
  span?.setAttribute("reaper.masking.track_count", tracks2.length);
6897
7084
  span?.setAttribute("reaper.masking.conflict_count", conflicts.length);
6898
7085
  logToolResult("measure_masking", args, startedAt, maskingSummary(result));
6899
- return text3(data);
7086
+ return text4(data);
6900
7087
  } catch (err) {
6901
7088
  logToolResult("measure_masking", args, startedAt, null, messageOf(err));
6902
- return error3(messageOf(err));
7089
+ return error4(messageOf(err));
6903
7090
  } finally {
6904
7091
  await Promise.all(rendered.map(discardRender));
6905
7092
  }
@@ -6910,33 +7097,33 @@ function registerMixcheckTools(server) {
6910
7097
  `Split a track (rendered post-FX, -1 = master) or an audio file into stems with Demucs: htdemucs gives drums, bass, other, vocals; htdemucs_6s adds guitar and piano. Writes one 32-bit float WAV per stem to outDir (default: a new folder under the project's Stems folder) and returns each stem's path, LUFS and peak. With insertTracks, adds them as tracks under a new folder in one undo point, lined up with the source (a track: after it, at startTime; a file: at filePosition + startTime); the folder starts muted, since the stems sum back to the source. Slow: about real time on a CPU, several times faster on Apple silicon or CUDA (max ${MAX_SEPARATION_SECONDS} s per call). Needs \`reaper-mcp setup-sidecar --with-separation\` (which downloads htdemucs; the first htdemucs_6s call downloads its ~80 MB weights).`,
6911
7098
  {
6912
7099
  ...sourceSchema2,
6913
- endTime: z30.coerce.number().min(0).optional().describe(`End in seconds (track default: startTime + ${SEPARATION_TRACK_SECONDS}; file default: its end)`),
6914
- model: z30.enum(["htdemucs", "htdemucs_6s"]).optional().default("htdemucs").describe("htdemucs (4 stems, default) or htdemucs_6s (adds guitar and piano)"),
6915
- stems: z30.array(z30.enum(["drums", "bass", "other", "vocals", "guitar", "piano"])).min(1).optional().describe("Write only these stems (default: all the model gives)"),
6916
- outDir: z30.string().min(1).optional().describe("Absolute folder for the stem WAVs (created if missing)"),
6917
- insertTracks: z30.boolean().optional().default(false).describe("Insert the stems as tracks under a new folder track (muted)"),
6918
- filePosition: z30.coerce.number().min(0).optional().describe("With path and insertTracks: project time where the file starts (default 0)")
7100
+ endTime: z31.coerce.number().min(0).optional().describe(`End in seconds (track default: startTime + ${SEPARATION_TRACK_SECONDS}; file default: its end)`),
7101
+ model: z31.enum(["htdemucs", "htdemucs_6s"]).optional().default("htdemucs").describe("htdemucs (4 stems, default) or htdemucs_6s (adds guitar and piano)"),
7102
+ stems: z31.array(z31.enum(["drums", "bass", "other", "vocals", "guitar", "piano"])).min(1).optional().describe("Write only these stems (default: all the model gives)"),
7103
+ outDir: z31.string().min(1).optional().describe("Absolute folder for the stem WAVs (created if missing)"),
7104
+ insertTracks: z31.boolean().optional().default(false).describe("Insert the stems as tracks under a new folder track (muted)"),
7105
+ filePosition: z31.coerce.number().min(0).optional().describe("With path and insertTracks: project time where the file starts (default 0)")
6919
7106
  },
6920
7107
  async (args) => {
6921
7108
  const startedAt = Date.now();
6922
7109
  const sidecar = getSidecarClient();
6923
- if (!sidecar.isAvailable()) return error3(SIDECAR_NOT_INSTALLED_MSG);
7110
+ if (!sidecar.isAvailable()) return error4(SIDECAR_NOT_INSTALLED_MSG);
6924
7111
  if (args.model === "htdemucs" && args.stems?.some((s) => s === "guitar" || s === "piano")) {
6925
- return error3("htdemucs has no guitar or piano stem: use model htdemucs_6s");
7112
+ return error4("htdemucs has no guitar or piano stem: use model htdemucs_6s");
6926
7113
  }
6927
7114
  try {
6928
7115
  const status = await sidecar.separationStatus();
6929
- if (!status.installed) return error3(status.message);
7116
+ if (!status.installed) return error4(status.message);
6930
7117
  } catch (err) {
6931
- return error3(messageOf(err));
7118
+ return error4(messageOf(err));
6932
7119
  }
6933
7120
  let src;
6934
7121
  try {
6935
7122
  src = await resolveSource(args, MAX_SEPARATION_SECONDS, SEPARATION_TRACK_SECONDS);
6936
7123
  } catch (err) {
6937
- return error3(messageOf(err));
7124
+ return error4(messageOf(err));
6938
7125
  }
6939
- if (typeof src === "string") return error3(src);
7126
+ if (typeof src === "string") return error4(src);
6940
7127
  try {
6941
7128
  const outDir = args.outDir ?? join7(await defaultStemsRoot(), `${safeName(src.name)}-${stamp()}`);
6942
7129
  const result = await sidecar.separate(
@@ -6980,10 +7167,10 @@ function registerMixcheckTools(server) {
6980
7167
  ...insertError ? { warning: insertError } : {}
6981
7168
  };
6982
7169
  logToolResult("separate_stems", args, startedAt, stemsSummary(src.name, data));
6983
- return text3(data);
7170
+ return text4(data);
6984
7171
  } catch (err) {
6985
7172
  logToolResult("separate_stems", args, startedAt, null, messageOf(err));
6986
- return error3(messageOf(err));
7173
+ return error4(messageOf(err));
6987
7174
  } finally {
6988
7175
  if (src.temp) await discardRender(src.temp);
6989
7176
  }
@@ -6992,14 +7179,14 @@ function registerMixcheckTools(server) {
6992
7179
  }
6993
7180
 
6994
7181
  // apps/reaper-mcp-server/src/tools/mixing.ts
6995
- import { z as z31 } from "zod/v4";
7182
+ import { z as z32 } from "zod/v4";
6996
7183
  import { trace as trace7 } from "@opentelemetry/api";
6997
7184
  var MAX_QUANTIZE_SECONDS = 900;
6998
- var error4 = (text8) => ({ content: [{ type: "text", text: `Error: ${text8}` }], isError: true });
7185
+ var error5 = (text9) => ({ content: [{ type: "text", text: `Error: ${text9}` }], isError: true });
6999
7186
  var ok = (data) => ({ content: [{ type: "text", text: JSON.stringify(data, null, 2) }] });
7000
7187
  async function run3(command2, params, timeoutMs) {
7001
7188
  const res = await sendCommand(command2, params, timeoutMs);
7002
- if (!res.success) return error4(res.error ?? "unknown error");
7189
+ if (!res.success) return error5(res.error ?? "unknown error");
7003
7190
  return { ...ok(res.data), data: res.data };
7004
7191
  }
7005
7192
  function flatten(args, keys) {
@@ -7007,16 +7194,16 @@ function flatten(args, keys) {
7007
7194
  for (const k of keys) if (out2[k] !== void 0) out2[k] = JSON.stringify(out2[k]);
7008
7195
  return out2;
7009
7196
  }
7010
- var trackIndex4 = z31.coerce.number().int().min(-1).describe("0-based track index (-1 = master)");
7011
- var fxIndex2 = z31.coerce.number().int().min(0).describe("0-based FX index in the track's chain");
7012
- var tracks = z31.array(trackRef).min(1).max(64);
7013
- var renderMode = z31.enum(["stereo", "mono", "multichannel"]).optional().default("stereo");
7014
- var automationMode = z31.enum(["trim", "read", "touch", "write", "latch", "latch_preview"]);
7015
- var fxParams = z31.array(z31.object({
7016
- paramIndex: z31.coerce.number().int().min(0),
7017
- value: z31.coerce.number().min(0).max(1).describe("Normalized 0..1")
7197
+ var trackIndex4 = z32.coerce.number().int().min(-1).describe("0-based track index (-1 = master)");
7198
+ var fxIndex2 = z32.coerce.number().int().min(0).describe("0-based FX index in the track's chain");
7199
+ var tracks = z32.array(trackRef).min(1).max(64);
7200
+ var renderMode = z32.enum(["stereo", "mono", "multichannel"]).optional().default("stereo");
7201
+ var automationMode = z32.enum(["trim", "read", "touch", "write", "latch", "latch_preview"]);
7202
+ var fxParams = z32.array(z32.object({
7203
+ paramIndex: z32.coerce.number().int().min(0),
7204
+ value: z32.coerce.number().min(0).max(1).describe("Normalized 0..1")
7018
7205
  })).optional().describe("Parameters to set, normalized 0..1");
7019
- var direction = z31.coerce.number().int().min(-1).max(1).optional().describe("-1 moves the value down from the baseline, 0 around it, 1 up (default)");
7206
+ var direction = z32.coerce.number().int().min(-1).max(1).optional().describe("-1 moves the value down from the baseline, 0 around it, 1 up (default)");
7020
7207
  function registerMixingTools(server) {
7021
7208
  server.tool(
7022
7209
  "set_automation_mode",
@@ -7024,14 +7211,14 @@ function registerMixingTools(server) {
7024
7211
  {
7025
7212
  tracks: tracks.optional().describe("Tracks to set (needs mode)"),
7026
7213
  mode: automationMode.optional(),
7027
- globalOverride: z31.enum(["none", "bypass", "trim", "read", "touch", "write", "latch", "latch_preview"]).optional().describe("Override every track's mode at once; not saved in the project")
7214
+ globalOverride: z32.enum(["none", "bypass", "trim", "read", "touch", "write", "latch", "latch_preview"]).optional().describe("Override every track's mode at once; not saved in the project")
7028
7215
  },
7029
7216
  async (args) => run3("set_automation_mode", flatten(args, ["tracks"]))
7030
7217
  );
7031
7218
  server.tool(
7032
7219
  "get_fx_param_modulation",
7033
7220
  "Read FX parameter modulation (REAPER 6.37+): LFO, audio control signal (sidechain follower) and parameter link, with the baseline. Without paramIndex, lists only the modulated parameters of the FX.",
7034
- { trackIndex: trackIndex4, fxIndex: fxIndex2, paramIndex: z31.coerce.number().int().min(0).optional() },
7221
+ { trackIndex: trackIndex4, fxIndex: fxIndex2, paramIndex: z32.coerce.number().int().min(0).optional() },
7035
7222
  async (args) => run3("get_fx_param_modulation", args)
7036
7223
  );
7037
7224
  server.tool(
@@ -7040,34 +7227,34 @@ function registerMixingTools(server) {
7040
7227
  {
7041
7228
  trackIndex: trackIndex4,
7042
7229
  fxIndex: fxIndex2,
7043
- paramIndex: z31.coerce.number().int().min(0),
7044
- enabled: z31.boolean().optional().describe("false turns off all modulation of this parameter"),
7045
- baseline: z31.coerce.number().min(0).max(1).optional().describe("0..1, the value the modulation moves around"),
7046
- lfo: z31.object({
7047
- enabled: z31.boolean().optional(),
7048
- shape: z31.enum(["sine", "square", "saw_down", "saw_up", "triangle", "random"]).optional(),
7049
- speed: z31.coerce.number().positive().max(64).optional().describe("Hz, or quarter notes per cycle with tempoSync"),
7050
- strength: z31.coerce.number().min(0).max(1).optional(),
7051
- phase: z31.coerce.number().min(0).max(1).optional(),
7052
- tempoSync: z31.boolean().optional(),
7230
+ paramIndex: z32.coerce.number().int().min(0),
7231
+ enabled: z32.boolean().optional().describe("false turns off all modulation of this parameter"),
7232
+ baseline: z32.coerce.number().min(0).max(1).optional().describe("0..1, the value the modulation moves around"),
7233
+ lfo: z32.object({
7234
+ enabled: z32.boolean().optional(),
7235
+ shape: z32.enum(["sine", "square", "saw_down", "saw_up", "triangle", "random"]).optional(),
7236
+ speed: z32.coerce.number().positive().max(64).optional().describe("Hz, or quarter notes per cycle with tempoSync"),
7237
+ strength: z32.coerce.number().min(0).max(1).optional(),
7238
+ phase: z32.coerce.number().min(0).max(1).optional(),
7239
+ tempoSync: z32.boolean().optional(),
7053
7240
  direction
7054
7241
  }).optional(),
7055
- audio: z31.object({
7056
- enabled: z31.boolean().optional(),
7057
- attackMs: z31.coerce.number().min(0).max(1e3).optional(),
7058
- releaseMs: z31.coerce.number().min(0).max(1e3).optional(),
7059
- minDb: z31.coerce.number().min(-60).max(12).optional().describe("Level that maps to no modulation"),
7060
- maxDb: z31.coerce.number().min(-60).max(12).optional().describe("Level that maps to full modulation"),
7061
- strength: z31.coerce.number().min(0).max(1).optional(),
7062
- channel: z31.coerce.number().int().min(1).max(64).optional().describe("Track channel to follow, 1-based (3 = a sidechain on 3/4)"),
7242
+ audio: z32.object({
7243
+ enabled: z32.boolean().optional(),
7244
+ attackMs: z32.coerce.number().min(0).max(1e3).optional(),
7245
+ releaseMs: z32.coerce.number().min(0).max(1e3).optional(),
7246
+ minDb: z32.coerce.number().min(-60).max(12).optional().describe("Level that maps to no modulation"),
7247
+ maxDb: z32.coerce.number().min(-60).max(12).optional().describe("Level that maps to full modulation"),
7248
+ strength: z32.coerce.number().min(0).max(1).optional(),
7249
+ channel: z32.coerce.number().int().min(1).max(64).optional().describe("Track channel to follow, 1-based (3 = a sidechain on 3/4)"),
7063
7250
  direction
7064
7251
  }).optional().describe("Audio control signal: the parameter follows a channel's level"),
7065
- link: z31.object({
7066
- enabled: z31.boolean().optional(),
7067
- fxIndex: z31.coerce.number().int().min(0).optional().describe("Source FX; required unless enabled is false"),
7068
- paramIndex: z31.coerce.number().int().min(0).optional().describe("Source parameter; required unless enabled is false"),
7069
- scale: z31.coerce.number().min(-10).max(10).optional(),
7070
- offset: z31.coerce.number().min(-1).max(1).optional()
7252
+ link: z32.object({
7253
+ enabled: z32.boolean().optional(),
7254
+ fxIndex: z32.coerce.number().int().min(0).optional().describe("Source FX; required unless enabled is false"),
7255
+ paramIndex: z32.coerce.number().int().min(0).optional().describe("Source parameter; required unless enabled is false"),
7256
+ scale: z32.coerce.number().min(-10).max(10).optional(),
7257
+ offset: z32.coerce.number().min(-1).max(1).optional()
7071
7258
  }).optional().describe("Follow another FX parameter on this track")
7072
7259
  },
7073
7260
  async (args) => {
@@ -7091,15 +7278,15 @@ function registerMixingTools(server) {
7091
7278
  {
7092
7279
  trackIndex: trackIndex4,
7093
7280
  fxIndex: fxIndex2,
7094
- inputs: z31.array(z31.union([
7095
- z31.array(z31.coerce.number().int().min(1).max(64)),
7096
- z31.object({ pin: z31.coerce.number().int().min(0), channels: z31.array(z31.coerce.number().int().min(1).max(64)) })
7281
+ inputs: z32.array(z32.union([
7282
+ z32.array(z32.coerce.number().int().min(1).max(64)),
7283
+ z32.object({ pin: z32.coerce.number().int().min(0), channels: z32.array(z32.coerce.number().int().min(1).max(64)) })
7097
7284
  ])).optional(),
7098
- outputs: z31.array(z31.union([
7099
- z31.array(z31.coerce.number().int().min(1).max(64)),
7100
- z31.object({ pin: z31.coerce.number().int().min(0), channels: z31.array(z31.coerce.number().int().min(1).max(64)) })
7285
+ outputs: z32.array(z32.union([
7286
+ z32.array(z32.coerce.number().int().min(1).max(64)),
7287
+ z32.object({ pin: z32.coerce.number().int().min(0), channels: z32.array(z32.coerce.number().int().min(1).max(64)) })
7101
7288
  ])).optional(),
7102
- trackChannels: z31.coerce.number().int().min(2).max(128).optional().describe("Even channel count for the track")
7289
+ trackChannels: z32.coerce.number().int().min(2).max(128).optional().describe("Even channel count for the track")
7103
7290
  },
7104
7291
  async (args) => {
7105
7292
  const res = await run3("set_fx_pins", flatten(args, ["inputs", "outputs"]));
@@ -7116,16 +7303,16 @@ function registerMixingTools(server) {
7116
7303
  server.tool(
7117
7304
  "add_monitoring_fx",
7118
7305
  "Add an FX to the monitoring chain (heard in the monitors, never rendered), with optional normalized parameters.",
7119
- { fxName: z31.string().min(1).describe('FX name as add_fx takes it, e.g. "ReaEQ" or "VST3: SoundID Reference"'), params: fxParams },
7306
+ { fxName: z32.string().min(1).describe('FX name as add_fx takes it, e.g. "ReaEQ" or "VST3: SoundID Reference"'), params: fxParams },
7120
7307
  async (args) => run3("add_monitoring_fx", flatten(args, ["params"]))
7121
7308
  );
7122
7309
  server.tool(
7123
7310
  "set_monitoring_fx",
7124
7311
  "Bypass, set offline, or set normalized parameters of a monitoring FX by index (from list_monitoring_fx).",
7125
7312
  {
7126
- fxIndex: z31.coerce.number().int().min(0),
7127
- enabled: z31.boolean().optional(),
7128
- offline: z31.boolean().optional(),
7313
+ fxIndex: z32.coerce.number().int().min(0),
7314
+ enabled: z32.boolean().optional(),
7315
+ offline: z32.boolean().optional(),
7129
7316
  params: fxParams
7130
7317
  },
7131
7318
  async (args) => run3("set_monitoring_fx", flatten(args, ["params"]))
@@ -7133,7 +7320,7 @@ function registerMixingTools(server) {
7133
7320
  server.tool(
7134
7321
  "remove_monitoring_fx",
7135
7322
  "Remove a monitoring FX by index (from list_monitoring_fx).",
7136
- { fxIndex: z31.coerce.number().int().min(0) },
7323
+ { fxIndex: z32.coerce.number().int().min(0) },
7137
7324
  async (args) => run3("remove_monitoring_fx", args)
7138
7325
  );
7139
7326
  server.tool(
@@ -7158,7 +7345,7 @@ function registerMixingTools(server) {
7158
7345
  "apply_fx_to_items",
7159
7346
  "Render in place: apply the track and take FX to items as a new active take (stereo, mono or multichannel). The old take stays, so the render can be switched back with set_active_take. Blocks REAPER while it renders. The item selection is put back.",
7160
7347
  {
7161
- items: z31.array(z31.object({ trackIndex: z31.coerce.number().int().min(0), itemIndex: z31.coerce.number().int().min(0) })).min(1).max(64),
7348
+ items: z32.array(z32.object({ trackIndex: z32.coerce.number().int().min(0), itemIndex: z32.coerce.number().int().min(0) })).min(1).max(64),
7162
7349
  mode: renderMode
7163
7350
  },
7164
7351
  async (args) => run3("apply_fx_to_items", flatten(args, ["items"]), 3e5)
@@ -7167,11 +7354,11 @@ function registerMixingTools(server) {
7167
7354
  "add_stretch_markers",
7168
7355
  "Add many stretch markers to an audio item in one call and one undo point. position is seconds from the item start; sourcePosition (seconds in the source) pins the audio at that spot to the new position, which stretches the audio around it.",
7169
7356
  {
7170
- trackIndex: z31.coerce.number().int().min(0),
7171
- itemIndex: z31.coerce.number().int().min(0),
7172
- markers: z31.array(z31.object({
7173
- position: z31.coerce.number().min(0),
7174
- sourcePosition: z31.coerce.number().optional()
7357
+ trackIndex: z32.coerce.number().int().min(0),
7358
+ itemIndex: z32.coerce.number().int().min(0),
7359
+ markers: z32.array(z32.object({
7360
+ position: z32.coerce.number().min(0),
7361
+ sourcePosition: z32.coerce.number().optional()
7175
7362
  })).min(1).max(2e3)
7176
7363
  },
7177
7364
  async (args) => run3("add_stretch_markers", flatten(args, ["markers"]))
@@ -7180,13 +7367,13 @@ function registerMixingTools(server) {
7180
7367
  "edit_stretch_markers",
7181
7368
  "Edit existing stretch markers of an audio item in one call and one undo point: move a marker (position, seconds from the item start), change which source time it pins (sourcePosition) and its slope (-1..1, the curve of the stretch after it). Markers are named by index, in position order. position is in item seconds, as this tool and add_stretch_markers report them; get_stretch_markers lists raw take positions, which equal item seconds only at play rate 1 (divide by the play rate otherwise). Only the fields given change. Every edit is checked first: a marker moved out of order (position or source), onto another marker, outside the item, or a repeated index refuses the whole call and changes nothing.",
7182
7369
  {
7183
- trackIndex: z31.coerce.number().int().min(0),
7184
- itemIndex: z31.coerce.number().int().min(0),
7185
- edits: z31.array(z31.object({
7186
- index: z31.coerce.number().int().min(0),
7187
- position: z31.coerce.number().min(0).optional(),
7188
- sourcePosition: z31.coerce.number().optional(),
7189
- slope: z31.coerce.number().min(-1).max(1).optional()
7370
+ trackIndex: z32.coerce.number().int().min(0),
7371
+ itemIndex: z32.coerce.number().int().min(0),
7372
+ edits: z32.array(z32.object({
7373
+ index: z32.coerce.number().int().min(0),
7374
+ position: z32.coerce.number().min(0).optional(),
7375
+ sourcePosition: z32.coerce.number().optional(),
7376
+ slope: z32.coerce.number().min(-1).max(1).optional()
7190
7377
  })).min(1).max(2e3)
7191
7378
  },
7192
7379
  async (args) => run3("edit_stretch_markers", flatten(args, ["edits"]))
@@ -7195,27 +7382,27 @@ function registerMixingTools(server) {
7195
7382
  "quantize_audio",
7196
7383
  "Quantize an audio item to the grid with stretch markers: finds the hits in the item's source (sidecar), puts a marker on each and moves it toward the nearest grid line (strength, window and swing as quantize_midi). The item keeps its length (anchors at both ends); the item's existing stretch markers are replaced. Returns the timing offset before and after (avg/max ms). Requires the sidecar.",
7197
7384
  {
7198
- trackIndex: z31.coerce.number().int().min(0),
7199
- itemIndex: z31.coerce.number().int().min(0),
7200
- grid: z31.coerce.number().positive().max(16).describe("Grid in quarter notes: 1 = quarter, 0.5 = 8th, 0.25 = 16th"),
7201
- strength: z31.coerce.number().min(0).max(1).optional().default(1).describe("0..1, how far each hit moves toward its line"),
7202
- window: z31.coerce.number().positive().max(1).optional().default(1).describe("0..1 of half a grid step (times 1 + swing, as quantize_midi); hits further from a line stay put"),
7203
- swing: z31.coerce.number().min(0).max(0.9).optional().default(0),
7204
- sensitivity: z31.coerce.number().min(0).max(1).optional().default(0.5).describe("Hit detection: higher finds softer hits"),
7205
- minGapMs: z31.coerce.number().min(5).max(2e3).optional().default(60),
7206
- minStrength: z31.coerce.number().min(0).max(1).optional().default(0.2).describe("Ignore hits weaker than this (0..1 of the loudest)")
7385
+ trackIndex: z32.coerce.number().int().min(0),
7386
+ itemIndex: z32.coerce.number().int().min(0),
7387
+ grid: z32.coerce.number().positive().max(16).describe("Grid in quarter notes: 1 = quarter, 0.5 = 8th, 0.25 = 16th"),
7388
+ strength: z32.coerce.number().min(0).max(1).optional().default(1).describe("0..1, how far each hit moves toward its line"),
7389
+ window: z32.coerce.number().positive().max(1).optional().default(1).describe("0..1 of half a grid step (times 1 + swing, as quantize_midi); hits further from a line stay put"),
7390
+ swing: z32.coerce.number().min(0).max(0.9).optional().default(0),
7391
+ sensitivity: z32.coerce.number().min(0).max(1).optional().default(0.5).describe("Hit detection: higher finds softer hits"),
7392
+ minGapMs: z32.coerce.number().min(5).max(2e3).optional().default(60),
7393
+ minStrength: z32.coerce.number().min(0).max(1).optional().default(0.2).describe("Ignore hits weaker than this (0..1 of the loudest)")
7207
7394
  },
7208
7395
  async ({ trackIndex: ti, itemIndex: itemIndex2, grid, strength, window, swing, sensitivity, minGapMs, minStrength }) => {
7209
7396
  const sidecar = getSidecarClient();
7210
- if (!sidecar.isAvailable()) return error4(SIDECAR_NOT_INSTALLED_MSG);
7397
+ if (!sidecar.isAvailable()) return error5(SIDECAR_NOT_INSTALLED_MSG);
7211
7398
  const props = await sendCommand("get_media_item_properties", { trackIndex: ti, itemIndex: itemIndex2 });
7212
- if (!props.success) return error4(props.error ?? "item not found");
7399
+ if (!props.success) return error5(props.error ?? "item not found");
7213
7400
  const item = props.data;
7214
- if (item.isMidi) return error4("quantize_audio needs an audio item; use quantize_midi for MIDI");
7215
- if (!item.sourceFile) return error4("The item has no source file to analyse");
7401
+ if (item.isMidi) return error5("quantize_audio needs an audio item; use quantize_midi for MIDI");
7402
+ if (!item.sourceFile) return error5("The item has no source file to analyse");
7216
7403
  const offs = item.startOffset ?? 0;
7217
7404
  const span = (item.length ?? 0) * (item.playRate ?? 1);
7218
- if (span > MAX_QUANTIZE_SECONDS) return error4(`Item too long: max ${MAX_QUANTIZE_SECONDS} s of source audio per call`);
7405
+ if (span > MAX_QUANTIZE_SECONDS) return error5(`Item too long: max ${MAX_QUANTIZE_SECONDS} s of source audio per call`);
7219
7406
  let detected;
7220
7407
  try {
7221
7408
  detected = await sidecar.transients({
@@ -7227,12 +7414,12 @@ function registerMixingTools(server) {
7227
7414
  minGapMs
7228
7415
  });
7229
7416
  } catch (err) {
7230
- return error4(`Hit detection failed: ${err instanceof Error ? err.message : String(err)}`);
7417
+ return error5(`Hit detection failed: ${err instanceof Error ? err.message : String(err)}`);
7231
7418
  }
7232
7419
  const all = detected["transients"] ?? [];
7233
7420
  const hits = all.filter((t) => t.strength >= (minStrength ?? 0.2)).map((t) => t.time);
7234
7421
  if (hits.length === 0) {
7235
- return error4(`No hits to quantize (${all.length} detected, none with strength >= ${minStrength ?? 0.2}) \u2014 nothing changed. Lower minStrength or raise sensitivity.`);
7422
+ return error5(`No hits to quantize (${all.length} detected, none with strength >= ${minStrength ?? 0.2}) \u2014 nothing changed. Lower minStrength or raise sensitivity.`);
7236
7423
  }
7237
7424
  const res = await run3("quantize_audio", { trackIndex: ti, itemIndex: itemIndex2, grid, strength, window, swing, hits: JSON.stringify(hits) }, 6e4);
7238
7425
  if (!res.data) return res;
@@ -7252,7 +7439,7 @@ function registerMixingTools(server) {
7252
7439
  }
7253
7440
 
7254
7441
  // apps/reaper-mcp-server/src/tools/align.ts
7255
- import { z as z32 } from "zod/v4";
7442
+ import { z as z33 } from "zod/v4";
7256
7443
  import { trace as trace8 } from "@opentelemetry/api";
7257
7444
 
7258
7445
  // apps/reaper-mcp-server/src/align.ts
@@ -7341,11 +7528,11 @@ function buildPairs(guideHits, doubleHits, g, opts) {
7341
7528
 
7342
7529
  // apps/reaper-mcp-server/src/tools/align.ts
7343
7530
  var MAX_ALIGN_SECONDS = 900;
7344
- var error5 = (text8) => ({ content: [{ type: "text", text: `Error: ${text8}` }], isError: true });
7531
+ var error6 = (text9) => ({ content: [{ type: "text", text: `Error: ${text9}` }], isError: true });
7345
7532
  var ok2 = (data) => ({ content: [{ type: "text", text: JSON.stringify(data, null, 2) }] });
7346
- var itemRef = z32.object({
7347
- trackIndex: z32.coerce.number().int().min(0),
7348
- itemIndex: z32.coerce.number().int().min(0)
7533
+ var itemRef = z33.object({
7534
+ trackIndex: z33.coerce.number().int().min(0),
7535
+ itemIndex: z33.coerce.number().int().min(0)
7349
7536
  });
7350
7537
  async function readItem(ref, what) {
7351
7538
  const res = await sendCommand("get_media_item_properties", ref);
@@ -7364,7 +7551,7 @@ var geometryOf = (item) => ({
7364
7551
  startOffset: item.startOffset ?? 0,
7365
7552
  playRate: item.playRate ?? 1
7366
7553
  });
7367
- async function detect2(item, d) {
7554
+ async function detect3(item, d) {
7368
7555
  const offs = item.startOffset ?? 0;
7369
7556
  const span = (item.length ?? 0) * (item.playRate ?? 1);
7370
7557
  const res = await getSidecarClient().transients({
@@ -7385,37 +7572,37 @@ function registerAlignTools(server) {
7385
7572
  "Align doubles (a second take, a harmony, a stack) to a guide item with stretch markers, the way VocalSync does: finds the hits (onsets) in the guide and in each double (sidecar), pairs them in order within maxShiftMs, and puts a stretch marker on each hit of the double so it lands on the guide's. Audio between hits is stretched; anchors at both ends keep each double's length. strength < 1 moves hits only part of the way. protectConsonants moves high-band hits (s, t, k, sh) as a block, so the stretch lands in the vowel after them instead of smearing the consonant. dryRun returns the planned moves and writes nothing. Each double's existing stretch markers are replaced; a guide that has stretch markers is refused (its hits would not sit where its source says). Returns, per double, the timing offset before and after (avg/max ms against the guide). Works on the items' source files (take FX are ignored). Requires the sidecar. Not pitch correction.",
7386
7573
  {
7387
7574
  guide: itemRef.describe("The item to align to (the lead)"),
7388
- doubles: z32.array(itemRef).min(1).max(8).describe("The items to move onto the guide"),
7389
- strength: z32.coerce.number().positive().max(1).optional().default(1).describe("0..1, how far each hit moves toward the guide's"),
7390
- maxShiftMs: z32.coerce.number().min(10).max(500).optional().default(120).describe("Hits further apart than this are not paired (and stay put)"),
7391
- protectConsonants: z32.boolean().optional().default(true).describe("Move high-band hits as a block with a rigid tail of consonantMs"),
7392
- consonantMs: z32.coerce.number().min(20).max(300).optional().default(80),
7393
- dryRun: z32.boolean().optional().default(false),
7394
- sensitivity: z32.coerce.number().min(0).max(1).optional().default(0.5).describe("Hit detection: higher finds softer hits"),
7395
- minGapMs: z32.coerce.number().min(5).max(2e3).optional().default(60),
7396
- minStrength: z32.coerce.number().min(0).max(1).optional().default(0.2).describe("Ignore hits weaker than this (0..1 of the loudest)")
7575
+ doubles: z33.array(itemRef).min(1).max(8).describe("The items to move onto the guide"),
7576
+ strength: z33.coerce.number().positive().max(1).optional().default(1).describe("0..1, how far each hit moves toward the guide's"),
7577
+ maxShiftMs: z33.coerce.number().min(10).max(500).optional().default(120).describe("Hits further apart than this are not paired (and stay put)"),
7578
+ protectConsonants: z33.boolean().optional().default(true).describe("Move high-band hits as a block with a rigid tail of consonantMs"),
7579
+ consonantMs: z33.coerce.number().min(20).max(300).optional().default(80),
7580
+ dryRun: z33.boolean().optional().default(false),
7581
+ sensitivity: z33.coerce.number().min(0).max(1).optional().default(0.5).describe("Hit detection: higher finds softer hits"),
7582
+ minGapMs: z33.coerce.number().min(5).max(2e3).optional().default(60),
7583
+ minStrength: z33.coerce.number().min(0).max(1).optional().default(0.2).describe("Ignore hits weaker than this (0..1 of the loudest)")
7397
7584
  },
7398
7585
  async ({ guide, doubles, strength, maxShiftMs, protectConsonants, consonantMs, dryRun, sensitivity, minGapMs, minStrength }) => {
7399
- if (!getSidecarClient().isAvailable()) return error5(SIDECAR_NOT_INSTALLED_MSG);
7586
+ if (!getSidecarClient().isAvailable()) return error6(SIDECAR_NOT_INSTALLED_MSG);
7400
7587
  const det = { sensitivity, minGapMs, minStrength };
7401
7588
  const guideRead = await readItem(guide, "The guide");
7402
- if ("error" in guideRead) return error5(guideRead.error);
7589
+ if ("error" in guideRead) return error6(guideRead.error);
7403
7590
  const markers = await sendCommand("get_stretch_markers", guide);
7404
7591
  if (markers.success && (markers.data.total ?? 0) > 0) {
7405
- return error5("The guide item has stretch markers, so its hits would not sit where its source says. Glue or render it first, or align to an item without stretch markers.");
7592
+ return error6("The guide item has stretch markers, so its hits would not sit where its source says. Glue or render it first, or align to an item without stretch markers.");
7406
7593
  }
7407
7594
  let guideHits;
7408
7595
  let guideTruncated = false;
7409
7596
  try {
7410
- const found = await detect2(guideRead.item, det);
7597
+ const found = await detect3(guideRead.item, det);
7411
7598
  guideTruncated = found.truncated;
7412
7599
  const raw = found.hits;
7413
7600
  const geo = geometryOf(guideRead.item);
7414
7601
  guideHits = raw.map((h) => ({ ...h, time: projectTime(geo, h.time) }));
7415
7602
  } catch (err) {
7416
- return error5(`Hit detection failed on the guide: ${err instanceof Error ? err.message : String(err)}`);
7603
+ return error6(`Hit detection failed on the guide: ${err instanceof Error ? err.message : String(err)}`);
7417
7604
  }
7418
- if (guideHits.length === 0) return error5("No hits found in the guide (lower minStrength or raise sensitivity) \u2014 nothing changed.");
7605
+ if (guideHits.length === 0) return error6("No hits found in the guide (lower minStrength or raise sensitivity) \u2014 nothing changed.");
7419
7606
  const results = [];
7420
7607
  for (const ref of doubles) {
7421
7608
  const label = `track ${ref.trackIndex} item ${ref.itemIndex}`;
@@ -7428,7 +7615,7 @@ function registerAlignTools(server) {
7428
7615
  let hits;
7429
7616
  let truncated = false;
7430
7617
  try {
7431
- const found = await detect2(doubleRead.item, det);
7618
+ const found = await detect3(doubleRead.item, det);
7432
7619
  hits = found.hits;
7433
7620
  truncated = found.truncated;
7434
7621
  } catch (err) {
@@ -7468,7 +7655,7 @@ function registerAlignTools(server) {
7468
7655
  span?.setAttribute("reaper.align.aligned", aligned);
7469
7656
  span?.setAttribute("reaper.align.dry_run", dryRun);
7470
7657
  if (aligned === 0) {
7471
- return error5(`Nothing aligned: ${results.map((r) => `${r["trackIndex"]}/${r["itemIndex"]}: ${r["error"]}`).join("; ")}`);
7658
+ return error6(`Nothing aligned: ${results.map((r) => `${r["trackIndex"]}/${r["itemIndex"]}: ${r["error"]}`).join("; ")}`);
7472
7659
  }
7473
7660
  return ok2({ guide, dryRun, aligned, failed: results.length - aligned, guideHits: guideHits.length, results });
7474
7661
  }
@@ -7476,7 +7663,7 @@ function registerAlignTools(server) {
7476
7663
  }
7477
7664
 
7478
7665
  // apps/reaper-mcp-server/src/tools/composition.ts
7479
- import { z as z33 } from "zod/v4";
7666
+ import { z as z34 } from "zod/v4";
7480
7667
  import { readFile as readFile2, stat as stat2 } from "node:fs/promises";
7481
7668
  import { basename as basename3, extname as extname2 } from "node:path";
7482
7669
  import { trace as trace9 } from "@opentelemetry/api";
@@ -7487,7 +7674,7 @@ var MAJOR = [6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2
7487
7674
  var MINOR = [6.33, 2.68, 3.52, 5.38, 2.6, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17];
7488
7675
  var SCALE = { major: [0, 2, 4, 5, 7, 9, 11], minor: [0, 2, 3, 5, 7, 8, 10] };
7489
7676
  var CONTRAST_FULL = 0.4;
7490
- var round2 = (x, digits = 3) => Math.round(x * 10 ** digits) / 10 ** digits;
7677
+ var round3 = (x, digits = 3) => Math.round(x * 10 ** digits) / 10 ** digits;
7491
7678
  function pearson(a, b) {
7492
7679
  const n = a.length;
7493
7680
  const ma = a.reduce((s, x) => s + x, 0) / n;
@@ -7529,13 +7716,13 @@ function estimateKey(profile) {
7529
7716
  const mean = profile.reduce((a, x) => a + x, 0) / 12;
7530
7717
  const cv = Math.sqrt(profile.reduce((a, x) => a + (x - mean) ** 2, 0) / 12) / mean;
7531
7718
  const confidence = gap * Math.min(1, cv / CONTRAST_FULL) * Math.max(0, best.r);
7532
- const short = (k) => ({ ...k, r: round2(k.r) });
7719
+ const short = (k) => ({ ...k, r: round3(k.r) });
7533
7720
  return {
7534
7721
  ...short(best),
7535
- confidence: round2(confidence, 2),
7722
+ confidence: round3(confidence, 2),
7536
7723
  relative: relative2,
7537
7724
  alternatives: ranked.slice(1, 4).map(short),
7538
- chroma: profile.map((x) => round2(x / top))
7725
+ chroma: profile.map((x) => round3(x / top))
7539
7726
  };
7540
7727
  }
7541
7728
 
@@ -7565,7 +7752,7 @@ var QUALITIES = {
7565
7752
  var MIN_SCORE = 0.6;
7566
7753
  var IN_KEY_BONUS = 0.03;
7567
7754
  var HOLD_MARGIN = 0.03;
7568
- var round3 = (x, digits = 3) => Math.round(x * 10 ** digits) / 10 ** digits;
7755
+ var round4 = (x, digits = 3) => Math.round(x * 10 ** digits) / 10 ** digits;
7569
7756
  function cosine(profile, tones) {
7570
7757
  let dot = 0;
7571
7758
  let norm = 0;
@@ -7645,20 +7832,20 @@ function mergeSpans(segments, picks, key) {
7645
7832
  const bass = has && p.bassPc !== void 0 && p.bassPc !== p.root ? PITCH_CLASSES[p.bassPc] : void 0;
7646
7833
  const last = spans[spans.length - 1];
7647
7834
  if (last && last.chord.split("/")[0] === chord && last.bass === bass && Math.abs(last.end - s.start) < 1e-3) {
7648
- last.end = round3(s.end);
7835
+ last.end = round4(s.end);
7649
7836
  last.length += 1;
7650
7837
  scores.push(p.score);
7651
- last.score = round3(scores.reduce((a, x) => a + x, 0) / scores.length);
7838
+ last.score = round4(scores.reduce((a, x) => a + x, 0) / scores.length);
7652
7839
  return;
7653
7840
  }
7654
7841
  scores = [p.score];
7655
7842
  const span = {
7656
- start: round3(s.start),
7657
- end: round3(s.end),
7843
+ start: round4(s.start),
7844
+ end: round4(s.end),
7658
7845
  ...s.bar !== void 0 ? { bar: s.bar, beat: s.beat } : {},
7659
7846
  length: 1,
7660
7847
  chord,
7661
- score: round3(p.score)
7848
+ score: round4(p.score)
7662
7849
  };
7663
7850
  if (has) {
7664
7851
  const root = p.root;
@@ -7751,7 +7938,7 @@ function modelPicks(grid, model) {
7751
7938
  best = id;
7752
7939
  bestCover = c;
7753
7940
  }
7754
- const score = round3(bestCover / length);
7941
+ const score = round4(bestCover / length);
7755
7942
  if (best === "N") return { score };
7756
7943
  const [root, quality, bassPc] = best.split(":");
7757
7944
  return { root: Number(root), quality, score, ...bassPc ? { bassPc: Number(bassPc) } : {} };
@@ -7810,7 +7997,7 @@ var Reader = class {
7810
7997
  return String.fromCharCode(...this.bytes(n));
7811
7998
  }
7812
7999
  };
7813
- function text4(body) {
8000
+ function text5(body) {
7814
8001
  let s;
7815
8002
  try {
7816
8003
  s = new TextDecoder("utf-8", { fatal: true }).decode(body);
@@ -7874,7 +8061,7 @@ function parseSmf(data) {
7874
8061
  if (b === 255) {
7875
8062
  const type = tr.byte();
7876
8063
  const body = tr.bytes(tr.varlen());
7877
- if (type === 3 && !track.name) track.name = text4(body);
8064
+ if (type === 3 && !track.name) track.name = text5(body);
7878
8065
  else if (type === 81 && body.length === 3) {
7879
8066
  tempoChanges++;
7880
8067
  if (tempo === null) tempo = Math.round(6e7 / (body[0] << 16 | body[1] << 8 | body[2]) * 1e3) / 1e3;
@@ -7973,19 +8160,19 @@ function writeSmf(tracks2, tempos) {
7973
8160
  }
7974
8161
 
7975
8162
  // apps/reaper-mcp-server/src/tools/composition.ts
7976
- var text5 = (data) => ({ content: [{ type: "text", text: JSON.stringify(data, null, 2) }] });
7977
- var error6 = (message) => ({ content: [{ type: "text", text: message }], isError: true });
8163
+ var text6 = (data) => ({ content: [{ type: "text", text: JSON.stringify(data, null, 2) }] });
8164
+ var error7 = (message) => ({ content: [{ type: "text", text: message }], isError: true });
7978
8165
  var MAX_MIDI_FILE_BYTES = 5 * 1024 * 1024;
7979
8166
  var MAX_IMPORT_NOTES = 2e4;
7980
8167
  var DEFAULT_KEY_SECONDS = 60;
7981
8168
  var chordModelTimeoutMs = (seconds2) => 6e4 + seconds2 * 500;
7982
8169
  var selectionSchema = {
7983
- trackIndex: z33.coerce.number().int().min(0).describe("Track index (0-based)"),
7984
- itemIndex: z33.coerce.number().int().min(0).describe("MIDI item index on the track (0-based, from list_midi_items)"),
7985
- notes: z33.array(z33.coerce.number().int().min(0)).optional().describe("Only these note indexes (from get_midi_notes); default: every note matching pitchMin/pitchMax/channel"),
7986
- pitchMin: z33.coerce.number().int().min(0).max(127).optional().describe("Only notes at or above this pitch"),
7987
- pitchMax: z33.coerce.number().int().min(0).max(127).optional().describe("Only notes at or below this pitch"),
7988
- channel: z33.coerce.number().int().min(0).max(15).optional().describe("Only notes on this MIDI channel (0-15; 9 = GM drums)")
8170
+ trackIndex: z34.coerce.number().int().min(0).describe("Track index (0-based)"),
8171
+ itemIndex: z34.coerce.number().int().min(0).describe("MIDI item index on the track (0-based, from list_midi_items)"),
8172
+ notes: z34.array(z34.coerce.number().int().min(0)).optional().describe("Only these note indexes (from get_midi_notes); default: every note matching pitchMin/pitchMax/channel"),
8173
+ pitchMin: z34.coerce.number().int().min(0).max(127).optional().describe("Only notes at or above this pitch"),
8174
+ pitchMax: z34.coerce.number().int().min(0).max(127).optional().describe("Only notes at or below this pitch"),
8175
+ channel: z34.coerce.number().int().min(0).max(15).optional().describe("Only notes on this MIDI channel (0-15; 9 = GM drums)")
7989
8176
  };
7990
8177
  function flatten2(args, objects = []) {
7991
8178
  const out2 = {};
@@ -8044,17 +8231,17 @@ function registerCompositionTools(server) {
8044
8231
  'Quantize the notes of a MIDI item to the project grid (beats, not the item start): grid in beats (1 = quarter, 0.5 = 8th, 0.25 = 16th, 1/3 = 8th triplet), strength 0..1 (partial moves keep feel), swing 0..0.9 (pushes every second grid line later), window 0..1 (only notes within that fraction of half the gap to the next line move; with swing the gaps are uneven, so the reach is (1 + swing) times half a step), lengths "keep" (default, notes move whole) or "quantize" (ends snap too). Acts on all notes or a selection (indexes, pitch range, channel). One undo point; a refused call changes nothing. Returns how many notes moved and the average and largest shift in beats.',
8045
8232
  {
8046
8233
  ...selectionSchema,
8047
- grid: z33.coerce.number().positive().max(16).describe("Grid in beats: 1 = quarter, 0.5 = 8th, 0.25 = 16th, 0.333 = 8th triplet"),
8048
- strength: z33.coerce.number().min(0).max(1).optional().describe("How far notes move toward the grid, 0..1 (default 1)"),
8049
- swing: z33.coerce.number().min(0).max(0.9).optional().describe("Off-beat delay as a fraction of a grid step, 0..0.9 (default 0)"),
8050
- window: z33.coerce.number().gt(0).max(1).optional().describe("Only move notes within this fraction of half the gap between lines, (1 + swing) half steps with swing (default 1 = all)"),
8051
- lengths: z33.enum(["keep", "quantize"]).optional().describe("keep (default): notes keep their length; quantize: note ends snap too")
8234
+ grid: z34.coerce.number().positive().max(16).describe("Grid in beats: 1 = quarter, 0.5 = 8th, 0.25 = 16th, 0.333 = 8th triplet"),
8235
+ strength: z34.coerce.number().min(0).max(1).optional().describe("How far notes move toward the grid, 0..1 (default 1)"),
8236
+ swing: z34.coerce.number().min(0).max(0.9).optional().describe("Off-beat delay as a fraction of a grid step, 0..0.9 (default 0)"),
8237
+ window: z34.coerce.number().gt(0).max(1).optional().describe("Only move notes within this fraction of half the gap between lines, (1 + swing) half steps with swing (default 1 = all)"),
8238
+ lengths: z34.enum(["keep", "quantize"]).optional().describe("keep (default): notes keep their length; quantize: note ends snap too")
8052
8239
  },
8053
8240
  async (args) => {
8054
8241
  const res = await sendCommand("quantize_midi", flatten2(args));
8055
- if (!res.success) return error6(`Error: ${res.error}`);
8242
+ if (!res.success) return error7(`Error: ${res.error}`);
8056
8243
  recordNotes("quantize_midi", Number(res.data.moved));
8057
- return text5(res.data);
8244
+ return text6(res.data);
8058
8245
  }
8059
8246
  );
8060
8247
  server.tool(
@@ -8062,61 +8249,61 @@ function registerCompositionTools(server) {
8062
8249
  "Transform the notes of a MIDI item in one undo point: transpose (semitones, refused if any note would leave 0-127), velocity (set, scale, add, then clamp to min/max), humanize (random timing in beats and velocity, reproducible with seed), length (set in beats, scale, or legato = each note runs to the next selected note on its channel). Acts on all notes or a selection (indexes, pitch range, channel). Returns how many notes it acted on, velocities before/after and the humanize seed.",
8063
8250
  {
8064
8251
  ...selectionSchema,
8065
- transpose: z33.coerce.number().int().min(-48).max(48).optional().describe("Semitones up (+) or down (-)"),
8066
- velocity: z33.object({
8067
- set: z33.coerce.number().int().min(1).max(127).optional().describe("Every velocity becomes this"),
8068
- scale: z33.coerce.number().min(0).max(4).optional().describe("Multiply velocities (0.8 = softer, 1.2 = harder)"),
8069
- add: z33.coerce.number().int().min(-126).max(126).optional().describe("Add to velocities"),
8070
- min: z33.coerce.number().int().min(1).max(127).optional().describe("Clamp: lowest velocity (default 1)"),
8071
- max: z33.coerce.number().int().min(1).max(127).optional().describe("Clamp: highest velocity (default 127)")
8252
+ transpose: z34.coerce.number().int().min(-48).max(48).optional().describe("Semitones up (+) or down (-)"),
8253
+ velocity: z34.object({
8254
+ set: z34.coerce.number().int().min(1).max(127).optional().describe("Every velocity becomes this"),
8255
+ scale: z34.coerce.number().min(0).max(4).optional().describe("Multiply velocities (0.8 = softer, 1.2 = harder)"),
8256
+ add: z34.coerce.number().int().min(-126).max(126).optional().describe("Add to velocities"),
8257
+ min: z34.coerce.number().int().min(1).max(127).optional().describe("Clamp: lowest velocity (default 1)"),
8258
+ max: z34.coerce.number().int().min(1).max(127).optional().describe("Clamp: highest velocity (default 127)")
8072
8259
  }).optional(),
8073
- humanize: z33.object({
8074
- timingBeats: z33.coerce.number().min(0).max(0.25).optional().describe("Random start shift up to \xB1 this many beats (0.02 \u2248 subtle)"),
8075
- velocity: z33.coerce.number().int().min(0).max(64).optional().describe("Random velocity change up to \xB1 this"),
8076
- seed: z33.coerce.number().int().optional().describe("Seed: the same seed gives the same result (default 1)")
8260
+ humanize: z34.object({
8261
+ timingBeats: z34.coerce.number().min(0).max(0.25).optional().describe("Random start shift up to \xB1 this many beats (0.02 \u2248 subtle)"),
8262
+ velocity: z34.coerce.number().int().min(0).max(64).optional().describe("Random velocity change up to \xB1 this"),
8263
+ seed: z34.coerce.number().int().optional().describe("Seed: the same seed gives the same result (default 1)")
8077
8264
  }).optional(),
8078
- length: z33.object({
8079
- set: z33.coerce.number().positive().max(64).optional().describe("Every note this many beats long"),
8080
- scale: z33.coerce.number().positive().max(8).optional().describe("Multiply lengths (0.5 = staccato)"),
8081
- legato: z33.boolean().optional().describe("Each note runs to the start of the next selected note on its channel (unselected notes are not counted)")
8265
+ length: z34.object({
8266
+ set: z34.coerce.number().positive().max(64).optional().describe("Every note this many beats long"),
8267
+ scale: z34.coerce.number().positive().max(8).optional().describe("Multiply lengths (0.5 = staccato)"),
8268
+ legato: z34.boolean().optional().describe("Each note runs to the start of the next selected note on its channel (unselected notes are not counted)")
8082
8269
  }).optional()
8083
8270
  },
8084
8271
  async (args) => {
8085
8272
  const res = await sendCommand("transform_midi", flatten2(args, ["velocity", "humanize", "length"]));
8086
- if (!res.success) return error6(`Error: ${res.error}`);
8273
+ if (!res.success) return error7(`Error: ${res.error}`);
8087
8274
  recordNotes("transform_midi", Number(res.data.notes));
8088
- return text5(res.data);
8275
+ return text6(res.data);
8089
8276
  }
8090
8277
  );
8091
8278
  server.tool(
8092
8279
  "import_midi_file",
8093
8280
  "Import a Standard MIDI File (.mid/.midi, type 0 or 1, up to 5 MB and 20000 notes) as MIDI items, without REAPER's import dialog: notes and controllers of every file track merged into one item on trackIndex, or with newTracks each file track on a new track named after it, inserted at trackIndex. Placed at position (seconds) on the project grid; the file's tempo is reported, not applied (set it with set_project_tempo). Pitch bend, program changes, aftertouch and sysex are not imported; file.notImported counts them. One undo point.",
8094
8281
  {
8095
- path: z33.string().min(1).describe("Absolute path of the .mid/.midi file"),
8096
- trackIndex: z33.coerce.number().int().min(0).default(0).describe("Track to put the item on, or with newTracks where the new tracks are inserted"),
8097
- newTracks: z33.boolean().optional().describe("One new named track per file track (default: merge onto trackIndex)"),
8098
- position: z33.coerce.number().min(0).default(0).describe("Project time in seconds where the file starts (default 0)")
8282
+ path: z34.string().min(1).describe("Absolute path of the .mid/.midi file"),
8283
+ trackIndex: z34.coerce.number().int().min(0).default(0).describe("Track to put the item on, or with newTracks where the new tracks are inserted"),
8284
+ newTracks: z34.boolean().optional().describe("One new named track per file track (default: merge onto trackIndex)"),
8285
+ position: z34.coerce.number().min(0).default(0).describe("Project time in seconds where the file starts (default 0)")
8099
8286
  },
8100
8287
  async (args) => {
8101
8288
  const ext = extname2(args.path).toLowerCase();
8102
- if (ext !== ".mid" && ext !== ".midi") return error6(`Not a MIDI file: ${basename3(args.path)} (expected .mid or .midi)`);
8289
+ if (ext !== ".mid" && ext !== ".midi") return error7(`Not a MIDI file: ${basename3(args.path)} (expected .mid or .midi)`);
8103
8290
  let bytes;
8104
8291
  try {
8105
8292
  const info = await stat2(args.path);
8106
- if (info.size > MAX_MIDI_FILE_BYTES) return error6(`File too large: ${info.size} bytes (max ${MAX_MIDI_FILE_BYTES})`);
8293
+ if (info.size > MAX_MIDI_FILE_BYTES) return error7(`File too large: ${info.size} bytes (max ${MAX_MIDI_FILE_BYTES})`);
8107
8294
  bytes = await readFile2(args.path);
8108
8295
  } catch (err) {
8109
- return error6(`Cannot read ${args.path}: ${err instanceof Error ? err.message : String(err)}`);
8296
+ return error7(`Cannot read ${args.path}: ${err instanceof Error ? err.message : String(err)}`);
8110
8297
  }
8111
8298
  let smf;
8112
8299
  try {
8113
8300
  smf = parseSmf(new Uint8Array(bytes));
8114
8301
  } catch (err) {
8115
- return error6(`Cannot import ${basename3(args.path)}: ${err instanceof Error ? err.message : String(err)} \u2014 nothing changed`);
8302
+ return error7(`Cannot import ${basename3(args.path)}: ${err instanceof Error ? err.message : String(err)} \u2014 nothing changed`);
8116
8303
  }
8117
8304
  const total = smf.tracks.reduce((n, t) => n + t.notes.length, 0);
8118
- if (smf.tracks.length === 0) return error6(`${basename3(args.path)} holds no notes or controllers \u2014 nothing changed`);
8119
- if (total > MAX_IMPORT_NOTES) return error6(`${basename3(args.path)} has ${total} notes; at most ${MAX_IMPORT_NOTES} per import \u2014 nothing changed`);
8305
+ if (smf.tracks.length === 0) return error7(`${basename3(args.path)} holds no notes or controllers \u2014 nothing changed`);
8306
+ if (total > MAX_IMPORT_NOTES) return error7(`${basename3(args.path)} has ${total} notes; at most ${MAX_IMPORT_NOTES} per import \u2014 nothing changed`);
8120
8307
  const r6 = (x) => Math.round(x * 1e6) / 1e6;
8121
8308
  const tracks2 = smf.tracks.map((t) => ({
8122
8309
  name: t.name,
@@ -8131,9 +8318,9 @@ function registerCompositionTools(server) {
8131
8318
  name: basename3(args.path),
8132
8319
  tracks: JSON.stringify(tracks2)
8133
8320
  }, 6e4);
8134
- if (!res.success) return error6(`Error: ${res.error}`);
8321
+ if (!res.success) return error7(`Error: ${res.error}`);
8135
8322
  recordNotes("import_midi_file", total);
8136
- return text5({
8323
+ return text6({
8137
8324
  ...res.data,
8138
8325
  file: {
8139
8326
  name: basename3(args.path),
@@ -8155,18 +8342,18 @@ function registerCompositionTools(server) {
8155
8342
  "detect_key",
8156
8343
  `Detect the musical key (e.g. "A minor") of a track or an audio file: from a track's MIDI notes (note time weighted by velocity, drums on channel 10 ignored) or, for audio, from its chroma (Python sidecar; a track is read from its own items, before FX and pan, without a render). Returns the key, confidence 0..1 (how far it stands out from the next candidate that is not its relative key, scaled down for a flat profile and by how well the key fits \u2014 its correlation), the relative key, the top 3 alternatives with their correlation, and the 12-bin chroma (C first). Use it before writing parts, choosing a pitch-correction scale or a harmonizer key.`,
8157
8344
  {
8158
- trackIndex: z33.coerce.number().int().min(-1).optional().describe("Track to analyze (-1 = master). Give this or path"),
8159
- path: z33.string().min(1).optional().describe("Absolute path of an audio file to analyze instead (sidecar)"),
8160
- itemIndex: z33.coerce.number().int().min(0).optional().describe("Only the time this media item covers on trackIndex (from list_media_items); instead of startTime/endTime. Audio renders the whole track over it"),
8161
- source: z33.enum(["auto", "midi", "audio"]).optional().default("auto").describe("For a track: midi (its MIDI notes), audio (render it), auto (default: MIDI notes when it has any, else audio)"),
8162
- startTime: z33.coerce.number().min(0).optional().describe("Start of the range in seconds (project time for a track, file time for a file; default 0)"),
8163
- endTime: z33.coerce.number().min(0).optional().describe(`End of the range in seconds (track audio default: start + ${DEFAULT_KEY_SECONDS} s; MIDI and file default: the end)`)
8345
+ trackIndex: z34.coerce.number().int().min(-1).optional().describe("Track to analyze (-1 = master). Give this or path"),
8346
+ path: z34.string().min(1).optional().describe("Absolute path of an audio file to analyze instead (sidecar)"),
8347
+ itemIndex: z34.coerce.number().int().min(0).optional().describe("Only the time this media item covers on trackIndex (from list_media_items); instead of startTime/endTime. Audio renders the whole track over it"),
8348
+ source: z34.enum(["auto", "midi", "audio"]).optional().default("auto").describe("For a track: midi (its MIDI notes), audio (render it), auto (default: MIDI notes when it has any, else audio)"),
8349
+ startTime: z34.coerce.number().min(0).optional().describe("Start of the range in seconds (project time for a track, file time for a file; default 0)"),
8350
+ endTime: z34.coerce.number().min(0).optional().describe(`End of the range in seconds (track audio default: start + ${DEFAULT_KEY_SECONDS} s; MIDI and file default: the end)`)
8164
8351
  },
8165
8352
  async (args) => {
8166
8353
  const startedAt = Date.now();
8167
8354
  const fail4 = (message) => {
8168
8355
  logToolResult("detect_key", args, startedAt, null, message);
8169
- return error6(message);
8356
+ return error7(message);
8170
8357
  };
8171
8358
  try {
8172
8359
  const { trackIndex: trackIndex5, path } = args;
@@ -8241,7 +8428,7 @@ function registerCompositionTools(server) {
8241
8428
  span?.setAttribute("reaper.key.source", source);
8242
8429
  span?.setAttribute("reaper.key.confidence", k.confidence);
8243
8430
  logToolResult("detect_key", args, startedAt, keySummary(name, source, k));
8244
- return text5({
8431
+ return text6({
8245
8432
  ...trackIndex5 != null ? { trackIndex: trackIndex5 } : { path },
8246
8433
  ...name ? { name } : {},
8247
8434
  source,
@@ -8258,25 +8445,25 @@ function registerCompositionTools(server) {
8258
8445
  "detect_chords",
8259
8446
  'Detect the chords of a track, one media item or an audio file, one per bar (default) or beat: from MIDI notes (drums on channel 10 ignored; the lowest held note gives slash chords like C/E) or from audio (Python sidecar chroma; a track is read from its own items, before FX and pan). Track bars and beats follow the project tempo map; a file uses `bpm` (bar 1 at startTime) or fixed windows. Returns the key, the progression ("Am F C G"), and chord spans (equal neighbours merged): start/end seconds, bar.beat, chord, root, quality (maj, min, 7, maj7, m7, sus2, sus4, dim, aug; the model also dim7, m7b5, 6, m6, 9, maj9, m9, mMaj7, 5, 11, 13), roman numeral in the key, bassMidi (a MIDI note for a bass line, E1-D#2) and a 0..1 fit; "N" = no chord. Paginated (offset/limit). Audio uses the chord model (lv-chordia, slash chords and sevenths from a full mix) when installed (setup-sidecar --with-chords), else chroma templates; `engine` picks. Use it before writing a bass line or other parts to existing guitars, keys or vocals.',
8260
8447
  {
8261
- trackIndex: z33.coerce.number().int().min(-1).optional().describe("Track to analyze (-1 = master, audio only). Give this or path"),
8262
- path: z33.string().min(1).optional().describe("Absolute path of an audio file to analyze instead (sidecar)"),
8263
- itemIndex: z33.coerce.number().int().min(0).optional().describe("Only the time this media item covers on trackIndex (from list_media_items); instead of startTime/endTime. Audio renders the whole track over it"),
8264
- source: z33.enum(["auto", "midi", "audio"]).optional().default("auto").describe("For a track: midi (its MIDI notes), audio (render it), auto (default: MIDI notes when it has any, else audio)"),
8265
- per: z33.enum(["bar", "beat"]).optional().default("bar").describe("One chord per bar (default) or per beat"),
8266
- engine: z33.enum(["auto", "model", "template"]).optional().default("auto").describe("Audio: model (the chord model, setup-sidecar --with-chords; also renders a MIDI track), template (chroma templates), auto (default: the model when installed). MIDI notes always use templates"),
8267
- startTime: z33.coerce.number().min(0).optional().describe("Start of the range in seconds (project time for a track, file time for a file; default 0)"),
8268
- endTime: z33.coerce.number().min(0).optional().describe(`End of the range in seconds (default: where the track's last item ends, the project end on the master, the file's end; max ${MAX_OFFLINE_SECONDS} s for audio)`),
8269
- bpm: z33.coerce.number().min(30).max(300).optional().describe("File only: its tempo, so segments are bars/beats from startTime"),
8270
- beatsPerBar: z33.coerce.number().int().min(1).max(16).optional().default(4).describe("File only, with bpm: beats per bar (default 4)"),
8271
- windowSeconds: z33.coerce.number().min(0.25).max(16).optional().default(2).describe("File only, without bpm: one chord per this many seconds (default 2)"),
8272
- offset: z33.coerce.number().int().min(0).optional().default(0).describe("First chord span to return (pagination)"),
8273
- limit: z33.coerce.number().int().min(1).max(256).optional().default(64).describe("Most chord spans to return (default 64, max 256)")
8448
+ trackIndex: z34.coerce.number().int().min(-1).optional().describe("Track to analyze (-1 = master, audio only). Give this or path"),
8449
+ path: z34.string().min(1).optional().describe("Absolute path of an audio file to analyze instead (sidecar)"),
8450
+ itemIndex: z34.coerce.number().int().min(0).optional().describe("Only the time this media item covers on trackIndex (from list_media_items); instead of startTime/endTime. Audio renders the whole track over it"),
8451
+ source: z34.enum(["auto", "midi", "audio"]).optional().default("auto").describe("For a track: midi (its MIDI notes), audio (render it), auto (default: MIDI notes when it has any, else audio)"),
8452
+ per: z34.enum(["bar", "beat"]).optional().default("bar").describe("One chord per bar (default) or per beat"),
8453
+ engine: z34.enum(["auto", "model", "template"]).optional().default("auto").describe("Audio: model (the chord model, setup-sidecar --with-chords; also renders a MIDI track), template (chroma templates), auto (default: the model when installed). MIDI notes always use templates"),
8454
+ startTime: z34.coerce.number().min(0).optional().describe("Start of the range in seconds (project time for a track, file time for a file; default 0)"),
8455
+ endTime: z34.coerce.number().min(0).optional().describe(`End of the range in seconds (default: where the track's last item ends, the project end on the master, the file's end; max ${MAX_OFFLINE_SECONDS} s for audio)`),
8456
+ bpm: z34.coerce.number().min(30).max(300).optional().describe("File only: its tempo, so segments are bars/beats from startTime"),
8457
+ beatsPerBar: z34.coerce.number().int().min(1).max(16).optional().default(4).describe("File only, with bpm: beats per bar (default 4)"),
8458
+ windowSeconds: z34.coerce.number().min(0.25).max(16).optional().default(2).describe("File only, without bpm: one chord per this many seconds (default 2)"),
8459
+ offset: z34.coerce.number().int().min(0).optional().default(0).describe("First chord span to return (pagination)"),
8460
+ limit: z34.coerce.number().int().min(1).max(256).optional().default(64).describe("Most chord spans to return (default 64, max 256)")
8274
8461
  },
8275
8462
  async (args) => {
8276
8463
  const startedAt = Date.now();
8277
8464
  const fail4 = (message) => {
8278
8465
  logToolResult("detect_chords", args, startedAt, null, message);
8279
- return error6(message);
8466
+ return error7(message);
8280
8467
  };
8281
8468
  try {
8282
8469
  const { trackIndex: trackIndex5, path } = args;
@@ -8420,7 +8607,7 @@ function registerCompositionTools(server) {
8420
8607
  trace9.getActiveSpan()?.setAttribute("reaper.chords.count", spans.length);
8421
8608
  trace9.getActiveSpan()?.setAttribute("reaper.chords.engine", engine);
8422
8609
  logToolResult("detect_chords", args, startedAt, chordsSummary(name, source, per, key.key, range, spans));
8423
- return text5({
8610
+ return text6({
8424
8611
  ...trackIndex5 != null ? { trackIndex: trackIndex5 } : { path },
8425
8612
  ...args.itemIndex != null ? { itemIndex: args.itemIndex } : {},
8426
8613
  ...name ? { name } : {},
@@ -8446,7 +8633,7 @@ function registerCompositionTools(server) {
8446
8633
  }
8447
8634
 
8448
8635
  // apps/reaper-mcp-server/src/tools/voice-sketch.ts
8449
- import { z as z34 } from "zod/v4";
8636
+ import { z as z35 } from "zod/v4";
8450
8637
  import { writeFile as writeFile2 } from "node:fs/promises";
8451
8638
  import { extname as extname3, isAbsolute as isAbsolute2 } from "node:path";
8452
8639
 
@@ -8588,23 +8775,23 @@ function registerVoiceSketchTools(server) {
8588
8775
  "transcribe_voice_sketch",
8589
8776
  "Compose an editable musical draft from humming, singing, beatboxing, or a mixture. Local Python sidecar, no model download. Returns stable rounded BPM, sustained tempo changes, tentative key, separate monophonic melody and GM drum notes, repeated 4/4 drum patterns, and original file times. Timing snaps to a shared grid (default sixteenths); pitches snap to semitones, NOT to a guessed key. By default arrange:true adds a proposed intro/verse/chorus/outro, a kick/snare/hat groove using detected kick positions and hat accents, chord accompaniment, bass locked to the kicks, and the repeated detected melody. Those backing parts and sections are GENERATED, not recovered from the recording. No true audio source separation. arrange:false exports only the detected melody/percussion. key overrides accompaniment only, never retunes the melody. Experimental: drum labels and octaves need review; speech is not removed. Use startTime/endTime to isolate music. No REAPER changes. outputPath writes the FULL score as a type-1 .mid with tempo map and GM instruments. With soundfontPath also renders a sampled mix and separate 32-bit WAV instrument stems into <outputPath without .mid>-stems/. This optional preview needs the FluidSynth shared library and a user-supplied GM .sf2; no audio device or REAPER needed. Then use import_midi_file(newTracks:true) and assign instruments. That importer skips GM programs and does NOT apply the file tempo: use set_project_tempo/add_tempo_marker separately, or REAPER native MIDI import. Summary-first: note arrays default to 100 events per part; limit:0 returns only summaries. Export is never paginated. At most 120 seconds input, 64 bars output, 240 seconds for previews. Requires setup-sidecar (core only is enough).",
8590
8777
  {
8591
- path: z34.string().min(1).describe("Absolute path of a voice recording (MP3/WAV/FLAC/AIFF/OGG)"),
8592
- startTime: z34.coerce.number().min(0).optional().describe("Start in file seconds (default 0); exclude spoken cues"),
8593
- endTime: z34.coerce.number().positive().optional().describe("End in file seconds (default end of file, max 120 seconds selected)"),
8594
- mode: z34.enum(["auto", "melody", "drums"]).default("auto").describe("auto: both layers, melody: humming only, drums: beatboxing only"),
8595
- bpm: z34.coerce.number().min(40).max(240).optional().describe("Force one fixed tempo; use for short clips or half/double-time ambiguity"),
8596
- grid: z34.coerce.number().min(1 / 12).max(1).default(0.25).describe("Grid in quarter-note beats: 0.25 sixteenths, 0.5 eighths, 1/3 triplets"),
8597
- pitchMin: z34.coerce.number().int().min(24).max(95).default(36).describe("Lowest vocal MIDI pitch (default C2 = 36)"),
8598
- pitchMax: z34.coerce.number().int().min(25).max(96).default(84).describe("Highest vocal MIDI pitch (default C6 = 84)"),
8599
- minNoteMs: z34.coerce.number().min(40).max(500).default(80).describe("Shortest stable pitched segment before quantization (default 80 ms)"),
8600
- tempoChangeThreshold: z34.coerce.number().min(0.1).max(0.5).default(0.2).describe("Minimum relative tempo change, persisting in two 4-second windows (default 0.2 = 20%)"),
8601
- arrange: z34.boolean().default(true).describe("Generate a full backing arrangement; false returns the raw detected sketch only"),
8602
- bars: z34.coerce.number().int().min(4).max(64).default(16).describe("Generated arrangement length in 4/4 bars (default 16); ignored with arrange:false"),
8603
- key: z34.string().regex(/^(C|C#|D|Eb|E|F|F#|G|Ab|A|Bb|B) (major|minor)$/).optional().describe("Optional accompaniment key, e.g. A minor or Eb major. Does not change detected melody"),
8604
- outputPath: z34.string().min(1).optional().describe("Optional absolute .mid path to create. Parent folder must exist. Existing files are never overwritten"),
8605
- soundfontPath: z34.string().min(1).optional().describe("Optional absolute GM .sf2 for real sampled mix + stems. Requires outputPath and local FluidSynth library"),
8606
- offset: z34.coerce.number().int().min(0).default(0).describe("Note offset, independently in each part"),
8607
- limit: z34.coerce.number().int().min(0).max(500).default(100).describe("Notes returned per part (default 100, 0 = summary only); export always includes all notes")
8778
+ path: z35.string().min(1).describe("Absolute path of a voice recording (MP3/WAV/FLAC/AIFF/OGG)"),
8779
+ startTime: z35.coerce.number().min(0).optional().describe("Start in file seconds (default 0); exclude spoken cues"),
8780
+ endTime: z35.coerce.number().positive().optional().describe("End in file seconds (default end of file, max 120 seconds selected)"),
8781
+ mode: z35.enum(["auto", "melody", "drums"]).default("auto").describe("auto: both layers, melody: humming only, drums: beatboxing only"),
8782
+ bpm: z35.coerce.number().min(40).max(240).optional().describe("Force one fixed tempo; use for short clips or half/double-time ambiguity"),
8783
+ grid: z35.coerce.number().min(1 / 12).max(1).default(0.25).describe("Grid in quarter-note beats: 0.25 sixteenths, 0.5 eighths, 1/3 triplets"),
8784
+ pitchMin: z35.coerce.number().int().min(24).max(95).default(36).describe("Lowest vocal MIDI pitch (default C2 = 36)"),
8785
+ pitchMax: z35.coerce.number().int().min(25).max(96).default(84).describe("Highest vocal MIDI pitch (default C6 = 84)"),
8786
+ minNoteMs: z35.coerce.number().min(40).max(500).default(80).describe("Shortest stable pitched segment before quantization (default 80 ms)"),
8787
+ tempoChangeThreshold: z35.coerce.number().min(0.1).max(0.5).default(0.2).describe("Minimum relative tempo change, persisting in two 4-second windows (default 0.2 = 20%)"),
8788
+ arrange: z35.boolean().default(true).describe("Generate a full backing arrangement; false returns the raw detected sketch only"),
8789
+ bars: z35.coerce.number().int().min(4).max(64).default(16).describe("Generated arrangement length in 4/4 bars (default 16); ignored with arrange:false"),
8790
+ key: z35.string().regex(/^(C|C#|D|Eb|E|F|F#|G|Ab|A|Bb|B) (major|minor)$/).optional().describe("Optional accompaniment key, e.g. A minor or Eb major. Does not change detected melody"),
8791
+ outputPath: z35.string().min(1).optional().describe("Optional absolute .mid path to create. Parent folder must exist. Existing files are never overwritten"),
8792
+ soundfontPath: z35.string().min(1).optional().describe("Optional absolute GM .sf2 for real sampled mix + stems. Requires outputPath and local FluidSynth library"),
8793
+ offset: z35.coerce.number().int().min(0).default(0).describe("Note offset, independently in each part"),
8794
+ limit: z35.coerce.number().int().min(0).max(500).default(100).describe("Notes returned per part (default 100, 0 = summary only); export always includes all notes")
8608
8795
  },
8609
8796
  async (args) => {
8610
8797
  const started = Date.now();
@@ -8729,7 +8916,7 @@ function registerVoiceSketchTools(server) {
8729
8916
  }
8730
8917
 
8731
8918
  // apps/reaper-mcp-server/src/tools/knowledge.ts
8732
- import { z as z35 } from "zod/v4";
8919
+ import { z as z36 } from "zod/v4";
8733
8920
  var LOREKIT_DEFAULT_URL = "https://pqokxlhvnosogizsjztg.supabase.co/functions/v1/mcp";
8734
8921
  var BUILTIN_LOREKIT_TOKEN = "lk_ro_9YKX9WXJXZYKDQeRrG3bRt9XxYDn77Rj";
8735
8922
  var BUILTIN_SCOPE = "project::reaper-mcp";
@@ -8769,9 +8956,9 @@ async function callLoreKit(tool, args) {
8769
8956
  if (!res.ok) throw new Error(`LoreKit HTTP ${res.status}`);
8770
8957
  const body = await res.json();
8771
8958
  if (body.error) throw new Error(`LoreKit: ${body.error.message ?? "unknown error"}`);
8772
- const text8 = body.result?.content?.[0]?.text ?? "null";
8773
- if (body.result?.isError) throw new Error(`LoreKit: ${text8}`);
8774
- const data = JSON.parse(text8);
8959
+ const text9 = body.result?.content?.[0]?.text ?? "null";
8960
+ if (body.result?.isError) throw new Error(`LoreKit: ${text9}`);
8961
+ const data = JSON.parse(text9);
8775
8962
  cache.set(cacheKey, { expires: Date.now() + CACHE_TTL_MS, data });
8776
8963
  return data;
8777
8964
  }
@@ -8792,10 +8979,10 @@ function registerKnowledgeTools(server) {
8792
8979
  "list_builtin_knowledge",
8793
8980
  `List the built-in (read-only, curated) mix knowledge: plugin records and mixing lessons. Without query: summaries (key, tags, preview) \u2014 filter plugins by tags such as "category::eq" or "fx::Pro-Q 3". With query: full-text search returning full bodies. Combine with the user's own LoreKit layer (user:: keys), which overrides these.`,
8794
8981
  {
8795
- kind: z35.enum(["plugins", "lessons", "all"]).optional().describe("Which bucket (default all)"),
8796
- tags: z35.array(z35.string()).optional().describe('List mode: return rows having ANY of these tags (e.g. ["category::compressor"])'),
8797
- query: z35.string().optional().describe('Full-text search instead of a list (e.g. "drum bus attack")'),
8798
- limit: z35.coerce.number().int().min(1).max(100).optional().describe("Max results (default 50 for list, 5 for search)")
8982
+ kind: z36.enum(["plugins", "lessons", "all"]).optional().describe("Which bucket (default all)"),
8983
+ tags: z36.array(z36.string()).optional().describe('List mode: return rows having ANY of these tags (e.g. ["category::compressor"])'),
8984
+ query: z36.string().optional().describe('Full-text search instead of a list (e.g. "drum bus attack")'),
8985
+ limit: z36.coerce.number().int().min(1).max(100).optional().describe("Max results (default 50 for list, 5 for search)")
8799
8986
  },
8800
8987
  async ({ kind = "all", tags, query, limit }) => {
8801
8988
  try {
@@ -8821,7 +9008,7 @@ function registerKnowledgeTools(server) {
8821
9008
  "get_builtin_knowledge",
8822
9009
  `Read one built-in (read-only) record by key: "plugins::<vendor>/<plugin>" (e.g. "plugins::fabfilter/pro-q-3") or "mixing-lessons::<slug>". Returns null when the built-in layer has no such record. The user's own "user::" record of the same name, if any, overrides it.`,
8823
9010
  {
8824
- key: z35.string().describe('Built-in key, e.g. "plugins::fabfilter/pro-q-3"')
9011
+ key: z36.string().describe('Built-in key, e.g. "plugins::fabfilter/pro-q-3"')
8825
9012
  },
8826
9013
  async ({ key }) => {
8827
9014
  if (!isBuiltInKey(key)) {
@@ -8838,7 +9025,7 @@ function registerKnowledgeTools(server) {
8838
9025
  }
8839
9026
 
8840
9027
  // apps/reaper-mcp-server/src/tools/jsfx.ts
8841
- import { z as z36 } from "zod/v4";
9028
+ import { z as z37 } from "zod/v4";
8842
9029
  import { trace as trace10 } from "@opentelemetry/api";
8843
9030
  import { copyFileSync as copyFileSync3, existsSync as existsSync5, mkdirSync as mkdirSync6, readFileSync as readFileSync5, writeFileSync as writeFileSync5 } from "node:fs";
8844
9031
  import { homedir as homedir7 } from "node:os";
@@ -8906,9 +9093,9 @@ var ALLOWED_HUES = (() => {
8906
9093
  }
8907
9094
  return out2;
8908
9095
  })();
8909
- function fnv1a(text8) {
9096
+ function fnv1a(text9) {
8910
9097
  let h = 2166136261;
8911
- for (const ch of text8) {
9098
+ for (const ch of text9) {
8912
9099
  h ^= ch.codePointAt(0) ?? 0;
8913
9100
  h = Math.imul(h, 16777619) >>> 0;
8914
9101
  }
@@ -8929,8 +9116,8 @@ function resolveAccent(slug, token) {
8929
9116
  if ("error" in parsed || parsed.kind === "auto" || !parsed.token) return { hex: slugAccent(slug), kind: "auto" };
8930
9117
  return parsed.kind === "named" ? { hex: NAMED_ACCENTS[parsed.token], kind: "named", token: parsed.token } : { hex: parsed.token, kind: "custom", token: parsed.token };
8931
9118
  }
8932
- function readAccentToken(text8) {
8933
- const m = text8.match(/^\/\/ accent: *(\S+)/m);
9119
+ function readAccentToken(text9) {
9120
+ const m = text9.match(/^\/\/ accent: *(\S+)/m);
8934
9121
  if (!m) return void 0;
8935
9122
  const parsed = parseAccent(m[1]);
8936
9123
  return "error" in parsed ? void 0 : parsed.token;
@@ -9430,13 +9617,13 @@ function encodePreset(name, values) {
9430
9617
  for (const b of bytes) sum = sum + b & 255;
9431
9618
  return { name, data: bytes.toString("hex").toUpperCase() + sum.toString(16).toUpperCase().padStart(2, "0"), len: bytes.length };
9432
9619
  }
9433
- function parsePresetFile(text8) {
9620
+ function parsePresetFile(text9) {
9434
9621
  const out2 = [];
9435
9622
  let cur;
9436
9623
  const flush = () => {
9437
9624
  if (cur?.name !== void 0 && cur.data) out2.push({ name: cur.name, data: cur.data, len: cur.len ?? 0 });
9438
9625
  };
9439
- for (const raw of text8.replace(/\r\n/g, "\n").split("\n")) {
9626
+ for (const raw of text9.replace(/\r\n/g, "\n").split("\n")) {
9440
9627
  const line = raw.trim();
9441
9628
  if (/^\[Preset\d+\]$/i.test(line)) {
9442
9629
  flush();
@@ -9553,7 +9740,7 @@ function breakingChanges(before, after) {
9553
9740
  }
9554
9741
  return out2;
9555
9742
  }
9556
- var text6 = (t, isError = false) => ({ content: [{ type: "text", text: t }], ...isError ? { isError: true } : {} });
9743
+ var text7 = (t, isError = false) => ({ content: [{ type: "text", text: t }], ...isError ? { isError: true } : {} });
9557
9744
  var fmt = (f) => `- ${f.severity}${f.line ? ` (line ${f.line})` : ""} [${f.rule}]: ${f.message}`;
9558
9745
  function writeJsfx(input) {
9559
9746
  const args = { ...input, source: stripGenerated(input.source) };
@@ -9561,14 +9748,14 @@ function writeJsfx(input) {
9561
9748
  const slug = slugify(args.name);
9562
9749
  if (!slug) {
9563
9750
  record({ outcome: "refused_name", overwrite: overwrite2 });
9564
- return text6("Error: the name needs at least one letter or digit (it becomes the file name).", true);
9751
+ return text7("Error: the name needs at least one letter or digit (it becomes the file name).", true);
9565
9752
  }
9566
9753
  let accentToken;
9567
9754
  if (args.accent !== void 0) {
9568
9755
  const parsed = parseAccent(args.accent);
9569
9756
  if ("error" in parsed) {
9570
9757
  record({ outcome: "refused_accent", overwrite: overwrite2 });
9571
- return text6(`Error: nothing was written: ${parsed.error}.`, true);
9758
+ return text7(`Error: nothing was written: ${parsed.error}.`, true);
9572
9759
  }
9573
9760
  accentToken = parsed.kind === "auto" ? "auto" : parsed.token;
9574
9761
  }
@@ -9579,7 +9766,7 @@ function writeJsfx(input) {
9579
9766
  const accent = resolveAccent(slug, accentToken === "auto" ? void 0 : accentToken);
9580
9767
  if (existing !== void 0 && !overwrite2) {
9581
9768
  record({ outcome: "refused_exists", overwrite: overwrite2 });
9582
- return text6(`Error: ${slug}.jsfx already exists. Pass overwrite: true to replace it (the old file is kept in the history), or pick another name.`, true);
9769
+ return text7(`Error: ${slug}.jsfx already exists. Pass overwrite: true to replace it (the old file is kept in the history), or pick another name.`, true);
9583
9770
  }
9584
9771
  const findings = lintJsfx(args.source);
9585
9772
  const sliders = parseSliders(args.source).sliders;
@@ -9589,7 +9776,7 @@ function writeJsfx(input) {
9589
9776
  if (errorsOf(findings).length) {
9590
9777
  record({ ...shape2, outcome: "refused_lint" });
9591
9778
  emitLog("warn", "write_jsfx refused: lint errors", { "reaper.jsfx.outcome": "refused_lint", "reaper.jsfx.lint.rules": [...new Set(errorsOf(findings).map((f) => f.rule))].join(",") });
9592
- return text6(`Error: nothing was written, fix these and call write_jsfx again:
9779
+ return text7(`Error: nothing was written, fix these and call write_jsfx again:
9593
9780
  ${findings.map(fmt).join("\n")}`, true);
9594
9781
  }
9595
9782
  if (existing !== void 0 && !args.breaking) {
@@ -9597,7 +9784,7 @@ ${findings.map(fmt).join("\n")}`, true);
9597
9784
  if (broken.length) {
9598
9785
  record({ ...shape2, outcome: "refused_breaking" });
9599
9786
  emitLog("warn", "write_jsfx refused: breaking slider change", { "reaper.jsfx.outcome": "refused_breaking", "reaper.jsfx.breaking_count": broken.length });
9600
- return text6(`Error: nothing was written. This would break automation saved in projects that use the plugin:
9787
+ return text7(`Error: nothing was written. This would break automation saved in projects that use the plugin:
9601
9788
  ${broken.map((b) => `- ${b}`).join("\n")}
9602
9789
  Keep existing sliders as they are and add new ones at the end, or pass breaking: true if that is intended.`, true);
9603
9790
  }
@@ -9606,7 +9793,7 @@ Keep existing sliders as they are and add new ones at the end, or pass breaking:
9606
9793
  if (resolved?.errors.length) {
9607
9794
  record({ ...shape2, outcome: "refused_presets" });
9608
9795
  emitLog("warn", "write_jsfx refused: invalid presets", { "reaper.jsfx.outcome": "refused_presets", "reaper.jsfx.presets": Math.min(args.presets?.length ?? 0, MAX_PRESETS) });
9609
- return text6(`Error: nothing was written, fix these presets and call write_jsfx again:
9796
+ return text7(`Error: nothing was written, fix these presets and call write_jsfx again:
9610
9797
  ${resolved.errors.map((e) => `- ${e}`).join("\n")}`, true);
9611
9798
  }
9612
9799
  const version = existing !== void 0 ? readVersion(existing) + 1 : 1;
@@ -9632,7 +9819,7 @@ ${resolved.errors.map((e) => `- ${e}`).join("\n")}`, true);
9632
9819
  throw err;
9633
9820
  }
9634
9821
  record({ ...shape2, outcome: "written", version, ...presets ? { presets: presets.written.length } : {} });
9635
- return text6(JSON.stringify({
9822
+ return text7(JSON.stringify({
9636
9823
  path,
9637
9824
  fxName: `${GENERATED_DIR}/${slug}`,
9638
9825
  version,
@@ -9654,15 +9841,15 @@ function registerJsfxTools(server) {
9654
9841
  "write_jsfx",
9655
9842
  "Write a generated REAPER plugin (JSFX) as one self-contained file in Effects/reaper-mcp-generated/. Give the plugin source (header, unnamed sliders, @init/@slider/@block/@sample, a @gfx section using the ui_* toolkit): the toolkit is inlined for you, the file is linted first and nothing is written when a rule fails. Use it from the /make-plugin skill. The plugin works without this server or the bridge. An existing slider is never renumbered or re-ranged without breaking: true (saved automation would break). Old versions are kept outside Effects/.",
9656
9843
  {
9657
- name: z36.string().min(1).max(60).describe(`The plugin's display name, e.g. "Mutate Verb". Becomes the file name (lowercase, dashes).`),
9658
- source: z36.string().min(1).max(MAX_SOURCE).describe("The plugin source, with or without the import line. May be a file this tool wrote earlier, edited: the old toolkit block is replaced."),
9659
- request: z36.string().max(300).optional().describe("One line of what the user asked for. Written as a comment in the file only; never sent anywhere."),
9660
- overwrite: z36.boolean().optional().describe("Replace an existing plugin of that name (version + 1; the old file goes to the history)"),
9661
- breaking: z36.boolean().optional().describe("Allow an existing slider to change range, step or options, or to be removed"),
9662
- accent: z36.string().max(20).optional().describe(`The plugin's accent colour: "auto" (from its name, the default), a name (blue, teal, green, amber, orange, red, pink, violet) or "#rrggbb". Leave it out to keep the current one. To recolour a plugin, call again with only this changed.`),
9663
- presets: z36.array(z36.object({
9664
- name: z36.string().min(1).max(MAX_PRESET_NAME).describe('2-3 words that say the intent, e.g. "Ghost tails"'),
9665
- values: z36.record(z36.string(), z36.coerce.number()).describe(`Slider index ("3") or label ("Mix") \u2192 value in the slider's own units (dB, Hz, 0..1, option index). Sliders left out take their default.`)
9844
+ name: z37.string().min(1).max(60).describe(`The plugin's display name, e.g. "Mutate Verb". Becomes the file name (lowercase, dashes).`),
9845
+ source: z37.string().min(1).max(MAX_SOURCE).describe("The plugin source, with or without the import line. May be a file this tool wrote earlier, edited: the old toolkit block is replaced."),
9846
+ request: z37.string().max(300).optional().describe("One line of what the user asked for. Written as a comment in the file only; never sent anywhere."),
9847
+ overwrite: z37.boolean().optional().describe("Replace an existing plugin of that name (version + 1; the old file goes to the history)"),
9848
+ breaking: z37.boolean().optional().describe("Allow an existing slider to change range, step or options, or to be removed"),
9849
+ accent: z37.string().max(20).optional().describe(`The plugin's accent colour: "auto" (from its name, the default), a name (blue, teal, green, amber, orange, red, pink, violet) or "#rrggbb". Leave it out to keep the current one. To recolour a plugin, call again with only this changed.`),
9850
+ presets: z37.array(z37.object({
9851
+ name: z37.string().min(1).max(MAX_PRESET_NAME).describe('2-3 words that say the intent, e.g. "Ghost tails"'),
9852
+ values: z37.record(z37.string(), z37.coerce.number()).describe(`Slider index ("3") or label ("Mix") \u2192 value in the slider's own units (dB, Hz, 0..1, option index). Sliders left out take their default.`)
9666
9853
  })).max(MAX_PRESETS).optional().describe(`Suggested presets (3-5, at most ${MAX_PRESETS}) that teach how the plugin is meant to be used. They appear in the plugin's preset dropdown; presets the user saved are kept. Every value is checked against its slider: one bad value refuses the whole call.`)
9667
9854
  },
9668
9855
  async (args) => {
@@ -9688,7 +9875,7 @@ function registerJsfxTools(server) {
9688
9875
  }
9689
9876
 
9690
9877
  // apps/reaper-mcp-server/src/tools/plugin-build.ts
9691
- import { z as z37 } from "zod/v4";
9878
+ import { z as z38 } from "zod/v4";
9692
9879
  import { trace as trace11 } from "@opentelemetry/api";
9693
9880
  var BUILD_OUTCOMES = ["shipped", "compile_failed", "checks_failed", "abandoned"];
9694
9881
  var BUILD_EXAMPLES = ["mutate-verb", "tape-sat", "width-bass-mono", "none"];
@@ -9713,13 +9900,13 @@ function registerPluginBuildTools(server) {
9713
9900
  "report_plugin_build",
9714
9901
  "Call once at the end of a /make-plugin run, after the scratch track is deleted, also when the run stopped early. Records how it went in pseudonymous usage telemetry as fixed values and counts \u2014 never the plugin's name or what it does. The result shows exactly what was sent. Changes nothing in REAPER.",
9715
9902
  {
9716
- outcome: z37.string().describe("shipped: it compiled (the plugin changed the audio against bypass) and every check passed; compile_failed: the plugin loaded but left the audio unchanged or silent; checks_failed: it loaded but a check failed and was not fixed; abandoned: stopped early"),
9717
- example: z37.string().optional().describe("The shipped example the plugin started from: mutate-verb, tape-sat, width-bass-mono, or none"),
9718
- rounds: z37.coerce.number().int().min(1).optional().describe("write_jsfx \u2192 load \u2192 check rounds it took (default 1)"),
9719
- checksPassed: z37.coerce.number().int().min(0).optional().describe("Verification checks that passed in the last round"),
9720
- checksFailed: z37.coerce.number().int().min(0).optional().describe("Verification checks that failed in the last round"),
9721
- cleanedUp: z37.boolean().optional().describe("The scratch track was deleted and nothing else changed"),
9722
- scratchTag: z37.string().optional().describe('The <TAG> of your "[MCP] make-plugin <TAG>" track, so the server can time the run. Never sent.')
9903
+ outcome: z38.string().describe("shipped: it compiled (the plugin changed the audio against bypass) and every check passed; compile_failed: the plugin loaded but left the audio unchanged or silent; checks_failed: it loaded but a check failed and was not fixed; abandoned: stopped early"),
9904
+ example: z38.string().optional().describe("The shipped example the plugin started from: mutate-verb, tape-sat, width-bass-mono, or none"),
9905
+ rounds: z38.coerce.number().int().min(1).optional().describe("write_jsfx \u2192 load \u2192 check rounds it took (default 1)"),
9906
+ checksPassed: z38.coerce.number().int().min(0).optional().describe("Verification checks that passed in the last round"),
9907
+ checksFailed: z38.coerce.number().int().min(0).optional().describe("Verification checks that failed in the last round"),
9908
+ cleanedUp: z38.boolean().optional().describe("The scratch track was deleted and nothing else changed"),
9909
+ scratchTag: z38.string().optional().describe('The <TAG> of your "[MCP] make-plugin <TAG>" track, so the server can time the run. Never sent.')
9723
9910
  },
9724
9911
  async (args) => {
9725
9912
  const attributes = buildAttributes({ ...args, seconds: runSeconds(args.scratchTag) });
@@ -9733,8 +9920,8 @@ function registerPluginBuildTools(server) {
9733
9920
  // apps/reaper-mcp-server/src/server.ts
9734
9921
  var MAX_STATUS_MESSAGE = 256;
9735
9922
  var TOOL_ERROR_MESSAGE = "reaper.tool.error.message";
9736
- function saveProjectErrorCause(text8) {
9737
- const t = text8.replace(/^Error:\s*/, "");
9923
+ function saveProjectErrorCause(text9) {
9924
+ const t = text9.replace(/^Error:\s*/, "");
9738
9925
  if (t.startsWith("refused: the project was never saved")) return "project_never_saved";
9739
9926
  if (t.startsWith("path must end in .rpp")) return "path_not_rpp";
9740
9927
  if (t.startsWith("path must be absolute")) return "path_not_absolute";
@@ -9743,13 +9930,13 @@ function saveProjectErrorCause(text8) {
9743
9930
  if (t.startsWith("save failed:")) return "file_not_written";
9744
9931
  return void 0;
9745
9932
  }
9746
- function toolErrorCause(text8, toolName) {
9933
+ function toolErrorCause(text9, toolName) {
9747
9934
  if (toolName === "save_project") {
9748
- const saveCause = saveProjectErrorCause(text8);
9935
+ const saveCause = saveProjectErrorCause(text9);
9749
9936
  if (saveCause) return saveCause;
9750
9937
  }
9751
- if (isSidecarMissing(text8)) return "sidecar_not_installed";
9752
- const type = classifyBridgeError(text8.replace(/^Error:\s*/, ""));
9938
+ if (isSidecarMissing(text9)) return "sidecar_not_installed";
9939
+ const type = classifyBridgeError(text9.replace(/^Error:\s*/, ""));
9753
9940
  return type === "bridge_not_running" || type === "bridge_outdated" ? type : void 0;
9754
9941
  }
9755
9942
  function instrumentToolHandlers(server) {
@@ -9875,6 +10062,7 @@ function createServer(profile = resolveProfile()) {
9875
10062
  registerAestheticsTools(server);
9876
10063
  registerOfflineTools(server);
9877
10064
  registerTransientTools(server);
10065
+ registerPitchTools(server);
9878
10066
  registerMixcheckTools(server);
9879
10067
  registerMixingTools(server);
9880
10068
  registerAlignTools(server);
@@ -9983,8 +10171,8 @@ import { readFile as readFile3, writeFile as writeFile3, unlink as unlink3 } fro
9983
10171
  import { join as join10 } from "node:path";
9984
10172
  var STATE_TIMEOUT_MS = 6e4;
9985
10173
  var b64 = (bytes) => Buffer.from(bytes).toString("base64");
9986
- var unb64 = (text8) => new Uint8Array(Buffer.from(text8, "base64"));
9987
- var fail2 = (error7) => ({ ok: false, error: error7 });
10174
+ var unb64 = (text9) => new Uint8Array(Buffer.from(text9, "base64"));
10175
+ var fail2 = (error8) => ({ ok: false, error: error8 });
9988
10176
  function createFxStateClient(host) {
9989
10177
  async function get(loc) {
9990
10178
  const dir = await host.bridgeDir();
@@ -10042,7 +10230,7 @@ ${b64(fixed.state)}
10042
10230
  }
10043
10231
 
10044
10232
  // apps/reaper-mcp-server/src/extensions.ts
10045
- import { z as z38 } from "zod/v4";
10233
+ import { z as z39 } from "zod/v4";
10046
10234
  import { existsSync as existsSync6 } from "node:fs";
10047
10235
  function getExtensionsDir() {
10048
10236
  return process.env["REAPER_MCP_EXTENSIONS"] || join11(homedir8(), ".reaper-mcp", "extensions");
@@ -10079,18 +10267,18 @@ async function discoverExtensions(root = getExtensionsDir()) {
10079
10267
  }
10080
10268
  var REGISTER_TIMEOUT_MS = 1e4;
10081
10269
  var TOOL_NAME = /^[a-z][a-z0-9_]{0,47}$/;
10082
- var text7 = (t) => ({ content: [{ type: "text", text: t }] });
10270
+ var text8 = (t) => ({ content: [{ type: "text", text: t }] });
10083
10271
  function createApi(server, manifest) {
10084
10272
  const prefix = manifest.name.replace(/-/g, "_");
10085
10273
  const toolNames = [];
10086
10274
  const registered = [];
10087
10275
  let categoryDescription;
10088
- const json2 = (data) => text7(JSON.stringify(data, null, 2));
10089
- const error7 = (message) => ({ content: [{ type: "text", text: `Error: ${message}` }], isError: true });
10276
+ const json2 = (data) => text8(JSON.stringify(data, null, 2));
10277
+ const error8 = (message) => ({ content: [{ type: "text", text: `Error: ${message}` }], isError: true });
10090
10278
  const api = {
10091
10279
  name: manifest.name,
10092
10280
  apiVersion: EXTENSION_API_VERSION,
10093
- z: z38,
10281
+ z: z39,
10094
10282
  tool(name, description, shape2, handler) {
10095
10283
  if (!TOOL_NAME.test(name)) throw new Error(`tool name "${name}" must be lowercase letters, digits and underscores`);
10096
10284
  const full = `${prefix}_${name}`;
@@ -10101,7 +10289,7 @@ function createApi(server, manifest) {
10101
10289
  try {
10102
10290
  return await handler(args);
10103
10291
  } catch (err) {
10104
- return error7(err instanceof Error ? err.message : String(err));
10292
+ return error8(err instanceof Error ? err.message : String(err));
10105
10293
  }
10106
10294
  });
10107
10295
  registered.push(reg);
@@ -10113,9 +10301,9 @@ function createApi(server, manifest) {
10113
10301
  bridge: (command2, params, timeoutMs) => sendCommand(command2, params, timeoutMs),
10114
10302
  bridgeDir: ensureBridgeDir
10115
10303
  }),
10116
- reply: (res) => res.success ? json2(res.data) : error7(res.error ?? "failed"),
10304
+ reply: (res) => res.success ? json2(res.data) : error8(res.error ?? "failed"),
10117
10305
  json: json2,
10118
- error: error7,
10306
+ error: error8,
10119
10307
  describeCategory(description) {
10120
10308
  categoryDescription = description;
10121
10309
  }
@@ -10219,7 +10407,7 @@ import { promisify } from "node:util";
10219
10407
  import { fileURLToPath as fileURLToPath5 } from "node:url";
10220
10408
  var run4 = promisify(execFile);
10221
10409
  var NAME2 = /^[a-z][a-z0-9-]{1,31}$/;
10222
- var fail3 = (error7) => ({ ok: false, error: error7 });
10410
+ var fail3 = (error8) => ({ ok: false, error: error8 });
10223
10411
  async function readManifest(dir) {
10224
10412
  let raw;
10225
10413
  try {
@@ -10480,17 +10668,17 @@ function assignExperimentVariant(flagKey, experiment, targetingKey) {
10480
10668
  }
10481
10669
 
10482
10670
  // libs/feature-flags/src/schema.ts
10483
- import { z as z39 } from "zod/v4";
10671
+ import { z as z40 } from "zod/v4";
10484
10672
  var FLAG_KEY_PATTERN = /^[a-z][a-z0-9-]*$/;
10485
- var FlagTypeSchema = z39.enum(["boolean", "string", "number", "object"]);
10486
- var ExperimentVariantSchema = z39.object({
10487
- key: z39.string().min(1),
10488
- description: z39.string().optional(),
10489
- weight: z39.number().min(0).max(100)
10673
+ var FlagTypeSchema = z40.enum(["boolean", "string", "number", "object"]);
10674
+ var ExperimentVariantSchema = z40.object({
10675
+ key: z40.string().min(1),
10676
+ description: z40.string().optional(),
10677
+ weight: z40.number().min(0).max(100)
10490
10678
  });
10491
- var ExperimentSchema = z39.object({
10492
- enabled: z39.boolean().default(false),
10493
- variants: z39.array(ExperimentVariantSchema).min(2)
10679
+ var ExperimentSchema = z40.object({
10680
+ enabled: z40.boolean().default(false),
10681
+ variants: z40.array(ExperimentVariantSchema).min(2)
10494
10682
  }).superRefine((experiment, ctx) => {
10495
10683
  const total = experiment.variants.reduce((sum, v) => sum + v.weight, 0);
10496
10684
  if (Math.abs(total - 100) > 1e-3) {
@@ -10504,21 +10692,21 @@ var ExperimentSchema = z39.object({
10504
10692
  ctx.addIssue({ code: "custom", message: "experiment.variants keys must be unique" });
10505
10693
  }
10506
10694
  });
10507
- var jsonValue = z39.lazy(
10508
- () => z39.union([z39.boolean(), z39.string(), z39.number(), z39.null(), z39.array(jsonValue), z39.record(z39.string(), jsonValue)])
10695
+ var jsonValue = z40.lazy(
10696
+ () => z40.union([z40.boolean(), z40.string(), z40.number(), z40.null(), z40.array(jsonValue), z40.record(z40.string(), jsonValue)])
10509
10697
  );
10510
- var FlagDefinitionSchema = z39.object({
10511
- key: z39.string().regex(FLAG_KEY_PATTERN, 'flag key must be kebab-case (e.g. "example-new-panel")'),
10512
- description: z39.string().min(1),
10698
+ var FlagDefinitionSchema = z40.object({
10699
+ key: z40.string().regex(FLAG_KEY_PATTERN, 'flag key must be kebab-case (e.g. "example-new-panel")'),
10700
+ description: z40.string().min(1),
10513
10701
  type: FlagTypeSchema,
10514
10702
  /** Variant key -> the value returned for that variant. Must include `defaultVariant`. */
10515
- variants: z39.record(z39.string(), jsonValue),
10516
- defaultVariant: z39.string().min(1),
10703
+ variants: z40.record(z40.string(), jsonValue),
10704
+ defaultVariant: z40.string().min(1),
10517
10705
  /** Optional A/B(/n) experiment. Every `experiment.variants[].key` must exist in `variants`. */
10518
10706
  experiment: ExperimentSchema.optional(),
10519
10707
  /** Who owns the flag, surfaced in the manifest for cleanup audits. */
10520
- owner: z39.string().min(1),
10521
- tags: z39.array(z39.string()).default([])
10708
+ owner: z40.string().min(1),
10709
+ tags: z40.array(z40.string()).default([])
10522
10710
  }).superRefine((def, ctx) => {
10523
10711
  if (!Object.hasOwn(def.variants, def.defaultVariant)) {
10524
10712
  ctx.addIssue({
@@ -10544,7 +10732,7 @@ var FlagDefinitionSchema = z39.object({
10544
10732
  });
10545
10733
  }
10546
10734
  });
10547
- var FlagRegistrySchema = z39.array(FlagDefinitionSchema).superRefine((defs, ctx) => {
10735
+ var FlagRegistrySchema = z40.array(FlagDefinitionSchema).superRefine((defs, ctx) => {
10548
10736
  const keys = defs.map((d) => d.key);
10549
10737
  const dupes = keys.filter((k, i) => keys.indexOf(k) !== i);
10550
10738
  if (dupes.length > 0) {
@@ -10632,11 +10820,11 @@ var featureFlagOtelHook = {
10632
10820
  attrs[ATTR_FEATURE_FLAG_RESULT_REASON] = flagReasonValue(details.reason);
10633
10821
  stampSpan(span, attrs);
10634
10822
  },
10635
- error(hookContext, error7) {
10823
+ error(hookContext, error8) {
10636
10824
  const span = trace12.getActiveSpan();
10637
10825
  if (!span) return;
10638
10826
  stampSpan(span, baseAttributes(hookContext));
10639
- if (error7 instanceof Error) span.recordException(error7);
10827
+ if (error8 instanceof Error) span.recordException(error8);
10640
10828
  }
10641
10829
  };
10642
10830
 
@@ -10997,15 +11185,15 @@ function detectHarnesses(env = realEnv()) {
10997
11185
  return HARNESSES.filter((h) => h.binary ? env.hasBinary(h.binary) : existsSync8(join15(env.home, ".cursor")));
10998
11186
  }
10999
11187
  function registeredServer(id, env = realEnv()) {
11000
- let text8;
11188
+ let text9;
11001
11189
  try {
11002
- text8 = readFileSync8(configPath(id, env), "utf-8");
11190
+ text9 = readFileSync8(configPath(id, env), "utf-8");
11003
11191
  } catch {
11004
11192
  return null;
11005
11193
  }
11006
- if (id === "codex") return codexServer(text8);
11194
+ if (id === "codex") return codexServer(text9);
11007
11195
  try {
11008
- const server = JSON.parse(text8)?.mcpServers?.[SERVER_NAME];
11196
+ const server = JSON.parse(text9)?.mcpServers?.[SERVER_NAME];
11009
11197
  if (!server || typeof server.command !== "string") return null;
11010
11198
  return { command: server.command, args: Array.isArray(server.args) ? server.args.filter((a) => typeof a === "string") : [] };
11011
11199
  } catch {
@@ -11311,7 +11499,7 @@ import { createHash as createHash3 } from "node:crypto";
11311
11499
  import { existsSync as existsSync11, mkdirSync as mkdirSync11, readFileSync as readFileSync11, readdirSync as readdirSync3, writeFileSync as writeFileSync10 } from "node:fs";
11312
11500
  import { join as join18 } from "node:path";
11313
11501
  var MANIFEST = ".installed.json";
11314
- var sha2 = (text8) => createHash3("sha256").update(text8).digest("hex");
11502
+ var sha2 = (text9) => createHash3("sha256").update(text9).digest("hex");
11315
11503
  function installExamplePlugins(examplesDir, outDir, toolkit, presetsDir2) {
11316
11504
  const result = { installed: [], kept: [], presets: {}, presetErrors: [] };
11317
11505
  if (!existsSync11(examplesDir)) return result;
@@ -11429,8 +11617,8 @@ function repairBridgeInstall(paths, version, opts) {
11429
11617
  const bridgeChanged = reapack ? false : installReaperFiles(paths);
11430
11618
  const startupPath = join19(paths.scriptsDir, "__startup.lua");
11431
11619
  const startup = existsSync12(startupPath) ? readFileSync12(startupPath, "utf-8") : "";
11432
- const { text: text8, changed } = ensureBridgeAutostart(startup);
11433
- if (changed) writeFileSync11(startupPath, text8, "utf-8");
11620
+ const { text: text9, changed } = ensureBridgeAutostart(startup);
11621
+ if (changed) writeFileSync11(startupPath, text9, "utf-8");
11434
11622
  writeBridgeVersion(paths.scriptsDir, version);
11435
11623
  return { from, bridgeChanged, autostartAdded: !startup.includes(AUTOSTART_MARKER) };
11436
11624
  }
@@ -11797,8 +11985,8 @@ async function enableWebInterface() {
11797
11985
  function installBridgeAutostart(scriptsDir) {
11798
11986
  console.log(ui.section("Starting the bridge with REAPER..."));
11799
11987
  const path = join21(scriptsDir, "__startup.lua");
11800
- const { text: text8, changed } = ensureBridgeAutostart(existsSync13(path) ? readFileSync15(path, "utf-8") : "");
11801
- if (changed) writeFileSync12(path, text8, "utf-8");
11988
+ const { text: text9, changed } = ensureBridgeAutostart(existsSync13(path) ? readFileSync15(path, "utf-8") : "");
11989
+ if (changed) writeFileSync12(path, text9, "utf-8");
11802
11990
  console.log(ui.item("ok", changed ? "Added to Scripts/__startup.lua (REAPER runs it at launch)" : "Already in Scripts/__startup.lua"));
11803
11991
  console.log(ui.dim(" Turn it off in the bridge window: Settings > Start with REAPER."));
11804
11992
  }
@@ -12154,7 +12342,7 @@ async function serve() {
12154
12342
  if (repair.bridgeChanged) startupSpan.setAttribute("reaper.bridge.files_updated", true);
12155
12343
  if (repair.autostartAdded) startupSpan.setAttribute("reaper.bridge.autostart_added", true);
12156
12344
  log(`Updated REAPER's reaper-mcp files from ${repair.from ?? "an earlier release"} to ${version}`);
12157
- for (const text8 of repairNotices(repair, version, bridge.state === "connected")) addNotice({ text: text8 });
12345
+ for (const text9 of repairNotices(repair, version, bridge.state === "connected")) addNotice({ text: text9 });
12158
12346
  }
12159
12347
  const profile = resolveProfile();
12160
12348
  const server = createServer(profile);
@@ -12186,13 +12374,13 @@ async function serve() {
12186
12374
  }));
12187
12375
  startupSpan.setStatus({ code: SpanStatusCode4.OK });
12188
12376
  log("MCP server connected via stdio");
12189
- } catch (error7) {
12190
- const err = error7 instanceof Error ? error7 : new Error(String(error7));
12377
+ } catch (error8) {
12378
+ const err = error8 instanceof Error ? error8 : new Error(String(error8));
12191
12379
  startupSpan.setStatus({
12192
12380
  code: SpanStatusCode4.ERROR,
12193
12381
  message: `${err.name}: ${err.message}`
12194
12382
  });
12195
- throw error7;
12383
+ throw error8;
12196
12384
  } finally {
12197
12385
  startupSpan.end();
12198
12386
  }