@luanpdd/kit-mcp 1.35.0 → 1.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/bin/cli.js +2 -2
  2. package/bin/mcp.js +6 -6
  3. package/bin/ui.js +74 -74
  4. package/gates/ai-prompt-stability.md +120 -120
  5. package/gates/budget-description.md +68 -68
  6. package/gates/confidence.md +29 -29
  7. package/gates/dependency-check.md +33 -33
  8. package/gates/dept-cycle-prevention.md +179 -179
  9. package/gates/golden-signals-coverage.md +133 -133
  10. package/gates/legacy-refactor-safety.md +178 -178
  11. package/gates/multi-tenant-rls-coverage.md +102 -102
  12. package/gates/no-personal-uuid.md +72 -72
  13. package/gates/obs-agents-mcp-supabase.md +86 -86
  14. package/gates/obs-skills-frontmatter.md +76 -76
  15. package/gates/observability-coverage.md +151 -151
  16. package/gates/omm-no-regression.md +83 -83
  17. package/gates/postmortem-template-required.md +127 -127
  18. package/gates/prr-checklist-coverage.md +128 -128
  19. package/gates/regression.md +32 -32
  20. package/gates/release-pipeline-policy.md +132 -132
  21. package/gates/secrets-scan.md +33 -33
  22. package/gates/service-role-not-in-user-facing.md +113 -113
  23. package/gates/skill-must-include.md +71 -71
  24. package/gates/sync-idempotent.md +62 -62
  25. package/gates/verify-phase-goal.md +34 -34
  26. package/kit/agents/designer-ui.md +216 -216
  27. package/kit/agents/workflow-generator.md +537 -167
  28. package/kit/commands/adicionar-backlog.md +1 -1
  29. package/kit/commands/adicionar-fase.md +1 -1
  30. package/kit/commands/adicionar-tarefa.md +1 -1
  31. package/kit/commands/auditar-observabilidade.md +103 -103
  32. package/kit/commands/auditar-toil.md +129 -129
  33. package/kit/commands/caracterizar-prompt.md +195 -195
  34. package/kit/commands/criar-workflow.md +158 -158
  35. package/kit/commands/definir-perfil.md +1 -1
  36. package/kit/commands/definir-slo.md +108 -108
  37. package/kit/commands/fio.md +1 -1
  38. package/kit/commands/golden-signals.md +142 -142
  39. package/kit/commands/instrumentar-fase.md +200 -200
  40. package/kit/commands/investigar-producao.md +162 -162
  41. package/kit/commands/observabilidade.md +118 -118
  42. package/kit/commands/postmortem.md +179 -179
  43. package/kit/commands/prr.md +205 -205
  44. package/kit/commands/publicar-rapido.md +207 -207
  45. package/kit/commands/risk-budget.md +220 -220
  46. package/kit/commands/sre.md +230 -230
  47. package/kit/file-manifest.json +424 -424
  48. package/kit/framework/references/output-style.md +22 -22
  49. package/kit/hooks/post-apply-migration.js +199 -199
  50. package/kit/hooks/sidecar-tool-publisher.js +210 -210
  51. package/kit/skills/_shared-dados-distribuidos/glossary.md +224 -224
  52. package/kit/skills/_shared-legacy/glossary.md +389 -389
  53. package/kit/skills/_shared-multi-tenant/glossary.md +186 -186
  54. package/kit/skills/_shared-observability/glossary.md +396 -396
  55. package/kit/skills/_shared-sre/glossary.md +712 -712
  56. package/kit/skills/_shared-supabase/glossary.md +234 -234
  57. package/kit/skills/blameless-postmortems/SKILL.md +340 -340
  58. package/kit/skills/burn-rate-alerting/SKILL.md +258 -258
  59. package/kit/skills/cascading-failures/SKILL.md +311 -311
  60. package/kit/skills/core-analysis-loop/SKILL.md +352 -352
  61. package/kit/skills/distributed-tracing/SKILL.md +362 -362
  62. package/kit/skills/dynamic-workflow-authoring/SKILL.md +327 -223
  63. package/kit/skills/eliminating-toil/SKILL.md +243 -243
  64. package/kit/skills/event-based-slos/SKILL.md +296 -296
  65. package/kit/skills/four-golden-signals/SKILL.md +314 -314
  66. package/kit/skills/hermetic-builds/SKILL.md +323 -323
  67. package/kit/skills/legacy-monster-methods/SKILL.md +444 -444
  68. package/kit/skills/llm-as-dependency/SKILL.md +436 -436
  69. package/kit/skills/load-shedding-graceful-degradation/SKILL.md +396 -396
  70. package/kit/skills/observability-driven-development/SKILL.md +315 -315
  71. package/kit/skills/observability-maturity-model/SKILL.md +222 -222
  72. package/kit/skills/opentelemetry-standard/SKILL.md +351 -351
  73. package/kit/skills/production-readiness-review/SKILL.md +305 -305
  74. package/kit/skills/release-engineering/SKILL.md +367 -367
  75. package/kit/skills/retry-strategies/SKILL.md +372 -372
  76. package/kit/skills/sre-risk-management/SKILL.md +221 -221
  77. package/kit/skills/structured-events/SKILL.md +265 -265
  78. package/kit/skills/supabase-cron-queues/SKILL.md +275 -275
  79. package/kit/skills/supabase-database-functions/SKILL.md +332 -332
  80. package/kit/skills/supabase-declarative-schema/SKILL.md +183 -183
  81. package/kit/skills/supabase-pgvector-rag/SKILL.md +253 -253
  82. package/kit/skills/supabase-postgres-style/SKILL.md +138 -138
  83. package/kit/skills/supabase-storage/SKILL.md +234 -234
  84. package/kit/skills/telemetry-pipelines/SKILL.md +259 -259
  85. package/kit/skills/telemetry-sampling/SKILL.md +256 -256
  86. package/kit/skills/ui-anti-padroes-ia/SKILL.md +261 -261
  87. package/kit/skills/ui-contexto-produto/SKILL.md +248 -248
  88. package/kit/skills/ui-cor-estrategia/SKILL.md +213 -213
  89. package/kit/skills/ui-critica-auditoria/SKILL.md +260 -260
  90. package/kit/skills/ui-motion-funcional/SKILL.md +264 -264
  91. package/kit/skills/ui-ritmo-espacial/SKILL.md +259 -259
  92. package/kit/skills/ui-tipografia/SKILL.md +211 -211
  93. package/package.json +1 -1
  94. package/src/cli/index.js +1114 -1114
  95. package/src/cli/render.js +194 -194
  96. package/src/cli/upgrade-check.js +135 -135
  97. package/src/core/error-redaction.js +76 -76
  98. package/src/core/failures.js +153 -153
  99. package/src/core/gate-runner.js +205 -205
  100. package/src/core/gates.js +82 -82
  101. package/src/core/logger.js +170 -170
  102. package/src/core/manifest-verify.js +174 -174
  103. package/src/core/metrics.js +268 -268
  104. package/src/core/notify.js +60 -60
  105. package/src/core/path-safety.js +141 -141
  106. package/src/core/replays.js +120 -120
  107. package/src/core/ui.js +185 -185
  108. package/src/mcp-server/install.js +149 -149
  109. package/src/mcp-server/roots.js +124 -124
  110. package/src/ui/auto-spawn.js +113 -113
  111. package/src/ui/browser.js +78 -78
  112. package/src/ui/client.js +130 -130
  113. package/src/ui/events.js +65 -65
  114. package/src/ui/lockfile.js +191 -191
  115. package/src/ui/port.js +67 -67
  116. package/src/ui/server.js +547 -547
  117. package/src/ui/wrapper.js +129 -129
package/src/core/ui.js CHANGED
@@ -1,185 +1,185 @@
1
- // UI primitives for the CLI: colors, icons, spinner, progress bar,
2
- // interactive select/confirm prompts, and a summary panel.
3
- //
4
- // Design rules:
5
- // - Respect process.stdout.isTTY: animations only when interactive.
6
- // In pipes/CI, fall back to linear status text.
7
- // - Respect NO_COLOR (https://no-color.org) and FORCE_COLOR=1.
8
- // - Animations write to stderr to keep stdout clean for `--json` mode
9
- // (the user can still pipe machine-readable output even with spinners).
10
- // - Zero hidden globals — every primitive is a plain function/class.
11
-
12
- import pc from 'picocolors';
13
-
14
- // PERF-16-05: @inquirer/prompts é optionalDependency. Carregamos lazy dentro
15
- // de select()/confirm() para que (a) modo MCP server e CI não paguem o custo
16
- // de boot, e (b) `npm install --omit=optional` produza CLI core funcional
17
- // (apenas comandos interativos falham com mensagem descritiva).
18
- let _inquirerModule = null;
19
- async function loadInquirer() {
20
- if (_inquirerModule) return _inquirerModule;
21
- try {
22
- _inquirerModule = await import('@inquirer/prompts');
23
- return _inquirerModule;
24
- } catch (err) {
25
- throw new Error(
26
- 'Interactive prompts require @inquirer/prompts. Install with `npm i @inquirer/prompts` or pass --yes / --no-interactive to skip the prompt.'
27
- );
28
- }
29
- }
30
-
31
- // --- color helpers ---
32
-
33
- const NO_COLOR = process.env.NO_COLOR && process.env.NO_COLOR !== '0';
34
- const FORCE = process.env.FORCE_COLOR === '1';
35
- const COLOR_ON = FORCE || (!NO_COLOR && process.stdout.isTTY);
36
-
37
- function id(s) { return String(s); }
38
- export const c = COLOR_ON
39
- ? {
40
- green: pc.green, red: pc.red, yellow: pc.yellow, cyan: pc.cyan,
41
- magenta: pc.magenta, blue: pc.blue, dim: pc.dim, bold: pc.bold,
42
- gray: pc.gray, underline: pc.underline,
43
- }
44
- : {
45
- green: id, red: id, yellow: id, cyan: id, magenta: id, blue: id,
46
- dim: id, bold: id, gray: id, underline: id,
47
- };
48
-
49
- export const icons = {
50
- check: '✓',
51
- cross: '✗',
52
- warn: '⚠',
53
- dot: '•',
54
- arrow: '→',
55
- spinner: ['⠋','⠙','⠹','⠸','⠼','⠴','⠦','⠧','⠇','⠏'],
56
- };
57
-
58
- // --- spinner ---
59
-
60
- export function spinner({ text = '' } = {}) {
61
- const tty = process.stderr.isTTY;
62
- let i = 0;
63
- let current = text;
64
- let timer = null;
65
-
66
- function render() {
67
- process.stderr.write(`\r${c.cyan(icons.spinner[i])} ${current}\x1b[K`);
68
- i = (i + 1) % icons.spinner.length;
69
- }
70
-
71
- if (tty) {
72
- timer = setInterval(render, 80);
73
- render();
74
- } else {
75
- process.stderr.write(`${icons.dot} ${current}\n`);
76
- }
77
-
78
- function clearLine() {
79
- if (tty) process.stderr.write('\r\x1b[K');
80
- }
81
-
82
- return {
83
- update(t) { current = t; if (!tty) process.stderr.write(`${icons.dot} ${t}\n`); },
84
- succeed(t) {
85
- if (timer) clearInterval(timer);
86
- clearLine();
87
- process.stderr.write(`${c.green(icons.check)} ${t ?? current}\n`);
88
- },
89
- fail(t) {
90
- if (timer) clearInterval(timer);
91
- clearLine();
92
- process.stderr.write(`${c.red(icons.cross)} ${t ?? current}\n`);
93
- },
94
- stop() {
95
- if (timer) clearInterval(timer);
96
- clearLine();
97
- },
98
- };
99
- }
100
-
101
- // --- progress bar ---
102
-
103
- export function progress({ total, label = '' } = {}) {
104
- const tty = process.stderr.isTTY;
105
- const width = 24;
106
- let current = 0;
107
- let lastLabel = label;
108
-
109
- function render() {
110
- const pct = total === 0 ? 100 : Math.min(100, Math.round((current / total) * 100));
111
- const filled = Math.round((width * pct) / 100);
112
- const bar = '━'.repeat(filled) + c.dim('━'.repeat(width - filled));
113
- const line = `${c.cyan(bar)} ${pct.toString().padStart(3)}% ${c.dim(`(${current}/${total})`)} ${lastLabel}`;
114
- process.stderr.write(`\r${line}\x1b[K`);
115
- }
116
-
117
- function tick({ label } = {}) {
118
- current++;
119
- if (label !== undefined) lastLabel = label;
120
- if (tty) {
121
- render();
122
- } else if (current === total || current % Math.max(1, Math.floor(total / 10)) === 0) {
123
- // Every ~10% in non-TTY mode
124
- const pct = total === 0 ? 100 : Math.round((current / total) * 100);
125
- process.stderr.write(` ${pct}% ${lastLabel}\n`);
126
- }
127
- }
128
-
129
- function finish(text) {
130
- if (tty) {
131
- process.stderr.write('\r\x1b[K');
132
- }
133
- if (text) process.stderr.write(`${c.green(icons.check)} ${text}\n`);
134
- }
135
-
136
- if (tty) render();
137
- return { tick, finish };
138
- }
139
-
140
- // --- interactive prompts ---
141
-
142
- export async function select(opts) {
143
- if (!process.stdin.isTTY) {
144
- throw new Error('Interactive prompt unavailable: stdin is not a TTY. Pass the value as a flag instead.');
145
- }
146
- const { select: inqSelect } = await loadInquirer();
147
- return inqSelect(opts);
148
- }
149
-
150
- export async function confirm(opts) {
151
- if (!process.stdin.isTTY) {
152
- throw new Error('Interactive prompt unavailable: stdin is not a TTY. Pass --yes to skip confirmation.');
153
- }
154
- const { confirm: inqConfirm } = await loadInquirer();
155
- return inqConfirm(opts);
156
- }
157
-
158
- // --- summary panel ---
159
-
160
- export function summary({ title, rows = [], total, hint }) {
161
- const lines = [];
162
- lines.push(`${c.green(icons.check)} ${c.bold(title)}`);
163
- lines.push('');
164
-
165
- // Compute label column width
166
- const w = Math.max(...rows.map(r => String(r[0]).length), 0);
167
- for (const [label, count, status] of rows) {
168
- const cnt = count > 0 ? c.green(String(count).padStart(4)) : c.dim(String(count).padStart(4));
169
- const tail = status === 'fail' ? c.red(icons.cross) : c.green(icons.check);
170
- lines.push(` ${label.padEnd(w)} ${cnt} ${tail}`);
171
- }
172
-
173
- if (total !== undefined || hint) {
174
- lines.push('');
175
- const totalStr = total !== undefined ? `Total: ${c.bold(total)}` : '';
176
- const hintStr = hint ? c.dim(`· ${hint}`) : '';
177
- lines.push(` ${totalStr}${totalStr && hintStr ? ' ' : ''}${hintStr}`);
178
- }
179
-
180
- return lines.join('\n');
181
- }
182
-
183
- // --- helpers exposed for tests ---
184
-
185
- export const _internal = { COLOR_ON };
1
+ // UI primitives for the CLI: colors, icons, spinner, progress bar,
2
+ // interactive select/confirm prompts, and a summary panel.
3
+ //
4
+ // Design rules:
5
+ // - Respect process.stdout.isTTY: animations only when interactive.
6
+ // In pipes/CI, fall back to linear status text.
7
+ // - Respect NO_COLOR (https://no-color.org) and FORCE_COLOR=1.
8
+ // - Animations write to stderr to keep stdout clean for `--json` mode
9
+ // (the user can still pipe machine-readable output even with spinners).
10
+ // - Zero hidden globals — every primitive is a plain function/class.
11
+
12
+ import pc from 'picocolors';
13
+
14
+ // PERF-16-05: @inquirer/prompts é optionalDependency. Carregamos lazy dentro
15
+ // de select()/confirm() para que (a) modo MCP server e CI não paguem o custo
16
+ // de boot, e (b) `npm install --omit=optional` produza CLI core funcional
17
+ // (apenas comandos interativos falham com mensagem descritiva).
18
+ let _inquirerModule = null;
19
+ async function loadInquirer() {
20
+ if (_inquirerModule) return _inquirerModule;
21
+ try {
22
+ _inquirerModule = await import('@inquirer/prompts');
23
+ return _inquirerModule;
24
+ } catch (err) {
25
+ throw new Error(
26
+ 'Interactive prompts require @inquirer/prompts. Install with `npm i @inquirer/prompts` or pass --yes / --no-interactive to skip the prompt.'
27
+ );
28
+ }
29
+ }
30
+
31
+ // --- color helpers ---
32
+
33
+ const NO_COLOR = process.env.NO_COLOR && process.env.NO_COLOR !== '0';
34
+ const FORCE = process.env.FORCE_COLOR === '1';
35
+ const COLOR_ON = FORCE || (!NO_COLOR && process.stdout.isTTY);
36
+
37
+ function id(s) { return String(s); }
38
+ export const c = COLOR_ON
39
+ ? {
40
+ green: pc.green, red: pc.red, yellow: pc.yellow, cyan: pc.cyan,
41
+ magenta: pc.magenta, blue: pc.blue, dim: pc.dim, bold: pc.bold,
42
+ gray: pc.gray, underline: pc.underline,
43
+ }
44
+ : {
45
+ green: id, red: id, yellow: id, cyan: id, magenta: id, blue: id,
46
+ dim: id, bold: id, gray: id, underline: id,
47
+ };
48
+
49
+ export const icons = {
50
+ check: '✓',
51
+ cross: '✗',
52
+ warn: '⚠',
53
+ dot: '•',
54
+ arrow: '→',
55
+ spinner: ['⠋','⠙','⠹','⠸','⠼','⠴','⠦','⠧','⠇','⠏'],
56
+ };
57
+
58
+ // --- spinner ---
59
+
60
+ export function spinner({ text = '' } = {}) {
61
+ const tty = process.stderr.isTTY;
62
+ let i = 0;
63
+ let current = text;
64
+ let timer = null;
65
+
66
+ function render() {
67
+ process.stderr.write(`\r${c.cyan(icons.spinner[i])} ${current}\x1b[K`);
68
+ i = (i + 1) % icons.spinner.length;
69
+ }
70
+
71
+ if (tty) {
72
+ timer = setInterval(render, 80);
73
+ render();
74
+ } else {
75
+ process.stderr.write(`${icons.dot} ${current}\n`);
76
+ }
77
+
78
+ function clearLine() {
79
+ if (tty) process.stderr.write('\r\x1b[K');
80
+ }
81
+
82
+ return {
83
+ update(t) { current = t; if (!tty) process.stderr.write(`${icons.dot} ${t}\n`); },
84
+ succeed(t) {
85
+ if (timer) clearInterval(timer);
86
+ clearLine();
87
+ process.stderr.write(`${c.green(icons.check)} ${t ?? current}\n`);
88
+ },
89
+ fail(t) {
90
+ if (timer) clearInterval(timer);
91
+ clearLine();
92
+ process.stderr.write(`${c.red(icons.cross)} ${t ?? current}\n`);
93
+ },
94
+ stop() {
95
+ if (timer) clearInterval(timer);
96
+ clearLine();
97
+ },
98
+ };
99
+ }
100
+
101
+ // --- progress bar ---
102
+
103
+ export function progress({ total, label = '' } = {}) {
104
+ const tty = process.stderr.isTTY;
105
+ const width = 24;
106
+ let current = 0;
107
+ let lastLabel = label;
108
+
109
+ function render() {
110
+ const pct = total === 0 ? 100 : Math.min(100, Math.round((current / total) * 100));
111
+ const filled = Math.round((width * pct) / 100);
112
+ const bar = '━'.repeat(filled) + c.dim('━'.repeat(width - filled));
113
+ const line = `${c.cyan(bar)} ${pct.toString().padStart(3)}% ${c.dim(`(${current}/${total})`)} ${lastLabel}`;
114
+ process.stderr.write(`\r${line}\x1b[K`);
115
+ }
116
+
117
+ function tick({ label } = {}) {
118
+ current++;
119
+ if (label !== undefined) lastLabel = label;
120
+ if (tty) {
121
+ render();
122
+ } else if (current === total || current % Math.max(1, Math.floor(total / 10)) === 0) {
123
+ // Every ~10% in non-TTY mode
124
+ const pct = total === 0 ? 100 : Math.round((current / total) * 100);
125
+ process.stderr.write(` ${pct}% ${lastLabel}\n`);
126
+ }
127
+ }
128
+
129
+ function finish(text) {
130
+ if (tty) {
131
+ process.stderr.write('\r\x1b[K');
132
+ }
133
+ if (text) process.stderr.write(`${c.green(icons.check)} ${text}\n`);
134
+ }
135
+
136
+ if (tty) render();
137
+ return { tick, finish };
138
+ }
139
+
140
+ // --- interactive prompts ---
141
+
142
+ export async function select(opts) {
143
+ if (!process.stdin.isTTY) {
144
+ throw new Error('Interactive prompt unavailable: stdin is not a TTY. Pass the value as a flag instead.');
145
+ }
146
+ const { select: inqSelect } = await loadInquirer();
147
+ return inqSelect(opts);
148
+ }
149
+
150
+ export async function confirm(opts) {
151
+ if (!process.stdin.isTTY) {
152
+ throw new Error('Interactive prompt unavailable: stdin is not a TTY. Pass --yes to skip confirmation.');
153
+ }
154
+ const { confirm: inqConfirm } = await loadInquirer();
155
+ return inqConfirm(opts);
156
+ }
157
+
158
+ // --- summary panel ---
159
+
160
+ export function summary({ title, rows = [], total, hint }) {
161
+ const lines = [];
162
+ lines.push(`${c.green(icons.check)} ${c.bold(title)}`);
163
+ lines.push('');
164
+
165
+ // Compute label column width
166
+ const w = Math.max(...rows.map(r => String(r[0]).length), 0);
167
+ for (const [label, count, status] of rows) {
168
+ const cnt = count > 0 ? c.green(String(count).padStart(4)) : c.dim(String(count).padStart(4));
169
+ const tail = status === 'fail' ? c.red(icons.cross) : c.green(icons.check);
170
+ lines.push(` ${label.padEnd(w)} ${cnt} ${tail}`);
171
+ }
172
+
173
+ if (total !== undefined || hint) {
174
+ lines.push('');
175
+ const totalStr = total !== undefined ? `Total: ${c.bold(total)}` : '';
176
+ const hintStr = hint ? c.dim(`· ${hint}`) : '';
177
+ lines.push(` ${totalStr}${totalStr && hintStr ? ' ' : ''}${hintStr}`);
178
+ }
179
+
180
+ return lines.join('\n');
181
+ }
182
+
183
+ // --- helpers exposed for tests ---
184
+
185
+ export const _internal = { COLOR_ON };
@@ -1,149 +1,149 @@
1
- // Install kit-mcp into an IDE's MCP-server config.
2
- //
3
- // Strategies:
4
- // merge-mcpServers-json — read JSON, merge `mcpServers[name]`, write back
5
- // append-toml-snippet — print TOML snippet for the user to paste (Codex)
6
- //
7
- // We never overwrite blindly: existing entries with the same name are replaced
8
- // only if --force is passed, otherwise we abort with a clear message.
9
-
10
- import path from 'node:path';
11
- import fs from 'node:fs/promises';
12
- import os from 'node:os';
13
- import { fileURLToPath } from 'node:url';
14
- import { getTarget, listTargets } from '../core/registry.js';
15
-
16
- const __filename = fileURLToPath(import.meta.url);
17
- const __dirname = path.dirname(__filename);
18
- const REPO_ROOT = path.resolve(__dirname, '../..');
19
-
20
- export async function installMcp(targetId, opts = {}) {
21
- const target = getTarget(targetId);
22
- if (!target.mcpConfig) {
23
- return { ok: false, target: targetId, reason: `${target.label} has no MCP config integration in registry.` };
24
- }
25
-
26
- const scope = opts.scope ?? 'user'; // 'user' | 'project'
27
- const name = opts.name ?? 'kit';
28
- const dryRun = !!opts.dryRun;
29
- const force = !!opts.force;
30
-
31
- const entry = buildServerEntry(opts);
32
- const configPath = resolveConfigPath(target.mcpConfig, scope, opts.projectRoot);
33
- if (!configPath) {
34
- return { ok: false, target: targetId, reason: `Could not resolve config path for scope=${scope}.` };
35
- }
36
-
37
- if (target.mcpConfig.strategy === 'merge-mcpServers-json') {
38
- return await mergeJson(configPath, target.mcpConfig.userKey ?? 'mcpServers', name, entry, { dryRun, force, target: targetId });
39
- }
40
- if (target.mcpConfig.strategy === 'append-toml-snippet') {
41
- return await appendToml(configPath, name, entry, { dryRun, force, target: targetId });
42
- }
43
- return { ok: false, target: targetId, reason: `Unknown strategy: ${target.mcpConfig.strategy}` };
44
- }
45
-
46
- export function listInstallTargets() {
47
- return listTargets().filter(t => t.capabilities.mcpConfig);
48
- }
49
-
50
- // --- helpers ---
51
-
52
- function buildServerEntry(opts) {
53
- // Three modes:
54
- // via=local (default) — point at this clone's bin/mcp.js with the running node
55
- // via=npx — `npx -y @luanpdd/kit-mcp` (portable, works on any machine after publish)
56
- // via=global — `kit-mcp` (assumes user has `npm install -g @luanpdd/kit-mcp`)
57
- // Override anything with explicit --command / --args.
58
- const via = opts.via ?? 'local';
59
- let command, args;
60
-
61
- if (via === 'npx') {
62
- command = 'npx';
63
- args = ['-y', opts.pkg ?? '@luanpdd/kit-mcp'];
64
- } else if (via === 'global') {
65
- command = 'kit-mcp';
66
- args = [];
67
- } else {
68
- command = process.execPath;
69
- args = [path.join(REPO_ROOT, 'bin', 'mcp.js')];
70
- }
71
-
72
- return {
73
- command: opts.command ?? command,
74
- args: opts.args ?? args,
75
- env: opts.env ?? {},
76
- };
77
- }
78
-
79
- function resolveConfigPath(cfg, scope, projectRoot) {
80
- if (scope === 'user' && cfg.userPath) return expandHome(cfg.userPath);
81
- if (scope === 'project' && cfg.path) return path.join(path.resolve(projectRoot ?? process.cwd()), cfg.path);
82
- if (cfg.userPath) return expandHome(cfg.userPath);
83
- if (cfg.path) return path.join(path.resolve(projectRoot ?? process.cwd()), cfg.path);
84
- return null;
85
- }
86
-
87
- function expandHome(p) {
88
- if (p.startsWith('~')) return path.join(os.homedir(), p.slice(1));
89
- return p;
90
- }
91
-
92
- async function mergeJson(filePath, key, name, entry, { dryRun, force, target }) {
93
- let json = {};
94
- try {
95
- const raw = await fs.readFile(filePath, 'utf8');
96
- json = JSON.parse(raw);
97
- } catch (e) {
98
- if (e.code !== 'ENOENT') {
99
- return { ok: false, target, reason: `Failed to parse existing config at ${filePath}: ${e.message}` };
100
- }
101
- }
102
- json[key] ??= {};
103
- if (json[key][name] && !force) {
104
- return {
105
- ok: false, target, configPath: filePath,
106
- reason: `An MCP server named "${name}" already exists in ${filePath}. Re-run with --force to replace, or pass --name <other>.`,
107
- };
108
- }
109
- json[key][name] = entry;
110
-
111
- if (dryRun) {
112
- return { ok: true, target, configPath: filePath, dryRun: true, preview: json };
113
- }
114
- await fs.mkdir(path.dirname(filePath), { recursive: true });
115
- await fs.writeFile(filePath, JSON.stringify(json, null, 2) + '\n', 'utf8');
116
- return { ok: true, target, configPath: filePath, name, entry };
117
- }
118
-
119
- async function appendToml(filePath, name, entry, { dryRun, target }) {
120
- // Codex MCP entries in TOML look like:
121
- // [mcp_servers.kit]
122
- // command = "node"
123
- // args = ["/abs/path/bin/mcp.js"]
124
- const toml = [
125
- `[mcp_servers.${name}]`,
126
- `command = ${JSON.stringify(entry.command)}`,
127
- `args = ${JSON.stringify(entry.args)}`,
128
- Object.keys(entry.env || {}).length
129
- ? `env = { ${Object.entries(entry.env).map(([k, v]) => `${k} = ${JSON.stringify(v)}`).join(', ')} }`
130
- : null,
131
- '',
132
- ].filter(Boolean).join('\n');
133
-
134
- if (dryRun) {
135
- return { ok: true, target, configPath: filePath, dryRun: true, snippet: toml };
136
- }
137
- await fs.mkdir(path.dirname(filePath), { recursive: true });
138
- // Append (Codex tolerates duplicate sections only with [tables.*]; manual review encouraged).
139
- let existing = '';
140
- try { existing = await fs.readFile(filePath, 'utf8'); } catch {}
141
- if (existing.includes(`[mcp_servers.${name}]`)) {
142
- return {
143
- ok: false, target, configPath: filePath,
144
- reason: `[mcp_servers.${name}] already exists in ${filePath}. Edit by hand or pass --name <other>.`,
145
- };
146
- }
147
- await fs.writeFile(filePath, existing + (existing.endsWith('\n') ? '' : '\n') + toml, 'utf8');
148
- return { ok: true, target, configPath: filePath, snippet: toml };
149
- }
1
+ // Install kit-mcp into an IDE's MCP-server config.
2
+ //
3
+ // Strategies:
4
+ // merge-mcpServers-json — read JSON, merge `mcpServers[name]`, write back
5
+ // append-toml-snippet — print TOML snippet for the user to paste (Codex)
6
+ //
7
+ // We never overwrite blindly: existing entries with the same name are replaced
8
+ // only if --force is passed, otherwise we abort with a clear message.
9
+
10
+ import path from 'node:path';
11
+ import fs from 'node:fs/promises';
12
+ import os from 'node:os';
13
+ import { fileURLToPath } from 'node:url';
14
+ import { getTarget, listTargets } from '../core/registry.js';
15
+
16
+ const __filename = fileURLToPath(import.meta.url);
17
+ const __dirname = path.dirname(__filename);
18
+ const REPO_ROOT = path.resolve(__dirname, '../..');
19
+
20
+ export async function installMcp(targetId, opts = {}) {
21
+ const target = getTarget(targetId);
22
+ if (!target.mcpConfig) {
23
+ return { ok: false, target: targetId, reason: `${target.label} has no MCP config integration in registry.` };
24
+ }
25
+
26
+ const scope = opts.scope ?? 'user'; // 'user' | 'project'
27
+ const name = opts.name ?? 'kit';
28
+ const dryRun = !!opts.dryRun;
29
+ const force = !!opts.force;
30
+
31
+ const entry = buildServerEntry(opts);
32
+ const configPath = resolveConfigPath(target.mcpConfig, scope, opts.projectRoot);
33
+ if (!configPath) {
34
+ return { ok: false, target: targetId, reason: `Could not resolve config path for scope=${scope}.` };
35
+ }
36
+
37
+ if (target.mcpConfig.strategy === 'merge-mcpServers-json') {
38
+ return await mergeJson(configPath, target.mcpConfig.userKey ?? 'mcpServers', name, entry, { dryRun, force, target: targetId });
39
+ }
40
+ if (target.mcpConfig.strategy === 'append-toml-snippet') {
41
+ return await appendToml(configPath, name, entry, { dryRun, force, target: targetId });
42
+ }
43
+ return { ok: false, target: targetId, reason: `Unknown strategy: ${target.mcpConfig.strategy}` };
44
+ }
45
+
46
+ export function listInstallTargets() {
47
+ return listTargets().filter(t => t.capabilities.mcpConfig);
48
+ }
49
+
50
+ // --- helpers ---
51
+
52
+ function buildServerEntry(opts) {
53
+ // Three modes:
54
+ // via=local (default) — point at this clone's bin/mcp.js with the running node
55
+ // via=npx — `npx -y @luanpdd/kit-mcp` (portable, works on any machine after publish)
56
+ // via=global — `kit-mcp` (assumes user has `npm install -g @luanpdd/kit-mcp`)
57
+ // Override anything with explicit --command / --args.
58
+ const via = opts.via ?? 'local';
59
+ let command, args;
60
+
61
+ if (via === 'npx') {
62
+ command = 'npx';
63
+ args = ['-y', opts.pkg ?? '@luanpdd/kit-mcp'];
64
+ } else if (via === 'global') {
65
+ command = 'kit-mcp';
66
+ args = [];
67
+ } else {
68
+ command = process.execPath;
69
+ args = [path.join(REPO_ROOT, 'bin', 'mcp.js')];
70
+ }
71
+
72
+ return {
73
+ command: opts.command ?? command,
74
+ args: opts.args ?? args,
75
+ env: opts.env ?? {},
76
+ };
77
+ }
78
+
79
+ function resolveConfigPath(cfg, scope, projectRoot) {
80
+ if (scope === 'user' && cfg.userPath) return expandHome(cfg.userPath);
81
+ if (scope === 'project' && cfg.path) return path.join(path.resolve(projectRoot ?? process.cwd()), cfg.path);
82
+ if (cfg.userPath) return expandHome(cfg.userPath);
83
+ if (cfg.path) return path.join(path.resolve(projectRoot ?? process.cwd()), cfg.path);
84
+ return null;
85
+ }
86
+
87
+ function expandHome(p) {
88
+ if (p.startsWith('~')) return path.join(os.homedir(), p.slice(1));
89
+ return p;
90
+ }
91
+
92
+ async function mergeJson(filePath, key, name, entry, { dryRun, force, target }) {
93
+ let json = {};
94
+ try {
95
+ const raw = await fs.readFile(filePath, 'utf8');
96
+ json = JSON.parse(raw);
97
+ } catch (e) {
98
+ if (e.code !== 'ENOENT') {
99
+ return { ok: false, target, reason: `Failed to parse existing config at ${filePath}: ${e.message}` };
100
+ }
101
+ }
102
+ json[key] ??= {};
103
+ if (json[key][name] && !force) {
104
+ return {
105
+ ok: false, target, configPath: filePath,
106
+ reason: `An MCP server named "${name}" already exists in ${filePath}. Re-run with --force to replace, or pass --name <other>.`,
107
+ };
108
+ }
109
+ json[key][name] = entry;
110
+
111
+ if (dryRun) {
112
+ return { ok: true, target, configPath: filePath, dryRun: true, preview: json };
113
+ }
114
+ await fs.mkdir(path.dirname(filePath), { recursive: true });
115
+ await fs.writeFile(filePath, JSON.stringify(json, null, 2) + '\n', 'utf8');
116
+ return { ok: true, target, configPath: filePath, name, entry };
117
+ }
118
+
119
+ async function appendToml(filePath, name, entry, { dryRun, target }) {
120
+ // Codex MCP entries in TOML look like:
121
+ // [mcp_servers.kit]
122
+ // command = "node"
123
+ // args = ["/abs/path/bin/mcp.js"]
124
+ const toml = [
125
+ `[mcp_servers.${name}]`,
126
+ `command = ${JSON.stringify(entry.command)}`,
127
+ `args = ${JSON.stringify(entry.args)}`,
128
+ Object.keys(entry.env || {}).length
129
+ ? `env = { ${Object.entries(entry.env).map(([k, v]) => `${k} = ${JSON.stringify(v)}`).join(', ')} }`
130
+ : null,
131
+ '',
132
+ ].filter(Boolean).join('\n');
133
+
134
+ if (dryRun) {
135
+ return { ok: true, target, configPath: filePath, dryRun: true, snippet: toml };
136
+ }
137
+ await fs.mkdir(path.dirname(filePath), { recursive: true });
138
+ // Append (Codex tolerates duplicate sections only with [tables.*]; manual review encouraged).
139
+ let existing = '';
140
+ try { existing = await fs.readFile(filePath, 'utf8'); } catch {}
141
+ if (existing.includes(`[mcp_servers.${name}]`)) {
142
+ return {
143
+ ok: false, target, configPath: filePath,
144
+ reason: `[mcp_servers.${name}] already exists in ${filePath}. Edit by hand or pass --name <other>.`,
145
+ };
146
+ }
147
+ await fs.writeFile(filePath, existing + (existing.endsWith('\n') ? '' : '\n') + toml, 'utf8');
148
+ return { ok: true, target, configPath: filePath, snippet: toml };
149
+ }