vacumify-mcp 1.1.0 → 1.2.1

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,98 +1,686 @@
1
1
  #!/usr/bin/env node
2
+ 'use strict';
2
3
 
3
- const { spawn, execSync } = require('child_process');
4
4
  const fs = require('fs');
5
5
  const path = require('path');
6
+ const readline = require('readline');
7
+ const scanner = require('../lib/scanner');
6
8
 
7
- function findVacumifyExecutable() {
8
- // 1. Explicit env variable
9
- if (process.env.VACUMIFY_PATH && fs.existsSync(process.env.VACUMIFY_PATH)) {
10
- return process.env.VACUMIFY_PATH;
11
- }
12
-
13
- // 2. Relative paths within the Vacumify repo
14
- const candidates = [
15
- path.resolve(__dirname, '../../StorageCleaner/StorageCleaner/bin/Release/net10.0-windows/win-x64/publish/Vacumify.exe'),
16
- path.resolve(__dirname, '../../StorageCleaner/StorageCleaner/bin/Release/net10.0-windows/win-x64/Vacumify.exe'),
17
- path.resolve(__dirname, '../../StorageCleaner/StorageCleaner/bin/Debug/net10.0-windows/Vacumify.exe'),
18
- path.resolve(process.cwd(), 'Vacumify.exe')
19
- ];
9
+ const SERVER_NAME = 'vacumify';
10
+ const SERVER_VERSION = '1.2.1';
11
+ const PROTOCOL_VERSION = '2024-11-05';
12
+ const MS_PER_DAY = 24 * 60 * 60 * 1000;
20
13
 
21
- for (const cand of candidates) {
22
- if (fs.existsSync(cand)) return cand;
14
+ const TOOLS = [
15
+ {
16
+ name: 'vacumify_scan',
17
+ description:
18
+ 'Scan a local folder to identify large files, duplicate file groups, forgotten files, and developer caches with Active/Dormant/Abandoned project context. Read-only operation.',
19
+ inputSchema: {
20
+ type: 'object',
21
+ properties: {
22
+ path: {
23
+ type: 'string',
24
+ description: 'Directory path to scan (e.g. C:\\Users\\Name\\Downloads or /home/user/Projects).'
25
+ },
26
+ includeHidden: {
27
+ type: 'boolean',
28
+ description: 'Include hidden files and folders (default: false).'
29
+ },
30
+ minDuplicateBytes: {
31
+ type: 'integer',
32
+ description: 'Minimum file size in bytes for duplicate detection (default: 102400 = 100 KB).'
33
+ },
34
+ minLargeFileBytes: {
35
+ type: 'integer',
36
+ description: 'Minimum file size in bytes to flag as a large file (default: 104857600 = 100 MB).'
37
+ },
38
+ forgottenDays: {
39
+ type: 'integer',
40
+ description: 'Days since last access/modification to flag a file as forgotten (default: 90).'
41
+ }
42
+ },
43
+ required: ['path']
44
+ }
45
+ },
46
+ {
47
+ name: 'vacumify_get_dev_caches',
48
+ description:
49
+ 'Scan a workspace or Projects directory specifically for reclaimable developer caches (node_modules, .NET bin/obj, .venv, Rust/Maven target, __pycache__, Gradle, .next, dist, build) with Active/Dormant/Abandoned git activity status.',
50
+ inputSchema: {
51
+ type: 'object',
52
+ properties: {
53
+ path: {
54
+ type: 'string',
55
+ description: 'Root workspace or Projects directory path to scan.'
56
+ },
57
+ olderThanDays: {
58
+ type: 'integer',
59
+ description: 'Optional filter: only return caches in projects untouched for at least N days.'
60
+ }
61
+ },
62
+ required: ['path']
63
+ }
64
+ },
65
+ {
66
+ name: 'vacumify_get_safe_junk',
67
+ description:
68
+ 'Identify safe-to-delete junk candidates in a folder: redundant duplicate copies (preserving original) and obsolete installers (.msi/.exe/.dmp/old .log untouched >30 days).',
69
+ inputSchema: {
70
+ type: 'object',
71
+ properties: {
72
+ path: {
73
+ type: 'string',
74
+ description: 'Directory path to analyze.'
75
+ }
76
+ },
77
+ required: ['path']
78
+ }
79
+ },
80
+ {
81
+ name: 'vacumify_recycle_items',
82
+ description:
83
+ 'Safely move specified files or folders into the OS Recycle Bin / System Trash. NEVER permanently deletes files, and blocks critical OS/system paths.',
84
+ inputSchema: {
85
+ type: 'object',
86
+ properties: {
87
+ paths: {
88
+ type: 'array',
89
+ items: { type: 'string' },
90
+ description: 'List of absolute file or directory paths to move to Recycle Bin / Trash.'
91
+ },
92
+ dryRun: {
93
+ type: 'boolean',
94
+ description: 'If true, preview what would be recycled without moving any files (default: false).'
95
+ }
96
+ },
97
+ required: ['paths']
98
+ }
23
99
  }
100
+ ];
24
101
 
25
- // 3. Check ~/.vacumify auto-install directory
26
- const userHome = process.env.USERPROFILE || process.env.HOME || '';
27
- const autoInstallDir = path.join(userHome, '.vacumify');
28
- const autoInstallExe = path.join(autoInstallDir, 'Vacumify.exe');
29
- if (fs.existsSync(autoInstallExe)) return autoInstallExe;
30
-
31
- // 4. Search PATH on Windows
32
- if (process.platform === 'win32') {
33
- try {
34
- const stdout = execSync('where.exe Vacumify.exe', { stdio: ['pipe', 'pipe', 'ignore'], encoding: 'utf8' });
35
- const firstLine = stdout.trim().split(/\r?\n/)[0];
36
- if (firstLine && fs.existsSync(firstLine)) return firstLine;
37
- } catch (_) {}
102
+ const PROMPTS = [
103
+ {
104
+ name: 'audit-storage',
105
+ description: 'Comprehensive storage audit covering dev caches, duplicates, forgotten files, and large files.',
106
+ arguments: [
107
+ {
108
+ name: 'path',
109
+ description: 'Directory path to audit (optional; defaults to asking or current workspace).',
110
+ required: false
111
+ }
112
+ ]
113
+ },
114
+ {
115
+ name: 'duplicates',
116
+ description: 'Find duplicate file groups and safely recycle redundant copies.',
117
+ arguments: [
118
+ {
119
+ name: 'path',
120
+ description: 'Directory path to scan for duplicates (optional).',
121
+ required: false
122
+ }
123
+ ]
124
+ },
125
+ {
126
+ name: 'forgotten-files',
127
+ description: 'Find untouched/forgotten files older than a configurable day threshold (default 90 days).',
128
+ arguments: [
129
+ {
130
+ name: 'path',
131
+ description: 'Directory path to inspect (optional).',
132
+ required: false
133
+ },
134
+ {
135
+ name: 'days',
136
+ description: 'Inactivity threshold in days (default: 90).',
137
+ required: false
138
+ }
139
+ ]
140
+ },
141
+ {
142
+ name: 'large-files',
143
+ description: 'Find oversized files exceeding a size threshold (default 100 MB).',
144
+ arguments: [
145
+ {
146
+ name: 'path',
147
+ description: 'Directory path to inspect (optional).',
148
+ required: false
149
+ },
150
+ {
151
+ name: 'minSizeMb',
152
+ description: 'Minimum file size in MB (default: 100).',
153
+ required: false
154
+ }
155
+ ]
156
+ },
157
+ {
158
+ name: 'dev-caches',
159
+ description: 'Scan workspace for bloated developer caches scored by Active/Dormant/Abandoned project activity.',
160
+ arguments: [
161
+ {
162
+ name: 'path',
163
+ description: 'Workspace or Projects directory path (optional).',
164
+ required: false
165
+ },
166
+ {
167
+ name: 'olderThanDays',
168
+ description: 'Optional minimum days untouched filter.',
169
+ required: false
170
+ }
171
+ ]
38
172
  }
173
+ ];
174
+
175
+ function sendMessage(msg) {
176
+ process.stdout.write(JSON.stringify(msg) + '\n');
177
+ }
39
178
 
40
- return null;
179
+ function sendResult(id, result) {
180
+ sendMessage({ jsonrpc: '2.0', id, result });
41
181
  }
42
182
 
43
- function downloadAndExtractRelease() {
44
- if (process.platform !== 'win32') {
45
- console.error('[vacumify-mcp] Vacumify currently supports Windows (x64).');
46
- process.exit(1);
183
+ function sendError(id, code, message, data) {
184
+ const err = { code, message };
185
+ if (data !== undefined) err.data = data;
186
+ sendMessage({ jsonrpc: '2.0', id, error: err });
187
+ }
188
+
189
+ function toolTextResult(payload, isError = false) {
190
+ return {
191
+ content: [
192
+ {
193
+ type: 'text',
194
+ text: typeof payload === 'string' ? payload : JSON.stringify(payload, null, 2)
195
+ }
196
+ ],
197
+ ...(isError ? { isError: true } : {})
198
+ };
199
+ }
200
+
201
+ function resolveValidDir(inputPath) {
202
+ if (!inputPath || typeof inputPath !== 'string' || !inputPath.trim()) {
203
+ throw new Error('Missing required "path" argument.');
47
204
  }
205
+ const resolved = path.resolve(inputPath.trim());
206
+ if (!fs.existsSync(resolved)) {
207
+ throw new Error(`Directory not found: ${resolved}`);
208
+ }
209
+ const stat = fs.statSync(resolved);
210
+ if (!stat.isDirectory()) {
211
+ throw new Error(`Path is not a directory: ${resolved}`);
212
+ }
213
+ return resolved;
214
+ }
48
215
 
49
- const userHome = process.env.USERPROFILE || process.env.HOME || '';
50
- const autoInstallDir = path.join(userHome, '.vacumify');
51
- const autoInstallExe = path.join(autoInstallDir, 'Vacumify.exe');
52
- const url = 'https://github.com/kuroi17/Vacumify/releases/latest/download/Vacumify-win-x64.zip';
216
+ function enrichActivity(targetPath, fallbackMs) {
217
+ const act = scanner.getProjectActivity(targetPath, fallbackMs);
218
+ return {
219
+ activityStatus: act.status,
220
+ daysUntouched: act.daysUntouched
221
+ };
222
+ }
53
223
 
54
- console.error('[vacumify-mcp] Vacumify.exe not found locally. Downloading latest release from GitHub...');
224
+ async function handleVacumifyScan(args) {
225
+ const targetPath = resolveValidDir(args.path);
226
+ const includeHidden = Boolean(args.includeHidden);
227
+ const minDuplicateBytes = Number.isFinite(args.minDuplicateBytes)
228
+ ? Math.max(1, Number(args.minDuplicateBytes))
229
+ : 100 * 1024;
230
+ const minLargeFileBytes = Number.isFinite(args.minLargeFileBytes)
231
+ ? Math.max(1, Number(args.minLargeFileBytes))
232
+ : 100 * 1024 * 1024;
233
+ const forgottenDays = Number.isFinite(args.forgottenDays)
234
+ ? Math.max(1, Number(args.forgottenDays))
235
+ : 90;
55
236
 
56
- try {
57
- if (!fs.existsSync(autoInstallDir)) fs.mkdirSync(autoInstallDir, { recursive: true });
58
- const zipPath = path.join(autoInstallDir, 'Vacumify-win-x64.zip');
237
+ const result = await scanner.scanDirectory(targetPath, {
238
+ includeHidden,
239
+ minDuplicateBytes,
240
+ fastLargeSampling: true
241
+ });
242
+
243
+ const nowMs = Date.now();
244
+ const forgottenCutoffMs = nowMs - forgottenDays * MS_PER_DAY;
245
+
246
+ const topLargeFiles = result.files
247
+ .filter((f) => f.size >= minLargeFileBytes)
248
+ .sort((a, b) => b.size - a.size)
249
+ .slice(0, 25)
250
+ .map((f) => ({
251
+ path: f.path,
252
+ name: f.name,
253
+ size: f.size,
254
+ sizeFormatted: scanner.formatBytes(f.size),
255
+ lastWrite: scanner.formatDate(f.lastWriteMs),
256
+ lastAccess: scanner.formatDate(f.lastAccessMs),
257
+ ...enrichActivity(f.path, f.lastWriteMs)
258
+ }));
59
259
 
60
- execSync(`powershell -Command "Invoke-WebRequest -Uri '${url}' -OutFile '${zipPath}'; Expand-Archive -Path '${zipPath}' -DestinationPath '${autoInstallDir}' -Force; Remove-Item '${zipPath}'"`, {
61
- stdio: ['ignore', 'inherit', 'inherit']
260
+ const forgottenAll = result.files.filter(
261
+ (f) => Math.max(f.lastAccessMs || 0, f.lastWriteMs || 0) < forgottenCutoffMs
262
+ );
263
+ const topForgottenFiles = forgottenAll
264
+ .sort((a, b) => b.size - a.size)
265
+ .slice(0, 25)
266
+ .map((f) => {
267
+ const lastTouchMs = Math.max(f.lastAccessMs || 0, f.lastWriteMs || 0);
268
+ const daysIdle = Math.max(0, Math.floor((nowMs - lastTouchMs) / MS_PER_DAY));
269
+ return {
270
+ path: f.path,
271
+ name: f.name,
272
+ size: f.size,
273
+ sizeFormatted: scanner.formatBytes(f.size),
274
+ daysIdle,
275
+ lastAccess: scanner.formatDate(f.lastAccessMs),
276
+ lastWrite: scanner.formatDate(f.lastWriteMs),
277
+ ...enrichActivity(f.path, f.lastWriteMs)
278
+ };
62
279
  });
63
280
 
64
- if (fs.existsSync(autoInstallExe)) {
65
- console.error('[vacumify-mcp] Successfully installed Vacumify to ' + autoInstallDir);
66
- return autoInstallExe;
281
+ const groupsMap = new Map();
282
+ for (const f of result.files) {
283
+ if (!f.duplicateGroupId) continue;
284
+ let list = groupsMap.get(f.duplicateGroupId);
285
+ if (!list) {
286
+ list = [];
287
+ groupsMap.set(f.duplicateGroupId, list);
67
288
  }
68
- } catch (err) {
69
- console.error('[vacumify-mcp] Auto-download failed: ' + err.message);
289
+ list.push(f);
70
290
  }
71
- return null;
291
+
292
+ const topDuplicateGroups = Array.from(groupsMap.entries())
293
+ .map(([groupId, items]) => {
294
+ const sorted = items.slice().sort((a, b) => (a.lastWriteMs || 0) - (b.lastWriteMs || 0));
295
+ const unitSize = sorted[0]?.size || 0;
296
+ const reclaimableBytes = unitSize * Math.max(0, sorted.length - 1);
297
+ const anchor = sorted[0];
298
+ return {
299
+ groupId,
300
+ fileCount: sorted.length,
301
+ unitSize,
302
+ reclaimableBytes,
303
+ reclaimableFormatted: scanner.formatBytes(reclaimableBytes),
304
+ ...enrichActivity(anchor.path, anchor.lastWriteMs),
305
+ paths: sorted.map((x) => x.path)
306
+ };
307
+ })
308
+ .sort((a, b) => b.reclaimableBytes - a.reclaimableBytes)
309
+ .slice(0, 20);
310
+
311
+ const devCaches = result.devCaches
312
+ .slice()
313
+ .sort((a, b) => b.size - a.size)
314
+ .slice(0, 30)
315
+ .map((c) => ({
316
+ path: c.path,
317
+ projectName: c.projectName,
318
+ cacheType: c.cacheType,
319
+ size: c.size,
320
+ sizeFormatted: scanner.formatBytes(c.size),
321
+ lastModified: scanner.formatDate(c.lastModifiedMs),
322
+ ...enrichActivity(c.path, c.lastModifiedMs)
323
+ }));
324
+
325
+ const safeJunkCandidates = scanner.identifySafeJunk(result.files);
326
+ const abandonedCaches = devCaches.filter((c) => c.activityStatus === 'ABANDONED');
327
+
328
+ const zeroRiskItems = [
329
+ ...safeJunkCandidates.map((f) => ({
330
+ path: f.path,
331
+ name: f.name,
332
+ size: f.size,
333
+ sizeFormatted: scanner.formatBytes(f.size),
334
+ reason: f.duplicateGroupId
335
+ ? 'Redundant duplicate copy (original preserved)'
336
+ : 'Obsolete installer / crash dump (>30d idle)',
337
+ category: f.duplicateGroupId ? 'duplicate' : 'obsolete_installer'
338
+ })),
339
+ ...abandonedCaches.map((c) => ({
340
+ path: c.path,
341
+ name: `${c.projectName} (${c.cacheType})`,
342
+ size: c.size,
343
+ sizeFormatted: c.sizeFormatted,
344
+ reason: `Dead dev cache in abandoned project (${c.daysUntouched}d idle)`,
345
+ category: 'abandoned_cache'
346
+ }))
347
+ ].sort((a, b) => b.size - a.size);
348
+
349
+ const zeroRiskBytes = zeroRiskItems.reduce((acc, item) => acc + item.size, 0);
350
+
351
+ const zeroRiskSummary = {
352
+ totalItems: zeroRiskItems.length,
353
+ reclaimableBytes: zeroRiskBytes,
354
+ reclaimableFormatted: scanner.formatBytes(zeroRiskBytes),
355
+ topRecommendations: zeroRiskItems.slice(0, 5)
356
+ };
357
+
358
+ const reviewNeededSummary = {
359
+ largeFilesCount: topLargeFiles.length,
360
+ forgottenFilesCount: forgottenAll.length,
361
+ activeOrDormantCachesCount: devCaches.filter((c) => c.activityStatus !== 'ABANDONED').length,
362
+ topLargeCandidates: topLargeFiles.slice(0, 3),
363
+ topForgottenCandidates: topForgottenFiles.slice(0, 3)
364
+ };
365
+
366
+ return {
367
+ scannedPath: targetPath,
368
+ totalFiles: result.files.length,
369
+ totalBytes: result.bytesScanned,
370
+ totalFormatted: scanner.formatBytes(result.bytesScanned),
371
+ conditions: {
372
+ forgottenDays,
373
+ minLargeFileBytes,
374
+ minDuplicateBytes,
375
+ includeHidden
376
+ },
377
+ zeroRiskSummary,
378
+ reviewNeededSummary,
379
+ reclaimableDuplicateBytes: result.reclaimableDuplicateBytes,
380
+ reclaimableDuplicateFormatted: scanner.formatBytes(result.reclaimableDuplicateBytes),
381
+ duplicateGroupCount: groupsMap.size,
382
+ forgottenFilesCount: forgottenAll.length,
383
+ devCacheCount: result.devCaches.length,
384
+ devCacheTotalBytes: result.devCaches.reduce((acc, c) => acc + c.size, 0),
385
+ devCacheTotalFormatted: scanner.formatBytes(result.devCaches.reduce((acc, c) => acc + c.size, 0)),
386
+ zeroRiskItems: zeroRiskItems.slice(0, 50),
387
+ topLargeFiles,
388
+ topForgottenFiles,
389
+ topDuplicateGroups,
390
+ devCaches,
391
+ errorsCount: result.errors.length
392
+ };
72
393
  }
73
394
 
74
- let exePath = findVacumifyExecutable() || downloadAndExtractRelease();
395
+ async function handleGetDevCaches(args) {
396
+ const targetPath = resolveValidDir(args.path);
397
+ const olderThanDays =
398
+ args.olderThanDays !== undefined && args.olderThanDays !== null
399
+ ? Math.max(0, Number(args.olderThanDays))
400
+ : null;
401
+
402
+ const result = await scanner.scanDirectory(targetPath, {
403
+ includeHidden: false,
404
+ minDuplicateBytes: 100 * 1024,
405
+ fastLargeSampling: true
406
+ });
75
407
 
76
- if (!exePath) {
77
- console.error('[vacumify-mcp] Error: Vacumify.exe not found.');
78
- console.error('[vacumify-mcp] Please either:');
79
- console.error(' 1. Set VACUMIFY_PATH environment variable to the path of Vacumify.exe');
80
- console.error(' 2. Place Vacumify.exe in your PATH');
81
- console.error(' 3. Or build the project: dotnet publish StorageCleaner/StorageCleaner/StorageCleaner.csproj -c Release -r win-x64 --self-contained true');
82
- process.exit(1);
408
+ let caches = result.devCaches.map((c) => {
409
+ const activity = scanner.getProjectActivity(c.path, c.lastModifiedMs);
410
+ return {
411
+ path: c.path,
412
+ projectName: c.projectName,
413
+ cacheType: c.cacheType,
414
+ size: c.size,
415
+ sizeFormatted: scanner.formatBytes(c.size),
416
+ lastModified: scanner.formatDate(c.lastModifiedMs),
417
+ activityStatus: activity.status,
418
+ daysUntouched: activity.daysUntouched,
419
+ projectRoot: activity.projectRoot
420
+ };
421
+ });
422
+
423
+ if (olderThanDays !== null && Number.isFinite(olderThanDays)) {
424
+ caches = caches.filter((c) => c.daysUntouched >= olderThanDays);
425
+ }
426
+
427
+ caches.sort((a, b) => b.size - a.size);
428
+ const totalBytes = caches.reduce((acc, c) => acc + c.size, 0);
429
+
430
+ return {
431
+ scannedPath: targetPath,
432
+ olderThanDays,
433
+ cacheCount: caches.length,
434
+ totalBytes,
435
+ totalFormatted: scanner.formatBytes(totalBytes),
436
+ caches
437
+ };
83
438
  }
84
439
 
85
- const child = spawn(exePath, ['--mcp'], {
86
- stdio: 'inherit',
87
- windowsHide: true
88
- });
440
+ async function handleGetSafeJunk(args) {
441
+ const targetPath = resolveValidDir(args.path);
442
+ const result = await scanner.scanDirectory(targetPath, {
443
+ includeHidden: false,
444
+ minDuplicateBytes: 100 * 1024,
445
+ fastLargeSampling: true
446
+ });
89
447
 
90
- child.on('error', (err) => {
91
- console.error(`[vacumify-mcp] Failed to spawn Vacumify: ${err.message}`);
92
- process.exit(1);
93
- });
448
+ const junk = scanner.identifySafeJunk(result.files);
449
+ const totalBytes = junk.reduce((acc, f) => acc + f.size, 0);
450
+
451
+ return {
452
+ scannedPath: targetPath,
453
+ candidateCount: junk.length,
454
+ totalBytes,
455
+ totalFormatted: scanner.formatBytes(totalBytes),
456
+ candidates: junk
457
+ .slice()
458
+ .sort((a, b) => b.size - a.size)
459
+ .slice(0, 100)
460
+ .map((f) => ({
461
+ path: f.path,
462
+ name: f.name,
463
+ size: f.size,
464
+ sizeFormatted: scanner.formatBytes(f.size),
465
+ reason: f.duplicateGroupId ? 'redundant_duplicate' : 'obsolete_installer_or_dump',
466
+ lastWrite: scanner.formatDate(f.lastWriteMs)
467
+ }))
468
+ };
469
+ }
470
+
471
+ async function handleRecycleItems(args) {
472
+ if (!Array.isArray(args.paths) || args.paths.length === 0) {
473
+ throw new Error('Argument "paths" must be a non-empty array of absolute file/folder paths.');
474
+ }
475
+ const dryRun = Boolean(args.dryRun);
476
+ return await scanner.recycleItems(args.paths, dryRun);
477
+ }
478
+
479
+ function getPromptResponse(name, args = {}) {
480
+ const target = args.path ? `"${args.path}"` : 'the target folder (ask the user if not specified)';
481
+ switch (name) {
482
+ case 'audit-storage':
483
+ return {
484
+ description: 'Executive storage audit with zero-risk recommendations and minimal noise.',
485
+ messages: [
486
+ {
487
+ role: 'user',
488
+ content: {
489
+ type: 'text',
490
+ text:
491
+ `Run an executive storage audit on ${target} using \`vacumify_scan\`.\n\n` +
492
+ 'OUTPUT GUIDELINES (DO NOT OUTPUT MASSIVE 50+ ROW TABLES):\n' +
493
+ '1. Topline Impact (1-2 sentences): State total files scanned, total directory size, and immediate zero-risk reclaimable space (from `zeroRiskSummary`).\n' +
494
+ '2. Zero-Risk Safe Sweep (Top 3-5 items): Highlight the highest-impact zero-risk items (redundant duplicate copies with original preserved, obsolete installers/dumps >30d, and abandoned project caches) with size and why they are 100% safe to recycle.\n' +
495
+ '3. Items Needing Review: Briefly mention the top 2-3 large files or forgotten files that the user might want to consider.\n' +
496
+ '4. Actionable Next Step: Offer to recycle the Zero-Risk items directly to Recycle Bin/Trash using `vacumify_recycle_items`, and mention that the user can ask for full lists ("show all duplicates", "show forgotten") if desired.\n' +
497
+ '5. Strict Safety: NEVER permanently delete. Always use `vacumify_recycle_items` after user confirms.'
498
+ }
499
+ }
500
+ ]
501
+ };
502
+ case 'duplicates':
503
+ return {
504
+ description: 'Find duplicate file groups and safely recycle redundant copies.',
505
+ messages: [
506
+ {
507
+ role: 'user',
508
+ content: {
509
+ type: 'text',
510
+ text:
511
+ `Scan ${target} for duplicate files using \`vacumify_scan\` (respecting \`minDuplicateBytes\`, default 100 KB).\n\n` +
512
+ 'OUTPUT GUIDELINES:\n' +
513
+ '1. State total duplicate groups found and total reclaimable space.\n' +
514
+ '2. Show only the top 3-5 duplicate groups by size. For each group, clearly indicate the original file to KEEP and the redundant copies safe to RECYCLE.\n' +
515
+ '3. Do not list dozens of rows. Offer to move the redundant copies to Recycle Bin via `vacumify_recycle_items`, or let the user ask to see more groups.'
516
+ }
517
+ }
518
+ ]
519
+ };
520
+ case 'forgotten-files': {
521
+ const days = args.days || '90';
522
+ return {
523
+ description: 'Find untouched files exceeding a day threshold.',
524
+ messages: [
525
+ {
526
+ role: 'user',
527
+ content: {
528
+ type: 'text',
529
+ text:
530
+ `Scan ${target} using \`vacumify_scan\` with \`forgottenDays: ${days}\`.\n\n` +
531
+ 'OUTPUT GUIDELINES:\n' +
532
+ `1. State total files untouched for ${days}+ days and their total size.\n` +
533
+ '2. Highlight only the top 3-5 largest forgotten files with their idle days and project activity status (ACTIVE / DORMANT / ABANDONED).\n' +
534
+ '3. Ask the user if they want to recycle any of these via `vacumify_recycle_items` or inspect more.'
535
+ }
536
+ }
537
+ ]
538
+ };
539
+ }
540
+ case 'large-files': {
541
+ const minMb = args.minSizeMb || '100';
542
+ const minBytes = Math.max(1, Number(minMb) || 100) * 1024 * 1024;
543
+ return {
544
+ description: 'Find oversized files above a configurable MB threshold.',
545
+ messages: [
546
+ {
547
+ role: 'user',
548
+ content: {
549
+ type: 'text',
550
+ text:
551
+ `Scan ${target} using \`vacumify_scan\` with \`minLargeFileBytes: ${minBytes}\` (${minMb} MB).\n\n` +
552
+ 'OUTPUT GUIDELINES:\n' +
553
+ `1. State total large files >= ${minMb} MB and aggregate size.\n` +
554
+ '2. Rank only the top 3-5 largest space hogs with file type, size, and last modified date.\n' +
555
+ '3. Ask the user for confirmation before recycling any files via `vacumify_recycle_items`.'
556
+ }
557
+ }
558
+ ]
559
+ };
560
+ }
561
+ case 'dev-caches': {
562
+ const olderClause = args.olderThanDays
563
+ ? ` with \`olderThanDays: ${args.olderThanDays}\``
564
+ : '';
565
+ return {
566
+ description: 'Find bloated developer caches with Active/Dormant/Abandoned context.',
567
+ messages: [
568
+ {
569
+ role: 'user',
570
+ content: {
571
+ type: 'text',
572
+ text:
573
+ `Scan ${target} using \`vacumify_get_dev_caches\`${olderClause}.\n\n` +
574
+ 'OUTPUT GUIDELINES:\n' +
575
+ '1. Summarize total dev cache size found.\n' +
576
+ '2. Group into ABANDONED (safe to sweep), DORMANT (review), and ACTIVE (warn user to keep intact).\n' +
577
+ '3. Recommend recycling the ABANDONED caches first and ask for user confirmation before calling `vacumify_recycle_items`.'
578
+ }
579
+ }
580
+ ]
581
+ };
582
+ }
583
+ default:
584
+ return null;
585
+ }
586
+ }
587
+
588
+ async function handleRequest(msg) {
589
+ const { id, method, params } = msg;
590
+ const isNotification = id === undefined || id === null;
591
+
592
+ try {
593
+ switch (method) {
594
+ case 'initialize': {
595
+ sendResult(id, {
596
+ protocolVersion: PROTOCOL_VERSION,
597
+ capabilities: {
598
+ tools: {},
599
+ prompts: {}
600
+ },
601
+ serverInfo: {
602
+ name: SERVER_NAME,
603
+ version: SERVER_VERSION
604
+ }
605
+ });
606
+ return;
607
+ }
608
+ case 'notifications/initialized':
609
+ case 'initialized':
610
+ return;
611
+ case 'ping': {
612
+ if (!isNotification) sendResult(id, {});
613
+ return;
614
+ }
615
+ case 'tools/list': {
616
+ sendResult(id, { tools: TOOLS });
617
+ return;
618
+ }
619
+ case 'tools/call': {
620
+ const toolName = params?.name;
621
+ const args = params?.arguments || {};
622
+ try {
623
+ let data;
624
+ if (toolName === 'vacumify_scan') {
625
+ data = await handleVacumifyScan(args);
626
+ } else if (toolName === 'vacumify_get_dev_caches') {
627
+ data = await handleGetDevCaches(args);
628
+ } else if (toolName === 'vacumify_get_safe_junk') {
629
+ data = await handleGetSafeJunk(args);
630
+ } else if (toolName === 'vacumify_recycle_items') {
631
+ data = await handleRecycleItems(args);
632
+ } else {
633
+ sendError(id, -32601, `Unknown tool: ${toolName}`);
634
+ return;
635
+ }
636
+ sendResult(id, toolTextResult(data));
637
+ } catch (toolErr) {
638
+ sendResult(id, toolTextResult({ error: toolErr.message || String(toolErr) }, true));
639
+ }
640
+ return;
641
+ }
642
+ case 'prompts/list': {
643
+ sendResult(id, { prompts: PROMPTS });
644
+ return;
645
+ }
646
+ case 'prompts/get': {
647
+ const promptName = params?.name;
648
+ const promptRes = getPromptResponse(promptName, params?.arguments || {});
649
+ if (!promptRes) {
650
+ sendError(id, -32602, `Unknown prompt: ${promptName}`);
651
+ return;
652
+ }
653
+ sendResult(id, promptRes);
654
+ return;
655
+ }
656
+ default: {
657
+ if (!isNotification) {
658
+ sendError(id, -32601, `Method not found: ${method}`);
659
+ }
660
+ }
661
+ }
662
+ } catch (err) {
663
+ if (!isNotification) {
664
+ sendError(id, -32603, err?.message || 'Internal error');
665
+ }
666
+ }
667
+ }
94
668
 
95
- child.on('exit', (code, signal) => {
96
- process.exit(code ?? (signal ? 1 : 0));
669
+ const rl = readline.createInterface({
670
+ input: process.stdin,
671
+ crlfDelay: Infinity
97
672
  });
98
673
 
674
+ let pending = Promise.resolve();
675
+ rl.on('line', (line) => {
676
+ const trimmed = line.trim();
677
+ if (!trimmed) return;
678
+ let parsed;
679
+ try {
680
+ parsed = JSON.parse(trimmed);
681
+ } catch (e) {
682
+ sendError(null, -32700, 'Parse error');
683
+ return;
684
+ }
685
+ pending = pending.then(() => handleRequest(parsed));
686
+ });