Skip to main content
Glama
README.md
<!-- mcp-name: io.github.Songjag/vidsight -->

<div align="center">

# Vidsight

### Multimodal YouTube analysis for AI agents

Read the spoken content. Inspect sampled frames. Keep the original timestamps.

[![Python](https://img.shields.io/badge/Python-3.11%2B-3776AB?logo=python&logoColor=white)](https://www.python.org/)
[![MCP Compatible](https://img.shields.io/badge/MCP-Compatible-7CB342?logo=anthropic&logoColor=white)](https://modelcontextprotocol.io/)
[![Powered by yt-dlp](https://img.shields.io/badge/Powered%20by-yt--dlp-111111?logo=youtube&logoColor=white)](https://github.com/yt-dlp/yt-dlp)
[![Providers](https://img.shields.io/badge/AI%20providers-pluggable-00A67E)](#providers)
[![Stars](https://img.shields.io/github/stars/Songjag/Vidsight-YouTube-Analysis-Skill?style=flat&label=stars)](https://github.com/Songjag/Vidsight-YouTube-Analysis-Skill/stargazers)
[![Watchers](https://img.shields.io/github/watchers/Songjag/Vidsight-YouTube-Analysis-Skill?style=flat&label=watchers)](https://github.com/Songjag/Vidsight-YouTube-Analysis-Skill/watchers)
[![Tests](https://img.shields.io/badge/tests-197%20passing-2EA44F)](#testing)

**Vidsight** is a Python toolkit and MCP server for evidence-grounded YouTube
video analysis. It combines timestamped subtitles or STT with sampled frames,
then sends one normalized request to the provider selected from configuration.

[Quick start](#quick-start) ·
[MCP tools](#mcp-server) ·
[Providers](#providers) ·
[Architecture](docs/architecture.md) ·
[Documentation](#documentation) ·
[Contributing](CONTRIBUTING.md)

</div>

> **Scope note:** Vidsight analyzes sampled evidence. It does not claim
> continuous viewing when only selected frames are submitted to a model.

## Version 0.2.0 verification

**197 offline tests**, including real subprocess MCP/timeout tests. With AI
disabled, a real 19-second video took **9.537 s on cache miss → 0.003 s on hit**;
a 43-minute lecture removed **42 duplicate frames from 240 candidates**.
These measure media/cache behavior, not successful AI inference.

The current gateway smoke returned HTTP 400. Cloud-native, local-server and
GGUF inference remain **NOT TESTED**. See the dated
[verification report](docs/verification-0.2.md) for commands and limitations.

[docs/en.md](docs/en.md) is the canonical guide. This overview and translations
may lag behind the English guide.

Released: [GitHub v0.2.0](https://github.com/Songjag/Vidsight-YouTube-Analysis-Skill/releases/tag/v0.2.0),
the public container below, and the
[official MCP Registry entry](https://registry.modelcontextprotocol.io/v0.1/servers/io.github.Songjag%2Fvidsight/versions/0.2.0).
PyPI publication is pending Trusted Publisher setup; use the release artifacts,
source checkout or container in the meantime.

## Why Vidsight?

Transcript-only systems miss what is visible on screen: code, diagrams,
terminal output, UI changes, charts, and demonstrations. Sending every video
frame is expensive and noisy. Vidsight keeps the two evidence streams separate,
preserves their timestamps, applies a request budget, and reports what was
actually used.

| Capability | Behavior |
|---|---|
| Speech evidence | YouTube subtitles first, then configured STT backends |
| Visual evidence | OpenCV frame sampling with JPEG MIME and source timestamps |
| AI selection | Explicit provider or one-time `auto` selection |
| Output | Timeline, frame timestamps, analysis, warnings, and evidence source |
| Agent integration | MCP server over stdio with three typed tools |
| Privacy | Sanitized errors and logs; no API keys or raw provider bodies |

## Powered by yt-dlp

Vidsight uses [`yt-dlp`](https://github.com/yt-dlp/yt-dlp) as its YouTube
ingestion layer. This gives the pipeline a reliable way to:

- validate and normalize supported single-video YouTube URLs;
- retrieve video metadata and duration before downloading;
- select a bounded media format, preferring video up to 480p;
- prevent playlist expansion with `noplaylist`;
- retry transient download and fragment failures;
- enforce a 500 MB file limit and a maximum 3600-second duration;
- provide the downloaded media to OpenCV for timestamped frame sampling and
  `ffmpeg` for audio extraction.

`yt-dlp` handles media acquisition; it does not watch or interpret the video.
Vidsight still reports whether the final result came from subtitles, STT,
sampled frames, or a combination of those evidence sources. Availability can
depend on YouTube restrictions, network conditions, video privacy settings,
and the installed `yt-dlp` version.

## Quick start

### 1. Clone the repository

```sh
git clone https://github.com/Songjag/Vidsight-YouTube-Analysis-Skill.git
cd Vidsight-YouTube-Analysis-Skill
```

### 2. Install

Requirements: **Python 3.11+**, [`ffmpeg`](https://ffmpeg.org/) in `PATH`, and
[`uv`](https://docs.astral.sh/uv/) recommended.

```sh
uv sync
```

### 3. Configure

```sh
cp .env.example .env
```

Then set a provider and a verified model in `.env`:

```dotenv
LLM_PROVIDER=gemini
GEMINI_API_KEY=<private-key>
LLM_MODEL=<verified-model>
LLM_ALLOW_CLOUD=true

# Enable only after verifying that this model supports images.
LLM_SUPPORTS_IMAGES=true
```

Never commit `.env` or paste an API key into an issue or chat.

### 4. Validate and analyze

```sh
# Offline configuration check
uv run vidsight --env-file .env doctor

# Analyze a bounded range
uv run vidsight --env-file .env analyze \
  'https://www.youtube.com/watch?v=VIDEO_ID' \
  --question 'What is the main topic?' \
  --start 0 --end 60
```

Require visual evidence explicitly:

```sh
uv run vidsight --env-file .env analyze \
  'https://www.youtube.com/watch?v=VIDEO_ID' \
  --question 'What action is visible on screen?' \
  --start 0 --end 60 \
  --require-vision
```

`doctor` is intentionally offline. `network_checked=false` and
`model_inference_tested=false` do not mean the configured endpoint is reachable.

## MCP server

Start the stdio server with an absolute `.env` path:

```sh
uv run vidsight --env-file yourpath/Vidsight/.env serve
```

The server reserves stdout for JSON-RPC. Restart it after changing `.env`; do
not pass API keys in tool arguments.

### Official tools

| Tool | Purpose | Parameters |
|---|---|---|
| `watch_video_overview` | Analyze a full video or return its raw timeline | `url` |
| `analyze_video_segment` | Analyze a bounded time range | `url`, `start`, `end`, `question`, `require_vision` |
| `ask_video_question` | Ask a question across the video | `url`, `question`, `require_vision` |

Successful results expose:

```text
video_id
start / end / duration
source
timeline
frame_timestamps
submitted_frame_timestamps
analysis
warnings
diagnostics
```

`frame_timestamps` are extracted frames. `submitted_frame_timestamps` are the
frames remaining after capability and request-budget processing. Errors use
`isError=true` and a sanitized `error.code`/`error.message`.

### Codex

Add the server to `~/.codex/config.toml` and replace paths for your machine:

```toml
[mcp_servers.vidsight]
command = "yourpath/Vidsight/.venv/bin/vidsight"
args = ["--env-file", "yourpath/Vidsight/.env", "serve"]
startup_timeout_sec = 30
tool_timeout_sec = 1200
```

### Claude Desktop

Add this entry to `claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "vidsight": {
      "command": "yourpath/Vidsight/.venv/bin/vidsight",
      "args": [
        "--env-file",
        "yourpath/Vidsight/.env",
        "serve"
      ]
    }
  }
}
```

Each tool runs in an owned worker process and temporary directory.
`MCP_MAX_CONCURRENT=1` limits simultaneous analysis; increasing it consumes more
CPU/RAM and can issue paid requests concurrently. `VIDSIGHT_ANALYZE_TIMEOUT_SEC=900`
bounds execution after the queue slot is acquired, including media, STT and AI.
On timeout the worker process tree is stopped before temporary files are removed.
Cancellation waits for completion or this timeout before releasing the slot.
Direct Python `VideoAnalyzer` calls remain synchronous; CLI/MCP provide supervision.

See the [MCP contract](docs/mcp-proposal.md) and
[step-by-step installation guide (Vietnamese)](docs/HUONG-DAN-CAI-MCP.md).

## Docker

The published Linux/amd64 image includes ffmpeg and the default dependencies
(no local model extras):

```sh
docker pull ghcr.io/songjag/vidsight:0.2.0
docker run --rm --network=none -e LLM_PROVIDER=none -e STT_PROVIDER=none \
  ghcr.io/songjag/vidsight:0.2.0 doctor
docker run --rm -i --env-file .env \
  -v vidsight-cache:/home/vidsight/.cache/vidsight ghcr.io/songjag/vidsight:0.2.0
```

To build from the checkout instead: `docker build -t vidsight:0.2.0 .`.

Use `-i` for stdio, with no TTY. The image runs as uid 10001 and never embeds
`.env`, keys or media. Docker `--env-file` reads literal `NAME=value` lines; omit
quotes/interpolation. Loopback in a container refers to the container, so a host
AI server needs a reachable endpoint allowed by your cloud policy.
The [English guide](docs/en.md#docker) includes an MCP client configuration.

## Providers

Provider selection is configuration-driven. `auto` selects one valid provider
at initialization; it never switches provider after a request failure.

| `LLM_PROVIDER` | Protocol | Status |
|---|---|---|
| `openai` | OpenAI Chat Completions | Mock HTTP tested |
| `openai_compatible` | OpenAI-compatible HTTP | Mock HTTP tested |
| `anthropic` | Anthropic Messages | Mock HTTP tested |
| `gemini` | Gemini `generateContent` | Mock HTTP tested; current smoke lacks credentials |
| `ollama` | Ollama `/api/chat` | Mock HTTP tested |
| `gguf` | Optional `llama-cpp-python` | Fake runtime tested; real inference not certified |

### Provider examples

<details>
<summary>OpenAI, Anthropic, or Gemini</summary>

```dotenv
# Choose one provider.
LLM_PROVIDER=openai
OPENAI_API_KEY=<private-key>

# Or:
# LLM_PROVIDER=anthropic
# ANTHROPIC_API_KEY=<private-key>

# Or:
# LLM_PROVIDER=gemini
# GEMINI_API_KEY=<private-key>

LLM_MODEL=<verified-model>
# LLM_SUPPORTS_IMAGES=true
```
</details>

<details>
<summary>Local OpenAI-compatible server or Ollama</summary>

```dotenv
# OpenAI-compatible server
LLM_PROVIDER=openai_compatible
LLM_BASE_URL=http://127.0.0.1:1234/v1
LLM_MODEL=<loaded-model>
LLM_ALLOW_CLOUD=false
```

```dotenv
# Ollama native API
LLM_PROVIDER=ollama
OLLAMA_BASE_URL=http://127.0.0.1:11434
OLLAMA_MODEL=<loaded-model>
LLM_ALLOW_CLOUD=false
```
</details>

<details>
<summary>Optional GGUF</summary>

```sh
uv sync --extra local
```

```dotenv
LLM_PROVIDER=gguf
GGUF_MODEL_PATH=/models/model.gguf
LLM_ALLOW_CLOUD=false
GGUF_N_CTX=8192
GGUF_N_GPU_LAYERS=0
```

GGUF does not download models. Vision requires an explicitly supported handler
and projector file; `auto` is text-only.
</details>

### Provider verification (2026-11-30)

| Backend / model | Real smoke | Evidence / limitation |
|---|---|---|
| OpenAI-compatible cloud gateway / `gpt-6.1-sol` | FAIL | 1×1 image probe and long-video transcript request returned HTTP 400, `invalid_request_error`; no fallback |
| Cloud-native API | NOT TESTED | No current native API credentials |
| Local HTTP server | NOT TESTED | No configured running model server |
| GGUF / LLaVA-1.5 + matching mmproj | NOT TESTED | No weights/projector or runtime; PyPI has no compatible prebuilt runtime wheel for the attempted environment |

Offline protocol and fake-runtime tests are separate from these real checks.
Full commands and results are in [the 0.2 verification report](docs/verification-0.2.md).

Directory submissions: [Glama (pending)](https://glama.ai/mcp/servers/Songjag/Vidsight-YouTube-Analysis-Skill)
via [directory PR #21140](https://github.com/punkpeye/awesome-mcp-servers/pull/21140)
and [mcp.so (pending review)](https://github.com/chatmcp/mcpso/issues/1#issuecomment-7260028138).
Pending links do not indicate an approved listing.

### Structured output and diagnostics

For a model with verified JSON support, set `LLM_SUPPORTS_JSON_MODE=true` and
`LLM_JSON_MODE=true`. Vidsight requests and validates
`{summary, timeline_points: [{start, end, point}], answer}`. Timestamps are
nonnegative original-video seconds with `end >= start`. Invalid JSON or schema
raises a sanitized `ProviderResponseError`; no provider repair/fallback is used.
The original response text and the validated object are available in
`analysis.text` and `analysis.structured`. Anthropic JSON mode is not implemented.

`LLM_MAX_TOKENS=1024` configures output reserve. HTTP adapters normalize reported
`input_tokens`, `output_tokens`, `total_tokens`; absent usage stays null. A missing
total is summed only when both component counts were reported.

```sh
# Explicit network/model test; sends one synthetic pixel, and may incur cost.
uv run vidsight --env-file .env doctor --probe
```

The probe requires configured image support. It reports request acceptance and
whether the returned color matched; it does not certify general vision ability.
The default `doctor` still makes no network requests or model calls.

`LLM_MAX_RETRIES=3` means at most three retries after the first attempt, within
the timeout budget. Auth errors and ordinary 400s are not retried. A gateway 400
with allowlisted `error.type=upstream_error` is an explicit exception: at most
one retry, still within `LLM_MAX_RETRIES`. Known error categories such as
`client_not_allowed` are exposed; arbitrary messages/types and keys are not.

## Evidence and privacy

- Unknown model capabilities default to text-only; vision is never inferred
  from a provider name alone.
- Images carry MIME type and original timestamps and are resized to the
  configured limit.
- The default Vidsight budget is up to 12 images with a 1024px maximum side.
- Native video upload is not implemented; Vidsight uses sampled frames.
- `LLM_ALLOW_CLOUD=false` blocks remote AI endpoints. YouTube retrieval still
  requires network access.
- Public errors and logs exclude API keys, authorization headers, full
  transcripts, images, and raw provider response bodies.
- A request failure does not silently switch cloud/local provider.

## STT

Subtitle retrieval is preferred. Depending on configuration, Vidsight can use
Groq Whisper, OpenAI-compatible transcription, or local `faster-whisper`.

```sh
uv sync --extra stt-local
```

Local models must already exist at `STT_MODEL_PATH`; Vidsight does not download
them automatically. Audio is extracted as mono 16 kHz WAV and chunk offsets are
restored to the original video range.

## Cache

Downloaded media, subtitle segments and download metadata are cached by video ID
in `~/.cache/vidsight/`. A second question reuses that evidence; AI answers are
generated again. Results include `diagnostics.cache` (`hit` or `miss`) and
`diagnostics.subtitles_cache`.

```sh
uv run vidsight cache info
uv run vidsight cache clear
```

`VIDSIGHT_CACHE_MAX_MB=2048` sets the size limit; `0` disables persistence.
`VIDSIGHT_CACHE_TTL_DAYS=7` sets expiry. `VIDSIGHT_CACHE_DIR` overrides the directory.
Expired entries and the least recently used videos are removed automatically.
The cache contains local copies of public video evidence; clear it when needed.

Ranges shorter than half the video duration use yt-dlp range downloads. Longer
ranges reuse or download the full file. Original video timestamps are preserved.
Subtitle retrieval and media downloading run in parallel on a cache miss.

## Long videos and visual evidence

Vidsight decodes a bounded scene sample (at most 240 candidate frames), removes
near duplicates, prioritizes sampled scene changes and fills the remaining image
slots across time. `VIDSIGHT_FRAME_DEDUP_THRESHOLD=0.01` controls the mean pixel
difference threshold; `VIDSIGHT_SCENE_THRESHOLD=0.3` controls histogram changes
(both 0–1). `diagnostics.duplicate_frames_removed` reports the count.

When a range exceeds 600 seconds **and** its transcript exceeds the request
budget, it is analyzed in windows of at most 600 seconds and synthesized with
the same provider. The one-hour ingestion limit bounds this to at most six
window requests plus one synthesis request. Warnings report splitting, reduced
evidence and extra calls/costs; `diagnostics.analysis_calls` records actual calls.
Short ranges keep a single request. This remains sampled evidence, not
continuous viewing.

`STT_LANGUAGES=vi,en` controls subtitle language priority. Audio chunk boundaries
remove matching suffix/prefix words only where their timestamps overlap.

## Architecture

The implementation architecture is documented with a dark-theme Mermaid
diagram:

**[Open the architecture diagram →](docs/architecture.md)**

```mermaid
flowchart LR
    Input["YouTube + subtitles"] --> Media["Frames + audio"]
    Media --> Evidence["Timestamped evidence"]
    Evidence --> Registry["Provider registry"]
    Registry --> Result["Structured analysis"]
```

## Testing

Default tests do not call external services. They use mock HTTP transports,
fake local models, and generated media fixtures.

```sh
uv run pytest -q
uv run ruff check .
uv run vidsight --env-file .env doctor
```

Real provider and YouTube smoke tests are separate from CI and must be reported
as `PASS`, `FAIL`, or `NOT TESTED`.

## Documentation

| Language | Guide |
|---|---|
| English | [docs/en.md](docs/en.md) |
| Tiếng Việt | [docs/vie.md](docs/vie.md) |
| 中文 | [docs/cn.md](docs/cn.md) |
| 日本語 | [docs/jp.md](docs/jp.md) |
| Architecture | [docs/architecture.md](docs/architecture.md) |
| Development | [docs/development.md](docs/development.md) |

## Project identity

| Field | Value |
|---|---|
| Project | `Vidsight` |
| Skill | `vidsight-youtube-analysis` |
| Package | `vidsight` |
| MCP server | `vidsight` |

## License

Vidsight is licensed under the [MIT License](LICENSE).

TDQS

A3.8/5.0

Scored across 3 tools

Disambiguation4/5

Each tool has a reasonably distinct scope: whole-video summary, time-range Q&A, and whole-video Q&A. The main overlap is between analyze_video_segment and ask_video_question, which both answer questions and differ only in evidence scope; the descriptions clarify this, but an agent could still pick ask_video_question for a segment query.

Naming Consistency5/5

All three names follow the same snake_case verb_noun pattern (watch/analyze/ask + video object) and consistently embed the video resource. Highly predictable and readable.

Tool Count3/5

Three tools is thin for a video analysis server, even a focused one. The set covers the main interaction modes but leaves little room for supporting operations such as transcript or metadata retrieval.

Completeness3/5

The core Q&A/summarization lifecycle is covered, but there are notable gaps: no way to fetch a raw transcript, get video metadata or chapters, or list available videos. Agents needing the underlying evidence or video discovery will hit a dead end.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues