@luanpdd/kit-mcp 1.28.0 → 1.29.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.
@@ -1,6 +1,6 @@
1
1
  {
2
- "version": "1.28.0",
3
- "timestamp": "2026-05-12T12:13:30.244Z",
2
+ "version": "1.29.0",
3
+ "timestamp": "2026-05-12T13:38:43.278Z",
4
4
  "files": {
5
5
  "COMANDOS.md": "d24ec61a6ec35db314cc5f2ae287bfb927b794789c8f1d558c55862f5e6534b2",
6
6
  "COMPATIBILITY.md": "794e336a87045cdf0161785b9a7a0975a49abbd80bdd816b8852251fcc8126ca",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@luanpdd/kit-mcp",
3
- "version": "1.28.0",
3
+ "version": "1.29.0",
4
4
  "description": "Generic infrastructure to ship YOUR personal kit of agents/commands/skills as an MCP server, with cross-IDE sync (Claude Code, Cursor, Codex, Gemini, Windsurf, Antigravity, Copilot, Trae).",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cli/index.js CHANGED
@@ -708,6 +708,39 @@ async function runDoctorChecks(projectRoot) {
708
708
  : 'enabled (default) — sidecar starts when MCP server boots',
709
709
  fix: noUi ? 'unset KIT_MCP_NO_UI if you want live tool-call visibility' : undefined });
710
710
 
711
+ // 10. (v1.29) auto-install drift check — is .claude/.kit-mcp-version aligned
712
+ // with the running kit-mcp package version?
713
+ try {
714
+ const versionMarker = path.join(projectRoot, '.claude', '.kit-mcp-version');
715
+ const restartMarker = path.join(projectRoot, '.claude', '.kit-mcp-restart-required');
716
+ let installedVersion = null;
717
+ try { installedVersion = fs.readFileSync(versionMarker, 'utf8').trim(); } catch { /* not installed */ }
718
+ const currentVersion = readPkgVersion();
719
+
720
+ if (!installedVersion) {
721
+ checks.push({ label: 'auto-install', status: 'warn',
722
+ detail: '.claude/.kit-mcp-version not found — kit not auto-installed in this project',
723
+ fix: 'call kit:auto-install MCP tool, or run: kit init' });
724
+ } else if (installedVersion !== currentVersion) {
725
+ checks.push({ label: 'auto-install', status: 'warn',
726
+ detail: `kit installed v${installedVersion}, MCP server is v${currentVersion}`,
727
+ fix: 'call kit:auto-install (idempotent) or rerun: kit sync claude-code' });
728
+ } else {
729
+ checks.push({ label: 'auto-install', status: 'pass',
730
+ detail: `v${installedVersion} (in sync)` });
731
+ }
732
+
733
+ if (fs.existsSync(restartMarker)) {
734
+ let payload = {};
735
+ try { payload = JSON.parse(fs.readFileSync(restartMarker, 'utf8')); } catch { /* malformed */ }
736
+ checks.push({ label: 'restart pending', status: 'warn',
737
+ detail: payload.reason
738
+ ? `${payload.reason} (written ${payload.writtenAt || 'unknown'})`
739
+ : 'restart marker present — IDE not yet reloaded since last auto-install',
740
+ fix: 'restart your IDE session, then call kit:ack-restart MCP tool (or just close/reopen)' });
741
+ }
742
+ } catch { /* .claude/ check is best-effort */ }
743
+
711
744
  return checks;
712
745
  }
713
746
 
@@ -34,11 +34,16 @@ import { wrapProgressForUi } from '../ui/wrapper.js';
34
34
  import { incrementInvocation, recordLatency, snapshot as metricsSnapshot, persistSnapshot } from '../core/metrics.js';
35
35
  import { logEvent } from '../core/logger.js';
36
36
  import { notify, isNotifyEnabled } from '../core/notify.js';
37
+ // Note: roots.js is imported dynamically inside handlers that need it
38
+ // (handleAutoInstall, handleAckRestart) — keeps boot path minimal.
37
39
 
38
40
  const TOOLS = [
39
41
  {
40
42
  name: 'kit',
41
- description: 'Browse the personal kit: agents, commands, skills.',
43
+ // Phase 170 (v1.29): description enriched with trigger keywords so MCP
44
+ // hosts route here on relevant intents even in MCP-pure mode (before
45
+ // auto-install made .claude/ native). Keep under 1024 chars (host limit).
46
+ description: 'Browse the personal kit: 66 agents, 89 commands, 76 skills. Call this when the user mentions Supabase (RLS, branching, migrations, Edge Functions, Custom Claims, Postgres Roles, Storage, Realtime, pgvector), multi-tenant SaaS, agentic harness, characterization tests, legacy refactor, observability (SLO, golden signals, error budgets), DDIA topics (consistency, replication lag, schema evolution), SRE (postmortems, toil, PRR), CI/CD (hermetic builds, pipelines), or any workflow that benefits from the canonical patterns. Use action=search to discover, action=get to read the full prompt/skill.',
42
47
  inputSchema: {
43
48
  type: 'object',
44
49
  properties: {
@@ -145,6 +150,37 @@ const TOOLS = [
145
150
  properties: {},
146
151
  },
147
152
  },
153
+ {
154
+ // Phase 167 (v1.29): auto-sync the kit content into the host project's
155
+ // .claude/ (or equivalent) directory so agents become real subagent_types,
156
+ // skills get native auto-trigger, and commands appear as slash-commands.
157
+ // Idempotent — re-runs are no-ops if .claude/.kit-mcp-version matches the
158
+ // running server's package version. Permission-gated by the host.
159
+ name: 'auto-install',
160
+ description: 'IMPORTANT for first contact: project kit/ into the host\'s native layout (.claude/agents/, skills/, commands/) so 66 agents become real subagent_types in the Agent tool, 76 skills get native auto-trigger via descriptions, and 89 commands appear as /slash-commands in the IDE. Idempotent — re-running is a no-op if already in sync. Run once per project on first kit-mcp contact; restart the IDE session after to load the new agents/skills/commands. After restart, call ack-restart to clear the marker.',
161
+ inputSchema: {
162
+ type: 'object',
163
+ properties: {
164
+ action: { type: 'string', enum: ['install', 'check'], description: 'install: write files. check: read-only drift report. Default: install.' },
165
+ target: { type: 'string', description: 'IDE id (claude-code, cursor, …). Defaults to claude-code.' },
166
+ projectRoot: { type: 'string', description: 'Override the auto-detected project root. Usually omitted — server reads it from MCP roots capability.' },
167
+ force: { type: 'boolean', description: 'Re-write even if .kit-mcp-version already matches. Default: false.' },
168
+ },
169
+ },
170
+ },
171
+ {
172
+ // Phase 168 (v1.29): acknowledge the restart-required marker after the
173
+ // user reloads the IDE session. Removes .claude/.kit-mcp-restart-required
174
+ // so doctor stops flagging it.
175
+ name: 'ack-restart',
176
+ description: 'Acknowledge that the IDE session was restarted after kit:auto-install. Removes the .kit-mcp-restart-required marker so kit:doctor stops warning. Called automatically by the harness when it detects the marker after reload, or manually by the user.',
177
+ inputSchema: {
178
+ type: 'object',
179
+ properties: {
180
+ projectRoot: { type: 'string' },
181
+ },
182
+ },
183
+ },
148
184
  ];
149
185
 
150
186
  // DRIFT-13-03: read version from package.json at module load (NOT inside
@@ -318,6 +354,163 @@ async function handleInstall(args) {
318
354
  let _lastAutoPersistTs = 0;
319
355
  const AUTO_PERSIST_THROTTLE_MS = 1000;
320
356
 
357
+ // Phase 167 (v1.29): auto-install handler.
358
+ // Bridges MCP → host-native integration by writing kit/ files into .claude/
359
+ // (or whatever the target IDE expects). Idempotent via .kit-mcp-version marker.
360
+ // Phase 168 hooks add the restart_recommended signal to the result.
361
+ async function handleAutoInstall(args) {
362
+ const action = args.action || 'install';
363
+ const target = args.target || 'claude-code';
364
+ const force = !!args.force;
365
+
366
+ // Resolve projectRoot: explicit arg > cwd fallback. (Future v1.30 will add
367
+ // MCP `roots` capability consumer for a tighter projectRoot signal — for now
368
+ // we use cwd to keep the boot path race-free with the SDK init handshake.)
369
+ let projectRoot = args.projectRoot;
370
+ const _rootsSource = projectRoot ? 'explicit' : 'cwd';
371
+ if (!projectRoot) projectRoot = process.cwd();
372
+
373
+ // SEC-14-03: validate project root (allowlist-of-1 — must be a real dir).
374
+ const guard = await validateProjectRoot(projectRoot);
375
+ if (!guard.ok) {
376
+ return { ok: false, reason: guard.reason, projectRoot, rootsSource: _rootsSource };
377
+ }
378
+ projectRoot = guard.resolvedPath;
379
+
380
+ const fs = await import('node:fs/promises');
381
+ const path = await import('node:path');
382
+ const markerPath = path.join(projectRoot, '.claude', '.kit-mcp-version');
383
+
384
+ // Read current marker if present.
385
+ let currentVersion = null;
386
+ try {
387
+ currentVersion = (await fs.readFile(markerPath, 'utf8')).trim();
388
+ } catch { /* not installed yet */ }
389
+
390
+ const targetVersion = PKG_VERSION;
391
+ const inSync = currentVersion === targetVersion;
392
+
393
+ // Phase 167 — action=check: read-only drift report.
394
+ if (action === 'check') {
395
+ return {
396
+ ok: true,
397
+ action: 'check',
398
+ target,
399
+ projectRoot,
400
+ rootsSource: _rootsSource,
401
+ installedVersion: currentVersion,
402
+ currentVersion: targetVersion,
403
+ inSync,
404
+ restartRecommended: false,
405
+ };
406
+ }
407
+
408
+ // action=install: skip if in sync and not forced.
409
+ if (inSync && !force) {
410
+ return {
411
+ ok: true,
412
+ action: 'install',
413
+ target,
414
+ projectRoot,
415
+ rootsSource: _rootsSource,
416
+ version: targetVersion,
417
+ skipped: true,
418
+ reason: 'already in sync',
419
+ restartRecommended: false,
420
+ };
421
+ }
422
+
423
+ // Run the sync.
424
+ let syncResult;
425
+ try {
426
+ syncResult = await syncTo(target, { projectRoot, mode: 'reference', dryRun: false });
427
+ } catch (e) {
428
+ return {
429
+ ok: false,
430
+ action: 'install',
431
+ target,
432
+ projectRoot,
433
+ rootsSource: _rootsSource,
434
+ reason: `sync_failed: ${e.message}`,
435
+ };
436
+ }
437
+
438
+ // Write/update marker file (.claude/.kit-mcp-version).
439
+ try {
440
+ await fs.mkdir(path.dirname(markerPath), { recursive: true });
441
+ await fs.writeFile(markerPath, targetVersion + '\n', 'utf8');
442
+ } catch (e) {
443
+ // Marker is best-effort — sync already succeeded. Just warn.
444
+ process.stderr.write(`[kit-mcp] auto-install marker write failed: ${e.message}\n`);
445
+ }
446
+
447
+ // Phase 168 (v1.29): write .kit-mcp-restart-required so doctor/host can detect
448
+ // pending restart even if the user closes/reopens kit-mcp without restarting IDE.
449
+ try {
450
+ const restartMarker = path.join(projectRoot, '.claude', '.kit-mcp-restart-required');
451
+ const payload = JSON.stringify({
452
+ version: targetVersion,
453
+ previousVersion: currentVersion,
454
+ writtenAt: new Date().toISOString(),
455
+ reason: currentVersion
456
+ ? `Kit updated ${currentVersion} → ${targetVersion}`
457
+ : 'Initial kit install',
458
+ }, null, 2);
459
+ await fs.writeFile(restartMarker, payload + '\n', 'utf8');
460
+ } catch (e) {
461
+ process.stderr.write(`[kit-mcp] restart marker write failed: ${e.message}\n`);
462
+ }
463
+
464
+ return {
465
+ ok: true,
466
+ action: 'install',
467
+ target,
468
+ projectRoot,
469
+ rootsSource: _rootsSource,
470
+ version: targetVersion,
471
+ previousVersion: currentVersion,
472
+ written: (syncResult.written || []).length,
473
+ restartRecommended: true,
474
+ _kit_action: 'session_restart_recommended',
475
+ _kit_reason: currentVersion
476
+ ? `Kit updated from ${currentVersion} to ${targetVersion} — restart the IDE session so agents/skills/commands reload.`
477
+ : `Kit installed (v${targetVersion}) into ${path.join('.claude', '')} — restart the IDE session for native subagent_type + slash-command + skill auto-trigger integration.`,
478
+ };
479
+ }
480
+
481
+ // Phase 168 (v1.29): acknowledge that the IDE was restarted after a kit:auto-install.
482
+ // Removes the .kit-mcp-restart-required marker. Read by kit:doctor (Phase 171)
483
+ // to stop flagging "pending restart".
484
+ async function handleAckRestart(args) {
485
+ let projectRoot = args.projectRoot || process.cwd();
486
+
487
+ const guard = await validateProjectRoot(projectRoot);
488
+ if (!guard.ok) return { ok: false, reason: guard.reason, projectRoot };
489
+ projectRoot = guard.resolvedPath;
490
+
491
+ const fs = await import('node:fs/promises');
492
+ const path = await import('node:path');
493
+ const restartMarker = path.join(projectRoot, '.claude', '.kit-mcp-restart-required');
494
+
495
+ let acked = false;
496
+ try {
497
+ await fs.unlink(restartMarker);
498
+ acked = true;
499
+ } catch (e) {
500
+ if (e.code !== 'ENOENT') {
501
+ return { ok: false, reason: `unlink_failed: ${e.message}`, projectRoot };
502
+ }
503
+ // ENOENT — nothing to ack, already clean. Not an error.
504
+ }
505
+
506
+ return {
507
+ ok: true,
508
+ projectRoot,
509
+ acked,
510
+ reason: acked ? 'restart marker removed' : 'no restart marker present (nothing to ack)',
511
+ };
512
+ }
513
+
321
514
  async function handleMetricsSnapshot() {
322
515
  const payload = metricsSnapshot();
323
516
  const now = Date.now();
@@ -336,13 +529,22 @@ async function handleMetricsSnapshot() {
336
529
  }
337
530
 
338
531
  const HANDLERS = {
339
- kit: handleKit,
340
- sync: handleSync,
341
- 'reverse-sync': handleReverseSync,
342
- gates: handleGates,
343
- forensics: handleForensics,
344
- install: handleInstall,
532
+ kit: handleKit,
533
+ sync: handleSync,
534
+ 'reverse-sync': handleReverseSync,
535
+ gates: handleGates,
536
+ forensics: handleForensics,
537
+ install: handleInstall,
345
538
  'metrics-snapshot': handleMetricsSnapshot,
539
+ 'auto-install': handleAutoInstall,
540
+ 'ack-restart': handleAckRestart,
541
+ };
542
+
543
+ // Phase 167+168 test affordances — exported for unit coverage.
544
+ // Production callers should go through the MCP dispatch (HANDLERS map).
545
+ export const __TEST_HANDLERS = {
546
+ handleAutoInstall,
547
+ handleAckRestart,
346
548
  };
347
549
 
348
550
  function slim(x) {
@@ -365,7 +567,7 @@ function slimTerse(x) {
365
567
  export async function createServer() {
366
568
  const server = new Server(
367
569
  { name: 'kit-mcp', version: PKG_VERSION },
368
- { capabilities: { tools: {} } }
570
+ { capabilities: { tools: {} } },
369
571
  );
370
572
 
371
573
  server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
@@ -457,6 +659,7 @@ export async function startStdio() {
457
659
  const transport = new StdioServerTransport();
458
660
  await server.connect(transport);
459
661
 
662
+
460
663
  // SRE-20-02 (Phase 105): pre-warm the kit cache to push MCP dispatch p95
461
664
  // below 100ms. Without this, the very first tools/call against `kit` pays
462
665
  // the full disk read (~144ms baseline on the v1.17 reference machine; ~96ms
@@ -0,0 +1,124 @@
1
+ // src/mcp-server/roots.js — MCP `roots` capability consumer.
2
+ //
3
+ // Phase 166 (v1.29). The MCP spec lets clients (hosts like Claude Code,
4
+ // Cursor) declare workspace roots via `roots/list`. Servers can query this
5
+ // to learn the project directory without guessing from `process.cwd()`.
6
+ //
7
+ // Flow:
8
+ // 1. Server declares capability `roots: { listChanged: true }` on init.
9
+ // 2. After `initialized` notification, server sends `roots/list` request.
10
+ // 3. Cache the response in memory.
11
+ // 4. Listen for `notifications/roots/list_changed` to refresh cache.
12
+ //
13
+ // Discipline:
14
+ // - Failures are silent — fallback to process.cwd() if host doesn't support.
15
+ // - Cache survives the session; not persisted to disk.
16
+ // - No side effects (the auto-sync that USES the roots lives in another module).
17
+
18
+ import { ListRootsRequestSchema, RootsListChangedNotificationSchema } from '@modelcontextprotocol/sdk/types.js';
19
+ import { fileURLToPath } from 'node:url';
20
+
21
+ // Module-level cache. Keyed by server instance via closure in attachRootsCapability.
22
+ let cachedRoots = null;
23
+ let supportLevel = 'unknown'; // 'supported' | 'unsupported' | 'unknown'
24
+
25
+ /**
26
+ * Convert a file:// URI to a local filesystem path. Returns null if invalid.
27
+ * @param {string} uri
28
+ */
29
+ function uriToPath(uri) {
30
+ if (typeof uri !== 'string') return null;
31
+ if (!uri.startsWith('file://')) return null;
32
+ try {
33
+ return fileURLToPath(uri);
34
+ } catch {
35
+ return null;
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Request roots/list from the connected client. Caches the result.
41
+ * Returns array of {uri, name, path} entries, or [] on failure.
42
+ * @param {import('@modelcontextprotocol/sdk/server/index.js').Server} server
43
+ */
44
+ export async function fetchRoots(server) {
45
+ try {
46
+ const result = await server.request(
47
+ { method: 'roots/list' },
48
+ // The SDK validates the response shape with this schema
49
+ // eslint-disable-next-line no-undef
50
+ // @ts-ignore — runtime-only import shape
51
+ undefined,
52
+ );
53
+ // Defensive: SDK may return either {roots: [...]} or the bare array depending on version
54
+ const roots = Array.isArray(result?.roots) ? result.roots
55
+ : Array.isArray(result) ? result
56
+ : [];
57
+ const normalized = roots.map((r) => ({
58
+ uri: r.uri,
59
+ name: r.name,
60
+ path: uriToPath(r.uri),
61
+ })).filter((r) => r.path);
62
+ cachedRoots = normalized;
63
+ supportLevel = 'supported';
64
+ return normalized;
65
+ } catch (e) {
66
+ // Client doesn't support roots, or returned an error.
67
+ supportLevel = 'unsupported';
68
+ cachedRoots = [];
69
+ return [];
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Attach roots capability handlers to the server. Must be called BEFORE
75
+ * server.connect(). Sets up the list_changed listener so cache stays fresh.
76
+ * @param {import('@modelcontextprotocol/sdk/server/index.js').Server} server
77
+ */
78
+ export function attachRootsCapability(server) {
79
+ // Listen for client telling us roots changed — invalidate cache.
80
+ server.setNotificationHandler(RootsListChangedNotificationSchema, async () => {
81
+ // Re-fetch on next access via fetchRoots(). Mark cache stale.
82
+ cachedRoots = null;
83
+ // Eager refresh — best-effort.
84
+ try { await fetchRoots(server); } catch { /* swallow */ }
85
+ });
86
+ }
87
+
88
+ /**
89
+ * Get the currently-cached roots, or trigger a fetch if not yet cached.
90
+ * Returns array of {uri, name, path}.
91
+ * @param {import('@modelcontextprotocol/sdk/server/index.js').Server} server
92
+ */
93
+ export async function getRoots(server) {
94
+ if (cachedRoots !== null) return cachedRoots;
95
+ return await fetchRoots(server);
96
+ }
97
+
98
+ /**
99
+ * Get the primary project root path. Falls back to process.cwd() if no
100
+ * roots were declared by the client. Synchronous accessor for use AFTER
101
+ * fetchRoots() has been called at least once.
102
+ */
103
+ export function getPrimaryProjectRoot() {
104
+ if (cachedRoots && cachedRoots.length > 0) {
105
+ return cachedRoots[0].path;
106
+ }
107
+ return process.cwd();
108
+ }
109
+
110
+ /**
111
+ * Diagnostic helper — exposes whether host declared roots support.
112
+ * Values: 'supported' | 'unsupported' | 'unknown'.
113
+ */
114
+ export function getRootsSupportLevel() {
115
+ return supportLevel;
116
+ }
117
+
118
+ /**
119
+ * Reset state. Test helper only.
120
+ */
121
+ export function __resetForTests() {
122
+ cachedRoots = null;
123
+ supportLevel = 'unknown';
124
+ }