local-mcp 3.0.420 → 3.0.424

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/index.js CHANGED
@@ -4,202 +4,20 @@
4
4
  * index.js — entry point del paquete npm local-mcp.
5
5
  *
6
6
  * Modos:
7
- * npx local-mcp → instala/actualiza runtime; en terminal interactiva muestra
8
- * mensaje de listo y sale (Cursor/Claude lanzan stdio solos)
7
+ * npx local-mcp → arranca el server MCP que trae el paquete (sin descargar nada); en
8
+ * terminal interactiva muestra mensaje de listo y sale
9
9
  * npx local-mcp setup → wizard de configuración de clientes
10
- * npx local-mcp update → fuerza re-descarga del runtime
11
- * npx local-mcp uninstall → elimina cache del runtime
10
+ * npx local-mcp update → dice cómo actualizar (npx -y local-mcp@latest)
11
+ * npx local-mcp uninstall → desinstala
12
12
  * npx local-mcp status → muestra estado del servidor local
13
13
  */
14
14
 
15
- const { spawn, execFileSync, execSync } = require('child_process')
15
+ const { spawn, execSync } = require('child_process')
16
16
  const path = require('path')
17
17
  const os = require('os')
18
18
  const fs = require('fs')
19
- const { https } = require('./user-agent')
20
19
  const evento = require('./launch-event')
21
20
 
22
- // ── Version + liveness helpers (module scope so they are testable) ────────────
23
-
24
- // PIDs of the server processes THIS process spawned. The liveness guard asks about
25
- // OTHER instances; counting our own child made it answer "servers running" forever.
26
- const _spawnedServerPids = []
27
- function spawnedServerPids() { return _spawnedServerPids.slice() }
28
- function noteSpawnedServer(pid) { if (typeof pid === 'number') _spawnedServerPids.push(pid) }
29
-
30
- /** Semver comparison: returns true if version a >= b (e.g. "3.0.72" >= "3.0.70") */
31
- function semverGte(a, b) {
32
- const av = (a || '').split('.').map(Number)
33
- const bv = (b || '').split('.').map(Number)
34
- for (let i = 0; i < 3; i++) {
35
- const ai = av[i] || 0, bi = bv[i] || 0
36
- if (ai > bi) return true
37
- if (ai < bi) return false
38
- }
39
- return true
40
- }
41
-
42
- /**
43
- * Whether the cached binary is fresh enough to exec directly (the fast path).
44
- *
45
- * #1394 §C: the gate used to be `semverGte(cachedVersion, pkg.version)` on every
46
- * platform. On Windows/Linux those two numbers are DIFFERENT SERIES by construction
47
- * — `.server-version` holds the go-server artifact version while pkg.version is the
48
- * npm/Mac release, and download.js documents the divergence it already has to work
49
- * around ("version=3.0.369 next to a 3.0.258 windows artifact"). The comparison is
50
- * therefore false on every machine in the fleet: every single spawn paid a
51
- * /runtime/latest round-trip and exit(1) when offline, holding a perfectly good
52
- * cached binary. And the slow path rewrites `.server-version` with the artifact
53
- * version again, so it can never heal itself.
54
- *
55
- * On darwin the two ARE the same series, so the comparison is meaningful and stays:
56
- * it is what stops a stale npx cache from downgrading a binary the tray already
57
- * upgraded (LMC-375). Off darwin, "there is a cached binary and we know its version"
58
- * is the whole requirement; the 24h background check below handles staleness.
59
- */
60
- function fastPathVersionOK(platform, cachedVersion, pkgVersion) {
61
- if (!cachedVersion) return false // nothing cached → must download
62
- if (platform === 'darwin') return semverGte(cachedVersion, pkgVersion)
63
- return true
64
- }
65
-
66
- /**
67
- * Whether the 24h background check should download a newer binary.
68
- *
69
- * fastPathVersionOK (arriba) declara que en Windows/Linux la version cacheada y
70
- * `info.version` son series distintas por construccion, se niega a compararlas,
71
- * y delega en "the 24h background check below". Ese chequeo hacia exactamente la
72
- * comparacion declarada invalida: `semverGte(cachedVersion, info.version)`, con
73
- * info.version = la release de MAC.
74
- *
75
- * Medido el 2026-08-27: las 21 Windows de la flota corrian 3.0.401 con 3.0.402
76
- * publicado y Mac en 3.0.377. semverGte('3.0.401','3.0.377') es true, asi que
77
- * ninguna se enteraba del update — en silencio. Y cuando la linea de Mac pasa a
78
- * la de Windows, la misma cuenta se da vuelta y actualiza lo que ya esta al dia.
79
- *
80
- * Sin version resoluble para la plataforma NO se actualiza: fail-closed, el
81
- * mismo criterio que download.js ("we FAIL rather than fall back to
82
- * info.version").
83
- */
84
- function backgroundUpdateNeeded(cachedVersion, info, arch) {
85
- if (!cachedVersion) return false
86
- const { latestVersionForPlatform } = require('./download')
87
- const latest = latestVersionForPlatform(info, arch)
88
- if (!latest) return false
89
- return !semverGte(cachedVersion, latest)
90
- }
91
-
92
- /**
93
- * PIDs of the lmcp/local-mcp servers running right now, or null when the answer
94
- * cannot be determined.
95
- *
96
- * #1394 §C: this was `pgrep -fc local-mcp-server`, which returned 0 on every
97
- * Windows/Linux machine for two reasons — Windows has no `pgrep` (the `|| echo 0`
98
- * swallowed it) and off macOS the binary is called `lmcp-server`. So the LMCA-1044
99
- * guard was permanently disabled exactly where the updater renames the file.
100
- *
101
- * The first fix for that inverted the defect, and the review of #1565 caught it:
102
- * counting was correct but the count was never zero, so nothing ever updated again.
103
- * Two independent causes, both handled here:
104
- *
105
- * 1. THIS process has already spawned its own server as a child (launchMcpStdio
106
- * runs ~10s before this timer fires), so the count always included it. We are
107
- * asking about OTHER instances — replacing the binary is what SIGTERMs sibling
108
- * proxies — so known PIDs are excluded by the caller.
109
- *
110
- * 2. `execSync` runs through `/bin/sh -c`, whose own cmdline contains the pattern,
111
- * so `pgrep -f 'lmcp-server'` matched the shell running the pgrep. Verified in
112
- * Docker: it returns 2 with nothing running. The `[l]` bracket makes the regex
113
- * match `lmcp-server` while the literal pattern text in the shell's cmdline
114
- * (with the brackets) does not match itself.
115
- */
116
- function listRunningServerPids(exec, platform = process.platform) {
117
- try {
118
- if (platform === 'win32') {
119
- // tasklist ships on every Windows SKU. CSV so the PID column is unambiguous.
120
- const pids = []
121
- for (const name of ['lmcp-server.exe', 'local-mcp-server.exe']) {
122
- const out = exec(`tasklist /FI "IMAGENAME eq ${name}" /NH /FO CSV`)
123
- if (/INFO:/i.test(out)) continue
124
- for (const line of String(out).split(/\r?\n/)) {
125
- const m = line.match(/^"[^"]+","(\d+)"/)
126
- if (m) pids.push(Number(m[1]))
127
- }
128
- }
129
- return pids
130
- }
131
- // See (2) above for the brackets. One alternation per name: `lmcp-server` is not
132
- // a substring of `local-mcp-server`, so both are needed.
133
- //
134
- // NO `|| true`, and that is the whole point of this branch. execSync throws on any
135
- // non-zero exit, and pgrep overloads the code: 1 means it ran and matched nothing
136
- // — a real answer — while 127 means the shell could not find pgrep at all (a
137
- // container with no procps) and 2/3 are usage/fatal. `|| true` collapsed every one
138
- // of them into empty stdout, so a MISSING pgrep read as "no servers running" and
139
- // the guard authorised the swap with a server live. Measured in Docker without
140
- // procps. Windows already honoured the contract below; the asymmetry was an
141
- // accident of the shell idiom, not a decision.
142
- let out
143
- try {
144
- out = exec(`pgrep -f '[l]mcp-server|[l]ocal-mcp-server'`)
145
- } catch (err) {
146
- if (err && err.status === 1) return [] // ran fine, nothing matched
147
- throw err // could not look → null, via the catch below
148
- }
149
- return String(out).trim().split(/\s+/).filter(Boolean).map(Number).filter(n => !Number.isNaN(n))
150
- } catch {
151
- return null
152
- }
153
- }
154
-
155
- /**
156
- * How many server processes are running OTHER than the ones we already know about.
157
- * Returns -1 when the count CANNOT be determined. Callers must treat that as
158
- * "assume servers are running": a guard that cannot see must not say yes.
159
- */
160
- function countRunningServers(exec, platform = process.platform, excludePids = []) {
161
- const pids = listRunningServerPids(exec, platform)
162
- if (pids === null) return -1
163
- const skip = new Set([process.pid, ...excludePids].filter(p => typeof p === 'number'))
164
- return pids.filter(p => !skip.has(p)).length
165
- }
166
-
167
- /** True when it is safe to replace the cached binary on disk. */
168
- function safeToReplaceBinary(exec, platform = process.platform, excludePids = []) {
169
- return countRunningServers(exec, platform, excludePids) === 0
170
- }
171
-
172
- /**
173
- * Replace the cached server binary with `srcPath`, refusing while any server is
174
- * running (LMCA-1044: swapping it mid-session changes its mtime and used to get
175
- * sibling stdio proxies SIGTERM'd → Cursor transport_closed).
176
- *
177
- * The check lives INSIDE this function on purpose. It used to sit at the call site,
178
- * and a mutation run showed the consequence: deleting it there passed every test,
179
- * because the only caller is a closure inside main()'s background update timer that
180
- * no unit test can reach. Callers can no longer forget a guard they cannot see.
181
- *
182
- * Returns 'replaced' | 'servers-running' | 'failed'.
183
- */
184
- function replaceCachedBinary(deps, srcPath, destPath, version, versionFilePath) {
185
- const { exec, fs, execFileSync, platform = process.platform, excludePids = [] } = deps
186
- if (!safeToReplaceBinary(exec, platform, excludePids)) return 'servers-running'
187
- try {
188
- const tmpPath = destPath + '.tmp'
189
- fs.copyFileSync(srcPath, tmpPath)
190
- fs.chmodSync(tmpPath, 0o755)
191
- if (platform === 'darwin') {
192
- try { execFileSync('codesign', ['--force', '--sign', '-', '--identifier', 'com.local-mcp.server', tmpPath], { stdio: 'pipe' }) } catch {}
193
- }
194
- fs.renameSync(tmpPath, destPath)
195
- fs.writeFileSync(versionFilePath, version)
196
- return 'replaced'
197
- } catch {
198
- return 'failed'
199
- }
200
- }
201
-
202
-
203
21
  // ── Uninstall sentinels ───────────────────────────────────────────────────────
204
22
  // A `.uninstalled` sentinel marks a machine the user removed, so no respawn (an
205
23
  // AI client that still has `local-mcp` in its config re-spawning `npx local-mcp`)
@@ -252,6 +70,29 @@ function marcarAvisoDesinstalado() {
252
70
  try { fs.writeFileSync(avisoDesinstaladoPath(), String(Date.now())) } catch {}
253
71
  }
254
72
 
73
+ // Whether the LMCP menu-bar app is on this machine. The server path never installs it; when
74
+ // it is missing the wrapper says so in one stderr line. Mac: the tray bundle in ~/Applications
75
+ // or /Applications. Windows: lmcp-tray.exe, which LMCP-Setup.exe puts next to the server in the
76
+ // cache dir (lmcp-win cmd/lmcp-server/tray_windows.go). On Windows `setup` installs no tray
77
+ // (ensureTray is a no-op there), so the line names only the installer.
78
+ function menuBarAppHowToInstall(platform = process.platform) {
79
+ return platform === 'darwin'
80
+ ? 'npx local-mcp setup, or the installer from https://local-mcp.com'
81
+ : 'the installer from https://local-mcp.com'
82
+ }
83
+ function menuBarAppMissingLine(platform = process.platform) {
84
+ return `[LMCP] The LMCP menu-bar app is not installed; running the MCP server only. To install it: ${menuBarAppHowToInstall(platform)}`
85
+ }
86
+ function menuBarAppInstalled(platform = process.platform) {
87
+ const exists = (p) => { try { return fs.existsSync(p) } catch { return false } }
88
+ if (platform === 'darwin') {
89
+ const { _isUsableTrayBundle, trayAppPaths } = require('./download')
90
+ return trayAppPaths().some(_isUsableTrayBundle)
91
+ }
92
+ if (platform === 'win32') return exists(path.join(require('./download').CACHE_DIR, 'lmcp-tray.exe'))
93
+ return false
94
+ }
95
+
255
96
  const cmd = process.argv[2]
256
97
 
257
98
  // Comandos que este wrapper entiende. Sin argumentos arranca el server MCP por stdio, que es
@@ -268,11 +109,22 @@ function reportarLanzamiento(outcome, opciones) {
268
109
  if (ES_LANZAMIENTO) evento.reportar(outcome, evento.claseDeArgumento(cmd), opciones)
269
110
  }
270
111
  // Antes que nada: un `spawned` que en Windows esperaba su id sale ahora, por el proceso suelto (#21).
271
- if (ES_LANZAMIENTO) process.on('exit', () => { evento.soltarPendiente(); reportarLanzamiento('other') })
112
+ // La red dice además por qué (#82), como clase: una excepción que nadie atrapó, o no se sabe.
113
+ let razonDeSalida = 'unknown'
114
+ if (ES_LANZAMIENTO) {
115
+ process.on('uncaughtExceptionMonitor', () => { razonDeSalida = 'uncaught-exception' })
116
+ process.on('exit', () => { evento.soltarPendiente(); reportarLanzamiento('other', { reason: razonDeSalida }) })
117
+ }
118
+ // #82: un server que sale con error dentro de esta ventana no arrancó. El `spawned` espera a que
119
+ // pase; el server y el cliente no esperan nada: sólo se demora el evento.
120
+ const VENTANA_ARRANQUE_MS = 2000
272
121
 
273
- // Platform support: macOS (Swift tray + embedded server) and Windows (go-server standalone
274
- // binary downloaded from R2). Linux passes this guard so that `--help`, `status`, `update` and
122
+ // Platform support: macOS (Swift server) and Windows (go-server), each shipped in its own npm
123
+ // platform package (npm/bundled.js). Linux passes this guard so that `--help`, `status`, `update` and
275
124
  // `uninstall` answer, but it is NOT supported: the server path and `setup` say so (#9).
125
+ // Since local-mcp-releases#61 row 5 npm refuses the install on Linux (`os` in package.json), so
126
+ // this branch is no longer reached through `npm install`/`npx`. It stays for whoever gets past
127
+ // that: `node index.js` on a checkout, `npm install --force`, or a tool that ignores `os`.
276
128
  const SUPPORTED_PLATFORMS = ['darwin', 'win32', 'linux']
277
129
  if (!SUPPORTED_PLATFORMS.includes(process.platform)) {
278
130
  console.error(`LMCP supports macOS and Windows. Your platform (${process.platform}) is not supported yet — see https://local-mcp.com`)
@@ -307,10 +159,7 @@ if (parseInt(process.version.slice(1)) < 16) {
307
159
  function detectManualUninstall() {
308
160
  if (process.platform !== 'darwin') return false
309
161
  const home = os.homedir()
310
- const appPresent =
311
- fs.existsSync(path.join(home, 'Applications', 'LocalMCPTray.app')) ||
312
- fs.existsSync('/Applications/LocalMCPTray.app')
313
- if (appPresent) return false
162
+ if (require('./download').trayAppPaths().length) return false // LocalMCPTray.app or LMCP.app (tray id)
314
163
  return (
315
164
  fs.existsSync(path.join(home, 'Library', 'LaunchAgents', 'com.local-mcp.tray.plist')) ||
316
165
  fs.existsSync(path.join(home, '.local', 'share', 'local-mcp', 'tray', '.version'))
@@ -331,7 +180,7 @@ Uso:
331
180
  local-mcp stdio lo mismo, dicho explícitamente
332
181
  local-mcp setup instala y configura
333
182
  local-mcp status muestra el estado
334
- local-mcp update limpia el cache del runtime
183
+ local-mcp update cómo actualizar (npx -y local-mcp@latest)
335
184
  local-mcp uninstall desinstala
336
185
 
337
186
  local-mcp --help esta ayuda`)
@@ -344,7 +193,15 @@ async function main() {
344
193
  // sólo buscaba ayuda de CLI. Un comando de consulta no instala software.
345
194
  //
346
195
  // Sin argumentos sigue arrancando el server, que es como lo invocan los clientes de IA.
347
- if (cmd !== undefined && !COMANDOS.includes(cmd) && !SINONIMOS_DEL_SERVER.includes(cmd)) {
196
+ //
197
+ // #88: un cliente de IA (stdin sin TTY) que manda un argumento desconocido quiere el server, y
198
+ // con exit 2 reintentaba en bucle. Ahí se ignora el argumento (una línea por stderr, nunca
199
+ // stdout: es JSON-RPC) y se sigue por el camino del server, que reporta `spawned` con la clase.
200
+ // En una terminal (TTY) y ante un pedido de ayuda sigue la ayuda: una consulta no descarga ni instala.
201
+ const desconocido = cmd !== undefined && !COMANDOS.includes(cmd) && !SINONIMOS_DEL_SERVER.includes(cmd)
202
+ if (desconocido && !PEDIDOS_DE_AYUDA.includes(cmd) && !(process.stdin && process.stdin.isTTY)) {
203
+ process.stderr.write(`[LMCP] ignoring unknown argument ${JSON.stringify(String(cmd).slice(0, 40))}; starting the MCP server\n`)
204
+ } else if (desconocido) {
348
205
  const pedidoDeAyuda = PEDIDOS_DE_AYUDA.includes(cmd)
349
206
  mostrarAyuda()
350
207
  if (!pedidoDeAyuda) {
@@ -363,15 +220,11 @@ async function main() {
363
220
  process.exit(process.platform === 'linux' ? 1 : 0)
364
221
  }
365
222
 
223
+ // 3.0.423: el server viene dentro del paquete; no hay runtime en cache que borrar (ese directorio
224
+ // guarda el id de la máquina y el token del relay, que no son del server de npm).
366
225
  if (cmd === 'update') {
367
- const { CACHE_DIR } = require('./download')
368
- const fs = require('fs')
369
- if (fs.existsSync(CACHE_DIR)) {
370
- fs.rmSync(CACHE_DIR, { recursive: true, force: true })
371
- console.log('Cache del runtime eliminado.')
372
- }
373
- // Re-descargar en el próximo arranque
374
- console.log('Ejecutá "npx local-mcp" nuevamente para descargar la última versión.')
226
+ console.log('El server de LMCP viene con el paquete de npm. Para la última versión: npx -y local-mcp@latest')
227
+ console.log('Con la app de LMCP instalada, la app se actualiza sola.')
375
228
  return
376
229
  }
377
230
 
@@ -481,22 +334,16 @@ async function main() {
481
334
  // ── Honor a MANUAL uninstall (.app trashed, no sentinel written) ────────────
482
335
  // Same intent as the sentinel check above, for the common case where the user removes the
483
336
  // app via the Trash instead of the uninstaller. Adopt it as an uninstall: write the
484
- // sentinel (so future respawns short-circuit at the check above), remove the orphaned tray
485
- // LaunchAgent (so launchd stops trying to relaunch a deleted app), and refuse to start —
486
- // NOT ensureTray(), which would re-download and resurrect a machine the user removed
487
- // (FB-A30CDC). The AI client's stale MCP config entry is left alone; it just respawns us
488
- // and we short-circuit here, which is harmless.
337
+ // sentinel (so future respawns short-circuit at the check above) and refuse to start (FB-A30CDC).
338
+ // The orphaned tray LaunchAgent is NOT touched here (3.0.423): the server path writes nothing
339
+ // outside LMCP's own folders; `uninstall` removes it and `setup` rewrites it. The AI client's
340
+ // stale MCP config entry is left alone; it just respawns us and we short-circuit here.
489
341
  {
490
342
  if (detectManualUninstall()) {
491
343
  reportarLanzamiento('uninstalled')
492
344
  writeUninstallSentinels()
493
- const trayPlist = path.join(os.homedir(), 'Library', 'LaunchAgents', 'com.local-mcp.tray.plist')
494
- if (fs.existsSync(trayPlist)) {
495
- try { execSync(`launchctl unload -w "${trayPlist}" 2>/dev/null`, { stdio: 'pipe' }) } catch {}
496
- try { fs.unlinkSync(trayPlist) } catch {}
497
- }
498
345
  process.stderr.write(
499
- '[LMCP] LocalMCPTray.app was removed — treating it as an uninstall, not starting.\n' +
346
+ '[LMCP] LMCP.app was removed — treating it as an uninstall, not starting.\n' +
500
347
  ' Reinstall: npx local-mcp setup\n'
501
348
  )
502
349
  process.exit(0)
@@ -504,89 +351,64 @@ async function main() {
504
351
  }
505
352
 
506
353
  // ── Linux no está soportado (#9) ────────────────────────────────────────────
507
- // Se dice acá, antes de cualquier descarga: sin esto el wrapper pedía un binario que no se
508
- // publica y terminaba en un 404. Va después de los chequeos de desinstalación, que no bajan nada.
354
+ // Se dice acá, antes de buscar el server: no hay paquete de plataforma para Linux. Va después de
355
+ // los chequeos de desinstalación.
509
356
  if (process.platform === 'linux') {
357
+ evento.fuente('missing_platform')
510
358
  process.stderr.write(require('./download').LINUX_NO_SOPORTADO + '\n')
511
359
  reportarLanzamiento('unsupported-platform')
512
360
  process.exit(1)
513
361
  }
514
362
 
515
363
  // ── Modo default: stdio MCP server ──────────────────────────────────────────
516
- const { CACHE_DIR } = require('./download')
517
- // macOS ships the Swift `local-mcp-server` (standalone fallback to the embedded
518
- // tray server); Windows/Linux ship the go-server `lmcp-server` binary that
519
- // download.js writes to CACHE_DIR. Keep this name in sync with download.js.
520
- const binName = process.platform === 'darwin'
521
- ? 'local-mcp-server'
522
- : (process.platform === 'win32' ? 'lmcp-server.exe' : 'lmcp-server')
523
- const stableBin = path.join(CACHE_DIR, binName)
524
- const versionFile = path.join(CACHE_DIR, '.server-version')
525
- // On Windows/Linux the file download.js and the go-server updater keep current is
526
- // `.go-server-version`; `.server-version` is only written by this script's slow
527
- // path. Read both, newest-wins, so the fast path sees what the updater actually
528
- // installed instead of a value only it ever writes (#1394 §C).
529
- const goVersionFileRead = path.join(CACHE_DIR, '.go-server-version')
530
- function readCachedVersion() {
531
- const read = (p) => { try { return fs.readFileSync(p, 'utf8').trim() } catch { return '' } }
532
- const own = read(versionFile)
533
- if (process.platform === 'darwin') return own
534
- const plat = read(goVersionFileRead)
535
- if (!own) return plat
536
- if (!plat) return own
537
- return semverGte(plat, own) ? plat : own
538
- }
364
+ // 3.0.423 (Darío, 2026-10-22, «A»): this path downloads NOTHING and writes nothing outside
365
+ // LMCP's own folder. The server is the native binary npm installed next to this file (the
366
+ // platform package, npm/bundled.js), run in place: no runtime download, no quarantine removal,
367
+ // no ad-hoc re-signing, no 24h self-update. Updates arrive with `npx -y local-mcp@latest`.
368
+ // The one exception is the Mac menu-bar app the person installed: its embedded, notarized
369
+ // server is preferred (ADR-0004) and the app keeps updating it.
539
370
  const pkg = require('./package.json')
540
371
 
541
372
  /** MCP hosts (Cursor, Claude) spawn us without a TTY — keep stdio bridge alive. */
542
373
  const isMcpClientSpawn = !(process.stdin && process.stdin.isTTY)
543
374
 
544
375
  function printInstallComplete(version) {
376
+ const app = menuBarAppInstalled()
545
377
  process.stderr.write('\n')
546
- process.stderr.write(`✓ Local MCP v${version} — installation complete.\n\n`)
547
- process.stderr.write(' • Menu bar: open LocalMCPTray from Applications (look for the LMCP icon).\n')
378
+ process.stderr.write(app
379
+ ? `✓ Local MCP v${version} — installation complete.\n\n`
380
+ : `✓ Local MCP v${version} — only the MCP server is set up; the menu-bar app is not installed.\n\n`)
548
381
  process.stderr.write(' • Cursor / Claude: enable the "local-mcp" MCP server in settings (they start it automatically).\n')
382
+ if (!app) process.stderr.write(` • Menu-bar app: install it with ${menuBarAppHowToInstall()}\n`)
549
383
  process.stderr.write(' • You can close this terminal — do not leave `npx local-mcp` running here.\n')
550
- process.stderr.write(' • Status: http://localhost:8765/status\n\n')
384
+ if (app) process.stderr.write(' • Status: http://localhost:8765/status\n')
385
+ process.stderr.write('\n')
551
386
  }
552
387
 
553
- async function ensureDarwinComponents() {
554
- if (process.platform !== 'darwin') return
555
- const { ensureTray, ensureTeamsProxy } = require('./download')
556
- await Promise.all([
557
- ensureTray().catch((e) => { process.stderr.write(`[LMCP] Tray install failed: ${e.message}\n`) }),
558
- ensureTeamsProxy().catch((e) => { process.stderr.write(`[LMCP] teams-proxy install failed: ${e.message}\n`) }),
559
- ])
560
- }
388
+ // Darío, 2026-10-21 (opción «a»): el camino del server arranca SÓLO el server MCP. La app de la
389
+ // barra de menú, su LaunchAgent, los proxies y el token del relay se instalan sólo cuando la
390
+ // persona lo pide: `npx local-mcp setup`, `npm install -g` (postinstall) o los instaladores.
391
+ // cursor.directory ocultó el plugin y el directorio de Anthropic lo retuvo porque este camino
392
+ // instalaba un LaunchAgent persistente sin consentimiento. Sin la app se avisa en una línea.
393
+ if (!menuBarAppInstalled()) process.stderr.write(menuBarAppMissingLine() + '\n')
561
394
 
562
- // ADR-0004 phase 1: the notarized server embedded in LocalMCPTray.app, if present.
563
- // Preferring it over the downloaded standalone binary (which gets re-signed
564
- // ad-hoc on install) keeps Automation TCC cert-based — so Mail/Notes/Messages/
565
- // Safari permissions survive client updates instead of resetting every time.
395
+ // ADR-0004: the notarized server embedded in LocalMCPTray.app, if present. Unchanged by 3.0.423.
566
396
  function findEmbeddedServer() {
567
397
  if (process.platform !== 'darwin') return null
568
- const candidates = [
569
- path.join(os.homedir(), 'Applications', 'LocalMCPTray.app', 'Contents', 'MacOS', 'local-mcp-server'),
570
- path.join('/Applications', 'LocalMCPTray.app', 'Contents', 'MacOS', 'local-mcp-server'),
571
- ]
398
+ const candidates = require('./download').trayAppPaths().map((app) => path.join(app, 'Contents', 'MacOS', 'local-mcp-server'))
572
399
  for (const p of candidates) {
573
400
  try { if (fs.existsSync(p) && fs.statSync(p).isFile()) return p } catch {}
574
401
  }
575
402
  return null
576
403
  }
577
404
 
578
- function launchMcpStdio(binaryPath, version) {
579
- // Prefer the embedded, notarized server when the .app provides it (ADR-0004).
580
- const embedded = findEmbeddedServer()
581
- if (embedded) binaryPath = embedded
405
+ // bundled: the binary belongs to npm, so npm updates it. The server's own updater stays off
406
+ // (it would download a newer server, the proxies and, on a Mac, LocalMCPTray.app into the user's
407
+ // folders: lmcp-mac UpdateManager.swift, lmcp-win internal/heartbeat/updater.go). A value the
408
+ // person already set is respected. The app's embedded server keeps its updater: the app owns it.
409
+ function launchMcpStdio(binaryPath, version, bundled) {
582
410
  if (!isMcpClientSpawn) {
583
411
  printInstallComplete(version)
584
- if (process.platform === 'darwin') {
585
- const home = os.homedir()
586
- const tray = path.join(home, 'Applications', 'LocalMCPTray.app')
587
- const trayPath = fs.existsSync(tray) ? tray : '/Applications/LocalMCPTray.app'
588
- try { execFileSync('open', ['-a', trayPath], { stdio: 'ignore' }) } catch {}
589
- }
590
412
  process.exit(0)
591
413
  return
592
414
  }
@@ -597,195 +419,72 @@ async function main() {
597
419
  // same root cause as the .mcpb stdio→--auto fix.
598
420
  const spawnArgs = process.platform === 'darwin' ? ['--auto'] : []
599
421
  // Pass the npm PACKAGE version to the server so the heartbeat reports which index.js actually
600
- // ran (vs the server binary version). A resurrection loop is often a STALE cached npx package
601
- // (pre-guard) — this lets us tell that apart from a guard that's failing on the current package.
602
- let _pkgVer = ''
603
- try { _pkgVer = require('./package.json').version || '' } catch {}
604
- const child = spawn(binaryPath, spawnArgs, { stdio: 'inherit', env: { ...process.env, LMCP_NPM_VERSION: _pkgVer } })
605
- noteSpawnedServer(child.pid)
606
- // El server ya arrancó y este proceso queda vivo toda la sesión: el evento sale desde acá.
607
- child.on('spawn', () => reportarLanzamiento('spawned', { enProceso: true }))
422
+ // ran (vs the server binary version).
423
+ const env = { ...process.env, LMCP_NPM_VERSION: pkg.version || '' }
424
+ if (bundled && env.LMCP_DISABLE_UPDATER === undefined) env.LMCP_DISABLE_UPDATER = '1'
425
+ const child = spawn(binaryPath, spawnArgs, { stdio: 'inherit', env })
426
+ // El server arrancó y sigue vivo pasada la ventana: este proceso queda toda la sesión y el
427
+ // evento sale desde acá.
428
+ let arranque = null
429
+ child.on('spawn', () => {
430
+ arranque = setTimeout(() => { arranque = null; reportarLanzamiento('spawned', { enProceso: true }) }, VENTANA_ARRANQUE_MS)
431
+ arranque.unref() // el evento nunca retiene al proceso ni demora una salida
432
+ })
608
433
  child.on('error', (err) => {
609
- reportarLanzamiento('spawn-failed')
434
+ reportarLanzamiento('spawn-failed', { reason: evento.razonDeError(err) })
610
435
  process.stderr.write(`Error ejecutando LMCP: ${err.message}\n`)
611
436
  process.exit(1)
612
437
  })
613
- child.on('exit', (code) => process.exit(code ?? 0))
614
- }
615
-
616
- // On Windows: apply pending update before launching (same as Mac's UpdateManager)
617
- // The Go server downloads new versions in background and stages them as .pending.
618
- // On next Claude Desktop restart, we swap them in here.
619
- if (process.platform === 'win32') {
620
- const goVersionFile = path.join(CACHE_DIR, '.go-server-version')
621
- const pendingBin = stableBin + '.pending'
622
- const pendingVersion = path.join(CACHE_DIR, '.pending-version')
623
- if (fs.existsSync(pendingBin)) {
624
- try {
625
- const oldBin = stableBin + '.old'
626
- try { fs.unlinkSync(oldBin) } catch {}
627
- try { fs.renameSync(stableBin, oldBin) } catch {}
628
- fs.renameSync(pendingBin, stableBin)
629
- if (fs.existsSync(pendingVersion)) {
630
- const newVer = fs.readFileSync(pendingVersion, 'utf8').trim()
631
- fs.writeFileSync(goVersionFile, newVer)
632
- fs.unlinkSync(pendingVersion)
633
- }
634
- try { fs.unlinkSync(oldBin) } catch {}
635
- try { fs.unlinkSync(path.join(CACHE_DIR, '.latest-version')) } catch {}
636
- process.stderr.write(`LMCP updated to v${fs.readFileSync(goVersionFile, 'utf8').trim()}\n`)
637
- } catch (e) {
638
- process.stderr.write(`Update apply failed: ${e.message}\n`)
438
+ child.on('exit', (code, signal) => {
439
+ // Dentro de la ventana (#82): salió con error = no arrancó (`spawn-failed`), nunca `spawned`.
440
+ // El código de salida pasa al cliente igual que siempre.
441
+ if (arranque) {
442
+ clearTimeout(arranque)
443
+ if (code === 0) reportarLanzamiento('spawned')
444
+ else reportarLanzamiento('spawn-failed', { reason: signal ? 'signal' : 'early-exit' })
639
445
  }
640
- }
641
- }
642
-
643
- // ADR-0004 phase 3 (darwin): prefer the notarized server embedded in
644
- // LocalMCPTray.app. Ensure the .app is installed, then launch its embedded
645
- // server directly — skipping the standalone download + ad-hoc re-sign that
646
- // resets Automation TCC (Mail/Notes/Messages/Safari) on every update. Only
647
- // if the .app can't be provided do we fall through to the legacy standalone
648
- // binary (which still ad-hoc signs as a last resort so the user isn't stranded).
649
- if (process.platform === 'darwin') {
650
- await ensureDarwinComponents()
651
- const embedded = findEmbeddedServer()
652
- if (embedded) {
653
- let v = pkg.version
654
- try {
655
- v = fs.readFileSync(
656
- path.join(os.homedir(), '.local', 'share', 'local-mcp', 'tray', '.version'),
657
- 'utf8'
658
- ).trim() || pkg.version
659
- } catch {}
660
- launchMcpStdio(embedded, v)
661
- return
662
- }
446
+ process.exit(code ?? 0)
447
+ })
663
448
  }
664
449
 
665
- // Fast path: if stable binary exists AND its version is >= our npm package version, exec directly.
666
- // Using >= (not ===) prevents Claude Desktop from downgrading a binary that the tray's
667
- // UpdateManager has already upgraded. LMC-375: machine 5F8445AE downgraded 3.0.72→3.0.70
668
- // because stale npx cache had old pkg.version and triggered the slow path unnecessarily.
669
- try {
670
- const stat = fs.lstatSync(stableBin)
671
- // Windows .exe files carry no Unix exec bit — Node's fs reports mode 0o666 —
672
- // so the `& 0o111` gate is always false there, which forced EVERY spawn onto
673
- // the slow path (a /runtime/latest network round-trip before launch, and a
674
- // hard failure when offline despite a valid cached binary). Only require the
675
- // exec bit off-Windows, where it's meaningful.
676
- if (stat.isFile() && (process.platform === 'win32' || (stat.mode & 0o111))) {
677
- const cachedVersion = readCachedVersion()
678
- if (fastPathVersionOK(process.platform, cachedVersion, pkg.version)) {
679
- // Cached binary is same or newer — use fast path, no download needed
680
- await ensureDarwinComponents()
681
- launchMcpStdio(stableBin, cachedVersion || pkg.version)
682
-
683
- // Background update check — fires 10s after startup, at most once per 24h.
684
- // Covers machines where the tray is dead and Sparkle can't update the binary.
685
- const lastCheckFile = path.join(CACHE_DIR, '.last-update-check')
686
- function _needsUpdateCheck() {
687
- try { return Date.now() - parseInt(fs.readFileSync(lastCheckFile, 'utf8').trim(), 10) > 86400000 } catch { return true }
688
- }
689
- if (_needsUpdateCheck()) {
690
- try { fs.writeFileSync(lastCheckFile, String(Date.now())) } catch {}
691
- const _cachedVersion = cachedVersion // capture for closure
692
- setTimeout(() => {
693
- const req = https.get('https://office-mcp-production.up.railway.app/runtime/latest', { timeout: 8000 }, (res) => {
694
- let buf = ''
695
- res.on('data', c => buf += c)
696
- res.on('end', () => {
697
- try {
698
- const info = JSON.parse(buf)
699
- const { latestVersionForPlatform, getArch } = require('./download')
700
- const _arch = getArch()
701
- // El nombre que se escribe en .server-version si hay que bajar:
702
- // el de ESTA plataforma, no el de la release de Mac.
703
- const latestVersion = latestVersionForPlatform(info, _arch)
704
- if (backgroundUpdateNeeded(_cachedVersion, info, _arch)) {
705
- // New version available — download for next restart only while no server is running.
706
- // Replacing stableBin mid-session changes its mtime and used to cause sibling
707
- // stdio proxies to be SIGTERM'd → Cursor transport_closed (LMCA-1044).
708
- const _exec = (cmd) => execSync(cmd, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] })
709
- // Our OWN server child does not count: launchMcpStdio spawned it
710
- // ~10s ago and it is the session this update is for. Counting it
711
- // made the guard permanently false and stopped every update.
712
- const _deps = { exec: _exec, fs, execFileSync, excludePids: spawnedServerPids() }
713
- // Cheap pre-check so we do not download for nothing; the binding
714
- // guard is the one inside replaceCachedBinary, re-checked after
715
- // the download (a server can start while it runs).
716
- if (!safeToReplaceBinary(_exec, process.platform, spawnedServerPids())) return
717
-
718
- const { ensureRuntime } = require('./download')
719
- ensureRuntime().then(({ binPath, version: downloadedVersion }) => {
720
- replaceCachedBinary(_deps, binPath, stableBin, downloadedVersion || latestVersion, versionFile)
721
- }).catch(() => {})
722
- }
723
- } catch {}
724
- })
725
- })
726
- req.on('error', () => {})
727
- req.on('timeout', () => { try { req.destroy() } catch {} })
728
- }, 10000)
729
- }
730
-
731
- return
732
- }
733
- // Cached binary is older than our npm package — download/update
734
- process.stderr.write(`Updating LMCP server (${cachedVersion || '?'} → ${pkg.version})...\n`)
735
- } else {
736
- // No cached binary version → first run via default mode
737
- }
738
- if (stat.isSymbolicLink()) fs.unlinkSync(stableBin)
739
- } catch {
740
- // stat failed — binary missing, fall through to download
450
+ const embedded = findEmbeddedServer()
451
+ if (embedded) {
452
+ let v = pkg.version
453
+ try {
454
+ v = fs.readFileSync(
455
+ path.join(os.homedir(), '.local', 'share', 'local-mcp', 'tray', '.version'),
456
+ 'utf8'
457
+ ).trim() || pkg.version
458
+ } catch {}
459
+ evento.fuente('app_embedded')
460
+ launchMcpStdio(embedded, v, false)
461
+ return
741
462
  }
742
463
 
743
- // Slow path: download/repair binary
744
- const { ensureRuntime } = require('./download')
745
-
746
- let runtime
747
- try {
748
- runtime = await ensureRuntime()
749
- } catch (err) {
750
- reportarLanzamiento('download-failed')
751
- process.stderr.write(`\nError al preparar el runtime de LMCP:\n${err.message}\n`)
752
- process.stderr.write(`Intentá reinstalar: npx local-mcp update\n\n`)
464
+ const bundled = require('./bundled').bundledServerPath()
465
+ evento.fuente(bundled && fs.existsSync(bundled) ? 'bundled' : 'missing_platform')
466
+ if (!bundled || !fs.existsSync(bundled)) {
467
+ reportarLanzamiento('spawn-failed', { reason: 'binary-missing' })
468
+ const { TARGETS } = require('./bundled')
469
+ process.stderr.write(TARGETS[`${process.platform}-${process.arch}`]
470
+ ? `[LMCP] The LMCP server for ${process.platform}-${process.arch} is not installed with this package.\n` +
471
+ ' npm skipped its platform package (an install with --omit=optional, or a mirror without it).\n' +
472
+ ' Run: npx -y --include=optional local-mcp@latest\n'
473
+ : `[LMCP] LMCP has no server for ${process.platform}-${process.arch}. It runs on 64-bit macOS and Windows (x64 or arm64) — https://local-mcp.com\n`
474
+ )
753
475
  process.exit(1)
754
476
  }
755
-
756
- const { binPath, version: downloadedVersion } = runtime
757
-
758
- // Copy binary to stable path (survives version cleanup)
759
- try {
760
- const tmpPath = stableBin + '.tmp'
761
- fs.copyFileSync(binPath, tmpPath)
762
- fs.chmodSync(tmpPath, 0o755)
763
- if (process.platform === 'darwin') { try { execFileSync('codesign', ['--force', '--sign', '-', '--identifier', 'com.local-mcp.server', tmpPath], { stdio: 'pipe' }) } catch {} }
764
- fs.renameSync(tmpPath, stableBin)
765
- // Write the ACTUAL downloaded binary version (not pkg.version) so the fast path
766
- // knows what version is on disk. Using pkg.version here caused LMC-375: machines
767
- // with old npm caches wrote an old version into .server-version even though
768
- // ensureBinary() downloaded a newer binary, causing HeartbeatManager to report
769
- // the stale version and triggering spurious downgrade events.
770
- fs.writeFileSync(versionFile, downloadedVersion || pkg.version)
771
- // Also copy settings.html
772
- const settingsSrc = path.join(path.dirname(binPath), 'settings.html')
773
- const settingsDst = path.join(CACHE_DIR, 'settings.html')
774
- if (fs.existsSync(settingsSrc)) fs.copyFileSync(settingsSrc, settingsDst)
775
- } catch {}
776
-
777
- await ensureDarwinComponents()
778
- launchMcpStdio(stableBin, downloadedVersion || pkg.version)
477
+ // The platform package carries the version of the binary inside it (the release it came from).
478
+ let binVersion = pkg.version
479
+ try { binVersion = fs.readFileSync(path.join(path.dirname(bundled), 'VERSION'), 'utf8').trim() || pkg.version } catch {}
480
+ launchMcpStdio(bundled, binVersion, true)
779
481
  }
780
482
 
781
- // Only auto-run as a program. Being requirable is what lets the version/liveness
782
- // helpers above be unit-tested at all — they guard a binary swap and a network
783
- // round-trip that no static check can see.
483
+ // Only auto-run as a program.
784
484
  if (require.main === module) {
785
485
  main().catch(err => {
486
+ razonDeSalida = 'uncaught-exception'
786
487
  process.stderr.write(`Error fatal: ${err.message}\n`)
787
488
  process.exit(1)
788
489
  })
789
490
  }
790
-
791
- module.exports = { semverGte, fastPathVersionOK, backgroundUpdateNeeded, listRunningServerPids, countRunningServers, safeToReplaceBinary, replaceCachedBinary }