@mcp.tool()
def read_file(file_path: str, max_size_kb: int = 1024) -> str:
"""
Read the content of any file, with size limits for safety.
Args:
file_path: Path to the file
max_size_kb: Maximum file size to read in KB
"""
path = Path(file_path)
if path.is_absolute():
if not is_path_allowed(path):
return f"Access denied: Can only read files in working directory: {WORKING_DIR}"
else:
path = WORKING_DIR / path
try:
if not path.exists():
return f"Error: File '{file_path}' not found"
file_size_kb = path.stat().st_size / 1024
if file_size_kb > max_size_kb:
return f"Error: File size ({file_size_kb:.2f} KB) exceeds maximum ({max_size_kb} KB)"
try:
with open(path, 'r', encoding='utf-8') as f:
content = f.read()
source_extensions = ['.py', '.js', '.html', '.css', '.json', '.xml', '.md', '.txt', '.sh', '.bat', '.ps1']
if path.suffix.lower() in source_extensions:
file_type = path.suffix[1:] if path.suffix else 'plain'
return f"File: {file_path}\n\n```{file_type}\n{content}\n```"
return f"File: {file_path}\n\n{content}"
except UnicodeDecodeError:
with open(path, 'rb') as f:
content = f.read()
hex_content = content.hex()
return f"Binary file: {file_path}\nSize: {len(content)} bytes\nHex (first 1024 chars):\n{hex_content[:1024]}"
except Exception as e:
return f"Error reading file: {str(e)}"