# MCPHealthGuardian - MCPController Integration

## Overview

The MCPHealthGuardian now subscribes to MCPController's `onConnectionStateChange` event to automatically pause/resume health monitoring based on the MCP connection state.

## Implementation Details

### Architecture

```
MCPController (connection lifecycle)
        │
        │ emits ConnectionStateChange events
        ↓
MCPHealthGuardian (health monitoring)
        │
        ├─→ on "connected": resume polling + force check
        ├─→ on "disconnected": pause polling + handleDisconnect
        └─→ on "error": pause polling + handleDisconnect
```

### Integration Points

#### 1. Activation-Time Integration

```typescript
// In extension activation or initialization code:
const controller = getMCPController();
const guardian = new MCPHealthGuardian();

await guardian.activate(
  context,
  mcpClient,
  aiDetector,
  controller // ← Pass MCPController for automatic subscription
);
```

#### 2. Post-Activation Registration

```typescript
// If controller becomes available after guardian initialization:
const subscription = guardian.registerController(controller);
context.subscriptions.push(subscription);
```

### Event Handling

When MCPController emits a connection state change:

| Event State | Guardian Action | Rationale |
|-------------|----------------|-----------|
| `connected` | Resume polling + force deep check | Connection restored, verify health immediately |
| `disconnected` | Pause polling + set state to unknown | No point checking health when disconnected |
| `error` | Pause polling + set state to unhealthy | Connection error indicates service unavailable |
| `connecting` | No action | Wait for final state (connected/error) |

### Internal Methods Used

- **`handleReconnection()`**: Resumes polling and performs deep health check
- **`handleDisconnection()`**: Pauses polling and updates state manager
- **`setupConnectionStateListeners()`**: Private method that subscribes to events

## Code Changes

### Files Modified

1. **`apps/vscode/src/services/MCPHealthGuardian.ts`**
   - Added `mcpController` parameter to `activate()` method
   - Added `registerController()` public method for late binding
   - Added `setupConnectionStateListeners()` private method
   - Imported `ConnectionStateChange` type from MCPController

2. **`apps/vscode/test/unit/services/MCPHealthGuardian.test.ts`**
   - Added integration test for connection state handling

### Type Safety

All integration uses the exported `ConnectionStateChange` interface from MCPController for type consistency:

```typescript
export interface ConnectionStateChange {
  state: "disconnected" | "connecting" | "connected" | "error";
  previousState: "disconnected" | "connecting" | "connected" | "error";
  timestamp: number;
  error?: Error;
}
```

## Behavioral Flow

```
1. MCPController starts connection attempt
   ↓
2. Emits onConnectionStateChange({ state: "connecting" })
   → Guardian: no action (waiting for final state)
   ↓
3a. Success: onConnectionStateChange({ state: "connected" })
    → Guardian: startPolling() + forceCheck("deep")

3b. Failure: onConnectionStateChange({ state: "error" })
    → Guardian: pausePolling() + handleDisconnect()
    ↓
4. Later disconnection: onConnectionStateChange({ state: "disconnected" })
   → Guardian: pausePolling() + handleDisconnect()
```

## Benefits

1. **Automatic Lifecycle Coordination**: No manual pause/resume calls needed
2. **Resource Efficiency**: No wasted polling when connection is down
3. **Fail-Safe**: Guardian handles disconnection gracefully
4. **Type-Safe**: Shared types prevent interface drift
5. **Flexible**: Supports both activation-time and late-binding patterns

## Spec Compliance

This implementation fulfills the requirement from the MCP Health Guardian specification (lines 269-278):

> **Guardian subscribes to lifecycle events:**
> - MCPController/MCPLifecycleManager exposes `onConnectionStateChange`
> - Guardian subscribes to pause/resume polling based on connection state
> - On disconnect: Guardian pauses polling, sets state to unknown
> - On reconnect: Guardian resumes polling, forces immediate check

## Testing

See `test/unit/services/MCPHealthGuardian.test.ts` for integration test coverage.

## Future Enhancements

- Add telemetry for connection state transitions
- Implement exponential backoff for health checks after repeated connection failures
- Add configuration option for auto-pause behavior
