Skip to main content
Glama
README.md
# Media MCP

A local MCP server that lets Claude Code, Codex, OpenCode or any MCP client analyse
local video and audio through OpenRouter, without the client needing video input of its own.
The default model is `google/gemini-4-hydrogen` on the Google AI Studio flex tier.

Useful for reviewing rendered videos, investigating recorded bugs, describing
music, checking narration, and asking focused questions about a particular clip.
The server works with MCP clients that support Streamable HTTP.

## Tools

`inspect_media(path, checks?, time_range?, thresholds?)` reads duration, codecs,
stream timing, audio channels/sample rate, dimensions and frame rate locally.
Optional checks measure silence, black/frozen frames, loudness and audio peaks.
It uploads nothing and does not need a key. Omit checks for quick metadata only.

`estimate_media(path, time_range?, include_audio?)` plans an analysis without any API call:
frames, sheets, token and cost estimates (typical and maximum) and spend against the caps.

`analyze_media(path, question?, time_range?, include_audio?, reasoning?)`:

```json
{
  "path": "/home/example/projects/demo/recording.mp4",
  "question": ["What happens immediately before the interface freezes?", "Is there an error dialog?"],
  "time_range": {"start_seconds": 120, "end_seconds": 165},
  "include_audio": true,
  "reasoning": "low"
}
```

- `question` is one question or a list. Put every question about a clip in **one call**.
  Omit it for a chronological summary.
- `time_range` selects the interval of the original file; only that interval is extracted.
- `include_audio` (default true) sends the audio track as MP3. Set false for silent clips.
- `reasoning` is `low` (default) or `high`. Use `high` only after a low answer fails a check
  you can run. There is no fps or quality setting.

### How video is analysed

Video does not go to the model as a video file. The server samples it at **16 frames per
second**, tiles the frames into **contact sheets of 128 frames** (16 x 8 cells, each fitting
a 240 px box), and sends the sheets as images, with the audio as a separate MP3. In
tests this caught 0.2-second events and cuts that the provider's native video path (1 fps)
missed, and it gives exact visual timing: the model cites frame indices like `[f123]` and the
server rewrites them to `[f123 = 12.34s]` in original-file seconds. A sheet costs about
1,200 input tokens regardless of size, so a minute of video is about 8 sheets.

**Audio times are approximate**: they can be off by about a second, so audio-visual
alignment finer than that is not reliable. For exact times of silences or loud events, use
`inspect_media` checks (`silence`, `audio_peaks`), which are measured locally. See `experiments/README.md` for the measurements
behind these choices and `docs/plan.md` for the design.

Long ranges are split into several requests (each under `MEDIA_MAX_REQUEST_MB` of images).
If a later request fails, earlier results are returned with `coverage_complete: false`.
A call is limited to `MEDIA_MAX_SHEETS` sheets (24, about 3 minutes of video); select a
`time_range` for longer files. Audio-only files are sent as audio in segments of up to 10
minutes.

Every response includes token usage and cost, and the running spend against
`MEDIA_SPEND_CAP_SESSION_USD` and `MEDIA_SPEND_CAP_DAY_USD`. A call that would exceed a cap
is refused before anything is uploaded.

## Local measurements with inspect_media

```json
{
  "path": "/home/example/projects/demo/render.mp4",
  "checks": ["silence", "black_frames", "loudness", "audio_peaks", "freeze_frames"],
  "time_range": {"start_seconds": 120, "end_seconds": 165},
  "thresholds": {
    "silence_dbfs": -40,
    "min_silence_seconds": 0.5,
    "peak_dbfs": -1,
    "min_freeze_seconds": 2
  }
}
```

All parameters except `path` are optional. Omit `time_range` to scan the whole
file. Measurements use the original decoded video/audio, with **no resolution or
FPS cap**, no uploaded clips, no OpenRouter requests and no API key requirement.

| Check | Result | Default threshold |
| --- | --- | --- |
| `silence` | Quiet intervals across all audio channels | -40 dBFS, at least 0.5 seconds |
| `black_frames` | Dark intervals meeting the configured pixel ratio | At least 98% black pixels, 0.1 pixel threshold, at least 0.5 seconds |
| `freeze_frames` | Intervals with little frame-to-frame change | -60 dB difference tolerance, at least 2 seconds |
| `audio_peaks` | Sample peak and merged threshold-crossing windows | -1 dBFS threshold, 0.1-second windows |
| `loudness` | EBU R128 integrated LUFS, loudness range and true peak | Measures the selected audio; no target normalization |

Use `thresholds` to override defaults. Additional fields are `min_black_seconds`,
`black_pixel_threshold`, `black_frame_ratio`, `peak_window_seconds` and
`freeze_noise_db`. Thresholds and intervals are returned with the measurements.

Interval timestamps refer to original-file playback, with time zero at the input's
playback start rather than an embedded recording timecode. Ranged scans retain
that timeline. An `ends_at_scan_boundary` flag means an event was still ongoing
at the scan/stream end and may continue outside the selected range. Video timing
has frame precision; EOF boundaries can be estimated when stream duration is
unknown (`boundary_end_estimated`). Audio peak intervals locate windows containing
high samples, rather than exact individual sample timestamps. Container timestamp
precision is respected when grouping adjacent windows.

Each requested measurement has a `status` of `complete`, `unavailable` or `error`.
Absent streams and ranges with no usable stream data are unavailable, not zero
measurements. A failed check is explicit and other completed results remain.
`inspection_complete` is false on scan errors. An overall scan timeout returns an
error and terminates FFmpeg. Metadata-only inspection can run while a scan or
OpenRouter analysis is in progress; heavy operations run one at a time.

Silence, dark scenes and static frames can be intentional. High sample peaks
alone **do not prove clipping**. Short/very quiet audio can have no gated LUFS
measurement; these values are null with an explicit availability flag. Audio and
video end-time differences in `stream_timing` are metadata measurements, not
lip-sync detection. The first primary audio/video streams are scanned.

Output retains at most 100 intervals per check by default. `total_intervals`,
`total_duration_seconds` and `intervals_truncated` report the full scan even when
the returned interval list is bounded. Select a narrower range to examine more
detail. Tune `MEDIA_INSPECT_MAX_INTERVALS` or `MEDIA_INSPECT_TIMEOUT_SECONDS`
(default 900 seconds) in the server environment when needed.

## Start with Docker

You need Linux (including WSL2), Docker with Compose, an MCP client such as Claude Code, Codex or OpenCode,
and an OpenRouter API key. Only the server needs the key; inspection is free of
provider requests, and analysis uses your OpenRouter credit.

Clone the repository and run from its directory:

```bash
git clone https://github.com/riqvip/media-mcp.git
cd media-mcp
cp .env.example .env       # Only for a new setup; preserve an existing .env.
chmod 600 .env
```

Set `OPENROUTER_API_KEY` in `.env`. The other settings are optional; see `.env.example`.

- `OPENROUTER_MODEL` defaults to `google/gemini-4-hydrogen`. The model must accept images
  and, for audio, audio input. There is no automatic model fallback.
- `OPENROUTER_PROVIDER` defaults to `google-ai-studio/flex` and `OPENROUTER_SERVICE_TIER`
  to `flex`, about half the standard price. The provider is pinned with OpenRouter fallbacks
  disabled. If flex is out of capacity (HTTP 429, 502, 503 or 504), the server retries once on
  the standard tier of the same provider, so the call still goes through at standard prices.
  Responses report `fell_back_to_standard` and the tier used per request. Set
  `MEDIA_FLEX_FALLBACK=0` to return flex capacity errors instead. Set the provider or tier to an
  empty value to disable the pin, for example when using another model, and update
  `MEDIA_PRICE_INPUT_PER_MILLION` and `MEDIA_PRICE_OUTPUT_PER_MILLION`, which are only used
  for estimates.
- `MEDIA_MAX_OUTPUT_TOKENS` defaults to 30000, because reasoning uses most of the output.

Model, provider and OpenRouter request ID are reported with each analysis, along with
`reasoning_tokens` when the provider supplies them. Reasoning text is not returned.
Recreate the container after changing environment settings:
`docker compose up -d --force-recreate --wait`.

```bash
docker compose up -d --build
docker compose ps
```

The endpoint is `http://127.0.0.1:8766/mcp`. The host port is configurable with
`MEDIA_MCP_PORT`; the container always listens on 8765. The health endpoint is
`/health` and checks server availability, not the API key or provider.

The container reads the Linux filesystem through the read-only `/:/host` mount.
Pass **original absolute Linux paths**, not `/host/...` paths. Absolute and relative
symlinks are resolved in the host filesystem namespace. There is no directory
allowlist or AGENTS.md path policy in this server. Codex must follow the user's
filesystem instructions when choosing paths. Standard Linux permissions still
apply: the container runs as UID/GID 1000 by default. Set `MEDIA_UID`/`MEDIA_GID`
in `.env` if the WSL user has different IDs. Symlinks into unavailable mount
namespaces cannot make inaccessible files readable.

The root mount is intentionally broad; the tool is limited to processing regular,
self-contained media files. It does not accept URLs or playlists, execute media
instructions, or modify source files. The OpenRouter key stays in server
configuration. Temporary clips are removed after success, failure or cancellation.

## Connect Codex

The following registers this endpoint and sets a 960-second tool timeout and
larger output budgets for both tools while preserving unrelated configuration:

```bash
python3 scripts/register_codex.py
```

The helper requires Python 3.11+ and the `codex` command. It uses your current
`CODEX_HOME`, or `~/.codex` by default. To connect additional profiles, pass their
Codex home directories explicitly. For example, if you have a `codexpro` wrapper
using `~/.codex-pro`:

```bash
python3 scripts/register_codex.py --home ~/.codex --home ~/.codex-pro
```

For a different host port, pass `--port` with the same value as `MEDIA_MCP_PORT`.
Other MCP clients can connect directly to the HTTP endpoint.

Alternatively, register manually and add `tool_timeout_sec = 960` to the
`[mcp_servers.media]` table:

```bash
codex mcp add media --url http://127.0.0.1:8766/mcp
```

Start a **new Codex session** and run `/mcp` to check the connection. Then ask:

> Analyze this video: `/absolute/path/demo.mp4`. Focus on 120–165 seconds and
> explain the visible error.

The server exposes these tools to MCP clients; running this server does not
retroactively add tools to an already-running Codex session.

## WSL startup

Once this Compose project is created, `restart: unless-stopped` starts its
container when the Linux Docker daemon starts. If Docker is not already enabled:

```bash
sudo systemctl enable --now docker.service
```

WSL must run systemd for this service setup. Check with `ps -p 1 -o comm=`.
If it does not, enable systemd in `/etc/wsl.conf` following the linked Microsoft
instructions and restart the distribution. This starts the service when WSL
starts; it does not start WSL when Windows boots. Deliberately stopping the
container keeps it stopped until `docker compose up -d` starts it again.

## Connect other clients

Any client that supports Streamable HTTP can use `http://127.0.0.1:8766/mcp`:

```bash
claude mcp add --transport http media http://127.0.0.1:8766/mcp
```

For OpenCode, add a remote server to `opencode.json`:

```json
{ "mcp": { "media": { "type": "remote", "url": "http://127.0.0.1:8766/mcp" } } }
```

Set the client's tool timeout to at least the call timeout (900 seconds by default) if it
has a shorter one.

## Limits and media quality

Defaults: at most 24 sheets per call (about 3 minutes of video), each request under 6 MiB of
images, 8 GiB source files, 30,000 output tokens per request, 600 seconds per provider request
and 900 seconds per analysis call. Responses keep every request's analysis in
chronological order rather than compressing them into another short summary. No cache
retains source media; temporary frames and audio are removed after success, failure or
cancellation.

Use `inspect_media` first and select ranges for long files. A range that needs more sheets
than the limit fails before any upload, as does a call whose estimated cost would exceed a
spend cap. A later provider failure returns earlier results with `coverage_complete: false`.
`output_truncated` and `analysis_complete` report provider token limits.

Frames are scaled to fit a 240 px box. That reads small on-screen text in tests but loses
finer detail, and `analyze_media` has no option to raise it. Audio is sent as 16 kHz mono
MP3, which can lose alternate audio tracks and spatial detail; only the first audio stream is
used. Fast, sub-second events are caught at the 16 fps sampling rate, but shorter events can
still fall between samples, and a confident model description is not a frame measurement.
Audio times can be off by about a second.
The tools currently accept local file paths. YouTube URL support requires a
separate input path and compatible provider routing; a model switch alone does
not enable URLs in these tools.

After changing `.env`, recreate this project so the container receives changes:

```bash
docker compose up -d --force-recreate
```

## Development and verification

Use Python 3.11+ and `uv`. Local execution also needs `ffmpeg` and `ffprobe`:

```bash
uv sync --dev
uv run ruff check src tests scripts
uv run pytest -q
uv run python -m media_mcp.server
```

For local execution load the key through the process environment. `MEDIA_HOST_FS_ROOT`
defaults to `/` outside Docker. `.env` is loaded by Compose, not automatically by
the Python module. To run with the same local `.env` configuration using `uv`:

```bash
uv run --env-file .env python -m media_mcp.server
```

The Docker test stage runs the full suite with real FFmpeg and mocked OpenRouter:

```bash
docker build --target test -t media-mcp-test .
```

Tests verify that each sheet cell holds the source frame at its 16 fps timestamp, sheet
and audio payloads, frame-index conversion, request splitting, partial coverage, spend
caps, timeout cleanup, credential redaction,
symlink mapping, local measurement intervals and an official MCP SDK client
handshake. Measurement fixtures contain known silence, dark frames, static scenes,
peak bursts and mismatched stream lengths. Host tests skip the
FFmpeg integration cases when FFmpeg is absent.

Test the running Docker endpoint without making paid API calls:

```bash
uv run python scripts/smoke_test.py --path /absolute/path/demo.mp4
```

Exercise local checks through the deployed MCP endpoint, without API requests:

```bash
uv run python scripts/smoke_test.py --path /absolute/path/demo.mp4 \
  --checks silence black_frames loudness audio_peaks freeze_frames \
  --start 120 --end 165 --thresholds '{"min_silence_seconds": 0.25}'
```

To test the complete delivery path with a real paid model call:

```bash
uv run python scripts/smoke_test.py --path /absolute/path/demo.mp4 \
  --analyze --start 120 --end 165 --question 'What happens before the error?'
```

## References

- [Codex MCP configuration](https://learn.chatgpt.com/docs/extend/mcp?surface=cli)
- [Official MCP Python SDK, pinned v1 maintenance line](https://py.sdk.modelcontextprotocol.io/v1/)
- [OpenRouter video input](https://openrouter.ai/docs/guides/overview/multimodal/videos)
- [OpenRouter audio input](https://openrouter.ai/docs/guides/overview/multimodal/audio)
- [Qwen3.8 Omni Flash](https://openrouter.ai/qwen/qwen3.8-omni-flash)
- [Gemini 3.5 Flash Lite](https://openrouter.ai/google/gemini-3.5-flash-lite)
- [FFmpeg measurement filters](https://ffmpeg.org/ffmpeg-filters.html)
- [Docker restart policies](https://docs.docker.com/engine/containers/start-containers-automatically/)
- [WSL systemd](https://learn.microsoft.com/en-us/windows/wsl/systemd)

## License

MIT. See [LICENSE](LICENSE).