# Step 06: Test Individual Server Modules

## Prerequisites
- Step 05 completed (health check system implemented)
- All servers have health check functions
- Main server can be created

## Objectives
1. Test each server module individually
2. Validate all server tools work correctly
3. Test server health checks
4. Document any issues found

## Implementation Details

### Step 1: Create Server Testing Framework
Create `_mcp/test_servers.py`:

```python
#!/usr/bin/env python3
"""
Individual Server Testing Framework
Tests each MCP server module independently
"""

import sys
import json
import traceback
from pathlib import Path
from typing import Dict, List

# Add project root to path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

class ServerTester:
    def __init__(self):
        self.results = {}
        self.servers = {}
    
    def test_server_creation(self, server_name: str, create_function) -> Dict:
        """Test if server can be created successfully."""
        try:
            server = create_function()
            return {
                "status": "success",
                "message": f"Server {server_name} created successfully",
                "details": {
                    "name": server.name,
                    "tools_count": len(server.tools),
                    "resources_count": len(server.resources) if hasattr(server, 'resources') else 0
                }
            }
        except Exception as e:
            return {
                "status": "error",
                "message": f"Failed to create server {server_name}: {str(e)}",
                "details": {"error": str(e), "traceback": traceback.format_exc()}
            }
    
    def test_server_tools(self, server_name: str, server) -> Dict:
        """Test server tools functionality."""
        tool_results = {}
        
        for tool in server.tools:
            try:
                # Test tool with default parameters
                if hasattr(tool, 'function'):
                    # Simple test - just check if function exists and is callable
                    tool_results[tool.name] = {
                        "status": "available",
                        "callable": callable(tool.function),
                        "tags": getattr(tool, 'tags', [])
                    }
                else:
                    tool_results[tool.name] = {
                        "status": "error",
                        "message": "Tool function not found"
                    }
            except Exception as e:
                tool_results[tool.name] = {
                    "status": "error",
                    "message": str(e)
                }
        
        return {
            "status": "success" if tool_results else "warning",
            "message": f"Tested {len(tool_results)} tools",
            "details": tool_results
        }
    
    def test_server_health(self, server_name: str, server) -> Dict:
        """Test server health check functionality."""
        try:
            # Look for health check tool
            health_tool = None
            for tool in server.tools:
                if tool.name == "health_check":
                    health_tool = tool
                    break
            
            if not health_tool:
                return {
                    "status": "warning",
                    "message": "No health check tool found",
                    "details": {"available_tools": [t.name for t in server.tools]}
                }
            
            # Execute health check
            health_result = health_tool.function()
            
            return {
                "status": "success",
                "message": "Health check executed successfully",
                "details": health_result
            }
            
        except Exception as e:
            return {
                "status": "error",
                "message": f"Health check failed: {str(e)}",
                "details": {"error": str(e)}
            }
    
    def test_all_servers(self) -> Dict:
        """Test all servers individually."""
        # Import server creation functions
        from _mcp.servers.coverage import create_coverage_server
        from _mcp.servers.testing import create_testing_server
        from _mcp.servers.security import create_security_server
        from _mcp.servers.patterns import create_patterns_server
        from _mcp.servers.gitlab import create_gitlab_server
        from _mcp.servers.python import create_python_server
        from _mcp.servers.core import create_core_server
        
        servers_to_test = {
            "coverage": create_coverage_server,
            "testing": create_testing_server,
            "security": create_security_server,
            "patterns": create_patterns_server,
            "gitlab": create_gitlab_server,
            "python": create_python_server,
            "core": create_core_server
        }
        
        results = {}
        
        for server_name, create_func in servers_to_test.items():
            print(f"Testing {server_name} server...")
            
            server_results = {}
            
            # Test server creation
            creation_result = self.test_server_creation(server_name, create_func)
            server_results["creation"] = creation_result
            
            if creation_result["status"] == "success":
                # If creation successful, test tools and health
                server = create_func()
                
                # Test tools
                tools_result = self.test_server_tools(server_name, server)
                server_results["tools"] = tools_result
                
                # Test health check
                health_result = self.test_server_health(server_name, server)
                server_results["health"] = health_result
                
                # Store server for later use
                self.servers[server_name] = server
            
            results[server_name] = server_results
        
        return results

def main():
    """Main testing function."""
    print("⚡ Storm Logger MCP Server Individual Testing")
    print("=" * 60)
    
    tester = ServerTester()
    results = tester.test_all_servers()
    
    # Print summary
    print("\n📊 Testing Summary:")
    print("-" * 40)
    
    total_servers = len(results)
    successful_creations = sum(1 for r in results.values() if r["creation"]["status"] == "success")
    
    print(f"Total servers tested: {total_servers}")
    print(f"Successful creations: {successful_creations}")
    print(f"Failed creations: {total_servers - successful_creations}")
    
    # Detailed results
    print("\n📋 Detailed Results:")
    for server_name, server_results in results.items():
        print(f"\n🔧 {server_name.upper()} Server:")
        
        # Creation status
        creation = server_results["creation"]
        status_icon = "✅" if creation["status"] == "success" else "❌"
        print(f"  {status_icon} Creation: {creation['message']}")
        
        if creation["status"] == "success":
            # Tools status
            if "tools" in server_results:
                tools = server_results["tools"]
                tool_count = len(tools.get("details", {}))
                print(f"  🛠️  Tools: {tool_count} tools available")
            
            # Health status
            if "health" in server_results:
                health = server_results["health"]
                health_icon = "✅" if health["status"] == "success" else "⚠️" if health["status"] == "warning" else "❌"
                print(f"  {health_icon} Health: {health['message']}")
    
    # Save results to file
    with open("_long_hauls/01-fix-mcp-server-health-and-run/server_test_results.json", "w") as f:
        json.dump(results, f, indent=2)
    
    print(f"\n💾 Results saved to server_test_results.json")
    
    # Return appropriate exit code
    if successful_creations == total_servers:
        print("\n🎉 All servers tested successfully!")
        return 0
    else:
        print(f"\n⚠️  {total_servers - successful_creations} servers had issues")
        return 1

if __name__ == "__main__":
    sys.exit(main())
```

### Step 2: Test Each Server Module
```bash
# Run individual server tests
python _mcp/test_servers.py
```

### Step 3: Test Specific Server Functionality
Create individual test scripts for each server:

```bash
# Test coverage server specifically
python -c "
import sys
sys.path.append('.')
from _mcp.servers.coverage import create_coverage_server
server = create_coverage_server()
print(f'Coverage server: {server.name}')
print(f'Tools: {[t.name for t in server.tools]}')
for tool in server.tools:
    print(f'  - {tool.name}: {tool.tags if hasattr(tool, \"tags\") else \"no tags\"}')
"
```

### Step 4: Test Tool Execution
For safe tools, test actual execution:

```bash
# Test health check tools
python -c "
import sys
sys.path.append('.')
from _mcp.servers.core import create_core_server
server = create_core_server()
for tool in server.tools:
    if tool.name == 'health_check':
        result = tool.function()
        print(f'Health check result: {result}')
"
```

## Testing/Validation

### Step 1: Server Creation Test
```bash
# Test all servers can be created
for server in coverage testing security patterns gitlab python core; do
    echo "Testing $server server..."
    python -c "
import sys
sys.path.append('.')
from _mcp.servers.$server import create_${server}_server
server = create_${server}_server()
print(f'✓ {server.name} created successfully')
"
done
```

### Step 2: Tool Availability Test
```bash
# Test that all servers have tools
python -c "
import sys
sys.path.append('.')
servers = ['coverage', 'testing', 'security', 'patterns', 'gitlab', 'python', 'core']
for server_name in servers:
    try:
        module = __import__(f'_mcp.servers.{server_name}', fromlist=['create_{}server'.format(server_name)])
        create_func = getattr(module, f'create_{server_name}_server')
        server = create_func()
        print(f'{server_name}: {len(server.tools)} tools, {len(server.resources) if hasattr(server, \"resources\") else 0} resources')
    except Exception as e:
        print(f'{server_name}: ERROR - {e}')
"
```

### Step 3: Health Check Test
```bash
# Test health checks work
python -c "
import sys
sys.path.append('.')
from _mcp.main import create_storm_mcp_server
server = create_storm_mcp_server()
for tool in server.tools:
    if tool.name == 'health_check':
        result = tool.function()
        print(f'Overall health: {result[\"overall_status\"]}')
        print(f'Server count: {len(result[\"servers\"])}')
"
```

## Success Criteria
- [ ] All 7 servers can be created without errors
- [ ] Each server has at least 1 tool
- [ ] Health check functions work for all servers
- [ ] No critical errors in server functionality
- [ ] Test results saved to file

## JSON Update Instructions

When starting this step:
```json
{
  "steps": {
    "06": {
      "status": "in_progress",
      "progress": 20,
      "issues": ["Testing server creation"],
      "next_action": "Test individual server modules"
    }
  }
}
```

When 50% complete (servers tested):
```json
{
  "steps": {
    "06": {
      "status": "in_progress",
      "progress": 50,
      "issues": ["Testing server functionality"],
      "next_action": "Test tool execution and health checks"
    }
  }
}
```

When complete:
```json
{
  "steps": {
    "06": {
      "status": "completed",
      "progress": 100,
      "issues": [],
      "next_action": "Proceed to Step 07"
    }
  },
  "current_step": "07",
  "overall_progress": 60,
  "completed_features": [
    "All 7 server modules implemented",
    "Health check functions added",
    "Server creation working",
    "Import dependencies resolved",
    "Complete health check system",
    "Individual server testing complete"
  ]
}
```

## Troubleshooting

### Common Issues

1. **Server creation fails**
   - Check import dependencies
   - Verify context_logic modules are available
   - Check for missing functions

2. **Tools not working**
   - Check tool function definitions
   - Verify tool registration
   - Check for missing imports

3. **Health check fails**
   - Check health check tool exists
   - Verify health check function works
   - Check for missing dependencies

### Debug Commands
```bash
# Debug specific server
python -c "
import sys
sys.path.append('.')
try:
    from _mcp.servers.coverage import create_coverage_server
    server = create_coverage_server()
    print(f'Server name: {server.name}')
    print(f'Tools: {[t.name for t in server.tools]}')
    print(f'First tool callable: {callable(server.tools[0].function) if server.tools else \"No tools\"}')
except Exception as e:
    import traceback
    print(f'Error: {e}')
    print(traceback.format_exc())
"
```

## Next Steps
After completing this step:
1. Update JSON status to "completed"
2. Proceed to Step 07: Integrate with Test Runner
3. Use test results to guide integration

## Notes
- This is a critical validation step
- Document any issues found for later resolution
- Test results will guide remaining steps
- Focus on basic functionality first