test_installation.py•6.63 kB
#!/usr/bin/env python3
"""Test script to validate the File System MCP Server installation."""
import asyncio
import json
import tempfile
from pathlib import Path
from src.file_system_mcp_server.config import Config, ConfigManager
from src.file_system_mcp_server.safety import SafetyManager
from src.file_system_mcp_server.file_operations import FileOperationsManager
from src.file_system_mcp_server.server import FileSystemMCPServer
async def test_basic_functionality():
"""Test basic functionality of the server."""
print("🧪 Testing File System MCP Server...")
# Create temporary workspace
with tempfile.TemporaryDirectory() as temp_dir:
workspace = Path(temp_dir)
print(f"📁 Using workspace: {workspace}")
# Create test configuration
config = Config(
backup_directory=str(workspace / "backups"),
max_file_size=1024 * 1024, # 1MB
max_recursion_depth=5,
protected_paths=["/etc", "/usr"],
enable_backups=True,
log_level="INFO"
)
# Initialize components
safety_manager = SafetyManager(config)
file_ops = FileOperationsManager(config, safety_manager)
print("✅ Components initialized successfully")
# Test file operations
test_file = workspace / "test.txt"
test_content = "Hello, MCP Server!"
# Test write
print("📝 Testing file write...")
write_result = await file_ops.write_file(str(test_file), test_content)
assert write_result.success, f"Write failed: {write_result.error}"
print(f"✅ File written: {write_result.path}")
# Test read
print("📖 Testing file read...")
read_result = await file_ops.read_file(str(test_file))
assert read_result.success, f"Read failed: {read_result.error}"
assert read_result.content == test_content, "Content mismatch"
print(f"✅ File read successfully: {len(read_result.content)} bytes")
# Test update
print("🔄 Testing file update...")
new_content = "Updated content!"
update_result = await file_ops.update_file(str(test_file), new_content)
assert update_result.success, f"Update failed: {update_result.error}"
print(f"✅ File updated with backup: {update_result.backup_created}")
# Test directory listing
print("📋 Testing directory listing...")
list_result = await file_ops.list_directory(str(workspace))
assert list_result.success, f"List failed: {list_result.error}"
print(f"✅ Directory listed: {list_result.total_entries} entries")
# Test file info
print("ℹ️ Testing file info...")
info_result = await file_ops.get_file_info(str(test_file))
assert info_result.success, f"Info failed: {info_result.error}"
assert info_result.exists, "File should exist"
print(f"✅ File info retrieved: {info_result.metadata.size} bytes")
# Test MCP server
print("🖥️ Testing MCP server...")
server = FileSystemMCPServer(config)
# Test tool listing
tools = await server.server._handlers["list_tools"]()
expected_tools = {"read_file", "write_file", "update_file", "list_directory", "delete_file", "get_file_info"}
actual_tools = {tool.name for tool in tools}
assert actual_tools == expected_tools, f"Tool mismatch: {actual_tools} != {expected_tools}"
print(f"✅ MCP server tools registered: {len(tools)} tools")
# Test tool call
result = await server.server._handlers["call_tool"]("read_file", {"path": str(test_file)})
response_data = json.loads(result[0].text)
assert response_data["success"], f"Tool call failed: {response_data.get('error')}"
print("✅ MCP tool call successful")
# Test configuration management
print("⚙️ Testing configuration...")
config_file = workspace / "test_config.json"
ConfigManager.save_config(config, config_file)
loaded_config = ConfigManager.load_config(str(config_file))
assert loaded_config.backup_directory == config.backup_directory
print("✅ Configuration save/load successful")
print("\n🎉 All tests passed! The File System MCP Server is working correctly.")
print("\n📋 Summary:")
print(f" • File operations: ✅ Write, Read, Update, List, Info")
print(f" • Safety features: ✅ Backups, Path validation")
print(f" • MCP integration: ✅ Tool registration, Tool calls")
print(f" • Configuration: ✅ Save, Load, Validate")
print(f" • Workspace: {workspace}")
return True
def test_cli_functionality():
"""Test CLI functionality."""
print("\n🖥️ Testing CLI functionality...")
# Test configuration creation
with tempfile.TemporaryDirectory() as temp_dir:
config_file = Path(temp_dir) / "test_config.json"
# Create example config
from src.file_system_mcp_server.main import create_example_config
create_example_config(str(config_file))
assert config_file.exists(), "Config file should be created"
# Validate config
from src.file_system_mcp_server.main import validate_config
try:
validate_config(str(config_file))
print("✅ CLI configuration validation successful")
except SystemExit as e:
if e.code == 0:
print("✅ CLI configuration validation successful")
else:
raise
return True
if __name__ == "__main__":
print("🚀 File System MCP Server - Installation Test")
print("=" * 50)
try:
# Test async functionality
asyncio.run(test_basic_functionality())
# Test CLI functionality
test_cli_functionality()
print("\n" + "=" * 50)
print("🎊 Installation test completed successfully!")
print("\nYou can now use the server with:")
print(" python -m file_system_mcp_server.main --help")
print(" python -m file_system_mcp_server.main --create-example-config config.json")
print(" python -m file_system_mcp_server.main --config config.json")
except Exception as e:
print(f"\n❌ Test failed: {e}")
import traceback
traceback.print_exc()
exit(1)