file_ops.py•3.67 kB
"""
File operations tool for MCP server.
Provides read_file and write_file capabilities.
"""
import os
from typing import Dict, Any
def read_file(args: Dict[str, Any]) -> Dict[str, Any]:
"""
Read contents of a file.
Args:
args: Dictionary with 'path' key
Returns:
Dictionary with 'content' key containing file contents
Raises:
ValueError: If path is missing or invalid
FileNotFoundError: If file doesn't exist
PermissionError: If file can't be read
"""
if "path" not in args:
raise ValueError("Missing required parameter: path")
path = args["path"]
# Expand user path and resolve to absolute
path = os.path.expanduser(path)
path = os.path.abspath(path)
# Security check - ensure path exists and is a file
if not os.path.exists(path):
raise FileNotFoundError(f"File not found: {path}")
if not os.path.isfile(path):
raise ValueError(f"Path is not a file: {path}")
# Read file contents
try:
with open(path, 'r', encoding='utf-8') as f:
content = f.read()
except UnicodeDecodeError:
# Try binary mode if UTF-8 fails
with open(path, 'rb') as f:
content = f.read().decode('latin-1')
return {
"content": content,
"path": path
}
def write_file(args: Dict[str, Any]) -> Dict[str, Any]:
"""
Write contents to a file.
Args:
args: Dictionary with 'path' and 'contents' keys
Returns:
Dictionary with success status and bytes written
Raises:
ValueError: If required parameters are missing
PermissionError: If file can't be written
"""
if "path" not in args:
raise ValueError("Missing required parameter: path")
if "contents" not in args:
raise ValueError("Missing required parameter: contents")
path = args["path"]
contents = args["contents"]
# Expand user path and resolve to absolute
path = os.path.expanduser(path)
path = os.path.abspath(path)
# Ensure parent directory exists
parent_dir = os.path.dirname(path)
if parent_dir and not os.path.exists(parent_dir):
os.makedirs(parent_dir, exist_ok=True)
# Write file contents
with open(path, 'w', encoding='utf-8') as f:
f.write(contents)
bytes_written = len(contents.encode('utf-8'))
return {
"success": True,
"path": path,
"bytes_written": bytes_written
}
# Tool definitions for registration
TOOLS = {
"read_file": {
"handler": read_file,
"description": "Read the contents of a file from the filesystem",
"inputSchema": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Path to the file to read (absolute or relative)"
}
},
"required": ["path"]
}
},
"write_file": {
"handler": write_file,
"description": "Write contents to a file on the filesystem",
"inputSchema": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Path to the file to write (absolute or relative)"
},
"contents": {
"type": "string",
"description": "Contents to write to the file"
}
},
"required": ["path", "contents"]
}
}
}