local-mcp 3.0.421 → 3.0.425

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)
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
12
- * npx local-mcp status → muestra estado del servidor local
7
+ * npx -y local-mcp@latest → arranca el server MCP que trae el paquete (sin descargar nada); en
8
+ * terminal interactiva muestra mensaje de listo y sale
9
+ * npx -y local-mcp@latest setup → wizard de configuración de clientes
10
+ * npx -y local-mcp@latest update → dice cómo actualizar (npx -y local-mcp@latest)
11
+ * npx -y local-mcp@latest uninstall → desinstala
12
+ * npx -y local-mcp@latest 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,55 @@ function marcarAvisoDesinstalado() {
252
70
  try { fs.writeFileSync(avisoDesinstaladoPath(), String(Date.now())) } catch {}
253
71
  }
254
72
 
73
+ // #48 (Darío, 2026-10-17, opción A): in the «uninstalled» state the wrapper does NOT exit 0 (the AI
74
+ // client would relaunch it in a loop). It stays alive on stdio and answers initialize and every tool
75
+ // with a clear error, until the client closes stdin. Newline-delimited JSON-RPC, no dependencies.
76
+ const MENSAJE_DESINSTALADO = 'LMCP was uninstalled; remove it from this AI client'
77
+ function quedarseVivoDesinstalado() {
78
+ evento.silenciar()
79
+ if (process.stdin.isTTY) process.exit(0)
80
+ const out = (id, extra) => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, ...extra }) + '\n')
81
+ let buf = ''
82
+ process.stdin.setEncoding('utf8')
83
+ process.stdin.on('data', (d) => {
84
+ buf += d
85
+ let i
86
+ while ((i = buf.indexOf('\n')) >= 0) {
87
+ const linea = buf.slice(0, i).trim(); buf = buf.slice(i + 1)
88
+ let m; try { m = JSON.parse(linea) } catch { continue }
89
+ if (!m || m.id === undefined || typeof m.method !== 'string') continue // notifications and replies
90
+ if (m.method === 'initialize') {
91
+ out(m.id, { result: { protocolVersion: (m.params && m.params.protocolVersion) || '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'local-mcp', version: require('./package.json').version }, instructions: MENSAJE_DESINSTALADO } })
92
+ } else if (m.method === 'tools/list') out(m.id, { result: { tools: [] } })
93
+ else if (m.method === 'tools/call') out(m.id, { result: { isError: true, content: [{ type: 'text', text: MENSAJE_DESINSTALADO }] } })
94
+ else if (m.method === 'ping') out(m.id, { result: {} })
95
+ else out(m.id, { error: { code: -32601, message: MENSAJE_DESINSTALADO } })
96
+ }
97
+ })
98
+ process.stdin.on('end', () => process.exit(0))
99
+ }
100
+
101
+ // Whether the LMCP menu-bar app is on this machine. The server path never installs it; when
102
+ // it is missing the wrapper says so in one stderr line. Mac: the tray bundle in ~/Applications
103
+ // or /Applications. Windows: lmcp-tray.exe, which LMCP-Setup.exe puts next to the server in the
104
+ // cache dir (lmcp-win cmd/lmcp-server/tray_windows.go). On Windows `setup` installs no tray
105
+ // (ensureTray is a no-op there), so the line names only the installer. Neither does it on Mac now: npx is server-only.
106
+ function menuBarAppHowToInstall() {
107
+ return 'the installer from https://local-mcp.com'
108
+ }
109
+ function menuBarAppMissingLine(platform = process.platform) {
110
+ return `[LMCP] The LMCP menu-bar app is not installed; running the MCP server only. To install it: ${menuBarAppHowToInstall(platform)}`
111
+ }
112
+ function menuBarAppInstalled(platform = process.platform) {
113
+ const exists = (p) => { try { return fs.existsSync(p) } catch { return false } }
114
+ if (platform === 'darwin') {
115
+ const { _isUsableTrayBundle, trayAppPaths } = require('./download')
116
+ return trayAppPaths().some(_isUsableTrayBundle)
117
+ }
118
+ if (platform === 'win32') return exists(path.join(require('./download').CACHE_DIR, 'lmcp-tray.exe'))
119
+ return false
120
+ }
121
+
255
122
  const cmd = process.argv[2]
256
123
 
257
124
  // Comandos que este wrapper entiende. Sin argumentos arranca el server MCP por stdio, que es
@@ -278,8 +145,8 @@ if (ES_LANZAMIENTO) {
278
145
  // pase; el server y el cliente no esperan nada: sólo se demora el evento.
279
146
  const VENTANA_ARRANQUE_MS = 2000
280
147
 
281
- // Platform support: macOS (Swift tray + embedded server) and Windows (go-server standalone
282
- // binary downloaded from R2). Linux passes this guard so that `--help`, `status`, `update` and
148
+ // Platform support: macOS (Swift server) and Windows (go-server), each shipped in its own npm
149
+ // platform package (npm/bundled.js). Linux passes this guard so that `--help`, `status`, `update` and
283
150
  // `uninstall` answer, but it is NOT supported: the server path and `setup` say so (#9).
284
151
  // Since local-mcp-releases#61 row 5 npm refuses the install on Linux (`os` in package.json), so
285
152
  // this branch is no longer reached through `npm install`/`npx`. It stays for whoever gets past
@@ -318,10 +185,7 @@ if (parseInt(process.version.slice(1)) < 16) {
318
185
  function detectManualUninstall() {
319
186
  if (process.platform !== 'darwin') return false
320
187
  const home = os.homedir()
321
- const appPresent =
322
- fs.existsSync(path.join(home, 'Applications', 'LocalMCPTray.app')) ||
323
- fs.existsSync('/Applications/LocalMCPTray.app')
324
- if (appPresent) return false
188
+ if (require('./download').trayAppPaths().length) return false // LocalMCPTray.app or LMCP.app (tray id)
325
189
  return (
326
190
  fs.existsSync(path.join(home, 'Library', 'LaunchAgents', 'com.local-mcp.tray.plist')) ||
327
191
  fs.existsSync(path.join(home, '.local', 'share', 'local-mcp', 'tray', '.version'))
@@ -342,7 +206,7 @@ Uso:
342
206
  local-mcp stdio lo mismo, dicho explícitamente
343
207
  local-mcp setup instala y configura
344
208
  local-mcp status muestra el estado
345
- local-mcp update limpia el cache del runtime
209
+ local-mcp update cómo actualizar (npx -y local-mcp@latest)
346
210
  local-mcp uninstall desinstala
347
211
 
348
212
  local-mcp --help esta ayuda`)
@@ -382,15 +246,11 @@ async function main() {
382
246
  process.exit(process.platform === 'linux' ? 1 : 0)
383
247
  }
384
248
 
249
+ // 3.0.423: el server viene dentro del paquete; no hay runtime en cache que borrar (ese directorio
250
+ // guarda el id de la máquina y el token del relay, que no son del server de npm).
385
251
  if (cmd === 'update') {
386
- const { CACHE_DIR } = require('./download')
387
- const fs = require('fs')
388
- if (fs.existsSync(CACHE_DIR)) {
389
- fs.rmSync(CACHE_DIR, { recursive: true, force: true })
390
- console.log('Cache del runtime eliminado.')
391
- }
392
- // Re-descargar en el próximo arranque
393
- console.log('Ejecutá "npx local-mcp" nuevamente para descargar la última versión.')
252
+ console.log('El server de LMCP viene con el paquete de npm. Para la última versión: npx -y local-mcp@latest')
253
+ console.log('Con la app de LMCP instalada, la app se actualiza sola.')
394
254
  return
395
255
  }
396
256
 
@@ -482,130 +342,97 @@ async function main() {
482
342
  // runtime-dir and durable App Support copies (see uninstallSentinelPaths).
483
343
  {
484
344
  if (anyUninstallSentinel()) {
485
- if (avisoDesinstaladoVigente()) {
486
- evento.silenciar()
487
- process.exit(0)
345
+ if (!avisoDesinstaladoVigente()) {
346
+ marcarAvisoDesinstalado()
347
+ reportarLanzamiento('uninstalled')
348
+ process.stderr.write(
349
+ '[LMCP] Local MCP was uninstalled — not starting.\n' +
350
+ ' Reinstall: npx -y local-mcp@latest setup\n' +
351
+ " Or remove the \"local-mcp\" entry from this app's MCP config.\n"
352
+ )
488
353
  }
489
- marcarAvisoDesinstalado()
490
- reportarLanzamiento('uninstalled')
491
- process.stderr.write(
492
- '[LMCP] Local MCP was uninstalled — not starting.\n' +
493
- ' Reinstall: npx local-mcp setup\n' +
494
- " Or remove the \"local-mcp\" entry from this app's MCP config.\n"
495
- )
496
- process.exit(0)
354
+ return quedarseVivoDesinstalado()
497
355
  }
498
356
  }
499
357
 
500
358
  // ── Honor a MANUAL uninstall (.app trashed, no sentinel written) ────────────
501
359
  // Same intent as the sentinel check above, for the common case where the user removes the
502
360
  // app via the Trash instead of the uninstaller. Adopt it as an uninstall: write the
503
- // sentinel (so future respawns short-circuit at the check above), remove the orphaned tray
504
- // LaunchAgent (so launchd stops trying to relaunch a deleted app), and refuse to start —
505
- // NOT ensureTray(), which would re-download and resurrect a machine the user removed
506
- // (FB-A30CDC). The AI client's stale MCP config entry is left alone; it just respawns us
507
- // and we short-circuit here, which is harmless.
361
+ // sentinel (so future respawns short-circuit at the check above) and refuse to start (FB-A30CDC).
362
+ // The orphaned tray LaunchAgent is NOT touched here (3.0.423): the server path writes nothing
363
+ // outside LMCP's own folders; `uninstall` removes it and `setup` rewrites it. The AI client's
364
+ // stale MCP config entry is left alone; it just respawns us and we short-circuit here.
508
365
  {
509
366
  if (detectManualUninstall()) {
510
367
  reportarLanzamiento('uninstalled')
511
368
  writeUninstallSentinels()
512
- const trayPlist = path.join(os.homedir(), 'Library', 'LaunchAgents', 'com.local-mcp.tray.plist')
513
- if (fs.existsSync(trayPlist)) {
514
- try { execSync(`launchctl unload -w "${trayPlist}" 2>/dev/null`, { stdio: 'pipe' }) } catch {}
515
- try { fs.unlinkSync(trayPlist) } catch {}
516
- }
517
369
  process.stderr.write(
518
- '[LMCP] LocalMCPTray.app was removed — treating it as an uninstall, not starting.\n' +
519
- ' Reinstall: npx local-mcp setup\n'
370
+ '[LMCP] LMCP.app was removed — treating it as an uninstall, not starting.\n' +
371
+ ' Reinstall: npx -y local-mcp@latest setup\n'
520
372
  )
521
- process.exit(0)
373
+ return quedarseVivoDesinstalado()
522
374
  }
523
375
  }
524
376
 
525
377
  // ── Linux no está soportado (#9) ────────────────────────────────────────────
526
- // Se dice acá, antes de cualquier descarga: sin esto el wrapper pedía un binario que no se
527
- // publica y terminaba en un 404. Va después de los chequeos de desinstalación, que no bajan nada.
378
+ // Se dice acá, antes de buscar el server: no hay paquete de plataforma para Linux. Va después de
379
+ // los chequeos de desinstalación.
528
380
  if (process.platform === 'linux') {
381
+ evento.fuente('missing_platform')
529
382
  process.stderr.write(require('./download').LINUX_NO_SOPORTADO + '\n')
530
383
  reportarLanzamiento('unsupported-platform')
531
384
  process.exit(1)
532
385
  }
533
386
 
534
387
  // ── Modo default: stdio MCP server ──────────────────────────────────────────
535
- const { CACHE_DIR } = require('./download')
536
- // macOS ships the Swift `local-mcp-server` (standalone fallback to the embedded
537
- // tray server); Windows/Linux ship the go-server `lmcp-server` binary that
538
- // download.js writes to CACHE_DIR. Keep this name in sync with download.js.
539
- const binName = process.platform === 'darwin'
540
- ? 'local-mcp-server'
541
- : (process.platform === 'win32' ? 'lmcp-server.exe' : 'lmcp-server')
542
- const stableBin = path.join(CACHE_DIR, binName)
543
- const versionFile = path.join(CACHE_DIR, '.server-version')
544
- // On Windows/Linux the file download.js and the go-server updater keep current is
545
- // `.go-server-version`; `.server-version` is only written by this script's slow
546
- // path. Read both, newest-wins, so the fast path sees what the updater actually
547
- // installed instead of a value only it ever writes (#1394 §C).
548
- const goVersionFileRead = path.join(CACHE_DIR, '.go-server-version')
549
- function readCachedVersion() {
550
- const read = (p) => { try { return fs.readFileSync(p, 'utf8').trim() } catch { return '' } }
551
- const own = read(versionFile)
552
- if (process.platform === 'darwin') return own
553
- const plat = read(goVersionFileRead)
554
- if (!own) return plat
555
- if (!plat) return own
556
- return semverGte(plat, own) ? plat : own
557
- }
388
+ // 3.0.423 (Darío, 2026-10-22, «A»): this path downloads NOTHING and writes nothing outside
389
+ // LMCP's own folder. The server is the native binary npm installed next to this file (the
390
+ // platform package, npm/bundled.js), run in place: no runtime download, no quarantine removal,
391
+ // no ad-hoc re-signing, no 24h self-update. Updates arrive with `npx -y local-mcp@latest`.
392
+ // The one exception is the Mac menu-bar app the person installed: its embedded, notarized
393
+ // server is preferred (ADR-0004) and the app keeps updating it.
558
394
  const pkg = require('./package.json')
559
395
 
560
396
  /** MCP hosts (Cursor, Claude) spawn us without a TTY — keep stdio bridge alive. */
561
397
  const isMcpClientSpawn = !(process.stdin && process.stdin.isTTY)
562
398
 
563
399
  function printInstallComplete(version) {
400
+ const app = menuBarAppInstalled()
564
401
  process.stderr.write('\n')
565
- process.stderr.write(`✓ Local MCP v${version} — installation complete.\n\n`)
566
- process.stderr.write(' • Menu bar: open LocalMCPTray from Applications (look for the LMCP icon).\n')
402
+ process.stderr.write(app
403
+ ? `✓ Local MCP v${version} — installation complete.\n\n`
404
+ : `✓ Local MCP v${version} — only the MCP server is set up; the menu-bar app is not installed.\n\n`)
567
405
  process.stderr.write(' • Cursor / Claude: enable the "local-mcp" MCP server in settings (they start it automatically).\n')
568
- process.stderr.write(' • You can close this terminal — do not leave `npx local-mcp` running here.\n')
569
- process.stderr.write(' • Status: http://localhost:8765/status\n\n')
406
+ if (!app) process.stderr.write(` • Menu-bar app: install it with ${menuBarAppHowToInstall()}\n`)
407
+ process.stderr.write(' • You can close this terminal — do not leave `npx -y local-mcp@latest` running here.\n')
408
+ if (app) process.stderr.write(' • Status: http://localhost:8765/status\n')
409
+ process.stderr.write('\n')
570
410
  }
571
411
 
572
- async function ensureDarwinComponents() {
573
- if (process.platform !== 'darwin') return
574
- const { ensureTray, ensureTeamsProxy } = require('./download')
575
- await Promise.all([
576
- ensureTray().catch((e) => { process.stderr.write(`[LMCP] Tray install failed: ${e.message}\n`) }),
577
- ensureTeamsProxy().catch((e) => { process.stderr.write(`[LMCP] teams-proxy install failed: ${e.message}\n`) }),
578
- ])
579
- }
412
+ // Darío, 2026-10-21 (opción «a»): el camino del server arranca SÓLO el server MCP. La app de la
413
+ // barra de menú, su LaunchAgent, los proxies y el token del relay se instalan sólo cuando la
414
+ // persona lo pide: `npx local-mcp setup`, `npm install -g` (postinstall) o los instaladores.
415
+ // cursor.directory ocultó el plugin y el directorio de Anthropic lo retuvo porque este camino
416
+ // instalaba un LaunchAgent persistente sin consentimiento. Sin la app se avisa en una línea.
417
+ if (!menuBarAppInstalled()) process.stderr.write(menuBarAppMissingLine() + '\n')
580
418
 
581
- // ADR-0004 phase 1: the notarized server embedded in LocalMCPTray.app, if present.
582
- // Preferring it over the downloaded standalone binary (which gets re-signed
583
- // ad-hoc on install) keeps Automation TCC cert-based — so Mail/Notes/Messages/
584
- // Safari permissions survive client updates instead of resetting every time.
419
+ // ADR-0004: the notarized server embedded in LocalMCPTray.app, if present. Unchanged by 3.0.423.
585
420
  function findEmbeddedServer() {
586
421
  if (process.platform !== 'darwin') return null
587
- const candidates = [
588
- path.join(os.homedir(), 'Applications', 'LocalMCPTray.app', 'Contents', 'MacOS', 'local-mcp-server'),
589
- path.join('/Applications', 'LocalMCPTray.app', 'Contents', 'MacOS', 'local-mcp-server'),
590
- ]
422
+ const candidates = require('./download').trayAppPaths().map((app) => path.join(app, 'Contents', 'MacOS', 'local-mcp-server'))
591
423
  for (const p of candidates) {
592
424
  try { if (fs.existsSync(p) && fs.statSync(p).isFile()) return p } catch {}
593
425
  }
594
426
  return null
595
427
  }
596
428
 
597
- function launchMcpStdio(binaryPath, version) {
598
- // Prefer the embedded, notarized server when the .app provides it (ADR-0004).
599
- const embedded = findEmbeddedServer()
600
- if (embedded) binaryPath = embedded
429
+ // bundled: the binary belongs to npm, so npm updates it. The server's own updater stays off
430
+ // (it would download a newer server, the proxies and, on a Mac, LocalMCPTray.app into the user's
431
+ // folders: lmcp-mac UpdateManager.swift, lmcp-win internal/heartbeat/updater.go). A value the
432
+ // person already set is respected. The app's embedded server keeps its updater: the app owns it.
433
+ function launchMcpStdio(binaryPath, version, bundled) {
601
434
  if (!isMcpClientSpawn) {
602
435
  printInstallComplete(version)
603
- if (process.platform === 'darwin') {
604
- const home = os.homedir()
605
- const tray = path.join(home, 'Applications', 'LocalMCPTray.app')
606
- const trayPath = fs.existsSync(tray) ? tray : '/Applications/LocalMCPTray.app'
607
- try { execFileSync('open', ['-a', trayPath], { stdio: 'ignore' }) } catch {}
608
- }
609
436
  process.exit(0)
610
437
  return
611
438
  }
@@ -616,12 +443,10 @@ async function main() {
616
443
  // same root cause as the .mcpb stdio→--auto fix.
617
444
  const spawnArgs = process.platform === 'darwin' ? ['--auto'] : []
618
445
  // Pass the npm PACKAGE version to the server so the heartbeat reports which index.js actually
619
- // ran (vs the server binary version). A resurrection loop is often a STALE cached npx package
620
- // (pre-guard) — this lets us tell that apart from a guard that's failing on the current package.
621
- let _pkgVer = ''
622
- try { _pkgVer = require('./package.json').version || '' } catch {}
623
- const child = spawn(binaryPath, spawnArgs, { stdio: 'inherit', env: { ...process.env, LMCP_NPM_VERSION: _pkgVer } })
624
- noteSpawnedServer(child.pid)
446
+ // ran (vs the server binary version).
447
+ const env = { ...process.env, LMCP_NPM_VERSION: pkg.version || '' }
448
+ if (bundled && env.LMCP_DISABLE_UPDATER === undefined) env.LMCP_DISABLE_UPDATER = '1'
449
+ const child = spawn(binaryPath, spawnArgs, { stdio: 'inherit', env })
625
450
  // El server arrancó y sigue vivo pasada la ventana: este proceso queda toda la sesión y el
626
451
  // evento sale desde acá.
627
452
  let arranque = null
@@ -646,174 +471,40 @@ async function main() {
646
471
  })
647
472
  }
648
473
 
649
- // On Windows: apply pending update before launching (same as Mac's UpdateManager)
650
- // The Go server downloads new versions in background and stages them as .pending.
651
- // On next Claude Desktop restart, we swap them in here.
652
- if (process.platform === 'win32') {
653
- const goVersionFile = path.join(CACHE_DIR, '.go-server-version')
654
- const pendingBin = stableBin + '.pending'
655
- const pendingVersion = path.join(CACHE_DIR, '.pending-version')
656
- if (fs.existsSync(pendingBin)) {
657
- try {
658
- const oldBin = stableBin + '.old'
659
- try { fs.unlinkSync(oldBin) } catch {}
660
- try { fs.renameSync(stableBin, oldBin) } catch {}
661
- fs.renameSync(pendingBin, stableBin)
662
- if (fs.existsSync(pendingVersion)) {
663
- const newVer = fs.readFileSync(pendingVersion, 'utf8').trim()
664
- fs.writeFileSync(goVersionFile, newVer)
665
- fs.unlinkSync(pendingVersion)
666
- }
667
- try { fs.unlinkSync(oldBin) } catch {}
668
- try { fs.unlinkSync(path.join(CACHE_DIR, '.latest-version')) } catch {}
669
- process.stderr.write(`LMCP updated to v${fs.readFileSync(goVersionFile, 'utf8').trim()}\n`)
670
- } catch (e) {
671
- process.stderr.write(`Update apply failed: ${e.message}\n`)
672
- }
673
- }
674
- }
675
-
676
- // ADR-0004 phase 3 (darwin): prefer the notarized server embedded in
677
- // LocalMCPTray.app. Ensure the .app is installed, then launch its embedded
678
- // server directly — skipping the standalone download + ad-hoc re-sign that
679
- // resets Automation TCC (Mail/Notes/Messages/Safari) on every update. Only
680
- // if the .app can't be provided do we fall through to the legacy standalone
681
- // binary (which still ad-hoc signs as a last resort so the user isn't stranded).
682
- if (process.platform === 'darwin') {
683
- await ensureDarwinComponents()
684
- const embedded = findEmbeddedServer()
685
- if (embedded) {
686
- let v = pkg.version
687
- try {
688
- v = fs.readFileSync(
689
- path.join(os.homedir(), '.local', 'share', 'local-mcp', 'tray', '.version'),
690
- 'utf8'
691
- ).trim() || pkg.version
692
- } catch {}
693
- launchMcpStdio(embedded, v)
694
- return
695
- }
696
- }
697
-
698
- // Fast path: if stable binary exists AND its version is >= our npm package version, exec directly.
699
- // Using >= (not ===) prevents Claude Desktop from downgrading a binary that the tray's
700
- // UpdateManager has already upgraded. LMC-375: machine 5F8445AE downgraded 3.0.72→3.0.70
701
- // because stale npx cache had old pkg.version and triggered the slow path unnecessarily.
702
- try {
703
- const stat = fs.lstatSync(stableBin)
704
- // Windows .exe files carry no Unix exec bit — Node's fs reports mode 0o666 —
705
- // so the `& 0o111` gate is always false there, which forced EVERY spawn onto
706
- // the slow path (a /runtime/latest network round-trip before launch, and a
707
- // hard failure when offline despite a valid cached binary). Only require the
708
- // exec bit off-Windows, where it's meaningful.
709
- if (stat.isFile() && (process.platform === 'win32' || (stat.mode & 0o111))) {
710
- const cachedVersion = readCachedVersion()
711
- if (fastPathVersionOK(process.platform, cachedVersion, pkg.version)) {
712
- // Cached binary is same or newer — use fast path, no download needed
713
- await ensureDarwinComponents()
714
- launchMcpStdio(stableBin, cachedVersion || pkg.version)
715
-
716
- // Background update check — fires 10s after startup, at most once per 24h.
717
- // Covers machines where the tray is dead and Sparkle can't update the binary.
718
- const lastCheckFile = path.join(CACHE_DIR, '.last-update-check')
719
- function _needsUpdateCheck() {
720
- try { return Date.now() - parseInt(fs.readFileSync(lastCheckFile, 'utf8').trim(), 10) > 86400000 } catch { return true }
721
- }
722
- if (_needsUpdateCheck()) {
723
- try { fs.writeFileSync(lastCheckFile, String(Date.now())) } catch {}
724
- const _cachedVersion = cachedVersion // capture for closure
725
- setTimeout(() => {
726
- const req = https.get('https://office-mcp-production.up.railway.app/runtime/latest', { timeout: 8000 }, (res) => {
727
- let buf = ''
728
- res.on('data', c => buf += c)
729
- res.on('end', () => {
730
- try {
731
- const info = JSON.parse(buf)
732
- const { latestVersionForPlatform, getArch } = require('./download')
733
- const _arch = getArch()
734
- // El nombre que se escribe en .server-version si hay que bajar:
735
- // el de ESTA plataforma, no el de la release de Mac.
736
- const latestVersion = latestVersionForPlatform(info, _arch)
737
- if (backgroundUpdateNeeded(_cachedVersion, info, _arch)) {
738
- // New version available — download for next restart only while no server is running.
739
- // Replacing stableBin mid-session changes its mtime and used to cause sibling
740
- // stdio proxies to be SIGTERM'd → Cursor transport_closed (LMCA-1044).
741
- const _exec = (cmd) => execSync(cmd, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] })
742
- // Our OWN server child does not count: launchMcpStdio spawned it
743
- // ~10s ago and it is the session this update is for. Counting it
744
- // made the guard permanently false and stopped every update.
745
- const _deps = { exec: _exec, fs, execFileSync, excludePids: spawnedServerPids() }
746
- // Cheap pre-check so we do not download for nothing; the binding
747
- // guard is the one inside replaceCachedBinary, re-checked after
748
- // the download (a server can start while it runs).
749
- if (!safeToReplaceBinary(_exec, process.platform, spawnedServerPids())) return
750
-
751
- const { ensureRuntime } = require('./download')
752
- ensureRuntime().then(({ binPath, version: downloadedVersion }) => {
753
- replaceCachedBinary(_deps, binPath, stableBin, downloadedVersion || latestVersion, versionFile)
754
- }).catch(() => {})
755
- }
756
- } catch {}
757
- })
758
- })
759
- req.on('error', () => {})
760
- req.on('timeout', () => { try { req.destroy() } catch {} })
761
- }, 10000)
762
- }
763
-
764
- return
765
- }
766
- // Cached binary is older than our npm package — download/update
767
- process.stderr.write(`Updating LMCP server (${cachedVersion || '?'} → ${pkg.version})...\n`)
768
- } else {
769
- // No cached binary version → first run via default mode
770
- }
771
- if (stat.isSymbolicLink()) fs.unlinkSync(stableBin)
772
- } catch {
773
- // stat failed — binary missing, fall through to download
474
+ const embedded = findEmbeddedServer()
475
+ if (embedded) {
476
+ let v = pkg.version
477
+ try {
478
+ v = fs.readFileSync(
479
+ path.join(os.homedir(), '.local', 'share', 'local-mcp', 'tray', '.version'),
480
+ 'utf8'
481
+ ).trim() || pkg.version
482
+ } catch {}
483
+ evento.fuente('app_embedded')
484
+ launchMcpStdio(embedded, v, false)
485
+ return
774
486
  }
775
487
 
776
- // Slow path: download/repair binary
777
- const { ensureRuntime } = require('./download')
778
-
779
- let runtime
780
- try {
781
- runtime = await ensureRuntime()
782
- } catch (err) {
783
- reportarLanzamiento('download-failed', { reason: evento.razonDeError(err) })
784
- process.stderr.write(`\nError al preparar el runtime de LMCP:\n${err.message}\n`)
785
- process.stderr.write(`Intentá reinstalar: npx local-mcp update\n\n`)
488
+ const bundled = require('./bundled').bundledServerPath()
489
+ evento.fuente(bundled && fs.existsSync(bundled) ? 'bundled' : 'missing_platform')
490
+ if (!bundled || !fs.existsSync(bundled)) {
491
+ reportarLanzamiento('spawn-failed', { reason: 'binary-missing' })
492
+ const { TARGETS } = require('./bundled')
493
+ process.stderr.write(TARGETS[`${process.platform}-${process.arch}`]
494
+ ? `[LMCP] The LMCP server for ${process.platform}-${process.arch} is not installed with this package.\n` +
495
+ ' npm skipped its platform package (an install with --omit=optional, or a mirror without it).\n' +
496
+ ' Run: npx -y --include=optional local-mcp@latest\n'
497
+ : `[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`
498
+ )
786
499
  process.exit(1)
787
500
  }
788
-
789
- const { binPath, version: downloadedVersion } = runtime
790
-
791
- // Copy binary to stable path (survives version cleanup)
792
- try {
793
- const tmpPath = stableBin + '.tmp'
794
- fs.copyFileSync(binPath, tmpPath)
795
- fs.chmodSync(tmpPath, 0o755)
796
- if (process.platform === 'darwin') { try { execFileSync('codesign', ['--force', '--sign', '-', '--identifier', 'com.local-mcp.server', tmpPath], { stdio: 'pipe' }) } catch {} }
797
- fs.renameSync(tmpPath, stableBin)
798
- // Write the ACTUAL downloaded binary version (not pkg.version) so the fast path
799
- // knows what version is on disk. Using pkg.version here caused LMC-375: machines
800
- // with old npm caches wrote an old version into .server-version even though
801
- // ensureBinary() downloaded a newer binary, causing HeartbeatManager to report
802
- // the stale version and triggering spurious downgrade events.
803
- fs.writeFileSync(versionFile, downloadedVersion || pkg.version)
804
- // Also copy settings.html
805
- const settingsSrc = path.join(path.dirname(binPath), 'settings.html')
806
- const settingsDst = path.join(CACHE_DIR, 'settings.html')
807
- if (fs.existsSync(settingsSrc)) fs.copyFileSync(settingsSrc, settingsDst)
808
- } catch {}
809
-
810
- await ensureDarwinComponents()
811
- launchMcpStdio(stableBin, downloadedVersion || pkg.version)
501
+ // The platform package carries the version of the binary inside it (the release it came from).
502
+ let binVersion = pkg.version
503
+ try { binVersion = fs.readFileSync(path.join(path.dirname(bundled), 'VERSION'), 'utf8').trim() || pkg.version } catch {}
504
+ launchMcpStdio(bundled, binVersion, true)
812
505
  }
813
506
 
814
- // Only auto-run as a program. Being requirable is what lets the version/liveness
815
- // helpers above be unit-tested at all — they guard a binary swap and a network
816
- // round-trip that no static check can see.
507
+ // Only auto-run as a program.
817
508
  if (require.main === module) {
818
509
  main().catch(err => {
819
510
  razonDeSalida = 'uncaught-exception'
@@ -821,5 +512,3 @@ if (require.main === module) {
821
512
  process.exit(1)
822
513
  })
823
514
  }
824
-
825
- module.exports = { semverGte, fastPathVersionOK, backgroundUpdateNeeded, listRunningServerPids, countRunningServers, safeToReplaceBinary, replaceCachedBinary }