Files
video-analyse/tests/test_mcp.py
T
alex 7f415c0dbb analysis+cli+mcp: one bounded-integer guard, one max-shots default (code-review F6)
The "int, not bool, within range" guard was hand-rolled five times (analysis.moment
max_frames/width, analysis.frame width, mcp max_images, mcp transcript_max_chars),
and the MCP tool signatures re-typed max_shots=64 instead of importing the constant.

- analysis: checked_int(value, name, minimum=, maximum=) is the one implementation
  (bool rejected, one message shape) and is exported for the doors; moment/frame use
  it for their numeric knobs
- mcp: max_images and transcript_max_chars go through the same guard, and both
  max_shots defaults are DEFAULT_MAX_SHOTS
- tests: the guard's message/range contract, moment+frame's public rejection paths,
  both MCP tool guards (no stage runs), and the tool schemas' max_shots default
  tied to DEFAULT_MAX_SHOTS (all shown red against a disabled range check)
2026-11-24 12:53:32 +00:00

835 lines
30 KiB
Python

"""Tests for the FastMCP server: tool surface, structured shapes and real ffmpeg frames.
Every model-dependent tool is exercised against one stub of the analysis module
(patched at ``mcp_server.analysis``), so these tests assert outcomes — not pipeline
wiring — and never start a model. ``get_frame_at`` and the context-free moment run the
real analysis frame path against the ``sample_video`` fixture; no test downloads a model
or opens a socket beyond the in-memory client transport.
"""
from __future__ import annotations
import base64
import io
from pathlib import Path
from typing import Any
import pytest
from fastmcp import Client
from fastmcp.exceptions import ToolError
from PIL import Image as PilImage
import video_analyse.mcp_server as mcp_server
from video_analyse.analysis import (
DEFAULT_MAX_SHOTS,
AnalysisOptions,
MomentResult,
MomentSegment,
ProgressEvent,
)
from video_analyse.config import Settings
from video_analyse.models import (
Artifacts,
Highlight,
MediaFacts,
MediaRef,
Segment,
Shot,
ShotDescription,
SpeakerTurn,
Transcript,
VideoReport,
Word,
)
from video_analyse.synthesis import AnswerResult
EXPECTED_TOOLS = {
"transcribe_video",
"extract_keyframes",
"analyze_video",
"analyze_moment",
"get_frame_at",
"ask_video",
}
VA_ENV_VARS = (
"VA_PROFILE",
"VA_CACHE_DIR",
"VA_LANGUAGE",
"VA_STT_BACKEND",
"VA_STT_API_BASE_URL",
"VA_STT_API_MODEL",
"VA_STT_MAX_UPLOAD_BYTES",
"VA_WHISPER_MODEL",
"VA_DIARIZE",
"VA_DIARIZE_BACKEND",
"VA_DIARIZE_CLUSTER_THRESHOLD",
"VA_DIARIZE_MIN_DURATION_ON",
"VA_DIARIZE_MIN_DURATION_OFF",
"VA_VLM_MODEL",
"VA_LLAMA_SERVER_URL",
"VA_SYNTHESIS_MODEL",
)
@pytest.fixture(autouse=True)
def clean_va_env(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
"""Keep every test independent of the developer's environment and cache."""
for name in VA_ENV_VARS:
monkeypatch.delenv(name, raising=False)
monkeypatch.setenv("VA_CACHE_DIR", str(tmp_path / "cache"))
class StubAnalysis:
"""Stand-in for the analysis module returning canned outcomes and recording calls."""
def __init__(self) -> None:
self.calls: list[dict[str, Any]] = []
self.artifacts: Artifacts | None = None
self.transcript_result: Transcript | None = None
self.shot_list: list[Shot] = []
self.answer: AnswerResult | None = None
self.moment_result: MomentResult | None = None
self.failure: BaseException | None = None
self.events: list[ProgressEvent] = []
def _record(self, operation: str, source: str, **values: Any) -> None:
self.calls.append({"operation": operation, "source": source, **values})
async def probe(self, source: str, *, settings: Settings, progress: Any = None) -> Artifacts:
self._record("probe", source, settings=settings, progress=progress)
assert self.artifacts is not None
return self.artifacts
async def transcript(
self,
source: str,
options: AnalysisOptions,
*,
settings: Settings,
progress: Any = None,
) -> Transcript:
self._record("transcript", source, options=options, settings=settings, progress=progress)
if self.failure is not None:
raise self.failure
assert self.transcript_result is not None
return self.transcript_result
async def shots(
self,
source: str,
options: AnalysisOptions,
*,
settings: Settings,
progress: Any = None,
) -> Artifacts:
self._record("shots", source, options=options, settings=settings, progress=progress)
if self.failure is not None:
raise self.failure
base = self.artifacts or Artifacts(source=source, workdir=Path())
return base.model_copy(update={"source": source, "shots": list(self.shot_list)})
async def analyse(
self,
source: str,
options: AnalysisOptions,
*,
settings: Settings,
progress: Any = None,
) -> Artifacts:
self._record("analyse", source, options=options, settings=settings, progress=progress)
if progress is not None:
for event in self.events:
progress(event)
if self.failure is not None:
raise self.failure
assert self.artifacts is not None
return self.artifacts
async def ask(
self,
source: str,
question: str,
options: AnalysisOptions,
*,
settings: Settings,
allow_analysis: bool = False,
) -> AnswerResult:
self._record(
"ask",
source,
question=question,
options=options,
settings=settings,
allow_analysis=allow_analysis,
)
if self.failure is not None:
raise self.failure
assert self.answer is not None
return self.answer
async def moment(
self,
source: str,
t_start: float,
t_end: float,
options: AnalysisOptions,
*,
settings: Settings,
max_frames: int = 4,
width: int = 768,
) -> MomentResult:
self._record(
"moment",
source,
t_start=t_start,
t_end=t_end,
options=options,
settings=settings,
max_frames=max_frames,
width=width,
)
if self.failure is not None:
raise self.failure
assert self.moment_result is not None
return self.moment_result
async def frame(
self,
source: str,
timestamp: float,
*,
settings: Settings,
width: int = 768,
) -> Any:
self._record("frame", source, timestamp=timestamp, settings=settings, width=width)
if self.failure is not None:
raise self.failure
raise AssertionError("frame is exercised through the real analysis path")
@pytest.fixture
def stub_analysis(monkeypatch: pytest.MonkeyPatch) -> StubAnalysis:
"""Replace the analysis module with one outcome-shaped stub for one test."""
stub = StubAnalysis()
monkeypatch.setattr(mcp_server, "analysis", stub)
return stub
def _transcript(*, speakers: bool = True) -> Transcript:
"""A two-segment, word-timed transcript, speaker-labelled when ``speakers``."""
turns = (
[
SpeakerTurn(start=0.0, end=2.0, speaker="S1"),
SpeakerTurn(start=2.0, end=4.0, speaker="S2"),
]
if speakers
else []
)
return Transcript(
language="en",
duration=10.0,
segments=[
Segment(
start=0.0,
end=2.0,
text="Hello there.",
words=[
Word(text="Hello", start=0.1, end=0.6, probability=0.91),
Word(text="there.", start=0.7, end=1.2, probability=0.88),
],
speaker="S1" if speakers else None,
),
Segment(
start=2.0,
end=4.0,
text="General Kenobi.",
words=[
Word(text="General", start=2.1, end=2.6),
Word(text="Kenobi.", start=2.7, end=3.2),
],
speaker="S2" if speakers else None,
),
],
speaker_turns=turns,
backend="stub",
model="stub-stt",
)
def _jpeg(path: Path, color: tuple[int, int, int]) -> Path:
"""Write a tiny solid-colour JPEG and return its path."""
path.parent.mkdir(parents=True, exist_ok=True)
PilImage.new("RGB", (64, 36), color).save(path, format="JPEG")
return path
def _shots(frames_dir: Path, *, described: bool = True) -> list[Shot]:
"""Two shots with real JPEG keyframes and optional descriptions."""
first = ShotDescription(summary="A red test pattern.", shot_type="screen", on_screen_text="0")
second = ShotDescription(summary="A blue test pattern.", shot_type="wide")
return [
Shot(
index=0,
start=0.0,
end=5.0,
keyframe=_jpeg(frames_dir / "shot-0.jpg", (200, 30, 30)),
phash="0000000000000001",
description=first if described else None,
),
Shot(
index=1,
start=5.0,
end=10.0,
keyframe=_jpeg(frames_dir / "shot-1.jpg", (30, 30, 200)),
phash="0000000000000002",
description=second if described else None,
),
]
def _media(path: Path, *, has_audio: bool = True, has_video: bool = True) -> MediaFacts:
"""Synthetic content facts for ``path`` (the file is never opened)."""
size = path.stat().st_size if path.is_file() else 0
return MediaFacts(
duration=10.0,
width=640 if has_video else None,
height=360 if has_video else None,
fps=12.0 if has_video else None,
has_audio=has_audio,
size_bytes=size,
format="mp4",
video_codec="h264" if has_video else None,
audio_codec="aac" if has_audio else None,
)
def _artifacts(
path: Path,
*,
transcript: Transcript | None = None,
shots: list[Shot] | None = None,
report: VideoReport | None = None,
has_audio: bool = True,
has_video: bool = True,
) -> Artifacts:
"""Canned analysis artifacts for one stub call."""
return Artifacts(
source=str(path),
workdir=path.parent,
media=_media(path, has_audio=has_audio, has_video=has_video),
ref=MediaRef(source=str(path), local_path=path),
transcript=transcript,
shots=shots or [],
report=report,
)
def _report(path: Path, transcript: Transcript, shots: list[Shot]) -> VideoReport:
"""A validated report built from the canned transcript and shots."""
return VideoReport(
source=str(path),
title="Synthetic clip",
duration=10.0,
summary="A synthetic test pattern with two spoken lines.",
topics=["test pattern"],
people=["S1", "S2"],
highlights=[
Highlight(start=2.0, end=4.0, description="[00:02] The second speaker answers.")
],
shots=shots,
transcript=transcript,
metadata={"width": 640, "height": 360},
)
def _image_blocks(result: Any) -> list[Any]:
"""Every image content block of a tool result, in order."""
return [block for block in result.content if block.type == "image"]
async def test_server_registers_exactly_the_six_documented_tools() -> None:
"""The server advertises the six planned tools with docstring descriptions."""
assert mcp_server.mcp.name == "video-analyse"
async with Client(mcp_server.mcp) as client:
tools = await client.list_tools()
assert {tool.name for tool in tools} == EXPECTED_TOOLS
for tool in tools:
assert tool.description, f"{tool.name} is missing a tool description"
assert len(tool.description) > 40
schemas = {tool.name: tool.input_schema for tool in tools}
assert "ctx" not in schemas["analyze_video"]["properties"]
assert schemas["transcribe_video"]["properties"]["diarize"]["default"] is None
assert schemas["extract_keyframes"]["properties"]["max_shots"]["default"] == DEFAULT_MAX_SHOTS
assert schemas["analyze_video"]["properties"]["max_shots"]["default"] == DEFAULT_MAX_SHOTS
assert set(schemas["analyze_moment"]["required"]) == {"source", "t_start", "t_end"}
assert schemas["ask_video"]["properties"]["no_cache"]["default"] is False
async def test_transcribe_video_returns_a_speaker_labelled_transcript(
stub_analysis: StubAnalysis, sample_video: Path
) -> None:
"""transcribe_video maps diarize=None to the analysis default and returns the Transcript."""
stub_analysis.transcript_result = _transcript()
async with Client(mcp_server.mcp) as client:
result = await client.call_tool("transcribe_video", {"source": str(sample_video)})
payload = result.structured_content
assert payload["language"] == "en"
assert payload["backend"] == "stub"
assert [segment["text"] for segment in payload["segments"]] == [
"Hello there.",
"General Kenobi.",
]
assert payload["segments"][0]["speaker"] == "S1"
assert payload["segments"][1]["speaker"] == "S2"
assert payload["segments"][0]["words"][0] == {
"text": "Hello",
"start": 0.1,
"end": 0.6,
"probability": 0.91,
}
assert payload["speaker_turns"] == [
{"start": 0.0, "end": 2.0, "speaker": "S1"},
{"start": 2.0, "end": 4.0, "speaker": "S2"},
]
call = stub_analysis.calls[-1]
assert call["operation"] == "transcript"
assert call["options"].diarize is None
assert call["source"] == str(sample_video)
async def test_transcribe_video_respects_the_diarize_flag(
stub_analysis: StubAnalysis, sample_video: Path
) -> None:
"""diarize=False reaches the analysis options unchanged."""
stub_analysis.transcript_result = _transcript(speakers=False)
async with Client(mcp_server.mcp) as client:
result = await client.call_tool(
"transcribe_video", {"source": str(sample_video), "diarize": False}
)
assert result.structured_content["speaker_turns"] == []
assert stub_analysis.calls[-1]["options"].diarize is False
async def test_url_sources_are_forwarded_to_the_pipeline(
stub_analysis: StubAnalysis, tmp_path: Path
) -> None:
"""An http(s) source is accepted and handed to the analysis ingest path (no network here)."""
url = "https://example.com/lecture.mp4"
stub_analysis.transcript_result = _transcript()
async with Client(mcp_server.mcp) as client:
await client.call_tool("transcribe_video", {"source": url})
assert stub_analysis.calls[-1]["source"] == url
async def test_transcribe_video_explains_a_missing_audio_stream(
stub_analysis: StubAnalysis, sample_video: Path
) -> None:
"""A silent video fails with the analysis diagnosis instead of an empty transcript."""
stub_analysis.failure = RuntimeError(
f"transcribe: no transcript for '{sample_video}': the file has no audio stream. "
"Check the file and the configured STT backend (VA_STT_BACKEND)."
)
async with Client(mcp_server.mcp) as client:
with pytest.raises(ToolError, match="no audio stream"):
await client.call_tool("transcribe_video", {"source": str(sample_video)})
async def test_extract_keyframes_returns_shots_plus_image_blocks(
stub_analysis: StubAnalysis, sample_video: Path, tmp_path: Path
) -> None:
"""extract_keyframes returns the shot list as data and one JPEG block per keyframe."""
stub_analysis.shot_list = _shots(tmp_path / "keyframes")
stub_analysis.artifacts = Artifacts(
source=str(sample_video), workdir=tmp_path, shots=stub_analysis.shot_list
)
async with Client(mcp_server.mcp) as client:
result = await client.call_tool(
"extract_keyframes", {"source": str(sample_video), "max_shots": 2}
)
payload = result.structured_content
assert payload["source"] == str(sample_video)
assert payload["workdir"] == str(tmp_path)
assert "count" not in payload
assert [shot["index"] for shot in payload["shots"]] == [0, 1]
assert payload["shots"][0]["start"] == 0.0 and payload["shots"][0]["end"] == 5.0
assert payload["shots"][0]["description"]["shot_type"] == "screen"
assert payload["shots"][1]["keyframe"].endswith("shot-1.jpg")
images = _image_blocks(result)
assert len(images) == 2
for block in images:
assert block.mime_type == "image/jpeg"
assert base64.b64decode(block.data)[:2] == b"\xff\xd8"
assert result.content[0].type == "text"
assert "2 shot(s)" in result.content[0].text
call = stub_analysis.calls[-1]
assert call["operation"] == "shots"
assert call["options"].max_shots == 2
async def test_extract_keyframes_rejects_an_invalid_max_images(
stub_analysis: StubAnalysis, sample_video: Path
) -> None:
"""A bad image cap fails the shared integer guard before any stage runs."""
async with Client(mcp_server.mcp) as client:
with pytest.raises(ToolError, match="max_images must be an integer >= 1"):
await client.call_tool(
"extract_keyframes", {"source": str(sample_video), "max_images": 0}
)
assert stub_analysis.calls == []
async def test_analyze_video_rejects_a_negative_transcript_cap(
stub_analysis: StubAnalysis, sample_video: Path
) -> None:
"""A negative transcript budget fails the shared integer guard before any stage runs."""
async with Client(mcp_server.mcp) as client:
with pytest.raises(ToolError, match="transcript_max_chars must be an integer >= 0"):
await client.call_tool(
"analyze_video",
{"source": str(sample_video), "transcript_max_chars": -1},
)
assert stub_analysis.calls == []
async def test_analyze_video_returns_a_report_and_reports_exact_progress(
stub_analysis: StubAnalysis, sample_video: Path, tmp_path: Path
) -> None:
"""analyze_video streams the analysis module's exact stage fractions and returns the report."""
transcript = _transcript()
shots = _shots(tmp_path / "keyframes")
stub_analysis.artifacts = _artifacts(
sample_video,
transcript=transcript,
shots=shots,
report=_report(sample_video, transcript, shots),
)
stub_analysis.events = [
ProgressEvent(stage="probe", state="start", index=1, total=3),
ProgressEvent(stage="probe", state="done", index=1, total=3),
ProgressEvent(stage="transcribe", state="cached", index=2, total=3),
ProgressEvent(stage="report", state="done", index=3, total=3),
]
notifications: list[tuple[float, float | None, str | None]] = []
async def handler(progress: float, total: float | None, message: str | None) -> None:
notifications.append((progress, total, message))
async with Client(mcp_server.mcp) as client:
result = await client.call_tool(
"analyze_video", {"source": str(sample_video)}, progress_handler=handler
)
payload = result.structured_content
assert payload["source"] == str(sample_video)
assert payload["title"] == "Synthetic clip"
assert payload["duration"] == 10.0
assert payload["summary"] == "A synthetic test pattern with two spoken lines."
assert payload["topics"] == ["test pattern"]
assert payload["people"] == ["S1", "S2"]
assert payload["highlights"] == [
{"start": 2.0, "end": 4.0, "description": "[00:02] The second speaker answers."}
]
assert payload["shots"][0]["description"]["summary"] == "A red test pattern."
assert payload["transcript"]["segments"][1]["speaker"] == "S2"
# Default result is bounded: no word timings, transcript cap recorded in metadata.
assert payload["transcript"]["segments"][0]["words"] == []
assert payload["metadata"]["transcript_words_included"] is False
assert "transcript_truncated" in payload["metadata"]
fractions = [progress for progress, _total, _message in notifications]
assert fractions[:4] == [pytest.approx(1 / 3), pytest.approx(1 / 3), pytest.approx(2 / 3), 1.0]
assert fractions[-1] == 1.0
assert all(total == 1.0 for _progress, total, _message in notifications)
assert notifications[-1][2] is not None
assert "analysis finished" in notifications[-1][2]
assert stub_analysis.calls[-1]["operation"] == "analyse"
async def test_analyze_video_surfaces_model_server_failures(
stub_analysis: StubAnalysis, sample_video: Path
) -> None:
"""The analysis module's diagnosed model failure reaches the client unchanged."""
stub_analysis.failure = RuntimeError(
"analyse: 'clip.mp4' failed: llama-server is not reachable at "
"http://127.0.0.1:8080/v1. Model stages need a reachable backend; `va doctor` "
"checks it."
)
async with Client(mcp_server.mcp) as client:
with pytest.raises(ToolError, match="llama-server is not reachable") as excinfo:
await client.call_tool("analyze_video", {"source": str(sample_video)})
message = str(excinfo.value)
assert "va doctor" in message
assert "analyse" in message
async def test_analyze_video_requires_audio_or_video(
stub_analysis: StubAnalysis, sample_video: Path
) -> None:
"""No report becomes the analysis module's actionable error, not a None result."""
stub_analysis.failure = RuntimeError(
f"analyse: no report was produced for '{sample_video}': the source has neither a "
"usable audio transcript nor video shots."
)
async with Client(mcp_server.mcp) as client:
with pytest.raises(ToolError, match="no report was produced"):
await client.call_tool("analyze_video", {"source": str(sample_video)})
async def test_ask_video_answers_from_the_cached_report(
stub_analysis: StubAnalysis, sample_video: Path
) -> None:
"""ask_video delegates to the analysis ask outcome and returns its AnswerResult."""
stub_analysis.answer = AnswerResult(answer="A synthetic test pattern [00:02].", cached=False)
async with Client(mcp_server.mcp) as client:
result = await client.call_tool(
"ask_video", {"source": str(sample_video), "question": " What is shown? "}
)
assert result.structured_content["answer"] == "A synthetic test pattern [00:02]."
call = stub_analysis.calls[-1]
assert call["operation"] == "ask"
assert call["options"].no_cache is False
assert call["allow_analysis"] is False
async def test_ask_video_honours_no_cache(stub_analysis: StubAnalysis, sample_video: Path) -> None:
"""no_cache reaches the analysis options (both front doors honour it)."""
stub_analysis.answer = AnswerResult(answer="fresh", cached=False)
async with Client(mcp_server.mcp) as client:
await client.call_tool(
"ask_video",
{"source": str(sample_video), "question": "Why?", "no_cache": True},
)
assert stub_analysis.calls[-1]["options"].no_cache is True
async def test_ask_video_is_cached_only_by_default(sample_video: Path) -> None:
"""With an empty cache the real analysis reports the missing report, not a full run."""
async with Client(mcp_server.mcp) as client:
with pytest.raises(ToolError, match="Run analyze_video first") as excinfo:
await client.call_tool(
"ask_video", {"source": str(sample_video), "question": "What happens?"}
)
assert "va analyse" in str(excinfo.value)
async def test_ask_video_rejects_a_blank_question(sample_video: Path) -> None:
"""A blank question fails in the analysis module before any model work starts."""
async with Client(mcp_server.mcp) as client:
with pytest.raises(ToolError, match="question must be a non-empty string"):
await client.call_tool("ask_video", {"source": str(sample_video), "question": " "})
async def test_ask_video_explains_an_unreachable_model(
stub_analysis: StubAnalysis, sample_video: Path
) -> None:
"""A failing synthesis model arrives with the analysis module's backend advice."""
stub_analysis.failure = RuntimeError(
"ask: the synthesis model could not answer the question about 'clip.mp4': "
"Connection error. Model stages need a reachable backend: the local default "
"requires llama-server; VA_SYNTHESIS_MODEL can switch to deepseek:deepseek-flash."
)
async with Client(mcp_server.mcp) as client:
with pytest.raises(ToolError, match="synthesis model could not answer") as excinfo:
await client.call_tool(
"ask_video", {"source": str(sample_video), "question": "What happens?"}
)
message = str(excinfo.value)
assert "Connection error." in message
assert "llama-server" in message
assert "deepseek:deepseek-flash" in message
async def test_get_frame_at_returns_a_real_jpeg(sample_video: Path) -> None:
"""get_frame_at runs the real analysis frame path against the fixture."""
async with Client(mcp_server.mcp) as client:
result = await client.call_tool("get_frame_at", {"source": str(sample_video), "t": 2.5})
images = _image_blocks(result)
assert len(images) == 1
assert images[0].mime_type == "image/jpeg"
raw = base64.b64decode(images[0].data)
with PilImage.open(io.BytesIO(raw)) as frame:
assert frame.format == "JPEG"
assert 0 < frame.width <= mcp_server.FRAME_WIDTH
assert frame.height > 0
payload = result.structured_content
assert payload["source"] == str(sample_video)
assert payload["t"] == pytest.approx(2.5)
assert payload["mime_type"] == "image/jpeg"
async def test_get_frame_at_rejects_timestamps_past_the_end(sample_video: Path) -> None:
"""A timestamp outside the video surfaces as an actionable tool error."""
async with Client(mcp_server.mcp) as client:
with pytest.raises(ToolError, match="beyond the end"):
await client.call_tool("get_frame_at", {"source": str(sample_video), "t": 99.0})
async def test_analyze_moment_is_a_thin_adapter_over_the_analysis_operation(
stub_analysis: StubAnalysis, sample_video: Path
) -> None:
"""analyze_moment turns the analysis MomentResult into text + image content blocks."""
stub_analysis.moment_result = MomentResult(
source=str(sample_video),
t_start=0.5,
t_end=4.0,
duration=10.0,
frame_timestamps=[0.9, 1.8, 2.7, 3.6],
transcript=[
MomentSegment(start=0.5, end=2.0, speaker="S1", text="there."),
MomentSegment(start=2.0, end=4.0, speaker="S2", text="General Kenobi."),
],
transcript_text="[00:00] S1: there.\n[00:02] S2: General Kenobi.",
shots=[
Shot(
index=0,
start=0.0,
end=5.0,
description=ShotDescription(summary="A red test pattern.", shot_type="screen"),
)
],
notes=["Frames were described with the configured vision model."],
frames=[b"\xff\xd8\xff\xe0frame-0", b"\xff\xd8\xff\xe0frame-1"],
)
async with Client(mcp_server.mcp) as client:
result = await client.call_tool(
"analyze_moment",
{"source": str(sample_video), "t_start": 0.5, "t_end": 4.0, "describe": True},
)
payload = result.structured_content
assert payload["source"] == str(sample_video)
assert payload["t_start"] == 0.5
assert payload["t_end"] == 4.0
assert payload["transcript_text"] == "[00:00] S1: there.\n[00:02] S2: General Kenobi."
assert payload["shots"][0]["description"]["summary"] == "A red test pattern."
assert payload["notes"] == ["Frames were described with the configured vision model."]
assert "frames" not in payload
images = _image_blocks(result)
assert len(images) == 2
for block in images:
assert block.mime_type == "image/jpeg"
assert base64.b64decode(block.data)[:2] == b"\xff\xd8"
call = stub_analysis.calls[-1]
assert call["operation"] == "moment"
assert call["options"].describe is True
assert call["t_start"] == 0.5 and call["t_end"] == 4.0
async def test_analyze_moment_without_cached_artifacts_explains_the_gap(
sample_video: Path,
) -> None:
"""With an empty cache, the real moment path still returns frames and explains the gap."""
async with Client(mcp_server.mcp) as client:
result = await client.call_tool(
"analyze_moment",
{"source": str(sample_video), "t_start": 1.0, "t_end": 2.0},
)
payload = result.structured_content
assert payload["transcript"] == []
assert payload["transcript_text"] == ""
assert payload["shots"] == []
notes = " ".join(payload["notes"])
assert "No cached transcript" in notes
assert "No cached shots" in notes
assert len(_image_blocks(result)) == 4
async def test_analyze_moment_validates_the_window(sample_video: Path) -> None:
"""A non-positive window is rejected before any ffmpeg work happens."""
async with Client(mcp_server.mcp) as client:
with pytest.raises(ToolError, match="t_end must be greater than t_start"):
await client.call_tool(
"analyze_moment",
{"source": str(sample_video), "t_start": 3.0, "t_end": 2.0},
)
async def test_missing_source_reports_an_actionable_error(tmp_path: Path) -> None:
"""A missing local file fails fast with the resolved path in the message."""
missing = tmp_path / "not-here.mp4"
async with Client(mcp_server.mcp) as client:
with pytest.raises(ToolError) as excinfo:
await client.call_tool("transcribe_video", {"source": str(missing)})
message = str(excinfo.value)
assert "not found" in message.lower()
assert str(missing) in message
class _RecordingServer:
"""Minimal stand-in for the FastMCP server, recording ``run`` calls."""
def __init__(self) -> None:
self.calls: list[dict[str, Any]] = []
def run(self, **kwargs: Any) -> None:
"""Record the transport options of one server start."""
self.calls.append(kwargs)
def test_run_defaults_to_stdio(monkeypatch: pytest.MonkeyPatch) -> None:
"""``run()`` and ``main()`` start the server over stdio without transport arguments."""
fake = _RecordingServer()
monkeypatch.setattr(mcp_server, "mcp", fake)
mcp_server.run()
mcp_server.main()
assert fake.calls == [{}, {}]
def test_run_serves_http_when_requested(monkeypatch: pytest.MonkeyPatch) -> None:
"""Requesting HTTP passes the host and port through to FastMCP."""
fake = _RecordingServer()
monkeypatch.setattr(mcp_server, "mcp", fake)
mcp_server.run(transport="http", host="0.0.0.0", port=9000)
assert fake.calls == [{"transport": "http", "host": "0.0.0.0", "port": 9000}]
def test_run_rejects_unknown_transports(monkeypatch: pytest.MonkeyPatch) -> None:
"""An unknown transport is rejected before any server is started."""
fake = _RecordingServer()
monkeypatch.setattr(mcp_server, "mcp", fake)
with pytest.raises(ValueError, match="unknown MCP transport"):
mcp_server.run(transport="carrier-pigeon")
assert fake.calls == []