# Step 07: Integrate with Test Runner

## Prerequisites
- Step 06 completed (individual server testing complete)
- All servers can be created and tested
- Health check system working

## Objectives
1. Integrate MCP server health checks with test.sh
2. Add MCP server validation to test runner
3. Create MCP-specific test commands
4. Ensure smooth integration with existing test workflow

## Implementation Details

### Step 1: Update test.sh with MCP Health Check
Add MCP health check functionality to `test.sh`:

```bash
# Add to test.sh after line 560 (after MCP insights function)

# ⚡ Storm MCP Server Health Check ⚡
check_mcp_server_health() {
    local verbosity=${1:-1}
    
    echo -e "${BLUE}⚡ Storm MCP Server Health Check${NC}"
    echo -e "${GRAY}Validating MCP server components...${NC}"
    
    # Check if MCP health check CLI exists
    if [[ ! -f "_mcp/health_cli.py" ]]; then
        echo -e "${RED}✗ MCP Health Check CLI not found${NC}"
        return 1
    fi
    
    # Run MCP health check
    if python _mcp/health_cli.py > /tmp/mcp_health.log 2>&1; then
        local health_status=$(grep "Overall Status:" /tmp/mcp_health.log | cut -d: -f2 | tr -d ' ')
        
        case "$health_status" in
            "HEALTHY")
                echo -e "${GREEN}✓ MCP Server Status: HEALTHY${NC}"
                if [[ $verbosity -ge 2 ]]; then
                    echo -e "${GRAY}$(cat /tmp/mcp_health.log)${NC}"
                fi
                return 0
                ;;
            "WARNING")
                echo -e "${YELLOW}⚠ MCP Server Status: WARNING${NC}"
                if [[ $verbosity -ge 1 ]]; then
                    echo -e "${GRAY}$(cat /tmp/mcp_health.log)${NC}"
                fi
                return 1
                ;;
            *)
                echo -e "${RED}✗ MCP Server Status: ERROR${NC}"
                if [[ $verbosity -ge 1 ]]; then
                    echo -e "${GRAY}$(cat /tmp/mcp_health.log)${NC}"
                fi
                return 2
                ;;
        esac
    else
        echo -e "${RED}✗ MCP Health Check Failed${NC}"
        if [[ $verbosity -ge 1 ]]; then
            echo -e "${GRAY}$(cat /tmp/mcp_health.log)${NC}"
        fi
        return 3
    fi
}

# ⚡ Storm MCP Individual Server Test ⚡
test_mcp_individual_servers() {
    local verbosity=${1:-1}
    
    echo -e "${BLUE}⚡ Storm MCP Individual Server Testing${NC}"
    echo -e "${GRAY}Testing each MCP server module...${NC}"
    
    # Check if individual server test script exists
    if [[ ! -f "_mcp/test_servers.py" ]]; then
        echo -e "${RED}✗ MCP Individual Server Test script not found${NC}"
        return 1
    fi
    
    # Run individual server tests
    if python _mcp/test_servers.py > /tmp/mcp_individual.log 2>&1; then
        local success_count=$(grep "All servers tested successfully" /tmp/mcp_individual.log | wc -l)
        
        if [[ $success_count -gt 0 ]]; then
            echo -e "${GREEN}✓ All MCP servers tested successfully${NC}"
            if [[ $verbosity -ge 2 ]]; then
                echo -e "${GRAY}$(cat /tmp/mcp_individual.log)${NC}"
            fi
            return 0
        else
            echo -e "${YELLOW}⚠ Some MCP servers have issues${NC}"
            if [[ $verbosity -ge 1 ]]; then
                echo -e "${GRAY}$(cat /tmp/mcp_individual.log)${NC}"
            fi
            return 1
        fi
    else
        echo -e "${RED}✗ MCP Individual Server Testing Failed${NC}"
        if [[ $verbosity -ge 1 ]]; then
            echo -e "${GRAY}$(cat /tmp/mcp_individual.log)${NC}"
        fi
        return 2
    fi
}

# ⚡ Storm MCP Complete Validation ⚡
validate_mcp_complete() {
    local verbosity=${1:-1}
    
    echo -e "${PURPLE}⚡ Storm MCP Complete Validation${NC}"
    echo -e "${GRAY}Full MCP server validation suite...${NC}"
    
    local exit_code=0
    
    # Step 1: Check MCP health
    if ! check_mcp_server_health $verbosity; then
        echo -e "${RED}✗ MCP Health Check Failed${NC}"
        exit_code=1
    fi
    
    # Step 2: Test individual servers
    if ! test_mcp_individual_servers $verbosity; then
        echo -e "${RED}✗ MCP Individual Server Testing Failed${NC}"
        exit_code=1
    fi
    
    # Step 3: Test main server creation
    echo -e "${BLUE}Testing main MCP server creation...${NC}"
    if python -c "
import sys
sys.path.append('.')
from _mcp.main import create_storm_mcp_server
server = create_storm_mcp_server()
print(f'✓ Main server created: {server.name}')
print(f'  Tools: {len(server.tools)}')
" > /tmp/mcp_main.log 2>&1; then
        echo -e "${GREEN}✓ Main MCP server creation successful${NC}"
        if [[ $verbosity -ge 2 ]]; then
            echo -e "${GRAY}$(cat /tmp/mcp_main.log)${NC}"
        fi
    else
        echo -e "${RED}✗ Main MCP server creation failed${NC}"
        if [[ $verbosity -ge 1 ]]; then
            echo -e "${GRAY}$(cat /tmp/mcp_main.log)${NC}"
        fi
        exit_code=1
    fi
    
    # Summary
    if [[ $exit_code -eq 0 ]]; then
        echo -e "${GREEN}🎉 MCP Complete Validation: SUCCESS${NC}"
    else
        echo -e "${RED}💥 MCP Complete Validation: FAILED${NC}"
    fi
    
    return $exit_code
}
```

### Step 2: Add MCP Options to Command Line Parser
Update the command line parsing section in `test.sh`:

```bash
# Add after existing options (around line 160)
        --mcp-health)
            check_mcp_server_health $VERBOSITY
            exit $?
            ;;
        --mcp-servers)
            test_mcp_individual_servers $VERBOSITY
            exit $?
            ;;
        --mcp-validate)
            validate_mcp_complete $VERBOSITY
            exit $?
            ;;
        --mcp-full)
            # Full MCP validation as part of test suite
            MCP_VALIDATION=1
            shift
            ;;
```

### Step 3: Add MCP Validation to Main Test Flow
Integrate MCP validation into the main test execution:

```bash
# Add after "Storm Diagnostic: Analyzing test collection..." section
if [[ $MCP_VALIDATION -eq 1 ]]; then
    echo -e "${PURPLE}⚡ Storm MCP Validation Phase${NC}"
    echo -e "${GRAY}Validating MCP server infrastructure...${NC}"
    
    if ! validate_mcp_complete $VERBOSITY; then
        echo -e "${RED}[FAIL] Storm Alert: MCP Validation Failed${NC}"
        echo -e "${GRAY}\"When MCP fails, Storm shows the way\"${NC}"
        echo
        echo -e "${PURPLE}🌪️ Storm Solution: MCP troubleshooting steps:${NC}"
        echo -e "${GRAY}   -> Check MCP health: ./test.sh --mcp-health${NC}"
        echo -e "${GRAY}   -> Test servers: ./test.sh --mcp-servers${NC}"
        echo -e "${GRAY}   -> Validate complete: ./test.sh --mcp-validate${NC}"
        echo
        echo -e "${RED}[FAIL] Stopping due to MCP validation errors${NC}"
        exit 1
    fi
    
    echo -e "${GREEN}✓ MCP Validation Complete${NC}"
fi
```

### Step 4: Update Help Text
Add MCP options to the help text:

```bash
# Update help function
show_help() {
    cat << EOF
⚡ Storm Logger Smart Test Runner ⚡

Usage: $0 [OPTIONS]

Test Options:
  --quick, -q           Quick test mode (skip slow tests)
  --unit               Run only unit tests
  --integration        Run only integration tests
  --performance        Run only performance tests
  --django             Run only Django tests
  --coverage           Run with coverage reporting
  --no-coverage        Skip coverage reporting
  --watch              Watch mode (re-run on changes)

MCP Server Options:
  --mcp-health         Check MCP server health
  --mcp-servers        Test individual MCP servers
  --mcp-validate       Complete MCP validation
  --mcp-full           Include MCP validation in test suite

Output Options:
  --verbose, -v        Verbose output
  --quiet              Quiet output (errors only)
  --no-color           Disable colors
  --json               JSON output format

Other Options:
  --help, -h           Show this help message
  --version            Show version information

Examples:
  $0                   # Run all tests
  $0 --quick           # Quick test run
  $0 --mcp-health      # Check MCP server health
  $0 --mcp-full        # Full test suite with MCP validation
  $0 --unit --verbose  # Verbose unit tests only

EOF
}
```

### Step 5: Create MCP Test Integration Script
Create `_mcp/test_integration.py`:

```python
#!/usr/bin/env python3
"""
MCP Test Integration Script
Integrates MCP server testing with the main test suite
"""

import sys
import subprocess
from pathlib import Path

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

def run_mcp_health_check():
    """Run MCP health check and return result."""
    try:
        result = subprocess.run([
            sys.executable, "_mcp/health_cli.py"
        ], capture_output=True, text=True)
        
        return {
            "success": result.returncode == 0,
            "output": result.stdout,
            "error": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "output": "",
            "error": str(e)
        }

def run_individual_server_tests():
    """Run individual server tests and return result."""
    try:
        result = subprocess.run([
            sys.executable, "_mcp/test_servers.py"
        ], capture_output=True, text=True)
        
        return {
            "success": result.returncode == 0,
            "output": result.stdout,
            "error": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "output": "",
            "error": str(e)
        }

def main():
    """Main integration function."""
    print("⚡ Storm MCP Test Integration")
    
    # Run health check
    health_result = run_mcp_health_check()
    if health_result["success"]:
        print("✓ MCP Health Check: PASSED")
    else:
        print("✗ MCP Health Check: FAILED")
        print(health_result["error"])
        return 1
    
    # Run individual server tests
    server_result = run_individual_server_tests()
    if server_result["success"]:
        print("✓ Individual Server Tests: PASSED")
    else:
        print("✗ Individual Server Tests: FAILED")
        print(server_result["error"])
        return 1
    
    print("🎉 MCP Integration Tests: ALL PASSED")
    return 0

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

## Testing/Validation

### Step 1: Test MCP Health Check Integration
```bash
# Test MCP health check option
./test.sh --mcp-health
```

### Step 2: Test Individual Server Testing
```bash
# Test individual server option
./test.sh --mcp-servers
```

### Step 3: Test Complete MCP Validation
```bash
# Test complete MCP validation
./test.sh --mcp-validate
```

### Step 4: Test Full Integration
```bash
# Test MCP validation as part of main test suite
./test.sh --mcp-full --quick
```

## Success Criteria
- [ ] MCP health check integrated with test.sh
- [ ] Individual server testing available via command line
- [ ] Complete MCP validation working
- [ ] Integration with main test flow
- [ ] Help text updated with MCP options

## JSON Update Instructions

When starting this step:
```json
{
  "steps": {
    "07": {
      "status": "in_progress",
      "progress": 25,
      "issues": ["Integrating MCP health check with test.sh"],
      "next_action": "Add MCP options to test runner"
    }
  }
}
```

When 50% complete (integration added):
```json
{
  "steps": {
    "07": {
      "status": "in_progress",
      "progress": 50,
      "issues": ["Testing MCP integration"],
      "next_action": "Test all MCP integration options"
    }
  }
}
```

When complete:
```json
{
  "steps": {
    "07": {
      "status": "completed",
      "progress": 100,
      "issues": [],
      "next_action": "Proceed to Step 08"
    }
  },
  "current_step": "08",
  "overall_progress": 70,
  "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",
    "MCP integration with test runner"
  ]
}
```

## Troubleshooting

### Common Issues

1. **MCP health check fails in test.sh**
   - Check Python path in test.sh
   - Verify health_cli.py exists
   - Check file permissions

2. **Command line options not working**
   - Check option parsing in test.sh
   - Verify function names match
   - Check for typos in option names

3. **Integration script fails**
   - Check Python path setup
   - Verify script permissions
   - Check for missing dependencies

### Debug Commands
```bash
# Test MCP health check directly
python _mcp/health_cli.py

# Test individual server tests
python _mcp/test_servers.py

# Test integration script
python _mcp/test_integration.py
```

## Next Steps
After completing this step:
1. Update JSON status to "completed"
2. Proceed to Step 08: Create Production Launcher
3. Use integration to guide production launcher

## Notes
- Integration should be seamless with existing test workflow
- MCP validation should be optional by default
- Provide clear feedback on MCP status
- Document all new command line options