rclean 0.1.1

A high-performance Rust-based disk cleanup tool that finds duplicates and storage outliers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
use crate::models::mcp::{
    CountArgs, DedupeArgs, McpRequest, McpResponse, OutliersArgs, SearchArgs, ToolCallParams,
};
use crate::{PatternType, WalkOptions};
use polars::prelude::IntoLazy;
use serde_json::{json, Value};
use tracing::{error, info};

pub fn handle_initialize(request: McpRequest) -> McpResponse {
    info!("Handling initialize request");

    McpResponse::success(
        request.id,
        json!({
            "protocolVersion": "2024-11-05",
            "capabilities": {
                "tools": {
                    "listChanged": true
                }
            },
            "serverInfo": {
                "name": "rclean",
                "version": env!("CARGO_PKG_VERSION")
            }
        }),
    )
}

pub fn handle_tools_list(request: McpRequest) -> McpResponse {
    info!("Handling tools/list request");

    McpResponse::success(
        request.id,
        json!({
            "tools": [
                {
                    "name": "dedupe",
                    "description": "Find duplicate files in a directory",
                    "inputSchema": {
                        "type": "object",
                        "properties": {
                            "path": {
                                "type": "string",
                                "description": "Path to scan for duplicates"
                            },
                            "pattern": {
                                "type": "string",
                                "description": "Pattern to match files",
                                "default": ""
                            },
                            "pattern_type": {
                                "type": "string",
                                "enum": ["literal", "glob", "regex"],
                                "default": "literal"
                            },
                            "hidden": {
                                "type": "boolean",
                                "description": "Include hidden files",
                                "default": false
                            },
                            "no_ignore": {
                                "type": "boolean",
                                "description": "Ignore .gitignore rules",
                                "default": false
                            },
                            "max_depth": {
                                "type": "integer",
                                "description": "Maximum depth to traverse"
                            },
                            "similarity": {
                                "type": "integer",
                                "description": "Similarity threshold (0-100) for fuzzy matching",
                                "minimum": 0,
                                "maximum": 100
                            }
                        },
                        "required": ["path"]
                    }
                },
                {
                    "name": "search",
                    "description": "Search for files matching a pattern",
                    "inputSchema": {
                        "type": "object",
                        "properties": {
                            "path": {
                                "type": "string",
                                "description": "Path to search in"
                            },
                            "pattern": {
                                "type": "string",
                                "description": "Pattern to match files",
                                "default": ""
                            },
                            "pattern_type": {
                                "type": "string",
                                "enum": ["literal", "glob", "regex"],
                                "default": "literal"
                            },
                            "hidden": {
                                "type": "boolean",
                                "description": "Include hidden files",
                                "default": false
                            },
                            "no_ignore": {
                                "type": "boolean",
                                "description": "Ignore .gitignore rules",
                                "default": false
                            },
                            "max_depth": {
                                "type": "integer",
                                "description": "Maximum depth to traverse"
                            }
                        },
                        "required": ["path"]
                    }
                },
                {
                    "name": "count",
                    "description": "Count files matching a pattern",
                    "inputSchema": {
                        "type": "object",
                        "properties": {
                            "path": {
                                "type": "string",
                                "description": "Path to count files in"
                            },
                            "pattern": {
                                "type": "string",
                                "description": "Pattern to match files",
                                "default": ""
                            },
                            "pattern_type": {
                                "type": "string",
                                "enum": ["literal", "glob", "regex"],
                                "default": "literal"
                            },
                            "hidden": {
                                "type": "boolean",
                                "description": "Include hidden files",
                                "default": false
                            },
                            "no_ignore": {
                                "type": "boolean",
                                "description": "Ignore .gitignore rules",
                                "default": false
                            },
                            "max_depth": {
                                "type": "integer",
                                "description": "Maximum depth to traverse"
                            }
                        },
                        "required": ["path"]
                    }
                },
                {
                    "name": "outliers",
                    "description": "Detect storage outliers (large files, hidden consumers, patterns)",
                    "inputSchema": {
                        "type": "object",
                        "properties": {
                            "path": {
                                "type": "string",
                                "description": "Path to analyze for outliers"
                            },
                            "min_size": {
                                "type": "string",
                                "description": "Minimum file size to consider (e.g., 100MB, 1GB)"
                            },
                            "top_n": {
                                "type": "integer",
                                "description": "Number of top outliers to return",
                                "default": 20
                            },
                            "std_dev_threshold": {
                                "type": "number",
                                "description": "Standard deviations from mean to consider as outlier",
                                "default": 2.0
                            },
                            "check_hidden_consumers": {
                                "type": "boolean",
                                "description": "Check for hidden space consumers (node_modules, .git, etc.)",
                                "default": true
                            },
                            "check_patterns": {
                                "type": "boolean",
                                "description": "Check for file patterns (backups, logs, etc.)",
                                "default": true
                            }
                        },
                        "required": ["path"]
                    }
                },
                {
                    "name": "analyze_file_clusters",
                    "description": "Detect clusters of similar large files using DBSCAN",
                    "inputSchema": {
                        "type": "object",
                        "properties": {
                            "path": {
                                "type": "string",
                                "description": "Directory path to analyze"
                            },
                            "min_similarity": {
                                "type": "integer",
                                "minimum": 50,
                                "maximum": 100,
                                "default": 70,
                                "description": "Minimum similarity percentage for clustering"
                            },
                            "min_cluster_size": {
                                "type": "integer",
                                "minimum": 2,
                                "default": 2,
                                "description": "Minimum files to form a cluster"
                            },
                            "min_file_size": {
                                "type": "string",
                                "default": "10MB",
                                "description": "Minimum file size to consider"
                            },
                            "files": {
                                "type": "array",
                                "items": { "type": "string" },
                                "description": "Specific files to analyze (for tool composition)"
                            }
                        },
                        "required": ["path"]
                    }
                }
            ]
        }),
    )
}

pub async fn handle_tool_call(request: McpRequest) -> McpResponse {
    let tool_params = match parse_tool_call_params(request.params, &request.id) {
        Ok(params) => params,
        Err(response) => return *response,
    };

    match tool_params.name.as_str() {
        "dedupe" => handle_dedupe_tool(request.id, tool_params.arguments).await,
        "search" => handle_search_tool(request.id, tool_params.arguments).await,
        "count" => handle_count_tool(request.id, tool_params.arguments).await,
        "outliers" => handle_outliers_tool(request.id, tool_params.arguments).await,
        "analyze_file_clusters" => handle_analyze_clusters_tool(request.id, tool_params.arguments).await,
        _ => McpResponse::error(
            request.id,
            -32602,
            format!("Unknown tool: {}", tool_params.name),
        ),
    }
}

fn parse_tool_call_params(
    params: Option<Value>,
    request_id: &Value,
) -> Result<ToolCallParams, Box<McpResponse>> {
    let params = match params {
        Some(p) => p,
        None => {
            return Err(Box::new(McpResponse::error(
                request_id.clone(),
                -32602,
                "Invalid params: missing tool call parameters".to_string(),
            )));
        },
    };

    match serde_json::from_value(params) {
        Ok(p) => Ok(p),
        Err(e) => Err(Box::new(McpResponse::error(
            request_id.clone(),
            -32602,
            format!("Invalid params: {}", e),
        ))),
    }
}

async fn handle_dedupe_tool(id: Value, arguments: Value) -> McpResponse {
    let args: DedupeArgs = match serde_json::from_value(arguments) {
        Ok(args) => args,
        Err(e) => {
            return McpResponse::error(id, -32602, format!("Invalid arguments for dedupe: {}", e));
        },
    };

    let walk_options = WalkOptions {
        include_hidden: args.hidden,
        respect_gitignore: !args.no_ignore,
        respect_ignore: !args.no_ignore,
        max_depth: args.max_depth,
    };

    let pattern = match create_pattern(&args.pattern, &args.pattern_type) {
        Ok(p) => p,
        Err(e) => {
            return McpResponse::error(id, -32602, format!("Invalid pattern: {}", e));
        },
    };

    // Run deduplication
    let result = if let Some(threshold) = args.similarity {
        crate::run_with_similarity(&args.path, &pattern, &walk_options, threshold, None)
    } else {
        crate::run_with_advanced_options(&args.path, &pattern, &walk_options, None)
    };

    match result {
        Ok(df) => {
            // Convert DataFrame results to JSON
            let height = df.height();
            let duplicates = df
                .clone()
                .lazy()
                .filter(polars::prelude::col("is_duplicate").eq(polars::prelude::lit(true)))
                .collect()
                .map(|df| df.height())
                .unwrap_or(0);

            McpResponse::success(
                id,
                json!({
                    "total_files": height,
                    "duplicate_files": duplicates,
                    "duplicate_groups": df
                        .column("duplicate_group")
                        .ok()
                        .and_then(|col| col.unique().ok())
                        .map(|unique| unique.len().saturating_sub(1)) // Subtract 1 for null values, prevent underflow
                        .unwrap_or(0),
                    "message": format!("Found {} duplicate files in {} total files", duplicates, height)
                }),
            )
        },
        Err(e) => {
            error!("Dedupe error: {}", e);
            McpResponse::error(id, -32603, format!("Dedupe failed: {}", e))
        },
    }
}

async fn handle_search_tool(id: Value, arguments: Value) -> McpResponse {
    let args: SearchArgs = match serde_json::from_value(arguments) {
        Ok(args) => args,
        Err(e) => {
            return McpResponse::error(id, -32602, format!("Invalid arguments for search: {}", e));
        },
    };

    let walk_options = WalkOptions {
        include_hidden: args.hidden,
        respect_gitignore: !args.no_ignore,
        respect_ignore: !args.no_ignore,
        max_depth: args.max_depth,
    };

    let pattern = match create_pattern(&args.pattern, &args.pattern_type) {
        Ok(p) => p,
        Err(e) => {
            return McpResponse::error(id, -32602, format!("Invalid pattern: {}", e));
        },
    };

    match crate::walk_with_options(&args.path, &walk_options) {
        Ok(files) => {
            let matched_files = crate::find_advanced(&files, &pattern);
            McpResponse::success(
                id,
                json!({
                    "files": matched_files,
                    "count": matched_files.len(),
                    "message": format!("Found {} files matching pattern", matched_files.len())
                }),
            )
        },
        Err(e) => {
            error!("Search error: {}", e);
            McpResponse::error(id, -32603, format!("Search failed: {}", e))
        },
    }
}

async fn handle_count_tool(id: Value, arguments: Value) -> McpResponse {
    let args: CountArgs = match serde_json::from_value(arguments) {
        Ok(args) => args,
        Err(e) => {
            return McpResponse::error(id, -32602, format!("Invalid arguments for count: {}", e));
        },
    };

    let walk_options = WalkOptions {
        include_hidden: args.hidden,
        respect_gitignore: !args.no_ignore,
        respect_ignore: !args.no_ignore,
        max_depth: args.max_depth,
    };

    let pattern = match create_pattern(&args.pattern, &args.pattern_type) {
        Ok(p) => p,
        Err(e) => {
            return McpResponse::error(id, -32602, format!("Invalid pattern: {}", e));
        },
    };

    match crate::walk_with_options(&args.path, &walk_options) {
        Ok(files) => {
            let matched_files = crate::find_advanced(&files, &pattern);
            McpResponse::success(
                id,
                json!({
                    "count": matched_files.len(),
                    "message": format!("Found {} files matching pattern", matched_files.len())
                }),
            )
        },
        Err(e) => {
            error!("Count error: {}", e);
            McpResponse::error(id, -32603, format!("Count failed: {}", e))
        },
    }
}

fn create_pattern(pattern: &str, pattern_type: &str) -> Result<PatternType, String> {
    match pattern_type {
        "literal" | "" => Ok(PatternType::Literal(pattern.to_string())),
        "glob" => {
            let glob = globset::Glob::new(pattern)
                .map_err(|e| format!("Invalid glob pattern: {}", e))?;
            let mut builder = globset::GlobSetBuilder::new();
            builder.add(glob);
            let globset = builder
                .build()
                .map_err(|e| format!("Failed to build globset: {}", e))?;
            Ok(PatternType::Glob(globset))
        },
        "regex" => {
            let regex = regex::Regex::new(pattern)
                .map_err(|e| format!("Invalid regex pattern: {}", e))?;
            Ok(PatternType::Regex(regex))
        },
        _ => Err(format!("Unknown pattern type: {}", pattern_type)),
    }
}

async fn handle_outliers_tool(id: Value, arguments: Value) -> McpResponse {
    let args: OutliersArgs = match serde_json::from_value(arguments) {
        Ok(args) => args,
        Err(e) => {
            return McpResponse::error(id, -32602, format!("Invalid arguments for outliers: {}", e));
        },
    };
    
    // Parse min_size if provided
    let min_size_bytes = args.min_size.as_ref().and_then(|s| parse_size(s).ok());
    
    let options = crate::outliers::OutlierOptions {
        min_size: min_size_bytes,
        top_n: Some(args.top_n),
        std_dev_threshold: args.std_dev_threshold,
        check_hidden_consumers: args.check_hidden_consumers,
        include_empty_dirs: false,
        check_patterns: args.check_patterns,
        enable_clustering: false, // Not enabled by default in outliers tool
        cluster_similarity_threshold: 70,
        min_cluster_size: 2,
    };
    
    match crate::outliers::detect_outliers(&args.path, &options) {
        Ok(report) => {
            // Convert report to JSON response
            let result = json!({
                "total_files_analyzed": report.total_files_analyzed,
                "total_size_analyzed": report.total_size_analyzed,
                "total_size_gb": report.total_size_analyzed as f64 / (1024.0 * 1024.0 * 1024.0),
                "large_files": report.large_files.iter().map(|o| json!({
                    "path": o.path.to_string_lossy(),
                    "size_bytes": o.size_bytes,
                    "size_mb": o.size_mb,
                    "percentage_of_total": o.percentage_of_total,
                    "std_devs_from_mean": o.std_devs_from_mean,
                })).collect::<Vec<_>>(),
                "hidden_consumers": report.hidden_consumers.iter().map(|c| json!({
                    "path": c.path.to_string_lossy(),
                    "pattern_type": c.pattern_type,
                    "total_size_bytes": c.total_size_bytes,
                    "file_count": c.file_count,
                    "recommendation": c.recommendation,
                })).collect::<Vec<_>>(),
                "pattern_groups": report.pattern_groups.iter().map(|g| json!({
                    "pattern": g.pattern,
                    "sample_files": g.sample_files.iter().map(|f| f.to_string_lossy()).collect::<Vec<_>>(),
                    "total_size_bytes": g.total_size_bytes,
                    "count": g.count,
                })).collect::<Vec<_>>(),
                "message": format!("Found {} outliers across {} files", 
                    report.large_files.len() + report.hidden_consumers.len() + report.pattern_groups.len(),
                    report.total_files_analyzed
                )
            });
            
            McpResponse::success(id, result)
        },
        Err(e) => {
            error!("Outliers detection error: {}", e);
            McpResponse::error(id, -32603, format!("Outliers detection failed: {}", e))
        },
    }
}

async fn handle_analyze_clusters_tool(id: Value, arguments: Value) -> McpResponse {
    // Parse arguments
    let path = arguments["path"].as_str().unwrap_or(".");
    let min_similarity = arguments["min_similarity"].as_u64().unwrap_or(70) as u8;
    let min_cluster_size = arguments["min_cluster_size"].as_u64().unwrap_or(2) as usize;
    let min_file_size = arguments["min_file_size"].as_str().unwrap_or("10MB");
    
    // Parse min file size
    let min_size_bytes = parse_size(min_file_size).unwrap_or(10 * 1024 * 1024);
    
    // Support tool composition via files parameter
    let files = if let Some(file_list) = arguments["files"].as_array() {
        // Analyze specific files from previous tool output
        let mut file_infos = Vec::new();
        for file_path in file_list {
            if let Some(path_str) = file_path.as_str() {
                if let Ok(metadata) = std::fs::metadata(path_str) {
                    if metadata.is_file() && metadata.len() >= min_size_bytes {
                        // Compute SSDEEP hash for large files
                        let ssdeep_hash = if let Ok(content) = std::fs::read(path_str) {
                            ssdeep::hash(&content).ok()
                        } else {
                            None
                        };
                        
                        file_infos.push(crate::outliers::SimpleFileInfo {
                            path: std::path::PathBuf::from(path_str),
                            size_bytes: metadata.len(),
                            ssdeep_hash,
                        });
                    }
                }
            }
        }
        file_infos
    } else {
        // Full directory scan for large files
        let walk_options = WalkOptions::default();
        let all_files = match crate::walk_with_options(path, &walk_options) {
            Ok(files) => files,
            Err(e) => {
                return McpResponse::error(id, -32603, format!("Error scanning directory: {}", e));
            }
        };
        
        // Collect large files with SSDEEP hashes
        let mut file_infos = Vec::new();
        for file_path in all_files {
            if let Ok(metadata) = std::fs::metadata(&file_path) {
                if metadata.is_file() && metadata.len() >= min_size_bytes {
                    // Compute SSDEEP hash
                    let ssdeep_hash = if let Ok(content) = std::fs::read(&file_path) {
                        ssdeep::hash(&content).ok()
                    } else {
                        None
                    };
                    
                    file_infos.push(crate::outliers::SimpleFileInfo {
                        path: std::path::PathBuf::from(file_path),
                        size_bytes: metadata.len(),
                        ssdeep_hash,
                    });
                }
            }
        }
        file_infos
    };
    
    // Perform clustering
    match crate::clustering::detect_large_file_clusters(&files, min_similarity, min_cluster_size) {
        Ok(clusters) => {
            let result = json!({
                "clusters": clusters.iter().map(|c| json!({
                    "cluster_id": c.cluster_id,
                    "files": c.files.iter().map(|f| json!({
                        "path": f.path.to_string_lossy(),
                        "size_bytes": f.size_bytes,
                        "size_mb": f.size_bytes as f64 / (1024.0 * 1024.0),
                    })).collect::<Vec<_>>(),
                    "total_size": c.total_size,
                    "total_size_mb": c.total_size as f64 / (1024.0 * 1024.0),
                    "avg_similarity": c.avg_similarity,
                    "density": c.density,
                })).collect::<Vec<_>>(),
                "summary": {
                    "total_clusters": clusters.len(),
                    "total_files": clusters.iter().map(|c| c.files.len()).sum::<usize>(),
                    "total_size": clusters.iter().map(|c| c.total_size).sum::<u64>(),
                    "files": clusters.iter()
                        .flat_map(|c| c.files.iter().map(|f| f.path.to_string_lossy().to_string()))
                        .collect::<Vec<_>>()
                },
                "message": format!("Found {} clusters containing {} similar files", 
                    clusters.len(),
                    clusters.iter().map(|c| c.files.len()).sum::<usize>()
                )
            });
            
            McpResponse::success(id, result)
        }
        Err(e) => {
            McpResponse::error(id, -32603, format!("Error detecting clusters: {}", e))
        }
    }
}

fn parse_size(size_str: &str) -> Result<u64, String> {
    let size_str = size_str.trim().to_uppercase();
    
    if let Some(num_str) = size_str.strip_suffix("KB") {
        num_str.trim().parse::<f64>()
            .map(|n| (n * 1024.0) as u64)
            .map_err(|_| format!("Invalid size: {}", size_str))
    } else if let Some(num_str) = size_str.strip_suffix("MB") {
        num_str.trim().parse::<f64>()
            .map(|n| (n * 1024.0 * 1024.0) as u64)
            .map_err(|_| format!("Invalid size: {}", size_str))
    } else if let Some(num_str) = size_str.strip_suffix("GB") {
        num_str.trim().parse::<f64>()
            .map(|n| (n * 1024.0 * 1024.0 * 1024.0) as u64)
            .map_err(|_| format!("Invalid size: {}", size_str))
    } else if let Some(num_str) = size_str.strip_suffix("B") {
        num_str.trim().parse::<u64>()
            .map_err(|_| format!("Invalid size: {}", size_str))
    } else {
        size_str.parse::<u64>()
            .map_err(|_| format!("Invalid size: {} (use B, KB, MB, or GB suffix)", size_str))
    }
}