Skip to content

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.

MCP tools/list derived from the contract: names, order, inputSchema and argument mapping from ToolSpecs (#19)

Shogo Kajiyama6b7188945e2e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 86adf53..daee0b8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,7 @@
- `--json` results now carry `"status": "completed"`; failures under `--json` also print `{"status": "failed", "error": {"kind", "message"}}` on stdout (stderr message and exit codes unchanged).
- `--dry-run` no longer writes the generated SRT (`caption.py --text`) or the HTML (`report.py`).
- MCP server lists `batch` (the one script it was missing); `tools/list` now equals the contract's tool list, and a test keeps it that way.
+- MCP `tools/list` is derived from the contract: no tool table or hand-written `inputSchema` in `mcp/server.py` any more. Names, order, `inputSchema` (translated from `ToolSpec.input_schema`: types, enums, defaults, descriptions, required fields, mutually exclusive groups, the non-canonical `argv` branch) and the structured-argument mapping all come from `scripts/_contract.py`. Tests: schema equality for all 21 tools, byte-identical `tools/list`, drift (add / remove / edit a script), and JSON-RPC round trips of probe, cut, silence, loudness, export and render built from the derived schema.
- Installer copies `package.json` so an installed skill knows its version, and answers `contract` / `doctor`.
- `tests/test_contract.py` (unit + integration, including a fake-ffmpeg dry-run guard and the real-device corpus when present), `evals/contract/`, `npm run release-check` extended.
- No new editing features; no script changed its media behaviour.
diff --git a/README.md b/README.md
index 9ffff41..6b967c7 100644
--- a/README.md
+++ b/README.md
@@ -18,7 +18,7 @@ npx ffmpeg-skill
- **Lossless when possible** — cuts and joins use stream copy by default; re-encoding only happens when it must (frame-accurate cuts, filters, format changes).
- **Cut & join** segments with `mm:ss` / `hh:mm:ss.ms` times.
- **Declarative edits** — describe the whole edit in a `project.json` (clips, transitions, captions, overlays, music, loudness, export, check) and re-render after every tweak.
-- **MCP server** — `mcp/server.py` exposes every script as an MCP tool over stdio (stdlib only) for Claude Desktop, Cursor or any MCP client.
+- **MCP server** — `mcp/server.py` exposes every script as an MCP tool over stdio (stdlib only) for Claude Desktop, Cursor or any MCP client; tool names, order and `inputSchema` are derived from the contract, so the MCP surface follows the scripts.
- **Batch / watch folder** — one recipe over a whole shoot with a content-hash cache; re-runs only touch what changed.
- **Optional local transcription** — `caption.py --transcribe` uses whisper.cpp / faster-whisper / openai-whisper when present; never required.
- **Brand kit** — one `brand.json` (fonts, colours, logo, safe margins, caption style) applied by captions, overlays, graphics and projects.
@@ -155,7 +155,7 @@ For agent frameworks that treat ffmpeg-skill as an execution skill: `contract --
{"mcpServers": {"ffmpeg-skill": {"command": "python3", "args": ["/Users/you/.claude/skills/ffmpeg-skill/mcp/server.py"]}}}
```
-`python3 mcp/server.py --list` prints the tools (the same set as `contract --json`); `--call probe '{"inputs": ["a.mp4"]}'` runs one from the shell.
+`python3 mcp/server.py --list` prints the tools (the same set, order and schemas as `contract --json`: the contract is the source of truth, MCP is the transport); `--call probe '{"inputs": ["a.mp4"]}'` runs one from the shell.
## Requirements
diff --git a/docs/contract.md b/docs/contract.md
index f4dd243..a00bcd2 100644
--- a/docs/contract.md
+++ b/docs/contract.md
@@ -159,10 +159,42 @@ before, and, when `--json` was given, on stdout:
## MCP relationship
-`mcp/server.py` is a transport. Its `tools/list` is the same set of names as the
-contract's tools (tested), and its argument mapping is the one the contract describes.
-The MCP `inputSchema` is deliberately loose; the contract's `input_schema` is the
-semantic definition. Do not treat the MCP schema as a second source of truth.
+`mcp/server.py` is a transport. It holds no tool table and no schema of its own:
+
+```
+argparse parser → ToolSpec.input_schema → contract → MCP tools/list inputSchema
+```
+
+At start-up the server builds the ToolSpecs (`_contract.build(detect=False)`) and
+derives each `tools/list` entry with `_contract.mcp_tool`: the name is the ToolSpec
+name, the order is the contract's sorted order, and `inputSchema` is
+`_contract.mcp_input_schema(ToolSpec)`. `tools/call` maps structured arguments to
+argv with the ToolSpec's `mcp.positional` and `mcp.argument_exceptions`. A new
+public script, a removed one, or a changed parser therefore changes the MCP surface
+with no edit to `mcp/`; `tests/test_contract.py` proves this by copying the skill,
+adding, removing and editing scripts, and reading `tools/list` again.
+
+### Translation, and what JSON Schema cannot say
+
+| ToolSpec.input_schema | MCP inputSchema |
+|---|---|
+| `properties.<dest>.type / enum / default / description / items` | copied as is |
+| `properties.<dest>.cli`, `.common` | dropped (ffmpeg-skill-only keys) |
+| `positional` | same properties, passed by name; description gets a `(positional N)` prefix |
+| `required` | `required` of the structured branch |
+| `mutually_exclusive` groups | `allOf: [{not: {required: [a, b]}} …]` for every pair |
+| `one_of_required` groups | `anyOf: [{required: [a]}, …]` |
+| raw `argv` compatibility | an `argv` array property; top-level `anyOf: [{required: [argv]}, <structured branch>]` |
+| `additionalProperties: false` | kept |
+
+Two things are documented rather than encoded, because JSON Schema has no way to
+express them: when `argv` is present every other key is ignored (stated in the `argv`
+description), and MCP has no notion of positional order, so positionals are named
+properties whose order is only informative. `%(default)s` help interpolation is
+already applied when the ToolSpec is built.
+
+The `tools/list` document is deterministic (byte-identical across processes and
+identical to the translation of `contract --json`), which the tests check.
## Consuming the contract from an agent
@@ -184,6 +216,6 @@ ffmpeg-skill contains no agent-specific code.
- `scripts/_contract.py`: the generator (`--json`, `--static`, `doctor`)
- `bin/install.js`: `ffmpeg-skill contract` and `ffmpeg-skill doctor`
-- `tests/test_contract.py`: schema, consistency (scripts = MCP = installer), dry-run, JSON shapes, verification policy, real-media run
+- `tests/test_contract.py`: schema, consistency (scripts = MCP = installer), MCP inputSchema derived from the contract (equality, determinism, drift, round trips), dry-run, JSON shapes, verification policy, real-media run
- `evals/contract/`: questions an agent must answer from the contract alone, with the expected answers checked against the live contract
- `tests/release_check.sh`: runs the contract from the packed and installed copies before a release
diff --git a/mcp/server.py b/mcp/server.py
index 1c7bc99..450811b 100755
--- a/mcp/server.py
+++ b/mcp/server.py
@@ -1,8 +1,10 @@
#!/usr/bin/env python3
"""ffmpeg-skill as an MCP server (stdio, JSON-RPC 2.0) — standard library only.
-Every script in ../scripts becomes a tool; arguments are passed as an argv list
-or as a flat object of flags. Results are the script's --json output.
+Every public script in ../scripts becomes a tool. Tool names, order, inputSchema and the
+structured-argument mapping all come from the contract (scripts/_contract.py); this file
+is only the transport. Arguments are passed as a flat object (keys = argparse dests) or,
+for CLI compatibility, as an argv list. Results are the script's --json output.
Run:
python3 mcp/server.py # stdio transport
@@ -20,42 +22,45 @@ HERE = Path(__file__).resolve().parent
SCRIPTS = HERE.parent / "scripts"
PROTOCOL_VERSION = "2024-11-05"
-TOOLS: Dict[str, str] = {
- "probe": "Inspect a media file: duration, fps/VFR, resolution, codecs, HDR, rotation, audio. Args: inputs (list), analyze (bool), compact (bool).",
- "cut": "Cut a range or several segments, lossless when possible. Args: input, start, end, duration, segments, accurate, output.",
- "fit": "Fit to a duration (speed/trim) and/or aspect (pad/crop). Args: input, duration, method, aspect, fit, width, fps, smooth, output.",
- "caption": "Burn SRT/ASS or timed text; animated/karaoke styles; brand. Args: input, srt, ass, text, animate, karaoke, font, size, position, brand, output.",
- "overlay": "Composite a logo/image/text with timing and fade. Args: input, image, text, logo, position, start, end, fade, opacity, scale, brand, output.",
- "graphics": "Motion-graphics templates: lower-third, title, chapter, progress, countdown, bug. Args: input, template, name, title, subtitle, start, end, brand, output.",
- "sync": "Detect offset between two recordings by audio, optional drift fix. Args: reference, second, fix_drift, replace_audio, trim_second, output.",
- "multicam": "Align N cameras/recorders and switch between them. Args: inputs (list), switch, auto, audio, fix_drift, output.",
- "audio": "Denoise/voice chain, music bed with ducking, fades, downmix, replace. Args: input, voice, denoise, music, duck, music_volume, fade_in, fade_out, downmix, replace, output.",
- "loudness": "Two-pass EBU R128 normalisation. Args: input, lufs, tp, measure_only, output.",
- "silence": "Remove dead air / list silences. Args: input, threshold, min_silence, margin, list, edl, output.",
- "join": "Concatenate clips with transitions, normalising size/fps/audio. Args: inputs (list), transition, duration, width, height, fps, output.",
- "color": "HDR→SDR tone mapping, LUTs, retag, strip Dolby Vision. Args: input, to_sdr, lut, retag, strip_dovi, tonemap, output.",
- "export": "Platform presets: youtube, youtube4k, reels, x, prores, h265, gif. Args: input, preset, fit, output.",
- "check": "Pre-delivery compliance per platform. Args: input, platform, no_loudness.",
- "scenes": "Scene changes, audio peaks, highlight proposals. Args: input, highlights, target, edl, sheet.",
- "look": "Contact sheet / frames / before-after PNG for visual checks. Args: input, at (list), tiles, compare, output.",
- "render": "Render a whole edit from project.json. Args: project, fast, stop_after, init.",
- "batch": "Apply a step recipe or render project to every file in a folder (content-hash cached). Args: folder, recipe, force, watch, work.",
- "verify": "Run the toolchain on real files and report PASS/FAIL. Args: paths (list), quick, report.",
- "report": "HTML delivery report. Args: after, before, platform, commands, notes, title, output.",
-}
-POSITIONAL = {"probe": ["inputs"], "sync": ["reference", "second"], "multicam": ["inputs"], "join": ["inputs"], "verify": ["paths"], "render": ["project"], "batch": ["folder"]}
+sys.path.insert(0, str(SCRIPTS))
+import _contract # noqa: E402 (the contract is the only source of tool names, schemas and argument mapping)
+
+_SPECS: Dict[str, Dict[str, Any]] = {}
+
+
+def specs() -> Dict[str, Dict[str, Any]]:
+ """ToolSpecs from the contract, generated once per process (argparse -> ToolSpec -> here)."""
+ if not _SPECS:
+ for spec in _contract.build(detect=False)["tools"]:
+ _SPECS[spec["name"]] = spec
+ return _SPECS
+
+
+class _Positional(dict):
+ """Positional argument names per tool, read from the contract (kept as a mapping for compatibility)."""
+
+ def __missing__(self, name: str) -> List[str]:
+ return list(specs()[name]["mcp"]["positional"]) if name in specs() else ["input"]
+
+ def get(self, name: str, default: Any = None) -> Any: # type: ignore[override]
+ return self[name] if name in specs() else default
+
+
+POSITIONAL: Dict[str, List[str]] = _Positional()
def build_argv(name: str, args: Dict[str, Any]) -> List[str]:
+ """Structured arguments -> argv, using the mapping the contract states (invocation.structured)."""
if isinstance(args.get("argv"), list):
argv = [str(a) for a in args["argv"]]
- if name not in ("look", "probe") and "--json" not in argv and "--help" not in argv:
+ if name not in _contract.MCP_JSON_EXEMPT and "--json" not in argv and "--help" not in argv:
argv.append("--json")
return argv
+ spec = specs().get(name)
+ exceptions = spec["mcp"]["argument_exceptions"] if spec else {}
argv: List[str] = []
args = dict(args)
- pos = POSITIONAL.get(name, ["input"])
- for key in pos:
+ for key in POSITIONAL[name]:
val = args.pop(key, None)
if val is None:
continue
@@ -66,11 +71,7 @@ def build_argv(name: str, args: Dict[str, Any]) -> List[str]:
for key, val in args.items():
if val is None or val is False:
continue
- flag = "--" + key.replace("_", "-")
- if key == "output":
- flag = "-o"
- if key == "lufs" and name == "loudness":
- flag = "-I"
+ flag = exceptions.get(key, "--" + key.replace("_", "-"))
if val is True:
argv.append(flag)
elif isinstance(val, list):
@@ -78,14 +79,14 @@ def build_argv(name: str, args: Dict[str, Any]) -> List[str]:
argv += [flag, str(v)]
else:
argv += [flag, str(val)]
- if name not in ("look", "probe") and "--json" not in argv and "--help" not in argv:
+ if name not in _contract.MCP_JSON_EXEMPT and "--json" not in argv and "--help" not in argv:
argv.append("--json")
return argv
def call_tool(name: str, args: Dict[str, Any]) -> Dict[str, Any]:
script = SCRIPTS / f"{name}.py"
- if not script.exists():
+ if name not in specs() or not script.exists():
return {"isError": True, "content": [{"type": "text", "text": f"unknown tool {name}"}]}
argv = build_argv(name, args or {})
proc = subprocess.run([sys.executable, str(script)] + argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
@@ -109,14 +110,8 @@ def call_tool(name: str, args: Dict[str, Any]) -> Dict[str, Any]:
def tool_list() -> List[Dict[str, Any]]:
- out = []
- for name, desc in TOOLS.items():
- out.append({
- "name": name,
- "description": desc + " Pass either named args (flags without dashes, underscores for hyphens) or argv (raw CLI list). Media paths must be absolute.",
- "inputSchema": {"type": "object", "properties": {"argv": {"type": "array", "items": {"type": "string"}, "description": "raw CLI arguments"}}, "additionalProperties": True},
- })
- return out
+ """tools/list: one entry per ToolSpec, in the contract's order, inputSchema derived from ToolSpec.input_schema."""
+ return [_contract.mcp_tool(spec) for spec in specs().values()]
def handle(req: Dict[str, Any]) -> Dict[str, Any]:
@@ -143,7 +138,7 @@ def version() -> str:
def main() -> int:
if "--list" in sys.argv:
for t in tool_list():
- print(f"{t['name']:10s} {t['description'].split(' Pass either')[0]}")
+ print(f"{t['name']:10s} {t['description'].split(' Structured arguments:')[0]}")
return 0
if "--call" in sys.argv: # debugging helper: --call NAME '{"input": "..."}'
i = sys.argv.index("--call")
diff --git a/scripts/_contract.py b/scripts/_contract.py
index f47bf4d..bcffa0f 100644
--- a/scripts/_contract.py
+++ b/scripts/_contract.py
@@ -372,6 +372,9 @@ def doctor() -> Dict[str, Any]:
# ----------------------------------------------------------------------------- contract
def tool_spec(name: str, version: str) -> Dict[str, Any]:
+ if name not in TOOL_META:
+ # a public script without metadata is drift: fail loudly instead of guessing its role or capabilities
+ raise RuntimeError(f"scripts/{name}.py is public but has no TOOL_META entry in scripts/_contract.py; add one (or prefix the file with '_')")
meta = TOOL_META[name]
parser = _capture_parser(HERE / f"{name}.py")
schema = input_schema(parser)
@@ -418,6 +421,74 @@ 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)
+MCP_JSON_EXEMPT = ("look", "probe")
+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.")
+
+
+def mcp_input_schema(spec: Dict[str, Any]) -> Dict[str, Any]:
+ """Translate a ToolSpec.input_schema into the JSON Schema an MCP tools/list entry carries.
+
+ Deterministic and lossless where JSON Schema can express argparse semantics:
+ - properties keep type / enum / default / description / items; the ffmpeg-skill-only keys
+ (`cli`, `common`) are dropped, positionals get a "(positional N)" prefix in the description;
+ - required fields, mutually exclusive groups (`not required [a, b]` per pair) and required
+ groups (`anyOf required`) apply to the structured branch;
+ - the raw-argv compatibility branch (`argv` present) lifts those constraints, which JSON Schema
+ expresses as a top-level anyOf of the two branches.
+ Not expressible and therefore documented rather than encoded: which keys the tool ignores when
+ `argv` is given (all of them), and argparse's `%(default)s` help interpolation (already applied).
+ """
+ src = spec["input_schema"]
+ props: Dict[str, Any] = {}
+ positional = list(src.get("positional", []))
+ for dest in sorted(src["properties"]):
+ p = src["properties"][dest]
+ out: Dict[str, Any] = {"type": p["type"]}
+ if p["type"] == "array":
+ out["items"] = dict(p.get("items", {"type": "string"}))
+ desc = p.get("description", "")
+ if dest in positional:
+ desc = f"(positional {positional.index(dest) + 1}) {desc}".strip()
+ if desc:
+ out["description"] = desc
+ for key in ("enum", "default"):
+ if key in p:
+ out[key] = p[key]
+ props[dest] = out
+ props["argv"] = {"type": "array", "items": {"type": "string"}, "description": "raw CLI arguments (non-canonical compatibility path; when present every other key is ignored)"}
+ structured: Dict[str, Any] = {}
+ if src.get("required"):
+ structured["required"] = list(src["required"])
+ all_of: List[Dict[str, Any]] = []
+ for group in src.get("mutually_exclusive", []):
+ for i, a in enumerate(group):
+ for b in group[i + 1:]:
+ all_of.append({"not": {"required": [a, b]}})
+ if all_of:
+ structured["allOf"] = all_of
+ 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]}]
+ schema: Dict[str, Any] = {"type": "object", "properties": props, "additionalProperties": False}
+ if structured:
+ schema["anyOf"] = [{"required": ["argv"]}, structured]
+ return schema
+
+
+def mcp_tool(spec: Dict[str, Any]) -> Dict[str, Any]:
+ """The MCP tools/list entry for a ToolSpec: name, description and the derived inputSchema."""
+ return {"name": spec["name"], "description": f"{spec['description']} {MCP_STRUCTURED_NOTE}".strip(), "inputSchema": mcp_input_schema(spec)}
+
+
+def mcp_tools(detect: bool = False) -> List[Dict[str, Any]]:
+ return [mcp_tool(spec) for spec in build(detect=detect)["tools"]]
+
+
def build(detect: bool = True) -> Dict[str, Any]:
version = skill_version()
tools = [tool_spec(n, version) for n in public_tools()]
diff --git a/tests/release_check.sh b/tests/release_check.sh
index fd97e1e..883d7d3 100755
--- a/tests/release_check.sh
+++ b/tests/release_check.sh
@@ -68,7 +68,16 @@ listed = subprocess.run([sys.executable, sys.argv[2] + "/mcp/server.py", "--list
names = {l.split()[0] for l in listed.splitlines() if l.strip()}
want = {t["name"] for t in doc["tools"]}
assert names == want, f"MCP {sorted(names ^ want)} differs from contract"
-print(f" ok ({len(names)} tools)")
+# tools/list inputSchema must be the translation of the installed contract's ToolSpecs
+sys.path.insert(0, sys.argv[2] + "/scripts")
+import _contract
+req = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "tools/list"}) + "\n"
+resp = json.loads(subprocess.run([sys.executable, sys.argv[2] + "/mcp/server.py"], input=req, stdout=subprocess.PIPE, text=True, check=True).stdout.splitlines()[0])
+mcp_tools = resp["result"]["tools"]
+assert [t["name"] for t in mcp_tools] == [t["name"] for t in doc["tools"]], "MCP order differs from contract"
+for entry, spec in zip(mcp_tools, doc["tools"]):
+ assert json.dumps(entry["inputSchema"], sort_keys=True) == json.dumps(_contract.mcp_input_schema(spec), sort_keys=True), f"{entry['name']}: inputSchema not derived from the contract"
+print(f" ok ({len(names)} tools, inputSchema derived from the contract)")
PY
python3 "$INST/scripts/_contract.py" doctor >/dev/null || { echo "FAIL: doctor reports missing required capabilities"; python3 "$INST/scripts/_contract.py" doctor; exit 1; }
echo " doctor ok"
diff --git a/tests/test_contract.py b/tests/test_contract.py
index 1310eb0..8b71b83 100644
--- a/tests/test_contract.py
+++ b/tests/test_contract.py
@@ -260,6 +260,125 @@ class ContractTests(unittest.TestCase):
resp = json.loads(proc.stdout.strip().splitlines()[0])
self.assertEqual(sorted(t["name"] for t in resp["result"]["tools"]), sorted(self.tools))
+ # ------------------------------------------------------------------ MCP inputSchema derived from the contract
+ def _rpc(self, requests, root=ROOT):
+ text = "".join(json.dumps(r) + "\n" for r in requests)
+ proc = subprocess.run([sys.executable, str(Path(root) / "mcp" / "server.py")], input=text, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ self.assertEqual(proc.returncode, 0, proc.stderr)
+ return [json.loads(line) for line in proc.stdout.strip().splitlines()]
+
+ @staticmethod
+ def _norm(obj):
+ return json.dumps(obj, sort_keys=True, separators=(",", ":"))
+
+ def test_mcp_input_schema_equals_translated_contract_schema(self):
+ listed = self._rpc([{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}])[0]["result"]["tools"]
+ self.assertEqual([t["name"] for t in listed], [t["name"] for t in self.contract["tools"]], "MCP order == contract order")
+ for entry in listed:
+ spec = self.tools[entry["name"]]
+ self.assertEqual(self._norm(entry["inputSchema"]), self._norm(_contract.mcp_input_schema(spec)), entry["name"])
+ self.assertEqual(self._norm(entry), self._norm(_contract.mcp_tool(spec)))
+ schema = entry["inputSchema"]
+ self.assertFalse(schema["additionalProperties"])
+ self.assertIn("argv", schema["properties"])
+ for dest, prop in spec["input_schema"]["properties"].items():
+ self.assertIn(dest, schema["properties"], f"{entry['name']}.{dest} lost in translation")
+ self.assertEqual(schema["properties"][dest]["type"], prop["type"])
+ for key in ("enum", "default"):
+ if key in prop:
+ self.assertEqual(schema["properties"][dest][key], prop[key])
+ self.assertNotIn("cli", schema["properties"][dest])
+ if spec["input_schema"]["required"] or spec["input_schema"].get("mutually_exclusive"):
+ self.assertEqual(schema["anyOf"][0], {"required": ["argv"]})
+ self.assertEqual(schema["anyOf"][1].get("required", []), spec["input_schema"]["required"])
+ # a group shows up as pairwise exclusion plus a required-one-of
+ color = next(t for t in listed if t["name"] == "color")["inputSchema"]["anyOf"][1]
+ self.assertIn({"not": {"required": ["to_sdr", "lut"]}}, color["allOf"])
+ self.assertIn({"required": ["to_sdr"]}, color["anyOf"])
+ # no hand-written schema or tool table is left in the transport
+ src = (ROOT / "mcp" / "server.py").read_text(encoding="utf-8")
+ self.assertNotIn("TOOLS:", src)
+ self.assertNotIn('"inputSchema": {"type"', src)
+
+ def test_mcp_tools_list_is_deterministic(self):
+ a = self._rpc([{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}])[0]
+ b = self._rpc([{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}])[0]
+ self.assertEqual(json.dumps(a), json.dumps(b), "tools/list must be byte-identical across processes")
+ c1 = sh(sys.executable, SCRIPTS / "_contract.py", "--json", "--static").stdout
+ c2 = sh(sys.executable, SCRIPTS / "_contract.py", "--json", "--static").stdout
+ self.assertEqual(c1, c2, "contract --json --static must be byte-identical")
+
+ def test_mcp_schema_drift_follows_the_scripts(self):
+ """Add a public script, remove one, change a parser: MCP must follow without any edit to mcp/."""
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp)
+ shutil.copytree(SCRIPTS, root / "scripts", ignore=shutil.ignore_patterns("__pycache__"))
+ shutil.copytree(ROOT / "mcp", root / "mcp", ignore=shutil.ignore_patterns("__pycache__"))
+ shutil.copy(ROOT / "package.json", root / "package.json")
+ (root / "scripts" / "cut.py").unlink()
+ # a new public script without metadata is reported, not silently dropped or guessed
+ (root / "scripts" / "zzztool.py").write_text("#!/usr/bin/env python3\nimport argparse\ndef main():\n argparse.ArgumentParser().parse_args()\nif __name__ == '__main__':\n main()\n", encoding="utf-8")
+ err = self._rpc([{"jsonrpc": "2.0", "id": 0, "method": "tools/list"}], root=root)[0]
+ self.assertIn("no TOOL_META entry", err["error"]["message"])
+ contract_py = (root / "scripts" / "_contract.py").read_text(encoding="utf-8")
+ contract_py = contract_py.replace('TOOL_META: Dict[str, Dict[str, Any]] = {', 'TOOL_META: Dict[str, Dict[str, Any]] = {\n "zzztool": dict(role="analysis", inputs=["x"], outputs=["y"], required=["ffprobe"], optional=[], video_required=False, audio_only=True, visual=False, verify=[], produces_artifact=False, idempotency="bit_exact", deterministic=True),', 1)
+ (root / "scripts" / "_contract.py").write_text(contract_py, encoding="utf-8")
+ (root / "scripts" / "zzztool.py").write_text(
+ '#!/usr/bin/env python3\n"""Drift probe tool."""\nimport argparse, sys, os\n'
+ 'sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))\nfrom _common import add_common, apply_common, emit\n'
+ 'def main():\n ap = argparse.ArgumentParser(description=__doc__)\n ap.add_argument("input")\n'
+ ' ap.add_argument("--knob", type=int, default=3, choices=[1, 2, 3], help="a knob")\n add_common(ap)\n'
+ ' args = ap.parse_args()\n apply_common(args)\n emit(None, knob=args.knob)\n return 0\n'
+ 'if __name__ == "__main__":\n sys.exit(main())\n', encoding="utf-8")
+ fit = (root / "scripts" / "fit.py").read_text(encoding="utf-8")
+ fit = fit.replace(' add_common(ap)', ' ap.add_argument("--drift-flag", action="store_true", help="added for the drift test")\n add_common(ap)', 1)
+ (root / "scripts" / "fit.py").write_text(fit, encoding="utf-8")
+ tools = {t["name"]: t for t in self._rpc([{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}], root=root)[0]["result"]["tools"]}
+ self.assertNotIn("cut", tools, "removed script still exposed")
+ self.assertIn("zzztool", tools, "new public script not exposed")
+ self.assertEqual(tools["zzztool"]["inputSchema"]["properties"]["knob"], {"type": "integer", "description": "a knob", "enum": [1, 2, 3], "default": 3})
+ self.assertIn("drift_flag", tools["fit"]["inputSchema"]["properties"], "parser change not reflected")
+ self.assertEqual(list(tools), sorted(tools), "order stays sorted after changes")
+ # the temporary tool also runs through the derived mapping
+ call = self._rpc([{"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "zzztool", "arguments": {"input": "x", "knob": 2}}}], root=root)[0]
+ self.assertEqual(call["result"]["structuredContent"]["knob"], 2)
+ unknown = self._rpc([{"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "_contract", "arguments": {}}}], root=root)[0]
+ self.assertTrue(unknown["result"]["isError"], "internal scripts are not callable")
+
+ def test_mcp_round_trips_built_from_the_derived_schema(self):
+ listed = {t["name"]: t["inputSchema"] for t in self._rpc([{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}])[0]["result"]["tools"]}
+ project = self.out("mcp_project.json")
+ project.write_text(json.dumps({"output": str(self.out("mcp_render.mp4")), "clips": [{"src": str(self.src), "in": 0, "out": 2}], "export": {"preset": "x"}}), encoding="utf-8")
+ calls = {
+ "probe": {"inputs": [str(self.wav)]},
+ "cut": {"input": str(self.src), "start": "1", "end": "3", "output": str(self.out("mcp_cut.mp4"))},
+ "silence": {"input": str(self.src), "list": True},
+ "loudness": {"input": str(self.wav), "lufs": -16.0, "tp": -1.5, "output": str(self.out("mcp_loud.wav"))},
+ "export": {"input": str(self.src), "preset": "x", "fast": True, "output": str(self.out("mcp_export.mp4"))},
+ "render": {"project": str(project), "fast": True},
+ }
+ reqs = []
+ for i, (name, args) in enumerate(calls.items(), start=10):
+ schema = listed[name]
+ for key, val in args.items():
+ self.assertIn(key, schema["properties"], f"{name}: {key} not in the derived schema")
+ jtype = schema["properties"][key]["type"]
+ py = {"string": str, "integer": int, "number": (int, float), "boolean": bool, "array": list}[jtype]
+ self.assertIsInstance(val, py, f"{name}.{key}")
+ for req in schema.get("anyOf", [{}, {}])[1].get("required", []):
+ self.assertIn(req, args, f"{name}: required {req} missing")
+ reqs.append({"jsonrpc": "2.0", "id": i, "method": "tools/call", "params": {"name": name, "arguments": args}})
+ for name, resp in zip(calls, self._rpc(reqs)):
+ self.assertNotIn("error", resp, name)
+ self.assertFalse(resp["result"].get("isError"), f"{name}: {resp['result']['content'][0]['text'][:300]}")
+ doc = resp["result"]["structuredContent"]
+ if name == "probe":
+ self.assertEqual(doc["audio"]["codec"], "pcm_s16le")
+ else:
+ self.assertEqual(doc["status"], "completed", name)
+ if doc.get("output"):
+ self.assertTrue(Path(doc["output"]).exists(), name)
+
def test_installer_payload_matches_contract(self):
js = (ROOT / "bin" / "install.js").read_text(encoding="utf-8")
payload = re.search(r"const PAYLOAD = \[(.*?)\];", js).group(1)