DEV Community

Cover image for Keep FFmpeg Off the JSON-RPC Pipe
Lucas Vance
Lucas Vance

Posted on

Keep FFmpeg Off the JSON-RPC Pipe

Keep FFmpeg Off the JSON-RPC Pipe

At 3:11 a.m. the agent session died with no stack trace. Claude Desktop showed the ffmpeg-skill server as disconnected. The Node process was still alive, FFmpeg had not even been asked to cut a frame, and the only clue was a parser that had stopped accepting lines. I had adopted kajisho5/ffmpeg-skill as the local video path for coding agents: forty-two FFmpeg tools, a machine-readable contract, and an MCP server aimed at Claude Code, Cursor, and Codex. Cut, captions, reframe, loudness, platform export. No cloud, no API keys. The footage should never leave the machine. The integration failed on the pipe before it failed on pixels.

MCP on stdio is JSON-RPC, one message per line, and the client parser is strict. FFmpeg and ffprobe write progress, warnings, and sometimes whole documents to their own stdout. If any of that lands on the MCP process stdout — a stray console.log, a library that logs to stdout, a shell wrapper that merges file descriptors — the next frame is not valid JSON-RPC. The client drops the session. From the outside it is a silent crash. The second failure mode shows up only after the pipe is clean: a tool that returns raw ffprobe JSON. On a long file that document carries streams, chapters, disposition flags, and side data. Drop it into the tool result and the agent spends its context window reading a probe it will never reason over, then cannot finish the cut.

The contract is the part worth keeping. The agent should call a narrow verb and get a path plus a short summary. I run a thin TypeScript adapter on @modelcontextprotocol/sdk in front of a local checkout of the repo. I did not write ffmpeg-skill; I only own the pipe discipline around it.

The machine-readable contract is what makes that split enforceable. Each tool declares inputs the model is allowed to fill — input path, in-point, out-point, target loudness, export preset — and a result schema small enough to quote back. I keep the adapter's return values inside that schema. Anything the contract does not list, including filter graphs and raw packets, stays on disk where a later tool can read it by path.

Two rules made the adapter survivable. The MCP process stdout is exclusively the transport. FFmpeg is spawned with an argv array, never a shell string, and its stdout is captured into the job folder. Diagnostics, including caught exceptions, go to stderr, which both Claude Desktop and Cursor already treat as server logs. Tool results are a budget, not a dump. A probe returns duration, codecs, frame size, and the sidecar path. A render returns the output path, the exit code, and a short stderr tail only when the exit code is non-zero.

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

const server = new McpServer({ name: "ffmpeg-skill", version: "0.1.0" });

server.tool(
  "media_probe",
  "Summarize a local file. Full ffprobe JSON is written to a sidecar and is not returned.",
  { path: z.string() },
  async ({ path }) => {
    const summary = await probeSummary(path); // argv spawn; stdout captured, never inherited
    return { content: [{ type: "text", text: JSON.stringify(summary) }] };
  },
);

async function main() {
  await server.connect(new StdioServerTransport());
}
main().catch((err) => {
  console.error(err);
  process.exit(1);
});
Enter fullscreen mode Exit fullscreen mode

probeSummary has to be boring on purpose: duration, video codec, width, height, audio codec, sample rate, sidecar path. If that function returns the raw document, the next model turn is already lost, captions or not. Resolve ffmpeg and ffprobe from PATH unless your checkout already documents otherwise. Do not invent flags the upstream server does not read.

The spawn is where a live child looks dead. Node stdio buffers are small. Inherit stdout, or capture it and forget to drain stderr while FFmpeg writes progress, and the child blocks when the kernel buffer fills. No JSON-RPC result is written. The client reads until timeout and reports a dead server. Drain both descriptors, keep a short stderr tail in memory, and spill the rest into the job directory. Never pull a multi-gigabyte intermediate into the MCP heap.

Overlapping calls are the race a clean pipe does not stop. Stdio serializes JSON-RPC frames. It does not serialize child processes. Two tools that share a sidecar name will clobber each other, and a path has no compare-and-swap that makes a global current output safe. Give each invocation its own job directory, keyed by a fresh id. That directory is the only state the call may mutate.

Claude Desktop needs a real stdio child. This is the block that stopped the merged-stream failure, in claude_desktop_config.json. Point args at the MCP entry your local build of ffmpeg-skill actually emits.

{
  "mcpServers": {
    "ffmpeg-skill": {
      "command": "node",
      "args": ["/opt/src/ffmpeg-skill/dist/mcp.js"]
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Cursor takes the same command and args under its MCP server settings. Do not launch through sh -c with 2>&1. The first FFmpeg warning will poison the parser again.

A non-zero FFmpeg status is an edit failure, not a dead transport. Map it to a tool error that carries a truncated stderr tail. The agent can retry that call. It cannot retry a process that threw before any JSON-RPC error was written, because the client blocks on stdout until the read times out. Catch every tool body. When I separate model latency from tool cost, calls go through a multi-provider fallback with baseURL: "https://b-lost.com/v1" on B-Lost's relay gateway, and that hop is only a latency baseline. It does not shrink tool results. An untrimmed probe still dominates the window no matter which provider answers. On that hop, back off on 429. Use a short jittered retry only for 502 or 503. Neither code repairs a poisoned stdio stream.

The trade-off is local and blunt. You inherit FFmpeg, fonts for burned-in captions, and disk for intermediates. You drop upload latency and key management. Forty-two tools is a wide menu; I expose probes first and writers second, because a smaller surface is what stops a reframe call when the edit was a cut. Returning paths instead of payloads makes the agent worse at inspecting a frame unless you add a separate thumbnail tool with a hard byte cap. That cap is worth it. A base64 PNG inside a tool result is how a short edit session turns into a context overflow.

The hardest operational dilemma is not which filter to expose. It is how little the model is allowed to see and still choose the next cut. Starve the summary and it invents timestamps. Hand it the full probe and the session dies of context. I still do not have a schema that stays honest on variable-frame-rate phone footage and fits in one tool result.

Where do you draw that line when the file is long, the client parser is strict, and the only durable state is a directory the model cannot open?

Top comments (0)