@mthines/reaper-mcp 0.104.1 → 0.106.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
@@ -10720,164 +10720,13 @@ Try it: reaper-mcp extension link ${basename4(r.dir)}`);
10720
10720
  }
10721
10721
  }
10722
10722
 
10723
- // apps/reaper-mcp-server/src/instance-cli.ts
10724
- import { execFileSync as execFileSync2, spawn as spawn2, spawnSync } from "node:child_process";
10725
- import { existsSync as existsSync10, realpathSync, statSync as statSync3 } from "node:fs";
10726
- import { homedir as homedir11, platform as platform6 } from "node:os";
10727
- import { join as join15 } from "node:path";
10728
-
10729
- // apps/reaper-mcp-server/src/harnesses.ts
10730
- import { execFileSync } from "node:child_process";
10731
- import { existsSync as existsSync8, mkdirSync as mkdirSync7, readFileSync as readFileSync6, writeFileSync as writeFileSync6 } from "node:fs";
10732
- import { delimiter, dirname as dirname8, isAbsolute as isAbsolute3, join as join13 } from "node:path";
10733
- import { homedir as homedir9, platform as platform4 } from "node:os";
10734
- var HARNESSES = [
10735
- { id: "claude", name: "Claude Code", binary: "claude", installHint: "https://claude.com/claude-code", skillsHome: "claude" },
10736
- { id: "codex", name: "Codex CLI", binary: "codex", installHint: "npm install -g @openai/codex (or: brew install codex)", skillsHome: "agents" },
10737
- { id: "gemini", name: "Gemini CLI", binary: "gemini", installHint: "npm install -g @google/gemini-cli", skillsHome: "agents" },
10738
- { id: "cursor", name: "Cursor", binary: null, installHint: "https://cursor.com", skillsHome: "agents" }
10739
- ];
10740
- var SERVER_NAME = "reaper";
10741
- var DEFAULT_SERVER = { name: SERVER_NAME, env: {} };
10742
- function onPath(name, pathVar = process.env.PATH ?? "", win = platform4() === "win32") {
10743
- const exts = win ? ["", ".exe", ".cmd", ".bat"] : [""];
10744
- return pathVar.split(delimiter).filter(Boolean).some((dir) => exts.some((ext) => existsSync8(join13(dir, name + ext))));
10745
- }
10746
- function realEnv() {
10747
- return { home: homedir9(), codexHome: process.env.CODEX_HOME || void 0, hasBinary: (name) => onPath(name) };
10748
- }
10749
- var configPath = (id, env) => ({
10750
- claude: join13(env.home, ".claude.json"),
10751
- codex: join13(env.codexHome ?? join13(env.home, ".codex"), "config.toml"),
10752
- gemini: join13(env.home, ".gemini", "settings.json"),
10753
- cursor: join13(env.home, ".cursor", "mcp.json")
10754
- })[id];
10755
- function detectHarnesses(env = realEnv()) {
10756
- return HARNESSES.filter((h) => h.binary ? env.hasBinary(h.binary) : existsSync8(join13(env.home, ".cursor")));
10757
- }
10758
- function registeredServer(id, env = realEnv(), name = SERVER_NAME) {
10759
- let text9;
10760
- try {
10761
- text9 = readFileSync6(configPath(id, env), "utf-8");
10762
- } catch {
10763
- return null;
10764
- }
10765
- if (id === "codex") return codexServer(text9, name);
10766
- try {
10767
- const server = JSON.parse(text9)?.mcpServers?.[name];
10768
- if (!server || typeof server.command !== "string") return null;
10769
- return { command: server.command, args: Array.isArray(server.args) ? server.args.filter((a) => typeof a === "string") : [] };
10770
- } catch {
10771
- return null;
10772
- }
10773
- }
10774
- function codexServer(toml, name) {
10775
- const header = new RegExp(`^\\[mcp_servers\\.(?:${name}|"${name}")\\]\\s*$`, "m").exec(toml);
10776
- if (!header) return null;
10777
- const rest = toml.slice(header.index + header[0].length);
10778
- const next = /^\[/m.exec(rest);
10779
- const section = next ? rest.slice(0, next.index) : rest;
10780
- const command2 = /^command\s*=\s*("(?:[^"\\]|\\.)*"|'[^']*')/m.exec(section)?.[1];
10781
- if (!command2) return null;
10782
- const args = /^args\s*=\s*\[([^\]]*)\]/m.exec(section)?.[1] ?? "";
10783
- const strings = (s) => [...s.matchAll(/"((?:[^"\\]|\\.)*)"|'([^']*)'/g)].map((m) => m[1] !== void 0 ? JSON.parse(`"${m[1]}"`) : m[2]);
10784
- return { command: strings(command2)[0], args: strings(args) };
10785
- }
10786
- function isStale(server) {
10787
- return [server.command, ...server.args].filter(isAbsolute3).some((p) => !existsSync8(p));
10788
- }
10789
- var envFlags = (env, flag) => Object.entries(env).flatMap(([k, v]) => [flag, `${k}=${v}`]);
10790
- function addCommand(id, node, mainJs, server = DEFAULT_SERVER) {
10791
- switch (id) {
10792
- case "claude":
10793
- return { bin: "claude", args: ["mcp", "add", "--scope", "user", ...envFlags(server.env, "--env"), server.name, "--", node, mainJs, "serve"] };
10794
- case "codex":
10795
- return { bin: "codex", args: ["mcp", "add", server.name, ...envFlags(server.env, "--env"), "--", node, mainJs, "serve"] };
10796
- case "gemini":
10797
- return { bin: "gemini", args: ["mcp", "add", "--scope", "user", ...envFlags(server.env, "-e"), server.name, node, mainJs, "serve"] };
10798
- case "cursor":
10799
- return null;
10800
- }
10801
- }
10802
- function removeCommand(id, name) {
10803
- switch (id) {
10804
- case "claude":
10805
- return { bin: "claude", args: ["mcp", "remove", "--scope", "user", name] };
10806
- case "codex":
10807
- return { bin: "codex", args: ["mcp", "remove", name] };
10808
- case "gemini":
10809
- return { bin: "gemini", args: ["mcp", "remove", "--scope", "user", name] };
10810
- case "cursor":
10811
- return null;
10812
- }
10813
- }
10814
- function manualCommand(id, node, mainJs, env = realEnv(), server = DEFAULT_SERVER) {
10815
- const add2 = addCommand(id, node, mainJs, server);
10816
- if (add2) return [add2.bin, ...add2.args].join(" ");
10817
- const envPart = Object.keys(server.env).length ? `, "env": ${JSON.stringify(server.env)}` : "";
10818
- return `add "${server.name}": { "command": "${node}", "args": ["${mainJs}", "serve"]${envPart} } under "mcpServers" in ${configPath(id, env)}`;
10819
- }
10820
- function quoteForCmd(arg) {
10821
- return /[\s"]/.test(arg) ? `"${arg.replace(/"/g, '\\"')}"` : arg;
10822
- }
10823
- var realRunner = (bin, args) => {
10824
- if (platform4() === "win32") execFileSync(quoteForCmd(bin), args.map(quoteForCmd), { stdio: "pipe", shell: true });
10825
- else execFileSync(bin, args, { stdio: "pipe" });
10826
- };
10827
- function writeJsonServer(path, node, mainJs, server) {
10828
- let config = {};
10829
- if (existsSync8(path)) config = JSON.parse(readFileSync6(path, "utf-8"));
10830
- const servers = config.mcpServers && typeof config.mcpServers === "object" ? config.mcpServers : {};
10831
- servers[server.name] = { command: node, args: [mainJs, "serve"], ...Object.keys(server.env).length ? { env: server.env } : {} };
10832
- config.mcpServers = servers;
10833
- mkdirSync7(dirname8(path), { recursive: true });
10834
- writeFileSync6(path, JSON.stringify(config, null, 2) + "\n", "utf-8");
10835
- }
10836
- function connectHarness(id, node, mainJs, env = realEnv(), run5 = realRunner, server = DEFAULT_SERVER) {
10837
- const existing = registeredServer(id, env, server.name);
10838
- if (existing && !isStale(existing)) return { id, status: "already" };
10839
- const manual = manualCommand(id, node, mainJs, env, server);
10840
- try {
10841
- const add2 = addCommand(id, node, mainJs, server);
10842
- if (!add2) {
10843
- writeJsonServer(configPath(id, env), node, mainJs, server);
10844
- } else {
10845
- const remove2 = removeCommand(id, server.name);
10846
- if (existing && remove2) run5(remove2.bin, remove2.args);
10847
- run5(add2.bin, add2.args);
10848
- }
10849
- } catch (err) {
10850
- const missing = err.code === "ENOENT";
10851
- const first = String(err.message).split("\n")[0];
10852
- return { id, status: "failed", detail: missing ? "its command was not found" : first, manual };
10853
- }
10854
- return { id, status: existing ? "replaced" : "connected" };
10855
- }
10856
- function parseHarnessFlag(argv) {
10857
- if (argv.includes("--all")) return HARNESSES.map((h) => h.id);
10858
- const i = argv.findIndex((a) => a === "--harness" || a.startsWith("--harness="));
10859
- if (i < 0) return null;
10860
- const value = argv[i].includes("=") ? argv[i].split("=")[1] : argv[i + 1];
10861
- const ids = (value ?? "").split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
10862
- const known = HARNESSES.map((h) => h.id);
10863
- const bad = ids.filter((s) => !known.includes(s));
10864
- if (!ids.length || bad.length) {
10865
- throw new Error(`Unknown harness${bad.length > 1 ? "es" : ""}: ${bad.join(", ") || "(none given)"}. Use one or more of: ${known.join(", ")}, or --all.`);
10866
- }
10867
- return [...new Set(ids)];
10868
- }
10869
- function skillsHomes(ids) {
10870
- const chosen = HARNESSES.filter((h) => ids.includes(h.id));
10871
- return { claude: chosen.some((h) => h.skillsHome === "claude"), agents: chosen.some((h) => h.skillsHome === "agents") };
10872
- }
10873
-
10874
10723
  // apps/reaper-mcp-server/src/instance.ts
10875
- import { copyFileSync as copyFileSync4, existsSync as existsSync9, mkdirSync as mkdirSync8, readdirSync as readdirSync2, readFileSync as readFileSync7, rmSync as rmSync2, statSync as statSync2, symlinkSync, writeFileSync as writeFileSync7 } from "node:fs";
10876
- import { homedir as homedir10, platform as platform5 } from "node:os";
10877
- import { join as join14 } from "node:path";
10724
+ import { copyFileSync as copyFileSync4, existsSync as existsSync8, mkdirSync as mkdirSync7, readdirSync as readdirSync2, readFileSync as readFileSync6, rmSync as rmSync2, statSync as statSync2, symlinkSync, writeFileSync as writeFileSync6 } from "node:fs";
10725
+ import { homedir as homedir9, platform as platform4 } from "node:os";
10726
+ import { join as join13 } from "node:path";
10878
10727
  var INSTANCE_NAME = /^[a-z][a-z0-9-]{0,29}$/;
10879
10728
  function instancesRoot() {
10880
- return process.env["REAPER_MCP_INSTANCES_DIR"] || join14(homedir10(), ".reaper-mcp", "instances");
10729
+ return process.env["REAPER_MCP_INSTANCES_DIR"] || join13(homedir9(), ".reaper-mcp", "instances");
10881
10730
  }
10882
10731
  function validateInstanceName(name) {
10883
10732
  if (!name || !INSTANCE_NAME.test(name)) {
@@ -10886,8 +10735,8 @@ function validateInstanceName(name) {
10886
10735
  if (name === "default") throw new Error('"default" is your own REAPER: pick another name');
10887
10736
  return name;
10888
10737
  }
10889
- var instanceDir = (name, root = instancesRoot()) => join14(root, name);
10890
- var infoPath = (name, root = instancesRoot()) => join14(instanceDir(name, root), "instance.json");
10738
+ var instanceDir = (name, root = instancesRoot()) => join13(root, name);
10739
+ var infoPath = (name, root = instancesRoot()) => join13(instanceDir(name, root), "instance.json");
10891
10740
  function iniForInstance(mainIni, port) {
10892
10741
  const eol = mainIni.includes("\r\n") ? "\r\n" : "\n";
10893
10742
  const kept = mainIni.split(/\r?\n/).filter((line) => !/^csurf_(?:cnt|\d+)=/.test(line) && !/^loadlastproj=/.test(line));
@@ -10905,17 +10754,17 @@ var SPLIT_DIRS = {
10905
10754
  };
10906
10755
  function link(target, path, isDir) {
10907
10756
  try {
10908
- symlinkSync(target, path, isDir ? platform5() === "win32" ? "junction" : "dir" : "file");
10757
+ symlinkSync(target, path, isDir ? platform4() === "win32" ? "junction" : "dir" : "file");
10909
10758
  } catch (err) {
10910
10759
  if (isDir) throw err;
10911
10760
  copyFileSync4(target, path);
10912
10761
  }
10913
10762
  }
10914
10763
  function linkSplit(main, instance, rel, linked) {
10915
- const src = join14(main, rel);
10916
- if (!existsSync9(src) || !statSync2(src).isDirectory()) return;
10917
- const dest = join14(instance, rel);
10918
- mkdirSync8(dest, { recursive: true });
10764
+ const src = join13(main, rel);
10765
+ if (!existsSync8(src) || !statSync2(src).isDirectory()) return;
10766
+ const dest = join13(instance, rel);
10767
+ mkdirSync7(dest, { recursive: true });
10919
10768
  for (const entry of readdirSync2(src)) {
10920
10769
  const entryRel = `${rel}/${entry}`;
10921
10770
  if (SPLIT_DIRS[rel].test(entry)) continue;
@@ -10923,19 +10772,19 @@ function linkSplit(main, instance, rel, linked) {
10923
10772
  linkSplit(main, instance, entryRel, linked);
10924
10773
  continue;
10925
10774
  }
10926
- if (existsSync9(join14(dest, entry))) continue;
10927
- link(join14(src, entry), join14(dest, entry), statSync2(join14(src, entry)).isDirectory());
10775
+ if (existsSync8(join13(dest, entry))) continue;
10776
+ link(join13(src, entry), join13(dest, entry), statSync2(join13(src, entry)).isDirectory());
10928
10777
  linked.push(entryRel);
10929
10778
  }
10930
10779
  }
10931
10780
  function linkShared(mainResource, instanceResource) {
10932
10781
  const linked = [];
10933
- if (!existsSync9(mainResource)) return linked;
10782
+ if (!existsSync8(mainResource)) return linked;
10934
10783
  for (const entry of readdirSync2(mainResource)) {
10935
10784
  if (SHARED_FILES.some((re) => re.test(entry)) || SHARED_DIRS.includes(entry)) {
10936
- const dest = join14(instanceResource, entry);
10937
- if (existsSync9(dest)) continue;
10938
- link(join14(mainResource, entry), dest, SHARED_DIRS.includes(entry));
10785
+ const dest = join13(instanceResource, entry);
10786
+ if (existsSync8(dest)) continue;
10787
+ link(join13(mainResource, entry), dest, SHARED_DIRS.includes(entry));
10939
10788
  linked.push(entry);
10940
10789
  }
10941
10790
  }
@@ -10943,9 +10792,9 @@ function linkShared(mainResource, instanceResource) {
10943
10792
  return linked;
10944
10793
  }
10945
10794
  function seedReaPack(mainResource, instanceResource) {
10946
- const src = join14(mainResource, "reapack.ini");
10947
- const dest = join14(instanceResource, "reapack.ini");
10948
- if (!existsSync9(src) || existsSync9(dest)) return false;
10795
+ const src = join13(mainResource, "reapack.ini");
10796
+ const dest = join13(instanceResource, "reapack.ini");
10797
+ if (!existsSync8(src) || existsSync8(dest)) return false;
10949
10798
  copyFileSync4(src, dest);
10950
10799
  return true;
10951
10800
  }
@@ -10955,7 +10804,7 @@ function nextFreePort(used, from = DEFAULT_WEB_PORT + 1) {
10955
10804
  return port;
10956
10805
  }
10957
10806
  function listInstances(root = instancesRoot()) {
10958
- if (!existsSync9(root)) return [];
10807
+ if (!existsSync8(root)) return [];
10959
10808
  const out2 = [];
10960
10809
  for (const name of readdirSync2(root).sort()) {
10961
10810
  const info = readInstance(name, root);
@@ -10965,7 +10814,7 @@ function listInstances(root = instancesRoot()) {
10965
10814
  }
10966
10815
  function readInstance(name, root = instancesRoot()) {
10967
10816
  try {
10968
- return JSON.parse(readFileSync7(infoPath(name, root), "utf-8"));
10817
+ return JSON.parse(readFileSync6(infoPath(name, root), "utf-8"));
10969
10818
  } catch {
10970
10819
  return null;
10971
10820
  }
@@ -10974,14 +10823,15 @@ function createInstanceFiles(options) {
10974
10823
  const name = validateInstanceName(options.name);
10975
10824
  const root = options.root ?? instancesRoot();
10976
10825
  if (readInstance(name, root)) throw new Error(`Instance "${name}" exists already (reaper-mcp instance remove ${name} first, or pick another name)`);
10977
- const mainIni = join14(options.mainResource, "reaper.ini");
10978
- if (!existsSync9(mainIni)) throw new Error(`${mainIni} not found: start REAPER once, quit it, then create the instance (or set REAPER_RESOURCE_PATH to REAPER's resource folder)`);
10826
+ const mainIni = join13(options.mainResource, "reaper.ini");
10827
+ if (!existsSync8(mainIni)) throw new Error(`${mainIni} not found: start REAPER once, quit it, then create the instance (or set REAPER_RESOURCE_PATH to REAPER's resource folder)`);
10979
10828
  const taken = listInstances(root).map((i) => i.port);
10980
10829
  const port = options.port ?? nextFreePort([...taken, Number(process.env["REAPER_WEB_PORT"]) || DEFAULT_WEB_PORT]);
10981
10830
  if (taken.includes(port)) throw new Error(`Port ${port} is used by another instance (reaper-mcp instance list)`);
10982
- const resourcePath = join14(instanceDir(name, root), "REAPER");
10983
- mkdirSync8(join14(resourcePath, "Scripts"), { recursive: true });
10984
- writeFileSync7(join14(resourcePath, "reaper.ini"), iniForInstance(readFileSync7(mainIni, "utf-8"), port), "utf-8");
10831
+ const resourcePath = join13(instanceDir(name, root), "REAPER");
10832
+ mkdirSync7(join13(resourcePath, "Scripts"), { recursive: true });
10833
+ writeInstanceConf({ name, resourcePath });
10834
+ writeFileSync6(join13(resourcePath, "reaper.ini"), iniForInstance(readFileSync6(mainIni, "utf-8"), port), "utf-8");
10985
10835
  linkShared(options.mainResource, resourcePath);
10986
10836
  seedReaPack(options.mainResource, resourcePath);
10987
10837
  const info = {
@@ -10998,7 +10848,7 @@ function createInstanceFiles(options) {
10998
10848
  return info;
10999
10849
  }
11000
10850
  function saveInstance(info, root = instancesRoot()) {
11001
- writeFileSync7(infoPath(info.name, root), JSON.stringify(info, null, 2) + "\n", "utf-8");
10851
+ writeFileSync6(infoPath(info.name, root), JSON.stringify(info, null, 2) + "\n", "utf-8");
11002
10852
  }
11003
10853
  function removeInstance(name, root = instancesRoot()) {
11004
10854
  validateInstanceName(name);
@@ -11007,13 +10857,37 @@ function removeInstance(name, root = instancesRoot()) {
11007
10857
  return true;
11008
10858
  }
11009
10859
  function launchCommand(info, project, os, reaperExe) {
11010
- const reaperArgs = ["-newinst", "-nosplash", "-cfgfile", join14(info.resourcePath, "reaper.ini"), ...project ? [project] : []];
10860
+ const reaperArgs = ["-newinst", "-nosplash", "-cfgfile", join13(info.resourcePath, "reaper.ini"), ...project ? [project] : []];
11011
10861
  if (os === "darwin" && info.app) return { bin: "open", args: ["-n", "-g", "-a", info.app, "--args", ...reaperArgs], detached: false };
11012
10862
  return { bin: reaperExe, args: reaperArgs, detached: true };
11013
10863
  }
10864
+ var INSTANCE_CONF = "mcp_instance.conf";
10865
+ function writeInstanceConf(info) {
10866
+ mkdirSync7(join13(info.resourcePath, "Scripts"), { recursive: true });
10867
+ writeFileSync6(join13(info.resourcePath, "Scripts", INSTANCE_CONF), instanceConfText(info.name), "utf-8");
10868
+ }
10869
+ function instanceConfText(name) {
10870
+ return `name=${name}
10871
+ `;
10872
+ }
10873
+ function instanceLines(root = instancesRoot(), now = Date.now()) {
10874
+ return listInstances(root).map((i) => ({ name: i.name, port: i.port, running: bridgeAlive(i.resourcePath, now) }));
10875
+ }
10876
+ function instanceText(i) {
10877
+ return `${i.name}: port ${i.port}, ${i.running ? "bridge answers" : "not running"}`;
10878
+ }
10879
+ function instancesCheck(lines) {
10880
+ if (lines.length === 0) return null;
10881
+ return {
10882
+ label: "Instances",
10883
+ status: "info",
10884
+ detail: lines.map(instanceText).join(" \xB7 "),
10885
+ fix: lines.some((i) => !i.running) ? "reaper-mcp instance start <name> for one that is not running" : void 0
10886
+ };
10887
+ }
11014
10888
  function bridgeAlive(resourcePath, now = Date.now()) {
11015
10889
  try {
11016
- const ts = JSON.parse(readFileSync7(join14(resourcePath, "Scripts", "mcp_bridge_data", "heartbeat.json"), "utf-8")).timestamp;
10890
+ const ts = JSON.parse(readFileSync6(join13(resourcePath, "Scripts", "mcp_bridge_data", "heartbeat.json"), "utf-8")).timestamp;
11017
10891
  return typeof ts === "number" && Math.abs(now - ts) < 5e3;
11018
10892
  } catch {
11019
10893
  return false;
@@ -11027,9 +10901,9 @@ function serverSpecFor(info) {
11027
10901
  }
11028
10902
  function buildAppCopy(source, dest, bundleId, visible2, run5) {
11029
10903
  rmSync2(dest, { recursive: true, force: true });
11030
- mkdirSync8(join14(dest, ".."), { recursive: true });
10904
+ mkdirSync7(join13(dest, ".."), { recursive: true });
11031
10905
  run5("ditto", [source, dest]);
11032
- const plist = join14(dest, "Contents", "Info.plist");
10906
+ const plist = join13(dest, "Contents", "Info.plist");
11033
10907
  const buddy = "/usr/libexec/PlistBuddy";
11034
10908
  run5(buddy, ["-c", `Set :CFBundleIdentifier ${bundleId}`, plist]);
11035
10909
  if (!visible2) {
@@ -11046,6 +10920,157 @@ function appCopyIsStale(info, sourceMtimeMs) {
11046
10920
  return Boolean(info.app) && info.appSourceMtimeMs !== sourceMtimeMs;
11047
10921
  }
11048
10922
 
10923
+ // apps/reaper-mcp-server/src/instance-cli.ts
10924
+ import { execFileSync as execFileSync2, spawn as spawn2, spawnSync } from "node:child_process";
10925
+ import { existsSync as existsSync10, realpathSync, statSync as statSync3 } from "node:fs";
10926
+ import { homedir as homedir11, platform as platform6 } from "node:os";
10927
+ import { join as join15 } from "node:path";
10928
+
10929
+ // apps/reaper-mcp-server/src/harnesses.ts
10930
+ import { execFileSync } from "node:child_process";
10931
+ import { existsSync as existsSync9, mkdirSync as mkdirSync8, readFileSync as readFileSync7, writeFileSync as writeFileSync7 } from "node:fs";
10932
+ import { delimiter, dirname as dirname8, isAbsolute as isAbsolute3, join as join14 } from "node:path";
10933
+ import { homedir as homedir10, platform as platform5 } from "node:os";
10934
+ var HARNESSES = [
10935
+ { id: "claude", name: "Claude Code", binary: "claude", installHint: "https://claude.com/claude-code", skillsHome: "claude" },
10936
+ { id: "codex", name: "Codex CLI", binary: "codex", installHint: "npm install -g @openai/codex (or: brew install codex)", skillsHome: "agents" },
10937
+ { id: "gemini", name: "Gemini CLI", binary: "gemini", installHint: "npm install -g @google/gemini-cli", skillsHome: "agents" },
10938
+ { id: "cursor", name: "Cursor", binary: null, installHint: "https://cursor.com", skillsHome: "agents" }
10939
+ ];
10940
+ var SERVER_NAME = "reaper";
10941
+ var DEFAULT_SERVER = { name: SERVER_NAME, env: {} };
10942
+ function onPath(name, pathVar = process.env.PATH ?? "", win = platform5() === "win32") {
10943
+ const exts = win ? ["", ".exe", ".cmd", ".bat"] : [""];
10944
+ return pathVar.split(delimiter).filter(Boolean).some((dir) => exts.some((ext) => existsSync9(join14(dir, name + ext))));
10945
+ }
10946
+ function realEnv() {
10947
+ return { home: homedir10(), codexHome: process.env.CODEX_HOME || void 0, hasBinary: (name) => onPath(name) };
10948
+ }
10949
+ var configPath = (id, env) => ({
10950
+ claude: join14(env.home, ".claude.json"),
10951
+ codex: join14(env.codexHome ?? join14(env.home, ".codex"), "config.toml"),
10952
+ gemini: join14(env.home, ".gemini", "settings.json"),
10953
+ cursor: join14(env.home, ".cursor", "mcp.json")
10954
+ })[id];
10955
+ function detectHarnesses(env = realEnv()) {
10956
+ return HARNESSES.filter((h) => h.binary ? env.hasBinary(h.binary) : existsSync9(join14(env.home, ".cursor")));
10957
+ }
10958
+ function registeredServer(id, env = realEnv(), name = SERVER_NAME) {
10959
+ let text9;
10960
+ try {
10961
+ text9 = readFileSync7(configPath(id, env), "utf-8");
10962
+ } catch {
10963
+ return null;
10964
+ }
10965
+ if (id === "codex") return codexServer(text9, name);
10966
+ try {
10967
+ const server = JSON.parse(text9)?.mcpServers?.[name];
10968
+ if (!server || typeof server.command !== "string") return null;
10969
+ return { command: server.command, args: Array.isArray(server.args) ? server.args.filter((a) => typeof a === "string") : [] };
10970
+ } catch {
10971
+ return null;
10972
+ }
10973
+ }
10974
+ function codexServer(toml, name) {
10975
+ const header = new RegExp(`^\\[mcp_servers\\.(?:${name}|"${name}")\\]\\s*$`, "m").exec(toml);
10976
+ if (!header) return null;
10977
+ const rest = toml.slice(header.index + header[0].length);
10978
+ const next = /^\[/m.exec(rest);
10979
+ const section = next ? rest.slice(0, next.index) : rest;
10980
+ const command2 = /^command\s*=\s*("(?:[^"\\]|\\.)*"|'[^']*')/m.exec(section)?.[1];
10981
+ if (!command2) return null;
10982
+ const args = /^args\s*=\s*\[([^\]]*)\]/m.exec(section)?.[1] ?? "";
10983
+ const strings = (s) => [...s.matchAll(/"((?:[^"\\]|\\.)*)"|'([^']*)'/g)].map((m) => m[1] !== void 0 ? JSON.parse(`"${m[1]}"`) : m[2]);
10984
+ return { command: strings(command2)[0], args: strings(args) };
10985
+ }
10986
+ function isStale(server) {
10987
+ return [server.command, ...server.args].filter(isAbsolute3).some((p) => !existsSync9(p));
10988
+ }
10989
+ var envFlags = (env, flag) => Object.entries(env).flatMap(([k, v]) => [flag, `${k}=${v}`]);
10990
+ function addCommand(id, node, mainJs, server = DEFAULT_SERVER) {
10991
+ switch (id) {
10992
+ case "claude":
10993
+ return { bin: "claude", args: ["mcp", "add", "--scope", "user", ...envFlags(server.env, "--env"), server.name, "--", node, mainJs, "serve"] };
10994
+ case "codex":
10995
+ return { bin: "codex", args: ["mcp", "add", server.name, ...envFlags(server.env, "--env"), "--", node, mainJs, "serve"] };
10996
+ case "gemini":
10997
+ return { bin: "gemini", args: ["mcp", "add", "--scope", "user", ...envFlags(server.env, "-e"), server.name, node, mainJs, "serve"] };
10998
+ case "cursor":
10999
+ return null;
11000
+ }
11001
+ }
11002
+ function removeCommand(id, name) {
11003
+ switch (id) {
11004
+ case "claude":
11005
+ return { bin: "claude", args: ["mcp", "remove", "--scope", "user", name] };
11006
+ case "codex":
11007
+ return { bin: "codex", args: ["mcp", "remove", name] };
11008
+ case "gemini":
11009
+ return { bin: "gemini", args: ["mcp", "remove", "--scope", "user", name] };
11010
+ case "cursor":
11011
+ return null;
11012
+ }
11013
+ }
11014
+ function manualCommand(id, node, mainJs, env = realEnv(), server = DEFAULT_SERVER) {
11015
+ const add2 = addCommand(id, node, mainJs, server);
11016
+ if (add2) return [add2.bin, ...add2.args].join(" ");
11017
+ const envPart = Object.keys(server.env).length ? `, "env": ${JSON.stringify(server.env)}` : "";
11018
+ return `add "${server.name}": { "command": "${node}", "args": ["${mainJs}", "serve"]${envPart} } under "mcpServers" in ${configPath(id, env)}`;
11019
+ }
11020
+ function quoteForCmd(arg) {
11021
+ return /[\s"]/.test(arg) ? `"${arg.replace(/"/g, '\\"')}"` : arg;
11022
+ }
11023
+ var realRunner = (bin, args) => {
11024
+ if (platform5() === "win32") execFileSync(quoteForCmd(bin), args.map(quoteForCmd), { stdio: "pipe", shell: true });
11025
+ else execFileSync(bin, args, { stdio: "pipe" });
11026
+ };
11027
+ function writeJsonServer(path, node, mainJs, server) {
11028
+ let config = {};
11029
+ if (existsSync9(path)) config = JSON.parse(readFileSync7(path, "utf-8"));
11030
+ const servers = config.mcpServers && typeof config.mcpServers === "object" ? config.mcpServers : {};
11031
+ servers[server.name] = { command: node, args: [mainJs, "serve"], ...Object.keys(server.env).length ? { env: server.env } : {} };
11032
+ config.mcpServers = servers;
11033
+ mkdirSync8(dirname8(path), { recursive: true });
11034
+ writeFileSync7(path, JSON.stringify(config, null, 2) + "\n", "utf-8");
11035
+ }
11036
+ function connectHarness(id, node, mainJs, env = realEnv(), run5 = realRunner, server = DEFAULT_SERVER) {
11037
+ const existing = registeredServer(id, env, server.name);
11038
+ if (existing && !isStale(existing)) return { id, status: "already" };
11039
+ const manual = manualCommand(id, node, mainJs, env, server);
11040
+ try {
11041
+ const add2 = addCommand(id, node, mainJs, server);
11042
+ if (!add2) {
11043
+ writeJsonServer(configPath(id, env), node, mainJs, server);
11044
+ } else {
11045
+ const remove2 = removeCommand(id, server.name);
11046
+ if (existing && remove2) run5(remove2.bin, remove2.args);
11047
+ run5(add2.bin, add2.args);
11048
+ }
11049
+ } catch (err) {
11050
+ const missing = err.code === "ENOENT";
11051
+ const first = String(err.message).split("\n")[0];
11052
+ return { id, status: "failed", detail: missing ? "its command was not found" : first, manual };
11053
+ }
11054
+ return { id, status: existing ? "replaced" : "connected" };
11055
+ }
11056
+ function parseHarnessFlag(argv) {
11057
+ if (argv.includes("--all")) return HARNESSES.map((h) => h.id);
11058
+ const i = argv.findIndex((a) => a === "--harness" || a.startsWith("--harness="));
11059
+ if (i < 0) return null;
11060
+ const value = argv[i].includes("=") ? argv[i].split("=")[1] : argv[i + 1];
11061
+ const ids = (value ?? "").split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
11062
+ const known = HARNESSES.map((h) => h.id);
11063
+ const bad = ids.filter((s) => !known.includes(s));
11064
+ if (!ids.length || bad.length) {
11065
+ throw new Error(`Unknown harness${bad.length > 1 ? "es" : ""}: ${bad.join(", ") || "(none given)"}. Use one or more of: ${known.join(", ")}, or --all.`);
11066
+ }
11067
+ return [...new Set(ids)];
11068
+ }
11069
+ function skillsHomes(ids) {
11070
+ const chosen = HARNESSES.filter((h) => ids.includes(h.id));
11071
+ return { claude: chosen.some((h) => h.skillsHome === "claude"), agents: chosen.some((h) => h.skillsHome === "agents") };
11072
+ }
11073
+
11049
11074
  // apps/reaper-mcp-server/src/instance-cli.ts
11050
11075
  var ui = createUi();
11051
11076
  function findReaper(os) {
@@ -11067,6 +11092,7 @@ function realInstanceDeps() {
11067
11092
  return r.status === 0;
11068
11093
  },
11069
11094
  findReaper: () => findReaper(os),
11095
+ requestQuit: requestQuitOverHttp,
11070
11096
  runner: (bin, args) => void execFileSync2(bin, args, { stdio: "pipe" }),
11071
11097
  launch: (bin, args, detached) => {
11072
11098
  const child = spawn2(bin, args, { detached, stdio: "ignore" });
@@ -11084,6 +11110,34 @@ function realInstanceDeps() {
11084
11110
  log: (line) => console.log(line)
11085
11111
  };
11086
11112
  }
11113
+ async function requestQuitOverHttp(port) {
11114
+ const base = `http://127.0.0.1:${port}/_/`;
11115
+ let body;
11116
+ try {
11117
+ body = await (await fetch(`${base}GET/EXTSTATE/MCPBridge/status`, { signal: AbortSignal.timeout(3e3) })).text();
11118
+ } catch {
11119
+ return "unreachable";
11120
+ }
11121
+ const prefix = "EXTSTATE MCPBridge status ";
11122
+ const line = body.split(/\r?\n/).find((l) => l.startsWith(prefix));
11123
+ let token;
11124
+ let instance;
11125
+ try {
11126
+ const status = JSON.parse(line.slice(prefix.length).replace(/\\(.)/g, (_, c) => c === "t" ? " " : c === "n" ? "\n" : c));
11127
+ token = status.control?.token;
11128
+ instance = status.instance;
11129
+ } catch {
11130
+ return "no-token";
11131
+ }
11132
+ if (typeof token !== "string" || token === "") return "no-token";
11133
+ if (typeof instance !== "string" || instance === "") return "not-an-instance";
11134
+ try {
11135
+ await fetch(`${base}SET/EXTSTATE/MCPBridge/request/quit-${token}`, { signal: AbortSignal.timeout(3e3) });
11136
+ return "sent";
11137
+ } catch {
11138
+ return "unreachable";
11139
+ }
11140
+ }
11087
11141
  function flagValue(args, flag) {
11088
11142
  const i = args.findIndex((a) => a === flag || a.startsWith(`${flag}=`));
11089
11143
  if (i < 0) return void 0;
@@ -11107,7 +11161,7 @@ async function instanceCommand(args, deps = realInstanceDeps()) {
11107
11161
  case "start":
11108
11162
  return start(rest, deps);
11109
11163
  case "stop":
11110
- return stop(rest, deps);
11164
+ return await stop(rest, deps);
11111
11165
  case "connect":
11112
11166
  return connect(rest, deps);
11113
11167
  case "list":
@@ -11176,19 +11230,30 @@ function start(args, deps) {
11176
11230
  }
11177
11231
  const project = args[1];
11178
11232
  if (project && !existsSync10(project)) throw new Error(`Project not found: ${project}`);
11233
+ writeInstanceConf(info);
11179
11234
  const cmd = launchCommand(info, project ? realpathSync(project) : void 0, deps.os, reaper);
11180
11235
  deps.launch(cmd.bin, cmd.args, cmd.detached);
11181
11236
  deps.log(`${ui.mark("ok")} Starting ${ui.bold(info.name)}${project ? ` with ${project}` : ""}. Its bridge comes up with REAPER: ${ui.link(`http://localhost:${info.port}/mcp_bridge.html`)}`);
11182
11237
  return 0;
11183
11238
  }
11184
- function stop(args, deps) {
11239
+ async function stop(args, deps) {
11185
11240
  const info = need(args[0]);
11186
11241
  if (deps.os === "darwin" && info.bundleId) {
11187
11242
  deps.runner("osascript", ["-e", `tell application id "${info.bundleId}" to quit`]);
11188
11243
  deps.log(`${ui.mark("ok")} Asked ${ui.bold(info.name)} to quit. If it holds unsaved changes it waits for you to answer.`);
11189
11244
  return 0;
11190
11245
  }
11191
- deps.log(`${ui.mark("info")} Quit ${info.name} from its own window (REAPER asks about unsaved changes there).`);
11246
+ if (!bridgeAlive(info.resourcePath)) {
11247
+ deps.log(`${ui.mark("info")} ${info.name} is not running (its bridge does not answer), so there is nothing to quit.`);
11248
+ return 1;
11249
+ }
11250
+ const result = await deps.requestQuit(info.port);
11251
+ if (result !== "sent") {
11252
+ const why = result === "no-token" ? "its bridge is too old to take a quit request: run reaper-mcp setup for it" : result === "not-an-instance" ? `its bridge does not know it is an instance, so it would ignore the request: after quitting it from its own window, reaper-mcp instance start ${info.name} adds the missing name file` : `nothing answers on port ${info.port}`;
11253
+ deps.log(`${ui.mark("fail")} Could not ask ${info.name} to quit (${why}). Quit it from its own window.`);
11254
+ return 1;
11255
+ }
11256
+ deps.log(`${ui.mark("ok")} Asked ${ui.bold(info.name)} to quit. If it holds unsaved changes REAPER asks you what to do with them first.`);
11192
11257
  return 0;
11193
11258
  }
11194
11259
  function connect(args, deps) {
@@ -12608,6 +12673,8 @@ async function doctor() {
12608
12673
  core2.push(
12609
12674
  bridgeRunning ? { label: "Lua bridge", status: "ok", detail: "Connected" } : { label: "Lua bridge", status: "fail", detail: "Not detected", fix: "reaper-mcp setup, then run mcp_bridge.lua in REAPER" }
12610
12675
  );
12676
+ const instancesRow = instancesCheck(instanceLines());
12677
+ if (instancesRow) core2.push(instancesRow);
12611
12678
  const readIfExists = (path) => existsSync15(path) ? readFileSync16(path, "utf-8") : null;
12612
12679
  core2.push(autostartCheck(
12613
12680
  readIfExists(join23(getReaperScriptsPath(), "__startup.lua")),
@@ -12932,6 +12999,7 @@ switch (command) {
12932
12999
  const running = status.state === "connected";
12933
13000
  console.log(`Bridge status: ${running ? ui2.ok("CONNECTED") : ui2.fail(`NOT DETECTED (${status.state})`)}`);
12934
13001
  if (!running) console.log(bridgeDownMessage(status));
13002
+ for (const i of instanceLines()) console.log(` ${ui2.mark(i.running ? "ok" : "info")} ${instanceText(i)}`);
12935
13003
  process.exit(running ? 0 : 1);
12936
13004
  })();
12937
13005
  break;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mthines/reaper-mcp",
3
- "version": "0.104.1",
3
+ "version": "0.106.0",
4
4
  "type": "module",
5
5
  "description": "MCP server for controlling REAPER DAW — real-time mixing, FX control, and frequency analysis for AI agents",
6
6
  "license": "MIT",
@@ -4847,6 +4847,14 @@ local can_restart = type(reaper.set_action_options) == "function" and type(scrip
4847
4847
  -- adds 2 (then start again), so a user re-running mcp_bridge.lua turns it off instead of getting a new window
4848
4848
  if can_restart then reaper.set_action_options(1) end
4849
4849
 
4850
+ -- `reaper-mcp instance create` writes mcp_instance.conf (name=<n>) into a second REAPER's Scripts folder; the main
4851
+ -- REAPER has none. Kept in `ext` because the main chunk is at Lua's 200-locals limit.
4852
+ do
4853
+ local text = read_file(script_dir .. "mcp_instance.conf")
4854
+ local name = text and text:match("name=([%w%-]+)")
4855
+ ext.instance = name ~= "" and name or nil
4856
+ end
4857
+
4850
4858
  local function update_config()
4851
4859
  local text = read_file(script_dir .. "mcp_update.conf")
4852
4860
  if not text then return nil end
@@ -4985,7 +4993,10 @@ local function check_control(now)
4985
4993
  if not installing then start_update(action) end
4986
4994
  elseif sidecar_job.flags[action] then
4987
4995
  if not (update and update.state == "running") then sidecar_job.start(action) end
4988
- elseif action == "restart" and can_restart then restart_bridge() return end
4996
+ elseif action == "restart" and can_restart then restart_bridge() return
4997
+ -- `reaper-mcp instance stop` off macOS: File: Quit REAPER (40004), which asks about unsaved changes itself.
4998
+ -- Only an instance obeys, so a stray request can never close the REAPER a person works in.
4999
+ elseif action == "quit" and ext.instance then log_event("bridge_quit", {}) reaper.Main_OnCommand(40004, 0) return end
4989
5000
  end
4990
5001
  end
4991
5002
  sidecar_job.poll(now)
@@ -5555,6 +5566,7 @@ local function publish_status(now, force)
5555
5566
  reaperVersion = reaper.GetAppVersion(),
5556
5567
  project = select(2, reaper.EnumProjects(-1)) or "",
5557
5568
  bridgeDir = bridge_dir,
5569
+ instance = ext.instance,
5558
5570
  commands = status.commands,
5559
5571
  errors = status.errors,
5560
5572
  deferMs = defer_n > 0 and math.floor(defer_sum / defer_n * 100000 + 0.5) / 100 or 0,