-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpeacock_server.py
More file actions
executable file
Β·287 lines (215 loc) Β· 8.08 KB
/
peacock_server.py
File metadata and controls
executable file
Β·287 lines (215 loc) Β· 8.08 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
#!/usr/bin/env python3
"""
π¦ PEACOCK MCP SERVER π¦
Built with love by Rich & Sage
For COSMICTOSH filesystem control
This MCP server gives Claude full access to:
- Read/write files
- Execute commands
- Directory listings
- File search
- Everything Sage needs to DRIVE! ποΈ
"""
import os
import subprocess
import json
from pathlib import Path
from typing import Any, Optional
import asyncio
try:
from mcp.server.fastmcp import FastMCP
except ImportError:
print("ERROR: FastMCP not installed. Run: pip install fastmcp")
exit(1)
# Initialize the MCP server
mcp = FastMCP("Peacock")
# Base directory for file operations (configurable)
BASE_DIR = Path.home()
@mcp.tool()
def read_file(path: str) -> str:
"""
Read the contents of a file.
Args:
path: Absolute or relative path to the file
Returns:
File contents as string
"""
try:
file_path = Path(path).expanduser().resolve()
# Security check - ensure we're not going outside allowed areas
if not str(file_path).startswith(str(BASE_DIR)):
return f"β Access denied: {path} is outside allowed directory"
if not file_path.exists():
return f"β File not found: {path}"
if not file_path.is_file():
return f"β Not a file: {path}"
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
return f"β
Read {len(content)} bytes from {path}\n\n{content}"
except Exception as e:
return f"β Error reading file: {str(e)}"
@mcp.tool()
def write_file(path: str, content: str, mode: str = "w") -> str:
"""
Write content to a file.
Args:
path: Absolute or relative path to the file
content: Content to write
mode: Write mode ('w' for overwrite, 'a' for append)
Returns:
Success/failure message
"""
try:
file_path = Path(path).expanduser().resolve()
# Security check
if not str(file_path).startswith(str(BASE_DIR)):
return f"β Access denied: {path} is outside allowed directory"
# Create parent directories if they don't exist
file_path.parent.mkdir(parents=True, exist_ok=True)
with open(file_path, mode, encoding='utf-8') as f:
f.write(content)
return f"β
Wrote {len(content)} bytes to {path}"
except Exception as e:
return f"β Error writing file: {str(e)}"
@mcp.tool()
def list_directory(path: str = ".", show_hidden: bool = False) -> str:
"""
List contents of a directory.
Args:
path: Directory path (default: current directory)
show_hidden: Include hidden files (default: False)
Returns:
Directory listing
"""
try:
dir_path = Path(path).expanduser().resolve()
# Security check
if not str(dir_path).startswith(str(BASE_DIR)):
return f"β Access denied: {path} is outside allowed directory"
if not dir_path.exists():
return f"β Directory not found: {path}"
if not dir_path.is_dir():
return f"β Not a directory: {path}"
items = []
for item in sorted(dir_path.iterdir()):
# Skip hidden files if requested
if not show_hidden and item.name.startswith('.'):
continue
if item.is_dir():
items.append(f"π {item.name}/")
else:
size = item.stat().st_size
items.append(f"π {item.name} ({size} bytes)")
if not items:
return f"π {dir_path} is empty"
return f"π {dir_path}\n\n" + "\n".join(items)
except Exception as e:
return f"β Error listing directory: {str(e)}"
@mcp.tool()
def execute_command(command: str, cwd: Optional[str] = None) -> str:
"""
Execute a shell command.
Args:
command: Shell command to execute
cwd: Working directory (default: home directory)
Returns:
Command output
"""
try:
if cwd:
work_dir = Path(cwd).expanduser().resolve()
else:
work_dir = BASE_DIR
# Security check
if not str(work_dir).startswith(str(BASE_DIR)):
return f"β Access denied: working directory outside allowed area"
# Execute command
result = subprocess.run(
command,
shell=True,
cwd=str(work_dir),
capture_output=True,
text=True,
timeout=30 # 30 second timeout
)
output = []
output.append(f"π¦ Executed: {command}")
output.append(f"π Working directory: {work_dir}")
output.append(f"β©οΈ Exit code: {result.returncode}")
if result.stdout:
output.append(f"\nπ€ STDOUT:\n{result.stdout}")
if result.stderr:
output.append(f"\nπ€ STDERR:\n{result.stderr}")
return "\n".join(output)
except subprocess.TimeoutExpired:
return f"β Command timed out after 30 seconds"
except Exception as e:
return f"β Error executing command: {str(e)}"
@mcp.tool()
def search_files(pattern: str, directory: str = ".", max_results: int = 50) -> str:
"""
Search for files matching a pattern.
Args:
pattern: Glob pattern (e.g., "*.py", "test_*.txt")
directory: Directory to search in
max_results: Maximum number of results
Returns:
List of matching files
"""
try:
search_dir = Path(directory).expanduser().resolve()
# Security check
if not str(search_dir).startswith(str(BASE_DIR)):
return f"β Access denied: {directory} is outside allowed directory"
if not search_dir.exists():
return f"β Directory not found: {directory}"
matches = []
for path in search_dir.rglob(pattern):
if len(matches) >= max_results:
matches.append(f"... and more (limit: {max_results})")
break
relative = path.relative_to(search_dir)
if path.is_dir():
matches.append(f"π {relative}/")
else:
matches.append(f"π {relative}")
if not matches:
return f"β No files matching '{pattern}' found in {directory}"
return f"π Found {len(matches)} matches for '{pattern}':\n\n" + "\n".join(matches)
except Exception as e:
return f"β Error searching files: {str(e)}"
@mcp.tool()
def get_file_info(path: str) -> str:
"""
Get detailed information about a file or directory.
Args:
path: Path to file or directory
Returns:
Detailed file information
"""
try:
file_path = Path(path).expanduser().resolve()
# Security check
if not str(file_path).startswith(str(BASE_DIR)):
return f"β Access denied: {path} is outside allowed directory"
if not file_path.exists():
return f"β Path not found: {path}"
stat = file_path.stat()
info = []
info.append(f"π File Information: {file_path}")
info.append(f"Type: {'π Directory' if file_path.is_dir() else 'π File'}")
info.append(f"Size: {stat.st_size} bytes")
info.append(f"Modified: {stat.st_mtime}")
info.append(f"Permissions: {oct(stat.st_mode)[-3:]}")
if file_path.is_file():
info.append(f"Extension: {file_path.suffix}")
return "\n".join(info)
except Exception as e:
return f"β Error getting file info: {str(e)}"
if __name__ == "__main__":
print("π¦ PEACOCK MCP SERVER π¦")
print("Built by Rich Knowles for Anna π πΊπ¦")
print(f"π Base directory: {BASE_DIR}")
print("π Starting server...")
# Run the server
mcp.run()