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
fix(safety): refuse to overwrite input via a same-file-different-string output path (#69)
Shogo Kajiyama9c432fba9344
diff --git a/README.md b/README.mdindex cea82fb..daaf8fb 100644--- a/README.md+++ b/README.md@@ -246,7 +246,9 @@ The contract is generated from the code that runs, not maintained beside it. For{"mcpServers": {"ffmpeg-skill": {"command": "python3", "args": ["/Users/you/.claude/skills/ffmpeg-skill/mcp/server.py"]}}}```-`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 21 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.+On Windows, `python3` is only on PATH if Python was installed from the Microsoft Store; a python.org install exposes `python` (or the `py` launcher) instead — if your MCP client reports the server failed to start, change `"command"` above to `"python"` (or the full path from `where python`).++`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 28 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.### Capability detectiondiff --git a/mcp/server.py b/mcp/server.pyindex 450811b..f2273da 100755--- a/mcp/server.py+++ b/mcp/server.py@@ -10,6 +10,8 @@ Run:python3 mcp/server.py # stdio transportClaude Desktop / Claude Code config example:{"mcpServers": {"ffmpeg-skill": {"command": "python3", "args": ["/path/to/ffmpeg-skill/mcp/server.py"]}}}+ On Windows, use "python" instead of "python3" unless Python was installed from the Microsoft+ Store (a python.org install exposes python/py, not python3) -- see README.md's MCP section."""import jsonimport osdiff --git a/scripts/_common.py b/scripts/_common.pyindex 454f178..69cc962 100755--- a/scripts/_common.py+++ b/scripts/_common.py@@ -41,12 +41,52 @@ INSTALL_HINTS = {}+# `kind` (below) has been the only machine-readable failure axis since 0.1: a flat, 4-value+# vocabulary (input / missing_tool / ffmpeg / output) set at the ~7 call sites that ever pass one+# explicitly, defaulting to "input" everywhere else. `ERROR_CODE` is an additive, purely+# informational refinement layered on top for agents that want a stable enum to switch on instead+# of pattern-matching `kind` strings -- it is a static 1:1 relabelling of the exact same 4 buckets,+# not a new taxonomy. It intentionally does NOT introduce categories this codebase cannot actually+# distinguish today (e.g. a separate ffprobe-vs-ffmpeg code, or an environment-vs-content-cause+# split of ffmpeg failures): every ffmpeg subprocess failure is currently one undifferentiated+# bucket regardless of whether ffmpeg rejected a bad filter argument or died from a full disk,+# and every "kind": "input" failure covers both a missing file and a bad flag value alike. Adding+# codes for distinctions the code can't actually make would be guessing, not reporting -- if a+# future call site can genuinely tell capability-missing apart from bad-argument (see doctor()'s+# available/missing/unknown states, which already model this for detection but aren't wired into+# any die() call), split ERROR_CODE then, with evidence, not speculatively now.+ERROR_CODE = {+ "input": "INPUT_INVALID",+ "missing_tool": "DEPENDENCY_MISSING",+ "ffmpeg": "FFMPEG_EXECUTION_FAILED",+ "output": "OUTPUT_INVALID",+}++# None of the four kinds above are retryable in practice: an "input"/"missing_tool" failure is+# always deterministic (the same bad path or absent binary fails identically every time), and a+# "ffmpeg"/"output" failure -- while it COULD in principle be caused by a transient environment+# condition (full disk, OOM) rather than a bad command -- is never distinguishable from a+# deterministic content-cause failure without exit-code/stderr sniffing this codebase does not do.+# Reporting retryable=True for a code we can't actually back up would invite an agent into a blind+# retry loop against a command that will fail the same way every time; false-for-everything is the+# honest answer until real sniffing exists to justify anything else.+ERROR_RETRYABLE = False++def die(msg: str, code: int = 1, kind: str = "input") -> "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."""sys.stderr.write(f"error: {msg}\n")if STATE.json:- print_json({"status": "failed", "exit_code": code, "error": {"kind": kind, "message": msg}, "commands": list(STATE.commands)})+ print_json({+ "status": "failed", "exit_code": code,+ "error": {+ "kind": kind, "message": msg,+ "code": ERROR_CODE.get(kind, "INTERNAL_ERROR"),+ "retryable": ERROR_RETRYABLE,+ },+ "commands": list(STATE.commands),+ })sys.exit(code)@@ -161,6 +201,33 @@ def _fail(cmd: Sequence[str], returncode: int, stderr: str) -> None:die(f"command failed ({returncode}): {cmd[0]}\n{tail}", code=returncode or 1, kind="ffmpeg")+def _check_no_overwrite_input(cmd: Sequence[str]) -> None:+ """Refuse an ffmpeg command whose output path resolves to the same file as one of its+ inputs. ffmpeg's own "Output same as Input" guard only catches byte-identical path+ strings; a relative/absolute pair, a leading "./", a redundant ".." segment, or a symlink+ all resolve to the same file but pass that check, so "-o ./same.mp4" on an input opened as+ "same.mp4" would otherwise silently let ffmpeg's -y clobber the source mid-encode. Every+ write-side script routes through this one run() choke point rather than each computing its+ own output path defensively, so the guard lives here once instead of at 25+ call sites."""+ output = cmd[-1]+ if output in ("-", "pipe:0", "pipe:1") or output.startswith("pipe:") or output.startswith("-"):+ return+ try:+ out_real = os.path.realpath(output)+ except OSError:+ return+ for i, a in enumerate(cmd):+ if a == "-i" and i + 1 < len(cmd):+ inp = cmd[i + 1]+ try:+ if os.path.realpath(inp) == out_real:+ die(f"refusing to run: output {output!r} is the same file as input {inp!r} "+ f"(would overwrite it while ffmpeg is still reading it) -- choose a different --output/-o path",+ kind="input")+ except OSError:+ continue++def run(cmd: Sequence[str], *, quiet: bool = False, check: bool = True) -> subprocess.CompletedProcess:"""Run a command, echoing it to stderr unless quiet. Exits on failure when check=True.@@ -170,6 +237,7 @@ def run(cmd: Sequence[str], *, quiet: bool = False, check: bool = True) -> subpr"""is_ffmpeg = _is_ffmpeg(cmd)if is_ffmpeg:+ _check_no_overwrite_input(cmd)STATE.commands.append(_cmdline(cmd))if not quiet:info(("[dry-run] $ " if STATE.dry_run and is_ffmpeg else "$ ") + _cmdline(cmd))diff --git a/scripts/_contract.py b/scripts/_contract.pyindex 07246f8..ac1575d 100644--- a/scripts/_contract.py+++ b/scripts/_contract.py@@ -196,7 +196,7 @@ REENCODE_META: Dict[str, Dict[str, str]] = {"caption": dict(video="conditional", audio="conditional", note="--mode burn (default) always re-encodes both streams to render pixels; --mode mux copies video and audio untouched and only adds a subtitle stream"),"overlay": dict(video="always", audio="always"),"graphics": dict(video="always", audio="always"),- "sync": dict(video="never", audio="conditional", note="video is never touched; audio is copied or re-encoded depending on --trim-second / --replace-audio / --fix-drift"),+ "sync": dict(video="conditional", audio="conditional", note="video is -c:v copy only for --trim-second when the second file started earlier (offset<0) and the copy succeeds; it is re-encoded whenever --replace-audio's stream copy fails, or in --trim-second when the second file started later (offset>=0, the common case) or --fix-drift is used"),"multicam": dict(video="always", audio="always"),"audio": dict(video="never", audio="always", note="video stream is always -c:v copy when present; this tool's job is the audio"),"loudness": dict(video="never", audio="always"),diff --git a/tests/test_contract.py b/tests/test_contract.pyindex 700960a..447d8c8 100644--- a/tests/test_contract.py+++ b/tests/test_contract.py@@ -356,6 +356,10 @@ class ContractTests(unittest.TestCase):self.assertEqual((self.tools["caption"]["reencodes_video"], self.tools["caption"]["reencodes_audio"]), ("conditional", "conditional"))self.assertEqual((self.tools["loudness"]["reencodes_video"], self.tools["loudness"]["reencodes_audio"]), ("never", "always"))self.assertEqual((self.tools["probe"]["reencodes_video"], self.tools["probe"]["reencodes_audio"]), ("never", "never"))+ # sync was declared video="never" but --trim-second re-encodes video whenever the second+ # file starts later (offset >= 0, the common case) or --fix-drift is used -- only the+ # offset<0 stream-copy path leaves video untouched (Hardening Phase 2 P0).+ self.assertEqual((self.tools["sync"]["reencodes_video"], self.tools["sync"]["reencodes_audio"]), ("conditional", "conditional"))# color is conditional, not "always": --strip-dovi and --retag are a stream copy of both# streams (see test_color_strip_dovi_and_retag_are_stream_copies below), only --to-sdr /# --lut / --correct re-encode.@@ -676,6 +680,15 @@ class ContractTests(unittest.TestCase):self.assertTrue(doc["error"]["message"], name)if kind:self.assertEqual(doc["error"]["kind"], kind, f"{name}: {doc['error']}")+ # "code"/"retryable" are additive to "kind" (Hardening Phase 2): a static, honest+ # relabelling of the same 4 kinds, not a new taxonomy the code can't actually back up --+ # see _common.ERROR_CODE. Every failure carries both; retryable is always False today+ # since no kind is distinguishable from a deterministic content-cause failure without+ # exit-code/stderr sniffing this codebase doesn't do.+ import _common+ self.assertIn("code", doc["error"], f"{name}: {doc['error']}")+ self.assertEqual(doc["error"]["code"], _common.ERROR_CODE.get(doc["error"]["kind"], "INTERNAL_ERROR"))+ self.assertEqual(doc["error"]["retryable"], False, f"{name}: {doc['error']}")if code:self.assertEqual(proc.returncode, code)self.assertIn("error:", proc.stderr)@@ -694,6 +707,20 @@ class ContractTests(unittest.TestCase):self._fails("fit", self.src, "--duration", "3", "--fps", "0", "-o", self.out("f8.mp4"), kind="input")self.assertEqual(sorted(p.name for p in self.work.glob("f[0-9].*")), [], "no partial outputs left behind")+ def test_output_path_resolving_to_the_same_file_as_input_is_refused(self):+ """A byte-different but same-file output path ("./x.mp4" for an input opened as "x.mp4",+ or an absolute/relative pair) is not caught by ffmpeg's own "Output same as Input" guard,+ which only compares path strings. Without our own realpath check, "-o ./same.mp4" would+ silently let ffmpeg's -y clobber the source mid-encode (Hardening Phase 2 P0)."""+ clone = self.out("clobber_src.mp4")+ shutil.copyfile(self.src, clone)+ before = self._sha(clone)+ same_but_different_string = self.work / ("." + os.sep + clone.name)+ doc = self._fails("crop", clone, "--x", "0", "--y", "0", "--width", "32", "--height", "32",+ "-o", same_but_different_string, kind="input")+ self.assertIn("same file", doc["error"]["message"])+ self.assertEqual(self._sha(clone), before, "input must be byte-identical after the refusal")+def test_ffmpeg_failures_are_loud(self):doc = self._fails("color", self.src, "--lut", self.badlut, "--fast", "-o", self.out("g1.mp4"), kind="ffmpeg")self.assertTrue(any("ffmpeg" in c for c in doc["commands"]), "the failing command is reported")