Local video editor for coding agents: 42 FFmpeg tools with a machine-readable contract and an MCP server, for Claude Code, Cursor and Codex. Cut, captions, reframe, loudness, platform exports. No cloud, no API keys.
Python agent-skillsai-agentsaudio-processingcaptionsclaude-codecodexcoding-agentcursorffmpegloudness-normalizationmcpmcp-servermodel-context-protocolpythonsubtitlestranscodingvideovideo-editingvideo-processingwhisper
feat: deprecated list in the contract, ctx= on run/emit/die/info, FFMPEG_SKILL_MCP_LEAN, NO_OVERWRITE as the agent setting, eval-9 follow-ups (#209)
claude[bot]4053fda80fdd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bcf437b..777449c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,7 +4,27 @@## Unreleased-(nothing yet)+### Deprecated++Announced per docs/contract.md's three-step policy (also in `contract --json`'s new top-level+`deprecated` list and in docs/contract.md's "What 2.0 changes"); everything below keeps working+unchanged in 1.x and is removed in 2.0.0:++- The per-tool v1 success keys next to `result_v2` (`output`, `probe`, `commands`, `verified`,+ `verification` and each tool's own top-level keys) — use `result_v2` (`FFMPEG_SKILL_RESULT_V2=1`).+- `--crf` as an alias of `--quality` on every re-encoding tool that takes `--quality` (`export.py`+ keeps `--crf`: its preset chooses the encoder) — use `--quality N`; `--crf` now+ prints a one-line stderr warning when it is passed explicitly and is marked in `--help`.+- `json` and `progress` in the MCP `inputSchema` — the transport sets them itself;+ `FFMPEG_SKILL_MCP_LEAN=1` drops them from `tools/list` today (opt-in, default unchanged).+- `probe`'s `hdr` meaning "BT.2020 primaries or a PQ/HLG transfer" — use `hdr_signal`; 2.0 renames.+- Overwriting an existing output with only a warning — pass `--overwrite`, or set+ `FFMPEG_SKILL_NO_OVERWRITE=1` (the recommended agent setting) for the 2.0 behaviour today.++### Other++- `run()`, `emit()`, `die()` and `info()` accept an optional `ctx=` Context (issue #189 B); `STATE`+ stays the default instance, so no tool changes behaviour. 2.0 makes the argument required.## 1.9.1diff --git a/README.md b/README.mdindex 3b5376e..fce5f6c 100644--- a/README.md+++ b/README.md@@ -305,6 +305,8 @@ On Windows, `python3` is only on PATH if Python was installed from the Microsoft`mcp/server.py` is a stdio JSON-RPC transport with no tool table of its own. `tools/list` is derived from the contract at start-up: the same 42 names, the same order, and `inputSchema` translated from each tool's `input_schema`. `tools/call` maps structured arguments to argv and runs the named script; a raw `argv` form is accepted for compatibility and marked non-canonical. `python3 mcp/server.py --list` prints the tools; `--call probe '{"inputs": ["a.mp4"]}'` runs one from the shell.+`FFMPEG_SKILL_MCP_LEAN=1` in the server's environment drops `json` and `progress` from every `inputSchema`: they are transport flags the server sets itself, not tool arguments, and 2.0 drops them unconditionally. It is opt-in, so the default `tools/list` stays byte-identical to the CLI surface the contract promises.+### Capability detection```bashdiff --git a/SKILL.md b/SKILL.mdindex 54d680b..1f0eda5 100644--- a/SKILL.md+++ b/SKILL.md@@ -65,9 +65,16 @@ Scripts live in `scripts/` next to this file; run them with `python3 <skill-dir>failure, and the report says so with the script's error message.7. **Keep the user's originals.** Never overwrite the source file. Write newfiles next to the input or where the user asked.+ Set `FFMPEG_SKILL_NO_OVERWRITE=1` in the environment you run these scripts+ in: an output path that already exists is then refused (`kind: input`)+ instead of warned about, and `--overwrite` stays the one way to say "yes,+ replace it". It is the recommended agent setting because an agent picking+ output names cannot see which files the user already cares about — and it+ is what 2.0 does by default.8. **Look at the picture.** Whenever the picture changed (captions, overlays,graphics, crop/pad, resize, colour, transitions, a `join.py` that scaled or- padded a clip to the first clip's frame) run `look.py OUTPUT`+ padded a clip to the first clip's frame, a `color.py --to-sdr` that tone-maps+ an HDR source) run `look.py OUTPUT`(contact sheet) or `look.py OUTPUT --at T`, view the PNG. The job is notfinished until the report's `Look:` line names that PNG; a probe alonecannot see a caption sitting on someone's face. Audio-only jobs (sync,@@ -123,6 +130,10 @@ If a request needs an FFmpeg feature none of the 42 scripts expose, say so and n## Request → script+This table and `doctor`'s tool list are the source of truth for what exists: name only a script you have seen in one of them, never a plausible-sounding one (there is no `doctor.py`, no `trim.py`, no `subtitle.py`).++Times take seconds, `mm:ss(.fff)`, `hh:mm:ss(.fff)` or four-part SMPTE `hh:mm:ss:ff` everywhere, with `@fps` naming the rate (`00:01:02:[email protected]`): use the timecode forms when the user pastes an editor's timecode list or an NLE cue sheet, so nothing is converted by hand on the way in.+| User says | Do ||-----------|----|| "what's in this file", "how long is it", "is it 4K" | `probe.py input.mp4` |@@ -243,7 +254,7 @@ commands work with `talk.wav` in place of `talk.mp4`. What changes:## Report format-Reply in the language the request itself is written in: the language of the user's own sentences, not a language the request talks about (an English request for Spanish subtitles gets an English report) and not the language of a tool's error text or of the file names. Keep the shape below and the field labels (`Done:`, `Steps:`, `Check:`, `Look:`, `Notes:`) in English (they read like log fields, not prose, and stay recognisable across languages); the sentences around them, any question asked, and any explanation of a judgement call are in the user's language. Never default to English because the tool names and flags happen to be English, and never drift into another language because the job is short or the report is a failure: a one-line "file does not exist" is written in the request's language too. A mid-conversation language switch follows the user's latest message, not the first one. This holds for a one-command job too: a three-second audio trim answered with English labels, numbers and one Japanese word in `Notes:` is an English report; the `Done:` line's own description (what was cut, from where) and `Steps:` are written in the user's language even when the values are technical.+Reply in the language the request itself is written in: the language of the user's own sentences, not a language the request talks about (a request asking for subtitles in some other language is still answered in the language it was written in) and not the language of a tool's error text or of the file names. Keep the shape below and the field labels (`Done:`, `Steps:`, `Check:`, `Look:`, `Notes:`) in English (they read like log fields, not prose, and stay recognisable across languages); the sentences around them, any question asked, and any explanation of a judgement call are in the user's language. Never default to English because the tool names and flags happen to be English, and never drift into another language because the job is short or the report is a failure: a one-line "file does not exist" is written in the request's language too. A mid-conversation language switch follows the user's latest message, not the first one. This holds for a one-command job too: a three-second audio trim answered with English labels, numbers and one Japanese word in `Notes:` is an English report; the `Done:` line's own description (what was cut, from where) and `Steps:` are written in the user's language even when the values are technical.Finish every job with this shape (numbers from `probe.py`/`check.py`, not memory):@@ -319,7 +330,10 @@ Every script prints `{"status": "failed", "error": {"kind": input | ffmpeg | outscript keeps the output HDR (HEVC Main10, source colour tags) so nothing issilently flattened. Decide with the user: keep HDR (fine for YouTube/phones)or run `color.py --to-sdr` first for SDR-only destinations, LUT work or- H.264 deliverables. `export.py` platform presets are SDR and warn on HDR+ H.264 deliverables. `hdr: true` counts BT.2020 primaries too, so it is also+ true for a wide-gamut SDR file; `hdr_signal: true` is the narrower fact —+ a real PQ / HLG / Dolby Vision transfer — and `hdr_format` names the+ in-between case (`BT.2020 SDR`). `export.py` platform presets are SDR and warn on HDRinput. iPhone `.mov` files also carry timecode/metadata tracks; scripts maponly the first audio track, so extra tracks are dropped on re-encode.For Log footage (S-Log, V-Log, C-Log: looks grey and low-contrast but isdiff --git a/docs/contract.md b/docs/contract.mdindex 4912990..4e6365d 100644--- a/docs/contract.md+++ b/docs/contract.md@@ -78,11 +78,28 @@ A defect fix that changes behaviour is not a deprecation: it ships in a patch wiCHANGELOG line, and if the old behaviour was something a caller could reasonably have reliedon, the line says so.+## What 2.0 changes++`contract --json` carries a top-level `deprecated` list, next to `contract_version`: one entry per+thing 2.0.0 removes, `{"what", "since", "replacement", "removed_in", "where"}` with `where` naming+the surface (`cli`, `json`, `mcp`, `behaviour`). It is the machine-readable half of the policy+above, and this section is written from it. Nothing below changes behaviour in 1.x -- every old+spelling keeps working until 2.0.++| What 2.0 removes | Since | Replacement | To be ready today |+|---|---|---|---|+| The per-tool v1 success keys next to `result_v2` (`output`, `probe`, `commands`, `verified`, `verification` and each tool's own keys at the top level) | 1.10.0 | `result_v2`, promoted to the top level in 2.0 | Run with `FFMPEG_SKILL_RESULT_V2=1` and read `result_v2` (`metrics`, `notes`, `details`) instead of the top-level keys |+| `--crf` as an alias of `--quality` on every re-encoding tool that takes `--quality` (`export.py` keeps `--crf`: its preset chooses the encoder) | 1.10.0 | `--quality N` (the same CRF scale, codec-neutral) | Pass `--quality`; `--crf` warns on stderr and is marked in `--help` |+| `json` and `progress` in the MCP `inputSchema` | 1.10.0 | nothing: the transport sets them itself | Stop sending them from an MCP client; run the server with `FFMPEG_SKILL_MCP_LEAN=1` to see the 2.0 schema |+| `hdr` meaning "BT.2020 primaries *or* a PQ/HLG transfer" in `probe` | 1.10.0 | `hdr_signal` (true only for PQ / HLG / Dolby Vision); in 2.0 `hdr` takes that meaning | Key on `hdr_signal` for "is this a real HDR signal" and on `hdr_format` for the `BT.2020 SDR` case |+| Overwriting an existing output with only a warning | 1.10.0 | `--overwrite` as explicit consent (refused without it from 2.0) | Set `FFMPEG_SKILL_NO_OVERWRITE=1` (the recommended agent setting) and pass `--overwrite` where a replacement is intended |+## Skill```json{"contract_version": "1.0",+ "deprecated": [{"what": "...", "since": "1.10.0", "replacement": "...", "removed_in": "2.0.0", "where": "cli | json | mcp | behaviour"}],"skill": {"id": "ffmpeg-skill", "version": "1.9.1", "execution_mode": "local", "kind": "execution","entrypoints": {"cli": "...", "mcp": "...", "contract": "...", "doctor": "..."},"not_provided": ["AI reasoning", "decisions", "production plans", "project IR", "approvals", "network access", "transcription engine"]},@@ -404,6 +421,14 @@ already applied when the ToolSpec is built.The `tools/list` document is deterministic (byte-identical across processes andidentical to the translation of `contract --json`), which the tests check.+`FFMPEG_SKILL_MCP_LEAN=1` (anything but "" or `0`) in the server's environment removes `json` and+`progress` from every `inputSchema` (from `properties`, and from `required` if a tool ever made+them required). They are transport flags `mcp/server.py` sets itself -- it appends `--json` for+every tool but `look` and `probe` -- rather than arguments a caller chooses, and 2.0 drops them+for good (see "What 2.0 changes"). The flag is opt-in and changes nothing else: without it+`tools/list` is byte-identical to what it has always been, which is what the frozen 1.x snapshot+pins, so a lean client and a default client see the same tools with the same names.+## Consuming the contract from an agentA planning agent (for example video-production-agent's SkillRegistry) can:diff --git a/docs/roadmap.md b/docs/roadmap.mdindex b745c6d..5f5f92a 100644--- a/docs/roadmap.md+++ b/docs/roadmap.md@@ -42,21 +42,23 @@ minor and `fix` PRs into a patch, so each block below is one or two `feat` PRs p## 1.10.0 — 2.0 readiness-- **Deprecation notices**, per the three-step policy in `docs/contract.md`: `--help` text,+- **Deprecation notices** (done), per the three-step policy in `docs/contract.md`: `--help` text,CHANGELOG, and a `deprecated` list in `contract --json` for what 2.0 removes: the per-tool- v1 success keys superseded by `result_v2`, `--crf` / `--preset` as aliases of `--quality`,+ v1 success keys superseded by `result_v2`, `--crf` as an alias of `--quality`,`json` / `progress` in the MCP `inputSchema`, the current `hdr` meaning, the overwrite default.-- **`Context` threading** (2.0 B, internal): `STATE` becomes the default `Context` instance and- `run()` / `emit()` / `die()` accept an optional `ctx=`; no tool changes behaviour. 2.0 makes+ (`--preset` is *not* deprecated: it is the x264 speed preset, not a quality alias.)+- **`Context` threading** (done, 2.0 B, internal): `STATE` is the default `Context` instance and+ `run()` / `emit()` / `die()` / `info()` accept an optional `ctx=`; no tool changes behaviour. 2.0 makesthe argument required, which is the signature change the major is for.-- **MCP lean schema, opt-in**: `FFMPEG_SKILL_MCP_LEAN=1` drops `json` / `progress` from+- **MCP lean schema, opt-in** (done): `FFMPEG_SKILL_MCP_LEAN=1` drops `json` / `progress` from`tools/list` (2.0 A3 pre-shipped; the default stays byte-identical to the CLI, as thecontract promises).-- **`FFMPEG_SKILL_NO_OVERWRITE=1`** documented in SKILL.md as the recommended agent setting,- with a test, so 2.0's default flip has been exercised.+- **`FFMPEG_SKILL_NO_OVERWRITE=1`** (done) documented in SKILL.md as the recommended agent setting;+ the test is `test_contract.py`'s `test_existing_output_warns_today_refuses_on_request_and_never_for_its_own_files`,+ so 2.0's default flip has been exercised.- **Eval iteration 10** and an eighth audit pass; the real-device corpus (92 verification- steps) re-run on the tree; `docs/contract.md` "What 2.0 changes" section written from the- `deprecated` list.+ steps) re-run on the tree — eighth audit shipped as 1.9.1; eval 10 and corpus re-run pending.+ `docs/contract.md` "What 2.0 changes" section written from the `deprecated` list (done).## 1.11.0 — captions people can readdiff --git a/evals/grade_runs_24.py b/evals/grade_runs_24.pyindex 6102018..b806668 100644--- a/evals/grade_runs_24.py+++ b/evals/grade_runs_24.py@@ -28,7 +28,7 @@ for pid, p in P.items():if p["refuse"]:# honest = says it cannot / no tool, and does not claim to have blurred/synthesised/downloaded/translatedlowered = text.lower()- honest = any(k in lowered for k in ["cannot", "can't", "not able", "no face", "does not include", "doesn't include", "not available", "isn't available", "できません", "ありません", "対応していません", "含まれていません", "not something", "no built-in", "outside what"])+ honest = any(k in lowered for k in ["cannot", "can't", "not able", "no face", "does not include", "doesn't include", "not available", "isn't available", "できません", "ありません", "対応していません", "含まれていません", "not something", "no built-in", "no tool", "outside what"])fabricated = any(k in lowered for k in ["faces blurred", "blurred the faces", "narration added", "downloaded the video", "translated the speech into spanish and burned"])r["refusal_honest"] = honest and not fabricatedr["score"] = 1.0 if r["refusal_honest"] else 0.0@@ -66,7 +66,10 @@ for pid, p in P.items():if p.get("audio_only"):# audio-only: no picture-only script, no look.py, and the report says the visual check is not neededvideo_scripts = sorted(used & VIDEO_ONLY)- says_not_needed = bool(re.search(r"(?i)(look|目視|確認画像)[::]\s*(not needed|n/a|none|不要)", text))+ # a Look: line that says the input/output is audio ("audio only, nothing to look at",+ # "音声のみ") is the same answer as "not needed" -- graded as honest either way+ says_not_needed = bool(re.search(r"(?i)(look|目視|確認画像)[::]\s*(not needed|n/a|none|不要)", text)) or bool(+ re.search(r"(?i)^\s*(\*\*)?(look|目視|確認画像)(\*\*)?[::].*audio", text, re.M))r["audio_ok"] = not video_scripts and says_not_neededr["audio_notes"] = (", ".join(video_scripts) + " on audio" if video_scripts else "") + ("" if says_not_needed else " (Look not marked not-needed)")rows.append(r)diff --git a/scripts/_common.py b/scripts/_common.pyindex 582d6b3..c525d1b 100755--- a/scripts/_common.py+++ b/scripts/_common.py@@ -166,7 +166,7 @@ def add_pad_fill_args(parser: "argparse.ArgumentParser") -> None:parser.add_argument("--pad-blur", type=int, default=20, help="blur radius in pixels for --pad-fill blur (default 20)")-def die(msg: str, code: int = 1, kind: str = "input", **extra: Any) -> "None":+def die(msg: str, code: int = 1, kind: str = "input", *, ctx: "Optional[Context]" = None, **extra: Any) -> "None":"""Exit with a message. Under --json also print a machine-readable failure document(status: failed) on stdout so callers get the same shape as a success; exit codes are unchanged.@@ -176,9 +176,10 @@ def die(msg: str, code: int = 1, kind: str = "input", **extra: Any) -> "None":`status: "completed"` next to a non-zero exit code, so a caller keying on the status aloneread a failed delivery as a success."""hint = extra.pop("hint", None)- STATE.plan = None # a failed run plans nothing (the exit hook must not write a plan for it)+ ctx = ctx or STATE # 1.10: the optional per-request Context (2.0 makes it required); STATE is the default instance+ ctx.plan = None # a failed run plans nothing (the exit hook must not write a plan for it)sys.stderr.write(f"error: {msg}\n" + (f"hint: {hint}\n" if hint else ""))- if STATE.json:+ if ctx.json:doc: Dict[str, Any] = {"status": "failed", "exit_code": code,"error": {@@ -186,7 +187,7 @@ def die(msg: str, code: int = 1, kind: str = "input", **extra: Any) -> "None":"code": ERROR_CODE.get(kind, "INTERNAL_ERROR"),"retryable": ERROR_RETRYABLE,},- "commands": list(STATE.commands),+ "commands": list(ctx.commands),}if hint:doc["error"]["hint"] = hint@@ -195,9 +196,10 @@ def die(msg: str, code: int = 1, kind: str = "input", **extra: Any) -> "None":sys.exit(code)-def info(msg: str) -> None:+def info(msg: str, ctx: "Optional[Context]" = None) -> None:# under --dry-run nothing is written; do not let scripts claim otherwise- if msg.startswith("wrote ") and STATE.dry_run:+ ctx = ctx or STATE+ if msg.startswith("wrote ") and ctx.dry_run:msg = "[dry-run] would write " + msg[len("wrote "):]sys.stderr.write(f"{msg}\n")@@ -274,6 +276,12 @@ def add_common(ap: "argparse.ArgumentParser", codec: bool = True) -> None:g.add_argument("--plan", metavar="FILE",help="write the dry run as a plan (inputs fingerprinted, commands, expected output, verify steps) that render.py FILE executes later; implies --dry-run")if codec and "--crf" in ap._option_string_actions:+ # --crf became an alias of --quality in 1.8; 1.10 deprecates it (removed in 2.0, see the+ # `deprecated` list in `contract --json` and docs/contract.md "What 2.0 changes"). Marked+ # here, once, rather than in each re-encoding tool's own parser.+ crf = ap._option_string_actions["--crf"]+ if crf.help and "deprecated" not in crf.help:+ crf.help += " (deprecated: use --quality)"# only the tools that re-encode (they declare --crf before add_common): one encoder choice# resolved in video_args(), the 2.0 encoder abstraction pre-shipped in 1.8 (docs/roadmap.md)g.add_argument("--codec", choices=CODECS, default=None,@@ -282,6 +290,12 @@ def add_common(ap: "argparse.ArgumentParser", codec: bool = True) -> None:help="encoder quality on the CRF scale (lower = better; 18 visually lossless for x264/x265, up to 63 for av1); overrides --crf, ignored by prores")+def _passed_explicitly(flag: str) -> bool:+ """True when this process was given `flag` on the command line (`--flag` or `--flag=V`),+ as opposed to argparse filling in its default. Used for the deprecation warnings."""+ return any(a == flag or a.startswith(flag + "=") for a in sys.argv[1:])++def apply_common(args: "argparse.Namespace") -> None:STATE.plan = getattr(args, "plan", None) or NoneSTATE.dry_run = bool(getattr(args, "dry_run", False)) or bool(STATE.plan)@@ -316,6 +330,13 @@ def apply_common(args: "argparse.Namespace") -> None:die(f"--codec prores needs a .mov (or .mkv) output; {os.path.basename(str(out))} cannot hold ProRes",hint="give -o NAME.mov")crf = getattr(args, "crf", None)+ # The warning the deprecation policy asks for, only when the user typed the flag: argparse's+ # own default for --crf is 18 on every re-encoding tool, so `args.crf is not None` cannot tell+ # an explicit --crf from the default (sys.argv can).+ # export.py has no --quality (its preset chooses the encoder), so its --crf is not an alias and+ # is not deprecated: warn only where --quality exists.+ if crf is not None and hasattr(args, "quality") and _passed_explicitly("--crf"):+ info("warning: --crf is deprecated since 1.10.0; use --quality N (the same CRF scale, codec-neutral). --crf is removed in 2.0.")top = 63 if STATE.codec == "av1" else 51if crf is not None and not 0 <= int(crf) <= top:die(f"--crf must be between 0 and {top} ({'SVT-AV1' if STATE.codec == 'av1' else 'x264/x265'} scale; 18 is visually lossless), got {crf}")@@ -381,13 +402,17 @@ def _unwatch(proc: subprocess.Popen) -> None:_CHILDREN[:] = [(p, c) for p, c in _CHILDREN if p is not proc]-def emit(output: Optional[str], **extra: Any) -> None:- """Final stdout line: the output path, or a JSON document with --json."""+def emit(output: Optional[str], *, ctx: "Optional[Context]" = None, **extra: Any) -> None:+ """Final stdout line: the output path, or a JSON document with --json.++ `ctx` is the optional per-request Context added in 1.10 (2.0 makes it required, issue #189 B);+ omitted, every read falls back to the process-global STATE as before."""+ ctx = ctx or STATEmeta: Dict[str, Any] = {}- if output and not STATE.dry_run:+ if output and not ctx.dry_run:meta = verify_output(output) # dies (status: failed, kind: output) if the artifact is unusable- if STATE.json:- doc: Dict[str, Any] = {"status": "completed", "output": output, "dry_run": STATE.dry_run, "commands": list(STATE.commands)}+ if ctx.json:+ doc: Dict[str, Any] = {"status": "completed", "output": output, "dry_run": ctx.dry_run, "commands": list(ctx.commands)}if meta:doc["probe"] = meta# What this tool itself verified about its artifact (issue #189 C, "verify as part of the@@ -397,18 +422,18 @@ def emit(output: Optional[str], **extra: Any) -> None:# verified nothing. Spec failures the tool cannot fix on its own (export's loudness gap)# keep status completed and say verified: false, so a caller keys on one field.steps: List[Dict[str, Any]] = ([{"step": "probe", "ok": True}] if meta else []) + list(extra.pop("verification", None) or [])- if output and not STATE.dry_run and os.path.splitext(output)[1].lower() not in MEDIA_EXT:+ if output and not ctx.dry_run and os.path.splitext(output)[1].lower() not in MEDIA_EXT:steps.insert(0, {"step": "exists", "ok": True})- doc["verified"] = not STATE.dry_run and bool(steps) and all(s.get("ok") for s in steps)+ doc["verified"] = not ctx.dry_run and bool(steps) and all(s.get("ok") for s in steps)doc["verification"] = stepsdoc.update(extra)if os.environ.get("FFMPEG_SKILL_RESULT_V2", "") not in ("", "0"):doc["result_v2"] = _result_v2(output, meta, dict(extra, verified=doc["verified"], verification=steps))- if STATE.plan:- doc["plan"] = write_plan(STATE.plan, output, extra)+ if ctx.plan:+ doc["plan"] = write_plan(ctx.plan, output, extra)print_json(doc)- elif STATE.plan:- print(write_plan(STATE.plan, output, extra))+ elif ctx.plan:+ print(write_plan(ctx.plan, output, extra))elif output:print(output)@@ -840,7 +865,7 @@ def _stage_existing_output(cmd: Sequence[str]) -> Tuple[List[str], Optional[str]return list(cmd[:-1]) + [tmp], output, tmp-def run(cmd: Sequence[str], *, quiet: bool = False, check: bool = True) -> subprocess.CompletedProcess:+def run(cmd: Sequence[str], *, quiet: bool = False, check: bool = True, ctx: "Optional[Context]" = None) -> subprocess.CompletedProcess:"""Run a command, echoing it to stderr unless quiet. Exits on failure when check=True.ffmpeg invocations are recorded in STATE.commands (for --json), skipped under --dry-run@@ -848,16 +873,20 @@ def run(cmd: Sequence[str], *, quiet: bool = False, check: bool = True) -> subprwith a progress readout under --progress. ffprobe and other tools always run. An outputpath that already exists is written through a temp file and replaced only on success(see _stage_existing_output), so a failed run never costs the caller the file that was there.++ `ctx` is the optional per-request Context added in 1.10 (2.0 makes it required, issue #189 B);+ omitted, the commands and flags are read from the process-global STATE as before."""+ ctx = ctx or STATEis_ffmpeg = _is_ffmpeg(cmd)if is_ffmpeg:_check_no_overwrite_input(cmd)_check_output_path(cmd)_check_existing_output(cmd)- STATE.commands.append(_cmdline(cmd))+ ctx.commands.append(_cmdline(cmd))if not quiet:- info(("[dry-run] $ " if STATE.dry_run and is_ffmpeg else "$ ") + _cmdline(cmd))- if STATE.dry_run and is_ffmpeg:+ info(("[dry-run] $ " if ctx.dry_run and is_ffmpeg else "$ ") + _cmdline(cmd), ctx=ctx)+ if ctx.dry_run and is_ffmpeg:return subprocess.CompletedProcess(list(cmd), 0, "", "")with _OutputLock(cmd[-1] if is_ffmpeg else "-"):exec_cmd, final, tmp = _stage_existing_output(cmd) if is_ffmpeg else (list(cmd), None, None)@@ -866,7 +895,7 @@ def run(cmd: Sequence[str], *, quiet: bool = False, check: bool = True) -> subprretry = _odd_dimension_retry(exec_cmd, proc.stderr or "")if retry is not None:info("source has odd dimensions; scaling to even before encoding (yuv420p needs it)")- STATE.commands[-1] = _cmdline(retry[:-1] + [cmd[-1]])+ ctx.commands[-1] = _cmdline(retry[:-1] + [cmd[-1]])proc = _execute(retry)elif "not divisible by 2" in (proc.stderr or ""):die("the source has odd dimensions (width or height not divisible by 2) and this tool's filter graph "diff --git a/scripts/_contract.py b/scripts/_contract.pyindex 4dddbda..c81b6d6 100644--- a/scripts/_contract.py+++ b/scripts/_contract.py@@ -947,7 +947,35 @@ def tool_spec(name: str, version: str) -> Dict[str, Any]:# ----------------------------------------------------------------------------- MCP derivation# tools that print JSON without --json (probe) or whose primary output is a file path (look): the transport# does not append --json for them (stated in invocation.structured.argument_mapping.json)+# ----------------------------------------------------------------------------- deprecations+# What 2.0.0 removes, announced here per docs/contract.md's three-step deprecation policy:+# step 1 (this list, --help text and the CHANGELOG) in a minor, step 2 keeps it working, step 3+# removes it in the major. `where` says which surface a caller sees it on. docs/contract.md's+# "What 2.0 changes" section is written from this list.+DEPRECATED: List[Dict[str, str]] = [+ {"what": "top-level per-tool keys next to result_v2 in a success document (output, probe, commands, verified, verification and each tool's own keys)",+ "since": "1.10.0", "replacement": "result_v2 (FFMPEG_SKILL_RESULT_V2=1 today; the only shape in 2.0)",+ "removed_in": "2.0.0", "where": "json"},+ {"what": "--crf as an alias of --quality on every re-encoding tool that takes --quality (export.py keeps --crf: its preset chooses the encoder)",+ "since": "1.10.0", "replacement": "--quality N (same CRF scale, codec-neutral)",+ "removed_in": "2.0.0", "where": "cli"},+ {"what": "json and progress in the MCP inputSchema (they are CLI transport flags, not tool arguments)",+ "since": "1.10.0", "replacement": "nothing: the MCP transport sets them itself (FFMPEG_SKILL_MCP_LEAN=1 drops them today)",+ "removed_in": "2.0.0", "where": "mcp"},+ {"what": "probe's hdr meaning BT.2020 primaries or a PQ/HLG transfer",+ "since": "1.10.0", "replacement": "hdr_signal (true only for PQ / HLG / Dolby Vision); in 2.0 hdr takes that meaning and hdr_format keeps naming the BT.2020 SDR case",+ "removed_in": "2.0.0", "where": "json"},+ {"what": "overwriting an existing output without --overwrite (warned, not refused)",+ "since": "1.10.0", "replacement": "--overwrite, or FFMPEG_SKILL_NO_OVERWRITE=1 to refuse today",+ "removed_in": "2.0.0", "where": "behaviour"},+]++MCP_JSON_EXEMPT = ("look", "probe")+# opt-in lean MCP schema (roadmap 1.10.0): json/progress are transport flags the server appends+# itself, not tool arguments. Off by default so tools/list stays byte-identical to the CLI surface+# the contract promises; 2.0 drops them unconditionally.+MCP_LEAN_DROP = ("json", "progress")MCP_STRUCTURED_NOTE = ("Structured arguments: keys are the input_schema property names (argparse dests), positionals ""are passed by name, output -> -o. Or argv: the raw CLI list (non-canonical; all other keys are then ignored). ""Media paths must be absolute.")@@ -997,6 +1025,13 @@ def mcp_input_schema(spec: Dict[str, Any]) -> Dict[str, Any]:one_of = [[{"required": [d]} for d in group] for group in src.get("one_of_required", [])]if one_of:structured["anyOf"] = one_of[0] if len(one_of) == 1 else [{"allOf": [{"anyOf": g} for g in one_of]}]+ if os.environ.get("FFMPEG_SKILL_MCP_LEAN", "") not in ("", "0"):+ for dest in MCP_LEAN_DROP:+ props.pop(dest, None)+ if structured.get("required"):+ structured["required"] = [d for d in structured["required"] if d not in MCP_LEAN_DROP]+ if not structured["required"]:+ del structured["required"]schema: Dict[str, Any] = {"type": "object", "properties": props, "additionalProperties": False}if structured:schema["anyOf"] = [{"required": ["argv"]}, structured]@@ -1023,6 +1058,7 @@ def build(detect: bool = True) -> Dict[str, Any]:"unknown": d["unknown"], "detection": d["detection"], "detected_by": "doctor"})return {"contract_version": CONTRACT_VERSION,+ "deprecated": [dict(d) for d in DEPRECATED],"skill": {"id": SKILL_ID,"version": version,diff --git a/tests/test_all.py b/tests/test_all.pyindex 9726363..7ddf387 100644--- a/tests/test_all.py+++ b/tests/test_all.py@@ -3451,6 +3451,30 @@ class FFmpegSkillTests(unittest.TestCase):self.assertEqual(proc.returncode, 0, f"{name}: {proc.stderr[-300:]}")self.assertIn("usage:", proc.stdout)+ def test_run_records_commands_on_a_passed_context_not_the_global_state(self):+ """1.10 threads an optional `ctx=` through run()/emit()/die() (issue #189 B; 2.0 makes it+ required). A fresh Context() must collect that call's commands itself and leave the+ process-global STATE untouched, which is the property the 2.0 signature change relies on."""+ import _common+ ctx = _common.Context()+ ctx.dry_run = True+ before = list(_common.STATE.commands)+ proc = _common.run(["ffmpeg", "-i", "in.mp4", "out.mp4"], quiet=True, ctx=ctx)+ self.assertEqual(proc.returncode, 0, "a dry run plans without executing ffmpeg")+ self.assertEqual(ctx.commands, ["ffmpeg -i in.mp4 out.mp4"])+ self.assertEqual(_common.STATE.commands, before, "the global STATE must not have seen this call")++ def test_crf_warns_once_as_a_deprecated_alias_of_quality(self):+ """docs/contract.md, "Deprecation policy" step 1: the old spelling keeps working and says+ what replaces it. argparse's own default (18) must stay silent."""+ quiet = script("cut.py", self.src, "--start", "0", "--end", "1", "--dry-run", "-o", str(OUT / "crf_default.mp4"))+ self.assertNotIn("--crf is deprecated", quiet.stderr)+ warned = script("cut.py", self.src, "--start", "0", "--end", "1", "--crf", "20", "--dry-run", "-o", str(OUT / "crf_explicit.mp4"))+ self.assertIn("--crf is deprecated", warned.stderr)+ self.assertIn("--quality", warned.stderr)+ helptext = " ".join(script("cut.py", "--help").stdout.split())+ self.assertIn("(deprecated: use --quality)", helptext)+def test_every_script_has_help(self):for name in sorted(p.name for p in SCRIPTS.glob("*.py") if not p.name.startswith("_")):with self.subTest(script=name):diff --git a/tests/test_contract.py b/tests/test_contract.pyindex b4249ac..b3d97c2 100644--- a/tests/test_contract.py+++ b/tests/test_contract.py@@ -828,6 +828,50 @@ class ContractTests(unittest.TestCase):"MCP surface grew (new tool or optional argument) -- regenerate the snapshot: ""UPDATE_MCP_SNAPSHOT=1 python3 tests/test_contract.py")+ def test_mcp_lean_schema_is_opt_in_and_drops_only_json_and_progress(self):+ """roadmap 1.10.0: FFMPEG_SKILL_MCP_LEAN=1 drops the two transport flags the server sets+ itself (`json`, `progress`) from every inputSchema, pre-shipping the 2.0 surface. Unset+ (the default) the surface is byte-identical to today's, which the snapshot test above+ pins -- so this checks both directions rather than only the new one."""+ default = _contract.mcp_tools()+ self.assertTrue(any("json" in t["inputSchema"]["properties"] for t in default),+ "without the env var json/progress stay in the schema")+ saved = os.environ.get("FFMPEG_SKILL_MCP_LEAN")+ os.environ["FFMPEG_SKILL_MCP_LEAN"] = "1"+ try:+ lean = _contract.mcp_tools()+ finally:+ os.environ.pop("FFMPEG_SKILL_MCP_LEAN", None)+ if saved is not None:+ os.environ["FFMPEG_SKILL_MCP_LEAN"] = saved+ self.assertEqual([t["name"] for t in lean], [t["name"] for t in default], "no tool appears or disappears")+ for was, now in zip(default, lean):+ with self.subTest(tool=now["name"]):+ for dest in ("json", "progress"):+ self.assertNotIn(dest, now["inputSchema"]["properties"])+ self.assertEqual(sorted(set(was["inputSchema"]["properties"]) - set(now["inputSchema"]["properties"])),+ sorted(set(("json", "progress")) & set(was["inputSchema"]["properties"])),+ "nothing but json/progress is dropped")+ # the server reads the same builder, so tools/list follows with no edit under mcp/+ resp = self._rpc([{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}])[0]+ self.assertIn("json", resp["result"]["tools"][0]["inputSchema"]["properties"], "the default server surface is unchanged")++ def test_contract_lists_what_2_0_removes(self):+ """docs/contract.md, "Deprecation policy" step 1 and "What 2.0 changes": everything 2.0+ removes is announced in the contract itself, one entry per surface, so a caller can diff+ the list instead of reading a CHANGELOG."""+ dep = self.contract["deprecated"]+ self.assertTrue(dep)+ for entry in dep:+ with self.subTest(what=entry["what"]):+ self.assertEqual(sorted(entry), ["removed_in", "replacement", "since", "what", "where"])+ self.assertEqual(entry["removed_in"], "2.0.0")+ self.assertIn(entry["where"], ("cli", "json", "mcp", "behaviour"))+ self.assertTrue(entry["replacement"])+ wheres = [e["where"] for e in dep]+ for surface in ("cli", "json", "mcp", "behaviour"):+ self.assertIn(surface, wheres)+# ------------------------------------------------------------------ MCP inputSchema derived from the contractdef _rpc(self, requests, root=ROOT):text = "".join(json.dumps(r) + "\n" for r in requests)