-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
357 lines (271 loc) · 9.69 KB
/
server.py
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
import os
import ast
import re
import json
import shutil
import subprocess
from typing import List, Tuple, Dict, Union
from pathlib import Path
from mcp.server.fastmcp import FastMCP
RUFF_PATH = Path(__file__).parent / ".venv" / "bin" / "ruff"
mcp = FastMCP("FileSystem")
@mcp.tool()
def ls(path: str) -> list[str]:
"""List files in a directory.
:param path: Path to the directory. Can be relative to current working
directory (see cd tool).
"""
return os.listdir(path)
@mcp.tool()
def cd(path: str) -> None:
"""Change the current working directory.
:param path: New working directory. Can be relative to current working
directory. Supports home directory expansion (~/path).
"""
expanded_path = os.path.expanduser(path)
os.chdir(expanded_path)
@mcp.tool()
def read_file(path: str) -> str:
"""Read a file from the filesystem.
:param path: Path to the file. Can be relative (see cd tool).
"""
with open(path, "rt", encoding="utf-8") as f:
return f.read()
@mcp.tool()
def write_file(path: str, content: str) -> None:
"""Write content to a file.
:param path: Path to the file. Can be relative (see cd tool).
:param content: Content to write to the file.
"""
with open(path, "wt", encoding="utf-8") as f:
f.write(content)
@mcp.tool()
def patch_file(path: str, patches: List[Tuple[str, str]]) -> None:
"""Apply sequence of search/replace operations to a file.
:param path: Path to the file to patch. Can be relative (see cd tool).
:param patches: List of (search_text, replace_text) tuples.
Ideally, try to replace entire lines to avoid partial matches. Including
a few lines of context in the search text helps to ensure the right match.
"""
with open(path, "rt", encoding="utf-8") as f:
content = f.read()
for search, replace in patches:
old_content = content
content = content.replace(search, replace)
if old_content == content:
raise ValueError(f"Search text not found in file:\n\n{search}")
with open(path, "wt", encoding="utf-8") as f:
f.write(content)
@mcp.tool()
def summary(path: str) -> List[str]:
"""Generate a summary of a Python or Markdown file.
:param path: Path to file to summarize. Supports .py and .md files.
:returns: List of important lines (headers for md, functions/classes for py)
"""
with open(path, "rt", encoding="utf-8") as f:
content = f.read()
if path.endswith(".md"):
return [
line.strip() for line in content.split("\n") if line.strip().startswith("#")
]
elif path.endswith(".py"):
tree = ast.parse(content)
return [
f"{type(node).__name__}: {node.name}"
for node in ast.walk(tree)
if isinstance(node, (ast.FunctionDef, ast.ClassDef))
]
raise ValueError(f"Unsupported file type: {path}")
@mcp.tool()
def mkdir(path: str) -> None:
"""Create a directory.
:param path: Directory path to create. Can be relative.
"""
os.makedirs(path, exist_ok=True)
@mcp.tool()
def rm(path: str) -> None:
"""Remove a file or empty directory.
:param path: Path to remove. Can be relative.
"""
if os.path.isdir(path):
os.rmdir(path) # Will fail if not empty
else:
os.unlink(path)
@mcp.tool()
def rmdir(path: str) -> None:
"""Remove directory and all its contents.
:param path: Directory to remove. Can be relative.
"""
shutil.rmtree(path)
@mcp.tool()
def cp(src: str, dst: str) -> None:
"""Copy file or directory.
:param src: Source path. Can be relative.
:param dst: Destination path. Can be relative.
"""
if os.path.isdir(src):
shutil.copytree(src, dst)
else:
shutil.copy2(src, dst)
@mcp.tool()
def mv(src: str, dst: str) -> None:
"""Move file or directory.
:param src: Source path. Can be relative.
:param dst: Destination path. Can be relative.
"""
shutil.move(src, dst)
def _get_notes_file() -> Path:
"""Find the root directory with .mcp-notes.json"""
current = Path.cwd()
while current != current.parent:
if (current / ".mcp-notes.json").exists():
return current / ".mcp-notes.json"
current = current.parent
return Path.cwd() / ".mcp-notes.json"
def _load_notes() -> Dict[str, Dict[str, str]]:
"""Load notes from file, creating if doesn't exist"""
notes_file = _get_notes_file()
if notes_file.exists():
with open(notes_file, "r") as f:
return json.load(f)
return {}
def _save_notes(notes: Dict[str, Dict[str, str]]) -> None:
"""Save notes to file"""
notes_file = _get_notes_file()
with open(notes_file, "w") as f:
json.dump(notes, f, indent=2)
def _get_relative_path(path: str) -> str:
"""Convert path to be relative to notes file location"""
abs_path = Path(path).absolute()
notes_root = _get_notes_file().parent.absolute()
try:
return str(abs_path.relative_to(notes_root))
except ValueError:
raise ValueError(f"Path {path} is not under notes root {notes_root}")
@mcp.tool()
def add_note(path: str, key: str, note: str) -> None:
"""Add or update a note about a file/directory.
:param path: Path to file/directory to annotate
:param key: Note key/category
:param note: Note content
"""
rel_path = _get_relative_path(path)
notes = _load_notes()
if rel_path not in notes:
notes[rel_path] = {}
notes[rel_path][key] = note
_save_notes(notes)
@mcp.tool()
def get_all_notes() -> Dict[str, Dict[str, str]]:
"""Get all notes for all paths.
:returns: Dict mapping paths to their notes (which are key-value dicts)
"""
return _load_notes()
@mcp.tool()
def remove_note(path: str, key: str) -> None:
"""Remove a note about a file/directory.
:param path: Path to file/directory
:param key: Note key to remove
"""
rel_path = _get_relative_path(path)
notes = _load_notes()
if rel_path in notes and key in notes[rel_path]:
del notes[rel_path][key]
if not notes[rel_path]: # Remove empty entries
del notes[rel_path]
_save_notes(notes)
@mcp.tool()
def grep(pattern: str, path: str) -> List[str]:
"""Search for pattern in file(s).
:param pattern: Regular expression to search for
:param path: Path to file or directory. If directory, searches recursively.
:returns: List of matches in format "filename:line_number:matched_line"
"""
results = []
pattern = re.compile(pattern)
def search_file(filepath):
try:
with open(filepath, "rt", encoding="utf-8") as f:
for i, line in enumerate(f, 1):
if pattern.search(line):
results.append(f"{filepath}:{i}:{line.rstrip()}")
except UnicodeDecodeError:
pass # Skip binary files
if os.path.isfile(path):
search_file(path)
else:
for root, _, files in os.walk(path):
for file in files:
search_file(os.path.join(root, file))
return results
@mcp.tool()
def ls_many(paths: list[str]) -> Dict[str, list[str]]:
"""List files in multiple directories.
:param paths: List of directory paths
:returns: Combined list of files from all directories
"""
results = {}
for path in paths:
results[path] = ls(path)
return results
@mcp.tool()
def read_files(paths: list[str]) -> Dict[str, str]:
"""Read multiple files.
:param paths: List of file paths
:returns: List of file contents in same order
"""
return {path: read_file(path) for path in paths}
@mcp.tool()
def summarize(paths: list[str]) -> Dict[str, list[str]]:
"""Generate summaries for multiple files.
:param paths: List of file paths
:returns: List of summaries in same order as input paths
"""
return {path: summary(path) for path in paths}
@mcp.tool()
def work_on(path: str) -> Dict[str, Union[List[str], Dict[str, Dict[str, str]]]]:
"""Change to directory, list its contents, and get all notes.
Useful for getting familiar with a project at the start of a chat.
:param path: Directory to work on. Supports home expansion (~/path).
:returns: Dict with 'files' and 'notes' keys
"""
cd(path)
return {"files": ls("."), "notes": get_all_notes()}
@mcp.tool()
def ruff_check(paths: list[str]) -> Dict[str, Union[str, int]]:
"""Run ruff linter on specified files. Useful to check that nothing was broken.
:param paths: List of file paths to check
:returns: Dict with 'output' and 'exit_code' keys
"""
try:
result = subprocess.run(
[str(RUFF_PATH), "check"] + paths,
capture_output=True,
text=True,
check=False,
)
return {"output": result.stdout + result.stderr, "exit_code": result.returncode}
except FileNotFoundError:
return {
"output": "Error: ruff not found. Please install ruff package.",
"exit_code": -1,
}
@mcp.tool()
def ruff_format(paths: list[str]) -> Dict[str, Union[str, int]]:
"""Format files using ruff. Useful for fixing formatting issues after edits.
:param paths: List of file paths to format
:returns: Dict with 'output' and 'exit_code' keys
"""
try:
result = subprocess.run(
[str(RUFF_PATH), "format"] + paths,
capture_output=True,
text=True,
check=False,
)
return {"output": result.stdout + result.stderr, "exit_code": result.returncode}
except FileNotFoundError:
return {
"output": "Error: ruff not found. Please install ruff package.",
"exit_code": -1,
}