# MediaCAT MCP Server

A Model Context Protocol (MCP) server for MediaCAT's subtitle generation workflow with XL8.ai integration. Supports local file processing, real-time SSE updates, and dynamic language detection.

## Features

- **Unified Workflow**: Single `run_sync` function consolidates entire subtitle generation process
- **Local File Optimization**: Direct file path support for local servers (avoids base64 encoding)
- **Real-time Progress**: Server-Sent Events (SSE) for live progress updates
- **Dynamic Language Support**: Automatically fetches supported languages from XL8.ai API
- **Flexible Deployment**: Works as CLI tool, Docker container, or cloud service
- **Optional Server API Key**: Configure once on server to simplify client requests

## Installation

```bash
npm install mediacat-mcp
```

## Usage

### As a CLI Tool

```bash
# Start the server
mediacat-mcp

# With environment variables
XL8_API_KEY=your_api_key mediacat-mcp
```

### As a Module

```javascript
import { MediaCatMCPServer } from 'mediacat-mcp';

const server = new MediaCatMCPServer();
await server.start();
```

## API Reference

### MCP Tool: `run_sync`

Generates subtitles for video files using XL8.ai.

**Parameters:**
- `fileData` (string, optional): Base64 encoded file data (for remote servers)
- `filePath` (string, optional): Local file path (for local servers - more efficient)
- `filename` (string, required): Name of the video file
- `mimeType` (string, required): MIME type (e.g., 'video/mp4')
- `language` (string, required): Target language code (e.g., 'en-US', 'ko-KR')
- `format` (string, required): Output format ('srt', 'vtt', 'ttml', 'json', 'xl8.json')
- `apiKey` (string, optional): XL8.ai API key (if not configured on server)
- `transcriptS3Key` (string, optional): S3 key of transcript file for reference

**Note:** Provide exactly one of `fileData` OR `filePath`.

**Returns:**
```json
{
  "success": true,
  "requestId": "xl8_request_id",
  "message": "Sync request initiated",
  "tracking": {
    "sseChannel": "/events/xl8_request_id",
    "events": ["sync_progress", "sync_completed", "sync_failed"]
  }
}
```

### SSE Events

Connect to `/events/{requestId}` to receive real-time updates:

- `{requestId}_sync_progress`: Processing progress updates
- `{requestId}_sync_completed`: Subtitle generation completed with content
- `{requestId}_sync_failed`: Error occurred during processing

### HTTP API Endpoints

- `POST /mcp` - MCP JSON-RPC endpoint
- `POST /api/run-sync` - Direct HTTP API for run_sync
- `GET /api/sync-status/:requestId` - Get sync status
- `GET /api/info` - Server info and capabilities
- `GET /health` - Health check
- `GET /events/:requestId` - SSE endpoint for progress updates

## Environment Variables

- `XL8_API_KEY` - XL8.ai API key (optional, enables keyless client requests)
- `PORT` - Server port (default: 3000)
- `DOCKER_ENV` - Set to disable MCP stdio transport in containers

## Examples

### MCP Client

```javascript
// Connect to MCP server
const response = await fetch('http://localhost:3000/mcp', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    jsonrpc: '2.0',
    id: 1,
    method: 'tools/call',
    params: {
      name: 'run_sync',
      arguments: {
        filePath: './video.mp4',  // Local file (efficient)
        filename: 'video.mp4',
        mimeType: 'video/mp4',
        language: 'en-US',
        format: 'srt'
      }
    }
  })
});

const result = await response.json();
const requestId = JSON.parse(result.result.content[0].text).requestId;

// Connect to SSE for progress updates
const eventSource = new EventSource(`http://localhost:3000/events/${requestId}`);
eventSource.addEventListener(`${requestId}_sync_completed`, (event) => {
  const data = JSON.parse(event.data);
  console.log('Subtitles:', data.data.content);
});
```

### HTTP API

```javascript
// For remote servers using base64 upload
const videoBuffer = fs.readFileSync('video.mp4');
const response = await fetch('http://localhost:3000/api/run-sync', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/octet-stream',
    'X-Filename': 'video.mp4',
    'X-Language': 'en-US',
    'X-Format': 'srt',
    'X-Api-Key': 'your_api_key'
  },
  body: videoBuffer
});
```

## Supported Languages

The server automatically fetches supported languages from XL8.ai API. Common languages include:
- en-US, en-GB (English)
- ko-KR (Korean)
- ja-JP (Japanese)
- es-ES, es-US (Spanish)
- fr-FR (French)
- de-DE (German)
- zh, zh-TW (Chinese)
- And many more...

## License

MIT
