# NeuBird MCP Server - Comprehensive Specification

## Overview

The NeuBird MCP (Model Context Protocol) Server enables AI coding agents (like Cursor.ai) to investigate cloud environment issues by leveraging NeuBird's automated incident analysis and root cause analysis capabilities. This server acts as a bridge between coding agents and the NeuBird API, providing intelligent, context-aware tools for cloud incident investigation.

## Use Cases

### Primary Use Case
A developer using Cursor.ai encounters an alert or incident in their cloud environment. They can:
1. Ask Cursor to investigate an alert by providing an alert ID
2. Request a new investigation with a custom prompt and timeframe
3. Get status updates on ongoing investigations
4. Retrieve and analyze completed RCAs
5. Follow up on existing investigations with additional questions

### Developer Experience Goals
- **Natural Language Interface**: Developers should be able to say "investigate alert XYZ" or "analyze my EKS cluster for the last 2 hours"
- **Intelligent Defaults**: The server should automatically handle project selection, timeframe formatting, and session management
- **Streaming Support**: Real-time feedback during long-running investigations
- **Context Awareness**: Remember previous investigations and allow follow-up questions

## Architecture

### Components

```
┌─────────────────────────────────────────────────────────┐
│                    Cursor.ai / AI Agent                  │
└──────────────────────┬──────────────────────────────────┘
                       │ MCP Protocol
┌──────────────────────▼──────────────────────────────────┐
│               NeuBird MCP Server                         │
│  ┌──────────────────────────────────────────────────┐   │
│  │  Tool Handlers:                                   │   │
│  │  • investigate_alert_by_id                        │   │
│  │  • create_investigation                           │   │
│  │  • get_investigation_status                       │   │
│  │  • get_rca_by_alert_id                           │   │
│  │  • continue_investigation                         │   │
│  │  • list_projects                                  │   │
│  │  • list_sessions                                  │   │
│  │  • inspect_session                                │   │
│  │  • get_session_report                             │   │
│  │  • get_session_summary                            │   │
│  │  • get_incident_report                            │   │
│  └──────────────────────────────────────────────────┘   │
│  ┌──────────────────────────────────────────────────┐   │
│  │  Core Services:                                   │   │
│  │  • AuthenticationService                          │   │
│  │  • SessionManager                                 │   │
│  │  • ProjectManager                                 │   │
│  │  • TimeframeParser                                │   │
│  │  • StreamingHandler                               │   │
│  └──────────────────────────────────────────────────┘   │
└──────────────────────┬──────────────────────────────────┘
                       │ HTTPS/REST
┌──────────────────────▼──────────────────────────────────┐
│                  NeuBird API                             │
│  • /api/v1/project                                       │
│  • /api/v1/inference/session/list                        │
│  • /api/v1/inference/new_session                         │
│  • /api/v1/inference/session                             │
│  • /api/v1/inference/session/inspect                     │
│  • /api/v1/inference/session_report                      │
│  • /api/v1/inference/session/summary/{uuid}              │
│  • /api/v1/inference/incident_report                     │
│  • /api/v1/user/login                                    │
└──────────────────────────────────────────────────────────┘
```

## MCP Tools Specification

### 1. `neubird_investigate_alert`

**Description**: Finds an existing RCA or creates a new investigation for a specific alert/incident ID.

**Input Schema**:
```typescript
{
  alert_id: string;           // Full alert ID (e.g., /subscriptions/.../alerts/...)
  project_uuid?: string;      // Optional: if not provided, will auto-detect
  wait_for_completion?: boolean; // Default: false. If true, polls until complete
  max_wait_seconds?: number;  // Default: 300 (5 minutes)
}
```

**Behavior**:
1. Searches for existing sessions associated with the alert_id
2. If found, returns the latest RCA
3. If not found, creates a new investigation session
4. If `wait_for_completion` is true, polls for completion
5. Returns investigation status and results

**Output**:
```typescript
{
  status: "found_existing" | "new_investigation" | "in_progress" | "completed";
  session_uuid: string;
  investigation_results?: {
    final_answer: string;
    chain_of_thoughts: Array<{
      description: string;
      investigation: string;
    }>;
    sources: Array<any>;
    follow_up_suggestions: string[];
  };
  message: string;
}
```

### 2. `neubird_create_investigation`

**Description**: Creates a new custom investigation with a user-provided prompt and timeframe.

**Input Schema**:
```typescript
{
  prompt: string;             // Investigation prompt
  timeframe?: string;         // Natural language timeframe (e.g., "last 2 hours", "past week")
  start_time?: string;        // ISO 8601 timestamp
  end_time?: string;          // ISO 8601 timestamp
  project_uuid?: string;      // Optional: if not provided, will auto-detect or use default
  wait_for_completion?: boolean; // Default: false
  max_wait_seconds?: number;  // Default: 300 (5 minutes)
  stream_updates?: boolean;   // Default: false. If true, provides real-time updates
}
```

**Behavior**:
1. Validates and parses timeframe into proper format
2. Enhances prompt to include timeframe context
3. Selects appropriate project (auto-detect or use default)
4. Creates new session
5. Sends investigation prompt
6. Optionally waits for completion or streams results

**Output**:
```typescript
{
  session_uuid: string;
  status: "created" | "in_progress" | "completed";
  enhanced_prompt: string;    // Shows how the prompt was enhanced
  timeframe_parsed: {
    start: string;
    end: string;
    description: string;
  };
  investigation_results?: {
    // Same as neubird_investigate_alert
  };
}
```

### 3. `neubird_get_investigation_status`

**Description**: Gets the current status and results of an ongoing or completed investigation.

**Input Schema**:
```typescript
{
  session_uuid: string;
  project_uuid?: string;      // Optional: will be auto-detected if not provided
  include_full_details?: boolean; // Default: true
}
```

**Output**:
```typescript
{
  session_uuid: string;
  status: "in_progress" | "completed" | "failed" | "unknown";
  progress_percentage?: number;
  current_step?: string;
  investigation_results?: {
    // Same as neubird_investigate_alert
  };
  created_at: string;
  updated_at: string;
}
```

### 4. `neubird_continue_investigation`

**Description**: Asks a follow-up question or provides additional context to an existing investigation.

**Input Schema**:
```typescript
{
  session_uuid: string;
  follow_up_prompt: string;
  project_uuid?: string;
  wait_for_completion?: boolean;
  max_wait_seconds?: number;
}
```

**Output**: Same as `neubird_create_investigation`

### 5. `neubird_list_projects`

**Description**: Lists all available NeuBird projects for the authenticated user.

**Input Schema**:
```typescript
{
  include_inactive?: boolean; // Default: false
}
```

**Output**:
```typescript
{
  projects: Array<{
    uuid: string;
    name: string;
    description: string;
    state: string;
    sync_state: string;
    training_state: string;
    created_at: string;
    updated_at: string;
  }>;
  default_project?: string; // UUID of the default project
}
```

### 6. `neubird_list_sessions`

**Description**: Lists sessions for a project with pagination, date filtering, and investigation status filtering support.

**Input Schema**:
```typescript
{
  project_uuid?: string;           // Optional: uses default if not provided
  page?: number;                   // Page number (1-indexed), default: 1
  limit?: number;                  // Results per page (max 100), default: 50
  date_from?: string;              // ISO 8601 date or date string (e.g., "2024-01-01")
  date_to?: string;                // ISO 8601 date or date string
  organization_uuid?: string;      // Optional: defaults to ORGANIZATION_NAME_ROOT
  only_uninvestigated?: boolean;   // Convenience: filter for uninvestigated incidents
  investigation_status?: string;   // Filter by investigation status (e.g., "INVESTIGATION_STATUS_NOT_STARTED")
  session_type?: string;           // Filter by session type (e.g., "SESSION_TYPE_INCIDENT")
  hide_grouped_incidents?: boolean; // If true, hides grouped incidents, default: false
  search_term?: string;            // Search for incidents by title keyword (e.g., "load avg", "database")
  compact?: boolean;               // If true, returns compact format to reduce token usage
}
```

**Behavior**:
1. Retrieves list of sessions for specified project
2. Supports pagination using page/limit parameters
3. Can filter by date range using create_time field
4. Can filter by investigation status (e.g., not started, in progress, completed)
5. Can filter by session type (e.g., incident vs manual investigations)
6. Convenience parameter `only_uninvestigated` automatically sets investigation_status to "INVESTIGATION_STATUS_NOT_STARTED" and session_type to "SESSION_TYPE_INCIDENT"
7. Can optionally hide grouped incidents
8. **Can search incidents by title using `search_term` parameter** - performs case-insensitive partial match on incident_info.title field. Works with both investigated and uninvestigated incidents.
9. Automatically enables compact mode for >10 results to reduce token usage (can be overridden with `compact` parameter)
10. Returns sessions sorted by creation time (most recent first)

**Output**:
```typescript
{
  sessions: Array<{
    session_uuid: string;
    name: string;
    create_time: string;
    last_update: string;
    prompt_cycle_count: number;
    incident_info?: {
      id: string;
      title?: string;
      priority?: string;
      status?: string;
      type?: string;
      grouped_incidents?: {
        id: string[];
        reason: string;
      };
    };
  }>;
  page: number;
  limit: number;
  count: number;
  project_uuid: string;
  compact_mode: boolean;
  filters_applied: {
    date_from?: string;
    date_to?: string;
    investigation_status?: string;
    session_type?: string;
    only_uninvestigated?: boolean;
    hide_grouped_incidents?: boolean;
    search_term?: string;
  };
  compact_hint?: string;           // Hint when compact mode is active
  pagination_hint?: string;        // Hint when more results are available
  investigation_hint?: string;     // Hint for uninvestigated incidents
}
```

### 7. `neubird_inspect_session`

**Description**: Gets detailed information about a session including all prompt cycles, chain of thoughts, sources, and follow-up suggestions.

**Input Schema**:
```typescript
{
  session_uuid: string;
  project_uuid?: string;      // Optional: will auto-detect if not provided
  organization_uuid?: string; // Optional: defaults to ORGANIZATION_NAME_ROOT
}
```

**Behavior**:
1. Retrieves full session details using /api/v1/inference/session/inspect
2. Returns all prompt cycles with detailed information
3. Includes chain of thoughts (analysis steps)
4. Includes sources used in the investigation
5. Includes follow-up suggestions

**Output**:
```typescript
{
  session_info: {
    session_uuid: string;
    name: string;
    create_time: string;
    last_update: string;
  };
  prompt_cycles: Array<{
    id: string;
    status: string; // PROMPT_STATUS_COMPLETED, PROMPT_STATUS_ERROR, etc.
    request: {
      messages: Array<{
        content: {
          content_type: string;
          parts: string[];
        };
      }>;
    };
    final_answer?: string;
    chain_of_thoughts: Array<{
      description: string;
      investigation?: string;
    }>;
    sources: Array<{
      id?: string;
      title?: string;
      // ... other source fields
    }>;
    follow_up_suggestions: string[];
  }>;
}
```

### 8. `neubird_get_session_report`

**Description**: Gets a summary report for one or more sessions, including time saved metrics.

**Input Schema**:
```typescript
{
  session_uuids: string[];    // Array of session UUIDs (can be single or multiple)
  project_uuid: string;       // Required: project UUID
}
```

**Behavior**:
1. Retrieves session reports using GET /api/v1/inference/session_report
2. Can fetch reports for multiple sessions in one call
3. Includes summary and time-saved metrics

**Output**:
```typescript
{
  reports: Array<{
    create_time: string;
    prompt: string;
    session_link: string;
    summary: string;
    time_saved: number; // in seconds
  }>;
}
```

### 9. `neubird_get_session_summary`

**Description**: Gets detailed analysis and scoring for a session, including accuracy and completeness metrics.

**Input Schema**:
```typescript
{
  session_uuid: string;
}
```

**Behavior**:
1. Retrieves session summary using GET /api/v1/inference/session/summary/{uuid}
2. Returns detailed scoring information if available
3. Includes qualitative feedback and improvement suggestions

**Output**:
```typescript
{
  analysis_score?: {
    accuracy: {
      root_cause_correct: 'Yes' | 'No' | 'Partial';
      impact_analysis_correct: 'Yes' | 'No' | 'Partial';
      timeline_accurate: 'Yes' | 'No' | 'Partial';
      overall_score: number;
    };
    completeness: {
      data_sources: number;
      remediation_steps: number;
      prevention_measures: number;
      business_impact: number;
      overall_score: number;
    };
    qualitative: {
      trust_without_review: 'Yes' | 'No' | 'Maybe';
      missing_elements: string;
      additional_notes: string;
      improvement_suggestions: string;
    };
    scored_by: string;
    scored_during_call: boolean;
    call_recording_url: string | null;
  };
}
```

### 10. `neubird_get_incident_report`

**Description**: Gets comprehensive incident statistics and analytics across all investigations.

**Input Schema**:
```typescript
{
  // No parameters required - returns organization-wide stats
}
```

**Behavior**:
1. Retrieves incident report using GET /api/v1/inference/incident_report
2. Returns organization-wide incident analytics
3. Includes time saved metrics, MTTR, and noise reduction stats

**Output**:
```typescript
{
  avg_investigation_time_saved_minutes: number;
  avg_mttr: number; // Mean Time To Resolution
  end_time: string;
  start_time: string;
  incident_type_reports: Array<{
    incident_type: string;
    priority_reports: Array<{
      avg_investigation_time_minutes: number;
      avg_mttr: number;
      avg_time_saved_minutes: number;
      investigated_incidents: number;
      percent_grouped: number;
      priority: string; // e.g., "P1", "P2", "P3"
      total_incidents: number;
    }>;
  }>;
  noise_reduction: number; // Percentage
  total_incidents: number;
  total_investigation_time_saved_hours: number;
  total_investigations: number;
}
```

### 11. `neubird_switch_instance`

**Description**: Switch to a different NeuBird instance by updating the base URL. Useful for users managing multiple NeuBird environments (dev, staging, prod) or multiple customer instances.

**Input Schema**:
```typescript
{
  base_url: string;  // The new NeuBird instance to connect to
                     // Accepts multiple formats:
                     // - Just subdomain: "prod", "customerA"
                     // - Partial URL: "prod.app.neubird.ai"
                     // - Full URL: "https://prod.app.neubird.ai/api"
}
```

**Behavior**:
1. Normalizes the input URL to ensure correct format:
   - Adds `.app.neubird.ai` suffix if only subdomain provided
   - Adds `https://` prefix if protocol missing
   - Adds `/api` path if not present
2. Validates the URL format
3. Updates the base URL configuration
4. Clears cached authentication tokens (different instance requires new auth)
5. Clears project cache (different instance has different projects)

**URL Normalization Examples**:

| Input | Normalized Output |
|-------|------------------|
| `"prod"` | `https://prod.app.neubird.ai/api` |
| `"customerA"` | `https://customerA.app.neubird.ai/api` |
| `"staging"` | `https://staging.app.neubird.ai/api` |
| `"prod.app.neubird.ai"` | `https://prod.app.neubird.ai/api` |
| `"https://prod.app.neubird.ai"` | `https://prod.app.neubird.ai/api` |
| `"https://prod.app.neubird.ai/api"` | `https://prod.app.neubird.ai/api` |
| `"custom.domain.com/api"` | `https://custom.domain.com/api` |

**Output**:
```typescript
{
  success: boolean;
  input_provided: string;      // Original input from user
  normalized_url: string;       // URL after normalization
  previous_url: string;         // Previous base URL
  new_url: string;             // New base URL (same as normalized_url)
  message: string;             // Human-readable status message
  note: string;                // Important information about next steps
}
```

**Success Response Example**:
```typescript
{
  success: true,
  input_provided: "prod",
  normalized_url: "https://prod.app.neubird.ai/api",
  previous_url: "https://sandbox.app.neubird.ai/api",
  new_url: "https://prod.app.neubird.ai/api",
  message: "Switched from https://sandbox.app.neubird.ai/api to https://prod.app.neubird.ai/api. Authentication tokens cleared. You can now use NeuBird tools with the new instance.",
  note: "The next NeuBird API call will authenticate against the new instance."
}
```

**Error Response Example**:
```typescript
{
  success: false,
  error: "Invalid base URL format: invalid-url",
  current_url: "https://sandbox.app.neubird.ai/api",
  suggestions: [
    "Verify the base URL format is correct (e.g., \"https://app.neubird.ai/api\")",
    "Ensure the URL includes the /api path",
    "Check that the instance is accessible"
  ]
}
```

**Important Notes**:
- Switching instances clears all authentication tokens
- Switching instances clears the project cache
- The next API call will trigger re-authentication
- Users will need to re-list projects after switching

---

### 12. `neubird_configure_defaults`

**Description**: Sets default project and preferences for the session.

**Input Schema**:
```typescript
{
  default_project_uuid?: string;
  default_organization_uuid?: string;
  default_timeframe?: string; // e.g., "last 1 hour"
  enable_streaming?: boolean;
}
```

**Output**:
```typescript
{
  status: "configured";
  current_defaults: {
    project_uuid: string;
    organization_uuid: string;
    timeframe: string;
    streaming_enabled: boolean;
  };
}
```

## Filtering and Search Capabilities

### Investigation Status Filtering

The `neubird_list_sessions` tool supports filtering sessions by investigation status. This allows you to find incidents based on whether they've been investigated or not.

**Supported Investigation Statuses**:
- `INVESTIGATION_STATUS_NOT_STARTED` - Incidents that have not been investigated yet
- `INVESTIGATION_STATUS_IN_PROGRESS` - Investigations currently in progress
- `INVESTIGATION_STATUS_COMPLETED` - Completed investigations

**Example - Find uninvestigated incidents**:
```json
{
  "investigation_status": "INVESTIGATION_STATUS_NOT_STARTED",
  "session_type": "SESSION_TYPE_INCIDENT"
}
```

**Convenience Parameter**:
For the common use case of finding uninvestigated incidents, use the `only_uninvestigated` parameter:
```json
{
  "only_uninvestigated": true
}
```
This automatically sets both `investigation_status` and `session_type` to the appropriate values.

### Session Type Filtering

Filter sessions by their type to distinguish between automated incident investigations and manual investigations.

**Supported Session Types**:
- `SESSION_TYPE_INCIDENT` - Automated incident investigations triggered by alerts
- `SESSION_TYPE_MANUAL` - Manual investigations created by users

### Date Range Filtering

Filter sessions by creation date using `date_from` and `date_to` parameters:

```json
{
  "date_from": "2024-01-01",
  "date_to": "2024-01-31"
}
```

Supports:
- ISO 8601 date strings (e.g., "2024-01-01")
- ISO 8601 datetime strings (e.g., "2024-01-01T00:00:00Z")

### Grouped Incidents

Some incidents may be automatically grouped by NeuBird when they share similar characteristics. Use the `hide_grouped_incidents` parameter to exclude these from results:

```json
{
  "hide_grouped_incidents": true
}
```

### Combining Filters

All filters can be combined for precise queries:

```json
{
  "project_uuid": "74acc801-3428-4292-8a74-ae16ecb71c24",
  "only_uninvestigated": true,
  "date_from": "2024-01-01",
  "hide_grouped_incidents": true,
  "limit": 20
}
```

## Core Services

### AuthenticationService

**Responsibilities**:
- Authenticate using email/password from environment variables
- Cache authentication tokens
- Refresh tokens before expiry
- Handle authentication failures gracefully

**Configuration**:
```typescript
{
  NEUBIRD_EMAIL: string;      // From .env
  NEUBIRD_PASSWORD: string;   // From .env
  NEUBIRD_BASE_URL: string;   // From .env, default: https://sandbox.app.neubird.ai/api
  TOKEN_REFRESH_BUFFER: number; // Default: 5 minutes before expiry
}
```

### SessionManager

**Responsibilities**:
- Create and manage investigation sessions
- Send prompts to sessions
- Poll for session completion
- Inspect session details
- Retrieve investigation results
- Handle streaming responses

**Key Methods**:
```typescript
async createSession(projectUuid: string, organizationUuid: string): Promise<Session>;
async sendPrompt(sessionUuid: string, projectUuid: string, prompt: string, options?: PromptOptions): Promise<PromptResponse>;
async inspectSession(sessionUuid: string, projectUuid: string, organizationUuid: string): Promise<SessionDetails>;
async pollForCompletion(sessionUuid: string, maxAttempts: number, intervalMs: number): Promise<SessionDetails>;
async findSessionsByAlertId(alertId: string, projectUuid: string, organizationUuid: string): Promise<Session[]>;
```

### ProjectManager

**Responsibilities**:
- List available projects
- Get project details
- Auto-select appropriate project based on context
- Manage project preferences

**Key Methods**:
```typescript
async listProjects(): Promise<Project[]>;
async getProject(projectUuid: string): Promise<Project>;
async getDefaultProject(): Promise<Project>;
async setDefaultProject(projectUuid: string): Promise<void>;
```

### TimeframeParser

**Responsibilities**:
- Parse natural language timeframes (e.g., "last 2 hours", "past 24 hours", "yesterday")
- Convert to ISO 8601 timestamps
- Validate timeframe inputs
- Provide intelligent defaults

**Supported Formats**:
- "last X hours/minutes/days/weeks"
- "past X hours/minutes/days/weeks"
- "since YYYY-MM-DD"
- "between YYYY-MM-DD and YYYY-MM-DD"
- ISO 8601 timestamps
- Relative time strings

**Key Methods**:
```typescript
parseTimeframe(input: string): { start: Date, end: Date, description: string };
formatForPrompt(timeframe: { start: Date, end: Date }): string;
validateTimeframe(start: Date, end: Date): boolean;
```

### StreamingHandler

**Responsibilities**:
- Handle Server-Sent Events (SSE) from NeuBird API
- Parse streaming response chunks
- Extract progress updates
- Detect completion
- Aggregate final results

**Key Methods**:
```typescript
async streamPromptResponse(sessionUuid: string, projectUuid: string, prompt: string, onProgress: (data: ProgressUpdate) => void): Promise<CompletedResponse>;
```

## Configuration

### Environment Variables

```bash
# Required
NEUBIRD_EMAIL=user@example.com
NEUBIRD_PASSWORD=your_password
NEUBIRD_BASE_URL=https://your-app.app.neubird.ai/api

# Optional
NEUBIRD_DEFAULT_PROJECT_UUID=uuid-here
NEUBIRD_DEFAULT_ORGANIZATION_UUID=ORGANIZATION_NAME_ROOT
NEUBIRD_DEFAULT_TIMEFRAME="last 1 hour"
NEUBIRD_ENABLE_STREAMING=true
NEUBIRD_MAX_POLL_ATTEMPTS=30
NEUBIRD_POLL_INTERVAL_MS=2000
```

### Server Configuration

```typescript
{
  name: "@neubirdai/mcp-server-neubird",
  version: "3.0.0",
  capabilities: {
    tools: {},
    logging: {},
    resources: {} // For caching investigation results
  }
}
```

## Error Handling

### Error Types

1. **Authentication Errors**
   - Invalid credentials
   - Token expiration
   - Network connectivity issues

2. **API Errors**
   - Rate limiting
   - Invalid requests
   - Server errors
   - Timeouts

3. **Validation Errors**
   - Invalid alert IDs
   - Invalid timeframes
   - Missing required parameters

4. **Investigation Errors**
   - Session creation failures
   - Prompt sending failures
   - Investigation timeouts
   - No results found

### Error Response Format

```typescript
{
  error: {
    type: "authentication" | "api" | "validation" | "investigation" | "unknown";
    message: string;
    details?: any;
    recovery_suggestions?: string[];
  }
}
```

## Performance Considerations

### Caching Strategy

1. **Authentication Tokens**: Cache for 55 minutes (with 5-minute buffer)
2. **Project List**: Cache for 5 minutes
3. **Completed Investigations**: Cache for 1 hour
4. **Session Status**: No caching (always fetch fresh)

### Rate Limiting

- Implement exponential backoff for API requests
- Respect API rate limits (if specified by NeuBird)
- Queue requests if necessary

### Optimization

- Parallel project and session listing when possible
- Lazy-load investigation details
- Stream large responses
- Compress request/response payloads where supported

## Security Considerations

1. **Credential Management**
   - Never log passwords or tokens
   - Store credentials in environment variables only
   - Clear sensitive data from memory after use

2. **Input Validation**
   - Validate all user inputs
   - Sanitize alert IDs and prompts
   - Prevent injection attacks

3. **Output Sanitization**
   - Strip potentially sensitive information from responses
   - Sanitize HTML in investigation results

## Testing Strategy

### Unit Tests

- Test each service independently
- Mock API responses
- Validate input/output schemas
- Test error handling paths

### Integration Tests

- Test against NeuBird staging/sandbox environment
- Validate end-to-end workflows
- Test streaming functionality
- Test timeout handling

### E2E Tests with Cursor

- Test natural language interactions
- Validate agent understanding of tool outputs
- Test multi-turn investigations
- Test error recovery

## Implementation Phases

### Phase 1: Core Infrastructure ✅ (COMPLETED)
- Authentication service
- Session manager
- Project manager
- Basic MCP tool scaffolding
- `neubird_list_projects`

### Phase 2: Investigation Tools ✅ (COMPLETED)
- `neubird_investigate_alert`
- `neubird_get_investigation_status`
- `neubird_continue_investigation`

### Phase 3: Session Management & Analytics ✅ (COMPLETED)
- `neubird_list_sessions` - List sessions with pagination, date filtering, and investigation status filtering
  - Supports filtering by investigation_status (e.g., not started, in progress, completed)
  - Supports filtering by session_type (e.g., incident vs manual)
  - Convenience parameter for uninvestigated incidents
  - Option to hide grouped incidents
- `neubird_inspect_session` - Get detailed session information
- `neubird_get_session_report` - Get session summaries and time-saved metrics
- `neubird_get_session_summary` - Get detailed analysis scores
- `neubird_get_incident_report` - Get organization-wide analytics

### Phase 4: Advanced Investigation Features (PLANNED)
- `neubird_create_investigation` - Custom investigations with timeframes
- Timeframe parser for natural language date inputs
- Enhanced prompt engineering for context-aware investigations

### Phase 5: Streaming & Real-time Updates (PLANNED)
- Streaming support for long-running investigations
- Real-time progress updates
- WebSocket or SSE support

### Phase 6: Optimization & Polish
- Caching strategies
- Error handling improvements
- Performance optimization
- Rate limiting and retry logic
- Comprehensive documentation and examples

## Documentation Requirements

### For Developers

1. **Setup Guide**: How to install and configure the MCP server
2. **Tool Reference**: Detailed documentation for each tool
3. **Examples**: Common use cases with example prompts
4. **Troubleshooting**: Common issues and solutions

### For AI Agents

1. **Tool Descriptions**: Clear, concise descriptions for each tool
2. **Example Interactions**: Sample prompts and expected responses
3. **Error Handling**: How to interpret and recover from errors
4. **Best Practices**: Optimal usage patterns

## Example Interactions

### Example 1: List Recent Sessions

**User to Cursor**:
```
Show me the recent investigations from the HTM-Azure project from the last week
```

**Cursor calls**:
```json
{
  "tool": "neubird_list_sessions",
  "arguments": {
    "project_uuid": "74acc801-3428-4292-8a74-ae16ecb71c24",
    "limit": 20,
    "date_from": "2024-01-14"
  }
}
```

### Example 1a: List Uninvestigated Incidents

**User to Cursor**:
```
Show me all the incidents that haven't been investigated yet in the HTM-Azure project
```

**Cursor calls**:
```json
{
  "tool": "neubird_list_sessions",
  "arguments": {
    "project_uuid": "74acc801-3428-4292-8a74-ae16ecb71c24",
    "only_uninvestigated": true,
    "limit": 50
  }
}
```

### Example 1b: Search for Specific Incidents

**User to Cursor**:
```
List all investigations into load avg issues
```

**Cursor calls**:
```json
{
  "tool": "neubird_list_sessions",
  "arguments": {
    "search_term": "load avg",
    "only_uninvestigated": true,
    "limit": 20
  }
}
```

**Notes**:
- The `search_term` performs case-insensitive partial matching on incident titles
- Works with both investigated and uninvestigated incidents
- Can be combined with other filters like date ranges, investigation status, etc.
- Example searches: "database", "timeout", "disk space", "API gateway", "high CPU"

**Alternative using explicit filters**:
```json
{
  "tool": "neubird_list_sessions",
  "arguments": {
    "project_uuid": "74acc801-3428-4292-8a74-ae16ecb71c24",
    "investigation_status": "INVESTIGATION_STATUS_NOT_STARTED",
    "session_type": "SESSION_TYPE_INCIDENT",
    "limit": 50
  }
}
```

### Example 2: Get Session Details

**User to Cursor**:
```
Can you show me the detailed analysis from session abc-123, including all the sources it used?
```

**Cursor calls**:
```json
{
  "tool": "neubird_inspect_session",
  "arguments": {
    "session_uuid": "abc-123",
    "project_uuid": "74acc801-3428-4292-8a74-ae16ecb71c24"
  }
}
```

### Example 3: Get Incident Analytics

**User to Cursor**:
```
Show me the overall incident statistics and how much time NeuBird has saved us
```

**Cursor calls**:
```json
{
  "tool": "neubird_get_incident_report",
  "arguments": {}
}
```

### Example 4: Get Session Report with Time Saved

**User to Cursor**:
```
Give me a summary report for these three investigations
```

**Cursor calls**:
```json
{
  "tool": "neubird_get_session_report",
  "arguments": {
    "session_uuids": ["session-1", "session-2", "session-3"],
    "project_uuid": "74acc801-3428-4292-8a74-ae16ecb71c24"
  }
}
```

### Example 5: Investigate an Alert

**User to Cursor**:
```
Can you investigate alert /subscriptions/cb3bc010-0fc7-476a-8577-03c3e45e2296/resourcegroups/test123/providers/microsoft.insights/components/test123-insights/providers/Microsoft.AlertsManagement/alerts/08f9c803-6bff-4030-bbe8-300a993af000?
```

**Cursor calls**:
```json
{
  "tool": "neubird_investigate_alert",
  "arguments": {
    "alert_id": "/subscriptions/cb3bc010-0fc7-476a-8577-03c3e45e2296/resourcegroups/test123/providers/microsoft.insights/components/test123-insights/providers/Microsoft.AlertsManagement/alerts/08f9c803-6bff-4030-bbe8-300a993af000",
    "wait_for_completion": true,
    "max_wait_seconds": 300
  }
}
```

### Example 6: Create Custom Investigation

**User to Cursor**:
```
Analyze my EKS cluster security for the last 2 hours
```

**Cursor calls**:
```json
{
  "tool": "neubird_create_investigation",
  "arguments": {
    "prompt": "Analyze my EKS cluster for security vulnerabilities and misconfigurations",
    "timeframe": "last 2 hours",
    "wait_for_completion": true
  }
}
```

### Example 7: Follow-up Investigation

**User to Cursor**:
```
Can you dig deeper into the network policy issues you found?
```

**Cursor calls**:
```json
{
  "tool": "neubird_continue_investigation",
  "arguments": {
    "session_uuid": "previous-session-uuid",
    "follow_up_prompt": "Please provide more details about the network policy issues, including specific configurations that need to be addressed",
    "wait_for_completion": true
  }
}
```

## Success Metrics

1. **Response Time**: < 500ms for non-investigation tools, < 5 minutes for investigations
2. **Success Rate**: > 95% successful API calls
3. **Developer Satisfaction**: Natural, intuitive interactions with minimal friction
4. **Cache Hit Rate**: > 80% for authentication tokens and project lists
5. **Error Recovery**: Clear, actionable error messages with recovery suggestions

## Future Enhancements

1. **Proactive Monitoring**: Subscribe to alerts and automatically trigger investigations
2. **Multi-Cloud Support**: Extend beyond current cloud providers
3. **Investigation Templates**: Pre-defined investigation templates for common scenarios
4. **Collaborative Investigations**: Share and collaborate on investigations
5. **Historical Analysis**: Trend analysis across multiple investigations
6. **Custom Integrations**: Webhooks, Slack notifications, etc.
7. **Advanced Filtering Enhancements**: Additional filtering capabilities such as:
   - Full-text search across session names and incident titles
   - Filter by priority (P1, P2, P3, P4)
   - Filter by incident type (FIREHYDRANT, PAGERDUTY, etc.)
   - Filter by time range with more granular controls
   - Saved filter presets
8. **Investigation Chaining**: Automatically trigger related investigations

---

## Questions for Clarification

Before implementation, please clarify:

1. **Organization UUID**: Is there a single organization UUID or should we support multiple? Should this be auto-detected?

2. **Project Selection**: Should the server:
   - Auto-detect the appropriate project based on alert content?
   - Always use a default project from config?
   - Ask the user to specify?

3. **Streaming Preference**: Should streaming be:
   - Default enabled for all investigations?
   - Optional based on investigation type?
   - User-configurable per request?

4. **Investigation Timeout**: What's a reasonable timeout for investigations?
   - 5 minutes?
   - 10 minutes?
   - Configurable based on investigation type?

5. **Pagination**: Should we support pagination for:
   - Project lists?
   - Session lists?
   - Investigation results?

6. **Alert ID Format**: Are there different alert ID formats we need to support beyond the Azure format shown?

7. **Additional Context**: Should investigations include:
   - Git commit information?
   - Recent deployments?
   - Related code changes?

8. **Cost Considerations**: Are there API rate limits or costs we should be aware of?
