local-mcp 3.0.428 → 3.0.430

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/unconfigure.js CHANGED
@@ -3,16 +3,395 @@
3
3
  // que puede alcanzar, con el MISMO catálogo que usa el setup (nada de lista de clientes aquí). Sin esto
4
4
  // el cliente sigue lanzando el wrapper en cada arranque contra una máquina ya desinstalada.
5
5
  //
6
- // Sólo toca lo que puede deshacer sin riesgo: JSON estándar (cfgSchema mcpServers / servers /
7
- // context_servers) y sólo la clave `local-mcp` dentro de ese objeto. Lo demás (TOML/YAML, esquemas
8
- // propios, JSON con comentarios o inválido, comodines sin carpeta) no se reescribe: se devuelve en
9
- // `left` con el motivo, para que el comando diga qué dejó.
6
+ // Sólo toca lo que puede deshacer sin riesgo: las claves de LMCP dentro de su contenedor, en cada esquema
7
+ // que setup escribe (#153). Lo demás (un esquema que no conoce, un archivo que no puede probar, comodines
8
+ // sin carpeta) no se reescribe: si el archivo nombra a LMCP, va a `left` con el motivo, para que el comando
9
+ // diga qué dejó. Un archivo que no lo nombra no tiene entrada y no se avisa.
10
10
  const fs = require('fs')
11
11
  const os = require('os')
12
12
  const path = require('path')
13
13
 
14
- const ENTRY = 'local-mcp'
15
- const KEY_BY_SCHEMA = { mcpServers: 'mcpServers', servers: 'servers', context_servers: 'context_servers' }
14
+ // lmcp-npm#153: the doors of the Go side (lmcp-win internal/clientscatalog), for the formats setup writes.
15
+ // Each takes the file's text and returns the new text, null when it holds no entry of ours, or throws
16
+ // with the cause and nothing is written. Outside what is LMCP's, the text stays byte for byte.
17
+ const OURS = ['local-mcp', 'lmcp']
18
+ const OURS_JSON = [...OURS, 'office-mcp'] // the older product name; it never wrote TOML or YAML
19
+ const isOurs = (key, names = OURS) => names.includes(String(key).toLowerCase())
20
+ const mentionsOurs = (text) => /local-mcp|lmcp|office-mcp/i.test(text)
21
+
22
+ // JSONC, offset for offset: comments blanked in `code`, and trailing commas too in `json`, what JSON.parse reads.
23
+ function _jsoncBlank (text) {
24
+ const code = text.replace(/^/, ' ').split('')
25
+ const commas = []
26
+ let comma = -1
27
+ for (let i = 0; i < code.length; i++) {
28
+ const c = code[i]
29
+ if (c === '"') {
30
+ for (i++; i < code.length && code[i] !== '"'; i++) if (code[i] === '\\') i++
31
+ comma = -1
32
+ } else if (c === '/' && (code[i + 1] === '/' || code[i + 1] === '*')) {
33
+ const block = code[i + 1] === '*'
34
+ const end = block ? text.indexOf('*/', i + 2) : text.indexOf('\n', i)
35
+ if (block && end < 0) throw new Error('not JSON with comments')
36
+ const to = end < 0 ? code.length : block ? end + 2 : end
37
+ for (; i < to; i++) if (code[i] !== '\n') code[i] = ' '
38
+ i--
39
+ } else if (c === ',') comma = i
40
+ else if ((c === '}' || c === ']') && comma >= 0) { commas.push(comma); comma = -1 } else if (!/\s/.test(c)) comma = -1
41
+ }
42
+ const json = code.slice()
43
+ for (const i of commas) json[i] = ' '
44
+ return { code: code.join(''), json: json.join('') }
45
+ }
46
+
47
+ function _jsoncParse (text) {
48
+ try { return JSON.parse(_jsoncBlank(text).json) } catch { throw new Error('not JSON with comments') }
49
+ }
50
+
51
+ function _jsoncMembers (s, open) {
52
+ const members = []
53
+ let i = open + 1
54
+ const space = () => { while (i < s.length && /\s/.test(s[i])) i++ }
55
+ const pastString = () => { for (i++; s[i] !== '"'; i++) if (s[i] === '\\') i++; i++ }
56
+ const pastValue = () => {
57
+ let depth = 0
58
+ do {
59
+ if (s[i] === '"') { pastString(); continue }
60
+ if (s[i] === '{' || s[i] === '[') depth++
61
+ if (s[i] === '}' || s[i] === ']') depth--
62
+ i++
63
+ } while (depth > 0 || !/[\s,}\]]/.test(s[i]))
64
+ }
65
+ for (;;) {
66
+ space()
67
+ if (s[i] === '}') return members
68
+ const keyStart = i
69
+ pastString()
70
+ const name = JSON.parse(s.slice(keyStart, i))
71
+ space()
72
+ i++ // the colon: this text has been through JSON.parse
73
+ space()
74
+ const valStart = i
75
+ pastValue()
76
+ const valEnd = i
77
+ space()
78
+ const comma = s[i] === ',' ? i++ : -1
79
+ members.push({ name, keyStart, valStart, valEnd, comma })
80
+ }
81
+ }
82
+
83
+ // A span widened to the full lines it fills when nothing else is on them.
84
+ function _wholeLines (text, start, end) {
85
+ const from = text.lastIndexOf('\n', start - 1) + 1
86
+ const nl = text.indexOf('\n', end)
87
+ if (text.slice(from, start).trim() || nl < 0 || text.slice(end, nl).trim()) return [start, end]
88
+ return [from, nl + 1]
89
+ }
90
+
91
+ function _editJsonc (container) {
92
+ return (text) => {
93
+ const parsed = _jsoncParse(text)
94
+ const held = parsed && parsed[container]
95
+ if (!held || typeof held !== 'object' || Array.isArray(held)) return null
96
+ const { code } = _jsoncBlank(text)
97
+ const holders = _jsoncMembers(code, code.indexOf('{')).filter((x) => x.name === container)
98
+ if (holders.length !== 1) throw new Error(`"${container}" appears more than once`)
99
+ const members = _jsoncMembers(code, holders[0].valStart)
100
+ const cuts = []
101
+ let lastKept = -1
102
+ members.forEach((x, i) => {
103
+ if (!isOurs(x.name, OURS_JSON)) { lastKept = i; return }
104
+ cuts.push(_wholeLines(text, x.keyStart, x.comma >= 0 ? x.comma + 1 : x.valEnd))
105
+ })
106
+ if (!cuts.length) return null
107
+ // The object had no trailing comma and its last member is gone: the new last one must not keep one.
108
+ const n = members.length
109
+ if (members[n - 1].comma < 0 && lastKept >= 0 && lastKept < n - 1) {
110
+ const c = members[lastKept].comma
111
+ cuts.push([c, c + 1])
112
+ }
113
+ let out = text
114
+ for (const [a, b] of cuts.sort((x, y) => y[0] - x[0])) out = out.slice(0, a) + out.slice(b)
115
+ return out
116
+ }
117
+ }
118
+
119
+ // What a line editor must know of TOML: where each statement starts, and where a comment does. null
120
+ // when a line cannot be classified. Refusing costs one entry; a broken file costs all of Codex's servers.
121
+ function _tomlScan (lines) {
122
+ const facts = []
123
+ let depth = 0
124
+ let open = '' // the quote of an open multi-line string
125
+ const triple = (line, i, q) => line.startsWith(q + q + q, i)
126
+ for (let idx = 0; idx < lines.length; idx++) {
127
+ const line = lines[idx]
128
+ const r = line.indexOf('\r')
129
+ if (r >= 0 && (r !== line.length - 1 || idx === lines.length - 1)) return null
130
+ const start = depth === 0 && !open
131
+ let comment = -1
132
+ for (let i = 0; i < line.length;) {
133
+ const c = line[i]
134
+ if (open) {
135
+ if (c === open && triple(line, i, open)) { open = ''; i += 3 } else if (open === '"' && c === '\\' && i + 1 < line.length) i += 2
136
+ else i++
137
+ } else if (c === '#') { comment = i; break } else if (c === '"' || c === "'") {
138
+ if (triple(line, i, c)) { open = c; i += 3; continue }
139
+ for (i++; i < line.length && line[i] !== c; i++) if (c === '"' && line[i] === '\\') i++
140
+ if (i >= line.length) return null
141
+ i++
142
+ } else {
143
+ if (c === '[' || c === '{') depth++
144
+ if (c === ']' || c === '}') depth--
145
+ if (depth < 0) return null
146
+ i++
147
+ }
148
+ }
149
+ facts.push({ start, comment })
150
+ }
151
+ return depth === 0 && !open ? facts : null
152
+ }
153
+
154
+ const _tomlCode = (line, f) => (f.comment < 0 ? line : line.slice(0, f.comment)).trim()
155
+
156
+ // `[ a."b" ]` → `a.b`; a quoted part holding a dot keeps its quotes: it is ONE name.
157
+ function _tomlName (raw) {
158
+ const s = raw.replace(/^\[+/, '').replace(/\]+$/, '')
159
+ let out = ''
160
+ let part = ''
161
+ let quote = ''
162
+ for (let i = 0; i < s.length; i++) {
163
+ const c = s[i]
164
+ if (!quote && (c === '"' || c === "'")) { quote = c; part = '' } else if (!quote) { if (!/\s/.test(c)) out += c } else if (c === quote) {
165
+ out += part.includes('.') ? `"${part}"` : part
166
+ quote = ''
167
+ } else if (c === '\\' && quote === '"' && i + 1 < s.length) part += s[++i]
168
+ else part += c
169
+ }
170
+ return out
171
+ }
172
+
173
+ // The table's [header, end) lines, null when it is not there. Throws on a shape a line edit cannot prove.
174
+ function _tomlSection (lines, facts, name) {
175
+ const table = 'mcp_servers.' + name
176
+ const canonical = `[${table}]`
177
+ const same = (a, b) => a.toLowerCase() === b.toLowerCase()
178
+ let header = -1
179
+ let end = lines.length
180
+ let current = ''
181
+ for (let i = 0; i < lines.length; i++) {
182
+ if (!facts[i].start) continue
183
+ const code = _tomlCode(lines[i], facts[i])
184
+ if (!code) continue
185
+ if (code.startsWith('[')) {
186
+ if (header !== -1 && end === lines.length && i > header) end = i
187
+ const n = _tomlName(code)
188
+ if (same(n, table)) {
189
+ if (code.startsWith('[[')) throw new Error(`\`${table}\` is an array of tables`)
190
+ if (!same(code, canonical)) throw new Error(`its header is written as \`${code}\` instead of plain \`${canonical}\``)
191
+ if (header !== -1) throw new Error(`\`${canonical}\` appears more than once`)
192
+ header = i
193
+ end = lines.length
194
+ }
195
+ current = n
196
+ continue
197
+ }
198
+ const eq = code.indexOf('=')
199
+ if (eq < 0) throw new Error(`this line isn't a key or a table header: \`${code.slice(0, 40)}\``)
200
+ const full = (current ? current + '.' : '') + _tomlName(code.slice(0, eq))
201
+ const low = full.toLowerCase()
202
+ const t = table.toLowerCase()
203
+ const inside = current.toLowerCase() === t || current.toLowerCase().startsWith(t + '.')
204
+ if ((!inside && (low === t || low.startsWith(t + '.'))) || full === 'mcp_servers') {
205
+ throw new Error(`\`${full}\` is written as a key, not as a \`${canonical}\` section`)
206
+ }
207
+ }
208
+ return header === -1 ? null : { header, end }
209
+ }
210
+
211
+ function _editToml (text) {
212
+ let lines = text.split('\n')
213
+ let changed = false
214
+ for (const name of OURS) {
215
+ for (;;) {
216
+ const facts = _tomlScan(lines)
217
+ if (!facts) throw new Error('it could not be read as TOML')
218
+ const sec = _tomlSection(lines, facts, name)
219
+ if (!sec) break
220
+ let { end } = sec
221
+ // Our subtables ([mcp_servers.local-mcp.env]) go with the table.
222
+ const table = ('mcp_servers.' + name).toLowerCase()
223
+ const isHeader = (i) => facts[i].start && _tomlCode(lines[i], facts[i]).startsWith('[')
224
+ while (end < lines.length) {
225
+ const code = facts[end].start ? _tomlCode(lines[end], facts[end]) : ''
226
+ if (code) {
227
+ const n = _tomlName(code).toLowerCase()
228
+ if (!code.startsWith('[') || (n !== table && !n.startsWith(table + '.'))) break
229
+ end++
230
+ while (end < lines.length && !isHeader(end)) end++
231
+ } else end++
232
+ }
233
+ // The blank and comment lines before the next section document that one.
234
+ while (end > sec.header + 1 && !_tomlCode(lines[end - 1], facts[end - 1])) end--
235
+ lines = [...lines.slice(0, sec.header), ...lines.slice(end)]
236
+ changed = true
237
+ }
238
+ }
239
+ return changed ? lines.join('\n') : null
240
+ }
241
+
242
+ // YAML by lines: one form only, a top-level block map holding the container, one block per server.
243
+ // Everything else is refused with its cause, as in yaml_lines.go. Go also asks a strict parser to agree;
244
+ // npm has no YAML dependency, so here the reader's refusals are the whole guard.
245
+ const YAML_KEY = /^\s*(?:"([^"]+)"|'([^']+)'|([^\s#'"\-[{][^:#]*?))\s*:(?:\s+(.*))?$/
246
+ const YAML_MAX = 1 << 20
247
+
248
+ function _yamlSplit (text) {
249
+ const parts = text.split('\n')
250
+ const whole = text.endsWith('\n')
251
+ if (parts[parts.length - 1] === '') parts.pop()
252
+ return parts.map((raw, i) => {
253
+ const cr = raw.endsWith('\r')
254
+ const t = cr ? raw.slice(0, -1) : raw
255
+ const rest = t.replace(/^ */, '')
256
+ const l = { text: t, eol: (cr ? '\r' : '') + (i < parts.length - 1 || whole ? '\n' : ''), indent: t.length - rest.length }
257
+ l.blank = !rest.trim() || rest.startsWith('#')
258
+ const m = l.blank ? null : YAML_KEY.exec(t)
259
+ if (m) {
260
+ l.name = (m[1] || m[2] || m[3] || '').trim()
261
+ l.value = _yamlStripComment(m[4] || '')
262
+ l.odd = (m[1] || '').includes('\\') || /^[!&*?|>@`%]/.test(m[3] || '')
263
+ }
264
+ return l
265
+ })
266
+ }
267
+
268
+ function _yamlStripComment (v) {
269
+ let quote = ''
270
+ let prev = ' '
271
+ for (let i = 0; i < v.length; i++) {
272
+ const c = v[i]
273
+ if (quote === '"' && c === '\\') i++
274
+ else if (quote) { if (c === quote) quote = '' } else if (c === '"' || c === "'") quote = c
275
+ else if (c === '#' && (prev === ' ' || prev === '\t')) return v.slice(0, i).trim()
276
+ prev = c
277
+ }
278
+ return v.trim()
279
+ }
280
+
281
+ // A value that opens a quoted string or a flow collection and does not close it on its line.
282
+ function _yamlContinues (t) {
283
+ while (/^[-?:] /.test(t)) t = t.slice(2).trim()
284
+ const m = YAML_KEY.exec(t)
285
+ if (m) t = (m[4] || '').trim()
286
+ while (t.startsWith('!') || t.startsWith('&')) t = t.includes(' ') ? t.slice(t.indexOf(' ')).trim() : ''
287
+ if (!t || !'"\'[{'.includes(t[0])) return false
288
+ let depth = 0
289
+ let quote = ''
290
+ for (let i = 0; i < t.length; i++) {
291
+ const c = t[i]
292
+ if (quote === '"' && c === '\\') i++
293
+ else if (quote) { if (c === quote) quote = '' } else if (c === '"' || c === "'") quote = c
294
+ else if (c === '[' || c === '{') depth++
295
+ else if (c === ']' || c === '}') depth--
296
+ else if (c === '#' && depth === 0 && i > 0 && t[i - 1] === ' ') return false
297
+ }
298
+ return Boolean(quote) || depth > 0
299
+ }
300
+
301
+ // A tag, an anchor, an alias or an explicit key, outside quotes and comments.
302
+ function _yamlHasProperty (t) {
303
+ let quote = ''
304
+ for (let i = 0; i < t.length; i++) {
305
+ const c = t[i]
306
+ const start = i === 0 || ' \t[{,'.includes(t[i - 1])
307
+ const named = i + 1 < t.length && t[i + 1] !== ' ' && t[i + 1] !== '\t'
308
+ if (quote === '"' && c === '\\') i++
309
+ else if (quote) { if (c === quote) quote = '' } else if (!start) continue
310
+ else if (c === '#' && i > 0) return false
311
+ else if (c === '"' || c === "'") quote = c
312
+ else if (c === '!' || ((c === '&' || c === '*') && named) || (c === '?' && !named)) return true
313
+ }
314
+ return false
315
+ }
316
+
317
+ function _yamlOpen (text, container) {
318
+ if (text.length > YAML_MAX) throw new Error('the file is larger than 1024 KB')
319
+ const lines = _yamlSplit(text)
320
+ const doc = { lines, container: -1, end: -1, childIndent: -1, children: [] }
321
+ let content = 0
322
+ let marker = false
323
+ let emptyDoc = false
324
+ lines.forEach((l, i) => {
325
+ if (/^ *\t/.test(l.text)) throw new Error('tabs in the indentation')
326
+ if (l.blank) return
327
+ const t = l.text.trim()
328
+ if (l.text.includes('\r')) throw new Error('line endings that are a lone CR')
329
+ if (_yamlContinues(t)) throw new Error('a quoted string or a flow collection that continues on the next line')
330
+ if (l.odd || _yamlHasProperty(t)) throw new Error('a tag, an anchor, an alias or an explicit key')
331
+ if (t === '---' && content === 0 && !marker) { marker = true; return }
332
+ if (t === '---' || t === '...') throw new Error('more than one document')
333
+ content++
334
+ if (emptyDoc || (content === 1 && l.indent > 0) || (!l.name && l.indent === 0 && !(t === '{}' && content === 1))) throw new Error('not a block map at the top level')
335
+ emptyDoc = t === '{}'
336
+ if (emptyDoc) return
337
+ if (l.name === '<<') throw new Error('anchors or aliases (a merge key)')
338
+ if (l.indent === 0 && l.name === container) {
339
+ if (doc.container >= 0) throw new Error(`\`${container}\` appears twice`)
340
+ doc.container = i
341
+ }
342
+ })
343
+ if (doc.container < 0) return doc
344
+ const c = doc.container
345
+ doc.end = c
346
+ for (let j = c + 1; j < lines.length && (lines[j].blank || lines[j].indent > 0); j++) if (!lines[j].blank) doc.end = j
347
+ const { value } = lines[c]
348
+ if (!['', '{}', 'null', '~'].includes(value)) throw new Error(`\`${container}\` is written in flow style`)
349
+ if (value && doc.end > c) throw new Error(`\`${container}: ${value}\` with content under it`)
350
+ for (let k = c + 1; k <= doc.end; k++) {
351
+ const l = lines[k]
352
+ if (l.blank) continue
353
+ if (doc.childIndent < 0) doc.childIndent = l.indent
354
+ if (l.indent < doc.childIndent) throw new Error(`uneven indentation inside \`${container}\``)
355
+ if (l.indent > doc.childIndent) continue
356
+ if (!l.name) throw new Error(`an entry of \`${container}\` is not \`key:\``)
357
+ doc.children.push({ name: l.name, line: k })
358
+ }
359
+ return doc
360
+ }
361
+
362
+ function _editYaml (container) {
363
+ return (text) => {
364
+ const bom = text.startsWith('') ? '' : ''
365
+ const body = text.slice(bom.length)
366
+ const doc = _yamlOpen(body, container)
367
+ const ours = doc.children.filter((ch) => isOurs(ch.name))
368
+ if (!ours.length) return null
369
+ const { lines } = doc
370
+ const gone = new Set()
371
+ for (const { line } of ours) {
372
+ let to = line + 1
373
+ for (let j = to; j <= doc.end && (lines[j].blank || lines[j].indent > doc.childIndent); j++) if (!lines[j].blank) to = j + 1
374
+ // Comments indented inside our entry go with it.
375
+ while (to < lines.length && lines[to].blank && lines[to].text.trim() && lines[to].indent > doc.childIndent) to++
376
+ for (let j = line; j < to; j++) gone.add(j)
377
+ }
378
+ // A container with no entry left is written `{}`: empty alone would be null.
379
+ if (ours.length === doc.children.length) lines[doc.container].text = lines[doc.container].text.replace(/:(\s|$)/, ': {}$1')
380
+ return bom + lines.filter((_, i) => !gone.has(i)).map((l) => l.text + l.eol).join('')
381
+ }
382
+ }
383
+
384
+ const EDITORS = {
385
+ mcpServers: _editJsonc('mcpServers'),
386
+ servers: _editJsonc('servers'),
387
+ context_servers: _editJsonc('context_servers'),
388
+ mcpServers_active: _editJsonc('mcpServers'),
389
+ mcpServers_copilot: _editJsonc('mcpServers'), // lmcp-win#1330, only in `extraCfg`
390
+ opencode_mcp: _editJsonc('mcp'),
391
+ mcp_servers_toml: _editToml,
392
+ goose_yaml: _editYaml('extensions'),
393
+ hermes_yaml: _editYaml('mcp_servers'),
394
+ }
16
395
 
17
396
  function _expand(p, env) {
18
397
  return p
@@ -45,20 +424,51 @@ function _paths(client, plat, env) {
45
424
  if (!platform || !Array.isArray(platform.cfgPaths)) return []
46
425
  const hosts = Array.isArray(platform.hosts) && platform.hosts.length ? platform.hosts : [null]
47
426
  const out = []
48
- for (const raw of platform.cfgPaths) {
427
+ // lmcp-win#1330: `extraCfg` names more files, each with its own schema.
428
+ const extra = (Array.isArray(platform.extraCfg) ? platform.extraCfg : []).filter((x) => x && typeof x.path === 'string')
429
+ // The list of CleanupPaths in lmcp-win: every `since` block, whatever the version that wrote the entry.
430
+ const textos = (x) => (Array.isArray(x) ? x : []).filter((p) => typeof p === 'string')
431
+ const sinHost = Object.values(platform.since || {}).flatMap((b) => textos(b && b.cfgPathsNoHost))
432
+ const propias = [...platform.cfgPaths, ...textos(platform.legacyCfgPaths), ...sinHost]
433
+ const rutas = [...propias.map((raw) => [raw, client.cfgSchema]), ...extra.map((x) => [x.path, x.cfgSchema])]
434
+ for (const [raw, schema] of rutas) {
49
435
  for (const h of hosts) {
50
436
  const withHost = h === null ? raw : raw.replace(/\{host\}/g, h)
51
437
  if (withHost.includes('{host}')) continue
52
- for (const f of _glob(_expand(withHost, env))) if (!out.includes(f)) out.push(f)
438
+ for (const file of _glob(_expand(withHost, env))) if (!out.some((p) => p.file === file)) out.push({ file, schema })
53
439
  }
54
440
  }
55
441
  return out
56
442
  }
57
443
 
58
- function _writeAtomic(file, data) {
59
- const tmp = file + '.lmcp-tmp'
60
- fs.writeFileSync(tmp, JSON.stringify(data, null, 2) + '\n', 'utf8')
61
- fs.renameSync(tmp, file)
444
+ // The file keeps its mode (a config may hold provider keys) and stays a symlink if it is one. The
445
+ // temporary is born with that mode: at no moment is there a copy others can read. `wx` after the rm:
446
+ // a stale one would keep its own mode. A file that changed since it was read (Goose rewrites its own)
447
+ // is not overwritten: `before` is what was read.
448
+ function _writeAtomic(file, text, before) {
449
+ const real = fs.realpathSync(file)
450
+ if (!fs.readFileSync(real).equals(before)) throw new Error('it changed while LMCP was reading it')
451
+ const mode = fs.statSync(real).mode & 0o777
452
+ const tmp = real + '.lmcp-tmp'
453
+ fs.rmSync(tmp, { force: true })
454
+ try {
455
+ fs.writeFileSync(tmp, text, { encoding: 'utf8', mode, flag: 'wx' })
456
+ fs.chmodSync(tmp, mode) // the umask can only have narrowed it
457
+ fs.renameSync(tmp, real)
458
+ } catch (e) {
459
+ fs.rmSync(tmp, { force: true })
460
+ throw e
461
+ }
462
+ }
463
+
464
+ // The copy a client's door keeps before it writes (YAMLBackupSuffix in lmcp-win): it lives as long as
465
+ // LMCP's entry, so a provider key the person rotates later is in no copy LMCP left behind.
466
+ function _dropBackup(file) { fs.rmSync(file + '.lmcp-backup', { force: true }) }
467
+
468
+ // The copy of a file that does not parse may be all that is left of the config: it stays, as in Go.
469
+ function _readable (raw, text, schema) {
470
+ if (!text.trim()) return true
471
+ try { return Buffer.from(text, 'utf8').equals(raw) && (EDITORS[schema](text), true) } catch { return false }
62
472
  }
63
473
 
64
474
  /**
@@ -79,23 +489,100 @@ function unconfigureClients(catalog, opts = {}) {
79
489
  const left = []
80
490
  if (!plat || !catalog || !Array.isArray(catalog.clients)) return { removed, left }
81
491
  for (const c of catalog.clients) {
82
- const files = _paths(c, plat, env).filter((f) => { try { return fs.statSync(f).isFile() } catch { return false } })
83
- for (const file of files) {
84
- const key = KEY_BY_SCHEMA[c.cfgSchema]
85
- if (!key) { left.push({ client: c.id, file, reason: 'schema ' + c.cfgSchema }); continue }
86
- let data
87
- try { data = JSON.parse(fs.readFileSync(file, 'utf8')) } catch {
88
- left.push({ client: c.id, file, reason: 'not plain JSON' }); continue
89
- }
90
- const block = data && typeof data === 'object' ? data[key] : null
91
- if (!block || typeof block !== 'object' || !(ENTRY in block)) continue
92
- delete block[ENTRY]
93
- try { _writeAtomic(file, data); removed.push({ client: c.id, file }) } catch (e) {
94
- left.push({ client: c.id, file, reason: e.message })
95
- }
492
+ for (const { file, schema } of _paths(c, plat, env)) {
493
+ const res = { client: c.id, file }
494
+ try {
495
+ if (!fs.existsSync(file)) { _dropBackup(file); continue }
496
+ if (!fs.statSync(file).isFile()) continue
497
+ const raw = fs.readFileSync(file)
498
+ const text = raw.toString('utf8')
499
+ if (!mentionsOurs(text)) {
500
+ if (_readable(raw, text, schema)) _dropBackup(file)
501
+ continue
502
+ }
503
+ if (!Buffer.from(text, 'utf8').equals(raw)) throw new Error('not UTF-8')
504
+ const edit = EDITORS[schema]
505
+ if (!edit) throw new Error('schema ' + schema)
506
+ const out = edit(text)
507
+ if (out !== null) {
508
+ _writeAtomic(file, out, raw)
509
+ removed.push(res)
510
+ }
511
+ _dropBackup(file)
512
+ } catch (e) { left.push({ ...res, reason: e.message }) }
96
513
  }
97
514
  }
98
515
  return { removed, left }
99
516
  }
100
517
 
101
- module.exports = { unconfigureClients }
518
+ // lmcp-npm#144 (Darío, 2026-10-24, option 2): uninstalling removes everything npx setup and its server
519
+ // left on Windows: the relay token and the device key in the Credential Manager, %APPDATA%\Local MCP,
520
+ // and %LOCALAPPDATA%\local-mcp save its sentinels (`.uninstalled`, `.uninstalled-aviso` of #48). The
521
+ // installed app (lmcp-tray.exe in local-mcp\bin) shares all of it: then nothing is touched. Off
522
+ // Windows: nothing beyond the runtime the command already removes (Mac not measured in #144).
523
+ const SENTINELS = ['.uninstalled', '.uninstalled-aviso']
524
+ const CREDENTIALS = ['LMCP:cloud-token', 'LMCP:tunnel-device-key']
525
+
526
+ function localState ({ platform = process.platform, localAppData = process.env.LOCALAPPDATA, appData = process.env.APPDATA, appInstalled } = {}) {
527
+ if (platform !== 'win32') return null
528
+ const home = os.homedir()
529
+ const base = path.join(localAppData || path.join(home, 'AppData', 'Local'), 'local-mcp')
530
+ return {
531
+ base,
532
+ config: path.join(appData || path.join(home, 'AppData', 'Roaming'), 'Local MCP'),
533
+ credentials: CREDENTIALS,
534
+ appInstalled: appInstalled === undefined ? fs.existsSync(path.join(base, 'bin', 'lmcp-tray.exe')) : appInstalled,
535
+ }
536
+ }
537
+
538
+ // Each removal on its own: one that fails (EBUSY, a locked log) goes to `left` and the rest still
539
+ // goes. cmdkey without a shell (#94's rule for credential stores). Its text changes with the Windows
540
+ // language, and it fails alike for an absent item and for no vault, so what tells them apart is the
541
+ // target's name in /list: not there and not deleted is `unconfirmed`, because ssh and session 0 list
542
+ // nothing whatever the vault holds, which is also why the delete runs without being listed.
543
+ function removeLocalState (st, { exec = require('child_process').execFileSync, rm = fs.rmSync } = {}) {
544
+ const removed = []
545
+ const left = []
546
+ const credentialsLeft = []
547
+ const unconfirmed = []
548
+ if (!st || st.appInstalled) return { removed, left, credentialsLeft, unconfirmed }
549
+ const quitar = (p) => { try { rm(p, { recursive: true, force: true }); removed.push(p) } catch { left.push(p) } }
550
+ let entries = []
551
+ try { entries = fs.readdirSync(st.base) } catch {}
552
+ for (const e of entries) if (!SENTINELS.includes(e)) quitar(path.join(st.base, e))
553
+ if (fs.existsSync(st.config)) quitar(st.config)
554
+ let listed = ''
555
+ try { listed = String(exec('cmdkey', ['/list:LMCP:*'], { stdio: 'pipe', shell: false })) } catch {}
556
+ for (const c of st.credentials) {
557
+ try {
558
+ exec('cmdkey', ['/delete:' + c], { stdio: 'pipe', shell: false })
559
+ removed.push(c)
560
+ } catch { (listed.includes(c) ? credentialsLeft : unconfirmed).push(c) }
561
+ }
562
+ return { removed, left, credentialsLeft, unconfirmed }
563
+ }
564
+
565
+ // What the command prints for removeLocalState: «uninstalled» alone only when nothing is in doubt.
566
+ function localStateReport ({ removed, left, credentialsLeft, unconfirmed }) {
567
+ const lines = []
568
+ if (removed.length) lines.push('Removed this computer\'s LMCP data: ' + removed.join(', '))
569
+ if (left.length) lines.push('Could not remove (in use): ' + left.join(', ') + '. Close LMCP and run uninstall again, or remove them by hand.')
570
+ if (credentialsLeft.length) lines.push('Could not remove: ' + credentialsLeft.join(', ') + '. Remove them in Credential Manager, under Windows Credentials.')
571
+ if (unconfirmed.length) lines.push('Not found, so not removed: ' + unconfirmed.join(', ') + '. This is expected if they were never created. Over ssh or in a service, Windows credentials cannot be seen: check Credential Manager from your desktop session.')
572
+ lines.push(left.length || credentialsLeft.length || unconfirmed.length ? 'Local MCP uninstalled, except anything listed above that is still there.' : 'Local MCP uninstalled.')
573
+ return lines
574
+ }
575
+
576
+ // #159: what Windows holds in the runtime folder, because something is running it. A running .exe
577
+ // opens for reading and not for writing (EBUSY, measured on Windows 10); any other error is left to the
578
+ // removal, so a read-only file never blocks uninstall forever. Elsewhere a running binary can be deleted.
579
+ function runtimeInUse (dir, { platform = process.platform, open = fs.openSync } = {}) {
580
+ if (platform !== 'win32') return []
581
+ let names
582
+ try { names = fs.readdirSync(dir, { recursive: true }) } catch { return [] }
583
+ return names.filter((n) => /\.exe$/i.test(n)).filter((n) => {
584
+ try { fs.closeSync(open(path.join(dir, n), 'r+')); return false } catch (e) { return e.code === 'EBUSY' }
585
+ })
586
+ }
587
+
588
+ module.exports = { unconfigureClients, localState, removeLocalState, localStateReport, runtimeInUse }