Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
61 commits
Select commit Hold shift + click to select a range
bacccf8
test(mcp): RED typed tool schema and structured result contract (#4445)
zackees Nov 9, 2026
a86793e
feat(mcp): typed tools, structured domain errors and schema snapshot …
zackees Nov 9, 2026
b23483d
docs(mcp): format generated schema by tool for review (#4445)
zackees Nov 9, 2026
c79b261
fix(mcp): preserve readiness errors and accurate operation hints (#4445)
zackees Nov 9, 2026
f988eb2
fix(mcp): retain legacy JSON text ordering and output descriptions (#…
zackees Nov 9, 2026
a11ee2a
test(mcp): RED device and pipeline counter baseline contract (#4446)
zackees Nov 9, 2026
bacedb8
feat(mcp): device, media and measured pipeline control (#4446)
zackees Nov 9, 2026
55af673
fix(mcp): guard camera readiness and track metric generations (#4446)
zackees Nov 9, 2026
278a1b1
style(mcp): format native readiness contract (#4446)
zackees Nov 9, 2026
861014e
test(mcp): RED deterministic condition waits and deadlines (#4447)
zackees Nov 9, 2026
7320a13
feat(mcp): bounded typed waits and start auto-wait (#4447)
zackees Nov 9, 2026
5213498
fix(mcp): reject late condition satisfaction after oversleep (#4447)
zackees Nov 9, 2026
a90961a
Merge branch 'infra/control-api-wait' into infra/control-api-transport
zackees Nov 9, 2026
3b16073
test(mcp): RED local endpoint contract (#4448)
zackees Nov 9, 2026
3754670
feat(mcp): attach to running OBS through private control sockets (#4448)
zackees Nov 9, 2026
c3dedb4
style(mcp): satisfy socket cleanup clippy gate (#4448)
zackees Nov 9, 2026
3a96a9d
test(mcp): RED typed client and probe transport contracts (#4449)
zackees Nov 9, 2026
7cfad72
feat(mcp): fluent typed client and automated A/V probe transport (#4449)
zackees Nov 9, 2026
2a04faf
Merge remote-tracking branch 'origin/master' into infra/control-api-d…
zackees Nov 9, 2026
3f1ef1c
fix(mcp): bind calldata ABI without linking OBS implementations (#4446)
zackees Nov 9, 2026
4cf6042
Merge branch 'infra/control-api-domains' into infra/control-api-wait
zackees Nov 9, 2026
d1ff018
Merge branch 'infra/control-api-wait' into infra/control-api-transport
zackees Nov 9, 2026
ecd7074
Merge branch 'infra/control-api-transport' into infra/control-api-client
zackees Nov 9, 2026
d70adda
fix(mcp): type frontend capabilities and stop before scene cleanup (#…
zackees Nov 10, 2026
6ec1489
test(mcp): RED cancellation drops buffered socket requests (#4448)
zackees Nov 10, 2026
c51bae5
test(mcp): RED bound the capture worker wait itself (#4449)
zackees Nov 10, 2026
bc1ba6f
fix(mcp): stop dispatching buffered requests after cancellation (#4448)
zackees Nov 10, 2026
492eb75
fix(mcp): bound ffmpeg worker waits before kill and reap (#4449)
zackees Nov 10, 2026
1ab4670
Merge remote-tracking branch 'origin/master' into infra/control-api-d…
zackees Nov 10, 2026
a02b707
Merge branch 'infra/control-api-domains' into infra/control-api-wait
zackees Nov 10, 2026
9fb1f5b
Merge branch 'infra/control-api-wait' into infra/control-api-transport
zackees Nov 10, 2026
2cc0bcc
fix(mcp): type frontend capabilities and stop before scene cleanup (#…
zackees Nov 10, 2026
b30179d
test(mcp): RED cancellation drops buffered socket requests (#4448)
zackees Nov 10, 2026
3f4ee74
fix(mcp): stop dispatching buffered requests after cancellation (#4448)
zackees Nov 10, 2026
13dcdb0
Merge branch 'infra/control-api-transport' into infra/control-api-client
zackees Nov 10, 2026
65c6207
fix(mcp): preserve frontend output preparation when attached (#4448)
zackees Nov 10, 2026
5fdef58
fix(mcp): preserve frontend output preparation when attached (#4448)
zackees Nov 10, 2026
f83a723
Merge branch 'infra/control-api-transport' into infra/control-api-client
zackees Nov 10, 2026
897e36c
test(mcp): RED tolerate future domain error fields (#4449)
zackees Nov 10, 2026
d8a5060
fix(mcp): preserve domain errors with forward-compatible fields (#4449)
zackees Nov 10, 2026
dfb1549
fix(mcp): preserve queued frontend start-stop ordering (#4448)
zackees Nov 10, 2026
1bde274
fix(mcp): preserve queued frontend start-stop ordering (#4448)
zackees Nov 10, 2026
5aa57c0
Merge branch 'infra/control-api-transport' into infra/control-api-client
zackees Nov 10, 2026
ba516ac
test(mcp): RED startup without reachable X or Wayland (#4464)
zackees Nov 10, 2026
62310aa
fix(mcp): GREEN start headless without an X server (#4464)
zackees Nov 10, 2026
284c4e4
Merge remote-tracking branch 'origin/master' into infra/control-api-h…
zackees Nov 10, 2026
f9e51fa
Merge remote-tracking branch 'origin/master' into infra/control-api-t…
zackees Nov 10, 2026
c47f1cf
Merge remote-tracking branch 'origin/master' into infra/control-api-c…
zackees Nov 10, 2026
1e7a9a5
Merge branch 'infra/control-api-headless-startup' into infra/control-…
zackees Nov 10, 2026
3b14236
ci: refresh client claim check after correcting PR reference
zackees Nov 10, 2026
1c29021
test(ci): RED require isolated transition-video scheduling (#4468)
zackees Nov 10, 2026
7beb525
ci: GREEN isolate transition video timing fixture (#4468)
zackees Nov 10, 2026
8d0b380
Merge remote-tracking branch 'origin/master' into infra/control-api-h…
zackees Nov 10, 2026
caa0110
Merge remote-tracking branch 'origin/master' into infra/control-api-t…
zackees Nov 10, 2026
2ea1e0f
Merge remote-tracking branch 'origin/master' into infra/control-api-c…
zackees Nov 10, 2026
4a631e3
Merge branch 'infra/control-api-transport' into infra/control-api-client
zackees Nov 10, 2026
1c1d8a9
Merge branch 'infra/control-api-headless-startup' into infra/control-…
zackees Nov 10, 2026
9b14acc
test(ci): RED keep uncached recovery in MCP plugin child (#4478)
zackees Nov 10, 2026
fbaaaf0
ci: GREEN preserve uncached recovery for MCP plugin builds (#4478)
zackees Nov 10, 2026
47af8b1
Merge remote-tracking branch 'origin/master' into infra/control-api-c…
zackees Nov 10, 2026
ad2f2e1
Merge remote-tracking branch 'origin/master' into infra/control-api-c…
zackees Nov 10, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions ci/test_tier2_build_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,32 @@ def test_recovery_preserves_first_failure_and_keeps_one_retry(self):
fields = output.read_text() if output.exists() else ''
self.assertEqual('cache-healthy=false' in fields, bool(daemon_status))

def test_mcp_plugin_child_inherits_uncached_recovery(self):
# The main retry succeeds, then validate.sh launches mcp-tests.sh.
# Its plugin builds must keep bypassing the daemon that just failed.
for daemon_status, expected in ((0, "unset"), (1, "1")):
with self.subTest(daemon_status=daemon_status), tempfile.TemporaryDirectory() as directory:
prefix = """
cmake() {
if [ ! -f "$build.calls" ]; then
echo 1 > "$build.calls"
echo 'FAILED: [code=125] first.o'
return 1
fi
echo 2 > "$build.calls"
return 0
}
"""
child = "\nbash -c 'printf \"MCP cache bypass: %s\\n\" \"${ZCCACHE_DISABLE:-unset}\"'\n"
result = subprocess.run(
['bash', '-euo', 'pipefail', '-c', prefix + self.recovery_script() + child],
env={**os.environ, 'SRC': str(ROOT), 'build': directory + '/build',
**self.zccache_stub(directory, str(daemon_status))},
capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertIn('MCP cache bypass: ' + expected, result.stdout)
self.assertEqual(Path(directory, 'build.calls').read_text().strip(), '2')

def test_recovery_clears_the_daemon_cool_down(self):
# zccache 1.15.5 keeps the cache root in its recovery cool-down after
# `zccache stop`, and the launcher then refuses even with
Expand Down
91 changes: 91 additions & 0 deletions ci/test_vcam_av_sync_mcp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
#!/usr/bin/env -S uv run --script
"""MCP probe transport tests, without devices, GUI or optional numerical packages."""
import asyncio
import importlib.util
import json
from pathlib import Path
import sys
import unittest
from unittest.mock import AsyncMock, Mock, patch

# Numerical analysis is not exercised by these transport tests.
spec = importlib.util.spec_from_file_location("vcam_probe_under_test", Path(__file__).with_name("vcam_av_sync.py"))
probe = importlib.util.module_from_spec(spec)
with patch.dict(sys.modules, {"numpy": Mock()}):
spec.loader.exec_module(probe)
McpSession = probe.McpSession

class Reader:
def __init__(self, reply): self.reply = reply
async def readline(self): return json.dumps(self.reply).encode() + b"\n"
class Writer:
def __init__(self): self.data = b""
def write(self, data): self.data += data
async def drain(self): pass

class McpProbeTransportTest(unittest.IsolatedAsyncioTestCase):
async def test_structured_reply_and_wire_request(self):
writer = Writer()
session = McpSession(Reader({"jsonrpc":"2.0", "id":1, "result":{"structuredContent":{"active":True}}}), writer)
self.assertEqual(await session.call("vcam_start", {"wait":True}), {"active":True})
request = json.loads(writer.data)
self.assertEqual(request["params"], {"name":"vcam_start", "arguments":{"wait":True}})

async def test_domain_failure_and_wrong_id_are_errors(self):
for reply in [
{"jsonrpc":"2.0", "id":1, "result":{"isError":True, "structuredContent":{"code":207, "message":"not ready"}}},
{"jsonrpc":"2.0", "id":9, "result":{}},
]:
with self.assertRaises(RuntimeError):
await McpSession(Reader(reply), Writer()).call("vcam_start")

async def test_probe_waits_and_always_removes_its_own_source(self):
async def reply(name, arguments=None):
return {"scene_get_current": {"name":"program"}, "screenshot":{"width":1280,"height":720},
"vmic_status":{"active":True}, "wait_for":{"satisfied":True}}.get(name, {})
session = Mock()
session.call = AsyncMock(side_effect=reply)
session.writer.wait_closed = AsyncMock()
recorder = Mock(returncode=0)
recorder.poll.return_value = 0
args = Mock(mcp_socket="/test/socket", seconds=0, device="/dev/test", source="test-mic")
with patch.object(probe, "connect_mcp", AsyncMock(return_value=session)), \
patch.object(probe.subprocess, "Popen", return_value=recorder), \
patch.object(probe.asyncio, "sleep", AsyncMock()), \
patch.object(probe, "analyze", return_value={"av_offset_ms":0}):
result = await probe.measure_mcp(args, Path("probe.mkv"), Path("capture.mkv"))
calls = session.call.await_args_list
names = [call.args[0] for call in calls]
self.assertLess(names.index("wait_for"), names.index("media_restart"))
self.assertEqual(names[-1], "source_remove")
created = next(call.args[1]["name"] for call in calls if call.args[0] == "source_create")
self.assertEqual(calls[-1].args[1]["name"], created)
self.assertEqual(result["transport"], "mcp")
session.writer.close.assert_called_once()

async def test_auto_falls_back_only_when_websocket_connection_is_absent(self):
import tempfile
args = Mock(transport="auto", url="ws://absent")
websocket = Mock(connect=AsyncMock(side_effect=ConnectionRefusedError()))
with tempfile.TemporaryDirectory() as directory, \
patch.dict(sys.modules, {"websockets":websocket}), \
patch.object(probe.tempfile, "mkdtemp", return_value=directory), \
patch.object(probe, "write_clip"), \
patch.object(probe, "measure_mcp", AsyncMock(return_value={"transport":"mcp"})) as fallback:
self.assertEqual(await probe.measure(args), {"transport":"mcp"})
fallback.assert_awaited_once()
args.transport = "websocket"
with self.assertRaises(ConnectionRefusedError):
await probe.measure(args)

async def test_capture_that_ignores_sigint_is_killed_and_reaped(self):
recorder = Mock()
recorder.poll.return_value = None
with patch.object(probe.asyncio, "to_thread", AsyncMock(side_effect=[probe.subprocess.TimeoutExpired("ffmpeg", 10), 0])) as wait:
await probe.stop_capture(recorder)
recorder.send_signal.assert_called_once_with(probe.signal.SIGINT)
recorder.kill.assert_called_once()
self.assertEqual(wait.await_count, 2)
self.assertEqual([entry.kwargs for entry in wait.await_args_list], [{"timeout":10}, {"timeout":5}])

if __name__ == "__main__": unittest.main()
155 changes: 151 additions & 4 deletions ci/vcam_av_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
# ///
"""A/V sync of the Linux Virtual Camera and its OBS Virtual Microphone.

Drives a running OBS over obs-websocket (no clicks, no computer use):
Drives OBS over a private MCP socket or obs-websocket (no clicks, no computer use):

uv run --script ci/vcam_av_sync.py measure [--seconds 12] [--url ws://127.0.0.1:4455]
uv run --script ci/vcam_av_sync.py analyze <capture.mkv> <clip events json>
Expand All @@ -31,6 +31,9 @@
import argparse
import asyncio
import json
import os
import stat
import uuid
import signal
import subprocess
import sys
Expand Down Expand Up @@ -155,14 +158,153 @@ async def obs_request(ws, kind: str, data: dict | None = None) -> dict:
return msg["d"].get("responseData") or {}


async def measure(args: argparse.Namespace) -> dict:
import websockets
class McpSession:
"""Bounded newline JSON-RPC exchange over an existing OBS socket."""

def __init__(self, reader, writer):
self.reader, self.writer = reader, writer
self.next_id = 0

async def rpc(self, method: str, params: dict) -> dict:
self.next_id += 1
request = {"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params}
self.writer.write(json.dumps(request).encode() + b"\n")
await self.writer.drain()
line = await asyncio.wait_for(self.reader.readline(), timeout=310)
if not line:
raise RuntimeError("MCP socket closed before response")
reply = json.loads(line)
if reply.get("jsonrpc") != "2.0" or reply.get("id") != self.next_id:
raise RuntimeError("MCP response version/ID mismatch")
if "error" in reply:
raise RuntimeError(f"MCP protocol error: {reply['error']}")
if "result" not in reply:
raise RuntimeError("MCP response has no result")
return reply["result"]

async def call(self, name: str, arguments: dict | None = None) -> dict:
result = await self.rpc("tools/call", {"name": name, "arguments": arguments or {}})
if result.get("isError"):
raise RuntimeError(f"{name}: {result.get('structuredContent', result)}")
if "structuredContent" not in result:
raise RuntimeError(f"{name}: missing structuredContent")
return result["structuredContent"]


async def connect_mcp(socket_path: str | None):
"""Attach without spawning a GUI or a second OBS."""
if socket_path is None:
runtime = os.environ.get("XDG_RUNTIME_DIR")
if not runtime:
raise RuntimeError("XDG_RUNTIME_DIR is unset; use --mcp-socket")
socket_path = str(Path(runtime) / "obs-studio-rust/control.sock")
metadata = Path(socket_path).lstat()
if not stat.S_ISSOCK(metadata.st_mode) or metadata.st_uid != os.geteuid() or metadata.st_mode & 0o077:
raise RuntimeError("MCP endpoint must be a private socket owned by this user")
reader, writer = await asyncio.open_unix_connection(socket_path, limit=32 * 1024 * 1024)
session = McpSession(reader, writer)
try:
await session.rpc("initialize", {"protocolVersion": "2025-06-18", "capabilities": {},
"clientInfo": {"name": "vcam-av-sync", "version": "1"}})
writer.write(json.dumps({"jsonrpc": "2.0", "method": "notifications/initialized"}).encode() + b"\n")
await writer.drain()
return session
except BaseException:
writer.close()
await writer.wait_closed()
raise


async def stop_capture(recorder) -> None:
"""Stop and reap a capture even when a device ignores SIGINT."""
if recorder.poll() is not None:
return
recorder.send_signal(signal.SIGINT)
try:
await asyncio.to_thread(recorder.wait, timeout=10)
except subprocess.TimeoutExpired:
recorder.kill()
await asyncio.to_thread(recorder.wait, timeout=5)


async def measure_mcp(args: argparse.Namespace, clip: Path, capture: Path) -> dict:
session = await connect_mcp(args.mcp_socket)
recorder = None
created = False
# A unique name prevents modifying or removing a user's existing source.
name = f"{SOURCE_NAME}-{uuid.uuid4().hex[:12]}"
try:
scene = (await session.call("scene_get_current"))["name"]
if not scene:
scene = f"vcam-av-sync-scene-{uuid.uuid4().hex[:12]}"
await session.call("scene_create", {"name": scene})
video = await session.call("screenshot", {"source": scene})
await session.call("vcam_start", {"wait": True, "timeout_ms": 5000, "audio_enabled": True})
mic = await session.call("vmic_status")
if mic.get("active") is not True:
raise RuntimeError(f"virtual microphone is not active: {mic}")
await session.call("source_create", {"scene": scene, "kind": "ffmpeg_source", "name": name,
"settings": {"is_local_file": True, "local_file": str(clip), "looping": True,
"restart_on_activate": True, "close_when_inactive": False}})
created = True
await session.call("scene_item_set_transform", {"scene": scene, "source": name,
"position": {"x": 0.0, "y": 0.0},
"scale": {"x": video["width"] / 640.0, "y": video["height"] / 360.0}})
state = await session.call("wait_for", {"condition": {"type": "media_state", "name": name, "state": "playing"},
"timeout_ms": 10000})
if not state["satisfied"]:
raise RuntimeError(f"probe did not start: {state}")
await session.call("stats_reset")
recorder = subprocess.Popen(
["ffmpeg", "-loglevel", "error", "-y", "-f", "v4l2", "-ts", "abs", "-i", args.device,
"-f", "pulse", "-wallclock", "1", "-fragment_size", "1920", "-i", args.source,
"-map", "0:v", "-map", "1:a", "-c:v", "ffv1", "-c:a", "pcm_f32le", "-copyts", str(capture)])
# Capture must already be listening before the known media timeline begins.
await asyncio.sleep(1.0)
await session.call("media_restart", {"name": name})
restarted = time.time()
await asyncio.sleep(args.seconds)
await stop_capture(recorder)
if recorder.returncode not in (0, 255):
raise RuntimeError(f"ffmpeg capture failed: {recorder.returncode}")
snapshot = await session.call("stats_get")
finally:
original_error = sys.exception()
try:
if created:
await session.call("source_remove", {"name": name})
except Exception as cleanup_error:
if original_error is None:
raise
original_error.add_note(f"probe cleanup also failed: {cleanup_error}")
finally:
try:
if recorder is not None:
await stop_capture(recorder)
finally:
session.writer.close()
await session.writer.wait_closed()
result = analyze(capture, EVENTS, restarted)
result.update({"capture": str(capture), "transport": "mcp", "stats": snapshot,
"measured_from": "independent ffmpeg v4l2/PulseAudio capture of flash/beep probe"})
return result


async def measure(args: argparse.Namespace) -> dict:
work = Path(tempfile.mkdtemp(prefix="vcam-av-sync-"))
clip = work / "probe.mkv"
write_clip(clip)
capture = work / "capture.mkv"
async with websockets.connect(args.url, subprotocols=["obswebsocket.json"]) as ws:
if args.transport == "mcp":
return await measure_mcp(args, clip, capture)
import websockets
try:
ws = await websockets.connect(args.url, subprotocols=["obswebsocket.json"], open_timeout=5)
except (OSError, TimeoutError):
if args.transport == "auto":
return await measure_mcp(args, clip, capture)
raise
try:
await ws.recv()
await ws.send(json.dumps({"op": 1, "d": {"rpcVersion": 1}}))
await ws.recv()
Expand Down Expand Up @@ -199,7 +341,10 @@ async def measure(args: argparse.Namespace) -> dict:
await asyncio.to_thread(recorder.wait)
finally:
await obs_request(ws, "RemoveInput", {"inputName": SOURCE_NAME})
finally:
await ws.close()
result = analyze(capture, EVENTS, restarted)
result["transport"] = "websocket"
result["capture"] = str(capture)
return result

Expand All @@ -224,6 +369,8 @@ def main(argv: list[str]) -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
sub = parser.add_subparsers(dest="cmd", required=True)
m = sub.add_parser("measure")
m.add_argument("--transport", choices=("auto", "websocket", "mcp"), default="auto")
m.add_argument("--mcp-socket", default=None)
m.add_argument("--url", default="ws://127.0.0.1:4455")
m.add_argument("--device", default="/dev/video9")
m.add_argument("--source", default="obs_virtual_microphone")
Expand Down
4 changes: 4 additions & 0 deletions docs/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -3075,3 +3075,7 @@ area.

- **Control socket** (#4456): private Unix MCP endpoint, `--mcp-attach` stdio proxy,
and an in-app frontend module that controls the existing OBS instance.

- **Typed control client and probe** (#4457): fluent Rust socket client and
`ci/vcam_av_sync.py --transport mcp` with automatic fallback when the websocket
service is absent, bounded capture shutdown, typed waits and probe cleanup.
21 changes: 21 additions & 0 deletions docs/rust-port/control-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,24 @@ Keep its stdin open for the test's lifetime; EOF stops the socket and libobs.
The attached backend resolves frontend scenes and output names on each call,
preserves coordinate settings, and queues scene changes through the graphics
thread so the frontend's UI mutation path cannot block shutdown.

## Clients and the A/V probe

```rust,ignore
let obs = obs_mcp::client::Client::attach(Default::default())?;
obs.vcam().start(obs_mcp::tools::control::StartInput {
wait: true, ..Default::default()
})?;
obs.wait_for(condition).timeout_ms(5000).call()?;
```

`uv run --script ci/vcam_av_sync.py measure --transport mcp --mcp-socket PATH`
creates a uniquely named media probe in the program scene, waits for playback,
starts independent ffmpeg v4l2/PulseAudio capture, restarts the clip and reports
A/V offset, per-path latency and `stats_get`. `source_remove` cleans up the probe.
`--transport auto` (default) falls back to MCP only when the websocket connection
cannot be opened. `--transport websocket` preserves the original path. Auth and
protocol failures are surfaced rather than retried with a second transport.
Capture timing is relative to the media restart response wall clock; the server
keeps end-to-end offset null until an independent capture probe measures it.
Run actual device capture only inside bosn. No GUI interaction is required.
Loading
Loading