# Step 03: Implement Missing Server Modules

## Prerequisites
- Step 02 completed (Python packaging fixed)
- All imports working correctly
- FastMCP available and functional

## Objectives
1. Fix FastMCP API compatibility issues in all server modules
2. Remove unsupported 'tags' parameter from FastMCP.__init__()
3. Implement proper FastMCP server creation
4. Test each server module individually

## Current Status Analysis
Based on testing, we've discovered:
- ✅ All server modules can be imported successfully
- ✅ Context logic modules are available and functional
- ❌ FastMCP API compatibility issues: 'tags' parameter not supported
- ❌ All 7 server modules fail to create due to API mismatch
- ✅ Main server creates successfully but can't mount sub-servers

## Implementation Details

### Step 1: Fix FastMCP API Compatibility Issues

**CRITICAL**: All server modules are failing due to FastMCP API mismatch. The 'tags' parameter is not supported in FastMCP.__init__().

**Fix Required**: Remove 'tags' parameter from all FastMCP server creation calls.

```bash
# First, let's identify all the FastMCP creation calls with 'tags'
grep -r "tags=" _mcp/servers/

# The issue is in every server module - they all use:
# server = FastMCP(name="...", instructions="...", tags={"..."})
# But FastMCP doesn't accept 'tags' parameter
```

**Current Error**: `FastMCP.__init__() got an unexpected keyword argument 'tags'`

**Solution**: Remove the 'tags' parameter from all server creation calls.

### Step 2: Implement Missing Server Functions

For each missing or broken server module, implement the following structure:

#### Template for Server Module:
```python
"""
[Module Name] Server Module
Specialized server for [specific functionality].
"""

from typing import List, Optional
from fastmcp import FastMCP
from _mcp.context_logic import [relevant_modules]

def create_[module]_server() -> FastMCP:
    """
    Create a specialized server for [module] tools.
    
    Returns:
        FastMCP server instance with [module] tools
    """
    server = FastMCP(
        name="Storm Logger [Module] Server",
        instructions="""
        This server provides [specific functionality] for the Storm Logger project.
        """,
        tags={"[module]", "storm_logger", "enterprise"}
    )
    
    @server.tool(tags={"public", "stable"})
    def example_tool(param: str = "default") -> str:
        """Example tool implementation."""
        return f"Tool executed with param: {param}"
    
    @server.resource(tags={"public"})
    def example_resource() -> str:
        """Example resource implementation."""
        return "Resource data"
    
    return server
```

### Step 3: Implement Core Server Module
Priority: HIGH - This is the main server coordinator

```python
"""
Core Server Module
Main coordination server for Storm Logger MCP functionality.
"""

from typing import Dict, List, Optional
from fastmcp import FastMCP
from _mcp.context_logic import workflow_optimization, project_management

def create_core_server() -> FastMCP:
    """
    Create the core Storm Logger MCP server.
    
    Returns:
        FastMCP server instance with core coordination tools
    """
    server = FastMCP(
        name="Storm Logger Core Server",
        instructions="""
        This is the main coordination server for Storm Logger MCP functionality.
        It provides project management, workflow optimization, and server coordination.
        """,
        tags={"core", "coordination", "storm_logger"}
    )
    
    @server.tool(tags={"public", "stable"})
    def get_server_status() -> Dict:
        """Get status of all Storm Logger MCP servers."""
        return {
            "status": "operational",
            "servers": ["core", "coverage", "testing", "security", "patterns", "gitlab", "python"],
            "health": "healthy"
        }
    
    @server.tool(tags={"public", "stable"})
    def optimize_workflow(workflow_type: str = "testing") -> str:
        """Optimize development workflow."""
        return workflow_optimization.optimize_testing_workflow()
    
    @server.resource(tags={"public"})
    def project_metadata() -> str:
        """Get Storm Logger project metadata."""
        return project_management.get_project_metadata()
    
    return server
```

### Step 4: Fix Coverage Server Module
Ensure it has all required functions:

```python
@server.tool(tags={"public", "stable"})
def analyze_coverage_gaps(
    project_path: str = "/home/mathew/python-3.10.12-Projects/storm_logger",
    run_coverage: bool = True,
    focus_modules: Optional[List[str]] = None
) -> str:
    """Analyze test coverage gaps with business intelligence."""
    return coverage_analysis.analyze_coverage_gaps(
        project_path, run_coverage, focus_modules
    )
```

### Step 5: Implement Health Check Functions
Add to each server module:

```python
@server.tool(tags={"internal", "health"})
def health_check() -> Dict:
    """Perform health check for this server module."""
    return {
        "server": "[module_name]",
        "status": "healthy",
        "timestamp": "2025-01-18T16:30:00Z",
        "checks": {
            "imports": "ok",
            "dependencies": "ok",
            "tools": "ok"
        }
    }
```

## Testing/Validation

### Step 1: Test Server Module Creation
```bash
# Test each server module
for module in coverage testing security patterns gitlab python core; do
    echo "Testing $module server creation..."
    python -c "
import sys
sys.path.append('.')
try:
    from _mcp.servers.$module import create_${module}_server
    server = create_${module}_server()
    print(f'✓ {module} server created successfully')
    print(f'  Name: {server.name}')
    print(f'  Tools: {len(server.tools)} tools')
except Exception as e:
    print(f'✗ {module} server failed: {e}')
"
done
```

### Step 2: Test Tool Functionality
```bash
# Test individual tools
python -c "
import sys
sys.path.append('.')
from _mcp.servers.core import create_core_server
server = create_core_server()
print('Core server tools:', [tool.name for tool in server.tools])
"
```

### Step 3: Test Health Check Functions
```bash
# Test health checks
python -c "
import sys
sys.path.append('.')
from _mcp.servers.core import create_core_server
server = create_core_server()
# Test health check tool if available
print('Health check tools available')
"
```

## Success Criteria
- [ ] All 7 server modules can be created without errors
- [ ] Each server has at least 2 tools implemented
- [ ] Each server has health check functionality
- [ ] All servers can be imported and instantiated
- [ ] No missing function errors

## JSON Update Instructions

When starting this step:
```json
{
  "steps": {
    "03": {
      "status": "in_progress",
      "progress": 10,
      "issues": ["Auditing server modules"],
      "next_action": "Implement missing server functions"
    }
  }
}
```

When 50% complete (core servers implemented):
```json
{
  "steps": {
    "03": {
      "status": "in_progress",
      "progress": 50,
      "issues": ["Implementing remaining server modules"],
      "next_action": "Complete all server modules and add health checks"
    }
  }
}
```

When complete:
```json
{
  "steps": {
    "03": {
      "status": "completed",
      "progress": 100,
      "issues": [],
      "next_action": "Proceed to Step 04"
    }
  },
  "current_step": "04",
  "overall_progress": 30,
  "completed_features": [
    "All 7 server modules implemented",
    "Health check functions added",
    "Server creation working"
  ]
}
```

## Troubleshooting

### Common Issues

1. **Function import errors**
   - Check context_logic modules are available
   - Verify function names match
   - Check for typos in import statements

2. **FastMCP server creation fails**
   - Check FastMCP version compatibility
   - Verify server configuration is correct
   - Check for conflicting parameters

3. **Missing context_logic modules**
   - Some functions may not exist yet
   - Create placeholder functions if needed
   - Document which functions need implementation

### Debug Commands
```bash
# Check specific server module
python -c "
import sys
sys.path.append('.')
from _mcp.servers.coverage import create_coverage_server
server = create_coverage_server()
print(f'Server: {server.name}')
print(f'Tools: {[t.name for t in server.tools]}')
print(f'Resources: {[r.name for r in server.resources]}')
"
```

## Next Steps
After completing this step:
1. Update JSON status to "completed"
2. Proceed to Step 04: Fix Import Dependencies
3. Use implemented servers to test import resolution

## Notes
- This is a critical step - all subsequent steps depend on it
- Document any placeholder functions created
- Keep track of which context_logic functions need implementation
- Test thoroughly before proceeding

## Checkpoint
This step completes the first major checkpoint. When finished:
1. All server modules should be functional
2. Ready for import dependency testing
3. Foundation for health check system is in place