Skip to main content
Glama
README.md
# ClipChat Engine

**Open-source video editing backend.** Natural language → FFmpeg operations via REST API and MCP server.

![Node 20](https://img.shields.io/badge/node-20%2B-brightgreen) ![TypeScript](https://img.shields.io/badge/TypeScript-5-blue) ![License](https://img.shields.io/badge/license-MIT-green)

---

## What is it?

ClipChat Engine is a self-hostable backend that exposes 20 FFmpeg operations as:

- **REST API** — async job queue (BullMQ) with SSE progress streaming
- **MCP Server** — Model Context Protocol server for AI agent integration (Claude, etc.)

It handles the FFmpeg heavy-lifting so you can focus on building interfaces — chat UIs, editors, automations, or AI agents that edit video through natural language.

---

## Features

| Feature | Detail |
|---------|--------|
| 20 FFmpeg tools | trim, merge, resize, crop, rotate/flip, color adjust, compress, thumbnail, normalize audio, fade audio, watermark, GIF, blur region, and more |
| Async job queue | BullMQ + Redis; jobs survive server restarts; 3 retries with exponential backoff |
| SSE streaming | Real-time progress updates via Server-Sent Events |
| AI chat | OpenRouter streaming with tool calling; `/chat` endpoint → NL → FFmpeg jobs |
| Session history | Chat sessions and messages persisted to PostgreSQL |
| MCP server | All 20 tools accessible to AI agents via stdio |
| Local + S3 storage | Pluggable storage adapter; DB-backed path lookup survives restarts |
| API key auth | SHA-256 hashed keys in PostgreSQL |
| Web UI | Self-hosted Next.js UI on :3001 — chat, video player, edit timeline |
| TypeScript + Zod | End-to-end type safety with schema validation |

---

## Quick Start (Docker)

```bash
git clone https://github.com/your-org/clipchat.git
cd clipchat
cp .env.example .env
```

Generate an API key for the web UI (required before starting):
```bash
# Start infra only to run the key generator
docker compose up -d postgres redis
npm install
npm run db:migrate -w packages/engine
npm run create-api-key -w packages/engine -- "prod"
# → clp_a1b2c3d4...  (copy this)
```

Start the full stack:
```bash
ENGINE_API_KEY=clp_a1b2c3d4... docker compose up -d
```

Set `OPENROUTER_API_KEY` in `.env` if you want AI chat (`/api/v1/chat`).

| Service | URL |
|---------|-----|
| Engine API | http://localhost:3000 |
| Web UI | http://localhost:3001 |

```bash
# Verify engine
curl http://localhost:3000/health
# {"status":"ok","version":"0.1.0"}
```

> Full local dev setup (without Docker): [Getting Started →](docs/getting-started.md)

---

## Architecture

```
HTTP Client / AI Agent / Web UI (:3001)
        │
        ▼
  Express API (:3000)
  ├── POST /api/v1/files/upload       → LocalStorage / S3
  ├── GET  /api/v1/files               → list files (paginated)
  ├── GET  /api/v1/files/:id/content  → stream raw bytes (range requests)
  ├── POST /api/v1/jobs               → BullMQ Queue (Redis)
  ├── GET  /api/v1/jobs/:id           → PostgreSQL (status poll)
  ├── GET  /api/v1/jobs/:id/stream    → SSE via BullMQ events (Redis pub/sub)
  ├── GET  /api/v1/tools              → tool manifest
  ├── POST /api/v1/chat               → OpenRouter streaming + tool calls → SSE
  ├── GET  /api/v1/sessions           → session list
  └── GET  /api/v1/sessions/:id/messages → chat history
        │
        ▼
  BullMQ Worker
  └── Dispatches to ffmpeg/*.ts
        │
        ▼
  FFmpeg (subprocess)
        │
        ▼
  Result stored in PostgreSQL

  ─────────────────────────────
  MCP Server (stdio, --mcp flag)
  └── 20 tools → FFmpeg direct (synchronous)

  ─────────────────────────────
  Web UI (packages/web, :3001)
  └── Next.js proxy → engine API (Bearer token injected server-side)
```

**Job flow:** `POST /jobs` → BullMQ queue → worker → FFmpeg → DB update → client polls `GET /jobs/:id` or streams via SSE.

**Chat flow:** `POST /chat { message, file_id? }` → first LLM call streams tool calls → jobs submitted to BullMQ → polls DB until complete (max 60s) → second LLM call synthesizes results → SSE events (`text`, `tool_call`, `done`). All turns persisted to `sessions`/`chat_messages`.

**MCP flow:** AI agent calls tool → FFmpeg runs synchronously → result returned immediately.

---

## API Overview

| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/health` | Health check |
| `POST` | `/api/v1/files/upload` | Upload a video/audio file (video/audio only) |
| `GET` | `/api/v1/files` | List uploaded files (`?limit`, `?offset`) |
| `GET` | `/api/v1/files/:id` | Get file metadata |
| `GET` | `/api/v1/files/:id/content` | Stream file bytes (supports Range requests) |
| `DELETE` | `/api/v1/files/:id` | Delete a file |
| `POST` | `/api/v1/jobs` | Submit an async job |
| `GET` | `/api/v1/jobs/:id` | Poll job status |
| `GET` | `/api/v1/jobs/:id/stream` | SSE job progress stream |
| `DELETE` | `/api/v1/jobs/:id` | Cancel a job |
| `GET` | `/api/v1/tools` | List available tools |
| `POST` | `/api/v1/tools/:name` | Direct tool invocation (async) |
| `POST` | `/api/v1/chat` | AI chat with tool calling → SSE stream |
| `GET` | `/api/v1/sessions` | List chat sessions (`?limit`, `?offset`) |
| `GET` | `/api/v1/sessions/:id/messages` | Fetch session message history |

All `/api/v1/*` endpoints require `Authorization: Bearer <api-key>` header (except `GET /health`).

Full endpoint docs: [API Reference →](docs/api-reference.md)

---

## FFmpeg Tools

| Tool | Description |
|------|-------------|
| `get_video_info` | Extract duration, resolution, codec, bitrate |
| `trim_video` | Cut a clip between two timestamps |
| `merge_clips` | Concatenate clips (with optional crossfade) |
| `resize_video` | Resize by dimensions or preset (720p, 1080p, 4k, square, 9:16) |
| `extract_audio` | Extract audio track as mp3/aac/wav |
| `replace_audio` | Swap or mix audio tracks |
| `add_text_overlay` | Burn text with custom font/size/color/position |
| `add_subtitles` | Burn SRT subtitles (or add as soft track) |
| `change_speed` | Speed up or slow down (0.25×–4×) |
| `export_video` | Re-encode to mp4/webm/mov/gif with quality control |
| `crop_video` | Crop to a region or preset (square_center, portrait_center, landscape_center) |
| `rotate_flip` | Rotate 90/180/270° or flip horizontally/vertically |
| `color_adjust` | Adjust brightness, contrast, saturation, gamma, hue |
| `compress_video` | Reduce file size with presets (web, mobile, whatsapp, telegram, archive) |
| `generate_thumbnail` | Extract a frame as JPG/PNG/WebP at any timestamp |
| `normalize_audio` | Loudness normalisation to target LUFS (default –14 for streaming) |
| `fade_audio` | Add audio fade-in and/or fade-out |
| `add_watermark` | Overlay a logo/image with opacity, scale, and position control |
| `create_gif` | Create animated GIF from a segment (two-pass, palette-optimised) |
| `blur_region` | Blur a rectangle (preset or manual coords) with optional time range |

Full tool docs with schemas and examples: [Tools Reference →](docs/tools-reference.md)

---

## MCP Integration

Connect ClipChat to Claude or any MCP-compatible AI:

```bash
# Build first
npm run build -w packages/engine

# Start as MCP server
node packages/engine/dist/index.js --mcp
```

Claude Desktop config:
```json
{
  "mcpServers": {
    "clipchat": {
      "command": "node",
      "args": ["/absolute/path/to/clipchat/packages/engine/dist/index.js", "--mcp"],
      "env": { "DATABASE_URL": "...", "REDIS_URL": "..." }
    }
  }
}
```

[MCP Integration Guide →](docs/mcp-integration.md)

---

## Tech Stack

- **Runtime:** Node.js 20, TypeScript 5
- **API:** Express 4, Multer (file uploads), CORS
- **Queue:** BullMQ 5 + Redis 7
- **Database:** PostgreSQL 16 + Drizzle ORM
- **FFmpeg:** fluent-ffmpeg wrapper
- **Validation:** Zod
- **MCP:** @modelcontextprotocol/sdk
- **Storage:** Local FS or AWS S3 / S3-compatible (MinIO)
- **Testing:** Vitest 1.6 + Supertest

---

## Roadmap

| Phase | Status | Description |
|-------|--------|-------------|
| Phase 1 | ✅ Complete | Open-source backend — REST API + MCP server |
| Phase 2 | ✅ Complete | AI/Claude chat layer — `/chat` endpoint, NL → tool calls, session history |
| Phase 3 | ✅ Complete | Self-hosted web UI — Next.js, video player, edit timeline, chat interface |

---

## Documentation

- [Getting Started](docs/getting-started.md) — local dev setup, running tests
- [API Reference](docs/api-reference.md) — all endpoints with schemas and examples
- [Tools Reference](docs/tools-reference.md) — all 20 FFmpeg tools documented
- [MCP Integration](docs/mcp-integration.md) — AI agent setup (Claude Desktop, Claude Code)
- [Deployment](docs/deployment.md) — Docker Compose, S3, production hardening
- [Contributing](CONTRIBUTING.md) — development workflow, adding new tools

---

## License

MIT