poly-mcp 0.5.0

A comprehensive MCP server with filesystem, diagnostics, scripting, time, network, context, git, input, clipboard, transform, and screen control tools
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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
use serde_json::{json, Value};
use anyhow::{Result, Context as _};
use std::path::{Path, PathBuf};
use std::fs;
use std::collections::HashMap;
use chrono::Local;
use notify::{Watcher, RecursiveMode};
use walkdir::WalkDir;
use std::sync::{Arc, Mutex};
use regex::Regex;

pub struct FilesystemModule {
    snapshots: Arc<Mutex<HashMap<String, Vec<SnapshotInfo>>>>,
}

#[derive(Clone)]
struct SnapshotInfo {
    #[allow(dead_code)]
    timestamp: String,
    path: PathBuf,
    compressed: bool,
}

impl Default for FilesystemModule {
    fn default() -> Self {
        Self::new()
    }
}

impl FilesystemModule {
    pub fn new() -> Self {
        Self {
            snapshots: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    pub fn get_tools(&self) -> Vec<Value> {
        vec![
            json!({
                "name": "fs_read",
                "description": "Read file contents, optionally reading specific line ranges",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "path": {
                            "type": "string",
                            "description": "Path to the file to read"
                        },
                        "lines": {
                            "type": "array",
                            "description": "Optional array of line ranges to read, e.g. [[1,10], [15,20]] reads lines 1-10 and 15-20",
                            "items": {
                                "type": "array",
                                "minItems": 2,
                                "maxItems": 2,
                                "items": {
                                    "type": "integer"
                                }
                            }
                        }
                    },
                    "required": ["path"]
                }
            }),
            json!({
                "name": "fs_write",
                "description": "Write content to a file, optionally writing to specific line ranges",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "path": {
                            "type": "string",
                            "description": "Path to the file to write"
                        },
                        "content": {
                            "type": "string",
                            "description": "Content to write to the file"
                        },
                        "lines": {
                            "type": "array",
                            "description": "Optional array of line ranges to replace, e.g. [[1,10], [15,20]]. Content will be split and replace specified ranges.",
                            "items": {
                                "type": "array",
                                "minItems": 2,
                                "maxItems": 2,
                                "items": {
                                    "type": "integer"
                                }
                            }
                        }
                    },
                    "required": ["path", "content"]
                }
            }),
            json!({
                "name": "fs_move",
                "description": "Move files or directories",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "source": {
                            "type": "string",
                            "description": "Source path"
                        },
                        "destination": {
                            "type": "string",
                            "description": "Destination path"
                        }
                    },
                    "required": ["source", "destination"]
                }
            }),
            json!({
                "name": "fs_copy",
                "description": "Copy files or directories",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "source": {
                            "type": "string",
                            "description": "Source path"
                        },
                        "destination": {
                            "type": "string",
                            "description": "Destination path"
                        }
                    },
                    "required": ["source", "destination"]
                }
            }),
            json!({
                "name": "fs_create",
                "description": "Create files or directories",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "path": {
                            "type": "string",
                            "description": "Path to create"
                        },
                        "type": {
                            "type": "string",
                            "enum": ["file", "dir"],
                            "description": "Type to create (file or dir)"
                        }
                    },
                    "required": ["path", "type"]
                }
            }),
            json!({
                "name": "fs_delete",
                "description": "Delete files or directories",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "path": {
                            "type": "string",
                            "description": "Path to delete"
                        }
                    },
                    "required": ["path"]
                }
            }),
            json!({
                "name": "fs_move_desktop",
                "description": "Move and organize items within the Desktop directory",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "item": {
                            "type": "string",
                            "description": "Item name or path within Desktop"
                        },
                        "destination": {
                            "type": "string",
                            "description": "Destination subfolder within Desktop"
                        }
                    },
                    "required": ["item", "destination"]
                }
            }),
            json!({
                "name": "fs_find",
                "description": "Search for files and directories by name pattern",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "path": {
                            "type": "string",
                            "description": "Root path to search from"
                        },
                        "pattern": {
                            "type": "string",
                            "description": "Search pattern (substring match, or glob with wildcards like *.rs)"
                        },
                        "type": {
                            "type": "string",
                            "enum": ["file", "dir", "all"],
                            "description": "Type to search for (default: all)"
                        },
                        "max_depth": {
                            "type": "number",
                            "description": "Maximum directory depth to search (default: unlimited)"
                        },
                        "max_results": {
                            "type": "number",
                            "description": "Maximum number of results to return (default: 1000)"
                        }
                    },
                    "required": ["path", "pattern"]
                }
            }),
            json!({
                "name": "fs_ld",
                "description": "List directory contents with details (like ls -la)",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "path": {
                            "type": "string",
                            "description": "Path to list"
                        }
                    },
                    "required": ["path"]
                }
            }),
            json!({
                "name": "fs_stat",
                "description": "Get file/directory metadata and statistics",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "path": {
                            "type": "string",
                            "description": "Path to get stats for"
                        }
                    },
                    "required": ["path"]
                }
            }),
            json!({
                "name": "fs_permissions",
                "description": "Get or set file permissions",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "path": {
                            "type": "string",
                            "description": "Path to file/directory"
                        },
                        "mode": {
                            "type": "string",
                            "description": "Permission mode (e.g., '755', '644') - omit to get current permissions"
                        }
                    },
                    "required": ["path"]
                }
            }),
            json!({
                "name": "fs_watch",
                "description": "Watch a file or directory for changes",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "path": {
                            "type": "string",
                            "description": "Path to watch"
                        },
                        "duration": {
                            "type": "number",
                            "description": "Duration to watch in seconds (default: 60)"
                        }
                    },
                    "required": ["path"]
                }
            }),
            json!({
                "name": "fs_snapshot",
                "description": "Create lightweight timestamped backups with automatic management",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "path": {
                            "type": "string",
                            "description": "Path to snapshot"
                        },
                        "max_snapshots": {
                            "type": "number",
                            "description": "Maximum number of snapshots to keep (default: 10)"
                        }
                    },
                    "required": ["path"]
                }
            }),
            json!({
                "name": "fs_tree",
                "description": "Display a visual directory tree structure. Much faster than recursive fs_find + fs_ld for understanding project layout.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "path": {
                            "type": "string",
                            "description": "Root directory path"
                        },
                        "max_depth": {
                            "type": "number",
                            "description": "Maximum depth to display (default: 4)"
                        },
                        "show_hidden": {
                            "type": "boolean",
                            "description": "Show hidden files/directories (default: false)"
                        },
                        "show_size": {
                            "type": "boolean",
                            "description": "Show file sizes (default: false)"
                        },
                        "dirs_only": {
                            "type": "boolean",
                            "description": "Only show directories (default: false)"
                        },
                        "pattern": {
                            "type": "string",
                            "description": "Only show entries matching this pattern (substring match)"
                        }
                    },
                    "required": ["path"]
                }
            }),
            json!({
                "name": "fs_grep",
                "description": "Search file contents by pattern across a directory. Returns matching lines with file paths and line numbers.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "path": {
                            "type": "string",
                            "description": "File or directory to search in"
                        },
                        "pattern": {
                            "type": "string",
                            "description": "Search pattern (regex supported)"
                        },
                        "case_insensitive": {
                            "type": "boolean",
                            "description": "Case-insensitive search (default: false)"
                        },
                        "max_results": {
                            "type": "number",
                            "description": "Maximum number of matches to return (default: 200)"
                        },
                        "context_lines": {
                            "type": "number",
                            "description": "Number of context lines before/after each match (default: 0)"
                        },
                        "file_pattern": {
                            "type": "string",
                            "description": "Only search files matching this pattern (e.g. '*.rs', '*.py')"
                        }
                    },
                    "required": ["path", "pattern"]
                }
            }),
            json!({
                "name": "fs_tail",
                "description": "Read the last N lines of a file. Essential for reading log files and build output.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "path": {
                            "type": "string",
                            "description": "Path to the file"
                        },
                        "lines": {
                            "type": "number",
                            "description": "Number of lines from the end (default: 20)"
                        }
                    },
                    "required": ["path"]
                }
            }),
            json!({
                "name": "fs_replace",
                "description": "Find and replace text across one or multiple files. Supports regex patterns and directory-wide bulk replacement.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "path": {
                            "type": "string",
                            "description": "File or directory to perform replacements in"
                        },
                        "find": {
                            "type": "string",
                            "description": "Text or regex pattern to find"
                        },
                        "replace": {
                            "type": "string",
                            "description": "Replacement text (supports $1 capture groups with regex)"
                        },
                        "regex": {
                            "type": "boolean",
                            "description": "Treat find as regex pattern (default: false)"
                        },
                        "file_pattern": {
                            "type": "string",
                            "description": "Only process files matching this pattern (e.g. '*.rs') — required for directories"
                        },
                        "dry_run": {
                            "type": "boolean",
                            "description": "Preview changes without writing (default: false)"
                        }
                    },
                    "required": ["path", "find", "replace"]
                }
            }),
        ]
    }

    pub async fn read(&self, args: Value) -> Result<Value> {
        let path = args["path"].as_str().context("Missing 'path' parameter")?;
        let full_content = fs::read_to_string(path)
            .with_context(|| format!("Failed to read file: {}", path))?;

        if let Some(lines_array) = args.get("lines").and_then(|v| v.as_array()) {
            let all_lines: Vec<&str> = full_content.lines().collect();
            let total_lines = all_lines.len();
            let mut selected_lines = Vec::new();

            for range in lines_array {
                if let Some(range_arr) = range.as_array() {
                    if range_arr.len() == 2 {
                        let from = range_arr[0].as_i64().unwrap_or(1) as usize;
                        let to = range_arr[1].as_i64().unwrap_or(all_lines.len() as i64) as usize;
                        let from_idx = from.saturating_sub(1);
                        let to_idx = to.min(all_lines.len());
                        if from_idx < all_lines.len() && from_idx < to_idx {
                            selected_lines.extend_from_slice(&all_lines[from_idx..to_idx]);
                        }
                    }
                }
            }

            let content = selected_lines.join("\n");
            Ok(json!({
                "path": path,
                "content": content,
                "size": content.len(),
                "total_lines": total_lines
            }))
        } else {
            let total_lines = bytecount_lines(&full_content);
            let size = full_content.len();
            Ok(json!({
                "path": path,
                "content": full_content,
                "size": size,
                "total_lines": total_lines
            }))
        }
    }

    pub async fn write(&self, args: Value) -> Result<Value> {
        let path = args["path"].as_str().context("Missing 'path' parameter")?;
        let content = args["content"].as_str().context("Missing 'content' parameter")?;

        // Check if lines parameter is provided
        let final_content = if let Some(lines_array) = args.get("lines").and_then(|v| v.as_array()) {
            // Read existing file or create empty if not exists
            let existing_content = fs::read_to_string(path).unwrap_or_default();
            let mut all_lines: Vec<String> = existing_content.lines().map(|s| s.to_string()).collect();
            let new_lines: Vec<&str> = content.lines().collect();
            let mut new_line_idx = 0;

            for range in lines_array {
                if let Some(range_arr) = range.as_array() {
                    if range_arr.len() == 2 {
                        let from = range_arr[0].as_i64().unwrap_or(1) as usize;
                        let to = range_arr[1].as_i64().unwrap_or(all_lines.len() as i64) as usize;

                        // Convert from 1-indexed to 0-indexed
                        let from_idx = from.saturating_sub(1);
                        let to_idx = to.min(all_lines.len());

                        // Calculate how many lines to replace
                        let range_size = to_idx.saturating_sub(from_idx);

                        // Extend file if needed
                        while all_lines.len() < to_idx {
                            all_lines.push(String::new());
                        }

                        // Replace lines in this range with corresponding new lines
                        for i in 0..range_size {
                            if new_line_idx < new_lines.len() {
                                all_lines[from_idx + i] = new_lines[new_line_idx].to_string();
                                new_line_idx += 1;
                            }
                        }
                    }
                }
            }

            all_lines.join("\n") + "\n"
        } else {
            content.to_string()
        };

        fs::write(path, &final_content)
            .with_context(|| format!("Failed to write file: {}", path))?;

        Ok(json!({
            "success": true,
            "path": path,
            "bytes_written": final_content.len()
        }))
    }

    pub async fn move_file(&self, args: Value) -> Result<Value> {
        let source = args["source"].as_str().context("Missing 'source' parameter")?;
        let destination = args["destination"].as_str().context("Missing 'destination' parameter")?;

        fs::rename(source, destination)
            .with_context(|| format!("Failed to move from {} to {}", source, destination))?;

        Ok(json!({
            "success": true,
            "source": source,
            "destination": destination
        }))
    }

    pub async fn copy(&self, args: Value) -> Result<Value> {
        let source = args["source"].as_str().context("Missing 'source' parameter")?;
        let destination = args["destination"].as_str().context("Missing 'destination' parameter")?;

        let source_path = Path::new(source);

        if source_path.is_file() {
            fs::copy(source, destination)
                .with_context(|| format!("Failed to copy file from {} to {}", source, destination))?;
        } else if source_path.is_dir() {
            copy_dir_all(source, destination)
                .with_context(|| format!("Failed to copy directory from {} to {}", source, destination))?;
        } else {
            anyhow::bail!("Source path does not exist: {}", source);
        }

        Ok(json!({
            "success": true,
            "source": source,
            "destination": destination
        }))
    }

    pub async fn create(&self, args: Value) -> Result<Value> {
        let path = args["path"].as_str().context("Missing 'path' parameter")?;
        let type_str = args["type"].as_str().context("Missing 'type' parameter")?;

        match type_str {
            "file" => {
                fs::File::create(path)
                    .with_context(|| format!("Failed to create file: {}", path))?;
            }
            "dir" => {
                fs::create_dir_all(path)
                    .with_context(|| format!("Failed to create directory: {}", path))?;
            }
            _ => anyhow::bail!("Invalid type: {}. Must be 'file' or 'dir'", type_str),
        }

        Ok(json!({
            "success": true,
            "path": path,
            "type": type_str
        }))
    }

    pub async fn delete(&self, args: Value) -> Result<Value> {
        let path = args["path"].as_str().context("Missing 'path' parameter")?;
        let path_obj = Path::new(path);

        if path_obj.is_file() {
            fs::remove_file(path)
                .with_context(|| format!("Failed to delete file: {}", path))?;
        } else if path_obj.is_dir() {
            fs::remove_dir_all(path)
                .with_context(|| format!("Failed to delete directory: {}", path))?;
        } else {
            anyhow::bail!("Path does not exist: {}", path);
        }

        Ok(json!({
            "success": true,
            "path": path
        }))
    }

    pub async fn move_desktop(&self, args: Value) -> Result<Value> {
        let item = args["item"].as_str().context("Missing 'item' parameter")?;
        let destination = args["destination"].as_str().context("Missing 'destination' parameter")?;

        // Get Desktop path
        let desktop = dirs::desktop_dir()
            .context("Could not find Desktop directory")?;

        let source_path = desktop.join(item);
        let dest_path = desktop.join(destination).join(item);

        // Create destination directory if it doesn't exist
        if let Some(parent) = dest_path.parent() {
            fs::create_dir_all(parent)?;
        }

        fs::rename(&source_path, &dest_path)
            .with_context(|| format!("Failed to move {} to {}", source_path.display(), dest_path.display()))?;

        Ok(json!({
            "success": true,
            "item": item,
            "from": source_path,
            "to": dest_path
        }))
    }

    pub async fn find(&self, args: Value) -> Result<Value> {
        let root_path = args["path"].as_str().context("Missing 'path' parameter")?;
        let pattern = args["pattern"].as_str().context("Missing 'pattern' parameter")?;
        let search_type = args["type"].as_str().unwrap_or("all");
        let max_results = args["max_results"].as_u64().unwrap_or(1000) as usize;

        let mut walker = WalkDir::new(root_path);
        if let Some(depth) = args["max_depth"].as_u64() {
            walker = walker.max_depth(depth as usize);
        }

        // Determine if pattern is a glob (contains * or ?)
        let is_glob = pattern.contains('*') || pattern.contains('?');

        let mut results = Vec::new();

        for entry in walker.into_iter().filter_map(|e| e.ok()) {
            if results.len() >= max_results {
                break;
            }

            let path = entry.path();
            let file_name = entry.file_name().to_string_lossy();

            let matches = if is_glob {
                glob_match(pattern, &file_name)
            } else {
                file_name.contains(pattern) || path.to_string_lossy().contains(pattern)
            };

            if !matches {
                continue;
            }

            // Type filtering
            match search_type {
                "file" if !path.is_file() => continue,
                "dir" if !path.is_dir() => continue,
                _ => {}
            }

            let size = path.metadata().map(|m| m.len()).unwrap_or(0);

            results.push(json!({
                "path": path.to_string_lossy(),
                "name": file_name,
                "type": if path.is_file() { "file" } else { "dir" },
                "size": size
            }));
        }

        let truncated = results.len() >= max_results;

        Ok(json!({
            "results": results,
            "count": results.len(),
            "truncated": truncated
        }))
    }

    pub async fn ld(&self, args: Value) -> Result<Value> {
        let path = args["path"].as_str().context("Missing 'path' parameter")?;
        let path_obj = Path::new(path);

        if !path_obj.exists() {
            anyhow::bail!("Path does not exist: {}", path);
        }

        let mut entries = Vec::new();

        for entry in fs::read_dir(path)? {
            let entry = entry?;
            let metadata = entry.metadata()?;
            let file_name = entry.file_name().to_string_lossy().to_string();

            #[cfg(unix)]
            use std::os::unix::fs::PermissionsExt;

            #[cfg(unix)]
            let permissions = format!("{:o}", metadata.permissions().mode() & 0o777);

            #[cfg(not(unix))]
            let permissions = if metadata.permissions().readonly() {
                "r--".to_string()
            } else {
                "rw-".to_string()
            };

            entries.push(json!({
                "name": file_name,
                "type": if metadata.is_file() { "file" } else if metadata.is_dir() { "dir" } else { "other" },
                "size": metadata.len(),
                "permissions": permissions,
                "modified": metadata.modified().ok().and_then(|t| {
                    t.duration_since(std::time::UNIX_EPOCH).ok().map(|d| d.as_secs())
                })
            }));
        }

        Ok(json!({
            "path": path,
            "entries": entries,
            "count": entries.len()
        }))
    }

    pub async fn stat(&self, args: Value) -> Result<Value> {
        let path = args["path"].as_str().context("Missing 'path' parameter")?;
        let metadata = fs::metadata(path)
            .with_context(|| format!("Failed to get metadata for: {}", path))?;

        #[cfg(unix)]
        use std::os::unix::fs::PermissionsExt;

        #[cfg(unix)]
        let permissions = format!("{:o}", metadata.permissions().mode() & 0o777);

        #[cfg(not(unix))]
        let permissions = if metadata.permissions().readonly() {
            "readonly".to_string()
        } else {
            "read-write".to_string()
        };

        Ok(json!({
            "path": path,
            "type": if metadata.is_file() { "file" } else if metadata.is_dir() { "dir" } else { "other" },
            "size": metadata.len(),
            "permissions": permissions,
            "readonly": metadata.permissions().readonly(),
            "created": metadata.created().ok().and_then(|t| {
                t.duration_since(std::time::UNIX_EPOCH).ok().map(|d| d.as_secs())
            }),
            "modified": metadata.modified().ok().and_then(|t| {
                t.duration_since(std::time::UNIX_EPOCH).ok().map(|d| d.as_secs())
            }),
            "accessed": metadata.accessed().ok().and_then(|t| {
                t.duration_since(std::time::UNIX_EPOCH).ok().map(|d| d.as_secs())
            })
        }))
    }

    pub async fn permissions(&self, args: Value) -> Result<Value> {
        let path = args["path"].as_str().context("Missing 'path' parameter")?;

        if let Some(mode_str) = args["mode"].as_str() {
            // Set permissions
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                let mode = u32::from_str_radix(mode_str, 8)
                    .with_context(|| format!("Invalid permission mode: {}", mode_str))?;
                let permissions = std::fs::Permissions::from_mode(mode);
                fs::set_permissions(path, permissions)
                    .with_context(|| format!("Failed to set permissions for: {}", path))?;

                Ok(json!({
                    "success": true,
                    "path": path,
                    "mode": mode_str
                }))
            }

            #[cfg(not(unix))]
            {
                anyhow::bail!("Setting permissions is only supported on Unix systems");
            }
        } else {
            // Get permissions
            let metadata = fs::metadata(path)?;

            #[cfg(unix)]
            use std::os::unix::fs::PermissionsExt;

            #[cfg(unix)]
            let mode = format!("{:o}", metadata.permissions().mode() & 0o777);

            #[cfg(not(unix))]
            let mode = if metadata.permissions().readonly() {
                "readonly"
            } else {
                "read-write"
            };

            Ok(json!({
                "path": path,
                "mode": mode,
                "readonly": metadata.permissions().readonly()
            }))
        }
    }

    pub async fn watch(&self, args: Value) -> Result<Value> {
        let path = args["path"].as_str().context("Missing 'path' parameter")?;
        let duration = args["duration"].as_u64().unwrap_or(60);
        let path_owned = path.to_string();

        let events = tokio::task::spawn_blocking(move || -> Result<Vec<Value>> {
            let (tx, rx) = std::sync::mpsc::channel();
            let mut watcher = notify::recommended_watcher(tx)?;
            watcher.watch(Path::new(&path_owned), RecursiveMode::Recursive)?;

            let mut events = Vec::new();
            let start = std::time::Instant::now();

            while start.elapsed().as_secs() < duration {
                if let Ok(Ok(event)) = rx.recv_timeout(std::time::Duration::from_secs(1)) {
                    events.push(json!({
                        "kind": format!("{:?}", event.kind),
                        "paths": event.paths.iter().map(|p| p.to_string_lossy()).collect::<Vec<_>>()
                    }));
                }
            }
            Ok(events)
        }).await??;

        Ok(json!({
            "path": path,
            "duration": duration,
            "events": events,
            "event_count": events.len()
        }))
    }

    pub async fn snapshot(&self, args: Value) -> Result<Value> {
        let path = args["path"].as_str().context("Missing 'path' parameter")?;
        let max_snapshots = args["max_snapshots"].as_u64().unwrap_or(10) as usize;

        let path_obj = Path::new(path);
        if !path_obj.exists() {
            anyhow::bail!("Path does not exist: {}", path);
        }

        // Create snapshot directory
        let snapshot_dir = path_obj.parent()
            .unwrap_or_else(|| Path::new("."))
            .join(".snapshots")
            .join(path_obj.file_name().unwrap_or(path_obj.as_os_str()));

        fs::create_dir_all(&snapshot_dir)?;

        // Create timestamp
        let timestamp = Local::now().format("%Y%m%d_%H%M%S").to_string();
        let snapshot_name = format!("snapshot_{}", timestamp);
        let snapshot_path = snapshot_dir.join(&snapshot_name);

        // Copy the file/directory
        if path_obj.is_file() {
            fs::copy(path, &snapshot_path)?;
        } else {
            copy_dir_all(path, &snapshot_path)?;
        }

        // Store snapshot info
        let mut snapshots = self.snapshots.lock().unwrap();
        let key = path.to_string();
        let snapshot_list = snapshots.entry(key.clone()).or_default();

        snapshot_list.push(SnapshotInfo {
            timestamp: timestamp.clone(),
            path: snapshot_path.clone(),
            compressed: false,
        });

        // Manage snapshots (compress old ones, delete oldest)
        if snapshot_list.len() > max_snapshots {
            // Compress older snapshots
            for snapshot in snapshot_list.iter_mut().rev().skip(3) {
                if !snapshot.compressed {
                    // TODO: Implement compression
                    snapshot.compressed = true;
                }
            }

            // Remove oldest snapshots
            while snapshot_list.len() > max_snapshots {
                if let Some(oldest) = snapshot_list.first() {
                    if oldest.path.exists() {
                        if oldest.path.is_file() {
                            fs::remove_file(&oldest.path)?;
                        } else {
                            fs::remove_dir_all(&oldest.path)?;
                        }
                    }
                }
                snapshot_list.remove(0);
            }
        }

        Ok(json!({
            "success": true,
            "path": path,
            "snapshot": snapshot_path,
            "timestamp": timestamp,
            "total_snapshots": snapshot_list.len(),
            "max_snapshots": max_snapshots
        }))
    }

    pub async fn tree(&self, args: Value) -> Result<Value> {
        let path = args["path"].as_str().context("Missing 'path' parameter")?;
        let max_depth = args["max_depth"].as_u64().unwrap_or(4) as usize;
        let show_hidden = args["show_hidden"].as_bool().unwrap_or(false);
        let show_size = args["show_size"].as_bool().unwrap_or(false);
        let dirs_only = args["dirs_only"].as_bool().unwrap_or(false);
        let pattern = args["pattern"].as_str();

        let root = Path::new(path);
        if !root.exists() {
            anyhow::bail!("Path does not exist: {}", path);
        }

        let mut output = String::new();
        let mut file_count = 0usize;
        let mut dir_count = 0usize;

        output.push_str(&format!("{}\n", root.display()));
        build_tree(root, "", max_depth, 0, show_hidden, show_size, dirs_only, pattern, &mut output, &mut file_count, &mut dir_count)?;

        Ok(json!({
            "tree": output,
            "path": path,
            "directories": dir_count,
            "files": file_count,
            "max_depth": max_depth
        }))
    }

    pub async fn grep(&self, args: Value) -> Result<Value> {
        let path = args["path"].as_str().context("Missing 'path' parameter")?;
        let pattern = args["pattern"].as_str().context("Missing 'pattern' parameter")?;
        let case_insensitive = args["case_insensitive"].as_bool().unwrap_or(false);
        let max_results = args["max_results"].as_u64().unwrap_or(200) as usize;
        let context_lines = args["context_lines"].as_u64().unwrap_or(0) as usize;
        let file_pattern = args["file_pattern"].as_str();

        let mut regex_pattern = String::new();
        if case_insensitive {
            regex_pattern.push_str("(?i)");
        }
        regex_pattern.push_str(pattern);

        let re = Regex::new(&regex_pattern)
            .with_context(|| format!("Invalid regex pattern: {}", pattern))?;

        let root = Path::new(path);
        let mut matches = Vec::new();
        let mut files_searched = 0usize;

        if root.is_file() {
            files_searched = 1;
            search_file(root, &re, max_results, context_lines, &mut matches);
        } else {
            for entry in WalkDir::new(root).into_iter().filter_map(|e| e.ok()) {
                if matches.len() >= max_results {
                    break;
                }
                if !entry.path().is_file() {
                    continue;
                }
                if let Some(fp) = file_pattern {
                    let name = entry.file_name().to_string_lossy();
                    if !glob_match(fp, &name) {
                        continue;
                    }
                }
                files_searched += 1;
                search_file(entry.path(), &re, max_results, context_lines, &mut matches);
            }
        }

        let truncated = matches.len() >= max_results;

        Ok(json!({
            "matches": matches,
            "count": matches.len(),
            "files_searched": files_searched,
            "pattern": pattern,
            "truncated": truncated
        }))
    }

    pub async fn tail(&self, args: Value) -> Result<Value> {
        let path = args["path"].as_str().context("Missing 'path' parameter")?;
        let n = args["lines"].as_u64().unwrap_or(20) as usize;

        let content = fs::read_to_string(path)
            .with_context(|| format!("Failed to read file: {}", path))?;

        // Count total and find the start of the last N lines in a single pass
        let mut total = 0usize;
        let mut newline_positions = Vec::new(); // store byte offsets of newlines
        for (i, b) in content.as_bytes().iter().enumerate() {
            if *b == b'\n' {
                newline_positions.push(i);
                total += 1;
            }
        }
        // Account for last line without trailing newline
        if !content.is_empty() && !content.ends_with('\n') {
            total += 1;
        }

        let start_line = total.saturating_sub(n);
        let byte_start = if start_line == 0 {
            0
        } else if start_line <= newline_positions.len() {
            newline_positions[start_line - 1] + 1
        } else {
            content.len()
        };

        let tail_content = &content[byte_start..];
        let lines_returned = total - start_line;

        Ok(json!({
            "path": path,
            "content": tail_content.trim_end_matches('\n'),
            "lines_returned": lines_returned,
            "total_lines": total,
            "from_line": start_line + 1
        }))
    }

    pub async fn replace(&self, args: Value) -> Result<Value> {
        let path = args["path"].as_str().context("Missing 'path' parameter")?;
        let find = args["find"].as_str().context("Missing 'find' parameter")?;
        let replace_with = args["replace"].as_str().context("Missing 'replace' parameter")?;
        let use_regex = args["regex"].as_bool().unwrap_or(false);
        let dry_run = args["dry_run"].as_bool().unwrap_or(false);
        let file_pattern = args["file_pattern"].as_str();

        let root = Path::new(path);

        let files: Vec<PathBuf> = if root.is_file() {
            vec![root.to_path_buf()]
        } else if root.is_dir() {
            let fp = file_pattern.context("'file_pattern' is required when path is a directory")?;
            WalkDir::new(root)
                .into_iter()
                .filter_map(|e| e.ok())
                .filter(|e| e.path().is_file())
                .filter(|e| glob_match(fp, &e.file_name().to_string_lossy()))
                .map(|e| e.path().to_path_buf())
                .collect()
        } else {
            anyhow::bail!("Path does not exist: {}", path);
        };

        let re = if use_regex {
            Some(Regex::new(find).with_context(|| format!("Invalid regex: {}", find))?)
        } else {
            None
        };

        let mut results = Vec::new();
        let mut total_replacements = 0usize;

        for file_path in &files {
            let content = match fs::read_to_string(file_path) {
                Ok(c) => c,
                Err(_) => continue,
            };

            let (new_content, count) = if let Some(ref re) = re {
                let count = re.find_iter(&content).count();
                if count == 0 {
                    (content, 0)
                } else {
                    let replaced = re.replace_all(&content, replace_with).to_string();
                    (replaced, count)
                }
            } else {
                let count = content.matches(find).count();
                let replaced = content.replace(find, replace_with);
                (replaced, count)
            };

            if count > 0 {
                if !dry_run {
                    fs::write(file_path, &new_content)
                        .with_context(|| format!("Failed to write: {}", file_path.display()))?;
                }
                total_replacements += count;
                results.push(json!({
                    "file": file_path.to_string_lossy(),
                    "replacements": count
                }));
            }
        }

        Ok(json!({
            "success": true,
            "dry_run": dry_run,
            "files_modified": results.len(),
            "total_replacements": total_replacements,
            "files_searched": files.len(),
            "details": results
        }))
    }
}

/// Fast line counting using memchr for newline bytes
fn bytecount_lines(s: &str) -> usize {
    if s.is_empty() { return 0; }
    let count = s.as_bytes().iter().filter(|&&b| b == b'\n').count();
    // If the string doesn't end with newline, add 1 for the last line
    if s.ends_with('\n') { count } else { count + 1 }
}

fn search_file(file_path: &Path, re: &Regex, max_results: usize, context_lines: usize, matches: &mut Vec<Value>) {
    let content = match fs::read_to_string(file_path) {
        Ok(c) => c,
        Err(_) => return,
    };

    let lines: Vec<&str> = content.lines().collect();

    for (line_num, line) in lines.iter().enumerate() {
        if matches.len() >= max_results {
            return;
        }
        if !re.is_match(line) {
            continue;
        }

        let mut entry = json!({
            "file": file_path.to_string_lossy(),
            "line": line_num + 1,
            "content": line
        });

        if context_lines > 0 {
            let start = line_num.saturating_sub(context_lines);
            let end = (line_num + 1 + context_lines).min(lines.len());
            entry["context_before"] = json!(&lines[start..line_num]);
            entry["context_after"] = json!(&lines[line_num + 1..end]);
        }

        matches.push(entry);
    }
}


fn build_tree(
    dir: &Path,
    prefix: &str,
    max_depth: usize,
    current_depth: usize,
    show_hidden: bool,
    show_size: bool,
    dirs_only: bool,
    pattern: Option<&str>,
    output: &mut String,
    file_count: &mut usize,
    dir_count: &mut usize,
) -> Result<()> {
    if current_depth >= max_depth {
        return Ok(());
    }

    let mut entries: Vec<_> = fs::read_dir(dir)?
        .filter_map(|e| e.ok())
        .collect();

    entries.sort_by_key(|a| a.file_name());

    // Filter hidden files
    if !show_hidden {
        entries.retain(|e| {
            !e.file_name().to_string_lossy().starts_with('.')
        });
    }

    // Filter by pattern
    if let Some(pat) = pattern {
        entries.retain(|e| {
            let name = e.file_name().to_string_lossy().to_string();
            let is_dir = e.path().is_dir();
            is_dir || name.contains(pat) || glob_match(pat, &name)
        });
    }

    // Filter dirs_only
    if dirs_only {
        entries.retain(|e| e.path().is_dir());
    }

    let count = entries.len();

    for (i, entry) in entries.iter().enumerate() {
        let is_last = i == count - 1;
        let connector = if is_last { "└── " } else { "├── " };
        let name = entry.file_name().to_string_lossy().to_string();
        let path = entry.path();
        let is_dir = path.is_dir();

        let size_str = if show_size && !is_dir {
            let size = path.metadata().map(|m| m.len()).unwrap_or(0);
            format!(" ({})", format_size(size))
        } else {
            String::new()
        };

        let dir_marker = if is_dir { "/" } else { "" };

        output.push_str(&format!("{}{}{}{}{}\n", prefix, connector, name, dir_marker, size_str));

        if is_dir {
            *dir_count += 1;
            let new_prefix = format!("{}{}", prefix, if is_last { "    " } else { "│   " });
            build_tree(&path, &new_prefix, max_depth, current_depth + 1, show_hidden, show_size, dirs_only, pattern, output, file_count, dir_count)?;
        } else {
            *file_count += 1;
        }
    }

    Ok(())
}

fn format_size(bytes: u64) -> String {
    if bytes >= 1_073_741_824 {
        format!("{:.1}G", bytes as f64 / 1_073_741_824.0)
    } else if bytes >= 1_048_576 {
        format!("{:.1}M", bytes as f64 / 1_048_576.0)
    } else if bytes >= 1024 {
        format!("{:.1}K", bytes as f64 / 1024.0)
    } else {
        format!("{}B", bytes)
    }
}

/// Iterative glob matching using dynamic programming — O(n*m) worst-case
fn glob_match(pattern: &str, text: &str) -> bool {
    let pat: Vec<char> = pattern.chars().collect();
    let txt: Vec<char> = text.chars().collect();
    let (plen, tlen) = (pat.len(), txt.len());

    let mut pi = 0usize;
    let mut ti = 0usize;
    let mut star_pi = usize::MAX;
    let mut star_ti = 0usize;

    while ti < tlen {
        if pi < plen && (pat[pi] == '?' || pat[pi].to_lowercase().eq(txt[ti].to_lowercase())) {
            pi += 1;
            ti += 1;
        } else if pi < plen && pat[pi] == '*' {
            star_pi = pi;
            star_ti = ti;
            pi += 1;
        } else if star_pi != usize::MAX {
            pi = star_pi + 1;
            star_ti += 1;
            ti = star_ti;
        } else {
            return false;
        }
    }

    while pi < plen && pat[pi] == '*' {
        pi += 1;
    }

    pi == plen
}

// Helper function to copy directories recursively
fn copy_dir_all(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> Result<()> {
    fs::create_dir_all(&dst)?;

    for entry in fs::read_dir(src)? {
        let entry = entry?;
        let ty = entry.file_type()?;

        if ty.is_dir() {
            copy_dir_all(entry.path(), dst.as_ref().join(entry.file_name()))?;
        } else {
            fs::copy(entry.path(), dst.as_ref().join(entry.file_name()))?;
        }
    }

    Ok(())
}