# Screenshot Integration - Automatic Configuration

## Overview

The screenshot MCP integration now automatically extracts cluster metadata from the workspace context, eliminating the need for users to manually specify cluster configuration parameters.

## How It Works

### 1. Workspace Metadata Loading

When a chat session is created for a workspace, the backend automatically:

1. Reads `cluster_meta.json` from the workspace directory
2. Extracts cluster information:
   - `cluster_id` - TiDB cluster ID
   - `org_id` - Organization ID
   - `tidb_version` - TiDB version (e.g., "v8.5.x")
   - `alert_time` + `lookback_hours` → calculates `start_time` and `end_time`
3. Finds the session directory (format: `session_{cluster_id}_{date}_{time}`)
4. Sets `output_dir` to the session directory for screenshot storage

### 2. Configuration Injection

The backend dynamically updates `.opencode/opencode.json` to include environment variables:

```json
{
  "mcp": {
    "clinic-screenshot": {
      "environment": {
        "PYTHONPATH": "/Users/lingtaoli/test/aiops",
        "CLUSTER_ID": "10355969091959802668",
        "ORG_ID": "1372813089196966040",
        "TIDB_VERSION": "v8.5.4",
        "START_TIME": "2025-01-20T18:22:47",
        "END_TIME": "2025-01-20T20:22:47",
        "OUTPUT_DIR": "/path/to/workspace/session_10355969091959802668_20251204_125800"
      }
    }
  }
}
```

### 3. System Prompt Enhancement

The system prompt sent to OpenCode is enhanced with cluster context:

```
## Current Workspace Context

This workspace is analyzing the following TiDB cluster:
- Cluster ID: 10355969091959802668
- Organization ID: 1372813089196966040
- TiDB Version: v8.5.4
- Analysis Time Range: 2025-01-20T18:22:47 to 2025-01-20T20:22:47
- Session Directory: /path/to/session_10355969091959802668_20251204_125800

**IMPORTANT FOR SCREENSHOT MCP TOOL:**
When using the `diagnostic_screenshot` MCP tool:
- Do NOT ask users for cluster_id, org_id, version, start_time, end_time, or output_dir
- These parameters are automatically provided from the workspace context
- You only need to specify which panels/dashboards to screenshot
```

### 4. MCP Tool Auto-Configuration

The `diagnostic_screenshot` MCP tool now:
- Accepts environment variables as parameter defaults
- Only requires the `query` parameter from users
- Automatically reads cluster metadata from environment variables

## User Experience

### Before (Manual Configuration)

Users had to provide all parameters:

```
Capture screenshot of QPS panel with:
- cluster_id: 10602564149339879488
- org_id: 1372813089196966040
- version: v8.5.x
- start_time: 2025-12-04T12:58:00
- end_time: 2025-12-04T13:58:00
- output_dir: /path/to/session
```

### After (Automatic Configuration)

Users only need to specify what they want:

```
Capture screenshot of QPS panel
```

or

```
Show me TiKV CPU usage
```

## Implementation Details

### Backend Files Modified

1. **[main.py](backend/main.py)**:
   - Added `_load_cluster_metadata()` - Reads cluster_meta.json
   - Added `_update_opencode_config_with_metadata()` - Injects env vars into opencode.json
   - Modified `_build_system_prompt()` - Creates context-aware system prompt
   - Updated `ACPSession.__init__()` - Calls metadata loading and config update

### MCP Tool Files Modified

2. **[diagnostic_screenshot_tool.py](../../aiops/service/diagnostic/mcp/diagnostic_screenshot_tool.py)**:
   - Modified `get_tool_definition()` - Changed parameters to optional, updated description
   - Modified `handle()` - Reads from environment variables, validates parameters

## File Locations

### Workspace Structure

```
data/
└── ws-{workspace-id}/
    ├── cluster_meta.json          # Source of cluster configuration
    ├── .opencode/
    │   └── opencode.json          # Dynamically updated with env vars
    └── session_{cluster-id}_{date}_{time}/
        └── *.png                  # Screenshots saved here
```

### cluster_meta.json Format

```json
{
  "alert_type": "slow_query_alert",
  "cluster_id": "10355969091959802668",
  "org_id": "1372813089196966040",
  "alert_time": "2025-01-20T20:22:47",
  "tidb_version": "v8.5.4",
  "lookback_hours": 2
}
```

## Benefits

1. **User-Friendly**: Users don't need to know or provide cluster configuration
2. **Accurate**: Configuration is extracted from actual workspace metadata
3. **Consistent**: Screenshots are automatically saved to the correct session directory
4. **Maintainable**: Configuration logic is centralized in the backend

## Testing

To test the integration:

1. Start the frontend and backend:
   ```bash
   make web    # Terminal 1
   make api    # Terminal 2
   ```

2. Open a workspace that contains `cluster_meta.json`

3. Enable the "Grafana Screenshot" connector in the left sidebar

4. Send a simple message:
   ```
   Show me QPS panel
   ```

5. Verify that:
   - OpenCode calls the diagnostic_screenshot tool
   - Screenshots are saved to the session directory
   - Images are displayed inline in the chat
   - User didn't need to specify any cluster parameters

## Future Improvements

1. **Dynamic Session Detection**: Automatically detect the most recent or relevant session directory
2. **Multi-Session Support**: Allow users to specify which session to analyze
3. **Session Creation**: Automatically create a new session directory if none exists
4. **Metadata Validation**: Add validation and error messages for missing or invalid cluster metadata
