-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpythonFileTools.py
More file actions
3078 lines (2644 loc) · 126 KB
/
Copy pathpythonFileTools.py
File metadata and controls
3078 lines (2644 loc) · 126 KB
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
"""
Python File Tools MCP Server
Version: 0.0.0 Experimental
A FastMCP-based server providing file manipulation tools for LLMs:
- list_folder: List directory contents with optional recursive mode
- search_file_content: Search files using regex patterns with configurable context lines and file filters
- read_file_content: Read file content with optional line range support (1-based indexing)
- edit_file: Apply text/regex/whitespace-tolerant/line-range edits to files, with git commit tracking for each change
- undo_edit: Revert file changes by checking out previous git commits
- preview_undo: Preview what changes would be made by an undo without applying them
- create_file: Create new files or overwrite existing ones, committed to git
- execute_command: Run bash commands and capture stdout/stderr with timeout support
- git_init: Initialize a git repository in a directory for edit tracking
All file operations are restricted to paths within the user's home directory. Each edit is committed to git for undo capability.
"""
import difflib
import math
import os
import re
import subprocess
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
# Security: Restrict file operations to home directory
HOME_DIR = Path.home().resolve()
from fastmcp import FastMCP
# Create a FastMCP server instance
mcp = FastMCP("Python File Tools")
# =============================================================================
# Configurable defaults (can be overridden via environment variables)
# =============================================================================
# Default number of lines to return from get_command_output when tail > 0.
# Override via environment variable: export MCP_DEFAULT_TAIL_LINES=30
_DEFAULT_TAIL_LINES = int(os.environ.get("MCP_DEFAULT_TAIL_LINES", "20"))
@mcp.tool()
def list_folder(path: str, recursive: bool = False) -> dict:
"""List the contents of a folder.
Args:
path: The directory path to list
recursive: If True, list files recursively. Default: False
Returns:
A dictionary with directory info and list of files/folders
"""
dir_path = Path(path)
if not dir_path.exists():
raise FileNotFoundError(f"Directory not found: {path}")
if not dir_path.is_dir():
raise NotADirectoryError(f"Not a directory: {path}")
entries = []
if recursive:
for item in dir_path.rglob("*"):
entries.append({
"name": item.name,
"path": str(item.relative_to(dir_path)),
"type": "directory" if item.is_dir() else "file",
})
else:
for item in dir_path.iterdir():
entries.append({
"name": item.name,
"path": item.name,
"type": "directory" if item.is_dir() else "file",
})
return {
"path": str(dir_path.resolve()),
"recursive": recursive,
"total_count": len(entries),
"entries": entries,
}
@mcp.tool()
def search_file_content(
pattern: str,
path: str = ".",
file_pattern: str = "*",
max_results: int = 50,
context_before: int = 0,
context_after: int = 0,
) -> dict:
"""Search for a regex pattern in file contents.
The search uses regular expressions, which makes it very powerful and flexible. Here are some tips for effective searching:
TIP 1 - Use multiple keywords with alternation (|): When you're looking for files that might contain any of several related terms, use the pipe character `|` to separate them. For example:
pattern="directory|path|folder"
This will match ANY line containing AT LEAST ONE of those words. This is especially useful when you're unsure which term the code uses - you'll catch all variations in one search instead of running multiple queries.
TIP 2 - Case-insensitive by default: The search is case-INSENSITIVE, so "Path", "PATH", and "path" will all match with a single pattern like `(?i)pat`. This means you don't need to worry about capitalization when searching.
TIP 3 - Combine OR and AND logic: Use `|` for OR (at least one matches) and simple concatenation for AND (all terms must appear). For example:
pattern="import|from" finds lines with either word (OR)
pattern="importos" finds lines containing both words together (AND)
Args:
pattern: The regular expression pattern to search for
path: The directory to search in. Default: current directory
file_pattern: Glob pattern to filter files (e.g., '*.py'). Default: all files
max_results: Maximum number of results to return. Default: 50
context_before: Number of lines before the match to include as context. Default: 0
context_after: Number of lines after the match to include as context. Default: 0
Returns:
A dictionary with search metadata and a list of matches including optional context lines
"""
search_path = Path(path)
if not search_path.exists():
raise FileNotFoundError(f"Search path not found: {path}")
if not search_path.is_dir():
raise NotADirectoryError(f"Not a directory: {path}")
try:
compiled_pattern = re.compile(pattern)
except re.error as e:
raise ValueError(f"Invalid regular expression: {e}")
matches = []
files_checked = 0
if file_pattern == "*":
file_paths = list(search_path.glob("**/*"))
else:
file_paths = list(search_path.glob(f"**/{file_pattern}"))
for file_path in file_paths:
if max_results is not None and len(matches) >= max_results:
break
if not file_path.is_file():
continue
files_checked += 1
try:
text = file_path.read_text(encoding="utf-8", errors="ignore")
except (PermissionError, OSError):
continue
lines = text.splitlines()
for line_idx, line in enumerate(lines):
if compiled_pattern.search(line):
start = max(0, line_idx - context_before)
end = min(len(lines), line_idx + 1 + context_after)
context_lines = []
for ctx_idx in range(start, end):
context_lines.append({
"line_number": ctx_idx + 1,
"content": lines[ctx_idx],
"is_match_line": ctx_idx == line_idx,
})
match_info = {
"file": str(file_path.relative_to(search_path)),
"line": line_idx + 1,
"match": compiled_pattern.search(line).group(),
"context": context_lines,
}
matches.append(match_info)
if max_results is not None and len(matches) >= max_results:
break
return {
"search_pattern": pattern,
"search_path": str(search_path.resolve()),
"file_pattern": file_pattern,
"files_checked": files_checked,
"total_matches": len(matches),
"context_before": context_before,
"context_after": context_after,
"results": matches,
}
def _validate_path(path: Path) -> Path:
"""Validate that a path is within the home directory for security."""
# Expand ~ (tilde) to user's home directory before resolving
expanded = os.path.expanduser(str(path))
resolved = Path(expanded).resolve()
if not str(resolved).startswith(str(HOME_DIR)):
raise ValueError(f"Access denied: paths outside home directory are not allowed. Requested: {resolved}")
return resolved
def _apply_changes_to_content(original_content: str, changes: list) -> tuple[str, list]:
"""Apply changes to content in memory and return (new_content, applied_changes_log)."""
applied_changes = []
current_content = original_content
for i, change in enumerate(changes):
mode = change.get("mode", "exact")
if mode == "whitespace_tolerant":
search_str = change.get("search", "")
replace_str = change.get("replace", "")
def _normalize_ws(text):
return " ".join(text.split())
norm_search = _normalize_ws(search_str)
norm_content = _normalize_ws(current_content)
if norm_search not in norm_content:
applied_changes.append({
"index": i,
"search": search_str,
"replace": replace_str,
"mode": mode,
"status": "not_found",
"message": "Search string (whitespace-normalized) not found in file",
})
continue
# Treat empty normalized search as "append to end"
if norm_search == "":
norm_replace = _normalize_ws(replace_str)
current_content = current_content + norm_replace
applied_changes.append({
"index": i,
"search": search_str,
"replace": replace_str,
"mode": mode,
"status": "proposed",
"replacements_made": 1,
})
else:
norm_replace = _normalize_ws(replace_str)
def _norm_to_orig_pos(norm_pos, content):
"""Convert a position in normalized content to corresponding position in original."""
nc = 0
pos = 0
while pos < len(content) and nc < norm_pos:
if content[pos].isspace():
while pos < len(content) and content[pos].isspace():
pos += 1
nc += 1
else:
nc += 1
pos += 1
return pos
# Build result by processing each match in normalized content,
# converting all positions from normalized to original content coordinates
orig_parts = []
last_end_norm = 0
for m in re.finditer(re.escape(norm_search), norm_content):
before_start_orig = _norm_to_orig_pos(last_end_norm, current_content)
before_end_orig = _norm_to_orig_pos(m.start(), current_content)
orig_parts.append(current_content[before_start_orig:before_end_orig])
orig_parts.append(norm_replace)
last_end_norm = m.end()
# Add remaining part after all matches
final_before_start = _norm_to_orig_pos(last_end_norm, current_content)
orig_parts.append(current_content[final_before_start:])
current_content = "".join(orig_parts)
applied_changes.append({
"index": i,
"search": search_str,
"replace": replace_str,
"mode": mode,
"status": "proposed",
"replacements_made": 1,
})
elif mode == "regex":
pattern = change.get("pattern") or change.get("search", "")
flags_str = change.get("flags", "")
replace_str = change.get("replace", "")
try:
compiled = re.compile(pattern, flags=int(flags_str) if flags_str else 0)
except Exception as e:
applied_changes.append({
"index": i,
"pattern": pattern,
"status": "error",
"message": f"Invalid regex pattern: {e}",
})
continue
match_objs = list(compiled.finditer(current_content))
if not match_objs:
applied_changes.append({
"index": i,
"pattern": pattern,
"status": "not_found",
"message": "Pattern not found in file",
})
continue
# Treat empty pattern as "append to end"
if pattern == "":
current_content = current_content + replace_str
applied_changes.append({
"index": i,
"pattern": pattern,
"replace": replace_str,
"mode": mode,
"status": "proposed",
"replacements_made": 1,
})
else:
current_content = compiled.sub(replace_str, current_content)
applied_changes.append({
"index": i,
"pattern": pattern,
"replace": replace_str,
"mode": mode,
"status": "proposed",
"replacements_made": len(match_objs),
})
elif mode == "line_range":
start_line = change.get("start_line")
end_line = change.get("end_line")
replacement_content = change.get("replacement_content", "")
if start_line is None or end_line is None:
applied_changes.append({
"index": i,
"status": "error",
"message": "'line_range' mode requires 'start_line' and 'end_line' fields (1-indexed)",
})
continue
lines = current_content.splitlines()
s_idx = max(0, start_line - 1)
e_idx = min(len(lines), end_line)
if s_idx >= len(lines):
applied_changes.append({
"index": i,
"start_line": start_line,
"end_line": end_line,
"status": "not_found",
"message": f"Line range [{start_line}, {end_line}] is beyond file length ({len(lines)} lines)",
})
continue
current_content = "\n".join(
lines[:s_idx] + [replacement_content] + lines[e_idx:]
)
applied_changes.append({
"index": i,
"start_line": start_line,
"end_line": end_line,
"replacement_content": replacement_content,
"mode": mode,
"status": "proposed",
"lines_replaced": e_idx - s_idx,
})
else: # exact (default)
search_str = change.get("search", "")
replace_str = change.get("replace", "")
if search_str not in current_content:
applied_changes.append({
"index": i,
"search": search_str,
"replace": replace_str,
"status": "not_found",
"message": "Search string not found in file",
})
continue
# Treat empty search string as "append to end"
if search_str == "":
current_content = current_content + replace_str
applied_changes.append({
"index": i,
"search": search_str,
"replace": replace_str,
"status": "proposed",
"replacements_made": 1,
})
else:
old_count = current_content.count(search_str)
new_content_after_replace = current_content.replace(search_str, replace_str)
replacements_made = old_count - (new_content_after_replace.count(search_str))
applied_changes.append({
"index": i,
"search": search_str,
"replace": replace_str,
"status": "proposed",
"replacements_made": replacements_made,
})
current_content = new_content_after_replace
return current_content, applied_changes
@mcp.tool()
def read_file_content(
path: str,
start_line: int = None,
end_line: int = None,
encoding: str = "utf-8",
) -> dict:
"""Read and return the content of a file (similar to cat in command line).
⚠️ IMPORTANT - Common Pitfalls:
- REQUIRED: `path` must be provided and must be an absolute path within your home directory (/home/user1/...).
- Paths outside your home directory are blocked for security. Use full absolute paths.
- Line numbers are 1-based (line 1 is the first line, not line 0).
- Always verify the file exists before editing — use this tool first, then `edit_file`.
Supports reading the entire file or a specific range of lines.
When line ranges are provided, only that portion is returned.
Args:
path: REQUIRED. The absolute file path (within home directory). Only paths within the home directory are allowed.
start_line: Optional 1-based line number to start reading from (inclusive). Default: first line.
end_line: Optional 1-based line number to stop reading at (inclusive). Default: last line.
encoding: The file encoding to use. Default: utf-8
Returns:
Dictionary with path, total_lines, content (full or filtered), and start/end line info.
"""
file_path = _validate_path(Path(path))
if not file_path.exists():
raise FileNotFoundError(f"File not found: {file_path}")
if not file_path.is_file():
raise IsADirectoryError(f"Not a file: {file_path}")
content = file_path.read_text(encoding=encoding)
lines = content.splitlines()
total_lines = len(lines)
# Adjust for 1-based indexing; clamp to valid range
if start_line is not None:
s_idx = max(0, start_line - 1)
else:
s_idx = 0
if end_line is not None:
e_idx = min(total_lines, end_line)
else:
e_idx = total_lines
# Slice the lines (handle empty file)
if not content:
selected_lines = []
else:
split_lines = content.splitlines()
selected_lines = split_lines[s_idx:e_idx]
return {
"path": str(file_path),
"total_lines": len(content.splitlines()),
"start_line": start_line,
"end_line": end_line,
"content": "\n".join(selected_lines),
}
@mcp.tool()
def edit_file(
path: str,
changes: list,
encoding: str = "utf-8",
git_dir: str = None,
) -> dict:
"""Apply edits to a file directly and commit the change to git (for undo capability).
⚠️ IMPORTANT - Common Pitfalls:
- REQUIRED: Both `path` and `changes` must be provided. `path` must be an absolute path within your home directory.
- REQUIRED: `changes` must be a JSON array `[...]` containing at least one change object.
- Each change object requires: `mode` (string), `search` (string), `replace` (string).
- The file must exist and reside in a git-initialized directory. If no git repo exists, run `git_init` first.
- Always use `read_file` first to verify the exact content you're searching for — typos in `search` cause "not found" errors.
- `git_dir` is OPTIONAL: Only provide it when the file is in a subdirectory of the git repo root.
Returns the applied changes as a diff. Each edit is committed to git so it can be undone later.
Supports four search modes specified per change object via the 'mode' field (defaults to 'exact'):
1. 'exact' - Standard exact string matching (default). Uses `search` and `replace` fields.
2. 'whitespace_tolerant' - Ignores differences in whitespace (spaces, tabs, newlines).
Normalizes all whitespace sequences to a single space for comparison.
3. 'regex' - Treats the search string as a regular expression pattern.
Supports back-references in replace via \\1, \\2, etc.
4. 'line_range' - Operates on line number ranges instead of text content.
Requires: `start_line`, `end_line`, `replacement_content` fields.
Args:
path: REQUIRED. The absolute file path (within home directory). Only paths within the home directory are allowed.
changes: REQUIRED. A list (array) of dictionaries describing each edit operation. See mode descriptions above.
encoding: The file encoding to use. Default: utf-8
git_dir: Optional path to the git repository root. If not specified, the file's parent directory is used.
Returns:
Dictionary with path, status ("success"/"no_changes"/"error"), content_changed, total_changes, applied_changes, diff, and commit_hash.
"""
file_path = _validate_path(Path(path))
if not file_path.exists():
raise FileNotFoundError(f"File not found: {file_path}")
if not file_path.is_file():
raise IsADirectoryError(f"Not a file: {file_path}")
original_content = file_path.read_text(encoding=encoding)
new_content, applied_changes = _apply_changes_to_content(original_content, changes)
content_changed = new_content != original_content
# Generate unified diff
if content_changed:
diff_lines = list(
difflib.unified_diff(
original_content.splitlines(keepends=True),
new_content.splitlines(keepends=True),
fromfile=f"a/{file_path.name}",
tofile=f"b/{file_path.name}",
)
)
else:
diff_lines = []
diff_output = "".join(diff_lines if diff_lines else "")
# Determine git directory for all operations
# If git_dir is specified, use it; otherwise fall back to file's parent directory
if git_dir is not None:
git_repo_dir = Path(git_dir)
else:
git_repo_dir = file_path.parent.resolve()
# Check if git is initialized in the specified directory or any parent directory BEFORE writing
def _is_git_repo(directory: Path) -> bool:
"""Check if a directory (or any of its ancestors) is a git repository."""
current = directory.resolve()
while True:
git_dir_path = current / ".git"
if git_dir_path.is_dir():
return True
parent = current.parent
if parent == current: # Reached root
break
current = parent
return False
if not _is_git_repo(git_repo_dir):
return {
"path": str(file_path),
"status": "error",
"message": f"No git repository found for '{file_path}'. Please initialize a git repository in this directory or its ancestors before using edit_file.",
"content_changed": False,
"total_changes": len(changes),
}
# Write to disk and commit to git for undo capability
commit_hash = "unknown"
def _configure_git_user(git_repo_dir: Path) -> dict | None:
"""Configure git user identity if not already set. Returns error dict or None."""
try:
result_check = subprocess.run(
["git", "-C", str(git_repo_dir), "config", "user.name"],
capture_output=True, text=True, timeout=5,
stdin=subprocess.DEVNULL,
)
if result_check.returncode != 0 or not result_check.stdout.strip():
# Try to get user info from system
import getpass
import socket
username = getpass.getuser()
hostname = socket.gethostname()
email = f"{username}@{hostname}"
config_result = subprocess.run(
["git", "-C", str(git_repo_dir), "config", "user.name", username],
capture_output=True, text=True, timeout=5,
stdin=subprocess.DEVNULL,
)
if config_result.returncode != 0:
return {
"status": "error",
"message": f"Failed to set git user.name: {config_result.stderr.strip()}"
}
config_result = subprocess.run(
["git", "-C", str(git_repo_dir), "config", "user.email", email],
capture_output=True, text=True, timeout=5,
stdin=subprocess.DEVNULL,
)
if config_result.returncode != 0:
return {
"status": "error",
"message": f"Failed to set git user.email: {config_result.stderr.strip()}"
}
except Exception as e:
return {
"status": "error",
"message": f"Git user configuration failed: {e}",
}
return None
if content_changed:
file_path.write_text(new_content, encoding=encoding)
timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
num_changes = len([c for c in applied_changes if c.get("status") == "proposed"])
commit_message = f"{timestamp} - edit_file: {num_changes} change(s) applied"
try:
result_add = subprocess.run(
["git", "-C", str(git_repo_dir), "add", str(file_path)],
capture_output=True, text=True, timeout=30,
stdin=subprocess.DEVNULL,
)
if result_add.returncode != 0:
return {
"path": str(file_path),
"status": "error",
"message": f"git add failed: {result_add.stderr.strip()}",
"content_changed": content_changed,
"total_changes": len(changes),
"applied_changes": applied_changes,
"diff": diff_output,
}
user_config_error = _configure_git_user(git_repo_dir)
if user_config_error:
return {
"path": str(file_path),
"status": "error",
"message": f"Git user identity not configured and could not be set: {user_config_error['message']}",
"content_changed": content_changed,
"total_changes": len(changes),
"applied_changes": applied_changes,
"diff": diff_output,
}
result_commit = subprocess.run(
["git", "-C", str(git_repo_dir), "commit", "-m", commit_message],
capture_output=True, text=True, timeout=30,
stdin=subprocess.DEVNULL,
)
if result_commit.returncode != 0:
return {
"path": str(file_path),
"status": "error",
"message": f"git commit failed: {result_commit.stderr.strip()}",
"content_changed": content_changed,
"total_changes": len(changes),
"applied_changes": applied_changes,
"diff": diff_output,
}
result_hash = subprocess.run(
["git", "-C", str(git_repo_dir), "rev-parse", "--short", "HEAD"],
capture_output=True, text=True, timeout=10,
stdin=subprocess.DEVNULL,
)
commit_hash = result_hash.stdout.strip() if result_hash.returncode == 0 else "unknown"
except subprocess.TimeoutExpired:
return {
"path": str(file_path),
"status": "error",
"message": "Git operation timed out",
"content_changed": content_changed,
"total_changes": len(changes),
"applied_changes": applied_changes,
"diff": diff_output,
}
return {
"path": str(file_path),
"status": "success" if content_changed else "no_changes",
"content_changed": content_changed,
"total_changes": len(changes),
"applied_changes": applied_changes,
"diff": diff_output,
"commit_hash": commit_hash if content_changed else None,
}
@mcp.tool()
def undo_edit(path: str, steps: int = 1) -> dict:
"""Revert a file to its state before N confirmed edits using git history.
⚠️ IMPORTANT - Common Pitfalls:
- REQUIRED: `path` must be an absolute path within your home directory.
- The file must have git history (commits from previous `edit_file` operations).
- If no git commits exist, use `edit_file` first to create commits, then undo.
- `steps` defaults to 1 — increase for reverting multiple edits.
Args:
path: REQUIRED. The absolute file path to revert (within home directory).
steps: Number of git commits to go back. Default: 1
Returns:
Dictionary with path, status ("undone"/"error"), steps_reverted, and commit_hash.
"""
file_path = _validate_path(Path(path))
path_str = str(file_path)
if not file_path.exists():
raise FileNotFoundError(f"File not found: {file_path}")
file_path_parent = file_path.parent.resolve()
def _configure_git_user(git_repo_dir: Path) -> dict | None:
"""Configure git user identity if not already set. Returns error dict or None."""
try:
result_check = subprocess.run(
["git", "-C", str(git_repo_dir), "config", "user.name"],
capture_output=True, text=True, timeout=5,
stdin=subprocess.DEVNULL,
)
if result_check.returncode != 0 or not result_check.stdout.strip():
import getpass
import socket
username = getpass.getuser()
hostname = socket.gethostname()
email = f"{username}@{hostname}"
config_result = subprocess.run(
["git", "-C", str(git_repo_dir), "config", "user.name", username],
capture_output=True, text=True, timeout=5,
stdin=subprocess.DEVNULL,
)
if config_result.returncode != 0:
return {
"status": "error",
"message": f"Failed to set git user.name: {config_result.stderr.strip()}"
}
config_result = subprocess.run(
["git", "-C", str(git_repo_dir), "config", "user.email", email],
capture_output=True, text=True, timeout=5,
stdin=subprocess.DEVNULL,
)
if config_result.returncode != 0:
return {
"status": "error",
"message": f"Failed to set git user.email: {config_result.stderr.strip()}"
}
except Exception as e:
return {
"status": "error",
"message": f"Git user configuration failed: {e}",
}
return None
try:
# Get the diff before undoing so we can report what changed
result_diff_before = subprocess.run(
["git", "-C", str(file_path_parent), "diff", f"HEAD~{steps}..HEAD", "--", str(file_path)],
capture_output=True, text=True, timeout=30,
stdin=subprocess.DEVNULL,
)
diff_output_before = result_diff_before.stdout if result_diff_before.returncode == 0 else ""
result_checkout = subprocess.run(
["git", "-C", str(file_path_parent), "checkout", f"HEAD~{steps}", "--", str(file_path)],
capture_output=True, text=True, timeout=30,
stdin=subprocess.DEVNULL,
)
if result_checkout.returncode != 0:
return {
"path": path_str,
"status": "error",
"message": f"git checkout failed: {result_checkout.stderr.strip()}",
}
timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
undo_message = f"{timestamp} - undo_edit: reverted {steps} step(s)"
subprocess.run(
["git", "-C", str(file_path_parent), "add", str(file_path)],
capture_output=True, text=True, timeout=30,
stdin=subprocess.DEVNULL,
)
user_config_error = _configure_git_user(file_path_parent)
if user_config_error:
return {
"path": path_str,
"status": "error",
"message": f"Git user identity not configured and could not be set: {user_config_error['message']}",
}
subprocess.run(
["git", "-C", str(file_path_parent), "commit", "-m", undo_message],
capture_output=True, text=True, timeout=30,
stdin=subprocess.DEVNULL,
)
result_hash = subprocess.run(
["git", "-C", str(file_path.parent), "rev-parse", "--short", "HEAD"],
capture_output=True, text=True, timeout=10,
stdin=subprocess.DEVNULL,
)
commit_hash = result_hash.stdout.strip() if result_hash.returncode == 0 else "unknown"
except subprocess.TimeoutExpired:
return {
"path": path_str,
"status": "error",
"message": "Git operation timed out",
}
except FileNotFoundError:
return {
"path": path_str,
"status": "error",
"message": "git is not installed or not in PATH",
}
return {
"path": path_str,
"status": "undone",
"steps_reverted": steps,
"commit_hash": commit_hash,
"commit_message": undo_message,
"diff": diff_output_before,
}
@mcp.tool()
def preview_undo(path: str, steps: int = 1) -> dict:
"""Preview what changes would be made if undo_edit was called.
Shows the git diff between the current state and HEAD~steps for this file,
without actually modifying anything.
Args:
path: The file path to preview.
steps: Number of commits to go back. Default: 1
Returns:
Dictionary with status, steps, and diff showing what would change.
"""
file_path = _validate_path(Path(path))
path_str = str(file_path)
if not file_path.exists():
raise FileNotFoundError(f"File not found: {file_path}")
try:
result_diff = subprocess.run(
["git", "diff", f"HEAD~{steps}", "HEAD", "--", str(file_path)],
capture_output=True, text=True, timeout=30,
stdin=subprocess.DEVNULL,
)
if result_diff.returncode != 0:
result_diff = subprocess.run(
["git", "diff", f"HEAD~{steps}", "--", str(file_path)],
capture_output=True, text=True, timeout=30,
stdin=subprocess.DEVNULL,
)
diff_output = result_diff.stdout.strip() if result_diff.stdout.strip() else ""
except subprocess.TimeoutExpired:
return {
"path": path_str,
"status": "error",
"message": "Git operation timed out",
}
except FileNotFoundError:
return {
"path": path_str,
"status": "error",
"message": "git is not installed or not in PATH",
}
return {
"path": path_str,
"steps": steps,
"diff": diff_output,
"status": "preview_ready" if diff_output else "no_changes_found",
}
@mcp.tool()
def create_file(
path: str,
content: str,
overwrite: bool = False,
encoding: str = "utf-8",
git_dir: str = None,
) -> dict:
"""Create a new file with the given content and commit to git for undo capability.
⚠️ IMPORTANT - Common Pitfalls:
- REQUIRED: Both `path` and `content` must be provided. `path` must be an absolute path within your home directory.
- The parent directory MUST exist. Use `list_folder` to verify, or `git_init` on the parent directory first.
- A git repository MUST exist in the file's directory or its ancestors. Run `git_init` first if needed.
- If the file already exists, set `overwrite: true` to replace it — otherwise you get an error.
Note that this tool can't be used in folders where no git is initialized.
It checks if git repository exists before creating the file. If the file already exists
and overwrite is False, returns an error. The file is written to disk and committed to git
so it can be undone later.
Args:
path: REQUIRED. The absolute file path (within home directory). Parent directory must exist.
content: REQUIRED. The content for the new file.
overwrite: If True, allow overwriting existing files. Default: False
encoding: The file encoding to use. Default: utf-8
git_dir: Optional path to the git repository root. If not specified, the file's parent directory is used.
Returns:
Dictionary with path, status ("success"/"overwritten"/"error"/"exists"), content_changed, and commit_hash.
"""
file_path = _validate_path(Path(path))
if not file_path.parent.exists():
return {
"path": str(file_path),
"status": "error",
"message": f"Parent directory does not exist: {file_path.parent}",
}
# Determine git directory for all operations
if git_dir is not None:
git_repo_dir = Path(git_dir)
else:
git_repo_dir = file_path.parent.resolve()
def _is_git_repo(directory: Path) -> bool:
"""Check if a directory (or any of its ancestors) is a git repository."""
current = directory.resolve()
while True:
git_dir_path = current / ".git"
if git_dir_path.is_dir():
return True
parent = current.parent
if parent == current:
break
current = parent
return False
if not _is_git_repo(git_repo_dir):
return {
"path": str(file_path),
"status": "error",
"message": f"No git repository found for '{file_path}'. Please initialize a git repository in this directory or its ancestors before using create_file.",
"content_changed": False,
"total_changes": 1,
}
exists = file_path.exists()
if exists and not overwrite:
return {
"path": str(file_path),
"status": "exists",
"content_changed": False,
"total_changes": 0,
"message": f"File already exists: {file_path}. Set overwrite=True.",
}
timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
commit_message = f"{timestamp} - create_file: {'overwrite' if exists else 'create'}"
def _configure_git_user(git_repo_dir: Path) -> dict | None:
"""Configure git user identity if not already set. Returns error dict or None."""
try:
result_check = subprocess.run(
["git", "-C", str(git_repo_dir), "config", "user.name"],
capture_output=True, text=True, timeout=5,
stdin=subprocess.DEVNULL,
)
if result_check.returncode != 0 or not result_check.stdout.strip():
import getpass
import socket