From bacccf85ce33879bc0eb4644422db7d4345f287c Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 13:31:23 -0800 Subject: [PATCH 01/39] test(mcp): RED typed tool schema and structured result contract (#4445) --- Cargo.lock | 65 ++++++++++++++++++++++++++++++++ Cargo.toml | 1 + docs/rust-port/control-api.md | 52 +++++++++++++++++++++++++ rust/obs-data/Cargo.toml | 2 + rust/obs-mcp/Cargo.toml | 1 + rust/obs-mcp/src/server/mod.rs | 3 ++ rust/obs-mcp/src/server/typed.rs | 42 +++++++++++++++++++++ rust/obs-mcp/tests/mcp/main.rs | 2 + rust/obs-mcp/tests/mcp/typed.rs | 36 ++++++++++++++++++ 9 files changed, 204 insertions(+) create mode 100644 docs/rust-port/control-api.md create mode 100644 rust/obs-mcp/src/server/typed.rs create mode 100644 rust/obs-mcp/tests/mcp/typed.rs diff --git a/Cargo.lock b/Cargo.lock index ba1c697b1c..e3f6de6738 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -268,6 +268,12 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + [[package]] name = "either" version = "1.19.0" @@ -590,6 +596,8 @@ dependencies = [ "obs-source-seam", "obs-util", "proptest", + "schemars", + "serde", "serde_json", ] @@ -651,6 +659,7 @@ dependencies = [ "flate2", "libc", "obs-sys", + "schemars", "serde", "serde_json", ] @@ -926,6 +935,26 @@ dependencies = [ "rand_core 0.9.5", ] +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "regex" version = "1.13.1" @@ -989,6 +1018,31 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "schemars" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" +dependencies = [ + "dyn-clone", + "ref-cast", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 3.0.6", +] + [[package]] name = "serde" version = "1.0.229" @@ -1019,6 +1073,17 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "serde_derive_internals" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "serde_json" version = "1.0.151" diff --git a/Cargo.toml b/Cargo.toml index c400f583c5..652484dc46 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,6 +26,7 @@ memchr = { version = "=2.8.3", default-features = false } pkg-config = { version = "=0.3.34", default-features = false } proptest = { version = "=1.11.0", default-features = false } serde = { version = "=1.0.229", default-features = false } +schemars = { version = "=1.2.3" } serde_json = { version = "=1.0.151", default-features = false } sha2 = { version = "=0.11.0", default-features = false } tempfile = { version = "=3.27.0", default-features = false } diff --git a/docs/rust-port/control-api.md b/docs/rust-port/control-api.md new file mode 100644 index 0000000000..22c3827937 --- /dev/null +++ b/docs/rust-port/control-api.md @@ -0,0 +1,52 @@ +# Control API + +Extend obs-mcp; preserve existing tool names, successful text/image payloads, +headless stdio and the unchanged C++ obs-websocket plugin. New tools use +`domain_verb`: `vcam_start`, `vcam_stop`, `vcam_status`, `vmic_status`, +`media_restart`, `media_status`, `stats_get`, `stats_reset`, `wait_for`, +`pipeline_dump`. + +## Contract + +TypedTool declares serde/schemars input/output structs, NAME and ANNOTATIONS. +Inputs reject unknown fields and default optional fields. The Tool adapter +publishes inputSchema/outputSchema and returns structuredContent alongside JSON +text (and screenshot image content). The committed schema snapshot must match +schemas generated from the registered types. Backend additions use request and +response structs, never positional multi-argument methods. + +Malformed requests and typed arguments are JSON-RPC errors. Domain failures +return isError and ToolError {code, category, message, retryable}, using +obs-websocket v5 status ranges: 5xx missing/not ready, 6xx state, 7xx processing. +Read operations have readOnlyHint; start/stop are idempotent. + +## State and measurements + +`wait_for {condition, timeout_ms}` first checks, then waits within the deadline; +it returns {satisfied, elapsed_ms, last_value}. Condition is a typed enum: +OutputState {output,state}, SourceActive {name}, MediaState {name,state}, +StatAtMost {metric,value}. Start accepts optional wait for bounded auto-wait. +Media uses obs_source_media_*; vcam uses virtualcam_output and its private +proc_handler. stats_get reports per-stage render/vcam/vmic {live, +latency_min_ns, latency_max_ns, frames_total, frames_dropped, xruns}, render +counters and {av_offset_ms, measured_from}. Unmeasured values remain unavailable; +queue estimates never masquerade as end-to-end measurements. stats_reset defines +a new counter baseline. pipeline_dump reports the current graph. + +## Attachment + +A loadable in-app module serves the same newline-delimited JSON-RPC Server on +$XDG_RUNTIME_DIR/obs-studio-rust/control.sock (0600). It uses the running OBS +instance; headless stdio still owns its own instance. `--mcp-attach [socket]` +proxies stdio to that socket. Socket ownership and cleanup follow module +lifecycle. OS code stays in src/platform or src/ffi. Windows named pipes require +a follow-up; unsupported attachment returns a clear error. + +## Delivery + +Parent #4444 has ordered native sub-issues: #4445 typed tools/errors/schema, +#4446 device/media/stats, #4447 waiting, #4448 socket/module/proxy, #4449 fluent +Rust client and ci/vcam_av_sync.py MCP transport. Each slice targets master +from a fresh infra/control-api-* branch with RED then GREEN shared MCP tests. +The client reuses server types; Python retains websocket and adds --transport +mcp plus fallback. Real GUI/device validation runs only in bosn containers. diff --git a/rust/obs-data/Cargo.toml b/rust/obs-data/Cargo.toml index 2572698008..7957d047ab 100644 --- a/rust/obs-data/Cargo.toml +++ b/rust/obs-data/Cargo.toml @@ -21,6 +21,8 @@ libc = { workspace = true, default-features = true } cc = { workspace = true, default-features = true, features = ["parallel"] } [dev-dependencies] +schemars = { workspace = true } +serde = { workspace = true, features = ["derive"] } obs-audio-monitoring = { path = "../obs-audio-monitoring" } obs-core = { path = "../obs-core" } obs-properties = { path = "../obs-properties" } diff --git a/rust/obs-mcp/Cargo.toml b/rust/obs-mcp/Cargo.toml index 51cc9f0ac1..4363c4cbba 100644 --- a/rust/obs-mcp/Cargo.toml +++ b/rust/obs-mcp/Cargo.toml @@ -27,6 +27,7 @@ libobs = ["dep:obs-sys", "dep:libc"] fault-injection = [] [dependencies] +schemars = { workspace = true } obs-sys = { path = "../obs-sys", optional = true } serde = { workspace = true, default-features = true, features = ["derive"] } serde_json = { workspace = true, features = ["std"] } diff --git a/rust/obs-mcp/src/server/mod.rs b/rust/obs-mcp/src/server/mod.rs index f6310a40da..6dacd5cf8d 100644 --- a/rust/obs-mcp/src/server/mod.rs +++ b/rust/obs-mcp/src/server/mod.rs @@ -5,3 +5,6 @@ mod tool; pub use dispatch::{PROTOCOL_VERSION, Server}; pub use tool::{Content, Tool, ToolRegistry}; + +mod typed; +pub use typed::{TypedTool, ToolAnnotations, ToolError}; diff --git a/rust/obs-mcp/src/server/typed.rs b/rust/obs-mcp/src/server/typed.rs new file mode 100644 index 0000000000..dc590c96ec --- /dev/null +++ b/rust/obs-mcp/src/server/typed.rs @@ -0,0 +1,42 @@ +//! Typed MCP tools and structured domain errors. +use schemars::JsonSchema; +use serde::{Serialize, de::DeserializeOwned}; +use serde_json::Value; +use super::Tool; + +/// Advisory MCP annotations. +#[derive(Clone, Copy)] +pub struct ToolAnnotations; +impl ToolAnnotations { + /// Observes state without modifying it. + pub const READ_ONLY: Self = Self; +} +/// A domain failure, distinct from a JSON-RPC fault. +pub struct ToolError; +impl ToolError { + /// Processing failure (obs-websocket v5 code 700). + pub fn processing(_message: impl Into) -> Self { Self } +} +/// Strongly typed operation exposed over MCP. +pub trait TypedTool { + /// Arguments. + type Input: DeserializeOwned + JsonSchema; + /// Successful response. + type Output: Serialize + JsonSchema; + /// Stable wire name. + const NAME: &'static str; + /// Tool annotations. + const ANNOTATIONS: ToolAnnotations; + /// Human-readable description. + fn description(&self) -> &str; + /// Execute against OBS. + /// # Errors + /// Reports a domain failure. + fn call(&self, input: Self::Input) -> Result; +} +impl Tool for T { + fn name(&self) -> &str { T::NAME } + fn description(&self) -> &str { TypedTool::description(self) } + fn input_schema(&self) -> Value { todo!("typed schema") } + fn call(&self, _arguments: &Value) -> Result { todo!("typed execution") } +} diff --git a/rust/obs-mcp/tests/mcp/main.rs b/rust/obs-mcp/tests/mcp/main.rs index 4cb27265ec..dd42459744 100644 --- a/rust/obs-mcp/tests/mcp/main.rs +++ b/rust/obs-mcp/tests/mcp/main.rs @@ -23,3 +23,5 @@ pub(crate) fn roundtrip(input: &str) -> Vec { .map(|l| serde_json::from_str(l).expect("output line is JSON")) .collect() } + +mod typed; diff --git a/rust/obs-mcp/tests/mcp/typed.rs b/rust/obs-mcp/tests/mcp/typed.rs new file mode 100644 index 0000000000..7cb5d9a0c6 --- /dev/null +++ b/rust/obs-mcp/tests/mcp/typed.rs @@ -0,0 +1,36 @@ +//! Typed control API contract (#4445), in the existing core harness. +use obs_mcp::server::{ToolRegistry, TypedTool, ToolAnnotations, ToolError}; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use serde_json::json; + +#[derive(Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +struct Input { value: String } +#[derive(Serialize, JsonSchema)] +struct Output { value: String } +struct Echo; +impl TypedTool for Echo { + type Input = Input; + type Output = Output; + const NAME: &'static str = "typed_echo"; + const ANNOTATIONS: ToolAnnotations = ToolAnnotations::READ_ONLY; + fn description(&self) -> &str { "Typed echo" } + fn call(&self, input: Input) -> Result { + if input.value == "fail" { return Err(ToolError::processing("deliberate failure")); } + Ok(Output { value: input.value }) + } +} +#[test] +fn typed_schema_and_structured_result() { + let mut tools = ToolRegistry::new(); + tools.register(Box::new(Echo)); + let listed = tools.list(); + assert_eq!(listed["tools"][0]["outputSchema"]["properties"]["value"]["type"], "string"); + assert_eq!(listed["tools"][0]["annotations"]["readOnlyHint"], true); + let mut server = obs_mcp::server::Server::with_tools(tools); + let mut out = Vec::new(); + server.serve(b"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"typed_echo\",\"arguments\":{\"value\":\"hello\"}}}\n".as_slice(), &mut out).unwrap(); + let reply: serde_json::Value = serde_json::from_slice(&out).unwrap(); + assert_eq!(reply["result"]["structuredContent"], json!({"value":"hello"})); +} From a86793ee894f164978ea0f26d248ac24c6934bce Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 13:43:10 -0800 Subject: [PATCH 02/39] feat(mcp): typed tools, structured domain errors and schema snapshot (#4445) --- Cargo.lock | 12 + Cargo.toml | 3 +- docs/features.md | 6 + docs/rust-port/control-api.schema.json | 1236 ++++++++++++++++++++++++ rust/obs-data/Cargo.toml | 2 +- rust/obs-mcp/Cargo.toml | 3 +- rust/obs-mcp/src/server/dispatch.rs | 10 +- rust/obs-mcp/src/server/mod.rs | 2 +- rust/obs-mcp/src/server/tool.rs | 31 +- rust/obs-mcp/src/server/typed.rs | 186 +++- rust/obs-mcp/src/tools/mod.rs | 39 + rust/obs-mcp/src/tools/outputs.rs | 244 +++-- rust/obs-mcp/src/tools/scenes.rs | 260 +++-- rust/obs-mcp/src/tools/screenshot.rs | 134 +-- rust/obs-mcp/src/tools/sources.rs | 742 ++++++++------ rust/obs-mcp/tests/mcp/outputs.rs | 32 +- rust/obs-mcp/tests/mcp/scenes.rs | 7 + rust/obs-mcp/tests/mcp/screenshot.rs | 15 +- rust/obs-mcp/tests/mcp/sources.rs | 16 +- rust/obs-mcp/tests/mcp/typed.rs | 80 +- 20 files changed, 2446 insertions(+), 614 deletions(-) create mode 100644 docs/rust-port/control-api.schema.json diff --git a/Cargo.lock b/Cargo.lock index e3f6de6738..2fe6331eb9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -662,6 +662,7 @@ dependencies = [ "schemars", "serde", "serde_json", + "serde_path_to_error", ] [[package]] @@ -1097,6 +1098,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + [[package]] name = "sha1" version = "0.11.0" diff --git a/Cargo.toml b/Cargo.toml index 652484dc46..a39e0998a5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,7 +26,8 @@ memchr = { version = "=2.8.3", default-features = false } pkg-config = { version = "=0.3.34", default-features = false } proptest = { version = "=1.11.0", default-features = false } serde = { version = "=1.0.229", default-features = false } -schemars = { version = "=1.2.3" } +schemars = { version = "=1.2.3", default-features = false } +serde_path_to_error = { version = "=0.1.20", default-features = false } serde_json = { version = "=1.0.151", default-features = false } sha2 = { version = "=0.11.0", default-features = false } tempfile = { version = "=3.27.0", default-features = false } diff --git a/docs/features.md b/docs/features.md index f4772b7ee6..e254acf9eb 100644 --- a/docs/features.md +++ b/docs/features.md @@ -75,6 +75,12 @@ not get a line. ### Headless and automation +- **Typed MCP control.** Existing OBS MCP tools publish input and output schemas, + structured results and machine-readable domain errors. Read operations carry + annotations, and repeated output start/stop calls succeed with current state. + *All*, 2026-11-09. Issue [#4445](https://github.com/obs-rust/obs-studio/issues/4445), + PR [#4450](https://github.com/obs-rust/obs-studio/pull/4450). + - **`--disable-shutdown-check` works again.** After an unclean stop (power loss, OOM killer, a hard stop of the VM or container), OBS starts without the "Crash Detected" dialog and logs the unclean shutdown as a warning on diff --git a/docs/rust-port/control-api.schema.json b/docs/rust-port/control-api.schema.json new file mode 100644 index 0000000000..b74dbf66c0 --- /dev/null +++ b/docs/rust-port/control-api.schema.json @@ -0,0 +1,1236 @@ +{ + "toolError": { + "$defs": { + "ErrorCategory": { + "description": "Domain failure category, using obs-websocket v5 status ranges.", + "oneOf": [ + { + "const": "not_ready", + "description": "A resource is absent or not ready (5xx).", + "type": "string" + }, + { + "const": "wrong_state", + "description": "The current state prevents the operation (6xx).", + "type": "string" + }, + { + "const": "processing", + "description": "OBS failed to process the operation (7xx).", + "type": "string" + } + ] + } + }, + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "A domain failure, distinct from a JSON-RPC fault.", + "properties": { + "category": { + "$ref": "#/$defs/ErrorCategory", + "description": "Stable machine-readable category." + }, + "code": { + "description": "obs-websocket v5 RequestStatus code.", + "format": "uint16", + "maximum": 65535, + "minimum": 0, + "type": "integer" + }, + "message": { + "description": "Human-readable context.", + "type": "string" + }, + "retryable": { + "description": "Whether a later retry may succeed.", + "type": "boolean" + } + }, + "required": [ + "code", + "category", + "message", + "retryable" + ], + "title": "ToolError", + "type": "object" + }, + "tools": [ + { + "annotations": { + "destructiveHint": false, + "idempotentHint": true, + "openWorldHint": false, + "readOnlyHint": false + }, + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Empty arguments, with unknown fields rejected.", + "properties": {}, + "title": "EmptyInput", + "type": "object" + }, + "name": "record_start", + "outputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "description": "State returned by a start or stop operation.", + "properties": { + "active": { + "description": "Whether the output is running.", + "type": "boolean" + } + }, + "required": [ + "active" + ], + "title": "ActiveOutput", + "type": "object" + } + }, + { + "annotations": { + "destructiveHint": false, + "idempotentHint": true, + "openWorldHint": false, + "readOnlyHint": true + }, + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Empty arguments, with unknown fields rejected.", + "properties": {}, + "title": "EmptyInput", + "type": "object" + }, + "name": "record_status", + "outputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "description": "The state of an output as reported by [`OutputBackend::status`].", + "properties": { + "active": { + "description": "Whether the output is running.", + "type": "boolean" + }, + "bytes": { + "description": "Bytes written or sent so far, where known.", + "format": "uint64", + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "duration_ms": { + "description": "Milliseconds since the output started, where known.", + "format": "uint64", + "minimum": 0, + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "active" + ], + "title": "OutputStatus", + "type": "object" + } + }, + { + "annotations": { + "destructiveHint": false, + "idempotentHint": true, + "openWorldHint": false, + "readOnlyHint": false + }, + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Empty arguments, with unknown fields rejected.", + "properties": {}, + "title": "EmptyInput", + "type": "object" + }, + "name": "record_stop", + "outputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "description": "State returned by a start or stop operation.", + "properties": { + "active": { + "description": "Whether the output is running.", + "type": "boolean" + } + }, + "required": [ + "active" + ], + "title": "ActiveOutput", + "type": "object" + } + }, + { + "annotations": { + "destructiveHint": false, + "idempotentHint": false, + "openWorldHint": false, + "readOnlyHint": false + }, + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "A scene name.", + "properties": { + "name": { + "description": "Scene name.", + "minLength": 1, + "type": "string" + } + }, + "required": [ + "name" + ], + "title": "NameInput", + "type": "object" + }, + "name": "scene_create", + "outputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "description": "Current or changed scene.", + "properties": { + "name": { + "description": "Null when there is no program scene.", + "type": [ + "string", + "null" + ] + } + }, + "title": "SceneOutput", + "type": "object" + } + }, + { + "annotations": { + "destructiveHint": false, + "idempotentHint": true, + "openWorldHint": false, + "readOnlyHint": true + }, + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Empty arguments, with unknown fields rejected.", + "properties": {}, + "title": "EmptyInput", + "type": "object" + }, + "name": "scene_get_current", + "outputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "description": "Current or changed scene.", + "properties": { + "name": { + "description": "Null when there is no program scene.", + "type": [ + "string", + "null" + ] + } + }, + "title": "SceneOutput", + "type": "object" + } + }, + { + "annotations": { + "destructiveHint": false, + "idempotentHint": false, + "openWorldHint": false, + "readOnlyHint": false + }, + "inputSchema": { + "$defs": { + "Pair": { + "additionalProperties": false, + "description": "Pixel position or scale factors.", + "properties": { + "x": { + "description": "Horizontal component.", + "format": "double", + "type": "number" + }, + "y": { + "description": "Vertical component.", + "format": "double", + "type": "number" + } + }, + "required": [ + "x", + "y" + ], + "type": "object" + } + }, + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Place an existing source in a scene.", + "properties": { + "position": { + "anyOf": [ + { + "$ref": "#/$defs/Pair" + }, + { + "type": "null" + } + ], + "description": "Initial position." + }, + "scene": { + "description": "Scene name.", + "type": "string" + }, + "source": { + "description": "Source name.", + "type": "string" + } + }, + "required": [ + "scene", + "source" + ], + "title": "AddItemInput", + "type": "object" + }, + "name": "scene_item_add", + "outputSchema": { + "$defs": { + "Pair": { + "additionalProperties": false, + "description": "Pixel position or scale factors.", + "properties": { + "x": { + "description": "Horizontal component.", + "format": "double", + "type": "number" + }, + "y": { + "description": "Vertical component.", + "format": "double", + "type": "number" + } + }, + "required": [ + "x", + "y" + ], + "type": "object" + } + }, + "$schema": "https://json-schema.org/draft/2020-12/schema", + "description": "Listed scene item, preserving the existing wire fields.", + "properties": { + "item": { + "description": "Item id.", + "format": "int64", + "type": "integer" + }, + "position": { + "$ref": "#/$defs/Pair", + "description": "Canvas position." + }, + "rotation": { + "description": "Rotation in degrees.", + "format": "double", + "type": "number" + }, + "scale": { + "$ref": "#/$defs/Pair", + "description": "Scale factors." + }, + "scene": { + "description": "Present when an item was added.", + "type": [ + "string", + "null" + ] + }, + "source": { + "description": "Source name.", + "type": "string" + }, + "visible": { + "description": "Visibility.", + "type": "boolean" + } + }, + "required": [ + "item", + "source", + "visible", + "position", + "scale", + "rotation" + ], + "title": "ItemOutput", + "type": "object" + } + }, + { + "annotations": { + "destructiveHint": false, + "idempotentHint": false, + "openWorldHint": false, + "readOnlyHint": false + }, + "inputSchema": { + "$defs": { + "Pair": { + "additionalProperties": false, + "description": "Pixel position or scale factors.", + "properties": { + "x": { + "description": "Horizontal component.", + "format": "double", + "type": "number" + }, + "y": { + "description": "Vertical component.", + "format": "double", + "type": "number" + } + }, + "required": [ + "x", + "y" + ], + "type": "object" + } + }, + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Transform update; at least one transform field is required.", + "properties": { + "item": { + "description": "Item id.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "position": { + "anyOf": [ + { + "$ref": "#/$defs/Pair" + }, + { + "type": "null" + } + ], + "description": "New position." + }, + "rotation": { + "description": "New rotation in degrees.", + "format": "double", + "type": [ + "number", + "null" + ] + }, + "scale": { + "anyOf": [ + { + "$ref": "#/$defs/Pair" + }, + { + "type": "null" + } + ], + "description": "New scale." + }, + "scene": { + "description": "Scene name.", + "type": "string" + }, + "source": { + "description": "Source name instead of item id.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "scene" + ], + "title": "TransformInput", + "type": "object" + }, + "name": "scene_item_set_transform", + "outputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "description": "Item mutation response, retaining the caller's selector.", + "properties": { + "item": { + "description": "Item id when selected by id.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "scene": { + "description": "Scene name.", + "type": "string" + }, + "source": { + "description": "Source name when selected by name.", + "type": [ + "string", + "null" + ] + }, + "visible": { + "description": "Present for visibility changes.", + "type": [ + "boolean", + "null" + ] + } + }, + "required": [ + "scene" + ], + "title": "ItemReply", + "type": "object" + } + }, + { + "annotations": { + "destructiveHint": false, + "idempotentHint": true, + "openWorldHint": false, + "readOnlyHint": false + }, + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Visibility update; exactly one of item/source must be specified.", + "properties": { + "item": { + "description": "Item id.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "scene": { + "description": "Scene name.", + "type": "string" + }, + "source": { + "description": "Source name instead of item id.", + "type": [ + "string", + "null" + ] + }, + "visible": { + "description": "New visibility.", + "type": "boolean" + } + }, + "required": [ + "scene", + "visible" + ], + "title": "VisibleInput", + "type": "object" + }, + "name": "scene_item_set_visible", + "outputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "description": "Item mutation response, retaining the caller's selector.", + "properties": { + "item": { + "description": "Item id when selected by id.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "scene": { + "description": "Scene name.", + "type": "string" + }, + "source": { + "description": "Source name when selected by name.", + "type": [ + "string", + "null" + ] + }, + "visible": { + "description": "Present for visibility changes.", + "type": [ + "boolean", + "null" + ] + } + }, + "required": [ + "scene" + ], + "title": "ItemReply", + "type": "object" + } + }, + { + "annotations": { + "destructiveHint": false, + "idempotentHint": true, + "openWorldHint": false, + "readOnlyHint": true + }, + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Scene selection.", + "properties": { + "scene": { + "description": "Scene name.", + "type": "string" + } + }, + "required": [ + "scene" + ], + "title": "ItemsInput", + "type": "object" + }, + "name": "scene_items_list", + "outputSchema": { + "$defs": { + "ItemOutput": { + "description": "Listed scene item, preserving the existing wire fields.", + "properties": { + "item": { + "description": "Item id.", + "format": "int64", + "type": "integer" + }, + "position": { + "$ref": "#/$defs/Pair", + "description": "Canvas position." + }, + "rotation": { + "description": "Rotation in degrees.", + "format": "double", + "type": "number" + }, + "scale": { + "$ref": "#/$defs/Pair", + "description": "Scale factors." + }, + "scene": { + "description": "Present when an item was added.", + "type": [ + "string", + "null" + ] + }, + "source": { + "description": "Source name.", + "type": "string" + }, + "visible": { + "description": "Visibility.", + "type": "boolean" + } + }, + "required": [ + "item", + "source", + "visible", + "position", + "scale", + "rotation" + ], + "type": "object" + }, + "Pair": { + "additionalProperties": false, + "description": "Pixel position or scale factors.", + "properties": { + "x": { + "description": "Horizontal component.", + "format": "double", + "type": "number" + }, + "y": { + "description": "Vertical component.", + "format": "double", + "type": "number" + } + }, + "required": [ + "x", + "y" + ], + "type": "object" + } + }, + "$schema": "https://json-schema.org/draft/2020-12/schema", + "description": "Items of a scene.", + "properties": { + "items": { + "description": "Items bottom to top.", + "items": { + "$ref": "#/$defs/ItemOutput" + }, + "type": "array" + }, + "scene": { + "description": "Scene name.", + "type": "string" + } + }, + "required": [ + "scene", + "items" + ], + "title": "ItemsOutput", + "type": "object" + } + }, + { + "annotations": { + "destructiveHint": false, + "idempotentHint": false, + "openWorldHint": false, + "readOnlyHint": false + }, + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "A scene name.", + "properties": { + "name": { + "description": "Scene name.", + "minLength": 1, + "type": "string" + } + }, + "required": [ + "name" + ], + "title": "NameInput", + "type": "object" + }, + "name": "scene_remove", + "outputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "description": "Current or changed scene.", + "properties": { + "name": { + "description": "Null when there is no program scene.", + "type": [ + "string", + "null" + ] + } + }, + "title": "SceneOutput", + "type": "object" + } + }, + { + "annotations": { + "destructiveHint": false, + "idempotentHint": true, + "openWorldHint": false, + "readOnlyHint": false + }, + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "A scene name.", + "properties": { + "name": { + "description": "Scene name.", + "minLength": 1, + "type": "string" + } + }, + "required": [ + "name" + ], + "title": "NameInput", + "type": "object" + }, + "name": "scene_set_current", + "outputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "description": "Current or changed scene.", + "properties": { + "name": { + "description": "Null when there is no program scene.", + "type": [ + "string", + "null" + ] + } + }, + "title": "SceneOutput", + "type": "object" + } + }, + { + "annotations": { + "destructiveHint": false, + "idempotentHint": true, + "openWorldHint": false, + "readOnlyHint": true + }, + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Empty arguments, with unknown fields rejected.", + "properties": {}, + "title": "EmptyInput", + "type": "object" + }, + "name": "scenes_list", + "outputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "description": "Scene listing.", + "properties": { + "scenes": { + "description": "Scene names in display order.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "scenes" + ], + "title": "ScenesOutput", + "type": "object" + } + }, + { + "annotations": { + "destructiveHint": false, + "idempotentHint": true, + "openWorldHint": false, + "readOnlyHint": true + }, + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Screenshot selection and requested size.", + "properties": { + "height": { + "description": "Height in pixels.", + "format": "uint32", + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "source": { + "description": "Source to capture; omit for program output.", + "type": [ + "string", + "null" + ] + }, + "width": { + "description": "Width in pixels.", + "format": "uint32", + "minimum": 0, + "type": [ + "integer", + "null" + ] + } + }, + "title": "CaptureInput", + "type": "object" + }, + "name": "screenshot", + "outputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "description": "Captured PNG and its dimensions.", + "properties": { + "data": { + "description": "PNG bytes encoded in base64.", + "type": "string" + }, + "height": { + "description": "Height in pixels.", + "format": "uint32", + "minimum": 0, + "type": "integer" + }, + "source": { + "description": "Source name, or null for program output.", + "type": [ + "string", + "null" + ] + }, + "width": { + "description": "Width in pixels.", + "format": "uint32", + "minimum": 0, + "type": "integer" + } + }, + "required": [ + "data", + "width", + "height" + ], + "title": "CaptureOutput", + "type": "object" + } + }, + { + "annotations": { + "destructiveHint": false, + "idempotentHint": false, + "openWorldHint": false, + "readOnlyHint": false + }, + "inputSchema": { + "$defs": { + "Pair": { + "additionalProperties": false, + "description": "Pixel position or scale factors.", + "properties": { + "x": { + "description": "Horizontal component.", + "format": "double", + "type": "number" + }, + "y": { + "description": "Vertical component.", + "format": "double", + "type": "number" + } + }, + "required": [ + "x", + "y" + ], + "type": "object" + } + }, + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Source creation, optionally placing it in a scene.", + "properties": { + "kind": { + "description": "Source kind id.", + "type": "string" + }, + "name": { + "description": "Unique name.", + "type": "string" + }, + "position": { + "anyOf": [ + { + "$ref": "#/$defs/Pair" + }, + { + "type": "null" + } + ], + "description": "Initial position (requires scene)." + }, + "scene": { + "description": "Scene receiving the source.", + "type": [ + "string", + "null" + ] + }, + "settings": { + "additionalProperties": true, + "description": "Kind-specific settings.", + "type": "object" + } + }, + "required": [ + "kind", + "name", + "settings" + ], + "title": "CreateInput", + "type": "object" + }, + "name": "source_create", + "outputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "description": "Created source.", + "properties": { + "item": { + "description": "Created item id.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "kind": { + "description": "Source kind.", + "type": "string" + }, + "name": { + "description": "Source name.", + "type": "string" + }, + "scene": { + "description": "Scene receiving the new item.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "name", + "kind" + ], + "title": "CreateOutput", + "type": "object" + } + }, + { + "annotations": { + "destructiveHint": false, + "idempotentHint": false, + "openWorldHint": false, + "readOnlyHint": false + }, + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Settings update.", + "properties": { + "name": { + "description": "Source name.", + "type": "string" + }, + "settings": { + "additionalProperties": true, + "description": "Kind-specific settings to merge.", + "type": "object" + } + }, + "required": [ + "name", + "settings" + ], + "title": "SettingsInput", + "type": "object" + }, + "name": "source_set_settings", + "outputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "description": "Updated source name.", + "properties": { + "name": { + "description": "Source name.", + "type": "string" + } + }, + "required": [ + "name" + ], + "title": "NameOutput", + "type": "object" + } + }, + { + "annotations": { + "destructiveHint": false, + "idempotentHint": true, + "openWorldHint": false, + "readOnlyHint": true + }, + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Empty arguments, with unknown fields rejected.", + "properties": {}, + "title": "EmptyInput", + "type": "object" + }, + "name": "sources_list", + "outputSchema": { + "$defs": { + "SourceInfo": { + "description": "A source as listed by [`SourceBackend::sources`].", + "properties": { + "kind": { + "description": "The source kind id, such as `color_source`.", + "type": "string" + }, + "name": { + "description": "The source's unique name.", + "type": "string" + } + }, + "required": [ + "name", + "kind" + ], + "type": "object" + } + }, + "$schema": "https://json-schema.org/draft/2020-12/schema", + "description": "Source listing.", + "properties": { + "sources": { + "description": "Sources in stable order.", + "items": { + "$ref": "#/$defs/SourceInfo" + }, + "type": "array" + } + }, + "required": [ + "sources" + ], + "title": "SourcesOutput", + "type": "object" + } + }, + { + "annotations": { + "destructiveHint": false, + "idempotentHint": true, + "openWorldHint": false, + "readOnlyHint": false + }, + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Empty arguments, with unknown fields rejected.", + "properties": {}, + "title": "EmptyInput", + "type": "object" + }, + "name": "stream_start", + "outputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "description": "State returned by a start or stop operation.", + "properties": { + "active": { + "description": "Whether the output is running.", + "type": "boolean" + } + }, + "required": [ + "active" + ], + "title": "ActiveOutput", + "type": "object" + } + }, + { + "annotations": { + "destructiveHint": false, + "idempotentHint": true, + "openWorldHint": false, + "readOnlyHint": true + }, + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Empty arguments, with unknown fields rejected.", + "properties": {}, + "title": "EmptyInput", + "type": "object" + }, + "name": "stream_status", + "outputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "description": "The state of an output as reported by [`OutputBackend::status`].", + "properties": { + "active": { + "description": "Whether the output is running.", + "type": "boolean" + }, + "bytes": { + "description": "Bytes written or sent so far, where known.", + "format": "uint64", + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "duration_ms": { + "description": "Milliseconds since the output started, where known.", + "format": "uint64", + "minimum": 0, + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "active" + ], + "title": "OutputStatus", + "type": "object" + } + }, + { + "annotations": { + "destructiveHint": false, + "idempotentHint": true, + "openWorldHint": false, + "readOnlyHint": false + }, + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Empty arguments, with unknown fields rejected.", + "properties": {}, + "title": "EmptyInput", + "type": "object" + }, + "name": "stream_stop", + "outputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "description": "State returned by a start or stop operation.", + "properties": { + "active": { + "description": "Whether the output is running.", + "type": "boolean" + } + }, + "required": [ + "active" + ], + "title": "ActiveOutput", + "type": "object" + } + } + ] +} diff --git a/rust/obs-data/Cargo.toml b/rust/obs-data/Cargo.toml index 7957d047ab..9a6ea0ae8b 100644 --- a/rust/obs-data/Cargo.toml +++ b/rust/obs-data/Cargo.toml @@ -21,7 +21,7 @@ libc = { workspace = true, default-features = true } cc = { workspace = true, default-features = true, features = ["parallel"] } [dev-dependencies] -schemars = { workspace = true } +schemars = { workspace = true, features = ["derive", "std"] } serde = { workspace = true, features = ["derive"] } obs-audio-monitoring = { path = "../obs-audio-monitoring" } obs-core = { path = "../obs-core" } diff --git a/rust/obs-mcp/Cargo.toml b/rust/obs-mcp/Cargo.toml index 4363c4cbba..c43b005d0a 100644 --- a/rust/obs-mcp/Cargo.toml +++ b/rust/obs-mcp/Cargo.toml @@ -27,7 +27,8 @@ libobs = ["dep:obs-sys", "dep:libc"] fault-injection = [] [dependencies] -schemars = { workspace = true } +schemars = { workspace = true, features = ["derive", "std"] } +serde_path_to_error = { workspace = true } obs-sys = { path = "../obs-sys", optional = true } serde = { workspace = true, default-features = true, features = ["derive"] } serde_json = { workspace = true, features = ["std"] } diff --git a/rust/obs-mcp/src/server/dispatch.rs b/rust/obs-mcp/src/server/dispatch.rs index 7de430e802..aee8270f92 100644 --- a/rust/obs-mcp/src/server/dispatch.rs +++ b/rust/obs-mcp/src/server/dispatch.rs @@ -8,7 +8,7 @@ use crate::protocol::{Request, Response, error_code, read_message, write_message use crate::resources::ResourceRegistry; -use super::{Content, ToolRegistry}; +use super::ToolRegistry; /// The MCP revision this server implements. pub const PROTOCOL_VERSION: &str = "2025-06-18"; @@ -118,12 +118,8 @@ impl Server { .get("arguments") .cloned() .unwrap_or_else(|| json!({})); - let (content, is_error) = match tool.call_content(&arguments) { - Ok(items) => (items, false), - Err(text) => (vec![Content::Text(text)], true), - }; - let content: Vec = content.iter().map(Content::to_json).collect(); - Ok(json!({ "content": content, "isError": is_error })) + tool.call_result(&arguments) + .map_err(|message| (error_code::INVALID_PARAMS, message)) } /// `resources/read`: an unknown URI is a protocol error. diff --git a/rust/obs-mcp/src/server/mod.rs b/rust/obs-mcp/src/server/mod.rs index 6dacd5cf8d..3724e1a911 100644 --- a/rust/obs-mcp/src/server/mod.rs +++ b/rust/obs-mcp/src/server/mod.rs @@ -7,4 +7,4 @@ pub use dispatch::{PROTOCOL_VERSION, Server}; pub use tool::{Content, Tool, ToolRegistry}; mod typed; -pub use typed::{TypedTool, ToolAnnotations, ToolError}; +pub use typed::{ErrorCategory, ToolAnnotations, ToolError, TypedTool, tool_schema}; diff --git a/rust/obs-mcp/src/server/tool.rs b/rust/obs-mcp/src/server/tool.rs index c78ae40e36..3a32ef3011 100644 --- a/rust/obs-mcp/src/server/tool.rs +++ b/rust/obs-mcp/src/server/tool.rs @@ -37,6 +37,26 @@ pub trait Tool { fn description(&self) -> &str; /// JSON Schema of the arguments object. fn input_schema(&self) -> Value; + /// JSON Schema of successful structured output, when supported. + fn output_schema(&self) -> Option { + None + } + /// MCP advisory annotations. + fn annotations(&self) -> Option { + None + } + /// Executes with protocol faults separated from domain failures. + /// # Errors + /// Returns a protocol invalid-arguments message. + fn call_result(&self, arguments: &Value) -> Result { + let (content, is_error) = match self.call_content(arguments) { + Ok(items) => (items, false), + Err(text) => (vec![Content::Text(text)], true), + }; + Ok( + json!({"content": content.iter().map(Content::to_json).collect::>(), "isError": is_error}), + ) + } /// Runs the tool; `Err` is reported to the model as a tool error. /// /// # Errors @@ -80,11 +100,18 @@ impl ToolRegistry { .tools .iter() .map(|t| { - json!({ + let mut definition = json!({ "name": t.name(), "description": t.description(), "inputSchema": t.input_schema(), - }) + }); + if let Some(schema) = t.output_schema() { + definition["outputSchema"] = schema; + } + if let Some(annotations) = t.annotations() { + definition["annotations"] = annotations; + } + definition }) .collect(); json!({ "tools": tools }) diff --git a/rust/obs-mcp/src/server/typed.rs b/rust/obs-mcp/src/server/typed.rs index dc590c96ec..4b9763a692 100644 --- a/rust/obs-mcp/src/server/typed.rs +++ b/rust/obs-mcp/src/server/typed.rs @@ -1,22 +1,112 @@ //! Typed MCP tools and structured domain errors. -use schemars::JsonSchema; -use serde::{Serialize, de::DeserializeOwned}; -use serde_json::Value; -use super::Tool; +use super::{Content, Tool}; +use schemars::{JsonSchema, schema_for}; +use serde::{Deserialize, Serialize, de::DeserializeOwned}; +use serde_json::{Value, json}; -/// Advisory MCP annotations. -#[derive(Clone, Copy)] -pub struct ToolAnnotations; +/// Advisory MCP annotations; clients must still enforce their own policy. +#[derive(Clone, Copy, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ToolAnnotations { + /// Does not mutate OBS. + pub read_only_hint: bool, + /// Repeating the same call has the same effect. + pub idempotent_hint: bool, + /// May destroy data. + pub destructive_hint: bool, + /// Interacts with external entities. + pub open_world_hint: bool, +} impl ToolAnnotations { - /// Observes state without modifying it. - pub const READ_ONLY: Self = Self; + /// Observes local state. + pub const READ_ONLY: Self = Self { + read_only_hint: true, + idempotent_hint: true, + destructive_hint: false, + open_world_hint: false, + }; + /// Changes local state. + pub const MUTATING: Self = Self { + read_only_hint: false, + idempotent_hint: false, + destructive_hint: false, + open_world_hint: false, + }; + /// Repeating start/stop succeeds with the current state. + pub const IDEMPOTENT: Self = Self { + idempotent_hint: true, + ..Self::MUTATING + }; +} +/// Domain failure category, using obs-websocket v5 status ranges. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum ErrorCategory { + /// A resource is absent or not ready (5xx). + NotReady, + /// The current state prevents the operation (6xx). + WrongState, + /// OBS failed to process the operation (7xx). + Processing, } /// A domain failure, distinct from a JSON-RPC fault. -pub struct ToolError; +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct ToolError { + /// obs-websocket v5 RequestStatus code. + pub code: u16, + /// Stable machine-readable category. + pub category: ErrorCategory, + /// Human-readable context. + pub message: String, + /// Whether a later retry may succeed. + pub retryable: bool, +} impl ToolError { - /// Processing failure (obs-websocket v5 code 700). - pub fn processing(_message: impl Into) -> Self { Self } + /// Processing failure (7xx control API range). + pub fn processing(message: impl Into) -> Self { + Self { + code: 700, + category: ErrorCategory::Processing, + message: message.into(), + retryable: false, + } + } + /// Missing resource (5xx control API range). + pub fn not_found(message: impl Into) -> Self { + Self { + code: 500, + category: ErrorCategory::NotReady, + message: message.into(), + retryable: false, + } + } + /// A required subsystem is unavailable (5xx control API range). + pub fn not_ready(message: impl Into) -> Self { + Self { + code: 509, + category: ErrorCategory::NotReady, + message: message.into(), + retryable: true, + } + } + /// Invalid resource state (6xx control API range). + pub fn wrong_state(message: impl Into) -> Self { + Self { + code: 604, + category: ErrorCategory::WrongState, + message: message.into(), + retryable: false, + } + } } +impl std::fmt::Display for ToolError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.message) + } +} +impl std::error::Error for ToolError {} + /// Strongly typed operation exposed over MCP. pub trait TypedTool { /// Arguments. @@ -33,10 +123,74 @@ pub trait TypedTool { /// # Errors /// Reports a domain failure. fn call(&self, input: Self::Input) -> Result; + /// Content accompanying structured output. Screenshots retain image content. + /// # Errors + /// Reports output serialization failures without panicking the server. + fn content(output: &Self::Output) -> Result, ToolError> { + serde_json::to_string(output) + .map(|text| vec![Content::Text(text)]) + .map_err(|error| ToolError::processing(error.to_string())) + } } impl Tool for T { - fn name(&self) -> &str { T::NAME } - fn description(&self) -> &str { TypedTool::description(self) } - fn input_schema(&self) -> Value { todo!("typed schema") } - fn call(&self, _arguments: &Value) -> Result { todo!("typed execution") } + fn name(&self) -> &str { + T::NAME + } + fn description(&self) -> &str { + TypedTool::description(self) + } + fn input_schema(&self) -> Value { + input_schema::() + } + fn output_schema(&self) -> Option { + Some(json!(schema_for!(T::Output))) + } + fn annotations(&self) -> Option { + Some(json!(T::ANNOTATIONS)) + } + fn call(&self, arguments: &Value) -> Result { + let input = parse_input(arguments)?; + let output = TypedTool::call(self, input).map_err(|e| e.to_string())?; + serde_json::to_string(&output).map_err(|e| e.to_string()) + } + fn call_content(&self, arguments: &Value) -> Result, String> { + let input = parse_input(arguments)?; + TypedTool::call(self, input) + .and_then(|output| T::content(&output)) + .map_err(|e| e.to_string()) + } + fn call_result(&self, arguments: &Value) -> Result { + let input = parse_input(arguments)?; + let result = TypedTool::call(self, input).and_then(|output| { + let content = T::content(&output)?; + let structured = serde_json::to_value(output).map_err(|error| ToolError::processing(error.to_string()))?; + Ok(json!({"content": content.iter().map(Content::to_json).collect::>(), "structuredContent": structured, "isError": false})) + }); + Ok(result.unwrap_or_else(|error| { + let structured = json!(error); + json!({"content": [{"type": "text", "text": structured.to_string()}], "structuredContent": structured, "isError": true}) + })) + } +} + +/// Generated argument schema with an explicit empty properties object. +#[must_use] +pub fn input_schema() -> Value { + let mut schema = json!(schema_for!(T)); + if schema["type"] == "object" && schema.get("properties").is_none() { + schema["properties"] = json!({}); + } + schema +} +/// The schema contract of a tool, without human-facing prose. +#[must_use] +pub fn tool_schema() -> Value { + json!({"name": T::NAME, "inputSchema": input_schema::(), "outputSchema": schema_for!(T::Output), "annotations": T::ANNOTATIONS}) +} + +fn parse_input(arguments: &Value) -> Result { + if !arguments.is_object() { + return Err("arguments must be an object".into()); + } + serde_path_to_error::deserialize(arguments).map_err(|error| error.to_string()) } diff --git a/rust/obs-mcp/src/tools/mod.rs b/rust/obs-mcp/src/tools/mod.rs index a49a99170b..981e9fd27d 100644 --- a/rust/obs-mcp/src/tools/mod.rs +++ b/rust/obs-mcp/src/tools/mod.rs @@ -1,6 +1,45 @@ //! The tools the server exposes, grouped by area. +// Each operation has a distinct input/output pair and compile-time wire name. +macro_rules! typed_tool { + ($tool:ident, $name:literal, $backend:ident, $input:ty, $output:ty, $annotations:ident, $description:expr, |$b:ident, $i:ident| $body:block) => { + struct $tool { + backend: std::rc::Rc, + } + impl crate::server::TypedTool for $tool { + type Input = $input; + type Output = $output; + const NAME: &'static str = $name; + const ANNOTATIONS: crate::server::ToolAnnotations = + crate::server::ToolAnnotations::$annotations; + fn description(&self) -> &str { + $description + } + fn call(&self, $i: Self::Input) -> Result { + let $b = &self.backend; + $body + } + } + }; +} + +/// Empty arguments, with unknown fields rejected. +#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct EmptyInput {} + pub mod outputs; pub mod scenes; pub mod screenshot; pub mod sources; + +/// Deterministic generated schema snapshot for all built-in tools. +#[must_use] +pub fn schema_snapshot() -> serde_json::Value { + let mut tools = scenes::schemas(); + tools.extend(sources::schemas()); + tools.extend(outputs::schemas()); + tools.extend(screenshot::schemas()); + tools.sort_by(|a, b| a["name"].as_str().cmp(&b["name"].as_str())); + serde_json::json!({"tools": tools, "toolError": schemars::schema_for!(crate::server::ToolError)}) +} diff --git a/rust/obs-mcp/src/tools/outputs.rs b/rust/obs-mcp/src/tools/outputs.rs index 22cfceb49c..1373f2654a 100644 --- a/rust/obs-mcp/src/tools/outputs.rs +++ b/rust/obs-mcp/src/tools/outputs.rs @@ -6,12 +6,16 @@ use std::rc::Rc; -use serde_json::{Map, Value, json}; +use super::EmptyInput; +use crate::server::ToolError; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; -use crate::server::{Tool, ToolRegistry}; +use crate::server::ToolRegistry; /// Which output a call is about. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] pub enum OutputKind { /// The recording output. Record, @@ -20,13 +24,15 @@ pub enum OutputKind { } /// The state of an output as reported by [`OutputBackend::status`]. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] pub struct OutputStatus { /// Whether the output is running. pub active: bool, /// Milliseconds since the output started, where known. + #[serde(skip_serializing_if = "Option::is_none", default)] pub duration_ms: Option, /// Bytes written or sent so far, where known. + #[serde(skip_serializing_if = "Option::is_none", default)] pub bytes: Option, } @@ -35,6 +41,33 @@ pub struct OutputStatus { /// Methods take `&self`: libobs owns the state, so implementations use their /// own interior mutability. pub trait OutputBackend { + /// Typed idempotent start. + /// # Errors + /// Reports a processing failure. + fn start_output(&self, request: OutputRequest) -> Result { + if !self.status(request.kind).active { + self.start(request.kind).map_err(ToolError::processing)?; + } + Ok(ActiveOutput { + active: self.status(request.kind).active, + }) + } + /// Typed idempotent stop. + /// # Errors + /// Reports a processing failure. + fn stop_output(&self, request: OutputRequest) -> Result { + if self.status(request.kind).active { + self.stop(request.kind).map_err(ToolError::processing)?; + } + Ok(ActiveOutput { + active: self.status(request.kind).active, + }) + } + /// Typed status request. + fn output_status(&self, request: OutputRequest) -> OutputStatus { + self.status(request.kind) + } + /// Starts the output of `kind`. /// /// # Errors @@ -51,92 +84,135 @@ pub trait OutputBackend { fn status(&self, kind: OutputKind) -> OutputStatus; } -/// Which operation an [`OutputTool`] performs. -#[derive(Clone, Copy)] -enum Action { - Start, - Stop, - Status, -} - -/// One output tool bound to a backend. -struct OutputTool { - kind: OutputKind, - action: Action, - backend: Rc, +/// State returned by a start or stop operation. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +pub struct ActiveOutput { + /// Whether the output is running. + pub active: bool, } - -impl Tool for OutputTool { - fn name(&self) -> &str { - match (self.kind, self.action) { - (OutputKind::Record, Action::Start) => "record_start", - (OutputKind::Record, Action::Stop) => "record_stop", - (OutputKind::Record, Action::Status) => "record_status", - (OutputKind::Stream, Action::Start) => "stream_start", - (OutputKind::Stream, Action::Stop) => "stream_stop", - (OutputKind::Stream, Action::Status) => "stream_status", - } +typed_tool!( + RecordStart, + "record_start", + OutputBackend, + EmptyInput, + ActiveOutput, + IDEMPOTENT, + "Start record output.", + |backend, _input| { + backend.start_output(OutputRequest { + kind: OutputKind::Record, + }) } - - fn description(&self) -> &str { - match (self.kind, self.action) { - (OutputKind::Record, Action::Start) => "Start recording.", - (OutputKind::Record, Action::Stop) => "Stop recording.", - (OutputKind::Record, Action::Status) => { - "Report whether recording is active, with duration_ms and bytes where known." - } - (OutputKind::Stream, Action::Start) => "Start streaming.", - (OutputKind::Stream, Action::Stop) => "Stop streaming.", - (OutputKind::Stream, Action::Status) => { - "Report whether streaming is active, with duration_ms and bytes where known." - } - } +); +typed_tool!( + RecordStop, + "record_stop", + OutputBackend, + EmptyInput, + ActiveOutput, + IDEMPOTENT, + "Stop record output.", + |backend, _input| { + backend.stop_output(OutputRequest { + kind: OutputKind::Record, + }) } - - fn input_schema(&self) -> Value { - json!({ - "type": "object", - "properties": {}, - "additionalProperties": false, +); +typed_tool!( + RecordStatus, + "record_status", + OutputBackend, + EmptyInput, + OutputStatus, + READ_ONLY, + "Status record output.", + |backend, _input| { + Ok(backend.output_status(OutputRequest { + kind: OutputKind::Record, + })) + } +); +typed_tool!( + StreamStart, + "stream_start", + OutputBackend, + EmptyInput, + ActiveOutput, + IDEMPOTENT, + "Start stream output.", + |backend, _input| { + backend.start_output(OutputRequest { + kind: OutputKind::Stream, }) } - - fn call(&self, _arguments: &Value) -> Result { - let result = match self.action { - Action::Start => { - self.backend.start(self.kind)?; - json!({ "active": true }) - } - Action::Stop => { - self.backend.stop(self.kind)?; - json!({ "active": false }) - } - Action::Status => { - let status = self.backend.status(self.kind); - let mut out = Map::new(); - out.insert("active".into(), status.active.into()); - if let Some(ms) = status.duration_ms { - out.insert("duration_ms".into(), ms.into()); - } - if let Some(bytes) = status.bytes { - out.insert("bytes".into(), bytes.into()); - } - Value::Object(out) - } - }; - Ok(result.to_string()) +); +typed_tool!( + StreamStop, + "stream_stop", + OutputBackend, + EmptyInput, + ActiveOutput, + IDEMPOTENT, + "Stop stream output.", + |backend, _input| { + backend.stop_output(OutputRequest { + kind: OutputKind::Stream, + }) } +); +typed_tool!( + StreamStatus, + "stream_status", + OutputBackend, + EmptyInput, + OutputStatus, + READ_ONLY, + "Status stream output.", + |backend, _input| { + Ok(backend.output_status(OutputRequest { + kind: OutputKind::Stream, + })) + } +); +/// Registers the six typed output tools. +pub fn register(registry: &mut ToolRegistry, backend: &Rc) { + registry.register(Box::new(RecordStart { + backend: Rc::clone(backend), + })); + registry.register(Box::new(RecordStop { + backend: Rc::clone(backend), + })); + registry.register(Box::new(RecordStatus { + backend: Rc::clone(backend), + })); + registry.register(Box::new(StreamStart { + backend: Rc::clone(backend), + })); + registry.register(Box::new(StreamStop { + backend: Rc::clone(backend), + })); + registry.register(Box::new(StreamStatus { + backend: Rc::clone(backend), + })); } -/// Registers the six output tools on `registry`, backed by `backend`. -pub fn register(registry: &mut ToolRegistry, backend: &Rc) { - for kind in [OutputKind::Record, OutputKind::Stream] { - for action in [Action::Start, Action::Stop, Action::Status] { - registry.register(Box::new(OutputTool { - kind, - action, - backend: Rc::clone(backend), - })); - } - } +/// Generated tool schema contracts. +#[must_use] +pub fn schemas() -> Vec { + vec![ + crate::server::tool_schema::(), + crate::server::tool_schema::(), + crate::server::tool_schema::(), + crate::server::tool_schema::(), + crate::server::tool_schema::(), + crate::server::tool_schema::(), + ] +} + +/// Selects an output for backend operations. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct OutputRequest { + /// Output to operate on. + pub kind: OutputKind, } diff --git a/rust/obs-mcp/src/tools/scenes.rs b/rust/obs-mcp/src/tools/scenes.rs index 32fe5eb454..d558a4a9d5 100644 --- a/rust/obs-mcp/src/tools/scenes.rs +++ b/rust/obs-mcp/src/tools/scenes.rs @@ -7,15 +7,69 @@ use std::rc::Rc; -use serde_json::{Value, json}; +use super::EmptyInput; +use crate::server::ToolError; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; -use crate::server::{Tool, ToolRegistry}; +use crate::server::ToolRegistry; /// The scene operations the tools need from OBS. /// /// Methods take `&self`: libobs owns the state, so implementations use their /// own interior mutability. pub trait SceneBackend { + /// Typed `ListScenes` backend operation. + /// # Errors + /// Reports invalid state, a missing resource or processing failure. + fn list_scenes(&self, _input: EmptyInput) -> Result { + Ok(ScenesOutput { + scenes: self.scenes(), + }) + } + /// Typed `CurrentScene` backend operation. + /// # Errors + /// Reports invalid state, a missing resource or processing failure. + fn current_scene(&self, _input: EmptyInput) -> Result { + Ok(SceneOutput { + name: self.current(), + }) + } + /// Typed `SetScene` backend operation. + /// # Errors + /// Reports invalid state, a missing resource or processing failure. + fn set_scene(&self, input: NameInput) -> Result { + check_name(&input.name)?; + self.set_current(&input.name) + .map_err(ToolError::not_found)?; + Ok(SceneOutput { + name: Some(input.name), + }) + } + /// Typed `CreateScene` backend operation. + /// # Errors + /// Reports invalid state, a missing resource or processing failure. + fn create_scene(&self, input: NameInput) -> Result { + check_name(&input.name)?; + self.create(&input.name).map_err(ToolError::wrong_state)?; + Ok(SceneOutput { + name: Some(input.name), + }) + } + /// Typed `RemoveScene` backend operation. + /// # Errors + /// Reports invalid state, a missing resource or processing failure. + fn remove_scene(&self, input: NameInput) -> Result { + check_name(&input.name)?; + self.remove(&input.name).map_err(ToolError::not_found)?; + Ok(SceneOutput { + name: Some(input.name), + }) + } + + // Legacy backend hooks retained for existing implementers. New operations + // use the typed request/response methods above. + /// Scene names in display order. fn scenes(&self) -> Vec; /// The current program scene, if any. @@ -40,110 +94,112 @@ pub trait SceneBackend { fn remove(&self, name: &str) -> Result<(), String>; } -/// Which scene operation a [`SceneTool`] performs. -#[derive(Clone, Copy)] -enum Op { - List, - GetCurrent, - SetCurrent, - Create, - Remove, +/// A scene name. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct NameInput { + /// Scene name. + #[schemars(length(min = 1))] + pub name: String, } - -/// One scene tool bound to a backend. -struct SceneTool { - op: Op, - backend: Rc, +/// Scene listing. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +pub struct ScenesOutput { + /// Scene names in display order. + pub scenes: Vec, } - -impl SceneTool { - /// The `name` argument, which must be a non-empty string. - fn name_arg(arguments: &Value) -> Result<&str, String> { - match arguments.get("name").and_then(Value::as_str) { - Some(name) if !name.is_empty() => Ok(name), - _ => Err("argument `name` must be a non-empty string".into()), - } - } +/// Current or changed scene. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +pub struct SceneOutput { + /// Null when there is no program scene. + pub name: Option, } - -impl Tool for SceneTool { - fn name(&self) -> &str { - match self.op { - Op::List => "scenes_list", - Op::GetCurrent => "scene_get_current", - Op::SetCurrent => "scene_set_current", - Op::Create => "scene_create", - Op::Remove => "scene_remove", - } - } - - fn description(&self) -> &str { - match self.op { - Op::List => "List the names of all scenes, in order.", - Op::GetCurrent => "Get the name of the current program scene, or null if none.", - Op::SetCurrent => "Make the named scene the current program scene.", - Op::Create => { - "Create a new empty scene with the given name. When there is no program scene \ - yet, the new scene becomes the current program scene." - } - Op::Remove => "Remove the scene with the given name.", - } - } - - fn input_schema(&self) -> Value { - match self.op { - Op::List | Op::GetCurrent => json!({ - "type": "object", - "properties": {}, - "additionalProperties": false, - }), - Op::SetCurrent | Op::Create | Op::Remove => json!({ - "type": "object", - "properties": { - "name": { "type": "string", "minLength": 1, "description": "Scene name." }, - }, - "required": ["name"], - "additionalProperties": false, - }), - } - } - - fn call(&self, arguments: &Value) -> Result { - let result = match self.op { - Op::List => json!({ "scenes": self.backend.scenes() }), - Op::GetCurrent => json!({ "name": self.backend.current() }), - Op::SetCurrent => { - let name = Self::name_arg(arguments)?; - self.backend.set_current(name)?; - json!({ "name": name }) - } - Op::Create => { - let name = Self::name_arg(arguments)?; - self.backend.create(name)?; - json!({ "name": name }) - } - Op::Remove => { - let name = Self::name_arg(arguments)?; - self.backend.remove(name)?; - json!({ "name": name }) - } - }; - Ok(result.to_string()) +fn check_name(name: &str) -> Result<(), ToolError> { + if name.is_empty() { + Err(ToolError::processing( + "argument `name` must be a non-empty string", + )) + } else { + Ok(()) } } - -/// Registers the five scene tools on `registry`, backed by `backend`. +typed_tool!( + ListScenes, + "scenes_list", + SceneBackend, + EmptyInput, + ScenesOutput, + READ_ONLY, + "List the names of all scenes, in order.", + |backend, input| { backend.list_scenes(input) } +); +typed_tool!( + CurrentScene, + "scene_get_current", + SceneBackend, + EmptyInput, + SceneOutput, + READ_ONLY, + "Get the name of the current program scene, or null if none.", + |backend, input| { backend.current_scene(input) } +); +typed_tool!( + SetScene, + "scene_set_current", + SceneBackend, + NameInput, + SceneOutput, + IDEMPOTENT, + "Make the named scene the current program scene.", + |backend, input| { backend.set_scene(input) } +); +typed_tool!( + CreateScene, + "scene_create", + SceneBackend, + NameInput, + SceneOutput, + MUTATING, + "Create a new empty scene with the given name. When there is no program scene yet, the new scene becomes the current program scene.", + |backend, input| { backend.create_scene(input) } +); +typed_tool!( + RemoveScene, + "scene_remove", + SceneBackend, + NameInput, + SceneOutput, + MUTATING, + "Remove the scene with the given name.", + |backend, input| { backend.remove_scene(input) } +); +/// Registers the five typed scene tools. pub fn register(registry: &mut ToolRegistry, backend: &Rc) { - for op in [ - Op::List, - Op::GetCurrent, - Op::SetCurrent, - Op::Create, - Op::Remove, - ] { - registry.register(Box::new(SceneTool { - op, - backend: Rc::clone(backend), - })); - } + registry.register(Box::new(ListScenes { + backend: Rc::clone(backend), + })); + registry.register(Box::new(CurrentScene { + backend: Rc::clone(backend), + })); + registry.register(Box::new(SetScene { + backend: Rc::clone(backend), + })); + registry.register(Box::new(CreateScene { + backend: Rc::clone(backend), + })); + registry.register(Box::new(RemoveScene { + backend: Rc::clone(backend), + })); +} + +/// Generated tool schema contracts. +#[must_use] +pub fn schemas() -> Vec { + vec![ + crate::server::tool_schema::(), + crate::server::tool_schema::(), + crate::server::tool_schema::(), + crate::server::tool_schema::(), + crate::server::tool_schema::(), + ] } diff --git a/rust/obs-mcp/src/tools/screenshot.rs b/rust/obs-mcp/src/tools/screenshot.rs index 770dfb8919..0c675261ca 100644 --- a/rust/obs-mcp/src/tools/screenshot.rs +++ b/rust/obs-mcp/src/tools/screenshot.rs @@ -7,13 +7,15 @@ use std::io::Write as _; use std::rc::Rc; +use crate::server::{ToolAnnotations, ToolError, TypedTool}; use base64::Engine as _; use base64::engine::general_purpose::STANDARD; use flate2::write::ZlibEncoder; use flate2::{Compression, Crc}; -use serde_json::{Value, json}; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; -use crate::server::{Content, Tool, ToolRegistry}; +use crate::server::{Content, ToolRegistry}; /// Raw pixels from [`CaptureBackend::capture`]. #[derive(Clone, Debug, PartialEq, Eq)] @@ -28,6 +30,14 @@ pub struct Frame { /// The capture operation the tool needs from OBS. pub trait CaptureBackend { + /// Typed frame capture request. + /// # Errors + /// Reports a missing source or unavailable graphics pipeline. + fn capture_frame(&self, request: CaptureInput) -> Result { + self.capture(request.source.as_deref(), request.width, request.height) + .map_err(ToolError::processing) + } + /// Renders `source` (or the program output when `None`) and returns its /// pixels. `width` and `height` are the requested size; a side left `None` /// keeps the aspect ratio or the native size. @@ -107,85 +117,83 @@ fn push_chunk(png: &mut Vec, kind: &[u8; 4], data: &[u8]) -> Result<(), Stri Ok(()) } -/// An optional positive pixel dimension argument. -fn dimension_arg(arguments: &Value, key: &str) -> Result, String> { - match arguments.get(key) { - None => Ok(None), - Some(v) => v - .as_u64() - .and_then(|n| u32::try_from(n).ok()) - .filter(|&n| n > 0) - .map(Some) - .ok_or_else(|| format!("argument `{key}` must be a positive integer")), - } +/// Screenshot selection and requested size. +#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct CaptureInput { + /// Source to capture; omit for program output. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source: Option, + /// Width in pixels. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub width: Option, + /// Height in pixels. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub height: Option, +} +/// Captured PNG and its dimensions. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +pub struct CaptureOutput { + /// PNG bytes encoded in base64. + pub data: String, + /// Width in pixels. + pub width: u32, + /// Height in pixels. + pub height: u32, + /// Source name, or null for program output. + pub source: Option, } - -/// The `screenshot` tool bound to a backend. struct ScreenshotTool { backend: Rc, } - -impl ScreenshotTool { - /// Captures; returns the base64 PNG, its size and the source captured. - fn capture(&self, arguments: &Value) -> Result<(String, Frame, Option), String> { - let source = match arguments.get("source") { - None => None, - Some(Value::String(s)) if !s.is_empty() => Some(s.as_str()), - Some(_) => return Err("argument `source` must be a non-empty string".into()), - }; - let width = dimension_arg(arguments, "width")?; - let height = dimension_arg(arguments, "height")?; - let frame = self.backend.capture(source, width, height)?; - let png = STANDARD.encode(encode_png(&frame)?); - Ok((png, frame, source.map(str::to_owned))) - } -} - -impl Tool for ScreenshotTool { - fn name(&self) -> &str { - "screenshot" - } - +impl TypedTool for ScreenshotTool { + type Input = CaptureInput; + type Output = CaptureOutput; + const NAME: &'static str = "screenshot"; + const ANNOTATIONS: ToolAnnotations = ToolAnnotations::READ_ONLY; fn description(&self) -> &str { - "Capture a PNG screenshot of a source, or of the program output when no source is named. \ - Returns the image plus a text item {width, height, source} (source is null for the \ - program output). The PNG has an alpha channel (RGBA): pixels nothing was drawn on, such as an empty scene, \ - are fully transparent, which a viewer may show as white. A source only appears in the \ - program output once it is an item of the program scene." + "Capture a PNG screenshot of a source, or of the program output when no source is named. Returns the image plus a text item {width, height, source} (source is null for the program output). The PNG has an alpha channel (RGBA): pixels nothing was drawn on, such as an empty scene, are fully transparent, which a viewer may show as white. A source only appears in the program output once it is an item of the program scene." } - - fn input_schema(&self) -> Value { - json!({ - "type": "object", - "properties": { - "source": { "type": "string", "minLength": 1, "description": "Source name; omit for the program output." }, - "width": { "type": "integer", "minimum": 1, "description": "Image width in pixels." }, - "height": { "type": "integer", "minimum": 1, "description": "Image height in pixels." }, - }, - "additionalProperties": false, + fn call(&self, input: CaptureInput) -> Result { + if input.source.as_ref().is_some_and(String::is_empty) { + return Err(ToolError::processing( + "argument `source` must be a non-empty string", + )); + } + if input.width == Some(0) || input.height == Some(0) { + return Err(ToolError::processing( + "width and height must be positive integers", + )); + } + let frame = self.backend.capture_frame(input.clone())?; + let data = STANDARD.encode(encode_png(&frame).map_err(ToolError::processing)?); + Ok(CaptureOutput { + data, + width: frame.width, + height: frame.height, + source: input.source, }) } - - fn call(&self, arguments: &Value) -> Result { - self.capture(arguments).map(|(png, ..)| png) - } - - fn call_content(&self, arguments: &Value) -> Result, String> { - let (data, frame, source) = self.capture(arguments)?; - let size = json!({ "width": frame.width, "height": frame.height, "source": source }); + fn content(output: &CaptureOutput) -> Result, ToolError> { + let size = serde_json::json!({ "width": output.width, "height": output.height, "source": output.source }); Ok(vec![ Content::Image { - data, + data: output.data.clone(), mime_type: "image/png".to_owned(), }, Content::Text(size.to_string()), ]) } } - -/// Registers the `screenshot` tool on `registry`, backed by `backend`. +/// Registers the typed screenshot tool. pub fn register(registry: &mut ToolRegistry, backend: &Rc) { registry.register(Box::new(ScreenshotTool { backend: Rc::clone(backend), })); } + +/// Generated tool schema contracts. +#[must_use] +pub fn schemas() -> Vec { + vec![crate::server::tool_schema::()] +} diff --git a/rust/obs-mcp/src/tools/sources.rs b/rust/obs-mcp/src/tools/sources.rs index bf07c616c5..b246af156e 100644 --- a/rust/obs-mcp/src/tools/sources.rs +++ b/rust/obs-mcp/src/tools/sources.rs @@ -7,12 +7,16 @@ use std::rc::Rc; -use serde_json::{Map, Value, json}; +use super::EmptyInput; +use crate::server::ToolError; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; -use crate::server::{Tool, ToolRegistry}; +use crate::server::ToolRegistry; /// A source as listed by [`SourceBackend::sources`]. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] pub struct SourceInfo { /// The source's unique name. pub name: String, @@ -39,7 +43,7 @@ pub struct ItemInfo { /// Names a scene item: by the id `scene_items_list` returns, or by the name /// of its source (the first item of that source). -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] pub enum ItemRef { /// The item id. Id(i64), @@ -63,6 +67,132 @@ pub struct Transform { /// Methods take `&self`: libobs owns the state, so implementations use their /// own interior mutability. pub trait SourceBackend { + /// Typed `ListSources` backend operation. + /// # Errors + /// Reports invalid state, a missing resource or processing failure. + fn list_sources(&self, _input: EmptyInput) -> Result { + Ok(SourcesOutput { + sources: self.sources(), + }) + } + /// Typed `CreateSource` backend operation. + /// # Errors + /// Reports invalid state, a missing resource or processing failure. + fn create_source(&self, input: CreateInput) -> Result { + nonempty(&input.name)?; + nonempty(&input.kind)?; + if input.position.is_some() && input.scene.is_none() { + return Err(ToolError::processing( + "`position` needs `scene`, the scene to add the source to", + )); + } + if let Some(scene) = &input.scene { + nonempty(scene)?; + } + self.create(&input.kind, &input.name, &Value::Object(input.settings)) + .map_err(ToolError::processing)?; + let item = if let Some(scene) = &input.scene { + Some( + self.add_item(scene, &input.name, input.position.map(Pair::tuple)) + .map_err(|error| { + ToolError::processing(format!( + "created source '{}' but could not add it to scene '{scene}': {error}", + input.name + )) + })? + .id, + ) + } else { + None + }; + Ok(CreateOutput { + name: input.name, + kind: input.kind, + scene: input.scene, + item, + }) + } + /// Typed `SetSettings` backend operation. + /// # Errors + /// Reports invalid state, a missing resource or processing failure. + fn update_settings(&self, input: SettingsInput) -> Result { + nonempty(&input.name)?; + self.set_settings(&input.name, &Value::Object(input.settings)) + .map_err(ToolError::not_found)?; + Ok(NameOutput { name: input.name }) + } + /// Typed `AddItem` backend operation. + /// # Errors + /// Reports invalid state, a missing resource or processing failure. + fn add_scene_item(&self, input: AddItemInput) -> Result { + nonempty(&input.scene)?; + nonempty(&input.source)?; + let mut output = ItemOutput::from( + self.add_item(&input.scene, &input.source, input.position.map(Pair::tuple)) + .map_err(ToolError::not_found)?, + ); + output.scene = Some(input.scene); + Ok(output) + } + /// Typed `ListItems` backend operation. + /// # Errors + /// Reports invalid state, a missing resource or processing failure. + fn list_scene_items(&self, input: ItemsInput) -> Result { + nonempty(&input.scene)?; + Ok(ItemsOutput { + items: self + .items(&input.scene) + .map_err(ToolError::not_found)? + .into_iter() + .map(ItemOutput::from) + .collect(), + scene: input.scene, + }) + } + /// Typed `SetVisible` backend operation. + /// # Errors + /// Reports invalid state, a missing resource or processing failure. + fn update_visibility(&self, input: VisibleInput) -> Result { + nonempty(&input.scene)?; + let item = selector(input.item, input.source.as_deref())?; + self.set_item_visible(&input.scene, &item, input.visible) + .map_err(ToolError::not_found)?; + Ok(ItemReply { + scene: input.scene, + item: input.item, + source: input.source, + visible: Some(input.visible), + }) + } + /// Typed `SetTransform` backend operation. + /// # Errors + /// Reports invalid state, a missing resource or processing failure. + fn update_transform(&self, input: TransformInput) -> Result { + nonempty(&input.scene)?; + let item = selector(input.item, input.source.as_deref())?; + let transform = Transform { + position: input.position.map(Pair::tuple), + scale: input.scale.map(Pair::tuple), + rotation: input.rotation, + }; + if transform == Transform::default() { + return Err(ToolError::processing( + "give at least one of `position`, `scale` or `rotation`", + )); + } + self.set_item_transform(&input.scene, &item, &transform) + .map_err(ToolError::not_found)?; + Ok(ItemReply { + scene: input.scene, + item: input.item, + source: input.source, + visible: None, + }) + } + + // Legacy backend hooks retained for existing implementers. New operations + // use the typed request/response methods above. + /// Every source, in a stable order. fn sources(&self) -> Vec; /// Creates a source of `kind` called `name` with `settings`. @@ -114,331 +244,313 @@ pub trait SourceBackend { ) -> Result<(), String>; } -/// Which source operation a [`SourceTool`] performs. -#[derive(Clone, Copy)] -enum Op { - List, - Create, - SetSettings, - ItemAdd, - ItemsList, - ItemSetVisible, - ItemSetTransform, +/// Pixel position or scale factors. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Pair { + /// Horizontal component. + pub x: f64, + /// Vertical component. + pub y: f64, } - -/// One source tool bound to a backend. -struct SourceTool { - op: Op, - backend: Rc, -} - -/// A required, non-empty string argument. -fn str_arg<'a>(arguments: &'a Value, key: &str) -> Result<&'a str, String> { - match arguments.get(key).and_then(Value::as_str) { - Some(s) if !s.is_empty() => Ok(s), - _ => Err(format!("argument `{key}` must be a non-empty string")), +impl Pair { + fn tuple(self) -> (f64, f64) { + (self.x, self.y) } } - -/// A required object argument. -fn object_arg<'a>(arguments: &'a Value, key: &str) -> Result<&'a Value, String> { - match arguments.get(key) { - Some(v) if v.is_object() => Ok(v), - _ => Err(format!("argument `{key}` must be an object")), - } +/// Source creation, optionally placing it in a scene. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct CreateInput { + /// Source kind id. + pub kind: String, + /// Unique name. + pub name: String, + /// Kind-specific settings. + pub settings: Map, + /// Scene receiving the source. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scene: Option, + /// Initial position (requires scene). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub position: Option, } - -/// An optional `{x, y}` pair; both members must be finite numbers. -fn pair_arg(arguments: &Value, key: &str) -> Result, String> { - let Some(v) = arguments.get(key) else { - return Ok(None); - }; - let bad = || format!("argument `{key}` must be an object with numeric `x` and `y`"); - let num = |k: &str| { - v.get(k) - .and_then(Value::as_f64) - .filter(|n| n.is_finite()) - .ok_or_else(bad) - }; - if !v.is_object() { - return Err(bad()); - } - Ok(Some((num("x")?, num("y")?))) +/// Created source. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +pub struct CreateOutput { + /// Source name. + pub name: String, + /// Source kind. + pub kind: String, + /// Scene receiving the new item. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scene: Option, + /// Created item id. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub item: Option, } - -/// The item a tool names: `item` (an id) or `source`, exactly one of them. -fn item_arg(arguments: &Value) -> Result { - match (arguments.get("item"), arguments.get("source")) { - (Some(_), Some(_)) => Err("give `item` or `source`, not both".into()), - (Some(id), None) => id - .as_i64() - .map(ItemRef::Id) - .ok_or_else(|| "argument `item` must be an integer item id".into()), - (None, Some(_)) => str_arg(arguments, "source").map(|s| ItemRef::Source(s.to_owned())), - (None, None) => Err("give `item` (an id from scene_items_list) or `source`".into()), - } +/// Settings update. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct SettingsInput { + /// Source name. + pub name: String, + /// Kind-specific settings to merge. + pub settings: Map, } - -/// The reply of an item tool: the scene, the item as it was named, and `extra`. -fn item_reply(scene: &str, item: &ItemRef, extra: Value) -> Value { - let mut out = Map::new(); - out.insert("scene".into(), scene.into()); - match item { - ItemRef::Id(id) => out.insert("item".into(), (*id).into()), - ItemRef::Source(source) => out.insert("source".into(), source.as_str().into()), - }; - if let Value::Object(extra) = extra { - out.extend(extra); - } - Value::Object(out) +/// Updated source name. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +pub struct NameOutput { + /// Source name. + pub name: String, } - -/// The JSON form of a listed item. -fn item_json(item: &ItemInfo) -> Value { - let pair = |(x, y): (f64, f64)| json!({ "x": x, "y": y }); - json!({ - "item": item.id, - "source": item.source, - "visible": item.visible, - "position": pair(item.position), - "scale": pair(item.scale), - "rotation": item.rotation, - }) +/// Source listing. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +pub struct SourcesOutput { + /// Sources in stable order. + pub sources: Vec, } - -/// Schema for an `{x, y}` pair. -fn pair_schema(description: &str) -> Value { - json!({ - "type": "object", - "properties": { "x": { "type": "number" }, "y": { "type": "number" } }, - "required": ["x", "y"], - "additionalProperties": false, - "description": description, - }) +/// Place an existing source in a scene. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct AddItemInput { + /// Scene name. + pub scene: String, + /// Source name. + pub source: String, + /// Initial position. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub position: Option, } - -impl Tool for SourceTool { - fn name(&self) -> &str { - match self.op { - Op::List => "sources_list", - Op::Create => "source_create", - Op::SetSettings => "source_set_settings", - Op::ItemAdd => "scene_item_add", - Op::ItemsList => "scene_items_list", - Op::ItemSetVisible => "scene_item_set_visible", - Op::ItemSetTransform => "scene_item_set_transform", +/// Scene selection. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ItemsInput { + /// Scene name. + pub scene: String, +} +/// Listed scene item, preserving the existing wire fields. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +pub struct ItemOutput { + /// Item id. + pub item: i64, + /// Source name. + pub source: String, + /// Visibility. + pub visible: bool, + /// Canvas position. + pub position: Pair, + /// Scale factors. + pub scale: Pair, + /// Rotation in degrees. + pub rotation: f64, + /// Present when an item was added. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scene: Option, +} +impl From for ItemOutput { + fn from(item: ItemInfo) -> Self { + Self { + item: item.id, + source: item.source, + visible: item.visible, + position: Pair { + x: item.position.0, + y: item.position.1, + }, + scale: Pair { + x: item.scale.0, + y: item.scale.1, + }, + rotation: item.rotation, + scene: None, } } - - fn description(&self) -> &str { - match self.op { - Op::List => "List all sources with their names and kind ids.", - Op::Create => { - "Create a source of the given kind with a name and settings. Give `scene` \ - (and optionally `position`) to also add it to that scene as an item." - } - Op::SetSettings => "Merge settings into an existing source's settings.", - Op::ItemAdd => { - "Add an existing source to a scene as a scene item, optionally at a position. \ - A source only shows in the program output once it is an item of the program scene." - } - Op::ItemsList => { - "List the items of a scene (bottom to top) with their id, source name, \ - visibility, position, scale and rotation." - } - Op::ItemSetVisible => { - "Show or hide a scene item, named by `item` (id from scene_items_list) or `source`." - } - Op::ItemSetTransform => { - "Set the position, scale and/or rotation of a scene item, named by `item` \ - (id from scene_items_list) or `source`." - } - } +} +/// Items of a scene. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +pub struct ItemsOutput { + /// Scene name. + pub scene: String, + /// Items bottom to top. + pub items: Vec, +} +/// Visibility update; exactly one of item/source must be specified. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct VisibleInput { + /// Scene name. + pub scene: String, + /// Item id. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub item: Option, + /// Source name instead of item id. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source: Option, + /// New visibility. + pub visible: bool, +} +/// Transform update; at least one transform field is required. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct TransformInput { + /// Scene name. + pub scene: String, + /// Item id. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub item: Option, + /// Source name instead of item id. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source: Option, + /// New position. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub position: Option, + /// New scale. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scale: Option, + /// New rotation in degrees. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rotation: Option, +} +/// Item mutation response, retaining the caller's selector. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +pub struct ItemReply { + /// Scene name. + pub scene: String, + /// Item id when selected by id. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub item: Option, + /// Source name when selected by name. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source: Option, + /// Present for visibility changes. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub visible: Option, +} +fn nonempty(name: &str) -> Result<(), ToolError> { + if name.is_empty() { + Err(ToolError::processing("name must be a non-empty string")) + } else { + Ok(()) } - - fn input_schema(&self) -> Value { - let name = json!({ "type": "string", "minLength": 1 }); - let item_id = json!({ - "type": "integer", - "description": "Item id from scene_items_list; give this or `source`.", - }); - match self.op { - Op::List => json!({ - "type": "object", - "properties": {}, - "additionalProperties": false, - }), - Op::Create => json!({ - "type": "object", - "properties": { - "kind": { "type": "string", "minLength": 1, "description": "Source kind id." }, - "name": { "type": "string", "minLength": 1, "description": "Source name." }, - "settings": { "type": "object", "description": "Kind-specific settings." }, - "scene": { "type": "string", "minLength": 1, "description": "Scene to add the new source to as an item." }, - "position": pair_schema("Item position in canvas pixels; needs `scene`."), - }, - "required": ["kind", "name", "settings"], - "additionalProperties": false, - }), - Op::SetSettings => json!({ - "type": "object", - "properties": { - "name": { "type": "string", "minLength": 1, "description": "Source name." }, - "settings": { "type": "object", "description": "Settings to merge in." }, - }, - "required": ["name", "settings"], - "additionalProperties": false, - }), - Op::ItemAdd => json!({ - "type": "object", - "properties": { - "scene": name, - "source": name, - "position": pair_schema("Item position in canvas pixels."), - }, - "required": ["scene", "source"], - "additionalProperties": false, - }), - Op::ItemsList => json!({ - "type": "object", - "properties": { "scene": name }, - "required": ["scene"], - "additionalProperties": false, - }), - Op::ItemSetVisible => json!({ - "type": "object", - "properties": { - "scene": name, - "item": item_id, - "source": name, - "visible": { "type": "boolean" }, - }, - "required": ["scene", "visible"], - "additionalProperties": false, - }), - Op::ItemSetTransform => json!({ - "type": "object", - "properties": { - "scene": name, - "item": item_id, - "source": name, - "position": pair_schema("Position in canvas pixels."), - "scale": pair_schema("Scale factors."), - "rotation": { "type": "number", "description": "Rotation in degrees." }, - }, - "required": ["scene"], - "additionalProperties": false, - }), +} +fn selector(item: Option, source: Option<&str>) -> Result { + match (item, source) { + (Some(id), None) => Ok(ItemRef::Id(id)), + (None, Some(name)) => { + nonempty(name)?; + Ok(ItemRef::Source(name.to_owned())) } - } - - fn call(&self, arguments: &Value) -> Result { - let result = match self.op { - Op::List => { - let sources: Vec = self - .backend - .sources() - .into_iter() - .map(|s| json!({ "name": s.name, "kind": s.kind })) - .collect(); - json!({ "sources": sources }) - } - Op::Create => { - let kind = str_arg(arguments, "kind")?; - let name = str_arg(arguments, "name")?; - let settings = object_arg(arguments, "settings")?; - let scene = match arguments.get("scene") { - None => None, - Some(_) => Some(str_arg(arguments, "scene")?), - }; - let position = pair_arg(arguments, "position")?; - if scene.is_none() && position.is_some() { - return Err("`position` needs `scene`, the scene to add the source to".into()); - } - self.backend.create(kind, name, settings)?; - let mut out = json!({ "name": name, "kind": kind }); - if let Some(scene) = scene { - let item = self.backend.add_item(scene, name, position).map_err(|e| { - format!( - "created source '{name}' but could not add it to scene '{scene}': {e}" - ) - })?; - out["scene"] = scene.into(); - out["item"] = item.id.into(); - } - out - } - Op::SetSettings => { - let name = str_arg(arguments, "name")?; - let settings = object_arg(arguments, "settings")?; - self.backend.set_settings(name, settings)?; - json!({ "name": name }) - } - Op::ItemAdd => { - let scene = str_arg(arguments, "scene")?; - let source = str_arg(arguments, "source")?; - let position = pair_arg(arguments, "position")?; - let item = self.backend.add_item(scene, source, position)?; - let mut out = item_json(&item); - out["scene"] = scene.into(); - out - } - Op::ItemsList => { - let scene = str_arg(arguments, "scene")?; - let items: Vec = self.backend.items(scene)?.iter().map(item_json).collect(); - json!({ "scene": scene, "items": items }) - } - Op::ItemSetVisible => { - let scene = str_arg(arguments, "scene")?; - let item = item_arg(arguments)?; - let visible = arguments - .get("visible") - .and_then(Value::as_bool) - .ok_or("argument `visible` must be a boolean")?; - self.backend.set_item_visible(scene, &item, visible)?; - item_reply(scene, &item, json!({ "visible": visible })) - } - Op::ItemSetTransform => { - let scene = str_arg(arguments, "scene")?; - let item = item_arg(arguments)?; - let rotation = match arguments.get("rotation") { - None => None, - Some(v) => Some( - v.as_f64() - .filter(|n| n.is_finite()) - .ok_or("argument `rotation` must be a number")?, - ), - }; - let transform = Transform { - position: pair_arg(arguments, "position")?, - scale: pair_arg(arguments, "scale")?, - rotation, - }; - if transform == Transform::default() { - return Err("give at least one of `position`, `scale` or `rotation`".into()); - } - self.backend.set_item_transform(scene, &item, &transform)?; - item_reply(scene, &item, json!({})) - } - }; - Ok(result.to_string()) + _ => Err(ToolError::processing( + "give exactly one of `item` or `source`", + )), } } - -/// Registers the seven source tools on `registry`, backed by `backend`. +typed_tool!( + ListSources, + "sources_list", + SourceBackend, + EmptyInput, + SourcesOutput, + READ_ONLY, + "List all sources with their names and kind ids.", + |backend, input| { backend.list_sources(input) } +); +typed_tool!( + CreateSource, + "source_create", + SourceBackend, + CreateInput, + CreateOutput, + MUTATING, + "Create a source of the given kind with a name and settings. Give `scene` (and optionally `position`) to also add it to that scene as an item.", + |backend, input| { backend.create_source(input) } +); +typed_tool!( + SetSettings, + "source_set_settings", + SourceBackend, + SettingsInput, + NameOutput, + MUTATING, + "Merge settings into an existing source's settings.", + |backend, input| { backend.update_settings(input) } +); +typed_tool!( + AddItem, + "scene_item_add", + SourceBackend, + AddItemInput, + ItemOutput, + MUTATING, + "Add an existing source to a scene as a scene item, optionally at a position. A source only shows in the program output once it is an item of the program scene.", + |backend, input| { backend.add_scene_item(input) } +); +typed_tool!( + ListItems, + "scene_items_list", + SourceBackend, + ItemsInput, + ItemsOutput, + READ_ONLY, + "List the items of a scene (bottom to top) with their id, source name, visibility, position, scale and rotation.", + |backend, input| { backend.list_scene_items(input) } +); +typed_tool!( + SetVisible, + "scene_item_set_visible", + SourceBackend, + VisibleInput, + ItemReply, + IDEMPOTENT, + "Show or hide a scene item, named by `item` (id from scene_items_list) or `source`.", + |backend, input| { backend.update_visibility(input) } +); +typed_tool!( + SetTransform, + "scene_item_set_transform", + SourceBackend, + TransformInput, + ItemReply, + MUTATING, + "Set the position, scale and/or rotation of a scene item, named by `item` (id from scene_items_list) or `source`.", + |backend, input| { backend.update_transform(input) } +); +/// Registers seven typed source tools. pub fn register(registry: &mut ToolRegistry, backend: &Rc) { - for op in [ - Op::List, - Op::Create, - Op::SetSettings, - Op::ItemAdd, - Op::ItemsList, - Op::ItemSetVisible, - Op::ItemSetTransform, - ] { - registry.register(Box::new(SourceTool { - op, - backend: Rc::clone(backend), - })); - } + registry.register(Box::new(ListSources { + backend: Rc::clone(backend), + })); + registry.register(Box::new(CreateSource { + backend: Rc::clone(backend), + })); + registry.register(Box::new(SetSettings { + backend: Rc::clone(backend), + })); + registry.register(Box::new(AddItem { + backend: Rc::clone(backend), + })); + registry.register(Box::new(ListItems { + backend: Rc::clone(backend), + })); + registry.register(Box::new(SetVisible { + backend: Rc::clone(backend), + })); + registry.register(Box::new(SetTransform { + backend: Rc::clone(backend), + })); +} + +/// Generated tool schema contracts. +#[must_use] +pub fn schemas() -> Vec { + vec![ + crate::server::tool_schema::(), + crate::server::tool_schema::(), + crate::server::tool_schema::(), + crate::server::tool_schema::(), + crate::server::tool_schema::(), + crate::server::tool_schema::(), + crate::server::tool_schema::(), + ] } diff --git a/rust/obs-mcp/tests/mcp/outputs.rs b/rust/obs-mcp/tests/mcp/outputs.rs index 676841d125..a0eb11abae 100644 --- a/rust/obs-mcp/tests/mcp/outputs.rs +++ b/rust/obs-mcp/tests/mcp/outputs.rs @@ -94,6 +94,10 @@ fn lists_six_tools_with_empty_object_schemas() { ] ); for t in tools { + let snapshot = obs_mcp::tools::schema_snapshot(); + let contract = snapshot["tools"].as_array().unwrap().iter().find(|entry| entry["name"] == t["name"]).unwrap(); + for field in ["inputSchema", "outputSchema", "annotations"] { assert_eq!(t[field], contract[field]); } + assert_eq!(t["inputSchema"]["type"], "object"); assert_eq!(t["inputSchema"]["properties"], json!({})); assert_eq!(t["inputSchema"]["additionalProperties"], false); @@ -151,18 +155,28 @@ fn record_and_stream_are_independent() { call(&mut s, "record_status", &json!({})), (false, json!({"active": false})) ); - assert!(call(&mut s, "record_stop", &json!({})).0); + assert_eq!( + call(&mut s, "record_stop", &json!({})), + (false, json!({"active": false})) + ); assert_eq!(call(&mut s, "stream_status", &json!({})).1["active"], true); } #[test] -fn backend_errors_become_tool_errors() { +fn start_and_stop_are_idempotent() { let mut s = server(); - let (is_err, msg) = call(&mut s, "record_stop", &json!({})); - assert!(is_err); - assert!(msg.as_str().unwrap().contains("not active")); - assert!(!call(&mut s, "stream_start", &json!({})).0); - let (is_err, msg) = call(&mut s, "stream_start", &json!({})); - assert!(is_err); - assert!(msg.as_str().unwrap().contains("already active")); + for name in [ + "record_stop", + "record_stop", + "record_start", + "record_start", + "record_stop", + "record_stop", + ] { + let active = name.ends_with("start"); + assert_eq!( + call(&mut s, name, &json!({})), + (false, json!({"active": active})) + ); + } } diff --git a/rust/obs-mcp/tests/mcp/scenes.rs b/rust/obs-mcp/tests/mcp/scenes.rs index 86c7628139..8acab021ad 100644 --- a/rust/obs-mcp/tests/mcp/scenes.rs +++ b/rust/obs-mcp/tests/mcp/scenes.rs @@ -64,6 +64,9 @@ fn rpc(s: &mut Server, method: &str, params: &Value) -> Value { /// Calls a tool; returns (isError, parsed JSON text or the error text). fn call(s: &mut Server, name: &str, args: &Value) -> (bool, Value) { let r = rpc(s, "tools/call", &json!({"name": name, "arguments": args})); + if let Some(error) = r.get("error") { + return (true, error["message"].clone()); + } let res = &r["result"]; let text = res["content"][0]["text"].as_str().expect("text content"); let is_err = res["isError"] == true; @@ -93,6 +96,10 @@ fn lists_five_tools_with_object_schemas() { ] ); for t in tools { + let snapshot = obs_mcp::tools::schema_snapshot(); + let contract = snapshot["tools"].as_array().unwrap().iter().find(|entry| entry["name"] == t["name"]).unwrap(); + for field in ["inputSchema", "outputSchema", "annotations"] { assert_eq!(t[field], contract[field]); } + assert_eq!(t["inputSchema"]["type"], "object"); assert!(!t["description"].as_str().unwrap().is_empty()); } diff --git a/rust/obs-mcp/tests/mcp/screenshot.rs b/rust/obs-mcp/tests/mcp/screenshot.rs index cb1b4535f5..e10754f009 100644 --- a/rust/obs-mcp/tests/mcp/screenshot.rs +++ b/rust/obs-mcp/tests/mcp/screenshot.rs @@ -127,6 +127,10 @@ fn lists_screenshot_with_optional_arguments() { let tools = r["result"]["tools"].as_array().unwrap(); assert_eq!(tools.len(), 1); assert_eq!(tools[0]["name"], "screenshot"); + let snapshot = obs_mcp::tools::schema_snapshot(); + let contract = snapshot["tools"].as_array().unwrap().iter().find(|entry| entry["name"] == "screenshot").unwrap(); + for field in ["inputSchema", "outputSchema", "annotations"] { assert_eq!(tools[0][field], contract[field]); } + let schema = &tools[0]["inputSchema"]; assert_eq!(schema["type"], "object"); assert_eq!(schema["additionalProperties"], false); @@ -210,8 +214,15 @@ fn invalid_arguments_never_reach_the_backend() { json!({"width": 1.5}), json!({"width": 99_999_999_999_u64}), ] { - let result = shoot(&mut s, &args); - assert_eq!(result["isError"], true, "{args}"); + let response = rpc( + &mut s, + "tools/call", + &json!({"name":"screenshot", "arguments":args}), + ); + assert!( + response["error"]["code"] == -32602 || response["result"]["isError"] == true, + "{args}: {response}" + ); } assert!(fake.requests.borrow().is_empty()); } diff --git a/rust/obs-mcp/tests/mcp/sources.rs b/rust/obs-mcp/tests/mcp/sources.rs index bf1a15a3dc..dd83c31806 100644 --- a/rust/obs-mcp/tests/mcp/sources.rs +++ b/rust/obs-mcp/tests/mcp/sources.rs @@ -147,6 +147,9 @@ fn rpc(s: &mut Server, method: &str, params: &Value) -> Value { /// Calls a tool; returns (isError, parsed JSON text or the error text). fn call(s: &mut Server, name: &str, args: &Value) -> (bool, Value) { let r = rpc(s, "tools/call", &json!({"name": name, "arguments": args})); + if let Some(error) = r.get("error") { + return (true, error["message"].clone()); + } let res = &r["result"]; let text = res["content"][0]["text"].as_str().expect("text content"); let is_err = res["isError"] == true; @@ -186,6 +189,10 @@ fn lists_seven_tools_with_object_schemas() { ] ); for t in tools { + let snapshot = obs_mcp::tools::schema_snapshot(); + let contract = snapshot["tools"].as_array().unwrap().iter().find(|entry| entry["name"] == t["name"]).unwrap(); + for field in ["inputSchema", "outputSchema", "annotations"] { assert_eq!(t[field], contract[field]); } + assert_eq!(t["inputSchema"]["type"], "object"); assert!(!t["description"].as_str().unwrap().is_empty()); } @@ -199,8 +206,11 @@ fn lists_seven_tools_with_object_schemas() { "object" ); let xf = &find("scene_item_set_transform")["inputSchema"]["properties"]; - assert_eq!(xf["position"]["required"], json!(["x", "y"])); - assert_eq!(xf["rotation"]["type"], "number"); + assert_eq!( + find("scene_item_set_transform")["inputSchema"]["$defs"]["Pair"]["required"], + json!(["x", "y"]) + ); + assert_eq!(xf["rotation"]["type"], json!(["number", "null"])); } #[test] @@ -442,7 +452,7 @@ fn bad_arguments_are_tool_errors() { }; let cases = [ ("source_create", json!({}), "kind"), - ("source_create", json!({"kind": "k", "name": ""}), "name"), + ("source_create", json!({"kind": "k", "name": "", "settings": {}}), "name"), ( "source_create", json!({"kind": "k", "name": "n"}), diff --git a/rust/obs-mcp/tests/mcp/typed.rs b/rust/obs-mcp/tests/mcp/typed.rs index 7cb5d9a0c6..33f224bf11 100644 --- a/rust/obs-mcp/tests/mcp/typed.rs +++ b/rust/obs-mcp/tests/mcp/typed.rs @@ -1,23 +1,31 @@ //! Typed control API contract (#4445), in the existing core harness. -use obs_mcp::server::{ToolRegistry, TypedTool, ToolAnnotations, ToolError}; +use obs_mcp::server::{ToolAnnotations, ToolError, ToolRegistry, TypedTool}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use serde_json::json; #[derive(Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] -struct Input { value: String } +struct Input { + value: String, +} #[derive(Serialize, JsonSchema)] -struct Output { value: String } +struct Output { + value: String, +} struct Echo; impl TypedTool for Echo { type Input = Input; type Output = Output; const NAME: &'static str = "typed_echo"; const ANNOTATIONS: ToolAnnotations = ToolAnnotations::READ_ONLY; - fn description(&self) -> &str { "Typed echo" } + fn description(&self) -> &str { + "Typed echo" + } fn call(&self, input: Input) -> Result { - if input.value == "fail" { return Err(ToolError::processing("deliberate failure")); } + if input.value == "fail" { + return Err(ToolError::processing("deliberate failure")); + } Ok(Output { value: input.value }) } } @@ -26,11 +34,69 @@ fn typed_schema_and_structured_result() { let mut tools = ToolRegistry::new(); tools.register(Box::new(Echo)); let listed = tools.list(); - assert_eq!(listed["tools"][0]["outputSchema"]["properties"]["value"]["type"], "string"); + assert_eq!( + listed["tools"][0]["outputSchema"]["properties"]["value"]["type"], + "string" + ); assert_eq!(listed["tools"][0]["annotations"]["readOnlyHint"], true); let mut server = obs_mcp::server::Server::with_tools(tools); let mut out = Vec::new(); server.serve(b"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"typed_echo\",\"arguments\":{\"value\":\"hello\"}}}\n".as_slice(), &mut out).unwrap(); let reply: serde_json::Value = serde_json::from_slice(&out).unwrap(); - assert_eq!(reply["result"]["structuredContent"], json!({"value":"hello"})); + assert_eq!( + reply["result"]["structuredContent"], + json!({"value":"hello"}) + ); +} + +fn rpc(arguments: serde_json::Value) -> serde_json::Value { + let mut tools = ToolRegistry::new(); + tools.register(Box::new(Echo)); + let mut server = obs_mcp::server::Server::with_tools(tools); + let line = json!({"jsonrpc":"2.0", "id":7, "method":"tools/call", "params":{"name":"typed_echo", "arguments":arguments}}).to_string() + "\n"; + let mut out = Vec::new(); + server.serve(line.as_bytes(), &mut out).unwrap(); + serde_json::from_slice(&out).unwrap() +} +#[test] +fn argument_faults_are_protocol_errors() { + for args in [ + json!({}), + json!({"value":2}), + json!({"value":"a","typo":true}), + json!([]), + ] { + let response = rpc(args); + assert_eq!(response["error"]["code"], -32602); + assert!(response.get("result").is_none()); + assert_eq!(response["id"], 7); + } +} +#[test] +fn domain_errors_have_machine_readable_status() { + let response = rpc(json!({"value":"fail"})); + assert!(response.get("error").is_none()); + assert_eq!(response["result"]["isError"], true); + assert_eq!( + response["result"]["structuredContent"], + json!({"code":700,"category":"processing","message":"deliberate failure","retryable":false}) + ); + let text: serde_json::Value = + serde_json::from_str(response["result"]["content"][0]["text"].as_str().unwrap()).unwrap(); + assert_eq!(text, response["result"]["structuredContent"]); +} +#[test] +fn schema_snapshot_has_not_drifted() { + let actual = obs_mcp::tools::schema_snapshot(); + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../docs/rust-port/control-api.schema.json"); + if std::env::var_os("OBS_UPDATE_CONTROL_SCHEMA").is_some() { + std::fs::write(&path, serde_json::to_string_pretty(&actual).unwrap() + "\n").unwrap(); + } + let expected: serde_json::Value = + serde_json::from_slice(&std::fs::read(path).expect("committed schema snapshot")).unwrap(); + assert_eq!( + actual, expected, + "regenerate with OBS_UPDATE_CONTROL_SCHEMA=1 and the focused schema test" + ); } From b23483d7e977f56e386a978fe84b34366f0ed49e Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 13:43:49 -0800 Subject: [PATCH 03/39] docs(mcp): format generated schema by tool for review (#4445) --- docs/rust-port/control-api.schema.json | 1252 +----------------------- rust/obs-mcp/tests/mcp/typed.rs | 3 +- 2 files changed, 22 insertions(+), 1233 deletions(-) diff --git a/docs/rust-port/control-api.schema.json b/docs/rust-port/control-api.schema.json index b74dbf66c0..13c04bd5ac 100644 --- a/docs/rust-port/control-api.schema.json +++ b/docs/rust-port/control-api.schema.json @@ -1,1236 +1,24 @@ { - "toolError": { - "$defs": { - "ErrorCategory": { - "description": "Domain failure category, using obs-websocket v5 status ranges.", - "oneOf": [ - { - "const": "not_ready", - "description": "A resource is absent or not ready (5xx).", - "type": "string" - }, - { - "const": "wrong_state", - "description": "The current state prevents the operation (6xx).", - "type": "string" - }, - { - "const": "processing", - "description": "OBS failed to process the operation (7xx).", - "type": "string" - } - ] - } - }, - "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": false, - "description": "A domain failure, distinct from a JSON-RPC fault.", - "properties": { - "category": { - "$ref": "#/$defs/ErrorCategory", - "description": "Stable machine-readable category." - }, - "code": { - "description": "obs-websocket v5 RequestStatus code.", - "format": "uint16", - "maximum": 65535, - "minimum": 0, - "type": "integer" - }, - "message": { - "description": "Human-readable context.", - "type": "string" - }, - "retryable": { - "description": "Whether a later retry may succeed.", - "type": "boolean" - } - }, - "required": [ - "code", - "category", - "message", - "retryable" - ], - "title": "ToolError", - "type": "object" - }, + "toolError": {"$defs":{"ErrorCategory":{"description":"Domain failure category, using obs-websocket v5 status ranges.","oneOf":[{"const":"not_ready","description":"A resource is absent or not ready (5xx).","type":"string"},{"const":"wrong_state","description":"The current state prevents the operation (6xx).","type":"string"},{"const":"processing","description":"OBS failed to process the operation (7xx).","type":"string"}]}},"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"A domain failure, distinct from a JSON-RPC fault.","properties":{"category":{"$ref":"#/$defs/ErrorCategory","description":"Stable machine-readable category."},"code":{"description":"obs-websocket v5 RequestStatus code.","format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"message":{"description":"Human-readable context.","type":"string"},"retryable":{"description":"Whether a later retry may succeed.","type":"boolean"}},"required":["code","category","message","retryable"],"title":"ToolError","type":"object"}, "tools": [ - { - "annotations": { - "destructiveHint": false, - "idempotentHint": true, - "openWorldHint": false, - "readOnlyHint": false - }, - "inputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": false, - "description": "Empty arguments, with unknown fields rejected.", - "properties": {}, - "title": "EmptyInput", - "type": "object" - }, - "name": "record_start", - "outputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "description": "State returned by a start or stop operation.", - "properties": { - "active": { - "description": "Whether the output is running.", - "type": "boolean" - } - }, - "required": [ - "active" - ], - "title": "ActiveOutput", - "type": "object" - } - }, - { - "annotations": { - "destructiveHint": false, - "idempotentHint": true, - "openWorldHint": false, - "readOnlyHint": true - }, - "inputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": false, - "description": "Empty arguments, with unknown fields rejected.", - "properties": {}, - "title": "EmptyInput", - "type": "object" - }, - "name": "record_status", - "outputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "description": "The state of an output as reported by [`OutputBackend::status`].", - "properties": { - "active": { - "description": "Whether the output is running.", - "type": "boolean" - }, - "bytes": { - "description": "Bytes written or sent so far, where known.", - "format": "uint64", - "minimum": 0, - "type": [ - "integer", - "null" - ] - }, - "duration_ms": { - "description": "Milliseconds since the output started, where known.", - "format": "uint64", - "minimum": 0, - "type": [ - "integer", - "null" - ] - } - }, - "required": [ - "active" - ], - "title": "OutputStatus", - "type": "object" - } - }, - { - "annotations": { - "destructiveHint": false, - "idempotentHint": true, - "openWorldHint": false, - "readOnlyHint": false - }, - "inputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": false, - "description": "Empty arguments, with unknown fields rejected.", - "properties": {}, - "title": "EmptyInput", - "type": "object" - }, - "name": "record_stop", - "outputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "description": "State returned by a start or stop operation.", - "properties": { - "active": { - "description": "Whether the output is running.", - "type": "boolean" - } - }, - "required": [ - "active" - ], - "title": "ActiveOutput", - "type": "object" - } - }, - { - "annotations": { - "destructiveHint": false, - "idempotentHint": false, - "openWorldHint": false, - "readOnlyHint": false - }, - "inputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": false, - "description": "A scene name.", - "properties": { - "name": { - "description": "Scene name.", - "minLength": 1, - "type": "string" - } - }, - "required": [ - "name" - ], - "title": "NameInput", - "type": "object" - }, - "name": "scene_create", - "outputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "description": "Current or changed scene.", - "properties": { - "name": { - "description": "Null when there is no program scene.", - "type": [ - "string", - "null" - ] - } - }, - "title": "SceneOutput", - "type": "object" - } - }, - { - "annotations": { - "destructiveHint": false, - "idempotentHint": true, - "openWorldHint": false, - "readOnlyHint": true - }, - "inputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": false, - "description": "Empty arguments, with unknown fields rejected.", - "properties": {}, - "title": "EmptyInput", - "type": "object" - }, - "name": "scene_get_current", - "outputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "description": "Current or changed scene.", - "properties": { - "name": { - "description": "Null when there is no program scene.", - "type": [ - "string", - "null" - ] - } - }, - "title": "SceneOutput", - "type": "object" - } - }, - { - "annotations": { - "destructiveHint": false, - "idempotentHint": false, - "openWorldHint": false, - "readOnlyHint": false - }, - "inputSchema": { - "$defs": { - "Pair": { - "additionalProperties": false, - "description": "Pixel position or scale factors.", - "properties": { - "x": { - "description": "Horizontal component.", - "format": "double", - "type": "number" - }, - "y": { - "description": "Vertical component.", - "format": "double", - "type": "number" - } - }, - "required": [ - "x", - "y" - ], - "type": "object" - } - }, - "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": false, - "description": "Place an existing source in a scene.", - "properties": { - "position": { - "anyOf": [ - { - "$ref": "#/$defs/Pair" - }, - { - "type": "null" - } - ], - "description": "Initial position." - }, - "scene": { - "description": "Scene name.", - "type": "string" - }, - "source": { - "description": "Source name.", - "type": "string" - } - }, - "required": [ - "scene", - "source" - ], - "title": "AddItemInput", - "type": "object" - }, - "name": "scene_item_add", - "outputSchema": { - "$defs": { - "Pair": { - "additionalProperties": false, - "description": "Pixel position or scale factors.", - "properties": { - "x": { - "description": "Horizontal component.", - "format": "double", - "type": "number" - }, - "y": { - "description": "Vertical component.", - "format": "double", - "type": "number" - } - }, - "required": [ - "x", - "y" - ], - "type": "object" - } - }, - "$schema": "https://json-schema.org/draft/2020-12/schema", - "description": "Listed scene item, preserving the existing wire fields.", - "properties": { - "item": { - "description": "Item id.", - "format": "int64", - "type": "integer" - }, - "position": { - "$ref": "#/$defs/Pair", - "description": "Canvas position." - }, - "rotation": { - "description": "Rotation in degrees.", - "format": "double", - "type": "number" - }, - "scale": { - "$ref": "#/$defs/Pair", - "description": "Scale factors." - }, - "scene": { - "description": "Present when an item was added.", - "type": [ - "string", - "null" - ] - }, - "source": { - "description": "Source name.", - "type": "string" - }, - "visible": { - "description": "Visibility.", - "type": "boolean" - } - }, - "required": [ - "item", - "source", - "visible", - "position", - "scale", - "rotation" - ], - "title": "ItemOutput", - "type": "object" - } - }, - { - "annotations": { - "destructiveHint": false, - "idempotentHint": false, - "openWorldHint": false, - "readOnlyHint": false - }, - "inputSchema": { - "$defs": { - "Pair": { - "additionalProperties": false, - "description": "Pixel position or scale factors.", - "properties": { - "x": { - "description": "Horizontal component.", - "format": "double", - "type": "number" - }, - "y": { - "description": "Vertical component.", - "format": "double", - "type": "number" - } - }, - "required": [ - "x", - "y" - ], - "type": "object" - } - }, - "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": false, - "description": "Transform update; at least one transform field is required.", - "properties": { - "item": { - "description": "Item id.", - "format": "int64", - "type": [ - "integer", - "null" - ] - }, - "position": { - "anyOf": [ - { - "$ref": "#/$defs/Pair" - }, - { - "type": "null" - } - ], - "description": "New position." - }, - "rotation": { - "description": "New rotation in degrees.", - "format": "double", - "type": [ - "number", - "null" - ] - }, - "scale": { - "anyOf": [ - { - "$ref": "#/$defs/Pair" - }, - { - "type": "null" - } - ], - "description": "New scale." - }, - "scene": { - "description": "Scene name.", - "type": "string" - }, - "source": { - "description": "Source name instead of item id.", - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "scene" - ], - "title": "TransformInput", - "type": "object" - }, - "name": "scene_item_set_transform", - "outputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "description": "Item mutation response, retaining the caller's selector.", - "properties": { - "item": { - "description": "Item id when selected by id.", - "format": "int64", - "type": [ - "integer", - "null" - ] - }, - "scene": { - "description": "Scene name.", - "type": "string" - }, - "source": { - "description": "Source name when selected by name.", - "type": [ - "string", - "null" - ] - }, - "visible": { - "description": "Present for visibility changes.", - "type": [ - "boolean", - "null" - ] - } - }, - "required": [ - "scene" - ], - "title": "ItemReply", - "type": "object" - } - }, - { - "annotations": { - "destructiveHint": false, - "idempotentHint": true, - "openWorldHint": false, - "readOnlyHint": false - }, - "inputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": false, - "description": "Visibility update; exactly one of item/source must be specified.", - "properties": { - "item": { - "description": "Item id.", - "format": "int64", - "type": [ - "integer", - "null" - ] - }, - "scene": { - "description": "Scene name.", - "type": "string" - }, - "source": { - "description": "Source name instead of item id.", - "type": [ - "string", - "null" - ] - }, - "visible": { - "description": "New visibility.", - "type": "boolean" - } - }, - "required": [ - "scene", - "visible" - ], - "title": "VisibleInput", - "type": "object" - }, - "name": "scene_item_set_visible", - "outputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "description": "Item mutation response, retaining the caller's selector.", - "properties": { - "item": { - "description": "Item id when selected by id.", - "format": "int64", - "type": [ - "integer", - "null" - ] - }, - "scene": { - "description": "Scene name.", - "type": "string" - }, - "source": { - "description": "Source name when selected by name.", - "type": [ - "string", - "null" - ] - }, - "visible": { - "description": "Present for visibility changes.", - "type": [ - "boolean", - "null" - ] - } - }, - "required": [ - "scene" - ], - "title": "ItemReply", - "type": "object" - } - }, - { - "annotations": { - "destructiveHint": false, - "idempotentHint": true, - "openWorldHint": false, - "readOnlyHint": true - }, - "inputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": false, - "description": "Scene selection.", - "properties": { - "scene": { - "description": "Scene name.", - "type": "string" - } - }, - "required": [ - "scene" - ], - "title": "ItemsInput", - "type": "object" - }, - "name": "scene_items_list", - "outputSchema": { - "$defs": { - "ItemOutput": { - "description": "Listed scene item, preserving the existing wire fields.", - "properties": { - "item": { - "description": "Item id.", - "format": "int64", - "type": "integer" - }, - "position": { - "$ref": "#/$defs/Pair", - "description": "Canvas position." - }, - "rotation": { - "description": "Rotation in degrees.", - "format": "double", - "type": "number" - }, - "scale": { - "$ref": "#/$defs/Pair", - "description": "Scale factors." - }, - "scene": { - "description": "Present when an item was added.", - "type": [ - "string", - "null" - ] - }, - "source": { - "description": "Source name.", - "type": "string" - }, - "visible": { - "description": "Visibility.", - "type": "boolean" - } - }, - "required": [ - "item", - "source", - "visible", - "position", - "scale", - "rotation" - ], - "type": "object" - }, - "Pair": { - "additionalProperties": false, - "description": "Pixel position or scale factors.", - "properties": { - "x": { - "description": "Horizontal component.", - "format": "double", - "type": "number" - }, - "y": { - "description": "Vertical component.", - "format": "double", - "type": "number" - } - }, - "required": [ - "x", - "y" - ], - "type": "object" - } - }, - "$schema": "https://json-schema.org/draft/2020-12/schema", - "description": "Items of a scene.", - "properties": { - "items": { - "description": "Items bottom to top.", - "items": { - "$ref": "#/$defs/ItemOutput" - }, - "type": "array" - }, - "scene": { - "description": "Scene name.", - "type": "string" - } - }, - "required": [ - "scene", - "items" - ], - "title": "ItemsOutput", - "type": "object" - } - }, - { - "annotations": { - "destructiveHint": false, - "idempotentHint": false, - "openWorldHint": false, - "readOnlyHint": false - }, - "inputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": false, - "description": "A scene name.", - "properties": { - "name": { - "description": "Scene name.", - "minLength": 1, - "type": "string" - } - }, - "required": [ - "name" - ], - "title": "NameInput", - "type": "object" - }, - "name": "scene_remove", - "outputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "description": "Current or changed scene.", - "properties": { - "name": { - "description": "Null when there is no program scene.", - "type": [ - "string", - "null" - ] - } - }, - "title": "SceneOutput", - "type": "object" - } - }, - { - "annotations": { - "destructiveHint": false, - "idempotentHint": true, - "openWorldHint": false, - "readOnlyHint": false - }, - "inputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": false, - "description": "A scene name.", - "properties": { - "name": { - "description": "Scene name.", - "minLength": 1, - "type": "string" - } - }, - "required": [ - "name" - ], - "title": "NameInput", - "type": "object" - }, - "name": "scene_set_current", - "outputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "description": "Current or changed scene.", - "properties": { - "name": { - "description": "Null when there is no program scene.", - "type": [ - "string", - "null" - ] - } - }, - "title": "SceneOutput", - "type": "object" - } - }, - { - "annotations": { - "destructiveHint": false, - "idempotentHint": true, - "openWorldHint": false, - "readOnlyHint": true - }, - "inputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": false, - "description": "Empty arguments, with unknown fields rejected.", - "properties": {}, - "title": "EmptyInput", - "type": "object" - }, - "name": "scenes_list", - "outputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "description": "Scene listing.", - "properties": { - "scenes": { - "description": "Scene names in display order.", - "items": { - "type": "string" - }, - "type": "array" - } - }, - "required": [ - "scenes" - ], - "title": "ScenesOutput", - "type": "object" - } - }, - { - "annotations": { - "destructiveHint": false, - "idempotentHint": true, - "openWorldHint": false, - "readOnlyHint": true - }, - "inputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": false, - "description": "Screenshot selection and requested size.", - "properties": { - "height": { - "description": "Height in pixels.", - "format": "uint32", - "minimum": 0, - "type": [ - "integer", - "null" - ] - }, - "source": { - "description": "Source to capture; omit for program output.", - "type": [ - "string", - "null" - ] - }, - "width": { - "description": "Width in pixels.", - "format": "uint32", - "minimum": 0, - "type": [ - "integer", - "null" - ] - } - }, - "title": "CaptureInput", - "type": "object" - }, - "name": "screenshot", - "outputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "description": "Captured PNG and its dimensions.", - "properties": { - "data": { - "description": "PNG bytes encoded in base64.", - "type": "string" - }, - "height": { - "description": "Height in pixels.", - "format": "uint32", - "minimum": 0, - "type": "integer" - }, - "source": { - "description": "Source name, or null for program output.", - "type": [ - "string", - "null" - ] - }, - "width": { - "description": "Width in pixels.", - "format": "uint32", - "minimum": 0, - "type": "integer" - } - }, - "required": [ - "data", - "width", - "height" - ], - "title": "CaptureOutput", - "type": "object" - } - }, - { - "annotations": { - "destructiveHint": false, - "idempotentHint": false, - "openWorldHint": false, - "readOnlyHint": false - }, - "inputSchema": { - "$defs": { - "Pair": { - "additionalProperties": false, - "description": "Pixel position or scale factors.", - "properties": { - "x": { - "description": "Horizontal component.", - "format": "double", - "type": "number" - }, - "y": { - "description": "Vertical component.", - "format": "double", - "type": "number" - } - }, - "required": [ - "x", - "y" - ], - "type": "object" - } - }, - "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": false, - "description": "Source creation, optionally placing it in a scene.", - "properties": { - "kind": { - "description": "Source kind id.", - "type": "string" - }, - "name": { - "description": "Unique name.", - "type": "string" - }, - "position": { - "anyOf": [ - { - "$ref": "#/$defs/Pair" - }, - { - "type": "null" - } - ], - "description": "Initial position (requires scene)." - }, - "scene": { - "description": "Scene receiving the source.", - "type": [ - "string", - "null" - ] - }, - "settings": { - "additionalProperties": true, - "description": "Kind-specific settings.", - "type": "object" - } - }, - "required": [ - "kind", - "name", - "settings" - ], - "title": "CreateInput", - "type": "object" - }, - "name": "source_create", - "outputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "description": "Created source.", - "properties": { - "item": { - "description": "Created item id.", - "format": "int64", - "type": [ - "integer", - "null" - ] - }, - "kind": { - "description": "Source kind.", - "type": "string" - }, - "name": { - "description": "Source name.", - "type": "string" - }, - "scene": { - "description": "Scene receiving the new item.", - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "name", - "kind" - ], - "title": "CreateOutput", - "type": "object" - } - }, - { - "annotations": { - "destructiveHint": false, - "idempotentHint": false, - "openWorldHint": false, - "readOnlyHint": false - }, - "inputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": false, - "description": "Settings update.", - "properties": { - "name": { - "description": "Source name.", - "type": "string" - }, - "settings": { - "additionalProperties": true, - "description": "Kind-specific settings to merge.", - "type": "object" - } - }, - "required": [ - "name", - "settings" - ], - "title": "SettingsInput", - "type": "object" - }, - "name": "source_set_settings", - "outputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "description": "Updated source name.", - "properties": { - "name": { - "description": "Source name.", - "type": "string" - } - }, - "required": [ - "name" - ], - "title": "NameOutput", - "type": "object" - } - }, - { - "annotations": { - "destructiveHint": false, - "idempotentHint": true, - "openWorldHint": false, - "readOnlyHint": true - }, - "inputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": false, - "description": "Empty arguments, with unknown fields rejected.", - "properties": {}, - "title": "EmptyInput", - "type": "object" - }, - "name": "sources_list", - "outputSchema": { - "$defs": { - "SourceInfo": { - "description": "A source as listed by [`SourceBackend::sources`].", - "properties": { - "kind": { - "description": "The source kind id, such as `color_source`.", - "type": "string" - }, - "name": { - "description": "The source's unique name.", - "type": "string" - } - }, - "required": [ - "name", - "kind" - ], - "type": "object" - } - }, - "$schema": "https://json-schema.org/draft/2020-12/schema", - "description": "Source listing.", - "properties": { - "sources": { - "description": "Sources in stable order.", - "items": { - "$ref": "#/$defs/SourceInfo" - }, - "type": "array" - } - }, - "required": [ - "sources" - ], - "title": "SourcesOutput", - "type": "object" - } - }, - { - "annotations": { - "destructiveHint": false, - "idempotentHint": true, - "openWorldHint": false, - "readOnlyHint": false - }, - "inputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": false, - "description": "Empty arguments, with unknown fields rejected.", - "properties": {}, - "title": "EmptyInput", - "type": "object" - }, - "name": "stream_start", - "outputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "description": "State returned by a start or stop operation.", - "properties": { - "active": { - "description": "Whether the output is running.", - "type": "boolean" - } - }, - "required": [ - "active" - ], - "title": "ActiveOutput", - "type": "object" - } - }, - { - "annotations": { - "destructiveHint": false, - "idempotentHint": true, - "openWorldHint": false, - "readOnlyHint": true - }, - "inputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": false, - "description": "Empty arguments, with unknown fields rejected.", - "properties": {}, - "title": "EmptyInput", - "type": "object" - }, - "name": "stream_status", - "outputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "description": "The state of an output as reported by [`OutputBackend::status`].", - "properties": { - "active": { - "description": "Whether the output is running.", - "type": "boolean" - }, - "bytes": { - "description": "Bytes written or sent so far, where known.", - "format": "uint64", - "minimum": 0, - "type": [ - "integer", - "null" - ] - }, - "duration_ms": { - "description": "Milliseconds since the output started, where known.", - "format": "uint64", - "minimum": 0, - "type": [ - "integer", - "null" - ] - } - }, - "required": [ - "active" - ], - "title": "OutputStatus", - "type": "object" - } - }, - { - "annotations": { - "destructiveHint": false, - "idempotentHint": true, - "openWorldHint": false, - "readOnlyHint": false - }, - "inputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": false, - "description": "Empty arguments, with unknown fields rejected.", - "properties": {}, - "title": "EmptyInput", - "type": "object" - }, - "name": "stream_stop", - "outputSchema": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "description": "State returned by a start or stop operation.", - "properties": { - "active": { - "description": "Whether the output is running.", - "type": "boolean" - } - }, - "required": [ - "active" - ], - "title": "ActiveOutput", - "type": "object" - } - } + {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"record_start","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"record_status","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"The state of an output as reported by [`OutputBackend::status`].","properties":{"active":{"description":"Whether the output is running.","type":"boolean"},"bytes":{"description":"Bytes written or sent so far, where known.","format":"uint64","minimum":0,"type":["integer","null"]},"duration_ms":{"description":"Milliseconds since the output started, where known.","format":"uint64","minimum":0,"type":["integer","null"]}},"required":["active"],"title":"OutputStatus","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"record_stop","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":false,"openWorldHint":false,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"A scene name.","properties":{"name":{"description":"Scene name.","minLength":1,"type":"string"}},"required":["name"],"title":"NameInput","type":"object"},"name":"scene_create","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Current or changed scene.","properties":{"name":{"description":"Null when there is no program scene.","type":["string","null"]}},"title":"SceneOutput","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"scene_get_current","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Current or changed scene.","properties":{"name":{"description":"Null when there is no program scene.","type":["string","null"]}},"title":"SceneOutput","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":false,"openWorldHint":false,"readOnlyHint":false},"inputSchema":{"$defs":{"Pair":{"additionalProperties":false,"description":"Pixel position or scale factors.","properties":{"x":{"description":"Horizontal component.","format":"double","type":"number"},"y":{"description":"Vertical component.","format":"double","type":"number"}},"required":["x","y"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Place an existing source in a scene.","properties":{"position":{"anyOf":[{"$ref":"#/$defs/Pair"},{"type":"null"}],"description":"Initial position."},"scene":{"description":"Scene name.","type":"string"},"source":{"description":"Source name.","type":"string"}},"required":["scene","source"],"title":"AddItemInput","type":"object"},"name":"scene_item_add","outputSchema":{"$defs":{"Pair":{"additionalProperties":false,"description":"Pixel position or scale factors.","properties":{"x":{"description":"Horizontal component.","format":"double","type":"number"},"y":{"description":"Vertical component.","format":"double","type":"number"}},"required":["x","y"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Listed scene item, preserving the existing wire fields.","properties":{"item":{"description":"Item id.","format":"int64","type":"integer"},"position":{"$ref":"#/$defs/Pair","description":"Canvas position."},"rotation":{"description":"Rotation in degrees.","format":"double","type":"number"},"scale":{"$ref":"#/$defs/Pair","description":"Scale factors."},"scene":{"description":"Present when an item was added.","type":["string","null"]},"source":{"description":"Source name.","type":"string"},"visible":{"description":"Visibility.","type":"boolean"}},"required":["item","source","visible","position","scale","rotation"],"title":"ItemOutput","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":false,"openWorldHint":false,"readOnlyHint":false},"inputSchema":{"$defs":{"Pair":{"additionalProperties":false,"description":"Pixel position or scale factors.","properties":{"x":{"description":"Horizontal component.","format":"double","type":"number"},"y":{"description":"Vertical component.","format":"double","type":"number"}},"required":["x","y"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Transform update; at least one transform field is required.","properties":{"item":{"description":"Item id.","format":"int64","type":["integer","null"]},"position":{"anyOf":[{"$ref":"#/$defs/Pair"},{"type":"null"}],"description":"New position."},"rotation":{"description":"New rotation in degrees.","format":"double","type":["number","null"]},"scale":{"anyOf":[{"$ref":"#/$defs/Pair"},{"type":"null"}],"description":"New scale."},"scene":{"description":"Scene name.","type":"string"},"source":{"description":"Source name instead of item id.","type":["string","null"]}},"required":["scene"],"title":"TransformInput","type":"object"},"name":"scene_item_set_transform","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Item mutation response, retaining the caller's selector.","properties":{"item":{"description":"Item id when selected by id.","format":"int64","type":["integer","null"]},"scene":{"description":"Scene name.","type":"string"},"source":{"description":"Source name when selected by name.","type":["string","null"]},"visible":{"description":"Present for visibility changes.","type":["boolean","null"]}},"required":["scene"],"title":"ItemReply","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Visibility update; exactly one of item/source must be specified.","properties":{"item":{"description":"Item id.","format":"int64","type":["integer","null"]},"scene":{"description":"Scene name.","type":"string"},"source":{"description":"Source name instead of item id.","type":["string","null"]},"visible":{"description":"New visibility.","type":"boolean"}},"required":["scene","visible"],"title":"VisibleInput","type":"object"},"name":"scene_item_set_visible","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Item mutation response, retaining the caller's selector.","properties":{"item":{"description":"Item id when selected by id.","format":"int64","type":["integer","null"]},"scene":{"description":"Scene name.","type":"string"},"source":{"description":"Source name when selected by name.","type":["string","null"]},"visible":{"description":"Present for visibility changes.","type":["boolean","null"]}},"required":["scene"],"title":"ItemReply","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Scene selection.","properties":{"scene":{"description":"Scene name.","type":"string"}},"required":["scene"],"title":"ItemsInput","type":"object"},"name":"scene_items_list","outputSchema":{"$defs":{"ItemOutput":{"description":"Listed scene item, preserving the existing wire fields.","properties":{"item":{"description":"Item id.","format":"int64","type":"integer"},"position":{"$ref":"#/$defs/Pair","description":"Canvas position."},"rotation":{"description":"Rotation in degrees.","format":"double","type":"number"},"scale":{"$ref":"#/$defs/Pair","description":"Scale factors."},"scene":{"description":"Present when an item was added.","type":["string","null"]},"source":{"description":"Source name.","type":"string"},"visible":{"description":"Visibility.","type":"boolean"}},"required":["item","source","visible","position","scale","rotation"],"type":"object"},"Pair":{"additionalProperties":false,"description":"Pixel position or scale factors.","properties":{"x":{"description":"Horizontal component.","format":"double","type":"number"},"y":{"description":"Vertical component.","format":"double","type":"number"}},"required":["x","y"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Items of a scene.","properties":{"items":{"description":"Items bottom to top.","items":{"$ref":"#/$defs/ItemOutput"},"type":"array"},"scene":{"description":"Scene name.","type":"string"}},"required":["scene","items"],"title":"ItemsOutput","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":false,"openWorldHint":false,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"A scene name.","properties":{"name":{"description":"Scene name.","minLength":1,"type":"string"}},"required":["name"],"title":"NameInput","type":"object"},"name":"scene_remove","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Current or changed scene.","properties":{"name":{"description":"Null when there is no program scene.","type":["string","null"]}},"title":"SceneOutput","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"A scene name.","properties":{"name":{"description":"Scene name.","minLength":1,"type":"string"}},"required":["name"],"title":"NameInput","type":"object"},"name":"scene_set_current","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Current or changed scene.","properties":{"name":{"description":"Null when there is no program scene.","type":["string","null"]}},"title":"SceneOutput","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"scenes_list","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Scene listing.","properties":{"scenes":{"description":"Scene names in display order.","items":{"type":"string"},"type":"array"}},"required":["scenes"],"title":"ScenesOutput","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Screenshot selection and requested size.","properties":{"height":{"description":"Height in pixels.","format":"uint32","minimum":0,"type":["integer","null"]},"source":{"description":"Source to capture; omit for program output.","type":["string","null"]},"width":{"description":"Width in pixels.","format":"uint32","minimum":0,"type":["integer","null"]}},"title":"CaptureInput","type":"object"},"name":"screenshot","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Captured PNG and its dimensions.","properties":{"data":{"description":"PNG bytes encoded in base64.","type":"string"},"height":{"description":"Height in pixels.","format":"uint32","minimum":0,"type":"integer"},"source":{"description":"Source name, or null for program output.","type":["string","null"]},"width":{"description":"Width in pixels.","format":"uint32","minimum":0,"type":"integer"}},"required":["data","width","height"],"title":"CaptureOutput","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":false,"openWorldHint":false,"readOnlyHint":false},"inputSchema":{"$defs":{"Pair":{"additionalProperties":false,"description":"Pixel position or scale factors.","properties":{"x":{"description":"Horizontal component.","format":"double","type":"number"},"y":{"description":"Vertical component.","format":"double","type":"number"}},"required":["x","y"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Source creation, optionally placing it in a scene.","properties":{"kind":{"description":"Source kind id.","type":"string"},"name":{"description":"Unique name.","type":"string"},"position":{"anyOf":[{"$ref":"#/$defs/Pair"},{"type":"null"}],"description":"Initial position (requires scene)."},"scene":{"description":"Scene receiving the source.","type":["string","null"]},"settings":{"additionalProperties":true,"description":"Kind-specific settings.","type":"object"}},"required":["kind","name","settings"],"title":"CreateInput","type":"object"},"name":"source_create","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Created source.","properties":{"item":{"description":"Created item id.","format":"int64","type":["integer","null"]},"kind":{"description":"Source kind.","type":"string"},"name":{"description":"Source name.","type":"string"},"scene":{"description":"Scene receiving the new item.","type":["string","null"]}},"required":["name","kind"],"title":"CreateOutput","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":false,"openWorldHint":false,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Settings update.","properties":{"name":{"description":"Source name.","type":"string"},"settings":{"additionalProperties":true,"description":"Kind-specific settings to merge.","type":"object"}},"required":["name","settings"],"title":"SettingsInput","type":"object"},"name":"source_set_settings","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Updated source name.","properties":{"name":{"description":"Source name.","type":"string"}},"required":["name"],"title":"NameOutput","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"sources_list","outputSchema":{"$defs":{"SourceInfo":{"description":"A source as listed by [`SourceBackend::sources`].","properties":{"kind":{"description":"The source kind id, such as `color_source`.","type":"string"},"name":{"description":"The source's unique name.","type":"string"}},"required":["name","kind"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Source listing.","properties":{"sources":{"description":"Sources in stable order.","items":{"$ref":"#/$defs/SourceInfo"},"type":"array"}},"required":["sources"],"title":"SourcesOutput","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stream_start","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stream_status","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"The state of an output as reported by [`OutputBackend::status`].","properties":{"active":{"description":"Whether the output is running.","type":"boolean"},"bytes":{"description":"Bytes written or sent so far, where known.","format":"uint64","minimum":0,"type":["integer","null"]},"duration_ms":{"description":"Milliseconds since the output started, where known.","format":"uint64","minimum":0,"type":["integer","null"]}},"required":["active"],"title":"OutputStatus","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stream_stop","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}} ] } diff --git a/rust/obs-mcp/tests/mcp/typed.rs b/rust/obs-mcp/tests/mcp/typed.rs index 33f224bf11..83397d5b42 100644 --- a/rust/obs-mcp/tests/mcp/typed.rs +++ b/rust/obs-mcp/tests/mcp/typed.rs @@ -91,7 +91,8 @@ fn schema_snapshot_has_not_drifted() { let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) .join("../../docs/rust-port/control-api.schema.json"); if std::env::var_os("OBS_UPDATE_CONTROL_SCHEMA").is_some() { - std::fs::write(&path, serde_json::to_string_pretty(&actual).unwrap() + "\n").unwrap(); + std::fs::write(&path, format!("{{\n \"toolError\": {},\n \"tools\": [\n{}\n ]\n}}\n", + actual["toolError"], actual["tools"].as_array().unwrap().iter().map(|tool| format!(" {tool}")).collect::>().join(",\n"))).unwrap(); } let expected: serde_json::Value = serde_json::from_slice(&std::fs::read(path).expect("committed schema snapshot")).unwrap(); From c79b261d4af929f601843a4b345cfe53e77689ad Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 13:47:25 -0800 Subject: [PATCH 04/39] fix(mcp): preserve readiness errors and accurate operation hints (#4445) --- docs/rust-port/control-api.md | 3 ++- docs/rust-port/control-api.schema.json | 26 ++++++++++---------- rust/obs-mcp/src/backend/mod.rs | 30 +++++++++++++++++++++-- rust/obs-mcp/src/server/typed.rs | 20 ++++++++-------- rust/obs-mcp/tests/libobs_backend.rs | 14 +++++++++++ rust/obs-mcp/tests/mcp/outputs.rs | 11 +++++++-- rust/obs-mcp/tests/mcp/scenes.rs | 11 +++++++-- rust/obs-mcp/tests/mcp/screenshot.rs | 11 +++++++-- rust/obs-mcp/tests/mcp/sources.rs | 17 ++++++++++--- rust/obs-mcp/tests/mcp/typed.rs | 33 +++++++++++++++++++++++--- 10 files changed, 138 insertions(+), 38 deletions(-) diff --git a/docs/rust-port/control-api.md b/docs/rust-port/control-api.md index 22c3827937..07f07efaec 100644 --- a/docs/rust-port/control-api.md +++ b/docs/rust-port/control-api.md @@ -17,7 +17,8 @@ response structs, never positional multi-argument methods. Malformed requests and typed arguments are JSON-RPC errors. Domain failures return isError and ToolError {code, category, message, retryable}, using -obs-websocket v5 status ranges: 5xx missing/not ready, 6xx state, 7xx processing. +obs-websocket v5 codes: 600 ResourceNotFound, 207 NotReady, 604 InvalidResourceState +and 702 RequestProcessingFailed. Categories are independent of numeric ranges. Read operations have readOnlyHint; start/stop are idempotent. ## State and measurements diff --git a/docs/rust-port/control-api.schema.json b/docs/rust-port/control-api.schema.json index 13c04bd5ac..5656f4d596 100644 --- a/docs/rust-port/control-api.schema.json +++ b/docs/rust-port/control-api.schema.json @@ -1,24 +1,24 @@ { - "toolError": {"$defs":{"ErrorCategory":{"description":"Domain failure category, using obs-websocket v5 status ranges.","oneOf":[{"const":"not_ready","description":"A resource is absent or not ready (5xx).","type":"string"},{"const":"wrong_state","description":"The current state prevents the operation (6xx).","type":"string"},{"const":"processing","description":"OBS failed to process the operation (7xx).","type":"string"}]}},"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"A domain failure, distinct from a JSON-RPC fault.","properties":{"category":{"$ref":"#/$defs/ErrorCategory","description":"Stable machine-readable category."},"code":{"description":"obs-websocket v5 RequestStatus code.","format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"message":{"description":"Human-readable context.","type":"string"},"retryable":{"description":"Whether a later retry may succeed.","type":"boolean"}},"required":["code","category","message","retryable"],"title":"ToolError","type":"object"}, + "toolError": {"$defs":{"ErrorCategory":{"description":"Domain failure category, using obs-websocket v5 status ranges.","oneOf":[{"const":"not_ready","description":"A resource is absent or not ready (ResourceNotFound/NotReady).","type":"string"},{"const":"wrong_state","description":"The current state prevents the operation (6xx).","type":"string"},{"const":"processing","description":"OBS failed to process the operation (7xx).","type":"string"}]}},"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"A domain failure, distinct from a JSON-RPC fault.","properties":{"category":{"$ref":"#/$defs/ErrorCategory","description":"Stable machine-readable category."},"code":{"description":"obs-websocket v5 RequestStatus code.","format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"message":{"description":"Human-readable context.","type":"string"},"retryable":{"description":"Whether a later retry may succeed.","type":"boolean"}},"required":["code","category","message","retryable"],"title":"ToolError","type":"object"}, "tools": [ - {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"record_start","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}}, + {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"record_start","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"record_status","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"The state of an output as reported by [`OutputBackend::status`].","properties":{"active":{"description":"Whether the output is running.","type":"boolean"},"bytes":{"description":"Bytes written or sent so far, where known.","format":"uint64","minimum":0,"type":["integer","null"]},"duration_ms":{"description":"Milliseconds since the output started, where known.","format":"uint64","minimum":0,"type":["integer","null"]}},"required":["active"],"title":"OutputStatus","type":"object"}}, - {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"record_stop","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}}, - {"annotations":{"destructiveHint":false,"idempotentHint":false,"openWorldHint":false,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"A scene name.","properties":{"name":{"description":"Scene name.","minLength":1,"type":"string"}},"required":["name"],"title":"NameInput","type":"object"},"name":"scene_create","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Current or changed scene.","properties":{"name":{"description":"Null when there is no program scene.","type":["string","null"]}},"title":"SceneOutput","type":"object"}}, + {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"record_stop","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}}, + {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"A scene name.","properties":{"name":{"description":"Scene name.","minLength":1,"type":"string"}},"required":["name"],"title":"NameInput","type":"object"},"name":"scene_create","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Current or changed scene.","properties":{"name":{"description":"Null when there is no program scene.","type":["string","null"]}},"title":"SceneOutput","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"scene_get_current","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Current or changed scene.","properties":{"name":{"description":"Null when there is no program scene.","type":["string","null"]}},"title":"SceneOutput","type":"object"}}, - {"annotations":{"destructiveHint":false,"idempotentHint":false,"openWorldHint":false,"readOnlyHint":false},"inputSchema":{"$defs":{"Pair":{"additionalProperties":false,"description":"Pixel position or scale factors.","properties":{"x":{"description":"Horizontal component.","format":"double","type":"number"},"y":{"description":"Vertical component.","format":"double","type":"number"}},"required":["x","y"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Place an existing source in a scene.","properties":{"position":{"anyOf":[{"$ref":"#/$defs/Pair"},{"type":"null"}],"description":"Initial position."},"scene":{"description":"Scene name.","type":"string"},"source":{"description":"Source name.","type":"string"}},"required":["scene","source"],"title":"AddItemInput","type":"object"},"name":"scene_item_add","outputSchema":{"$defs":{"Pair":{"additionalProperties":false,"description":"Pixel position or scale factors.","properties":{"x":{"description":"Horizontal component.","format":"double","type":"number"},"y":{"description":"Vertical component.","format":"double","type":"number"}},"required":["x","y"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Listed scene item, preserving the existing wire fields.","properties":{"item":{"description":"Item id.","format":"int64","type":"integer"},"position":{"$ref":"#/$defs/Pair","description":"Canvas position."},"rotation":{"description":"Rotation in degrees.","format":"double","type":"number"},"scale":{"$ref":"#/$defs/Pair","description":"Scale factors."},"scene":{"description":"Present when an item was added.","type":["string","null"]},"source":{"description":"Source name.","type":"string"},"visible":{"description":"Visibility.","type":"boolean"}},"required":["item","source","visible","position","scale","rotation"],"title":"ItemOutput","type":"object"}}, - {"annotations":{"destructiveHint":false,"idempotentHint":false,"openWorldHint":false,"readOnlyHint":false},"inputSchema":{"$defs":{"Pair":{"additionalProperties":false,"description":"Pixel position or scale factors.","properties":{"x":{"description":"Horizontal component.","format":"double","type":"number"},"y":{"description":"Vertical component.","format":"double","type":"number"}},"required":["x","y"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Transform update; at least one transform field is required.","properties":{"item":{"description":"Item id.","format":"int64","type":["integer","null"]},"position":{"anyOf":[{"$ref":"#/$defs/Pair"},{"type":"null"}],"description":"New position."},"rotation":{"description":"New rotation in degrees.","format":"double","type":["number","null"]},"scale":{"anyOf":[{"$ref":"#/$defs/Pair"},{"type":"null"}],"description":"New scale."},"scene":{"description":"Scene name.","type":"string"},"source":{"description":"Source name instead of item id.","type":["string","null"]}},"required":["scene"],"title":"TransformInput","type":"object"},"name":"scene_item_set_transform","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Item mutation response, retaining the caller's selector.","properties":{"item":{"description":"Item id when selected by id.","format":"int64","type":["integer","null"]},"scene":{"description":"Scene name.","type":"string"},"source":{"description":"Source name when selected by name.","type":["string","null"]},"visible":{"description":"Present for visibility changes.","type":["boolean","null"]}},"required":["scene"],"title":"ItemReply","type":"object"}}, - {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Visibility update; exactly one of item/source must be specified.","properties":{"item":{"description":"Item id.","format":"int64","type":["integer","null"]},"scene":{"description":"Scene name.","type":"string"},"source":{"description":"Source name instead of item id.","type":["string","null"]},"visible":{"description":"New visibility.","type":"boolean"}},"required":["scene","visible"],"title":"VisibleInput","type":"object"},"name":"scene_item_set_visible","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Item mutation response, retaining the caller's selector.","properties":{"item":{"description":"Item id when selected by id.","format":"int64","type":["integer","null"]},"scene":{"description":"Scene name.","type":"string"},"source":{"description":"Source name when selected by name.","type":["string","null"]},"visible":{"description":"Present for visibility changes.","type":["boolean","null"]}},"required":["scene"],"title":"ItemReply","type":"object"}}, + {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$defs":{"Pair":{"additionalProperties":false,"description":"Pixel position or scale factors.","properties":{"x":{"description":"Horizontal component.","format":"double","type":"number"},"y":{"description":"Vertical component.","format":"double","type":"number"}},"required":["x","y"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Place an existing source in a scene.","properties":{"position":{"anyOf":[{"$ref":"#/$defs/Pair"},{"type":"null"}],"description":"Initial position."},"scene":{"description":"Scene name.","type":"string"},"source":{"description":"Source name.","type":"string"}},"required":["scene","source"],"title":"AddItemInput","type":"object"},"name":"scene_item_add","outputSchema":{"$defs":{"Pair":{"additionalProperties":false,"description":"Pixel position or scale factors.","properties":{"x":{"description":"Horizontal component.","format":"double","type":"number"},"y":{"description":"Vertical component.","format":"double","type":"number"}},"required":["x","y"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Listed scene item, preserving the existing wire fields.","properties":{"item":{"description":"Item id.","format":"int64","type":"integer"},"position":{"$ref":"#/$defs/Pair","description":"Canvas position."},"rotation":{"description":"Rotation in degrees.","format":"double","type":"number"},"scale":{"$ref":"#/$defs/Pair","description":"Scale factors."},"scene":{"description":"Present when an item was added.","type":["string","null"]},"source":{"description":"Source name.","type":"string"},"visible":{"description":"Visibility.","type":"boolean"}},"required":["item","source","visible","position","scale","rotation"],"title":"ItemOutput","type":"object"}}, + {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$defs":{"Pair":{"additionalProperties":false,"description":"Pixel position or scale factors.","properties":{"x":{"description":"Horizontal component.","format":"double","type":"number"},"y":{"description":"Vertical component.","format":"double","type":"number"}},"required":["x","y"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Transform update; at least one transform field is required.","properties":{"item":{"description":"Item id.","format":"int64","type":["integer","null"]},"position":{"anyOf":[{"$ref":"#/$defs/Pair"},{"type":"null"}],"description":"New position."},"rotation":{"description":"New rotation in degrees.","format":"double","type":["number","null"]},"scale":{"anyOf":[{"$ref":"#/$defs/Pair"},{"type":"null"}],"description":"New scale."},"scene":{"description":"Scene name.","type":"string"},"source":{"description":"Source name instead of item id.","type":["string","null"]}},"required":["scene"],"title":"TransformInput","type":"object"},"name":"scene_item_set_transform","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Item mutation response, retaining the caller's selector.","properties":{"item":{"description":"Item id when selected by id.","format":"int64","type":["integer","null"]},"scene":{"description":"Scene name.","type":"string"},"source":{"description":"Source name when selected by name.","type":["string","null"]},"visible":{"description":"Present for visibility changes.","type":["boolean","null"]}},"required":["scene"],"title":"ItemReply","type":"object"}}, + {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Visibility update; exactly one of item/source must be specified.","properties":{"item":{"description":"Item id.","format":"int64","type":["integer","null"]},"scene":{"description":"Scene name.","type":"string"},"source":{"description":"Source name instead of item id.","type":["string","null"]},"visible":{"description":"New visibility.","type":"boolean"}},"required":["scene","visible"],"title":"VisibleInput","type":"object"},"name":"scene_item_set_visible","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Item mutation response, retaining the caller's selector.","properties":{"item":{"description":"Item id when selected by id.","format":"int64","type":["integer","null"]},"scene":{"description":"Scene name.","type":"string"},"source":{"description":"Source name when selected by name.","type":["string","null"]},"visible":{"description":"Present for visibility changes.","type":["boolean","null"]}},"required":["scene"],"title":"ItemReply","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Scene selection.","properties":{"scene":{"description":"Scene name.","type":"string"}},"required":["scene"],"title":"ItemsInput","type":"object"},"name":"scene_items_list","outputSchema":{"$defs":{"ItemOutput":{"description":"Listed scene item, preserving the existing wire fields.","properties":{"item":{"description":"Item id.","format":"int64","type":"integer"},"position":{"$ref":"#/$defs/Pair","description":"Canvas position."},"rotation":{"description":"Rotation in degrees.","format":"double","type":"number"},"scale":{"$ref":"#/$defs/Pair","description":"Scale factors."},"scene":{"description":"Present when an item was added.","type":["string","null"]},"source":{"description":"Source name.","type":"string"},"visible":{"description":"Visibility.","type":"boolean"}},"required":["item","source","visible","position","scale","rotation"],"type":"object"},"Pair":{"additionalProperties":false,"description":"Pixel position or scale factors.","properties":{"x":{"description":"Horizontal component.","format":"double","type":"number"},"y":{"description":"Vertical component.","format":"double","type":"number"}},"required":["x","y"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Items of a scene.","properties":{"items":{"description":"Items bottom to top.","items":{"$ref":"#/$defs/ItemOutput"},"type":"array"},"scene":{"description":"Scene name.","type":"string"}},"required":["scene","items"],"title":"ItemsOutput","type":"object"}}, - {"annotations":{"destructiveHint":false,"idempotentHint":false,"openWorldHint":false,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"A scene name.","properties":{"name":{"description":"Scene name.","minLength":1,"type":"string"}},"required":["name"],"title":"NameInput","type":"object"},"name":"scene_remove","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Current or changed scene.","properties":{"name":{"description":"Null when there is no program scene.","type":["string","null"]}},"title":"SceneOutput","type":"object"}}, - {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"A scene name.","properties":{"name":{"description":"Scene name.","minLength":1,"type":"string"}},"required":["name"],"title":"NameInput","type":"object"},"name":"scene_set_current","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Current or changed scene.","properties":{"name":{"description":"Null when there is no program scene.","type":["string","null"]}},"title":"SceneOutput","type":"object"}}, + {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"A scene name.","properties":{"name":{"description":"Scene name.","minLength":1,"type":"string"}},"required":["name"],"title":"NameInput","type":"object"},"name":"scene_remove","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Current or changed scene.","properties":{"name":{"description":"Null when there is no program scene.","type":["string","null"]}},"title":"SceneOutput","type":"object"}}, + {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"A scene name.","properties":{"name":{"description":"Scene name.","minLength":1,"type":"string"}},"required":["name"],"title":"NameInput","type":"object"},"name":"scene_set_current","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Current or changed scene.","properties":{"name":{"description":"Null when there is no program scene.","type":["string","null"]}},"title":"SceneOutput","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"scenes_list","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Scene listing.","properties":{"scenes":{"description":"Scene names in display order.","items":{"type":"string"},"type":"array"}},"required":["scenes"],"title":"ScenesOutput","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Screenshot selection and requested size.","properties":{"height":{"description":"Height in pixels.","format":"uint32","minimum":0,"type":["integer","null"]},"source":{"description":"Source to capture; omit for program output.","type":["string","null"]},"width":{"description":"Width in pixels.","format":"uint32","minimum":0,"type":["integer","null"]}},"title":"CaptureInput","type":"object"},"name":"screenshot","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Captured PNG and its dimensions.","properties":{"data":{"description":"PNG bytes encoded in base64.","type":"string"},"height":{"description":"Height in pixels.","format":"uint32","minimum":0,"type":"integer"},"source":{"description":"Source name, or null for program output.","type":["string","null"]},"width":{"description":"Width in pixels.","format":"uint32","minimum":0,"type":"integer"}},"required":["data","width","height"],"title":"CaptureOutput","type":"object"}}, - {"annotations":{"destructiveHint":false,"idempotentHint":false,"openWorldHint":false,"readOnlyHint":false},"inputSchema":{"$defs":{"Pair":{"additionalProperties":false,"description":"Pixel position or scale factors.","properties":{"x":{"description":"Horizontal component.","format":"double","type":"number"},"y":{"description":"Vertical component.","format":"double","type":"number"}},"required":["x","y"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Source creation, optionally placing it in a scene.","properties":{"kind":{"description":"Source kind id.","type":"string"},"name":{"description":"Unique name.","type":"string"},"position":{"anyOf":[{"$ref":"#/$defs/Pair"},{"type":"null"}],"description":"Initial position (requires scene)."},"scene":{"description":"Scene receiving the source.","type":["string","null"]},"settings":{"additionalProperties":true,"description":"Kind-specific settings.","type":"object"}},"required":["kind","name","settings"],"title":"CreateInput","type":"object"},"name":"source_create","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Created source.","properties":{"item":{"description":"Created item id.","format":"int64","type":["integer","null"]},"kind":{"description":"Source kind.","type":"string"},"name":{"description":"Source name.","type":"string"},"scene":{"description":"Scene receiving the new item.","type":["string","null"]}},"required":["name","kind"],"title":"CreateOutput","type":"object"}}, - {"annotations":{"destructiveHint":false,"idempotentHint":false,"openWorldHint":false,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Settings update.","properties":{"name":{"description":"Source name.","type":"string"},"settings":{"additionalProperties":true,"description":"Kind-specific settings to merge.","type":"object"}},"required":["name","settings"],"title":"SettingsInput","type":"object"},"name":"source_set_settings","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Updated source name.","properties":{"name":{"description":"Source name.","type":"string"}},"required":["name"],"title":"NameOutput","type":"object"}}, + {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$defs":{"Pair":{"additionalProperties":false,"description":"Pixel position or scale factors.","properties":{"x":{"description":"Horizontal component.","format":"double","type":"number"},"y":{"description":"Vertical component.","format":"double","type":"number"}},"required":["x","y"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Source creation, optionally placing it in a scene.","properties":{"kind":{"description":"Source kind id.","type":"string"},"name":{"description":"Unique name.","type":"string"},"position":{"anyOf":[{"$ref":"#/$defs/Pair"},{"type":"null"}],"description":"Initial position (requires scene)."},"scene":{"description":"Scene receiving the source.","type":["string","null"]},"settings":{"additionalProperties":true,"description":"Kind-specific settings.","type":"object"}},"required":["kind","name","settings"],"title":"CreateInput","type":"object"},"name":"source_create","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Created source.","properties":{"item":{"description":"Created item id.","format":"int64","type":["integer","null"]},"kind":{"description":"Source kind.","type":"string"},"name":{"description":"Source name.","type":"string"},"scene":{"description":"Scene receiving the new item.","type":["string","null"]}},"required":["name","kind"],"title":"CreateOutput","type":"object"}}, + {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Settings update.","properties":{"name":{"description":"Source name.","type":"string"},"settings":{"additionalProperties":true,"description":"Kind-specific settings to merge.","type":"object"}},"required":["name","settings"],"title":"SettingsInput","type":"object"},"name":"source_set_settings","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Updated source name.","properties":{"name":{"description":"Source name.","type":"string"}},"required":["name"],"title":"NameOutput","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"sources_list","outputSchema":{"$defs":{"SourceInfo":{"description":"A source as listed by [`SourceBackend::sources`].","properties":{"kind":{"description":"The source kind id, such as `color_source`.","type":"string"},"name":{"description":"The source's unique name.","type":"string"}},"required":["name","kind"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Source listing.","properties":{"sources":{"description":"Sources in stable order.","items":{"$ref":"#/$defs/SourceInfo"},"type":"array"}},"required":["sources"],"title":"SourcesOutput","type":"object"}}, - {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stream_start","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}}, + {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stream_start","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stream_status","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"The state of an output as reported by [`OutputBackend::status`].","properties":{"active":{"description":"Whether the output is running.","type":"boolean"},"bytes":{"description":"Bytes written or sent so far, where known.","format":"uint64","minimum":0,"type":["integer","null"]},"duration_ms":{"description":"Milliseconds since the output started, where known.","format":"uint64","minimum":0,"type":["integer","null"]}},"required":["active"],"title":"OutputStatus","type":"object"}}, - {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stream_stop","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}} + {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stream_stop","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}} ] } diff --git a/rust/obs-mcp/src/backend/mod.rs b/rust/obs-mcp/src/backend/mod.rs index 331c932b8f..d63c0baff4 100644 --- a/rust/obs-mcp/src/backend/mod.rs +++ b/rust/obs-mcp/src/backend/mod.rs @@ -31,8 +31,10 @@ use serde_json::{Value, json}; use crate::ffi::{self, CpuUsage, Output, Source}; use crate::resources::stats::{Stats, StatsBackend}; use crate::resources::{self, ResourceRegistry}; -use crate::server::{Server, ToolRegistry}; -use crate::tools::outputs::{self, OutputBackend, OutputKind, OutputStatus}; +use crate::server::{Server, ToolError, ToolRegistry}; +use crate::tools::outputs::{ + self, ActiveOutput, OutputBackend, OutputKind, OutputRequest, OutputStatus, +}; use crate::tools::scenes::{self, SceneBackend}; use crate::tools::screenshot::{self, CaptureBackend, Frame}; use crate::tools::sources::{self, ItemInfo, ItemRef, SourceBackend, SourceInfo, Transform}; @@ -334,6 +336,30 @@ fn narrow(value: f64) -> f32 { } impl OutputBackend for ObsBackend { + fn start_output(&self, request: OutputRequest) -> Result { + let output = self.output(request.kind).map_err(ToolError::not_ready)?; + if !output.active() { + if request.kind == OutputKind::Record { + self.prepare_recording(&output) + .map_err(ToolError::processing)?; + } + output.start().map_err(ToolError::processing)?; + } + Ok(ActiveOutput { + active: output.active(), + }) + } + + fn stop_output(&self, request: OutputRequest) -> Result { + let output = self.output(request.kind).map_err(ToolError::not_ready)?; + if output.active() { + output.stop(); + } + Ok(ActiveOutput { + active: output.active(), + }) + } + fn start(&self, kind: OutputKind) -> Result<(), String> { let output = self.output(kind)?; if output.active() { diff --git a/rust/obs-mcp/src/server/typed.rs b/rust/obs-mcp/src/server/typed.rs index 4b9763a692..539dd1c1bc 100644 --- a/rust/obs-mcp/src/server/typed.rs +++ b/rust/obs-mcp/src/server/typed.rs @@ -29,8 +29,8 @@ impl ToolAnnotations { pub const MUTATING: Self = Self { read_only_hint: false, idempotent_hint: false, - destructive_hint: false, - open_world_hint: false, + destructive_hint: true, + open_world_hint: true, }; /// Repeating start/stop succeeds with the current state. pub const IDEMPOTENT: Self = Self { @@ -42,7 +42,7 @@ impl ToolAnnotations { #[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum ErrorCategory { - /// A resource is absent or not ready (5xx). + /// A resource is absent or not ready (ResourceNotFound/NotReady). NotReady, /// The current state prevents the operation (6xx). WrongState, @@ -63,34 +63,34 @@ pub struct ToolError { pub retryable: bool, } impl ToolError { - /// Processing failure (7xx control API range). + /// Processing failure (obs-websocket v5 RequestProcessingFailed, 702). pub fn processing(message: impl Into) -> Self { Self { - code: 700, + code: 702, category: ErrorCategory::Processing, message: message.into(), retryable: false, } } - /// Missing resource (5xx control API range). + /// Missing resource (obs-websocket v5 ResourceNotFound, 600). pub fn not_found(message: impl Into) -> Self { Self { - code: 500, + code: 600, category: ErrorCategory::NotReady, message: message.into(), retryable: false, } } - /// A required subsystem is unavailable (5xx control API range). + /// A required subsystem is unavailable (obs-websocket v5 NotReady, 207). pub fn not_ready(message: impl Into) -> Self { Self { - code: 509, + code: 207, category: ErrorCategory::NotReady, message: message.into(), retryable: true, } } - /// Invalid resource state (6xx control API range). + /// Invalid resource state (obs-websocket v5 InvalidResourceState, 604). pub fn wrong_state(message: impl Into) -> Self { Self { code: 604, diff --git a/rust/obs-mcp/tests/libobs_backend.rs b/rust/obs-mcp/tests/libobs_backend.rs index 43e235cc9a..ad56b907eb 100644 --- a/rust/obs-mcp/tests/libobs_backend.rs +++ b/rust/obs-mcp/tests/libobs_backend.rs @@ -253,6 +253,20 @@ fn stats_capture_and_outputs(backend: &ObsBackend) { let error = named.start(OutputKind::Record).unwrap_err(); assert!(error.contains("missing_record"), "{error}"); assert!(!named.status(OutputKind::Record).active); + // Typed operations distinguish readiness from processing failures, including + // stop on an unconfigured output (not an already-stopped configured output). + let request = obs_mcp::tools::outputs::OutputRequest { + kind: OutputKind::Record, + }; + for error in [ + backend.start_output(request).unwrap_err(), + backend.stop_output(request).unwrap_err(), + named.start_output(request).unwrap_err(), + ] { + assert_eq!(error.code, 207); + assert_eq!(error.category, obs_mcp::server::ErrorCategory::NotReady); + assert!(error.retryable); + } } /// The tools and resources a client calls reach the same libobs state. diff --git a/rust/obs-mcp/tests/mcp/outputs.rs b/rust/obs-mcp/tests/mcp/outputs.rs index a0eb11abae..03cd01df20 100644 --- a/rust/obs-mcp/tests/mcp/outputs.rs +++ b/rust/obs-mcp/tests/mcp/outputs.rs @@ -95,8 +95,15 @@ fn lists_six_tools_with_empty_object_schemas() { ); for t in tools { let snapshot = obs_mcp::tools::schema_snapshot(); - let contract = snapshot["tools"].as_array().unwrap().iter().find(|entry| entry["name"] == t["name"]).unwrap(); - for field in ["inputSchema", "outputSchema", "annotations"] { assert_eq!(t[field], contract[field]); } + let contract = snapshot["tools"] + .as_array() + .unwrap() + .iter() + .find(|entry| entry["name"] == t["name"]) + .unwrap(); + for field in ["inputSchema", "outputSchema", "annotations"] { + assert_eq!(t[field], contract[field]); + } assert_eq!(t["inputSchema"]["type"], "object"); assert_eq!(t["inputSchema"]["properties"], json!({})); diff --git a/rust/obs-mcp/tests/mcp/scenes.rs b/rust/obs-mcp/tests/mcp/scenes.rs index 8acab021ad..0151fd97b8 100644 --- a/rust/obs-mcp/tests/mcp/scenes.rs +++ b/rust/obs-mcp/tests/mcp/scenes.rs @@ -97,8 +97,15 @@ fn lists_five_tools_with_object_schemas() { ); for t in tools { let snapshot = obs_mcp::tools::schema_snapshot(); - let contract = snapshot["tools"].as_array().unwrap().iter().find(|entry| entry["name"] == t["name"]).unwrap(); - for field in ["inputSchema", "outputSchema", "annotations"] { assert_eq!(t[field], contract[field]); } + let contract = snapshot["tools"] + .as_array() + .unwrap() + .iter() + .find(|entry| entry["name"] == t["name"]) + .unwrap(); + for field in ["inputSchema", "outputSchema", "annotations"] { + assert_eq!(t[field], contract[field]); + } assert_eq!(t["inputSchema"]["type"], "object"); assert!(!t["description"].as_str().unwrap().is_empty()); diff --git a/rust/obs-mcp/tests/mcp/screenshot.rs b/rust/obs-mcp/tests/mcp/screenshot.rs index e10754f009..730ae91fe9 100644 --- a/rust/obs-mcp/tests/mcp/screenshot.rs +++ b/rust/obs-mcp/tests/mcp/screenshot.rs @@ -128,8 +128,15 @@ fn lists_screenshot_with_optional_arguments() { assert_eq!(tools.len(), 1); assert_eq!(tools[0]["name"], "screenshot"); let snapshot = obs_mcp::tools::schema_snapshot(); - let contract = snapshot["tools"].as_array().unwrap().iter().find(|entry| entry["name"] == "screenshot").unwrap(); - for field in ["inputSchema", "outputSchema", "annotations"] { assert_eq!(tools[0][field], contract[field]); } + let contract = snapshot["tools"] + .as_array() + .unwrap() + .iter() + .find(|entry| entry["name"] == "screenshot") + .unwrap(); + for field in ["inputSchema", "outputSchema", "annotations"] { + assert_eq!(tools[0][field], contract[field]); + } let schema = &tools[0]["inputSchema"]; assert_eq!(schema["type"], "object"); diff --git a/rust/obs-mcp/tests/mcp/sources.rs b/rust/obs-mcp/tests/mcp/sources.rs index dd83c31806..12ce475169 100644 --- a/rust/obs-mcp/tests/mcp/sources.rs +++ b/rust/obs-mcp/tests/mcp/sources.rs @@ -190,8 +190,15 @@ fn lists_seven_tools_with_object_schemas() { ); for t in tools { let snapshot = obs_mcp::tools::schema_snapshot(); - let contract = snapshot["tools"].as_array().unwrap().iter().find(|entry| entry["name"] == t["name"]).unwrap(); - for field in ["inputSchema", "outputSchema", "annotations"] { assert_eq!(t[field], contract[field]); } + let contract = snapshot["tools"] + .as_array() + .unwrap() + .iter() + .find(|entry| entry["name"] == t["name"]) + .unwrap(); + for field in ["inputSchema", "outputSchema", "annotations"] { + assert_eq!(t[field], contract[field]); + } assert_eq!(t["inputSchema"]["type"], "object"); assert!(!t["description"].as_str().unwrap().is_empty()); @@ -452,7 +459,11 @@ fn bad_arguments_are_tool_errors() { }; let cases = [ ("source_create", json!({}), "kind"), - ("source_create", json!({"kind": "k", "name": "", "settings": {}}), "name"), + ( + "source_create", + json!({"kind": "k", "name": "", "settings": {}}), + "name", + ), ( "source_create", json!({"kind": "k", "name": "n"}), diff --git a/rust/obs-mcp/tests/mcp/typed.rs b/rust/obs-mcp/tests/mcp/typed.rs index 83397d5b42..2d16e0c668 100644 --- a/rust/obs-mcp/tests/mcp/typed.rs +++ b/rust/obs-mcp/tests/mcp/typed.rs @@ -79,7 +79,7 @@ fn domain_errors_have_machine_readable_status() { assert_eq!(response["result"]["isError"], true); assert_eq!( response["result"]["structuredContent"], - json!({"code":700,"category":"processing","message":"deliberate failure","retryable":false}) + json!({"code":702,"category":"processing","message":"deliberate failure","retryable":false}) ); let text: serde_json::Value = serde_json::from_str(response["result"]["content"][0]["text"].as_str().unwrap()).unwrap(); @@ -91,8 +91,21 @@ fn schema_snapshot_has_not_drifted() { let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) .join("../../docs/rust-port/control-api.schema.json"); if std::env::var_os("OBS_UPDATE_CONTROL_SCHEMA").is_some() { - std::fs::write(&path, format!("{{\n \"toolError\": {},\n \"tools\": [\n{}\n ]\n}}\n", - actual["toolError"], actual["tools"].as_array().unwrap().iter().map(|tool| format!(" {tool}")).collect::>().join(",\n"))).unwrap(); + std::fs::write( + &path, + format!( + "{{\n \"toolError\": {},\n \"tools\": [\n{}\n ]\n}}\n", + actual["toolError"], + actual["tools"] + .as_array() + .unwrap() + .iter() + .map(|tool| format!(" {tool}")) + .collect::>() + .join(",\n") + ), + ) + .unwrap(); } let expected: serde_json::Value = serde_json::from_slice(&std::fs::read(path).expect("committed schema snapshot")).unwrap(); @@ -101,3 +114,17 @@ fn schema_snapshot_has_not_drifted() { "regenerate with OBS_UPDATE_CONTROL_SCHEMA=1 and the focused schema test" ); } + +#[test] +fn domain_status_codes_match_websocket_v5() { + use obs_mcp::server::ErrorCategory; + let missing = ToolError::not_found("missing"); + assert_eq!( + (missing.code, missing.category, missing.retryable), + (600, ErrorCategory::NotReady, false) + ); + let not_ready = ToolError::not_ready("initializing"); + assert_eq!((not_ready.code, not_ready.retryable), (207, true)); + assert_eq!(ToolError::wrong_state("state").code, 604); + assert_eq!(ToolError::processing("failed").code, 702); +} From f988eb2826b010b73c95a22451460795e5562a08 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 13:53:52 -0800 Subject: [PATCH 05/39] fix(mcp): retain legacy JSON text ordering and output descriptions (#4445) --- rust/obs-mcp/src/server/typed.rs | 8 +++++--- rust/obs-mcp/src/tools/outputs.rs | 12 ++++++------ 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/rust/obs-mcp/src/server/typed.rs b/rust/obs-mcp/src/server/typed.rs index 539dd1c1bc..d1f3d5a4e0 100644 --- a/rust/obs-mcp/src/server/typed.rs +++ b/rust/obs-mcp/src/server/typed.rs @@ -127,8 +127,8 @@ pub trait TypedTool { /// # Errors /// Reports output serialization failures without panicking the server. fn content(output: &Self::Output) -> Result, ToolError> { - serde_json::to_string(output) - .map(|text| vec![Content::Text(text)]) + serde_json::to_value(output) + .map(|value| vec![Content::Text(value.to_string())]) .map_err(|error| ToolError::processing(error.to_string())) } } @@ -151,7 +151,9 @@ impl Tool for T { fn call(&self, arguments: &Value) -> Result { let input = parse_input(arguments)?; let output = TypedTool::call(self, input).map_err(|e| e.to_string())?; - serde_json::to_string(&output).map_err(|e| e.to_string()) + serde_json::to_value(output) + .map(|value| value.to_string()) + .map_err(|e| e.to_string()) } fn call_content(&self, arguments: &Value) -> Result, String> { let input = parse_input(arguments)?; diff --git a/rust/obs-mcp/src/tools/outputs.rs b/rust/obs-mcp/src/tools/outputs.rs index 1373f2654a..230f86d5e8 100644 --- a/rust/obs-mcp/src/tools/outputs.rs +++ b/rust/obs-mcp/src/tools/outputs.rs @@ -97,7 +97,7 @@ typed_tool!( EmptyInput, ActiveOutput, IDEMPOTENT, - "Start record output.", + "Start recording.", |backend, _input| { backend.start_output(OutputRequest { kind: OutputKind::Record, @@ -111,7 +111,7 @@ typed_tool!( EmptyInput, ActiveOutput, IDEMPOTENT, - "Stop record output.", + "Stop recording.", |backend, _input| { backend.stop_output(OutputRequest { kind: OutputKind::Record, @@ -125,7 +125,7 @@ typed_tool!( EmptyInput, OutputStatus, READ_ONLY, - "Status record output.", + "Report whether recording is active, with duration_ms and bytes where known.", |backend, _input| { Ok(backend.output_status(OutputRequest { kind: OutputKind::Record, @@ -139,7 +139,7 @@ typed_tool!( EmptyInput, ActiveOutput, IDEMPOTENT, - "Start stream output.", + "Start streaming.", |backend, _input| { backend.start_output(OutputRequest { kind: OutputKind::Stream, @@ -153,7 +153,7 @@ typed_tool!( EmptyInput, ActiveOutput, IDEMPOTENT, - "Stop stream output.", + "Stop streaming.", |backend, _input| { backend.stop_output(OutputRequest { kind: OutputKind::Stream, @@ -167,7 +167,7 @@ typed_tool!( EmptyInput, OutputStatus, READ_ONLY, - "Status stream output.", + "Report whether streaming is active, with duration_ms and bytes where known.", |backend, _input| { Ok(backend.output_status(OutputRequest { kind: OutputKind::Stream, From a11ee2ad2b417322f9c671e383254f167f7248c8 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 14:35:49 -0800 Subject: [PATCH 06/39] test(mcp): RED device and pipeline counter baseline contract (#4446) --- rust/obs-mcp/src/tools/control.rs | 184 ++++++++++++++++++++++++++++++ rust/obs-mcp/src/tools/mod.rs | 2 + rust/obs-mcp/tests/mcp/control.rs | 8 ++ rust/obs-mcp/tests/mcp/main.rs | 2 + 4 files changed, 196 insertions(+) create mode 100644 rust/obs-mcp/src/tools/control.rs create mode 100644 rust/obs-mcp/tests/mcp/control.rs diff --git a/rust/obs-mcp/src/tools/control.rs b/rust/obs-mcp/src/tools/control.rs new file mode 100644 index 0000000000..05f4fa5a44 --- /dev/null +++ b/rust/obs-mcp/src/tools/control.rs @@ -0,0 +1,184 @@ +//! Device, media and measured pipeline control (#4446). +use std::rc::Rc; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use crate::server::{ToolError, ToolRegistry}; +use super::EmptyInput; + +/// Bounded start options, extended by the wait domain. +#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct StartInput { + /// Wait until the output reports active. + #[serde(default)] + pub wait: bool, +} +/// Virtual Camera and its paired audio source. +#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] +pub struct VcamStatus { + /// Whether the registered output exists. + pub configured: bool, + /// Video output is active. + pub active: bool, + /// Paired virtual microphone is active, when the plugin supports the query. + pub vmic_active: Option, +} +/// Virtual microphone state. +#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] +pub struct VmicStatus { + /// Active according to virtualcam_audio; null means unsupported. + pub active: Option, + /// Runtime source name, when known. + pub source_name: Option, +} +/// A media source selection. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct MediaInput { + /// Name of an existing media source. + pub name: String, +} +/// libobs media state. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum MediaState { + /// Not a controllable media source. + #[default] + None, + /// Playing. + Playing, + /// Opening. + Opening, + /// Buffering. + Buffering, + /// Paused. + Paused, + /// Stopped. + Stopped, + /// Playback reached the end. + Ended, + /// Playback failed. + Error, +} +/// Media playback snapshot, in milliseconds. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +pub struct MediaStatus { + /// Source name. + pub name: String, + /// Current media state. + pub state: MediaState, + /// Total duration, if known. + pub duration_ms: Option, + /// Playback position, if known. + pub position_ms: Option, +} +/// One live pipeline stage; null values are unmeasured, never synthetic zeroes. +#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] +pub struct StageStats { + /// Currently running. + pub live: bool, + /// Observed minimum stage residence time, if measured. + pub latency_min_ns: Option, + /// Observed maximum stage residence time, if measured. + pub latency_max_ns: Option, + /// Frames handled since the counter baseline. + pub frames_total: Option, + /// Dropped frames since baseline, if measured. + pub frames_dropped: Option, + /// Underruns/overruns since baseline, if measured. + pub xruns: Option, +} +/// Render and device stages. +#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] +pub struct Stages { + /// OBS render stage. + pub render: StageStats, + /// Virtual Camera write stage. + pub vcam: StageStats, + /// Virtual microphone stage. + pub vmic: StageStats, +} +/// End-to-end measurement provenance. +#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] +pub struct SyncStats { + /// Measured audio minus video offset; null until independently measured. + pub av_offset_ms: Option, + /// Measurement source; queue estimates are not end-to-end measurements. + pub measured_from: String, +} +/// GetStats-style render counters. +#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] +pub struct RenderStats { + /// Actual render FPS. + pub active_fps: f64, + /// Average render duration, not end-to-end latency. + pub average_frame_time_ns: u64, + /// Frames rendered since baseline. + pub render_total_frames: u64, + /// Frames lagged since baseline. + pub render_skipped_frames: u64, +} +/// Typed pipeline statistics. +#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] +pub struct StatsSnapshot { + /// Per-stage measured counters and bounds. + pub stages: Stages, + /// End-to-end sync, with explicit provenance. + pub end_to_end: SyncStats, + /// Render counters. + pub render: RenderStats, +} +/// Graph snapshot useful for diagnosing missing sources and outputs. +#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] +pub struct PipelineDump { + /// Program source name. + pub program: Option, + /// Source names in stable order. + pub sources: Vec, + /// Virtual output state. + pub vcam: VcamStatus, + /// Current pipeline measurements. + pub stats: StatsSnapshot, +} +/// Backend operations take typed requests and return typed responses. +pub trait ControlBackend { + /// Starts or observes an already-running camera. + /// # Errors + /// Reports missing plugins, unavailable devices or processing failures. + fn vcam_start(&self, request: StartInput) -> Result; + /// Stops or observes an already-stopped camera. + /// # Errors + /// Reports unavailable output configuration. + fn vcam_stop(&self, request: EmptyInput) -> Result; + /// Camera status. + /// # Errors + /// Reports query failures. + fn vcam_status(&self, request: EmptyInput) -> Result; + /// Microphone status. + /// # Errors + /// Reports query failures. + fn vmic_status(&self, request: EmptyInput) -> Result; + /// Restarts a media source. + /// # Errors + /// Reports missing or non-media sources. + fn media_restart(&self, request: MediaInput) -> Result; + /// Media status. + /// # Errors + /// Reports missing sources. + fn media_status(&self, request: MediaInput) -> Result; + /// Statistics since the current baseline. + /// # Errors + /// Reports query failures. + fn stats_get(&self, request: EmptyInput) -> Result; + /// Sets a new baseline and returns the resulting snapshot. + /// # Errors + /// Reports query failures. + fn stats_reset(&self, request: EmptyInput) -> Result; + /// Graph and measurements. + /// # Errors + /// Reports query failures. + fn pipeline_dump(&self, request: EmptyInput) -> Result; +} +/// Difference from a baseline; a recreated counter begins a new generation. +#[must_use] +pub fn counter_delta(current: u64, baseline: u64) -> u64 { todo!("counter baseline") } diff --git a/rust/obs-mcp/src/tools/mod.rs b/rust/obs-mcp/src/tools/mod.rs index 981e9fd27d..ac39f2c144 100644 --- a/rust/obs-mcp/src/tools/mod.rs +++ b/rust/obs-mcp/src/tools/mod.rs @@ -43,3 +43,5 @@ pub fn schema_snapshot() -> serde_json::Value { tools.sort_by(|a, b| a["name"].as_str().cmp(&b["name"].as_str())); serde_json::json!({"tools": tools, "toolError": schemars::schema_for!(crate::server::ToolError)}) } + +pub mod control; diff --git a/rust/obs-mcp/tests/mcp/control.rs b/rust/obs-mcp/tests/mcp/control.rs new file mode 100644 index 0000000000..a579e88f59 --- /dev/null +++ b/rust/obs-mcp/tests/mcp/control.rs @@ -0,0 +1,8 @@ +//! Control API domains (#4446); no additional test executable. +use obs_mcp::tools::control::counter_delta; +#[test] +fn counters_are_relative_to_baseline_and_survive_recreation() { + assert_eq!(counter_delta(20, 5), 15); + assert_eq!(counter_delta(5, 5), 0); + assert_eq!(counter_delta(3, 20), 3); +} diff --git a/rust/obs-mcp/tests/mcp/main.rs b/rust/obs-mcp/tests/mcp/main.rs index dd42459744..eeb8ab3bec 100644 --- a/rust/obs-mcp/tests/mcp/main.rs +++ b/rust/obs-mcp/tests/mcp/main.rs @@ -25,3 +25,5 @@ pub(crate) fn roundtrip(input: &str) -> Vec { } mod typed; + +mod control; From bacedb8fc09d67fe5ea8e06112b5c8603c968564 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 14:46:48 -0800 Subject: [PATCH 07/39] feat(mcp): device, media and measured pipeline control (#4446) --- Cargo.lock | 1 + docs/features.md | 6 + docs/rust-port/control-api.schema.json | 11 +- plugins/linux-v4l2/v4l2-output.c.h | 71 +++++++++- rust/obs-mcp/Cargo.toml | 3 +- rust/obs-mcp/src/backend/control.rs | 126 +++++++++++++++++ rust/obs-mcp/src/backend/mod.rs | 8 ++ rust/obs-mcp/src/ffi/control.rs | 153 ++++++++++++++++++++ rust/obs-mcp/src/ffi/mod.rs | 3 + rust/obs-mcp/src/tools/control.rs | 186 ++++++++++++++++++++++++- rust/obs-mcp/src/tools/mod.rs | 1 + rust/obs-mcp/tests/mcp/control.rs | 111 +++++++++++++++ 12 files changed, 668 insertions(+), 12 deletions(-) create mode 100644 rust/obs-mcp/src/backend/control.rs create mode 100644 rust/obs-mcp/src/ffi/control.rs diff --git a/Cargo.lock b/Cargo.lock index 2fe6331eb9..41ac77bbf1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -658,6 +658,7 @@ dependencies = [ "base64", "flate2", "libc", + "obs-callback", "obs-sys", "schemars", "serde", diff --git a/docs/features.md b/docs/features.md index e254acf9eb..cd929e1368 100644 --- a/docs/features.md +++ b/docs/features.md @@ -75,6 +75,12 @@ not get a line. ### Headless and automation +- **Virtual device and media control.** MCP can start/stop Virtual Camera, inspect + its paired mic, restart media, inspect pipeline graphs and read/reset measured + stage counters. Unmeasured device/sync values stay null. *All* (device support + depends on the loaded plugin), 2026-11-09. Issue [#4446](https://github.com/obs-rust/obs-studio/issues/4446), + PR [#4452](https://github.com/obs-rust/obs-studio/pull/4452). + - **Typed MCP control.** Existing OBS MCP tools publish input and output schemas, structured results and machine-readable domain errors. Read operations carry annotations, and repeated output start/stop calls succeed with current state. diff --git a/docs/rust-port/control-api.schema.json b/docs/rust-port/control-api.schema.json index 5656f4d596..9ff16237ed 100644 --- a/docs/rust-port/control-api.schema.json +++ b/docs/rust-port/control-api.schema.json @@ -1,6 +1,9 @@ { "toolError": {"$defs":{"ErrorCategory":{"description":"Domain failure category, using obs-websocket v5 status ranges.","oneOf":[{"const":"not_ready","description":"A resource is absent or not ready (ResourceNotFound/NotReady).","type":"string"},{"const":"wrong_state","description":"The current state prevents the operation (6xx).","type":"string"},{"const":"processing","description":"OBS failed to process the operation (7xx).","type":"string"}]}},"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"A domain failure, distinct from a JSON-RPC fault.","properties":{"category":{"$ref":"#/$defs/ErrorCategory","description":"Stable machine-readable category."},"code":{"description":"obs-websocket v5 RequestStatus code.","format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"message":{"description":"Human-readable context.","type":"string"},"retryable":{"description":"Whether a later retry may succeed.","type":"boolean"}},"required":["code","category","message","retryable"],"title":"ToolError","type":"object"}, "tools": [ + {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"A media source selection.","properties":{"name":{"description":"Name of an existing media source.","type":"string"}},"required":["name"],"title":"MediaInput","type":"object"},"name":"media_restart","outputSchema":{"$defs":{"MediaState":{"description":"libobs media state.","oneOf":[{"const":"none","description":"Not a controllable media source.","type":"string"},{"const":"playing","description":"Playing.","type":"string"},{"const":"opening","description":"Opening.","type":"string"},{"const":"buffering","description":"Buffering.","type":"string"},{"const":"paused","description":"Paused.","type":"string"},{"const":"stopped","description":"Stopped.","type":"string"},{"const":"ended","description":"Playback reached the end.","type":"string"},{"const":"error","description":"Playback failed.","type":"string"}]}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Media playback snapshot, in milliseconds.","properties":{"duration_ms":{"description":"Total duration, if known.","format":"int64","type":["integer","null"]},"name":{"description":"Source name.","type":"string"},"position_ms":{"description":"Playback position, if known.","format":"int64","type":["integer","null"]},"state":{"$ref":"#/$defs/MediaState","description":"Current media state."}},"required":["name","state"],"title":"MediaStatus","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"A media source selection.","properties":{"name":{"description":"Name of an existing media source.","type":"string"}},"required":["name"],"title":"MediaInput","type":"object"},"name":"media_status","outputSchema":{"$defs":{"MediaState":{"description":"libobs media state.","oneOf":[{"const":"none","description":"Not a controllable media source.","type":"string"},{"const":"playing","description":"Playing.","type":"string"},{"const":"opening","description":"Opening.","type":"string"},{"const":"buffering","description":"Buffering.","type":"string"},{"const":"paused","description":"Paused.","type":"string"},{"const":"stopped","description":"Stopped.","type":"string"},{"const":"ended","description":"Playback reached the end.","type":"string"},{"const":"error","description":"Playback failed.","type":"string"}]}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Media playback snapshot, in milliseconds.","properties":{"duration_ms":{"description":"Total duration, if known.","format":"int64","type":["integer","null"]},"name":{"description":"Source name.","type":"string"},"position_ms":{"description":"Playback position, if known.","format":"int64","type":["integer","null"]},"state":{"$ref":"#/$defs/MediaState","description":"Current media state."}},"required":["name","state"],"title":"MediaStatus","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"pipeline_dump","outputSchema":{"$defs":{"RenderStats":{"description":"GetStats-style render counters.","properties":{"active_fps":{"description":"Actual render FPS.","format":"double","type":"number"},"average_frame_time_ns":{"description":"Average render duration, not end-to-end latency.","format":"uint64","minimum":0,"type":"integer"},"render_skipped_frames":{"description":"Frames lagged since baseline.","format":"uint64","minimum":0,"type":"integer"},"render_total_frames":{"description":"Frames rendered since baseline.","format":"uint64","minimum":0,"type":"integer"}},"required":["active_fps","average_frame_time_ns","render_total_frames","render_skipped_frames"],"type":"object"},"StageStats":{"description":"One live pipeline stage; null values are unmeasured, never synthetic zeroes.","properties":{"frames_dropped":{"description":"Dropped frames since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"frames_total":{"description":"Frames handled since the counter baseline.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_max_ns":{"description":"Observed maximum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_min_ns":{"description":"Observed minimum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"live":{"description":"Currently running.","type":"boolean"},"xruns":{"description":"Underruns/overruns since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]}},"required":["live"],"type":"object"},"Stages":{"description":"Render and device stages.","properties":{"render":{"$ref":"#/$defs/StageStats","description":"OBS render stage."},"vcam":{"$ref":"#/$defs/StageStats","description":"Virtual Camera write stage."},"vmic":{"$ref":"#/$defs/StageStats","description":"Virtual microphone stage."}},"required":["render","vcam","vmic"],"type":"object"},"StatsSnapshot":{"description":"Typed pipeline statistics.","properties":{"end_to_end":{"$ref":"#/$defs/SyncStats","description":"End-to-end sync, with explicit provenance."},"render":{"$ref":"#/$defs/RenderStats","description":"Render counters."},"stages":{"$ref":"#/$defs/Stages","description":"Per-stage measured counters and bounds."}},"required":["stages","end_to_end","render"],"type":"object"},"SyncStats":{"description":"End-to-end measurement provenance.","properties":{"av_offset_ms":{"description":"Measured audio minus video offset; null until independently measured.","format":"double","type":["number","null"]},"measured_from":{"description":"Measurement source; queue estimates are not end-to-end measurements.","type":"string"}},"required":["measured_from"],"type":"object"},"VcamStatus":{"description":"Virtual Camera and its paired audio source.","properties":{"active":{"description":"Video output is active.","type":"boolean"},"configured":{"description":"Whether the registered output exists.","type":"boolean"},"vmic_active":{"description":"Paired virtual microphone is active, when the plugin supports the query.","type":["boolean","null"]}},"required":["configured","active"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Graph snapshot useful for diagnosing missing sources and outputs.","properties":{"program":{"description":"Program source name.","type":["string","null"]},"sources":{"description":"Source names in stable order.","items":{"type":"string"},"type":"array"},"stats":{"$ref":"#/$defs/StatsSnapshot","description":"Current pipeline measurements."},"vcam":{"$ref":"#/$defs/VcamStatus","description":"Virtual output state."}},"required":["sources","vcam","stats"],"title":"PipelineDump","type":"object"}}, {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"record_start","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"record_status","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"The state of an output as reported by [`OutputBackend::status`].","properties":{"active":{"description":"Whether the output is running.","type":"boolean"},"bytes":{"description":"Bytes written or sent so far, where known.","format":"uint64","minimum":0,"type":["integer","null"]},"duration_ms":{"description":"Milliseconds since the output started, where known.","format":"uint64","minimum":0,"type":["integer","null"]}},"required":["active"],"title":"OutputStatus","type":"object"}}, {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"record_stop","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}}, @@ -17,8 +20,14 @@ {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$defs":{"Pair":{"additionalProperties":false,"description":"Pixel position or scale factors.","properties":{"x":{"description":"Horizontal component.","format":"double","type":"number"},"y":{"description":"Vertical component.","format":"double","type":"number"}},"required":["x","y"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Source creation, optionally placing it in a scene.","properties":{"kind":{"description":"Source kind id.","type":"string"},"name":{"description":"Unique name.","type":"string"},"position":{"anyOf":[{"$ref":"#/$defs/Pair"},{"type":"null"}],"description":"Initial position (requires scene)."},"scene":{"description":"Scene receiving the source.","type":["string","null"]},"settings":{"additionalProperties":true,"description":"Kind-specific settings.","type":"object"}},"required":["kind","name","settings"],"title":"CreateInput","type":"object"},"name":"source_create","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Created source.","properties":{"item":{"description":"Created item id.","format":"int64","type":["integer","null"]},"kind":{"description":"Source kind.","type":"string"},"name":{"description":"Source name.","type":"string"},"scene":{"description":"Scene receiving the new item.","type":["string","null"]}},"required":["name","kind"],"title":"CreateOutput","type":"object"}}, {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Settings update.","properties":{"name":{"description":"Source name.","type":"string"},"settings":{"additionalProperties":true,"description":"Kind-specific settings to merge.","type":"object"}},"required":["name","settings"],"title":"SettingsInput","type":"object"},"name":"source_set_settings","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Updated source name.","properties":{"name":{"description":"Source name.","type":"string"}},"required":["name"],"title":"NameOutput","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"sources_list","outputSchema":{"$defs":{"SourceInfo":{"description":"A source as listed by [`SourceBackend::sources`].","properties":{"kind":{"description":"The source kind id, such as `color_source`.","type":"string"},"name":{"description":"The source's unique name.","type":"string"}},"required":["name","kind"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Source listing.","properties":{"sources":{"description":"Sources in stable order.","items":{"$ref":"#/$defs/SourceInfo"},"type":"array"}},"required":["sources"],"title":"SourcesOutput","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stats_get","outputSchema":{"$defs":{"RenderStats":{"description":"GetStats-style render counters.","properties":{"active_fps":{"description":"Actual render FPS.","format":"double","type":"number"},"average_frame_time_ns":{"description":"Average render duration, not end-to-end latency.","format":"uint64","minimum":0,"type":"integer"},"render_skipped_frames":{"description":"Frames lagged since baseline.","format":"uint64","minimum":0,"type":"integer"},"render_total_frames":{"description":"Frames rendered since baseline.","format":"uint64","minimum":0,"type":"integer"}},"required":["active_fps","average_frame_time_ns","render_total_frames","render_skipped_frames"],"type":"object"},"StageStats":{"description":"One live pipeline stage; null values are unmeasured, never synthetic zeroes.","properties":{"frames_dropped":{"description":"Dropped frames since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"frames_total":{"description":"Frames handled since the counter baseline.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_max_ns":{"description":"Observed maximum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_min_ns":{"description":"Observed minimum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"live":{"description":"Currently running.","type":"boolean"},"xruns":{"description":"Underruns/overruns since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]}},"required":["live"],"type":"object"},"Stages":{"description":"Render and device stages.","properties":{"render":{"$ref":"#/$defs/StageStats","description":"OBS render stage."},"vcam":{"$ref":"#/$defs/StageStats","description":"Virtual Camera write stage."},"vmic":{"$ref":"#/$defs/StageStats","description":"Virtual microphone stage."}},"required":["render","vcam","vmic"],"type":"object"},"SyncStats":{"description":"End-to-end measurement provenance.","properties":{"av_offset_ms":{"description":"Measured audio minus video offset; null until independently measured.","format":"double","type":["number","null"]},"measured_from":{"description":"Measurement source; queue estimates are not end-to-end measurements.","type":"string"}},"required":["measured_from"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Typed pipeline statistics.","properties":{"end_to_end":{"$ref":"#/$defs/SyncStats","description":"End-to-end sync, with explicit provenance."},"render":{"$ref":"#/$defs/RenderStats","description":"Render counters."},"stages":{"$ref":"#/$defs/Stages","description":"Per-stage measured counters and bounds."}},"required":["stages","end_to_end","render"],"title":"StatsSnapshot","type":"object"}}, + {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stats_reset","outputSchema":{"$defs":{"RenderStats":{"description":"GetStats-style render counters.","properties":{"active_fps":{"description":"Actual render FPS.","format":"double","type":"number"},"average_frame_time_ns":{"description":"Average render duration, not end-to-end latency.","format":"uint64","minimum":0,"type":"integer"},"render_skipped_frames":{"description":"Frames lagged since baseline.","format":"uint64","minimum":0,"type":"integer"},"render_total_frames":{"description":"Frames rendered since baseline.","format":"uint64","minimum":0,"type":"integer"}},"required":["active_fps","average_frame_time_ns","render_total_frames","render_skipped_frames"],"type":"object"},"StageStats":{"description":"One live pipeline stage; null values are unmeasured, never synthetic zeroes.","properties":{"frames_dropped":{"description":"Dropped frames since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"frames_total":{"description":"Frames handled since the counter baseline.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_max_ns":{"description":"Observed maximum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_min_ns":{"description":"Observed minimum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"live":{"description":"Currently running.","type":"boolean"},"xruns":{"description":"Underruns/overruns since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]}},"required":["live"],"type":"object"},"Stages":{"description":"Render and device stages.","properties":{"render":{"$ref":"#/$defs/StageStats","description":"OBS render stage."},"vcam":{"$ref":"#/$defs/StageStats","description":"Virtual Camera write stage."},"vmic":{"$ref":"#/$defs/StageStats","description":"Virtual microphone stage."}},"required":["render","vcam","vmic"],"type":"object"},"SyncStats":{"description":"End-to-end measurement provenance.","properties":{"av_offset_ms":{"description":"Measured audio minus video offset; null until independently measured.","format":"double","type":["number","null"]},"measured_from":{"description":"Measurement source; queue estimates are not end-to-end measurements.","type":"string"}},"required":["measured_from"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Typed pipeline statistics.","properties":{"end_to_end":{"$ref":"#/$defs/SyncStats","description":"End-to-end sync, with explicit provenance."},"render":{"$ref":"#/$defs/RenderStats","description":"Render counters."},"stages":{"$ref":"#/$defs/Stages","description":"Per-stage measured counters and bounds."}},"required":["stages","end_to_end","render"],"title":"StatsSnapshot","type":"object"}}, {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stream_start","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stream_status","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"The state of an output as reported by [`OutputBackend::status`].","properties":{"active":{"description":"Whether the output is running.","type":"boolean"},"bytes":{"description":"Bytes written or sent so far, where known.","format":"uint64","minimum":0,"type":["integer","null"]},"duration_ms":{"description":"Milliseconds since the output started, where known.","format":"uint64","minimum":0,"type":["integer","null"]}},"required":["active"],"title":"OutputStatus","type":"object"}}, - {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stream_stop","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}} + {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stream_stop","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}}, + {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Bounded start options, extended by the wait domain.","properties":{"wait":{"default":false,"description":"Wait until the output reports active.","type":"boolean"}},"title":"StartInput","type":"object"},"name":"vcam_start","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Virtual Camera and its paired audio source.","properties":{"active":{"description":"Video output is active.","type":"boolean"},"configured":{"description":"Whether the registered output exists.","type":"boolean"},"vmic_active":{"description":"Paired virtual microphone is active, when the plugin supports the query.","type":["boolean","null"]}},"required":["configured","active"],"title":"VcamStatus","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"vcam_status","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Virtual Camera and its paired audio source.","properties":{"active":{"description":"Video output is active.","type":"boolean"},"configured":{"description":"Whether the registered output exists.","type":"boolean"},"vmic_active":{"description":"Paired virtual microphone is active, when the plugin supports the query.","type":["boolean","null"]}},"required":["configured","active"],"title":"VcamStatus","type":"object"}}, + {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"vcam_stop","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Virtual Camera and its paired audio source.","properties":{"active":{"description":"Video output is active.","type":"boolean"},"configured":{"description":"Whether the registered output exists.","type":"boolean"},"vmic_active":{"description":"Paired virtual microphone is active, when the plugin supports the query.","type":["boolean","null"]}},"required":["configured","active"],"title":"VcamStatus","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"vmic_status","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Virtual microphone state.","properties":{"active":{"description":"Active according to virtualcam_audio; null means unsupported.","type":["boolean","null"]},"source_name":{"description":"Runtime source name, when known.","type":["string","null"]}},"title":"VmicStatus","type":"object"}} ] } diff --git a/plugins/linux-v4l2/v4l2-output.c.h b/plugins/linux-v4l2/v4l2-output.c.h index ecab2c2c42..1c0fa75ccf 100644 --- a/plugins/linux-v4l2/v4l2-output.c.h +++ b/plugins/linux-v4l2/v4l2-output.c.h @@ -49,6 +49,11 @@ struct virtualcam_data { char mic_path[256]; char mic_lock_path[256]; int mic_lock; + /* Lifetime counters; all accesses hold sync.mutex. Never consumed by logging. */ + uint64_t stats_video_frames, stats_video_dropped, stats_video_measured; + uint64_t stats_video_min_ns, stats_video_max_ns; + uint64_t stats_audio_frames, stats_audio_dropped, stats_audio_measured; + uint64_t stats_audio_min_ns, stats_audio_max_ns; }; static void vmic_stop(struct virtualcam_data *vcam); @@ -941,6 +946,28 @@ static void virtualcam_audio_proc(void *data, calldata_t *cd) calldata_set_bool(cd, "active", vcam->mic_fifo >= 0); } +/* Private Control API: bounds measure libobs timestamps to completed writes, + * not device capture or end-to-end A/V latency. Native PipeWire xruns remain + * absent on the FIFO backend (#4124); consumers must represent them as unknown. */ +static void virtualcam_stats_proc(void *data, calldata_t *cd) +{ + struct virtualcam_data *vcam = data; + pthread_mutex_lock(&vcam->sync.mutex); + calldata_set_int(cd, "vcam_frames", (long long)vcam->stats_video_frames); + calldata_set_int(cd, "vcam_dropped", (long long)vcam->stats_video_dropped); + calldata_set_int(cd, "vmic_frames", (long long)vcam->stats_audio_frames); + calldata_set_int(cd, "vmic_dropped", (long long)vcam->stats_audio_dropped); + if (vcam->stats_video_measured) { + calldata_set_int(cd, "vcam_min_ns", (long long)vcam->stats_video_min_ns); + calldata_set_int(cd, "vcam_max_ns", (long long)vcam->stats_video_max_ns); + } + if (vcam->stats_audio_measured) { + calldata_set_int(cd, "vmic_min_ns", (long long)vcam->stats_audio_min_ns); + calldata_set_int(cd, "vmic_max_ns", (long long)vcam->stats_audio_max_ns); + } + pthread_mutex_unlock(&vcam->sync.mutex); +} + static void *virtualcam_create(obs_data_t *settings, obs_output_t *output) { struct virtualcam_data *vcam = (struct virtualcam_data *)bzalloc(sizeof(*vcam)); @@ -957,6 +984,11 @@ static void *virtualcam_create(obs_data_t *settings, obs_output_t *output) if (output) proc_handler_add(obs_output_get_proc_handler(output), "void virtualcam_audio(out bool active)", virtualcam_audio_proc, vcam); + if (output) + proc_handler_add( + obs_output_get_proc_handler(output), + "void virtualcam_stats(out int vcam_frames, out int vcam_dropped, out int vmic_frames, out int vmic_dropped, out int vcam_min_ns, out int vcam_max_ns, out int vmic_min_ns, out int vmic_max_ns)", + virtualcam_stats_proc, vcam); return vcam; } @@ -1136,7 +1168,7 @@ static void virtualcam_stop(void *data, uint64_t ts) UNUSED_PARAMETER(ts); } -static void vcam_write_frame(struct virtualcam_data *vcam, const uint8_t *frame_data) +static void vcam_write_frame(struct virtualcam_data *vcam, const uint8_t *frame_data, uint64_t timestamp) { uint32_t frame_size = vcam->frame_size; while (frame_size > 0) { @@ -1148,6 +1180,20 @@ static void vcam_write_frame(struct virtualcam_data *vcam, const uint8_t *frame_ frame_data += written; frame_size -= (uint32_t)written; } + if (frame_size) { + vcam->stats_video_dropped++; + } else { + uint64_t now = os_gettime_ns(); + vcam->stats_video_frames++; + if (now < timestamp) + return; + uint64_t latency = now - timestamp; + if (!vcam->stats_video_measured || latency < vcam->stats_video_min_ns) + vcam->stats_video_min_ns = latency; + if (latency > vcam->stats_video_max_ns) + vcam->stats_video_max_ns = latency; + vcam->stats_video_measured++; + } } /* Sends the waiting frames whose audio the microphone has; under sync.mutex. */ @@ -1155,7 +1201,7 @@ static void vcam_sync_flush(struct virtualcam_data *vcam) { struct vcam_sync *sync = &vcam->sync; while (sync->len > 0 && sync->ts[sync->head] + vcam->mic_lead_ns <= sync->audio_end) { - vcam_write_frame(vcam, sync->frame[sync->head]); + vcam_write_frame(vcam, sync->frame[sync->head], sync->ts[sync->head]); sync->head = (sync->head + 1) % VCAM_SYNC_FRAMES; sync->len--; } @@ -1170,13 +1216,13 @@ static void virtual_video(void *param, struct video_data *frame) /* No running microphone (mic_rate is set only by vmic_start): nothing to wait for. */ if (vcam->mic_fifo < 0 || vcam->mic_rate == 0 || (sync->len == 0 && frame->timestamp + vcam->mic_lead_ns <= sync->audio_end)) { - vcam_write_frame(vcam, frame->data[0]); + vcam_write_frame(vcam, frame->data[0], frame->timestamp); pthread_mutex_unlock(&sync->mutex); return; } if (sync->len == VCAM_SYNC_FRAMES) { /* The audio stopped: the picture goes on without it. */ - vcam_write_frame(vcam, sync->frame[sync->head]); + vcam_write_frame(vcam, sync->frame[sync->head], sync->ts[sync->head]); sync->head = (sync->head + 1) % VCAM_SYNC_FRAMES; sync->len--; } @@ -1196,11 +1242,24 @@ static void virtual_audio(void *param, struct audio_data *frames) return; size_t size = (size_t)frames->frames * VMIC_CHANNELS * sizeof(float); /* Keep at most one packet unread, so a reader hears the newest audio. */ - vmic_drop_stale(vcam->mic_drain, vcam->mic_fifo, size); - vmic_write_packet(vcam->mic_fifo, vcam->mic_pipe_size, &vcam->mic_tail, frames->data[0], size); + size_t discarded = vmic_drop_stale(vcam->mic_drain, vcam->mic_fifo, size); + bool accepted = vmic_write_packet(vcam->mic_fifo, vcam->mic_pipe_size, &vcam->mic_tail, frames->data[0], size); uint64_t end = frames->timestamp + util_mul_div64(frames->frames, 1000000000ULL, vcam->mic_rate); pthread_mutex_lock(&vcam->sync.mutex); + vcam->stats_audio_frames += frames->frames; + vcam->stats_audio_dropped += discarded / (VMIC_CHANNELS * sizeof(float)); + if (!accepted) + vcam->stats_audio_dropped += frames->frames; + uint64_t now = os_gettime_ns(); + if (accepted && !vcam->mic_tail.len && now >= frames->timestamp) { + uint64_t latency = now - frames->timestamp; + if (!vcam->stats_audio_measured || latency < vcam->stats_audio_min_ns) + vcam->stats_audio_min_ns = latency; + if (latency > vcam->stats_audio_max_ns) + vcam->stats_audio_max_ns = latency; + vcam->stats_audio_measured++; + } if (end > vcam->sync.audio_end) vcam->sync.audio_end = end; vcam_sync_flush(vcam); diff --git a/rust/obs-mcp/Cargo.toml b/rust/obs-mcp/Cargo.toml index c43b005d0a..5bec571a4f 100644 --- a/rust/obs-mcp/Cargo.toml +++ b/rust/obs-mcp/Cargo.toml @@ -19,7 +19,7 @@ test = false # Binds the backend traits to libobs through obs-sys (#3283). Off by default: # it needs the libobs symbols at link time, which only the application and the # `bundled-native` contract tests provide. -libobs = ["dep:obs-sys", "dep:libc"] +libobs = ["dep:obs-sys", "dep:libc", "dep:obs-callback"] # Test-only fault injection (with `libobs`): `host::fail_audio_mixer` makes the next start # behave as if libobs could not open its audio mixer (#3491). Enabled only by # obs-studio-rust's dev-dependency, so no shipped build can reach it; the @@ -27,6 +27,7 @@ libobs = ["dep:obs-sys", "dep:libc"] fault-injection = [] [dependencies] +obs-callback = { path = "../obs-callback", optional = true } schemars = { workspace = true, features = ["derive", "std"] } serde_path_to_error = { workspace = true } obs-sys = { path = "../obs-sys", optional = true } diff --git a/rust/obs-mcp/src/backend/control.rs b/rust/obs-mcp/src/backend/control.rs new file mode 100644 index 0000000000..2d93f3a618 --- /dev/null +++ b/rust/obs-mcp/src/backend/control.rs @@ -0,0 +1,126 @@ +//! Native implementations of typed control domains. +use super::{ObsBackend, Output, Source}; +use crate::server::ToolError; +use crate::tools::EmptyInput; +use crate::tools::control::{ + ControlBackend, MediaInput, MediaStatus, PipelineDump, StageStats, Stages, StartInput, + StatsSnapshot, SyncStats, VcamStatus, VmicStatus, +}; +use crate::tools::scenes::SceneBackend; +use crate::tools::sources::SourceBackend; + +const CAMERA: &str = "virtualcam_output"; +impl ObsBackend { + fn camera(&self, create: bool) -> Result, ToolError> { + if let Some(output) = Output::by_name(CAMERA) { + return Ok(Some(output)); + } + if !create { + return Ok(None); + } + let output = + Output::create(CAMERA, CAMERA, &serde_json::json!({})).map_err(ToolError::not_ready)?; + self.camera.replace(Some(output)); + Ok(Output::by_name(CAMERA)) + } + fn raw_stats(&self) -> Result { + let render = crate::ffi::render_stats(); + let mut stages = Stages { + render: StageStats { + live: crate::ffi::has_video(), + frames_total: Some(render.render_total_frames), + frames_dropped: Some(render.render_skipped_frames), + ..StageStats::default() + }, + ..Stages::default() + }; + if let Some(output) = self.camera(false)? { + if let Some((video, audio)) = output.device_stats() { + stages.vcam = video; + stages.vmic = audio; + } else { + stages.vcam.live = output.active(); + stages.vmic.live = output.virtual_audio().unwrap_or(false); + } + } + Ok(StatsSnapshot { stages, render, end_to_end: SyncStats { av_offset_ms: None, measured_from: "unavailable: independent capture probe required; stage bounds are libobs timestamp to completed device write".into() } }) + } + fn media_source(request: &MediaInput) -> Result { + if request.name.is_empty() { + return Err(ToolError::wrong_state("media name must not be empty")); + } + Source::by_name(&request.name) + .ok_or_else(|| ToolError::not_found(format!("no source named '{}'", request.name))) + } +} +impl ControlBackend for ObsBackend { + fn vcam_start(&self, request: StartInput) -> Result { + let output = self + .camera(true)? + .ok_or_else(|| ToolError::not_ready("Virtual Camera output unavailable"))?; + if !output.active() { + output.start().map_err(ToolError::processing)?; + } + let status = self.vcam_status(EmptyInput::default())?; + if request.wait && !status.active { + return Err(ToolError::not_ready("Virtual Camera has not become active")); + } + Ok(status) + } + fn vcam_stop(&self, _request: EmptyInput) -> Result { + if let Some(output) = self.camera(false)? + && output.active() + { + output.stop(); + } + self.vcam_status(EmptyInput::default()) + } + fn vcam_status(&self, _request: EmptyInput) -> Result { + Ok(self + .camera(false)? + .map_or_else(VcamStatus::default, |output| VcamStatus { + configured: true, + active: output.active(), + vmic_active: output.virtual_audio(), + })) + } + fn vmic_status(&self, _request: EmptyInput) -> Result { + Ok(VmicStatus { + active: self + .camera(false)? + .and_then(|output| output.virtual_audio()), + source_name: None, + }) + } + fn media_restart(&self, request: MediaInput) -> Result { + let source = Self::media_source(&request)?; + source.restart_media().map_err(ToolError::wrong_state)?; + Ok(source.media()) + } + fn media_status(&self, request: MediaInput) -> Result { + Ok(Self::media_source(&request)?.media()) + } + fn stats_get(&self, _request: EmptyInput) -> Result { + let current = self.raw_stats()?; + Ok(self.baseline.borrow().as_ref().map_or_else( + || current.clone(), + |baseline| current.clone().relative_to(baseline), + )) + } + fn stats_reset(&self, _request: EmptyInput) -> Result { + self.baseline.replace(Some(self.raw_stats()?)); + self.stats_get(EmptyInput::default()) + } + fn pipeline_dump(&self, _request: EmptyInput) -> Result { + Ok(PipelineDump { + program: self.current(), + sources: self + .sources() + .into_iter() + .map(|source| source.name) + .collect(), + vcam: self.vcam_status(EmptyInput::default())?, + stats: self.stats_get(EmptyInput::default())?, + }) + } +} diff --git a/rust/obs-mcp/src/backend/mod.rs b/rust/obs-mcp/src/backend/mod.rs index d63c0baff4..ee895fb764 100644 --- a/rust/obs-mcp/src/backend/mod.rs +++ b/rust/obs-mcp/src/backend/mod.rs @@ -55,6 +55,8 @@ pub struct ObsBackend { /// Why the host could not create the outputs, quoted in the errors that need them. output_error: Option, cpu: Option, + camera: RefCell>, + baseline: RefCell>, } impl Default for ObsBackend { @@ -78,6 +80,8 @@ impl ObsBackend { video_error: None, output_error: None, cpu: CpuUsage::start(), + camera: RefCell::new(None), + baseline: RefCell::new(None), } } @@ -131,6 +135,8 @@ impl ObsBackend { sources::register(&mut tools, &sources); outputs::register(&mut tools, &outputs); screenshot::register(&mut tools, &capture); + let control: Rc = Rc::clone(backend) as _; + crate::tools::control::register(&mut tools, &control); let mut resources = ResourceRegistry::new(); resources::scenes::register(&mut resources, &scenes, &sources); @@ -472,3 +478,5 @@ impl StatsBackend for ObsBackend { } } } + +mod control; diff --git a/rust/obs-mcp/src/ffi/control.rs b/rust/obs-mcp/src/ffi/control.rs new file mode 100644 index 0000000000..b03274b8ec --- /dev/null +++ b/rust/obs-mcp/src/ffi/control.rs @@ -0,0 +1,153 @@ +//! Private libobs media/procedure bindings; public C headers stay unchanged. +use super::{Output, Source, sys}; +use crate::tools::control::{MediaState, MediaStatus, RenderStats, StageStats}; +use obs_callback::ffi::calldata::calldata; +use std::ffi::{CStr, c_char, c_int, c_void}; + +unsafe extern "C" { + fn obs_source_get_output_flags(source: *const sys::obs_source_t) -> u32; + fn obs_source_media_restart(source: *mut sys::obs_source_t); + fn obs_source_media_get_state(source: *mut sys::obs_source_t) -> c_int; + fn obs_source_media_get_duration(source: *mut sys::obs_source_t) -> i64; + fn obs_source_media_get_time(source: *mut sys::obs_source_t) -> i64; + fn obs_get_total_frames() -> u32; + fn obs_get_average_frame_time_ns() -> u64; + fn obs_output_get_proc_handler(output: *const sys::obs_output_t) -> *mut c_void; + fn proc_handler_call(handler: *mut c_void, name: *const c_char, params: *mut calldata) -> bool; + fn calldata_get_data( + data: *const calldata, + name: *const c_char, + out: *mut c_void, + size: usize, + ) -> bool; + fn bfree(data: *mut c_void); +} +struct Params(calldata); +impl Params { + fn new() -> Self { + Self(calldata { + stack: std::ptr::null_mut(), + size: 0, + capacity: 0, + fixed: false, + }) + } + fn count(&self, name: &CStr) -> Option { + let mut value = 0_i64; + // SAFETY: live calldata, terminated key and correctly sized writable integer. + let found = unsafe { + calldata_get_data( + &raw const self.0, + name.as_ptr(), + (&raw mut value).cast(), + size_of::(), + ) + }; + found.then(|| u64::try_from(value).ok()).flatten() + } + fn boolean(&self, name: &CStr) -> Option { + let mut value = false; + // SAFETY: live calldata, terminated key and correctly sized writable C bool. + unsafe { + calldata_get_data( + &raw const self.0, + name.as_ptr(), + (&raw mut value).cast(), + size_of::(), + ) + } + .then_some(value) + } +} +impl Drop for Params { + fn drop(&mut self) { + // SAFETY: dynamic calldata storage is owned here and allocated by libobs. + unsafe { bfree(self.0.stack.cast()) }; + } +} +impl Source { + pub fn restart_media(&self) -> Result<(), String> { + // SAFETY: owns a live source reference; the flag is OBS_SOURCE_CONTROLLABLE_MEDIA. + if unsafe { obs_source_get_output_flags(self.0.as_ptr()) } & (1 << 13) == 0 { + return Err(format!( + "source '{}' is not controllable media", + self.name() + )); + } + // SAFETY: live controllable media source. + unsafe { obs_source_media_restart(self.0.as_ptr()) }; + Ok(()) + } + pub fn media(&self) -> MediaStatus { + // SAFETY: all queries retain the live source reference throughout. + let (state, duration, position) = unsafe { + ( + obs_source_media_get_state(self.0.as_ptr()), + obs_source_media_get_duration(self.0.as_ptr()), + obs_source_media_get_time(self.0.as_ptr()), + ) + }; + let state = match state { + 1 => MediaState::Playing, + 2 => MediaState::Opening, + 3 => MediaState::Buffering, + 4 => MediaState::Paused, + 5 => MediaState::Stopped, + 6 => MediaState::Ended, + 7 => MediaState::Error, + _ => MediaState::None, + }; + MediaStatus { + name: self.name(), + state, + duration_ms: (duration > 0).then_some(duration), + position_ms: (state != MediaState::None && position >= 0).then_some(position), + } + } +} +impl Output { + fn procedure(&self, name: &CStr) -> Option { + let mut params = Params::new(); + // SAFETY: the output reference pins its procedure handler and callback data; + // params owns the returned calldata until all values have been copied. + let found = unsafe { + let handler = obs_output_get_proc_handler(self.0.as_ptr()); + !handler.is_null() && proc_handler_call(handler, name.as_ptr(), &raw mut params.0) + }; + found.then_some(params) + } + pub fn virtual_audio(&self) -> Option { + self.procedure(c"virtualcam_audio")?.boolean(c"active") + } + pub fn device_stats(&self) -> Option<(StageStats, StageStats)> { + let data = self.procedure(c"virtualcam_stats")?; + let video = StageStats { + live: self.active(), + latency_min_ns: data.count(c"vcam_min_ns"), + latency_max_ns: data.count(c"vcam_max_ns"), + frames_total: data.count(c"vcam_frames"), + frames_dropped: data.count(c"vcam_dropped"), + xruns: None, + }; + let audio = StageStats { + live: self.virtual_audio().unwrap_or(false), + latency_min_ns: data.count(c"vmic_min_ns"), + latency_max_ns: data.count(c"vmic_max_ns"), + frames_total: data.count(c"vmic_frames"), + frames_dropped: data.count(c"vmic_dropped"), + xruns: data.count(c"vmic_xruns"), + }; + Some((video, audio)) + } +} +pub fn render_stats() -> RenderStats { + // SAFETY: plain libobs statistics queries, valid even without configured video. + unsafe { + RenderStats { + active_fps: sys::obs_get_active_fps(), + average_frame_time_ns: obs_get_average_frame_time_ns(), + render_total_frames: u64::from(obs_get_total_frames()), + render_skipped_frames: u64::from(sys::obs_get_lagged_frames()), + } + } +} diff --git a/rust/obs-mcp/src/ffi/mod.rs b/rust/obs-mcp/src/ffi/mod.rs index ab43faeb28..69b5253b1e 100644 --- a/rust/obs-mcp/src/ffi/mod.rs +++ b/rust/obs-mcp/src/ffi/mod.rs @@ -677,3 +677,6 @@ pub fn log_warning(text: &str) { // consumes exactly the one argument passed. unsafe { blog(LOG_WARNING, c"obs-mcp: %s".as_ptr(), text.as_ptr()) }; } + +mod control; +pub use control::render_stats; diff --git a/rust/obs-mcp/src/tools/control.rs b/rust/obs-mcp/src/tools/control.rs index 05f4fa5a44..d64bdc6720 100644 --- a/rust/obs-mcp/src/tools/control.rs +++ b/rust/obs-mcp/src/tools/control.rs @@ -1,9 +1,9 @@ //! Device, media and measured pipeline control (#4446). -use std::rc::Rc; +use super::EmptyInput; +use crate::server::{ToolError, ToolRegistry}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -use crate::server::{ToolError, ToolRegistry}; -use super::EmptyInput; +use std::rc::Rc; /// Bounded start options, extended by the wait domain. #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] @@ -181,4 +181,182 @@ pub trait ControlBackend { } /// Difference from a baseline; a recreated counter begins a new generation. #[must_use] -pub fn counter_delta(current: u64, baseline: u64) -> u64 { todo!("counter baseline") } +pub fn counter_delta(current: u64, baseline: u64) -> u64 { + if current >= baseline { + current - baseline + } else { + current + } +} + +typed_tool!( + VcamStart, + "vcam_start", + ControlBackend, + StartInput, + VcamStatus, + IDEMPOTENT, + "vcam start: control and inspect OBS directly.", + |backend, input| { backend.vcam_start(input) } +); + +typed_tool!( + VcamStop, + "vcam_stop", + ControlBackend, + EmptyInput, + VcamStatus, + IDEMPOTENT, + "vcam stop: control and inspect OBS directly.", + |backend, input| { backend.vcam_stop(input) } +); + +typed_tool!( + VcamGet, + "vcam_status", + ControlBackend, + EmptyInput, + VcamStatus, + READ_ONLY, + "vcam status: control and inspect OBS directly.", + |backend, input| { backend.vcam_status(input) } +); + +typed_tool!( + VmicGet, + "vmic_status", + ControlBackend, + EmptyInput, + VmicStatus, + READ_ONLY, + "vmic status: control and inspect OBS directly.", + |backend, input| { backend.vmic_status(input) } +); + +typed_tool!( + MediaRestart, + "media_restart", + ControlBackend, + MediaInput, + MediaStatus, + MUTATING, + "media restart: control and inspect OBS directly.", + |backend, input| { backend.media_restart(input) } +); + +typed_tool!( + MediaGet, + "media_status", + ControlBackend, + MediaInput, + MediaStatus, + READ_ONLY, + "media status: control and inspect OBS directly.", + |backend, input| { backend.media_status(input) } +); + +typed_tool!( + StatsGet, + "stats_get", + ControlBackend, + EmptyInput, + StatsSnapshot, + READ_ONLY, + "stats get: control and inspect OBS directly.", + |backend, input| { backend.stats_get(input) } +); + +typed_tool!( + StatsReset, + "stats_reset", + ControlBackend, + EmptyInput, + StatsSnapshot, + MUTATING, + "stats reset: control and inspect OBS directly.", + |backend, input| { backend.stats_reset(input) } +); + +typed_tool!( + PipelineGet, + "pipeline_dump", + ControlBackend, + EmptyInput, + PipelineDump, + READ_ONLY, + "pipeline dump: control and inspect OBS directly.", + |backend, input| { backend.pipeline_dump(input) } +); + +/// Registers device, media and measurement tools. +pub fn register(registry: &mut ToolRegistry, backend: &Rc) { + registry.register(Box::new(VcamStart { + backend: Rc::clone(backend), + })); + registry.register(Box::new(VcamStop { + backend: Rc::clone(backend), + })); + registry.register(Box::new(VcamGet { + backend: Rc::clone(backend), + })); + registry.register(Box::new(VmicGet { + backend: Rc::clone(backend), + })); + registry.register(Box::new(MediaRestart { + backend: Rc::clone(backend), + })); + registry.register(Box::new(MediaGet { + backend: Rc::clone(backend), + })); + registry.register(Box::new(StatsGet { + backend: Rc::clone(backend), + })); + registry.register(Box::new(StatsReset { + backend: Rc::clone(backend), + })); + registry.register(Box::new(PipelineGet { + backend: Rc::clone(backend), + })); +} + +/// Generated tool contracts. +#[must_use] +pub fn schemas() -> Vec { + vec![ + crate::server::tool_schema::(), + crate::server::tool_schema::(), + crate::server::tool_schema::(), + crate::server::tool_schema::(), + crate::server::tool_schema::(), + crate::server::tool_schema::(), + crate::server::tool_schema::(), + crate::server::tool_schema::(), + crate::server::tool_schema::(), + ] +} + +impl StatsSnapshot { + /// Subtract counter baselines while leaving latency gauges unchanged. + #[must_use] + pub fn relative_to(mut self, baseline: &Self) -> Self { + fn stage(now: &mut StageStats, old: &StageStats) { + let delta = + |n: Option, b: Option| n.map(|v| counter_delta(v, b.unwrap_or(0))); + now.frames_total = delta(now.frames_total, old.frames_total); + now.frames_dropped = delta(now.frames_dropped, old.frames_dropped); + now.xruns = delta(now.xruns, old.xruns); + } + stage(&mut self.stages.render, &baseline.stages.render); + stage(&mut self.stages.vcam, &baseline.stages.vcam); + stage(&mut self.stages.vmic, &baseline.stages.vmic); + self.render.render_total_frames = counter_delta( + self.render.render_total_frames, + baseline.render.render_total_frames, + ); + self.render.render_skipped_frames = counter_delta( + self.render.render_skipped_frames, + baseline.render.render_skipped_frames, + ); + self + } +} diff --git a/rust/obs-mcp/src/tools/mod.rs b/rust/obs-mcp/src/tools/mod.rs index ac39f2c144..1051b39105 100644 --- a/rust/obs-mcp/src/tools/mod.rs +++ b/rust/obs-mcp/src/tools/mod.rs @@ -40,6 +40,7 @@ pub fn schema_snapshot() -> serde_json::Value { tools.extend(sources::schemas()); tools.extend(outputs::schemas()); tools.extend(screenshot::schemas()); + tools.extend(control::schemas()); tools.sort_by(|a, b| a["name"].as_str().cmp(&b["name"].as_str())); serde_json::json!({"tools": tools, "toolError": schemars::schema_for!(crate::server::ToolError)}) } diff --git a/rust/obs-mcp/tests/mcp/control.rs b/rust/obs-mcp/tests/mcp/control.rs index a579e88f59..0b628317a8 100644 --- a/rust/obs-mcp/tests/mcp/control.rs +++ b/rust/obs-mcp/tests/mcp/control.rs @@ -6,3 +6,114 @@ fn counters_are_relative_to_baseline_and_survive_recreation() { assert_eq!(counter_delta(5, 5), 0); assert_eq!(counter_delta(3, 20), 3); } +use obs_mcp::server::{Server, ToolError, ToolRegistry}; +use obs_mcp::tools::{ + EmptyInput, + control::{ + ControlBackend, MediaInput, MediaState, MediaStatus, PipelineDump, StartInput, + StatsSnapshot, VcamStatus, VmicStatus, register, + }, +}; +use serde_json::{Value, json}; +use std::cell::Cell; +use std::rc::Rc; +#[derive(Default)] +struct Fake { + active: Cell, +} +impl ControlBackend for Fake { + fn vcam_start(&self, _: StartInput) -> Result { + self.active.set(true); + self.vcam_status(EmptyInput {}) + } + fn vcam_stop(&self, _: EmptyInput) -> Result { + self.active.set(false); + self.vcam_status(EmptyInput {}) + } + fn vcam_status(&self, _: EmptyInput) -> Result { + Ok(VcamStatus { + configured: true, + active: self.active.get(), + vmic_active: Some(self.active.get()), + }) + } + fn vmic_status(&self, _: EmptyInput) -> Result { + Ok(VmicStatus { + active: Some(self.active.get()), + source_name: None, + }) + } + fn media_restart(&self, request: MediaInput) -> Result { + self.media_status(request) + } + fn media_status(&self, request: MediaInput) -> Result { + if request.name != "clip" { + return Err(ToolError::not_found("missing media")); + } + Ok(MediaStatus { + name: request.name, + state: MediaState::Playing, + duration_ms: Some(1000), + position_ms: Some(0), + }) + } + fn stats_get(&self, _: EmptyInput) -> Result { + Ok(StatsSnapshot::default()) + } + fn stats_reset(&self, _: EmptyInput) -> Result { + self.stats_get(EmptyInput {}) + } + fn pipeline_dump(&self, _: EmptyInput) -> Result { + Ok(PipelineDump::default()) + } +} +fn rpc(server: &mut Server, name: &str, arguments: Value) -> Value { + let request = json!({"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":name,"arguments":arguments}}).to_string()+"\n"; + let mut output = Vec::new(); + server.serve(request.as_bytes(), &mut output).unwrap(); + serde_json::from_slice(&output).unwrap() +} +#[test] +fn device_media_tools_have_typed_results_and_strict_arguments() { + let mut tools = ToolRegistry::new(); + let backend: Rc = Rc::new(Fake::default()); + register(&mut tools, &backend); + assert_eq!(tools.list()["tools"].as_array().unwrap().len(), 9); + let mut server = Server::with_tools(tools); + for name in ["vcam_start", "vcam_start", "vcam_stop", "vcam_stop"] { + let response = rpc(&mut server, name, json!({})); + assert_eq!(response["result"]["isError"], false); + assert_eq!( + response["result"]["structuredContent"]["active"], + name.ends_with("start") + ); + } + assert_eq!( + rpc(&mut server, "media_restart", json!({"name":"clip"}))["result"]["structuredContent"]["state"], + "playing" + ); + assert_eq!( + rpc(&mut server, "media_status", json!({"name":"missing"}))["result"]["structuredContent"] + ["code"], + 600 + ); + assert_eq!( + rpc(&mut server, "vcam_start", json!({"typo":true}))["error"]["code"], + -32602 + ); + let stats = rpc(&mut server, "stats_get", json!({})); + assert!(stats["result"]["structuredContent"]["end_to_end"]["av_offset_ms"].is_null()); + assert!(stats["result"]["structuredContent"]["stages"]["vmic"]["xruns"].is_null()); +} +#[test] +fn reset_changes_counters_but_preserves_gauges_and_unknown_values() { + let mut now = StatsSnapshot::default(); + now.stages.vcam.frames_total = Some(30); + now.stages.vcam.latency_max_ns = Some(800); + let mut baseline = StatsSnapshot::default(); + baseline.stages.vcam.frames_total = Some(10); + let result = now.relative_to(&baseline); + assert_eq!(result.stages.vcam.frames_total, Some(20)); + assert_eq!(result.stages.vcam.latency_max_ns, Some(800)); + assert_eq!(result.stages.vmic.xruns, None); +} From 55af673f7b8c8a46e3310f0fc533d5d087179af4 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 14:53:23 -0800 Subject: [PATCH 08/39] fix(mcp): guard camera readiness and track metric generations (#4446) --- docs/rust-port/control-api.schema.json | 8 +-- plugins/linux-v4l2/v4l2-output.c.h | 21 +++++- rust/obs-mcp/src/backend/control.rs | 27 ++++++-- rust/obs-mcp/src/backend/mod.rs | 2 +- rust/obs-mcp/src/ffi/control.rs | 5 ++ rust/obs-mcp/src/tools/control.rs | 89 +++++++++++++++++++++++++- rust/obs-mcp/tests/libobs_backend.rs | 2 + rust/obs-mcp/tests/mcp/control.rs | 23 +++++++ 8 files changed, 165 insertions(+), 12 deletions(-) diff --git a/docs/rust-port/control-api.schema.json b/docs/rust-port/control-api.schema.json index 9ff16237ed..2e6ab44ae5 100644 --- a/docs/rust-port/control-api.schema.json +++ b/docs/rust-port/control-api.schema.json @@ -3,7 +3,7 @@ "tools": [ {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"A media source selection.","properties":{"name":{"description":"Name of an existing media source.","type":"string"}},"required":["name"],"title":"MediaInput","type":"object"},"name":"media_restart","outputSchema":{"$defs":{"MediaState":{"description":"libobs media state.","oneOf":[{"const":"none","description":"Not a controllable media source.","type":"string"},{"const":"playing","description":"Playing.","type":"string"},{"const":"opening","description":"Opening.","type":"string"},{"const":"buffering","description":"Buffering.","type":"string"},{"const":"paused","description":"Paused.","type":"string"},{"const":"stopped","description":"Stopped.","type":"string"},{"const":"ended","description":"Playback reached the end.","type":"string"},{"const":"error","description":"Playback failed.","type":"string"}]}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Media playback snapshot, in milliseconds.","properties":{"duration_ms":{"description":"Total duration, if known.","format":"int64","type":["integer","null"]},"name":{"description":"Source name.","type":"string"},"position_ms":{"description":"Playback position, if known.","format":"int64","type":["integer","null"]},"state":{"$ref":"#/$defs/MediaState","description":"Current media state."}},"required":["name","state"],"title":"MediaStatus","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"A media source selection.","properties":{"name":{"description":"Name of an existing media source.","type":"string"}},"required":["name"],"title":"MediaInput","type":"object"},"name":"media_status","outputSchema":{"$defs":{"MediaState":{"description":"libobs media state.","oneOf":[{"const":"none","description":"Not a controllable media source.","type":"string"},{"const":"playing","description":"Playing.","type":"string"},{"const":"opening","description":"Opening.","type":"string"},{"const":"buffering","description":"Buffering.","type":"string"},{"const":"paused","description":"Paused.","type":"string"},{"const":"stopped","description":"Stopped.","type":"string"},{"const":"ended","description":"Playback reached the end.","type":"string"},{"const":"error","description":"Playback failed.","type":"string"}]}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Media playback snapshot, in milliseconds.","properties":{"duration_ms":{"description":"Total duration, if known.","format":"int64","type":["integer","null"]},"name":{"description":"Source name.","type":"string"},"position_ms":{"description":"Playback position, if known.","format":"int64","type":["integer","null"]},"state":{"$ref":"#/$defs/MediaState","description":"Current media state."}},"required":["name","state"],"title":"MediaStatus","type":"object"}}, - {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"pipeline_dump","outputSchema":{"$defs":{"RenderStats":{"description":"GetStats-style render counters.","properties":{"active_fps":{"description":"Actual render FPS.","format":"double","type":"number"},"average_frame_time_ns":{"description":"Average render duration, not end-to-end latency.","format":"uint64","minimum":0,"type":"integer"},"render_skipped_frames":{"description":"Frames lagged since baseline.","format":"uint64","minimum":0,"type":"integer"},"render_total_frames":{"description":"Frames rendered since baseline.","format":"uint64","minimum":0,"type":"integer"}},"required":["active_fps","average_frame_time_ns","render_total_frames","render_skipped_frames"],"type":"object"},"StageStats":{"description":"One live pipeline stage; null values are unmeasured, never synthetic zeroes.","properties":{"frames_dropped":{"description":"Dropped frames since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"frames_total":{"description":"Frames handled since the counter baseline.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_max_ns":{"description":"Observed maximum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_min_ns":{"description":"Observed minimum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"live":{"description":"Currently running.","type":"boolean"},"xruns":{"description":"Underruns/overruns since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]}},"required":["live"],"type":"object"},"Stages":{"description":"Render and device stages.","properties":{"render":{"$ref":"#/$defs/StageStats","description":"OBS render stage."},"vcam":{"$ref":"#/$defs/StageStats","description":"Virtual Camera write stage."},"vmic":{"$ref":"#/$defs/StageStats","description":"Virtual microphone stage."}},"required":["render","vcam","vmic"],"type":"object"},"StatsSnapshot":{"description":"Typed pipeline statistics.","properties":{"end_to_end":{"$ref":"#/$defs/SyncStats","description":"End-to-end sync, with explicit provenance."},"render":{"$ref":"#/$defs/RenderStats","description":"Render counters."},"stages":{"$ref":"#/$defs/Stages","description":"Per-stage measured counters and bounds."}},"required":["stages","end_to_end","render"],"type":"object"},"SyncStats":{"description":"End-to-end measurement provenance.","properties":{"av_offset_ms":{"description":"Measured audio minus video offset; null until independently measured.","format":"double","type":["number","null"]},"measured_from":{"description":"Measurement source; queue estimates are not end-to-end measurements.","type":"string"}},"required":["measured_from"],"type":"object"},"VcamStatus":{"description":"Virtual Camera and its paired audio source.","properties":{"active":{"description":"Video output is active.","type":"boolean"},"configured":{"description":"Whether the registered output exists.","type":"boolean"},"vmic_active":{"description":"Paired virtual microphone is active, when the plugin supports the query.","type":["boolean","null"]}},"required":["configured","active"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Graph snapshot useful for diagnosing missing sources and outputs.","properties":{"program":{"description":"Program source name.","type":["string","null"]},"sources":{"description":"Source names in stable order.","items":{"type":"string"},"type":"array"},"stats":{"$ref":"#/$defs/StatsSnapshot","description":"Current pipeline measurements."},"vcam":{"$ref":"#/$defs/VcamStatus","description":"Virtual output state."}},"required":["sources","vcam","stats"],"title":"PipelineDump","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"pipeline_dump","outputSchema":{"$defs":{"RenderStats":{"description":"GetStats-style render counters.","properties":{"active_fps":{"description":"Actual render FPS.","format":"double","type":"number"},"average_frame_time_ns":{"description":"Average render duration, not end-to-end latency.","format":"uint64","minimum":0,"type":"integer"},"render_skipped_frames":{"description":"Frames lagged since baseline.","format":"uint64","minimum":0,"type":"integer"},"render_total_frames":{"description":"Frames rendered since baseline.","format":"uint64","minimum":0,"type":"integer"}},"required":["active_fps","average_frame_time_ns","render_total_frames","render_skipped_frames"],"type":"object"},"StageStats":{"description":"One live pipeline stage; null values are unmeasured, never synthetic zeroes.","properties":{"frames_dropped":{"description":"Dropped frames since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"frames_total":{"description":"Frames handled since the counter baseline.","format":"uint64","minimum":0,"type":["integer","null"]},"generation":{"description":"Counter generation, when the provider exposes one.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_max_ns":{"description":"Observed maximum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_min_ns":{"description":"Observed minimum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"live":{"description":"Currently running.","type":"boolean"},"xruns":{"description":"Underruns/overruns since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]}},"required":["live"],"type":"object"},"Stages":{"description":"Render and device stages.","properties":{"render":{"$ref":"#/$defs/StageStats","description":"OBS render stage."},"vcam":{"$ref":"#/$defs/StageStats","description":"Virtual Camera write stage."},"vmic":{"$ref":"#/$defs/StageStats","description":"Virtual microphone stage."}},"required":["render","vcam","vmic"],"type":"object"},"StatsSnapshot":{"description":"Typed pipeline statistics.","properties":{"end_to_end":{"$ref":"#/$defs/SyncStats","description":"End-to-end sync, with explicit provenance."},"render":{"$ref":"#/$defs/RenderStats","description":"Render counters."},"stages":{"$ref":"#/$defs/Stages","description":"Per-stage measured counters and bounds."}},"required":["stages","end_to_end","render"],"type":"object"},"SyncStats":{"description":"End-to-end measurement provenance.","properties":{"av_offset_ms":{"description":"Measured audio minus video offset; null until independently measured.","format":"double","type":["number","null"]},"measured_from":{"description":"Measurement source; queue estimates are not end-to-end measurements.","type":"string"}},"required":["measured_from"],"type":"object"},"VcamStatus":{"description":"Virtual Camera and its paired audio source.","properties":{"active":{"description":"Video output is active.","type":"boolean"},"configured":{"description":"Whether the registered output exists.","type":"boolean"},"vmic_active":{"description":"Paired virtual microphone is active, when the plugin supports the query.","type":["boolean","null"]}},"required":["configured","active"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Graph snapshot useful for diagnosing missing sources and outputs.","properties":{"program":{"description":"Program source name.","type":["string","null"]},"sources":{"description":"Source names in stable order.","items":{"type":"string"},"type":"array"},"stats":{"$ref":"#/$defs/StatsSnapshot","description":"Current pipeline measurements."},"vcam":{"$ref":"#/$defs/VcamStatus","description":"Virtual output state."}},"required":["sources","vcam","stats"],"title":"PipelineDump","type":"object"}}, {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"record_start","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"record_status","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"The state of an output as reported by [`OutputBackend::status`].","properties":{"active":{"description":"Whether the output is running.","type":"boolean"},"bytes":{"description":"Bytes written or sent so far, where known.","format":"uint64","minimum":0,"type":["integer","null"]},"duration_ms":{"description":"Milliseconds since the output started, where known.","format":"uint64","minimum":0,"type":["integer","null"]}},"required":["active"],"title":"OutputStatus","type":"object"}}, {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"record_stop","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}}, @@ -20,12 +20,12 @@ {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$defs":{"Pair":{"additionalProperties":false,"description":"Pixel position or scale factors.","properties":{"x":{"description":"Horizontal component.","format":"double","type":"number"},"y":{"description":"Vertical component.","format":"double","type":"number"}},"required":["x","y"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Source creation, optionally placing it in a scene.","properties":{"kind":{"description":"Source kind id.","type":"string"},"name":{"description":"Unique name.","type":"string"},"position":{"anyOf":[{"$ref":"#/$defs/Pair"},{"type":"null"}],"description":"Initial position (requires scene)."},"scene":{"description":"Scene receiving the source.","type":["string","null"]},"settings":{"additionalProperties":true,"description":"Kind-specific settings.","type":"object"}},"required":["kind","name","settings"],"title":"CreateInput","type":"object"},"name":"source_create","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Created source.","properties":{"item":{"description":"Created item id.","format":"int64","type":["integer","null"]},"kind":{"description":"Source kind.","type":"string"},"name":{"description":"Source name.","type":"string"},"scene":{"description":"Scene receiving the new item.","type":["string","null"]}},"required":["name","kind"],"title":"CreateOutput","type":"object"}}, {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Settings update.","properties":{"name":{"description":"Source name.","type":"string"},"settings":{"additionalProperties":true,"description":"Kind-specific settings to merge.","type":"object"}},"required":["name","settings"],"title":"SettingsInput","type":"object"},"name":"source_set_settings","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Updated source name.","properties":{"name":{"description":"Source name.","type":"string"}},"required":["name"],"title":"NameOutput","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"sources_list","outputSchema":{"$defs":{"SourceInfo":{"description":"A source as listed by [`SourceBackend::sources`].","properties":{"kind":{"description":"The source kind id, such as `color_source`.","type":"string"},"name":{"description":"The source's unique name.","type":"string"}},"required":["name","kind"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Source listing.","properties":{"sources":{"description":"Sources in stable order.","items":{"$ref":"#/$defs/SourceInfo"},"type":"array"}},"required":["sources"],"title":"SourcesOutput","type":"object"}}, - {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stats_get","outputSchema":{"$defs":{"RenderStats":{"description":"GetStats-style render counters.","properties":{"active_fps":{"description":"Actual render FPS.","format":"double","type":"number"},"average_frame_time_ns":{"description":"Average render duration, not end-to-end latency.","format":"uint64","minimum":0,"type":"integer"},"render_skipped_frames":{"description":"Frames lagged since baseline.","format":"uint64","minimum":0,"type":"integer"},"render_total_frames":{"description":"Frames rendered since baseline.","format":"uint64","minimum":0,"type":"integer"}},"required":["active_fps","average_frame_time_ns","render_total_frames","render_skipped_frames"],"type":"object"},"StageStats":{"description":"One live pipeline stage; null values are unmeasured, never synthetic zeroes.","properties":{"frames_dropped":{"description":"Dropped frames since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"frames_total":{"description":"Frames handled since the counter baseline.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_max_ns":{"description":"Observed maximum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_min_ns":{"description":"Observed minimum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"live":{"description":"Currently running.","type":"boolean"},"xruns":{"description":"Underruns/overruns since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]}},"required":["live"],"type":"object"},"Stages":{"description":"Render and device stages.","properties":{"render":{"$ref":"#/$defs/StageStats","description":"OBS render stage."},"vcam":{"$ref":"#/$defs/StageStats","description":"Virtual Camera write stage."},"vmic":{"$ref":"#/$defs/StageStats","description":"Virtual microphone stage."}},"required":["render","vcam","vmic"],"type":"object"},"SyncStats":{"description":"End-to-end measurement provenance.","properties":{"av_offset_ms":{"description":"Measured audio minus video offset; null until independently measured.","format":"double","type":["number","null"]},"measured_from":{"description":"Measurement source; queue estimates are not end-to-end measurements.","type":"string"}},"required":["measured_from"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Typed pipeline statistics.","properties":{"end_to_end":{"$ref":"#/$defs/SyncStats","description":"End-to-end sync, with explicit provenance."},"render":{"$ref":"#/$defs/RenderStats","description":"Render counters."},"stages":{"$ref":"#/$defs/Stages","description":"Per-stage measured counters and bounds."}},"required":["stages","end_to_end","render"],"title":"StatsSnapshot","type":"object"}}, - {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stats_reset","outputSchema":{"$defs":{"RenderStats":{"description":"GetStats-style render counters.","properties":{"active_fps":{"description":"Actual render FPS.","format":"double","type":"number"},"average_frame_time_ns":{"description":"Average render duration, not end-to-end latency.","format":"uint64","minimum":0,"type":"integer"},"render_skipped_frames":{"description":"Frames lagged since baseline.","format":"uint64","minimum":0,"type":"integer"},"render_total_frames":{"description":"Frames rendered since baseline.","format":"uint64","minimum":0,"type":"integer"}},"required":["active_fps","average_frame_time_ns","render_total_frames","render_skipped_frames"],"type":"object"},"StageStats":{"description":"One live pipeline stage; null values are unmeasured, never synthetic zeroes.","properties":{"frames_dropped":{"description":"Dropped frames since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"frames_total":{"description":"Frames handled since the counter baseline.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_max_ns":{"description":"Observed maximum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_min_ns":{"description":"Observed minimum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"live":{"description":"Currently running.","type":"boolean"},"xruns":{"description":"Underruns/overruns since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]}},"required":["live"],"type":"object"},"Stages":{"description":"Render and device stages.","properties":{"render":{"$ref":"#/$defs/StageStats","description":"OBS render stage."},"vcam":{"$ref":"#/$defs/StageStats","description":"Virtual Camera write stage."},"vmic":{"$ref":"#/$defs/StageStats","description":"Virtual microphone stage."}},"required":["render","vcam","vmic"],"type":"object"},"SyncStats":{"description":"End-to-end measurement provenance.","properties":{"av_offset_ms":{"description":"Measured audio minus video offset; null until independently measured.","format":"double","type":["number","null"]},"measured_from":{"description":"Measurement source; queue estimates are not end-to-end measurements.","type":"string"}},"required":["measured_from"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Typed pipeline statistics.","properties":{"end_to_end":{"$ref":"#/$defs/SyncStats","description":"End-to-end sync, with explicit provenance."},"render":{"$ref":"#/$defs/RenderStats","description":"Render counters."},"stages":{"$ref":"#/$defs/Stages","description":"Per-stage measured counters and bounds."}},"required":["stages","end_to_end","render"],"title":"StatsSnapshot","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stats_get","outputSchema":{"$defs":{"RenderStats":{"description":"GetStats-style render counters.","properties":{"active_fps":{"description":"Actual render FPS.","format":"double","type":"number"},"average_frame_time_ns":{"description":"Average render duration, not end-to-end latency.","format":"uint64","minimum":0,"type":"integer"},"render_skipped_frames":{"description":"Frames lagged since baseline.","format":"uint64","minimum":0,"type":"integer"},"render_total_frames":{"description":"Frames rendered since baseline.","format":"uint64","minimum":0,"type":"integer"}},"required":["active_fps","average_frame_time_ns","render_total_frames","render_skipped_frames"],"type":"object"},"StageStats":{"description":"One live pipeline stage; null values are unmeasured, never synthetic zeroes.","properties":{"frames_dropped":{"description":"Dropped frames since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"frames_total":{"description":"Frames handled since the counter baseline.","format":"uint64","minimum":0,"type":["integer","null"]},"generation":{"description":"Counter generation, when the provider exposes one.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_max_ns":{"description":"Observed maximum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_min_ns":{"description":"Observed minimum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"live":{"description":"Currently running.","type":"boolean"},"xruns":{"description":"Underruns/overruns since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]}},"required":["live"],"type":"object"},"Stages":{"description":"Render and device stages.","properties":{"render":{"$ref":"#/$defs/StageStats","description":"OBS render stage."},"vcam":{"$ref":"#/$defs/StageStats","description":"Virtual Camera write stage."},"vmic":{"$ref":"#/$defs/StageStats","description":"Virtual microphone stage."}},"required":["render","vcam","vmic"],"type":"object"},"SyncStats":{"description":"End-to-end measurement provenance.","properties":{"av_offset_ms":{"description":"Measured audio minus video offset; null until independently measured.","format":"double","type":["number","null"]},"measured_from":{"description":"Measurement source; queue estimates are not end-to-end measurements.","type":"string"}},"required":["measured_from"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Typed pipeline statistics.","properties":{"end_to_end":{"$ref":"#/$defs/SyncStats","description":"End-to-end sync, with explicit provenance."},"render":{"$ref":"#/$defs/RenderStats","description":"Render counters."},"stages":{"$ref":"#/$defs/Stages","description":"Per-stage measured counters and bounds."}},"required":["stages","end_to_end","render"],"title":"StatsSnapshot","type":"object"}}, + {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stats_reset","outputSchema":{"$defs":{"RenderStats":{"description":"GetStats-style render counters.","properties":{"active_fps":{"description":"Actual render FPS.","format":"double","type":"number"},"average_frame_time_ns":{"description":"Average render duration, not end-to-end latency.","format":"uint64","minimum":0,"type":"integer"},"render_skipped_frames":{"description":"Frames lagged since baseline.","format":"uint64","minimum":0,"type":"integer"},"render_total_frames":{"description":"Frames rendered since baseline.","format":"uint64","minimum":0,"type":"integer"}},"required":["active_fps","average_frame_time_ns","render_total_frames","render_skipped_frames"],"type":"object"},"StageStats":{"description":"One live pipeline stage; null values are unmeasured, never synthetic zeroes.","properties":{"frames_dropped":{"description":"Dropped frames since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"frames_total":{"description":"Frames handled since the counter baseline.","format":"uint64","minimum":0,"type":["integer","null"]},"generation":{"description":"Counter generation, when the provider exposes one.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_max_ns":{"description":"Observed maximum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_min_ns":{"description":"Observed minimum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"live":{"description":"Currently running.","type":"boolean"},"xruns":{"description":"Underruns/overruns since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]}},"required":["live"],"type":"object"},"Stages":{"description":"Render and device stages.","properties":{"render":{"$ref":"#/$defs/StageStats","description":"OBS render stage."},"vcam":{"$ref":"#/$defs/StageStats","description":"Virtual Camera write stage."},"vmic":{"$ref":"#/$defs/StageStats","description":"Virtual microphone stage."}},"required":["render","vcam","vmic"],"type":"object"},"SyncStats":{"description":"End-to-end measurement provenance.","properties":{"av_offset_ms":{"description":"Measured audio minus video offset; null until independently measured.","format":"double","type":["number","null"]},"measured_from":{"description":"Measurement source; queue estimates are not end-to-end measurements.","type":"string"}},"required":["measured_from"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Typed pipeline statistics.","properties":{"end_to_end":{"$ref":"#/$defs/SyncStats","description":"End-to-end sync, with explicit provenance."},"render":{"$ref":"#/$defs/RenderStats","description":"Render counters."},"stages":{"$ref":"#/$defs/Stages","description":"Per-stage measured counters and bounds."}},"required":["stages","end_to_end","render"],"title":"StatsSnapshot","type":"object"}}, {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stream_start","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stream_status","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"The state of an output as reported by [`OutputBackend::status`].","properties":{"active":{"description":"Whether the output is running.","type":"boolean"},"bytes":{"description":"Bytes written or sent so far, where known.","format":"uint64","minimum":0,"type":["integer","null"]},"duration_ms":{"description":"Milliseconds since the output started, where known.","format":"uint64","minimum":0,"type":["integer","null"]}},"required":["active"],"title":"OutputStatus","type":"object"}}, {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stream_stop","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}}, - {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Bounded start options, extended by the wait domain.","properties":{"wait":{"default":false,"description":"Wait until the output reports active.","type":"boolean"}},"title":"StartInput","type":"object"},"name":"vcam_start","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Virtual Camera and its paired audio source.","properties":{"active":{"description":"Video output is active.","type":"boolean"},"configured":{"description":"Whether the registered output exists.","type":"boolean"},"vmic_active":{"description":"Paired virtual microphone is active, when the plugin supports the query.","type":["boolean","null"]}},"required":["configured","active"],"title":"VcamStatus","type":"object"}}, + {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Bounded start options, extended by the wait domain.","properties":{"audio_enabled":{"default":true,"description":"Enable the paired microphone before a stopped output starts.","type":"boolean"},"audio_track":{"default":1,"description":"One-based OBS audio mix (1 through 6).","format":"uint32","minimum":0,"type":"integer"},"wait":{"default":false,"description":"Wait until the output reports active.","type":"boolean"}},"title":"StartInput","type":"object"},"name":"vcam_start","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Virtual Camera and its paired audio source.","properties":{"active":{"description":"Video output is active.","type":"boolean"},"configured":{"description":"Whether the registered output exists.","type":"boolean"},"vmic_active":{"description":"Paired virtual microphone is active, when the plugin supports the query.","type":["boolean","null"]}},"required":["configured","active"],"title":"VcamStatus","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"vcam_status","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Virtual Camera and its paired audio source.","properties":{"active":{"description":"Video output is active.","type":"boolean"},"configured":{"description":"Whether the registered output exists.","type":"boolean"},"vmic_active":{"description":"Paired virtual microphone is active, when the plugin supports the query.","type":["boolean","null"]}},"required":["configured","active"],"title":"VcamStatus","type":"object"}}, {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"vcam_stop","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Virtual Camera and its paired audio source.","properties":{"active":{"description":"Video output is active.","type":"boolean"},"configured":{"description":"Whether the registered output exists.","type":"boolean"},"vmic_active":{"description":"Paired virtual microphone is active, when the plugin supports the query.","type":["boolean","null"]}},"required":["configured","active"],"title":"VcamStatus","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"vmic_status","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Virtual microphone state.","properties":{"active":{"description":"Active according to virtualcam_audio; null means unsupported.","type":["boolean","null"]},"source_name":{"description":"Runtime source name, when known.","type":["string","null"]}},"title":"VmicStatus","type":"object"}} diff --git a/plugins/linux-v4l2/v4l2-output.c.h b/plugins/linux-v4l2/v4l2-output.c.h index 1c0fa75ccf..b52e1c4172 100644 --- a/plugins/linux-v4l2/v4l2-output.c.h +++ b/plugins/linux-v4l2/v4l2-output.c.h @@ -50,6 +50,7 @@ struct virtualcam_data { char mic_lock_path[256]; int mic_lock; /* Lifetime counters; all accesses hold sync.mutex. Never consumed by logging. */ + uint64_t stats_generation; uint64_t stats_video_frames, stats_video_dropped, stats_video_measured; uint64_t stats_video_min_ns, stats_video_max_ns; uint64_t stats_audio_frames, stats_audio_dropped, stats_audio_measured; @@ -953,6 +954,7 @@ static void virtualcam_stats_proc(void *data, calldata_t *cd) { struct virtualcam_data *vcam = data; pthread_mutex_lock(&vcam->sync.mutex); + calldata_set_int(cd, "generation", (long long)vcam->stats_generation); calldata_set_int(cd, "vcam_frames", (long long)vcam->stats_video_frames); calldata_set_int(cd, "vcam_dropped", (long long)vcam->stats_video_dropped); calldata_set_int(cd, "vmic_frames", (long long)vcam->stats_audio_frames); @@ -968,10 +970,24 @@ static void virtualcam_stats_proc(void *data, calldata_t *cd) pthread_mutex_unlock(&vcam->sync.mutex); } +static void virtualcam_stats_reset_proc(void *data, calldata_t *cd) +{ + struct virtualcam_data *vcam = data; + pthread_mutex_lock(&vcam->sync.mutex); + vcam->stats_generation = os_gettime_ns(); + vcam->stats_video_frames = vcam->stats_video_dropped = vcam->stats_video_measured = 0; + vcam->stats_video_min_ns = vcam->stats_video_max_ns = 0; + vcam->stats_audio_frames = vcam->stats_audio_dropped = vcam->stats_audio_measured = 0; + vcam->stats_audio_min_ns = vcam->stats_audio_max_ns = 0; + pthread_mutex_unlock(&vcam->sync.mutex); + UNUSED_PARAMETER(cd); +} + static void *virtualcam_create(obs_data_t *settings, obs_output_t *output) { struct virtualcam_data *vcam = (struct virtualcam_data *)bzalloc(sizeof(*vcam)); vcam->output = output; + vcam->stats_generation = os_gettime_ns(); vcam->device = -1; vcam->mic_fifo = -1; vcam->mic_drain = -1; @@ -987,8 +1003,11 @@ static void *virtualcam_create(obs_data_t *settings, obs_output_t *output) if (output) proc_handler_add( obs_output_get_proc_handler(output), - "void virtualcam_stats(out int vcam_frames, out int vcam_dropped, out int vmic_frames, out int vmic_dropped, out int vcam_min_ns, out int vcam_max_ns, out int vmic_min_ns, out int vmic_max_ns)", + "void virtualcam_stats(out int generation, out int vcam_frames, out int vcam_dropped, out int vmic_frames, out int vmic_dropped, out int vcam_min_ns, out int vcam_max_ns, out int vmic_min_ns, out int vmic_max_ns)", virtualcam_stats_proc, vcam); + if (output) + proc_handler_add(obs_output_get_proc_handler(output), "void virtualcam_stats_reset()", + virtualcam_stats_reset_proc, vcam); return vcam; } diff --git a/rust/obs-mcp/src/backend/control.rs b/rust/obs-mcp/src/backend/control.rs index 2d93f3a618..051ea058b1 100644 --- a/rust/obs-mcp/src/backend/control.rs +++ b/rust/obs-mcp/src/backend/control.rs @@ -55,10 +55,21 @@ impl ObsBackend { } impl ControlBackend for ObsBackend { fn vcam_start(&self, request: StartInput) -> Result { + if !crate::ffi::has_video() { + return Err(ToolError::not_ready( + "Virtual Camera requires initialized video", + )); + } + if !(1..=6).contains(&request.audio_track) { + return Err(ToolError::wrong_state( + "audio_track must be between 1 and 6", + )); + } let output = self .camera(true)? .ok_or_else(|| ToolError::not_ready("Virtual Camera output unavailable"))?; if !output.active() { + output.update(&serde_json::json!({"audio_enabled":request.audio_enabled,"audio_track":request.audio_track})).map_err(ToolError::processing)?; output.start().map_err(ToolError::processing)?; } let status = self.vcam_status(EmptyInput::default())?; @@ -102,13 +113,19 @@ impl ControlBackend for ObsBackend { } fn stats_get(&self, _request: EmptyInput) -> Result { let current = self.raw_stats()?; - Ok(self.baseline.borrow().as_ref().map_or_else( - || current.clone(), - |baseline| current.clone().relative_to(baseline), - )) + if let Some(baseline) = self.baseline.borrow_mut().as_mut() { + return Ok(baseline.apply(current)); + } + Ok(current) } fn stats_reset(&self, _request: EmptyInput) -> Result { - self.baseline.replace(Some(self.raw_stats()?)); + if let Some(output) = self.camera(false)? { + output.reset_device_stats(); + } + self.baseline + .replace(Some(crate::tools::control::StatsBaseline::new( + self.raw_stats()?, + ))); self.stats_get(EmptyInput::default()) } fn pipeline_dump(&self, _request: EmptyInput) -> Result { diff --git a/rust/obs-mcp/src/backend/mod.rs b/rust/obs-mcp/src/backend/mod.rs index ee895fb764..90aa838905 100644 --- a/rust/obs-mcp/src/backend/mod.rs +++ b/rust/obs-mcp/src/backend/mod.rs @@ -56,7 +56,7 @@ pub struct ObsBackend { output_error: Option, cpu: Option, camera: RefCell>, - baseline: RefCell>, + baseline: RefCell>, } impl Default for ObsBackend { diff --git a/rust/obs-mcp/src/ffi/control.rs b/rust/obs-mcp/src/ffi/control.rs index b03274b8ec..381fa0daa2 100644 --- a/rust/obs-mcp/src/ffi/control.rs +++ b/rust/obs-mcp/src/ffi/control.rs @@ -119,10 +119,14 @@ impl Output { pub fn virtual_audio(&self) -> Option { self.procedure(c"virtualcam_audio")?.boolean(c"active") } + pub fn reset_device_stats(&self) { + let _ = self.procedure(c"virtualcam_stats_reset"); + } pub fn device_stats(&self) -> Option<(StageStats, StageStats)> { let data = self.procedure(c"virtualcam_stats")?; let video = StageStats { live: self.active(), + generation: data.count(c"generation"), latency_min_ns: data.count(c"vcam_min_ns"), latency_max_ns: data.count(c"vcam_max_ns"), frames_total: data.count(c"vcam_frames"), @@ -131,6 +135,7 @@ impl Output { }; let audio = StageStats { live: self.virtual_audio().unwrap_or(false), + generation: data.count(c"generation"), latency_min_ns: data.count(c"vmic_min_ns"), latency_max_ns: data.count(c"vmic_max_ns"), frames_total: data.count(c"vmic_frames"), diff --git a/rust/obs-mcp/src/tools/control.rs b/rust/obs-mcp/src/tools/control.rs index d64bdc6720..8429f7acb7 100644 --- a/rust/obs-mcp/src/tools/control.rs +++ b/rust/obs-mcp/src/tools/control.rs @@ -6,12 +6,33 @@ use serde::{Deserialize, Serialize}; use std::rc::Rc; /// Bounded start options, extended by the wait domain. -#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] pub struct StartInput { /// Wait until the output reports active. #[serde(default)] pub wait: bool, + /// Enable the paired microphone before a stopped output starts. + #[serde(default = "enabled")] + pub audio_enabled: bool, + /// One-based OBS audio mix (1 through 6). + #[serde(default = "first_mix")] + pub audio_track: u32, +} +fn enabled() -> bool { + true +} +fn first_mix() -> u32 { + 1 +} +impl Default for StartInput { + fn default() -> Self { + Self { + wait: false, + audio_enabled: true, + audio_track: 1, + } + } } /// Virtual Camera and its paired audio source. #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] @@ -77,6 +98,8 @@ pub struct MediaStatus { pub struct StageStats { /// Currently running. pub live: bool, + /// Counter generation, when the provider exposes one. + pub generation: Option, /// Observed minimum stage residence time, if measured. pub latency_min_ns: Option, /// Observed maximum stage residence time, if measured. @@ -360,3 +383,67 @@ impl StatsSnapshot { self } } + +/// Stateful baselines detect provider recreation even after raw counters exceed +/// the previous baseline. Latency bounds are gauges, reset by the provider. +#[derive(Clone, Debug)] +pub struct StatsBaseline { + baseline: StatsSnapshot, + previous: StatsSnapshot, +} +impl StatsBaseline { + /// Establishes a baseline from the current raw snapshot. + #[must_use] + pub fn new(snapshot: StatsSnapshot) -> Self { + Self { + previous: snapshot.clone(), + baseline: snapshot, + } + } + /// Observe a raw snapshot, resetting rolled-back/recreated counter baselines. + pub fn apply(&mut self, snapshot: StatsSnapshot) -> StatsSnapshot { + fn stage(now: &StageStats, previous: &StageStats, baseline: &mut StageStats) { + let recreated = now.generation.is_some() && now.generation != previous.generation; + let fix = |current: Option, prior: Option, base: &mut Option| { + if recreated || current.zip(prior).is_some_and(|(n, p)| n < p) { + *base = current.map(|_| 0); + } + }; + fix( + now.frames_total, + previous.frames_total, + &mut baseline.frames_total, + ); + fix( + now.frames_dropped, + previous.frames_dropped, + &mut baseline.frames_dropped, + ); + fix(now.xruns, previous.xruns, &mut baseline.xruns); + baseline.generation = now.generation; + } + stage( + &snapshot.stages.render, + &self.previous.stages.render, + &mut self.baseline.stages.render, + ); + stage( + &snapshot.stages.vcam, + &self.previous.stages.vcam, + &mut self.baseline.stages.vcam, + ); + stage( + &snapshot.stages.vmic, + &self.previous.stages.vmic, + &mut self.baseline.stages.vmic, + ); + if snapshot.render.render_total_frames < self.previous.render.render_total_frames { + self.baseline.render.render_total_frames = 0; + } + if snapshot.render.render_skipped_frames < self.previous.render.render_skipped_frames { + self.baseline.render.render_skipped_frames = 0; + } + self.previous = snapshot.clone(); + snapshot.relative_to(&self.baseline) + } +} diff --git a/rust/obs-mcp/tests/libobs_backend.rs b/rust/obs-mcp/tests/libobs_backend.rs index ad56b907eb..402b619a40 100644 --- a/rust/obs-mcp/tests/libobs_backend.rs +++ b/rust/obs-mcp/tests/libobs_backend.rs @@ -234,6 +234,8 @@ fn sources_and_items(backend: &ObsBackend) { } fn stats_capture_and_outputs(backend: &ObsBackend) { + let error = obs_mcp::tools::control::ControlBackend::vcam_start(backend, Default::default()).unwrap_err(); + assert_eq!(error.code, 207, "no video must be rejected before entering the native camera plugin"); let stats = backend.stats(); assert_eq!(stats.fps, 0.0, "no video subsystem, no frames"); assert_eq!(stats.dropped_frames, 0); diff --git a/rust/obs-mcp/tests/mcp/control.rs b/rust/obs-mcp/tests/mcp/control.rs index 0b628317a8..e0dffa1696 100644 --- a/rust/obs-mcp/tests/mcp/control.rs +++ b/rust/obs-mcp/tests/mcp/control.rs @@ -117,3 +117,26 @@ fn reset_changes_counters_but_preserves_gauges_and_unknown_values() { assert_eq!(result.stages.vcam.latency_max_ns, Some(800)); assert_eq!(result.stages.vmic.xruns, None); } + +#[test] +fn recreated_counter_stays_in_new_generation_across_old_baseline() { + use obs_mcp::tools::control::StatsBaseline; + let mut old = StatsSnapshot::default(); + old.stages.vcam.frames_total = Some(20); + old.stages.vcam.generation = Some(1); + let mut tracker = StatsBaseline::new(old); + let mut new = StatsSnapshot::default(); + new.stages.vcam.frames_total = Some(3); + new.stages.vcam.generation = Some(2); + assert_eq!(tracker.apply(new.clone()).stages.vcam.frames_total, Some(3)); + new.stages.vcam.frames_total = Some(25); + assert_eq!( + tracker.apply(new.clone()).stages.vcam.frames_total, + Some(25) + ); + new.stages.vcam.frames_total = Some(30); + new.stages.vcam.generation = Some(3); + assert_eq!(tracker.apply(new).stages.vcam.frames_total, Some(30)); + assert!(StartInput::default().audio_enabled); + assert_eq!(StartInput::default().audio_track, 1); +} From 278a1b1dd478683bc98883a48529c7aaa1cb860d Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 14:58:45 -0800 Subject: [PATCH 09/39] style(mcp): format native readiness contract (#4446) --- rust/obs-mcp/tests/libobs_backend.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/rust/obs-mcp/tests/libobs_backend.rs b/rust/obs-mcp/tests/libobs_backend.rs index 402b619a40..3304eee439 100644 --- a/rust/obs-mcp/tests/libobs_backend.rs +++ b/rust/obs-mcp/tests/libobs_backend.rs @@ -234,8 +234,12 @@ fn sources_and_items(backend: &ObsBackend) { } fn stats_capture_and_outputs(backend: &ObsBackend) { - let error = obs_mcp::tools::control::ControlBackend::vcam_start(backend, Default::default()).unwrap_err(); - assert_eq!(error.code, 207, "no video must be rejected before entering the native camera plugin"); + let error = obs_mcp::tools::control::ControlBackend::vcam_start(backend, Default::default()) + .unwrap_err(); + assert_eq!( + error.code, 207, + "no video must be rejected before entering the native camera plugin" + ); let stats = backend.stats(); assert_eq!(stats.fps, 0.0, "no video subsystem, no frames"); assert_eq!(stats.dropped_frames, 0); From 861014e9a8439369f3c85af09f5a9fd1bd63a42f Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 15:02:03 -0800 Subject: [PATCH 10/39] test(mcp): RED deterministic condition waits and deadlines (#4447) --- rust/obs-mcp/src/tools/mod.rs | 2 + rust/obs-mcp/src/tools/waiting.rs | 118 ++++++++++++++++++++++++++++++ rust/obs-mcp/tests/mcp/main.rs | 2 + rust/obs-mcp/tests/mcp/waiting.rs | 34 +++++++++ 4 files changed, 156 insertions(+) create mode 100644 rust/obs-mcp/src/tools/waiting.rs create mode 100644 rust/obs-mcp/tests/mcp/waiting.rs diff --git a/rust/obs-mcp/src/tools/mod.rs b/rust/obs-mcp/src/tools/mod.rs index 1051b39105..9062a25e94 100644 --- a/rust/obs-mcp/src/tools/mod.rs +++ b/rust/obs-mcp/src/tools/mod.rs @@ -46,3 +46,5 @@ pub fn schema_snapshot() -> serde_json::Value { } pub mod control; + +pub mod waiting; diff --git a/rust/obs-mcp/src/tools/waiting.rs b/rust/obs-mcp/src/tools/waiting.rs new file mode 100644 index 0000000000..b0d13a0fb1 --- /dev/null +++ b/rust/obs-mcp/src/tools/waiting.rs @@ -0,0 +1,118 @@ +//! Bounded typed waits, with a deterministic clock seam (#4447). +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use crate::server::ToolError; +use super::control::MediaState; + +/// Default auto-wait deadline. +pub const DEFAULT_TIMEOUT_MS: u64 = 5000; +/// Maximum request deadline, keeping control requests bounded. +pub const MAX_TIMEOUT_MS: u64 = 300_000; +/// Default timeout used by serde and fluent clients. +#[must_use] +pub fn default_timeout_ms() -> u64 { DEFAULT_TIMEOUT_MS } +/// An output controlled by OBS. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all="snake_case")] +pub enum OutputName { /// Recording. +Record, /// Streaming. +Stream, /// Virtual Camera. +Vcam, /// Paired virtual microphone. +Vmic } +/// Desired output state. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all="snake_case")] +pub enum OutputState { /// Running. +Active, /// Stopped. +Inactive } +/// A supported numeric metric, never an expression. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all="snake_case")] +pub enum Metric { /// Average render duration. +RenderFrameTimeNs, /// Render drops since baseline. +RenderFramesDropped, /// Camera maximum measured stage latency. +VcamLatencyMaxNs, /// Microphone maximum measured stage latency. +VmicLatencyMaxNs, /// Microphone xruns, if measured. +VmicXruns, /// Absolute independently measured sync offset. +AvOffsetAbsMs } +/// Explicit condition language, rejecting unknown fields. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[serde(tag="type",rename_all="snake_case",deny_unknown_fields)] +pub enum Condition { + /// Wait for an output to reach a state. + OutputState { /// Output selector. + output: OutputName, /// Desired state. + state: OutputState }, + /// Wait until a source exists and is active. + SourceActive { /// Source name. + name: String }, + /// Wait for a named media source's state. + MediaState { /// Source name. + name: String, /// Desired media state. + state: MediaState }, + /// Wait until a measured metric is at most the threshold. + StatAtMost { /// Metric selector. + metric: Metric, /// Maximum acceptable value, in the metric's units. + value: f64 }, +} +/// One wait request. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct WaitInput { /// Condition to observe before waiting. + pub condition: Condition, /// Deadline in milliseconds; zero still observes once. + #[serde(default="default_timeout_ms")] + pub timeout_ms: u64 } +/// Typed final observation, including unavailable measurements. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[serde(tag="kind",rename_all="snake_case")] +pub enum LastValue { + /// Output observation. + Output { /// Null if the output state cannot be queried. + active: Option }, + /// Source observation. + Source { /// Whether the source exists. + present: bool, /// Whether it is active. + active: bool }, + /// Media observation. + Media { /// Null if the named source is absent. + state: Option }, + /// Numeric observation. + Stat { /// Metric selector. + metric: Metric, /// Null if unavailable; never satisfies a threshold. + value: Option }, +} +/// Result of one observation. +#[derive(Clone, Debug)] +pub struct Observation { /// Whether the condition is met. + pub satisfied: bool, /// Typed current value. + pub value: LastValue } +/// Final wait result. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +pub struct WaitOutput { /// Condition met before the deadline. + pub satisfied: bool, /// Monotonic elapsed time. + pub elapsed_ms: u64, /// Last observed value, including on timeout. + pub last_value: LastValue } +/// Backend request for a single observation. +#[derive(Clone, Debug)] +pub struct ObserveInput { /// Condition to evaluate. + pub condition: Condition } +/// Backend seam, reusable for automatic waits. +pub trait WaitBackend { + /// Observe without waiting. + /// # Errors + /// Reports an unavailable subsystem or failed query. + fn observe(&self, request: &ObserveInput) -> Result; + /// Shutdown cancellation is checked before accessing libobs. + fn cancelled(&self) -> bool { false } +} +/// Monotonic clock and bounded parking; tests do not sleep. +pub trait WaitClock { /// Monotonic time in milliseconds. + fn now_ms(&self) -> u64; /// Wait for at most the supplied interval. + fn wait_ms(&self, milliseconds: u64); } +/// Evaluate first, then wait within the deadline. +/// # Errors +/// Reports backend failure, cancellation or an excessive timeout. +pub fn run_wait(backend: &B, request: WaitInput, clock: &C) -> Result { + let _ = (backend, request, clock); + todo!("bounded condition wait") +} diff --git a/rust/obs-mcp/tests/mcp/main.rs b/rust/obs-mcp/tests/mcp/main.rs index eeb8ab3bec..5e6bdfe826 100644 --- a/rust/obs-mcp/tests/mcp/main.rs +++ b/rust/obs-mcp/tests/mcp/main.rs @@ -27,3 +27,5 @@ pub(crate) fn roundtrip(input: &str) -> Vec { mod typed; mod control; + +mod waiting; diff --git a/rust/obs-mcp/tests/mcp/waiting.rs b/rust/obs-mcp/tests/mcp/waiting.rs new file mode 100644 index 0000000000..bf4a888761 --- /dev/null +++ b/rust/obs-mcp/tests/mcp/waiting.rs @@ -0,0 +1,34 @@ +//! Deterministic wait contract (#4447), using no sleeps or own threads. +use std::cell::Cell; +use obs_mcp::server::ToolError; +use obs_mcp::tools::control::MediaState; +use obs_mcp::tools::waiting::{Condition, LastValue, Observation, ObserveInput, WaitBackend, WaitClock, WaitInput, run_wait}; +#[derive(Default)] +struct Clock(Cell); +impl WaitClock for Clock { + fn now_ms(&self) -> u64 { self.0.get() } + fn wait_ms(&self, ms:u64) { self.0.set(self.0.get()+ms); } +} +struct Backend<'a> { clock: &'a Clock, ready_at: u64, observations: Cell } +impl WaitBackend for Backend<'_> { + fn observe(&self,_:&ObserveInput)->Result { + self.observations.set(self.observations.get()+1); + let ready = self.clock.now_ms()>=self.ready_at; + Ok(Observation { satisfied:ready, value:LastValue::Media {state:Some(if ready {MediaState::Playing} else {MediaState::Opening})} }) + } +} +fn input(timeout_ms:u64)->WaitInput { WaitInput { condition:Condition::MediaState {name:"clip".into(),state:MediaState::Playing}, timeout_ms } } +#[test] +fn already_satisfied_zero_timeout_observes_without_waiting() { + let clock=Clock::default();let backend=Backend{clock:&clock,ready_at:0,observations:Cell::new(0)}; + let result=run_wait(&backend,input(0),&clock).unwrap(); + assert!(result.satisfied); assert_eq!(result.elapsed_ms,0); assert_eq!(backend.observations.get(),1); +} +#[test] +fn transition_and_timeout_preserve_last_observation() { + let clock=Clock::default();let backend=Backend{clock:&clock,ready_at:20,observations:Cell::new(0)}; + let result=run_wait(&backend,input(100),&clock).unwrap();assert!(result.satisfied);assert_eq!(result.elapsed_ms,20); + let clock=Clock::default();let backend=Backend{clock:&clock,ready_at:100,observations:Cell::new(0)}; + let result=run_wait(&backend,input(15),&clock).unwrap();assert!(!result.satisfied);assert_eq!(result.elapsed_ms,15); + assert!(matches!(result.last_value,LastValue::Media {state:Some(MediaState::Opening)})); +} From 7320a134257dff132bdc4390c6e3570edb4a06e3 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 15:12:38 -0800 Subject: [PATCH 11/39] feat(mcp): bounded typed waits and start auto-wait (#4447) --- docs/features.md | 6 + docs/rust-port/control-api.schema.json | 9 +- rust/obs-mcp/src/backend/control.rs | 27 ++- rust/obs-mcp/src/backend/mod.rs | 9 + rust/obs-mcp/src/backend/waiting.rs | 83 ++++++++ rust/obs-mcp/src/ffi/control.rs | 6 + rust/obs-mcp/src/tools/control.rs | 4 + rust/obs-mcp/src/tools/mod.rs | 1 + rust/obs-mcp/src/tools/outputs.rs | 76 ++++++- rust/obs-mcp/src/tools/waiting.rs | 265 +++++++++++++++++++------ rust/obs-mcp/tests/mcp/outputs.rs | 6 +- rust/obs-mcp/tests/mcp/waiting.rs | 126 ++++++++++-- 12 files changed, 523 insertions(+), 95 deletions(-) create mode 100644 rust/obs-mcp/src/backend/waiting.rs diff --git a/docs/features.md b/docs/features.md index cd929e1368..bf17fea8a2 100644 --- a/docs/features.md +++ b/docs/features.md @@ -75,6 +75,12 @@ not get a line. ### Headless and automation +- **Bounded MCP waits.** Agents can wait for typed output/source/media/metric + conditions and request automatic waits on starts, without GUI interaction or + fixed sleeps. Timeouts return the last observation. *All*, 2026-11-09. + Issue [#4447](https://github.com/obs-rust/obs-studio/issues/4447), + PR [#4454](https://github.com/obs-rust/obs-studio/pull/4454). + - **Virtual device and media control.** MCP can start/stop Virtual Camera, inspect its paired mic, restart media, inspect pipeline graphs and read/reset measured stage counters. Unmeasured device/sync values stay null. *All* (device support diff --git a/docs/rust-port/control-api.schema.json b/docs/rust-port/control-api.schema.json index 2e6ab44ae5..cc60c0a65a 100644 --- a/docs/rust-port/control-api.schema.json +++ b/docs/rust-port/control-api.schema.json @@ -4,7 +4,7 @@ {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"A media source selection.","properties":{"name":{"description":"Name of an existing media source.","type":"string"}},"required":["name"],"title":"MediaInput","type":"object"},"name":"media_restart","outputSchema":{"$defs":{"MediaState":{"description":"libobs media state.","oneOf":[{"const":"none","description":"Not a controllable media source.","type":"string"},{"const":"playing","description":"Playing.","type":"string"},{"const":"opening","description":"Opening.","type":"string"},{"const":"buffering","description":"Buffering.","type":"string"},{"const":"paused","description":"Paused.","type":"string"},{"const":"stopped","description":"Stopped.","type":"string"},{"const":"ended","description":"Playback reached the end.","type":"string"},{"const":"error","description":"Playback failed.","type":"string"}]}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Media playback snapshot, in milliseconds.","properties":{"duration_ms":{"description":"Total duration, if known.","format":"int64","type":["integer","null"]},"name":{"description":"Source name.","type":"string"},"position_ms":{"description":"Playback position, if known.","format":"int64","type":["integer","null"]},"state":{"$ref":"#/$defs/MediaState","description":"Current media state."}},"required":["name","state"],"title":"MediaStatus","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"A media source selection.","properties":{"name":{"description":"Name of an existing media source.","type":"string"}},"required":["name"],"title":"MediaInput","type":"object"},"name":"media_status","outputSchema":{"$defs":{"MediaState":{"description":"libobs media state.","oneOf":[{"const":"none","description":"Not a controllable media source.","type":"string"},{"const":"playing","description":"Playing.","type":"string"},{"const":"opening","description":"Opening.","type":"string"},{"const":"buffering","description":"Buffering.","type":"string"},{"const":"paused","description":"Paused.","type":"string"},{"const":"stopped","description":"Stopped.","type":"string"},{"const":"ended","description":"Playback reached the end.","type":"string"},{"const":"error","description":"Playback failed.","type":"string"}]}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Media playback snapshot, in milliseconds.","properties":{"duration_ms":{"description":"Total duration, if known.","format":"int64","type":["integer","null"]},"name":{"description":"Source name.","type":"string"},"position_ms":{"description":"Playback position, if known.","format":"int64","type":["integer","null"]},"state":{"$ref":"#/$defs/MediaState","description":"Current media state."}},"required":["name","state"],"title":"MediaStatus","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"pipeline_dump","outputSchema":{"$defs":{"RenderStats":{"description":"GetStats-style render counters.","properties":{"active_fps":{"description":"Actual render FPS.","format":"double","type":"number"},"average_frame_time_ns":{"description":"Average render duration, not end-to-end latency.","format":"uint64","minimum":0,"type":"integer"},"render_skipped_frames":{"description":"Frames lagged since baseline.","format":"uint64","minimum":0,"type":"integer"},"render_total_frames":{"description":"Frames rendered since baseline.","format":"uint64","minimum":0,"type":"integer"}},"required":["active_fps","average_frame_time_ns","render_total_frames","render_skipped_frames"],"type":"object"},"StageStats":{"description":"One live pipeline stage; null values are unmeasured, never synthetic zeroes.","properties":{"frames_dropped":{"description":"Dropped frames since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"frames_total":{"description":"Frames handled since the counter baseline.","format":"uint64","minimum":0,"type":["integer","null"]},"generation":{"description":"Counter generation, when the provider exposes one.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_max_ns":{"description":"Observed maximum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_min_ns":{"description":"Observed minimum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"live":{"description":"Currently running.","type":"boolean"},"xruns":{"description":"Underruns/overruns since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]}},"required":["live"],"type":"object"},"Stages":{"description":"Render and device stages.","properties":{"render":{"$ref":"#/$defs/StageStats","description":"OBS render stage."},"vcam":{"$ref":"#/$defs/StageStats","description":"Virtual Camera write stage."},"vmic":{"$ref":"#/$defs/StageStats","description":"Virtual microphone stage."}},"required":["render","vcam","vmic"],"type":"object"},"StatsSnapshot":{"description":"Typed pipeline statistics.","properties":{"end_to_end":{"$ref":"#/$defs/SyncStats","description":"End-to-end sync, with explicit provenance."},"render":{"$ref":"#/$defs/RenderStats","description":"Render counters."},"stages":{"$ref":"#/$defs/Stages","description":"Per-stage measured counters and bounds."}},"required":["stages","end_to_end","render"],"type":"object"},"SyncStats":{"description":"End-to-end measurement provenance.","properties":{"av_offset_ms":{"description":"Measured audio minus video offset; null until independently measured.","format":"double","type":["number","null"]},"measured_from":{"description":"Measurement source; queue estimates are not end-to-end measurements.","type":"string"}},"required":["measured_from"],"type":"object"},"VcamStatus":{"description":"Virtual Camera and its paired audio source.","properties":{"active":{"description":"Video output is active.","type":"boolean"},"configured":{"description":"Whether the registered output exists.","type":"boolean"},"vmic_active":{"description":"Paired virtual microphone is active, when the plugin supports the query.","type":["boolean","null"]}},"required":["configured","active"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Graph snapshot useful for diagnosing missing sources and outputs.","properties":{"program":{"description":"Program source name.","type":["string","null"]},"sources":{"description":"Source names in stable order.","items":{"type":"string"},"type":"array"},"stats":{"$ref":"#/$defs/StatsSnapshot","description":"Current pipeline measurements."},"vcam":{"$ref":"#/$defs/VcamStatus","description":"Virtual output state."}},"required":["sources","vcam","stats"],"title":"PipelineDump","type":"object"}}, - {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"record_start","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}}, + {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Auto-wait options for recording/streaming starts.","properties":{"timeout_ms":{"default":5000,"description":"Bounded wait deadline.","format":"uint64","minimum":0,"type":"integer"},"wait":{"default":false,"description":"Wait for the output to report active.","type":"boolean"}},"title":"OutputStartInput","type":"object"},"name":"record_start","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"record_status","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"The state of an output as reported by [`OutputBackend::status`].","properties":{"active":{"description":"Whether the output is running.","type":"boolean"},"bytes":{"description":"Bytes written or sent so far, where known.","format":"uint64","minimum":0,"type":["integer","null"]},"duration_ms":{"description":"Milliseconds since the output started, where known.","format":"uint64","minimum":0,"type":["integer","null"]}},"required":["active"],"title":"OutputStatus","type":"object"}}, {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"record_stop","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}}, {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"A scene name.","properties":{"name":{"description":"Scene name.","minLength":1,"type":"string"}},"required":["name"],"title":"NameInput","type":"object"},"name":"scene_create","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Current or changed scene.","properties":{"name":{"description":"Null when there is no program scene.","type":["string","null"]}},"title":"SceneOutput","type":"object"}}, @@ -22,12 +22,13 @@ {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"sources_list","outputSchema":{"$defs":{"SourceInfo":{"description":"A source as listed by [`SourceBackend::sources`].","properties":{"kind":{"description":"The source kind id, such as `color_source`.","type":"string"},"name":{"description":"The source's unique name.","type":"string"}},"required":["name","kind"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Source listing.","properties":{"sources":{"description":"Sources in stable order.","items":{"$ref":"#/$defs/SourceInfo"},"type":"array"}},"required":["sources"],"title":"SourcesOutput","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stats_get","outputSchema":{"$defs":{"RenderStats":{"description":"GetStats-style render counters.","properties":{"active_fps":{"description":"Actual render FPS.","format":"double","type":"number"},"average_frame_time_ns":{"description":"Average render duration, not end-to-end latency.","format":"uint64","minimum":0,"type":"integer"},"render_skipped_frames":{"description":"Frames lagged since baseline.","format":"uint64","minimum":0,"type":"integer"},"render_total_frames":{"description":"Frames rendered since baseline.","format":"uint64","minimum":0,"type":"integer"}},"required":["active_fps","average_frame_time_ns","render_total_frames","render_skipped_frames"],"type":"object"},"StageStats":{"description":"One live pipeline stage; null values are unmeasured, never synthetic zeroes.","properties":{"frames_dropped":{"description":"Dropped frames since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"frames_total":{"description":"Frames handled since the counter baseline.","format":"uint64","minimum":0,"type":["integer","null"]},"generation":{"description":"Counter generation, when the provider exposes one.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_max_ns":{"description":"Observed maximum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_min_ns":{"description":"Observed minimum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"live":{"description":"Currently running.","type":"boolean"},"xruns":{"description":"Underruns/overruns since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]}},"required":["live"],"type":"object"},"Stages":{"description":"Render and device stages.","properties":{"render":{"$ref":"#/$defs/StageStats","description":"OBS render stage."},"vcam":{"$ref":"#/$defs/StageStats","description":"Virtual Camera write stage."},"vmic":{"$ref":"#/$defs/StageStats","description":"Virtual microphone stage."}},"required":["render","vcam","vmic"],"type":"object"},"SyncStats":{"description":"End-to-end measurement provenance.","properties":{"av_offset_ms":{"description":"Measured audio minus video offset; null until independently measured.","format":"double","type":["number","null"]},"measured_from":{"description":"Measurement source; queue estimates are not end-to-end measurements.","type":"string"}},"required":["measured_from"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Typed pipeline statistics.","properties":{"end_to_end":{"$ref":"#/$defs/SyncStats","description":"End-to-end sync, with explicit provenance."},"render":{"$ref":"#/$defs/RenderStats","description":"Render counters."},"stages":{"$ref":"#/$defs/Stages","description":"Per-stage measured counters and bounds."}},"required":["stages","end_to_end","render"],"title":"StatsSnapshot","type":"object"}}, {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stats_reset","outputSchema":{"$defs":{"RenderStats":{"description":"GetStats-style render counters.","properties":{"active_fps":{"description":"Actual render FPS.","format":"double","type":"number"},"average_frame_time_ns":{"description":"Average render duration, not end-to-end latency.","format":"uint64","minimum":0,"type":"integer"},"render_skipped_frames":{"description":"Frames lagged since baseline.","format":"uint64","minimum":0,"type":"integer"},"render_total_frames":{"description":"Frames rendered since baseline.","format":"uint64","minimum":0,"type":"integer"}},"required":["active_fps","average_frame_time_ns","render_total_frames","render_skipped_frames"],"type":"object"},"StageStats":{"description":"One live pipeline stage; null values are unmeasured, never synthetic zeroes.","properties":{"frames_dropped":{"description":"Dropped frames since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"frames_total":{"description":"Frames handled since the counter baseline.","format":"uint64","minimum":0,"type":["integer","null"]},"generation":{"description":"Counter generation, when the provider exposes one.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_max_ns":{"description":"Observed maximum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_min_ns":{"description":"Observed minimum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"live":{"description":"Currently running.","type":"boolean"},"xruns":{"description":"Underruns/overruns since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]}},"required":["live"],"type":"object"},"Stages":{"description":"Render and device stages.","properties":{"render":{"$ref":"#/$defs/StageStats","description":"OBS render stage."},"vcam":{"$ref":"#/$defs/StageStats","description":"Virtual Camera write stage."},"vmic":{"$ref":"#/$defs/StageStats","description":"Virtual microphone stage."}},"required":["render","vcam","vmic"],"type":"object"},"SyncStats":{"description":"End-to-end measurement provenance.","properties":{"av_offset_ms":{"description":"Measured audio minus video offset; null until independently measured.","format":"double","type":["number","null"]},"measured_from":{"description":"Measurement source; queue estimates are not end-to-end measurements.","type":"string"}},"required":["measured_from"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Typed pipeline statistics.","properties":{"end_to_end":{"$ref":"#/$defs/SyncStats","description":"End-to-end sync, with explicit provenance."},"render":{"$ref":"#/$defs/RenderStats","description":"Render counters."},"stages":{"$ref":"#/$defs/Stages","description":"Per-stage measured counters and bounds."}},"required":["stages","end_to_end","render"],"title":"StatsSnapshot","type":"object"}}, - {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stream_start","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}}, + {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Auto-wait options for recording/streaming starts.","properties":{"timeout_ms":{"default":5000,"description":"Bounded wait deadline.","format":"uint64","minimum":0,"type":"integer"},"wait":{"default":false,"description":"Wait for the output to report active.","type":"boolean"}},"title":"OutputStartInput","type":"object"},"name":"stream_start","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stream_status","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"The state of an output as reported by [`OutputBackend::status`].","properties":{"active":{"description":"Whether the output is running.","type":"boolean"},"bytes":{"description":"Bytes written or sent so far, where known.","format":"uint64","minimum":0,"type":["integer","null"]},"duration_ms":{"description":"Milliseconds since the output started, where known.","format":"uint64","minimum":0,"type":["integer","null"]}},"required":["active"],"title":"OutputStatus","type":"object"}}, {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stream_stop","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}}, - {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Bounded start options, extended by the wait domain.","properties":{"audio_enabled":{"default":true,"description":"Enable the paired microphone before a stopped output starts.","type":"boolean"},"audio_track":{"default":1,"description":"One-based OBS audio mix (1 through 6).","format":"uint32","minimum":0,"type":"integer"},"wait":{"default":false,"description":"Wait until the output reports active.","type":"boolean"}},"title":"StartInput","type":"object"},"name":"vcam_start","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Virtual Camera and its paired audio source.","properties":{"active":{"description":"Video output is active.","type":"boolean"},"configured":{"description":"Whether the registered output exists.","type":"boolean"},"vmic_active":{"description":"Paired virtual microphone is active, when the plugin supports the query.","type":["boolean","null"]}},"required":["configured","active"],"title":"VcamStatus","type":"object"}}, + {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Bounded start options, extended by the wait domain.","properties":{"audio_enabled":{"default":true,"description":"Enable the paired microphone before a stopped output starts.","type":"boolean"},"audio_track":{"default":1,"description":"One-based OBS audio mix (1 through 6).","format":"uint32","minimum":0,"type":"integer"},"timeout_ms":{"default":5000,"description":"Auto-wait deadline in milliseconds.","format":"uint64","minimum":0,"type":"integer"},"wait":{"default":false,"description":"Wait until the output reports active.","type":"boolean"}},"title":"StartInput","type":"object"},"name":"vcam_start","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Virtual Camera and its paired audio source.","properties":{"active":{"description":"Video output is active.","type":"boolean"},"configured":{"description":"Whether the registered output exists.","type":"boolean"},"vmic_active":{"description":"Paired virtual microphone is active, when the plugin supports the query.","type":["boolean","null"]}},"required":["configured","active"],"title":"VcamStatus","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"vcam_status","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Virtual Camera and its paired audio source.","properties":{"active":{"description":"Video output is active.","type":"boolean"},"configured":{"description":"Whether the registered output exists.","type":"boolean"},"vmic_active":{"description":"Paired virtual microphone is active, when the plugin supports the query.","type":["boolean","null"]}},"required":["configured","active"],"title":"VcamStatus","type":"object"}}, {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"vcam_stop","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Virtual Camera and its paired audio source.","properties":{"active":{"description":"Video output is active.","type":"boolean"},"configured":{"description":"Whether the registered output exists.","type":"boolean"},"vmic_active":{"description":"Paired virtual microphone is active, when the plugin supports the query.","type":["boolean","null"]}},"required":["configured","active"],"title":"VcamStatus","type":"object"}}, - {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"vmic_status","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Virtual microphone state.","properties":{"active":{"description":"Active according to virtualcam_audio; null means unsupported.","type":["boolean","null"]},"source_name":{"description":"Runtime source name, when known.","type":["string","null"]}},"title":"VmicStatus","type":"object"}} + {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"vmic_status","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Virtual microphone state.","properties":{"active":{"description":"Active according to virtualcam_audio; null means unsupported.","type":["boolean","null"]},"source_name":{"description":"Runtime source name, when known.","type":["string","null"]}},"title":"VmicStatus","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$defs":{"Condition":{"description":"Explicit condition language, rejecting unknown fields.","oneOf":[{"additionalProperties":false,"description":"Wait for an output to reach a state.","properties":{"output":{"$ref":"#/$defs/OutputName","description":"Output selector."},"state":{"$ref":"#/$defs/OutputState","description":"Desired state."},"type":{"const":"output_state","type":"string"}},"required":["type","output","state"],"type":"object"},{"additionalProperties":false,"description":"Wait until a source exists and is active.","properties":{"name":{"description":"Source name.","type":"string"},"type":{"const":"source_active","type":"string"}},"required":["type","name"],"type":"object"},{"additionalProperties":false,"description":"Wait for a named media source's state.","properties":{"name":{"description":"Source name.","type":"string"},"state":{"$ref":"#/$defs/MediaState","description":"Desired media state."},"type":{"const":"media_state","type":"string"}},"required":["type","name","state"],"type":"object"},{"additionalProperties":false,"description":"Wait until a measured metric is at most the threshold.","properties":{"metric":{"$ref":"#/$defs/Metric","description":"Metric selector."},"type":{"const":"stat_at_most","type":"string"},"value":{"description":"Maximum acceptable value, in the metric's units.","format":"double","type":"number"}},"required":["type","metric","value"],"type":"object"}]},"MediaState":{"description":"libobs media state.","oneOf":[{"const":"none","description":"Not a controllable media source.","type":"string"},{"const":"playing","description":"Playing.","type":"string"},{"const":"opening","description":"Opening.","type":"string"},{"const":"buffering","description":"Buffering.","type":"string"},{"const":"paused","description":"Paused.","type":"string"},{"const":"stopped","description":"Stopped.","type":"string"},{"const":"ended","description":"Playback reached the end.","type":"string"},{"const":"error","description":"Playback failed.","type":"string"}]},"Metric":{"description":"A supported numeric metric, never an expression.","oneOf":[{"const":"render_frame_time_ns","description":"Average render duration.","type":"string"},{"const":"render_frames_dropped","description":"Render drops since baseline.","type":"string"},{"const":"vcam_latency_max_ns","description":"Camera maximum measured stage latency.","type":"string"},{"const":"vmic_latency_max_ns","description":"Microphone maximum measured stage latency.","type":"string"},{"const":"vmic_xruns","description":"Microphone xruns, if measured.","type":"string"},{"const":"av_offset_abs_ms","description":"Absolute independently measured sync offset.","type":"string"}]},"OutputName":{"description":"An output controlled by OBS.","oneOf":[{"const":"record","description":"Recording.","type":"string"},{"const":"stream","description":"Streaming.","type":"string"},{"const":"vcam","description":"Virtual Camera.","type":"string"},{"const":"vmic","description":"Paired virtual microphone.","type":"string"}]},"OutputState":{"description":"Desired output state.","oneOf":[{"const":"active","description":"Running.","type":"string"},{"const":"inactive","description":"Stopped.","type":"string"}]}},"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"One wait request.","properties":{"condition":{"$ref":"#/$defs/Condition","description":"Condition to observe before waiting."},"timeout_ms":{"default":5000,"description":"Deadline in milliseconds; zero still observes once.","format":"uint64","minimum":0,"type":"integer"}},"required":["condition"],"title":"WaitInput","type":"object"},"name":"wait_for","outputSchema":{"$defs":{"LastValue":{"description":"Typed final observation, including unavailable measurements.","oneOf":[{"description":"Output observation.","properties":{"active":{"description":"Null if the output state cannot be queried.","type":["boolean","null"]},"kind":{"const":"output","type":"string"}},"required":["kind"],"type":"object"},{"description":"Source observation.","properties":{"active":{"description":"Whether it is active.","type":"boolean"},"kind":{"const":"source","type":"string"},"present":{"description":"Whether the source exists.","type":"boolean"}},"required":["kind","present","active"],"type":"object"},{"description":"Media observation.","properties":{"kind":{"const":"media","type":"string"},"state":{"anyOf":[{"$ref":"#/$defs/MediaState"},{"type":"null"}],"description":"Null if the named source is absent."}},"required":["kind"],"type":"object"},{"description":"Numeric observation.","properties":{"kind":{"const":"stat","type":"string"},"metric":{"$ref":"#/$defs/Metric","description":"Metric selector."},"value":{"description":"Null if unavailable; never satisfies a threshold.","format":"double","type":["number","null"]}},"required":["kind","metric"],"type":"object"}]},"MediaState":{"description":"libobs media state.","oneOf":[{"const":"none","description":"Not a controllable media source.","type":"string"},{"const":"playing","description":"Playing.","type":"string"},{"const":"opening","description":"Opening.","type":"string"},{"const":"buffering","description":"Buffering.","type":"string"},{"const":"paused","description":"Paused.","type":"string"},{"const":"stopped","description":"Stopped.","type":"string"},{"const":"ended","description":"Playback reached the end.","type":"string"},{"const":"error","description":"Playback failed.","type":"string"}]},"Metric":{"description":"A supported numeric metric, never an expression.","oneOf":[{"const":"render_frame_time_ns","description":"Average render duration.","type":"string"},{"const":"render_frames_dropped","description":"Render drops since baseline.","type":"string"},{"const":"vcam_latency_max_ns","description":"Camera maximum measured stage latency.","type":"string"},{"const":"vmic_latency_max_ns","description":"Microphone maximum measured stage latency.","type":"string"},{"const":"vmic_xruns","description":"Microphone xruns, if measured.","type":"string"},{"const":"av_offset_abs_ms","description":"Absolute independently measured sync offset.","type":"string"}]}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Final wait result.","properties":{"elapsed_ms":{"description":"Monotonic elapsed time.","format":"uint64","minimum":0,"type":"integer"},"last_value":{"$ref":"#/$defs/LastValue","description":"Last observed value, including on timeout."},"satisfied":{"description":"Condition met before the deadline.","type":"boolean"}},"required":["satisfied","elapsed_ms","last_value"],"title":"WaitOutput","type":"object"}} ] } diff --git a/rust/obs-mcp/src/backend/control.rs b/rust/obs-mcp/src/backend/control.rs index 051ea058b1..88bda122ae 100644 --- a/rust/obs-mcp/src/backend/control.rs +++ b/rust/obs-mcp/src/backend/control.rs @@ -55,6 +55,12 @@ impl ObsBackend { } impl ControlBackend for ObsBackend { fn vcam_start(&self, request: StartInput) -> Result { + if crate::tools::waiting::WaitBackend::cancelled(self) { + return Err(ToolError::not_ready("OBS control is shutting down")); + } + if request.wait { + crate::tools::waiting::validate_timeout(request.timeout_ms)?; + } if !crate::ffi::has_video() { return Err(ToolError::not_ready( "Virtual Camera requires initialized video", @@ -73,8 +79,25 @@ impl ControlBackend for ObsBackend { output.start().map_err(ToolError::processing)?; } let status = self.vcam_status(EmptyInput::default())?; - if request.wait && !status.active { - return Err(ToolError::not_ready("Virtual Camera has not become active")); + if request.wait { + use crate::tools::waiting::{ + Condition, OutputName, OutputState, SystemClock, WaitInput, run_wait, + }; + let result = run_wait( + self, + WaitInput { + condition: Condition::OutputState { + output: OutputName::Vcam, + state: OutputState::Active, + }, + timeout_ms: request.timeout_ms, + }, + &SystemClock::default(), + )?; + if !result.satisfied { + return Err(ToolError::not_ready("Virtual Camera start timed out")); + } + return self.vcam_status(EmptyInput::default()); } Ok(status) } diff --git a/rust/obs-mcp/src/backend/mod.rs b/rust/obs-mcp/src/backend/mod.rs index 90aa838905..d4d0ec7eb1 100644 --- a/rust/obs-mcp/src/backend/mod.rs +++ b/rust/obs-mcp/src/backend/mod.rs @@ -56,6 +56,7 @@ pub struct ObsBackend { output_error: Option, cpu: Option, camera: RefCell>, + cancellation: Option>, baseline: RefCell>, } @@ -81,6 +82,7 @@ impl ObsBackend { output_error: None, cpu: CpuUsage::start(), camera: RefCell::new(None), + cancellation: None, baseline: RefCell::new(None), } } @@ -137,6 +139,8 @@ impl ObsBackend { screenshot::register(&mut tools, &capture); let control: Rc = Rc::clone(backend) as _; crate::tools::control::register(&mut tools, &control); + let waiting: Rc = Rc::clone(backend) as _; + crate::tools::waiting::register(&mut tools, &waiting); let mut resources = ResourceRegistry::new(); resources::scenes::register(&mut resources, &scenes, &sources); @@ -342,6 +346,9 @@ fn narrow(value: f64) -> f32 { } impl OutputBackend for ObsBackend { + fn control_cancelled(&self) -> bool { + crate::tools::waiting::WaitBackend::cancelled(self) + } fn start_output(&self, request: OutputRequest) -> Result { let output = self.output(request.kind).map_err(ToolError::not_ready)?; if !output.active() { @@ -480,3 +487,5 @@ impl StatsBackend for ObsBackend { } mod control; + +mod waiting; diff --git a/rust/obs-mcp/src/backend/waiting.rs b/rust/obs-mcp/src/backend/waiting.rs new file mode 100644 index 0000000000..df494e9ffd --- /dev/null +++ b/rust/obs-mcp/src/backend/waiting.rs @@ -0,0 +1,83 @@ +//! Wait observations over unchanged libobs queries. +use super::{ObsBackend, Source}; +use crate::server::ToolError; +use crate::tools::EmptyInput; +use crate::tools::control::ControlBackend; +use crate::tools::outputs::{OutputBackend, OutputKind}; +use crate::tools::waiting::{ + Condition, LastValue, Metric, Observation, ObserveInput, OutputName, OutputState, WaitBackend, +}; +impl ObsBackend { + /// Cancels pending waits when an in-app host shuts down. + #[must_use] + pub fn with_cancellation( + mut self, + flag: std::sync::Arc, + ) -> Self { + self.cancellation = Some(flag); + self + } +} +impl WaitBackend for ObsBackend { + fn cancelled(&self) -> bool { + self.cancellation + .as_ref() + .is_some_and(|flag| flag.load(std::sync::atomic::Ordering::Acquire)) + } + #[allow( + clippy::cast_precision_loss, + reason = "interactive stage measurements and xrun counts are far below 2^53" + )] + fn observe(&self, request: &ObserveInput) -> Result { + let (satisfied, value) = match &request.condition { + Condition::OutputState { output, state } => { + let active = match output { + OutputName::Record => Some(self.status(OutputKind::Record).active), + OutputName::Stream => Some(self.status(OutputKind::Stream).active), + OutputName::Vcam => Some(self.vcam_status(EmptyInput {})?.active), + OutputName::Vmic => self.vmic_status(EmptyInput {})?.active, + }; + ( + active == Some(matches!(state, OutputState::Active)), + LastValue::Output { active }, + ) + } + Condition::SourceActive { name } => { + let source = Source::by_name(name); + let active = source.as_ref().is_some_and(Source::active); + ( + active, + LastValue::Source { + present: source.is_some(), + active, + }, + ) + } + Condition::MediaState { name, state } => { + let current = Source::by_name(name).map(|source| source.media().state); + (current == Some(*state), LastValue::Media { state: current }) + } + Condition::StatAtMost { metric, value } => { + let stats = self.stats_get(EmptyInput {})?; + let current = match metric { + Metric::RenderFrameTimeNs => (stats.stages.render.live + && stats.render.average_frame_time_ns > 0) + .then_some(stats.render.average_frame_time_ns as f64), + Metric::RenderFramesDropped => Some(stats.render.render_skipped_frames as f64), + Metric::VcamLatencyMaxNs => stats.stages.vcam.latency_max_ns.map(|v| v as f64), + Metric::VmicLatencyMaxNs => stats.stages.vmic.latency_max_ns.map(|v| v as f64), + Metric::VmicXruns => stats.stages.vmic.xruns.map(|v| v as f64), + Metric::AvOffsetAbsMs => stats.end_to_end.av_offset_ms.map(f64::abs), + }; + ( + crate::tools::waiting::metric_at_most(current, *value), + LastValue::Stat { + metric: *metric, + value: current, + }, + ) + } + }; + Ok(Observation { satisfied, value }) + } +} diff --git a/rust/obs-mcp/src/ffi/control.rs b/rust/obs-mcp/src/ffi/control.rs index 381fa0daa2..3c984185a0 100644 --- a/rust/obs-mcp/src/ffi/control.rs +++ b/rust/obs-mcp/src/ffi/control.rs @@ -5,6 +5,7 @@ use obs_callback::ffi::calldata::calldata; use std::ffi::{CStr, c_char, c_int, c_void}; unsafe extern "C" { + fn obs_source_active(source: *const sys::obs_source_t) -> bool; fn obs_source_get_output_flags(source: *const sys::obs_source_t) -> u32; fn obs_source_media_restart(source: *mut sys::obs_source_t); fn obs_source_media_get_state(source: *mut sys::obs_source_t) -> c_int; @@ -66,6 +67,11 @@ impl Drop for Params { } } impl Source { + pub fn active(&self) -> bool { + // SAFETY: the source reference remains live during the query. + unsafe { obs_source_active(self.0.as_ptr()) } + } + pub fn restart_media(&self) -> Result<(), String> { // SAFETY: owns a live source reference; the flag is OBS_SOURCE_CONTROLLABLE_MEDIA. if unsafe { obs_source_get_output_flags(self.0.as_ptr()) } & (1 << 13) == 0 { diff --git a/rust/obs-mcp/src/tools/control.rs b/rust/obs-mcp/src/tools/control.rs index 8429f7acb7..ba37caebc7 100644 --- a/rust/obs-mcp/src/tools/control.rs +++ b/rust/obs-mcp/src/tools/control.rs @@ -12,6 +12,9 @@ pub struct StartInput { /// Wait until the output reports active. #[serde(default)] pub wait: bool, + /// Auto-wait deadline in milliseconds. + #[serde(default = "super::waiting::default_timeout_ms")] + pub timeout_ms: u64, /// Enable the paired microphone before a stopped output starts. #[serde(default = "enabled")] pub audio_enabled: bool, @@ -29,6 +32,7 @@ impl Default for StartInput { fn default() -> Self { Self { wait: false, + timeout_ms: super::waiting::DEFAULT_TIMEOUT_MS, audio_enabled: true, audio_track: 1, } diff --git a/rust/obs-mcp/src/tools/mod.rs b/rust/obs-mcp/src/tools/mod.rs index 9062a25e94..a81e5db32b 100644 --- a/rust/obs-mcp/src/tools/mod.rs +++ b/rust/obs-mcp/src/tools/mod.rs @@ -41,6 +41,7 @@ pub fn schema_snapshot() -> serde_json::Value { tools.extend(outputs::schemas()); tools.extend(screenshot::schemas()); tools.extend(control::schemas()); + tools.extend(waiting::schemas()); tools.sort_by(|a, b| a["name"].as_str().cmp(&b["name"].as_str())); serde_json::json!({"tools": tools, "toolError": schemars::schema_for!(crate::server::ToolError)}) } diff --git a/rust/obs-mcp/src/tools/outputs.rs b/rust/obs-mcp/src/tools/outputs.rs index 230f86d5e8..f3492917d9 100644 --- a/rust/obs-mcp/src/tools/outputs.rs +++ b/rust/obs-mcp/src/tools/outputs.rs @@ -41,6 +41,41 @@ pub struct OutputStatus { /// Methods take `&self`: libobs owns the state, so implementations use their /// own interior mutability. pub trait OutputBackend { + /// Whether the owning control host is shutting down. + fn control_cancelled(&self) -> bool { + false + } + /// Starts with optional bounded auto-wait. + /// # Errors + /// Reports start failure or an auto-wait timeout. + fn start_with_wait(&self, request: OutputStartRequest) -> Result { + use super::waiting::{SystemClock, WaitClock, validate_timeout}; + if request.options.wait { + validate_timeout(request.options.timeout_ms)?; + } + if self.control_cancelled() { + return Err(ToolError::not_ready("OBS control is shutting down")); + } + let state = self.start_output(OutputRequest { kind: request.kind })?; + if !request.options.wait { + return Ok(state); + } + let clock = SystemClock::default(); + loop { + if self.control_cancelled() { + return Err(ToolError::not_ready("OBS control is shutting down")); + } + if self.status(request.kind).active { + return Ok(ActiveOutput { active: true }); + } + let elapsed = clock.now_ms(); + if elapsed >= request.options.timeout_ms { + return Err(ToolError::not_ready("output start timed out")); + } + clock.wait_ms((request.options.timeout_ms - elapsed).min(10)); + } + } + /// Typed idempotent start. /// # Errors /// Reports a processing failure. @@ -94,13 +129,14 @@ typed_tool!( RecordStart, "record_start", OutputBackend, - EmptyInput, + OutputStartInput, ActiveOutput, IDEMPOTENT, "Start recording.", - |backend, _input| { - backend.start_output(OutputRequest { + |backend, input| { + backend.start_with_wait(OutputStartRequest { kind: OutputKind::Record, + options: input, }) } ); @@ -136,13 +172,14 @@ typed_tool!( StreamStart, "stream_start", OutputBackend, - EmptyInput, + OutputStartInput, ActiveOutput, IDEMPOTENT, "Start streaming.", - |backend, _input| { - backend.start_output(OutputRequest { + |backend, input| { + backend.start_with_wait(OutputStartRequest { kind: OutputKind::Stream, + options: input, }) } ); @@ -216,3 +253,30 @@ pub struct OutputRequest { /// Output to operate on. pub kind: OutputKind, } + +/// Auto-wait options for recording/streaming starts. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct OutputStartInput { + /// Wait for the output to report active. + #[serde(default)] + pub wait: bool, + /// Bounded wait deadline. + #[serde(default = "super::waiting::default_timeout_ms")] + pub timeout_ms: u64, +} +impl Default for OutputStartInput { + fn default() -> Self { + Self { + wait: false, + timeout_ms: super::waiting::DEFAULT_TIMEOUT_MS, + } + } +} +/// Backend start request. +pub struct OutputStartRequest { + /// Output selector. + pub kind: OutputKind, + /// Auto-wait options. + pub options: OutputStartInput, +} diff --git a/rust/obs-mcp/src/tools/waiting.rs b/rust/obs-mcp/src/tools/waiting.rs index b0d13a0fb1..bfa8d9da52 100644 --- a/rust/obs-mcp/src/tools/waiting.rs +++ b/rust/obs-mcp/src/tools/waiting.rs @@ -1,8 +1,8 @@ //! Bounded typed waits, with a deterministic clock seam (#4447). +use super::control::MediaState; +use crate::server::ToolError; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -use crate::server::ToolError; -use super::control::MediaState; /// Default auto-wait deadline. pub const DEFAULT_TIMEOUT_MS: u64 = 5000; @@ -10,92 +10,142 @@ pub const DEFAULT_TIMEOUT_MS: u64 = 5000; pub const MAX_TIMEOUT_MS: u64 = 300_000; /// Default timeout used by serde and fluent clients. #[must_use] -pub fn default_timeout_ms() -> u64 { DEFAULT_TIMEOUT_MS } +pub fn default_timeout_ms() -> u64 { + DEFAULT_TIMEOUT_MS +} /// An output controlled by OBS. #[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema)] -#[serde(rename_all="snake_case")] -pub enum OutputName { /// Recording. -Record, /// Streaming. -Stream, /// Virtual Camera. -Vcam, /// Paired virtual microphone. -Vmic } +#[serde(rename_all = "snake_case")] +pub enum OutputName { + /// Recording. + Record, + /// Streaming. + Stream, + /// Virtual Camera. + Vcam, + /// Paired virtual microphone. + Vmic, +} /// Desired output state. #[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema)] -#[serde(rename_all="snake_case")] -pub enum OutputState { /// Running. -Active, /// Stopped. -Inactive } +#[serde(rename_all = "snake_case")] +pub enum OutputState { + /// Running. + Active, + /// Stopped. + Inactive, +} /// A supported numeric metric, never an expression. #[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema)] -#[serde(rename_all="snake_case")] -pub enum Metric { /// Average render duration. -RenderFrameTimeNs, /// Render drops since baseline. -RenderFramesDropped, /// Camera maximum measured stage latency. -VcamLatencyMaxNs, /// Microphone maximum measured stage latency. -VmicLatencyMaxNs, /// Microphone xruns, if measured. -VmicXruns, /// Absolute independently measured sync offset. -AvOffsetAbsMs } +#[serde(rename_all = "snake_case")] +pub enum Metric { + /// Average render duration. + RenderFrameTimeNs, + /// Render drops since baseline. + RenderFramesDropped, + /// Camera maximum measured stage latency. + VcamLatencyMaxNs, + /// Microphone maximum measured stage latency. + VmicLatencyMaxNs, + /// Microphone xruns, if measured. + VmicXruns, + /// Absolute independently measured sync offset. + AvOffsetAbsMs, +} /// Explicit condition language, rejecting unknown fields. #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] -#[serde(tag="type",rename_all="snake_case",deny_unknown_fields)] +#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] pub enum Condition { /// Wait for an output to reach a state. - OutputState { /// Output selector. - output: OutputName, /// Desired state. - state: OutputState }, + OutputState { + /// Output selector. + output: OutputName, + /// Desired state. + state: OutputState, + }, /// Wait until a source exists and is active. - SourceActive { /// Source name. - name: String }, + SourceActive { + /// Source name. + name: String, + }, /// Wait for a named media source's state. - MediaState { /// Source name. - name: String, /// Desired media state. - state: MediaState }, + MediaState { + /// Source name. + name: String, + /// Desired media state. + state: MediaState, + }, /// Wait until a measured metric is at most the threshold. - StatAtMost { /// Metric selector. - metric: Metric, /// Maximum acceptable value, in the metric's units. - value: f64 }, + StatAtMost { + /// Metric selector. + metric: Metric, + /// Maximum acceptable value, in the metric's units. + value: f64, + }, } /// One wait request. #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] -pub struct WaitInput { /// Condition to observe before waiting. - pub condition: Condition, /// Deadline in milliseconds; zero still observes once. - #[serde(default="default_timeout_ms")] - pub timeout_ms: u64 } +pub struct WaitInput { + /// Condition to observe before waiting. + pub condition: Condition, + /// Deadline in milliseconds; zero still observes once. + #[serde(default = "default_timeout_ms")] + pub timeout_ms: u64, +} /// Typed final observation, including unavailable measurements. #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] -#[serde(tag="kind",rename_all="snake_case")] +#[serde(tag = "kind", rename_all = "snake_case")] pub enum LastValue { /// Output observation. - Output { /// Null if the output state cannot be queried. - active: Option }, + Output { + /// Null if the output state cannot be queried. + active: Option, + }, /// Source observation. - Source { /// Whether the source exists. - present: bool, /// Whether it is active. - active: bool }, + Source { + /// Whether the source exists. + present: bool, + /// Whether it is active. + active: bool, + }, /// Media observation. - Media { /// Null if the named source is absent. - state: Option }, + Media { + /// Null if the named source is absent. + state: Option, + }, /// Numeric observation. - Stat { /// Metric selector. - metric: Metric, /// Null if unavailable; never satisfies a threshold. - value: Option }, + Stat { + /// Metric selector. + metric: Metric, + /// Null if unavailable; never satisfies a threshold. + value: Option, + }, } /// Result of one observation. #[derive(Clone, Debug)] -pub struct Observation { /// Whether the condition is met. - pub satisfied: bool, /// Typed current value. - pub value: LastValue } +pub struct Observation { + /// Whether the condition is met. + pub satisfied: bool, + /// Typed current value. + pub value: LastValue, +} /// Final wait result. #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] -pub struct WaitOutput { /// Condition met before the deadline. - pub satisfied: bool, /// Monotonic elapsed time. - pub elapsed_ms: u64, /// Last observed value, including on timeout. - pub last_value: LastValue } +pub struct WaitOutput { + /// Condition met before the deadline. + pub satisfied: bool, + /// Monotonic elapsed time. + pub elapsed_ms: u64, + /// Last observed value, including on timeout. + pub last_value: LastValue, +} /// Backend request for a single observation. #[derive(Clone, Debug)] -pub struct ObserveInput { /// Condition to evaluate. - pub condition: Condition } +pub struct ObserveInput { + /// Condition to evaluate. + pub condition: Condition, +} /// Backend seam, reusable for automatic waits. pub trait WaitBackend { /// Observe without waiting. @@ -103,16 +153,103 @@ pub trait WaitBackend { /// Reports an unavailable subsystem or failed query. fn observe(&self, request: &ObserveInput) -> Result; /// Shutdown cancellation is checked before accessing libobs. - fn cancelled(&self) -> bool { false } + fn cancelled(&self) -> bool { + false + } } /// Monotonic clock and bounded parking; tests do not sleep. -pub trait WaitClock { /// Monotonic time in milliseconds. - fn now_ms(&self) -> u64; /// Wait for at most the supplied interval. - fn wait_ms(&self, milliseconds: u64); } +pub trait WaitClock { + /// Monotonic time in milliseconds. + fn now_ms(&self) -> u64; + /// Wait for at most the supplied interval. + fn wait_ms(&self, milliseconds: u64); +} /// Evaluate first, then wait within the deadline. /// # Errors /// Reports backend failure, cancellation or an excessive timeout. -pub fn run_wait(backend: &B, request: WaitInput, clock: &C) -> Result { - let _ = (backend, request, clock); - todo!("bounded condition wait") +pub fn run_wait( + backend: &B, + request: WaitInput, + clock: &C, +) -> Result { + validate_timeout(request.timeout_ms)?; + if let Condition::StatAtMost { value, .. } = &request.condition + && !value.is_finite() + { + return Err(ToolError::wrong_state("metric threshold must be finite")); + } + let start = clock.now_ms(); + let observation = ObserveInput { + condition: request.condition, + }; + loop { + if backend.cancelled() { + return Err(ToolError::not_ready("OBS control is shutting down")); + } + let current = backend.observe(&observation)?; + let elapsed_ms = clock.now_ms().saturating_sub(start); + if current.satisfied || elapsed_ms >= request.timeout_ms { + return Ok(WaitOutput { + satisfied: current.satisfied, + elapsed_ms, + last_value: current.value, + }); + } + clock.wait_ms((request.timeout_ms - elapsed_ms).min(10)); + } +} + +/// Reject excessive deadlines before an operation changes OBS state. +/// # Errors +/// Returns a domain error when the timeout exceeds the bound. +pub fn validate_timeout(timeout_ms: u64) -> Result<(), ToolError> { + if timeout_ms > MAX_TIMEOUT_MS { + Err(ToolError::wrong_state("timeout_ms must be at most 300000")) + } else { + Ok(()) + } +} +/// Production monotonic clock. Parking is bounded and cancellation is rechecked. +pub struct SystemClock(std::time::Instant); +impl Default for SystemClock { + fn default() -> Self { + Self(std::time::Instant::now()) + } +} +impl WaitClock for SystemClock { + fn now_ms(&self) -> u64 { + u64::try_from(self.0.elapsed().as_millis()).unwrap_or(u64::MAX) + } + fn wait_ms(&self, milliseconds: u64) { + std::thread::park_timeout(std::time::Duration::from_millis(milliseconds)); + } +} +use crate::server::ToolRegistry; +use std::rc::Rc; +typed_tool!( + WaitTool, + "wait_for", + WaitBackend, + WaitInput, + WaitOutput, + READ_ONLY, + "Observe a typed condition immediately, then wait within timeout_ms. Returns the final typed value on timeout; unavailable metrics never satisfy a threshold.", + |backend, input| { run_wait(backend.as_ref(), input, &SystemClock::default()) } +); +/// Registers the wait domain. +pub fn register(registry: &mut ToolRegistry, backend: &Rc) { + registry.register(Box::new(WaitTool { + backend: Rc::clone(backend), + })); +} +/// Generated tool contract. +#[must_use] +pub fn schemas() -> Vec { + vec![crate::server::tool_schema::()] +} + +/// Unknown or non-finite metrics never satisfy a numeric condition. +#[must_use] +pub fn metric_at_most(value: Option, threshold: f64) -> bool { + threshold.is_finite() && value.is_some_and(|value| value.is_finite() && value <= threshold) } diff --git a/rust/obs-mcp/tests/mcp/outputs.rs b/rust/obs-mcp/tests/mcp/outputs.rs index 03cd01df20..7e89cdbcb8 100644 --- a/rust/obs-mcp/tests/mcp/outputs.rs +++ b/rust/obs-mcp/tests/mcp/outputs.rs @@ -106,7 +106,11 @@ fn lists_six_tools_with_empty_object_schemas() { } assert_eq!(t["inputSchema"]["type"], "object"); - assert_eq!(t["inputSchema"]["properties"], json!({})); + if t["name"].as_str().unwrap().ends_with("start") { + assert!(t["inputSchema"]["properties"].get("wait").is_some()); + } else { + assert_eq!(t["inputSchema"]["properties"], json!({})); + } assert_eq!(t["inputSchema"]["additionalProperties"], false); assert!(!t["description"].as_str().unwrap().is_empty()); } diff --git a/rust/obs-mcp/tests/mcp/waiting.rs b/rust/obs-mcp/tests/mcp/waiting.rs index bf4a888761..b7a3a04b14 100644 --- a/rust/obs-mcp/tests/mcp/waiting.rs +++ b/rust/obs-mcp/tests/mcp/waiting.rs @@ -1,34 +1,124 @@ //! Deterministic wait contract (#4447), using no sleeps or own threads. -use std::cell::Cell; use obs_mcp::server::ToolError; use obs_mcp::tools::control::MediaState; -use obs_mcp::tools::waiting::{Condition, LastValue, Observation, ObserveInput, WaitBackend, WaitClock, WaitInput, run_wait}; +use obs_mcp::tools::waiting::{ + Condition, LastValue, Observation, ObserveInput, WaitBackend, WaitClock, WaitInput, run_wait, +}; +use std::cell::Cell; #[derive(Default)] struct Clock(Cell); impl WaitClock for Clock { - fn now_ms(&self) -> u64 { self.0.get() } - fn wait_ms(&self, ms:u64) { self.0.set(self.0.get()+ms); } + fn now_ms(&self) -> u64 { + self.0.get() + } + fn wait_ms(&self, ms: u64) { + self.0.set(self.0.get() + ms); + } +} +struct Backend<'a> { + clock: &'a Clock, + ready_at: u64, + observations: Cell, } -struct Backend<'a> { clock: &'a Clock, ready_at: u64, observations: Cell } impl WaitBackend for Backend<'_> { - fn observe(&self,_:&ObserveInput)->Result { - self.observations.set(self.observations.get()+1); - let ready = self.clock.now_ms()>=self.ready_at; - Ok(Observation { satisfied:ready, value:LastValue::Media {state:Some(if ready {MediaState::Playing} else {MediaState::Opening})} }) + fn observe(&self, _: &ObserveInput) -> Result { + self.observations.set(self.observations.get() + 1); + let ready = self.clock.now_ms() >= self.ready_at; + Ok(Observation { + satisfied: ready, + value: LastValue::Media { + state: Some(if ready { + MediaState::Playing + } else { + MediaState::Opening + }), + }, + }) + } +} +fn input(timeout_ms: u64) -> WaitInput { + WaitInput { + condition: Condition::MediaState { + name: "clip".into(), + state: MediaState::Playing, + }, + timeout_ms, } } -fn input(timeout_ms:u64)->WaitInput { WaitInput { condition:Condition::MediaState {name:"clip".into(),state:MediaState::Playing}, timeout_ms } } #[test] fn already_satisfied_zero_timeout_observes_without_waiting() { - let clock=Clock::default();let backend=Backend{clock:&clock,ready_at:0,observations:Cell::new(0)}; - let result=run_wait(&backend,input(0),&clock).unwrap(); - assert!(result.satisfied); assert_eq!(result.elapsed_ms,0); assert_eq!(backend.observations.get(),1); + let clock = Clock::default(); + let backend = Backend { + clock: &clock, + ready_at: 0, + observations: Cell::new(0), + }; + let result = run_wait(&backend, input(0), &clock).unwrap(); + assert!(result.satisfied); + assert_eq!(result.elapsed_ms, 0); + assert_eq!(backend.observations.get(), 1); } #[test] fn transition_and_timeout_preserve_last_observation() { - let clock=Clock::default();let backend=Backend{clock:&clock,ready_at:20,observations:Cell::new(0)}; - let result=run_wait(&backend,input(100),&clock).unwrap();assert!(result.satisfied);assert_eq!(result.elapsed_ms,20); - let clock=Clock::default();let backend=Backend{clock:&clock,ready_at:100,observations:Cell::new(0)}; - let result=run_wait(&backend,input(15),&clock).unwrap();assert!(!result.satisfied);assert_eq!(result.elapsed_ms,15); - assert!(matches!(result.last_value,LastValue::Media {state:Some(MediaState::Opening)})); + let clock = Clock::default(); + let backend = Backend { + clock: &clock, + ready_at: 20, + observations: Cell::new(0), + }; + let result = run_wait(&backend, input(100), &clock).unwrap(); + assert!(result.satisfied); + assert_eq!(result.elapsed_ms, 20); + let clock = Clock::default(); + let backend = Backend { + clock: &clock, + ready_at: 100, + observations: Cell::new(0), + }; + let result = run_wait(&backend, input(15), &clock).unwrap(); + assert!(!result.satisfied); + assert_eq!(result.elapsed_ms, 15); + assert!(matches!( + result.last_value, + LastValue::Media { + state: Some(MediaState::Opening) + } + )); +} + +#[test] +fn cancellation_and_excessive_deadlines_do_not_touch_backend() { + struct Cancelled; + impl WaitBackend for Cancelled { + fn cancelled(&self) -> bool { + true + } + fn observe(&self, _: &ObserveInput) -> Result { + panic!("cancelled host must not be queried") + } + } + let clock = Clock::default(); + assert_eq!( + run_wait(&Cancelled, input(100), &clock).unwrap_err().code, + 207 + ); + let backend = Backend { + clock: &clock, + ready_at: 0, + observations: Cell::new(0), + }; + assert_eq!( + run_wait(&backend, input(300001), &clock).unwrap_err().code, + 604 + ); + assert_eq!(backend.observations.get(), 0); +} +#[test] +fn unmeasured_metrics_cannot_pass_a_threshold() { + use obs_mcp::tools::waiting::metric_at_most; + assert!(!metric_at_most(None, 1000.0)); + assert!(!metric_at_most(Some(f64::NAN), 1000.0)); + assert!(!metric_at_most(Some(1.0), f64::NAN)); + assert!(metric_at_most(Some(5.0), 5.0)); + assert!(!metric_at_most(Some(5.1), 5.0)); } From 52134981ce73361a440a748f185fe0096432c87f Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 15:23:17 -0800 Subject: [PATCH 12/39] fix(mcp): reject late condition satisfaction after oversleep (#4447) --- rust/obs-mcp/src/tools/outputs.rs | 61 ++++++++++++++++++++++++------- rust/obs-mcp/src/tools/waiting.rs | 8 +++- rust/obs-mcp/tests/mcp/waiting.rs | 33 +++++++++++++++++ 3 files changed, 86 insertions(+), 16 deletions(-) diff --git a/rust/obs-mcp/src/tools/outputs.rs b/rust/obs-mcp/src/tools/outputs.rs index f3492917d9..5899e5e4c7 100644 --- a/rust/obs-mcp/src/tools/outputs.rs +++ b/rust/obs-mcp/src/tools/outputs.rs @@ -49,7 +49,9 @@ pub trait OutputBackend { /// # Errors /// Reports start failure or an auto-wait timeout. fn start_with_wait(&self, request: OutputStartRequest) -> Result { - use super::waiting::{SystemClock, WaitClock, validate_timeout}; + use super::waiting::{ + Condition, OutputName, OutputState, SystemClock, WaitInput, run_wait, validate_timeout, + }; if request.options.wait { validate_timeout(request.options.timeout_ms)?; } @@ -60,19 +62,28 @@ pub trait OutputBackend { if !request.options.wait { return Ok(state); } - let clock = SystemClock::default(); - loop { - if self.control_cancelled() { - return Err(ToolError::not_ready("OBS control is shutting down")); - } - if self.status(request.kind).active { - return Ok(ActiveOutput { active: true }); - } - let elapsed = clock.now_ms(); - if elapsed >= request.options.timeout_ms { - return Err(ToolError::not_ready("output start timed out")); - } - clock.wait_ms((request.options.timeout_ms - elapsed).min(10)); + let output = match request.kind { + OutputKind::Record => OutputName::Record, + OutputKind::Stream => OutputName::Stream, + }; + let result = run_wait( + &OutputWait { + backend: self, + kind: request.kind, + }, + WaitInput { + condition: Condition::OutputState { + output, + state: OutputState::Active, + }, + timeout_ms: request.options.timeout_ms, + }, + &SystemClock::default(), + )?; + if result.satisfied { + Ok(ActiveOutput { active: true }) + } else { + Err(ToolError::not_ready("output start timed out")) } } @@ -280,3 +291,25 @@ pub struct OutputStartRequest { /// Auto-wait options. pub options: OutputStartInput, } + +struct OutputWait<'a, B: OutputBackend + ?Sized> { + backend: &'a B, + kind: OutputKind, +} +impl super::waiting::WaitBackend for OutputWait<'_, B> { + fn cancelled(&self) -> bool { + self.backend.control_cancelled() + } + fn observe( + &self, + _: &super::waiting::ObserveInput, + ) -> Result { + let active = self.backend.status(self.kind).active; + Ok(super::waiting::Observation { + satisfied: active, + value: super::waiting::LastValue::Output { + active: Some(active), + }, + }) + } +} diff --git a/rust/obs-mcp/src/tools/waiting.rs b/rust/obs-mcp/src/tools/waiting.rs index bfa8d9da52..50553e9044 100644 --- a/rust/obs-mcp/src/tools/waiting.rs +++ b/rust/obs-mcp/src/tools/waiting.rs @@ -182,19 +182,23 @@ pub fn run_wait( let observation = ObserveInput { condition: request.condition, }; + let mut initial = true; loop { if backend.cancelled() { return Err(ToolError::not_ready("OBS control is shutting down")); } let current = backend.observe(&observation)?; let elapsed_ms = clock.now_ms().saturating_sub(start); - if current.satisfied || elapsed_ms >= request.timeout_ms { + let satisfied = current.satisfied + && (elapsed_ms <= request.timeout_ms || (initial && request.timeout_ms == 0)); + if satisfied || elapsed_ms >= request.timeout_ms { return Ok(WaitOutput { - satisfied: current.satisfied, + satisfied, elapsed_ms, last_value: current.value, }); } + initial = false; clock.wait_ms((request.timeout_ms - elapsed_ms).min(10)); } } diff --git a/rust/obs-mcp/tests/mcp/waiting.rs b/rust/obs-mcp/tests/mcp/waiting.rs index b7a3a04b14..700e5a5bc1 100644 --- a/rust/obs-mcp/tests/mcp/waiting.rs +++ b/rust/obs-mcp/tests/mcp/waiting.rs @@ -122,3 +122,36 @@ fn unmeasured_metrics_cannot_pass_a_threshold() { assert!(metric_at_most(Some(5.0), 5.0)); assert!(!metric_at_most(Some(5.1), 5.0)); } + +#[test] +fn scheduler_oversleep_cannot_turn_a_timeout_into_success() { + struct Oversleep(Cell); + impl WaitClock for Oversleep { + fn now_ms(&self) -> u64 { + self.0.get() + } + fn wait_ms(&self, ms: u64) { + self.0.set(self.0.get() + ms + 10); + } + } + struct Late<'a>(&'a Oversleep); + impl WaitBackend for Late<'_> { + fn observe(&self, _: &ObserveInput) -> Result { + let active = self.0.now_ms() >= 15; + Ok(Observation { + satisfied: active, + value: LastValue::Output { + active: Some(active), + }, + }) + } + } + let clock = Oversleep(Cell::new(0)); + let result = run_wait(&Late(&clock), input(10), &clock).unwrap(); + assert!(!result.satisfied); + assert_eq!(result.elapsed_ms, 20); + assert!(matches!( + result.last_value, + LastValue::Output { active: Some(true) } + )); +} From 3b160737f08d291d46c14ffdb716ff24f7838e1a Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 15:28:03 -0800 Subject: [PATCH 13/39] test(mcp): RED local endpoint contract (#4448) --- rust/obs-mcp/src/lib.rs | 2 ++ rust/obs-mcp/src/platform/mod.rs | 5 +++++ rust/obs-mcp/tests/mcp/main.rs | 2 ++ rust/obs-mcp/tests/mcp/transport.rs | 6 ++++++ 4 files changed, 15 insertions(+) create mode 100644 rust/obs-mcp/src/platform/mod.rs create mode 100644 rust/obs-mcp/tests/mcp/transport.rs diff --git a/rust/obs-mcp/src/lib.rs b/rust/obs-mcp/src/lib.rs index 41e611852a..5279e4f382 100644 --- a/rust/obs-mcp/src/lib.rs +++ b/rust/obs-mcp/src/lib.rs @@ -40,3 +40,5 @@ use std::io::{self, BufRead, Write}; pub fn serve(reader: R, writer: W) -> io::Result<()> { server::Server::new().serve(reader, writer) } + +pub mod platform; diff --git a/rust/obs-mcp/src/platform/mod.rs b/rust/obs-mcp/src/platform/mod.rs new file mode 100644 index 0000000000..512aa85d89 --- /dev/null +++ b/rust/obs-mcp/src/platform/mod.rs @@ -0,0 +1,5 @@ +//! Owner-only local control transport. +use std::{io, path::PathBuf}; +#[derive(Clone, Debug, Default)] +pub struct EndpointOptions { pub socket: Option } +pub fn endpoint(options: &EndpointOptions) -> io::Result { todo!("endpoint: {options:?}") } diff --git a/rust/obs-mcp/tests/mcp/main.rs b/rust/obs-mcp/tests/mcp/main.rs index 5e6bdfe826..91c270fa13 100644 --- a/rust/obs-mcp/tests/mcp/main.rs +++ b/rust/obs-mcp/tests/mcp/main.rs @@ -29,3 +29,5 @@ mod typed; mod control; mod waiting; + +mod transport; diff --git a/rust/obs-mcp/tests/mcp/transport.rs b/rust/obs-mcp/tests/mcp/transport.rs new file mode 100644 index 0000000000..3adabaa1f0 --- /dev/null +++ b/rust/obs-mcp/tests/mcp/transport.rs @@ -0,0 +1,6 @@ +use obs_mcp::platform::{endpoint, EndpointOptions}; +#[test] +fn explicit_endpoint_is_preserved() { + let path = std::path::PathBuf::from("/test/control.sock"); + assert_eq!(endpoint(&EndpointOptions { socket:Some(path.clone()) }).unwrap(), path); +} From 37546706074db2c890fe2b052d20acd739b48400 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 15:40:07 -0800 Subject: [PATCH 14/39] feat(mcp): attach to running OBS through private control sockets (#4448) --- Cargo.lock | 10 +- ci/shared-build-files.txt | 3 + docs/features.md | 3 + docs/rust-port/control-api.md | 20 ++ local-gate.toml | 2 +- rust/obs-data/Cargo.toml | 1 + rust/obs-mcp-module/Cargo.toml | 18 ++ rust/obs-mcp-module/build.rs | 5 + rust/obs-mcp-module/src/ffi/mod.rs | 27 +++ rust/obs-mcp-module/src/lib.rs | 5 + rust/obs-mcp-module/src/platform/link.rs | 6 + rust/obs-mcp-module/src/platform/mod.rs | 4 + rust/obs-mcp-module/src/platform/unix.rs | 241 +++++++++++++++++++++ rust/obs-mcp/Cargo.toml | 5 +- rust/obs-mcp/src/backend/mod.rs | 41 +++- rust/obs-mcp/src/ffi/control.rs | 13 +- rust/obs-mcp/src/host.rs | 33 ++- rust/obs-mcp/src/platform/mod.rs | 29 ++- rust/obs-mcp/src/platform/unix.rs | 257 +++++++++++++++++++++++ rust/obs-mcp/src/platform/unsupported.rs | 37 ++++ rust/obs-mcp/tests/mcp/transport.rs | 103 ++++++++- rust/obs-studio-rust/Cargo.toml | 4 +- rust/obs-studio-rust/src/main.rs | 26 ++- rust/obs-studio-rust/src/mcp.rs | 17 ++ 24 files changed, 879 insertions(+), 31 deletions(-) create mode 100644 rust/obs-mcp-module/Cargo.toml create mode 100644 rust/obs-mcp-module/build.rs create mode 100644 rust/obs-mcp-module/src/ffi/mod.rs create mode 100644 rust/obs-mcp-module/src/lib.rs create mode 100644 rust/obs-mcp-module/src/platform/link.rs create mode 100644 rust/obs-mcp-module/src/platform/mod.rs create mode 100644 rust/obs-mcp-module/src/platform/unix.rs create mode 100644 rust/obs-mcp/src/platform/unix.rs create mode 100644 rust/obs-mcp/src/platform/unsupported.rs diff --git a/Cargo.lock b/Cargo.lock index 41ac77bbf1..2a14f76eb9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -599,6 +599,7 @@ dependencies = [ "schemars", "serde", "serde_json", + "tempfile", ] [[package]] @@ -658,7 +659,6 @@ dependencies = [ "base64", "flate2", "libc", - "obs-callback", "obs-sys", "schemars", "serde", @@ -666,6 +666,14 @@ dependencies = [ "serde_path_to_error", ] +[[package]] +name = "obs-mcp-module" +version = "0.1.0" +dependencies = [ + "libloading", + "obs-mcp", +] + [[package]] name = "obs-media-io" version = "0.1.0" diff --git a/ci/shared-build-files.txt b/ci/shared-build-files.txt index a9ea465a80..9333f8c4e3 100644 --- a/ci/shared-build-files.txt +++ b/ci/shared-build-files.txt @@ -86,6 +86,9 @@ rust/obs-exit-watchdog/src/platform/mod.rs # new crate's platform boundary (#406 rust/obs-gpu-status/src/platform/mod.rs rust/obs-graphics/src/platform/mod.rs rust/obs-hotkey/build.rs +rust/obs-mcp-module/build.rs # Control transport/platform selector; native module ABI requires cross-platform checks (#4448). +rust/obs-mcp-module/src/platform/mod.rs # Control transport/platform selector; native module ABI requires cross-platform checks (#4448). +rust/obs-mcp/src/platform/mod.rs # Control transport/platform selector; native module ABI requires cross-platform checks (#4448). rust/obs-media-io/src/platform/mod.rs rust/obs-nvenc/src/platform/mod.rs rust/obs-preflight/src/platform/mod.rs diff --git a/docs/features.md b/docs/features.md index bf17fea8a2..5c77ece973 100644 --- a/docs/features.md +++ b/docs/features.md @@ -3066,3 +3066,6 @@ area. *All platforms*, 2026-11-02. Follows [#3491](https://github.com/obs-rust/obs-studio/pull/3491), epic [#3283](https://github.com/obs-rust/obs-studio/issues/3283). + +- **Control socket** (#4456): private Unix MCP endpoint, `--mcp-attach` stdio proxy, + and an in-app frontend module that controls the existing OBS instance. diff --git a/docs/rust-port/control-api.md b/docs/rust-port/control-api.md index 07f07efaec..37a247adfe 100644 --- a/docs/rust-port/control-api.md +++ b/docs/rust-port/control-api.md @@ -51,3 +51,23 @@ Rust client and ci/vcam_av_sync.py MCP transport. Each slice targets master from a fresh infra/control-api-* branch with RED then GREEN shared MCP tests. The client reuses server types; Python retains websocket and adds --transport mcp plus fallback. Real GUI/device validation runs only in bosn containers. + +## Attach to the application + +Build `soldr cargo build -p obs-mcp-module` and install the resulting +`libobs_mcp_module.so` in OBS's normal module search path. The module binds +`$XDG_RUNTIME_DIR/obs-studio-rust/control.sock` with mode 0600 in a private +directory. It shares the app's libobs and stops its worker on frontend EXIT, +prior to libobs shutdown. It never starts a second OBS instance. + +`obs-studio-rust --mcp-attach [socket]` relays stdio to that instance. The same +newline JSON-RPC Server handles both transports. At most 32 clients share the +control thread; requests are serial, bounded to 16 MiB per buffered frame. +`wait_for` blocks the control thread, while OBS render/audio threads continue. +Windows named pipes are unsupported pending #4455. + +For headless CI use `obs-studio-rust --mcp-listen [socket]` (native build). +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. diff --git a/local-gate.toml b/local-gate.toml index 88e3d73760..0304c8e9ba 100644 --- a/local-gate.toml +++ b/local-gate.toml @@ -94,7 +94,7 @@ exclude = [ "docs/**", "**/*.md", "build-aux/**", "libobs-d3d11/**", "libobs-metal/**", "libobs-winrt/**", "additional_install_files/**", "tools/**", "ci/**", ".github/**", ".claude/**", "rust/*/tests/**", "rust/*/benches/**", "rust/*/examples/**", "rust/obs-c-oracle/**", "rust/obs-camera-busy/**", "rust/obs-exit-watchdog/**", - "rust/obs-fallback-warning/**", "rust/obs-gpu-status/**", "rust/obs-frontend/**", + "rust/obs-mcp-module/**", "rust/obs-fallback-warning/**", "rust/obs-gpu-status/**", "rust/obs-frontend/**", ] keep = ["rust/*/Cargo.toml", "rust/obs-mcp/tests/**", "rust/obs-studio-rust/tests/**", "rust/obs-sys/tests/**"] diff --git a/rust/obs-data/Cargo.toml b/rust/obs-data/Cargo.toml index 9a6ea0ae8b..28e9662d3b 100644 --- a/rust/obs-data/Cargo.toml +++ b/rust/obs-data/Cargo.toml @@ -21,6 +21,7 @@ libc = { workspace = true, default-features = true } cc = { workspace = true, default-features = true, features = ["parallel"] } [dev-dependencies] +tempfile = { workspace = true, default-features = true } schemars = { workspace = true, features = ["derive", "std"] } serde = { workspace = true, features = ["derive"] } obs-audio-monitoring = { path = "../obs-audio-monitoring" } diff --git a/rust/obs-mcp-module/Cargo.toml b/rust/obs-mcp-module/Cargo.toml new file mode 100644 index 0000000000..702055e1e9 --- /dev/null +++ b/rust/obs-mcp-module/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "obs-mcp-module" +version = "0.1.0" +description = "In-app local control module for OBS" +autotests = false +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true +[lib] +crate-type = ["cdylib"] +test = false +doctest = false +[lints] +workspace = true +[target.'cfg(unix)'.dependencies] +obs-mcp = { path = "../obs-mcp", features = ["libobs"] } +libloading = { workspace = true, default-features = true } diff --git a/rust/obs-mcp-module/build.rs b/rust/obs-mcp-module/build.rs new file mode 100644 index 0000000000..0bcc36074d --- /dev/null +++ b/rust/obs-mcp-module/build.rs @@ -0,0 +1,5 @@ +#[path = "src/platform/link.rs"] +mod link; +fn main() { + link::configure(); +} diff --git a/rust/obs-mcp-module/src/ffi/mod.rs b/rust/obs-mcp-module/src/ffi/mod.rs new file mode 100644 index 0000000000..5494bfa082 --- /dev/null +++ b/rust/obs-mcp-module/src/ffi/mod.rs @@ -0,0 +1,27 @@ +use std::ffi::{c_char, c_void}; +#[unsafe(no_mangle)] +pub extern "C" fn obs_module_ver() -> u32 { + crate::platform::version() +} +#[unsafe(no_mangle)] +pub extern "C" fn obs_module_set_pointer(_: *mut c_void) {} +#[unsafe(no_mangle)] +pub extern "C" fn obs_module_load() -> bool { + crate::platform::load() +} +#[unsafe(no_mangle)] +pub extern "C" fn obs_module_unload() { + crate::platform::unload(); +} +#[unsafe(no_mangle)] +pub extern "C" fn obs_module_name() -> *const c_char { + c"OBS Control API".as_ptr() +} +#[unsafe(no_mangle)] +pub extern "C" fn obs_module_description() -> *const c_char { + c"Owner-only MCP socket for the running OBS instance".as_ptr() +} +#[unsafe(no_mangle)] +pub extern "C" fn obs_module_author() -> *const c_char { + c"obs-rust".as_ptr() +} diff --git a/rust/obs-mcp-module/src/lib.rs b/rust/obs-mcp-module/src/lib.rs new file mode 100644 index 0000000000..55d7fe2b98 --- /dev/null +++ b/rust/obs-mcp-module/src/lib.rs @@ -0,0 +1,5 @@ +//! Loadable OBS frontend control module. It never starts or shuts down libobs. +#![deny(unsafe_code)] +#[allow(unsafe_code, reason = "OBS module C ABI exports")] +mod ffi; +mod platform; diff --git a/rust/obs-mcp-module/src/platform/link.rs b/rust/obs-mcp-module/src/platform/link.rs new file mode 100644 index 0000000000..9000e24d17 --- /dev/null +++ b/rust/obs-mcp-module/src/platform/link.rs @@ -0,0 +1,6 @@ +pub fn configure() { + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") { + println!("cargo:rustc-link-arg=-undefined"); + println!("cargo:rustc-link-arg=dynamic_lookup"); + } +} diff --git a/rust/obs-mcp-module/src/platform/mod.rs b/rust/obs-mcp-module/src/platform/mod.rs new file mode 100644 index 0000000000..d783680437 --- /dev/null +++ b/rust/obs-mcp-module/src/platform/mod.rs @@ -0,0 +1,4 @@ +std::cfg_select! { + unix => {mod unix; pub use unix::*;} + _ => {pub fn version()->u32{0} pub fn load()->bool{false} pub fn unload(){} } +} diff --git a/rust/obs-mcp-module/src/platform/unix.rs b/rust/obs-mcp-module/src/platform/unix.rs new file mode 100644 index 0000000000..80585a19b7 --- /dev/null +++ b/rust/obs-mcp-module/src/platform/unix.rs @@ -0,0 +1,241 @@ +//! Frontend callbacks stop the control thread before libobs shutdown. +#![allow(unsafe_code, reason = "resolve the already-loaded OBS frontend ABI")] +use obs_mcp::{ + backend::ObsBackend, + platform::{EndpointOptions, SocketServer}, +}; +use std::{ + ffi::c_void, + rc::Rc, + sync::{ + Arc, Mutex, + atomic::{AtomicBool, Ordering}, + }, + thread::JoinHandle, + time::Duration, +}; +type Callback = unsafe extern "C" fn(i32, *mut c_void); +type Registration = unsafe extern "C" fn(Callback, *mut c_void); +struct Worker { + stop: Arc, + thread: JoinHandle<()>, +} +struct State { + worker: Option, + remove: Registration, + _library: libloading::os::unix::Library, +} +static STATE: Mutex> = Mutex::new(None); +fn stop(state: &mut State) { + if let Some(worker) = state.worker.take() { + worker.stop.store(true, Ordering::Release); + let _ = worker.thread.join(); + } +} +unsafe extern "C" fn event(event: i32, _: *mut c_void) { + if event == 17 + && let Ok(mut state) = STATE.lock() + && let Some(state) = state.as_mut() + { + stop(state); + } +} +pub fn version() -> u32 { + let lib = libloading::os::unix::Library::this(); + // SAFETY: the host defines the documented no-argument OBS version function. + unsafe { + lib.get:: u32>(b"obs_get_version\0") + .map_or(0, |f| f()) + } +} +pub fn load() -> bool { + match start() { + Ok(()) => true, + Err(e) => { + eprintln!("OBS control module: {e}"); + false + } + } +} +fn start() -> Result<(), String> { + let mut slot = STATE.lock().map_err(|e| e.to_string())?; + if slot.is_some() { + return Ok(()); + } + let library = libloading::os::unix::Library::this(); + // SAFETY: symbols have the signatures in obs-frontend-api.h; library stays owned by State. + let (add, remove) = unsafe { + ( + *library + .get::(b"obs_frontend_add_event_callback\0") + .map_err(|e| e.to_string())?, + *library + .get::(b"obs_frontend_remove_event_callback\0") + .map_err(|e| e.to_string())?, + ) + }; + let frontend = Frontend::resolve(&library)?; + let stop_flag = Arc::new(AtomicBool::new(false)); + let thread_stop = stop_flag.clone(); + let (tx, rx) = std::sync::mpsc::sync_channel(1); + let thread = std::thread::spawn(move || { + let server = match SocketServer::bind(&EndpointOptions::default()) { + Ok(s) => s, + Err(e) => { + let _ = tx.send(Err(e.to_string())); + return; + } + }; + let backend = + Rc::new(ObsBackend::attached(Rc::new(frontend)).with_cancellation(thread_stop.clone())); + if tx.send(Ok(())).is_ok() + && let Err(e) = server.run(&thread_stop, || ObsBackend::server(&backend)) + { + eprintln!("OBS control socket: {e}"); + } + }); + match rx.recv_timeout(Duration::from_secs(5)) { + Ok(Ok(())) => (), + other => { + stop_flag.store(true, Ordering::Release); + let _ = thread.join(); + return Err(format!("control socket startup: {other:?}")); + } + } + // SAFETY: callback is static, userdata null and callback lifetime ends on unload. + unsafe { + add(event, std::ptr::null_mut()); + } + *slot = Some(State { + worker: Some(Worker { + stop: stop_flag, + thread, + }), + remove, + _library: library, + }); + Ok(()) +} +pub fn unload() { + if let Ok(mut slot) = STATE.lock() + && let Some(mut state) = slot.take() + { + // SAFETY: unregister the exact static callback before dropping the library. + unsafe { + (state.remove)(event, std::ptr::null_mut()); + } + stop(&mut state); + } +} + +type GetSource = unsafe extern "C" fn() -> *mut c_void; +type GetName = unsafe extern "C" fn(*mut c_void) -> *const std::ffi::c_char; +type Release = unsafe extern "C" fn(*mut c_void); +#[derive(Clone, Copy)] +struct Frontend { + current: GetSource, + set: unsafe extern "C" fn(*mut c_void), + source: unsafe extern "C" fn(*const std::ffi::c_char) -> *mut c_void, + name: GetName, + release: Release, + record: GetSource, + stream: GetSource, + output_name: GetName, + output_release: Release, + queue: unsafe extern "C" fn(i32, unsafe extern "C" fn(*mut c_void), *mut c_void, bool), +} +impl Frontend { + fn resolve(lib: &libloading::os::unix::Library) -> Result { + // SAFETY: documented frontend/libobs symbols, held by State for all worker calls. + unsafe { + Ok(Self { + current: *lib + .get(b"obs_frontend_get_current_scene\0") + .map_err(|e| e.to_string())?, + set: *lib + .get(b"obs_frontend_set_current_scene\0") + .map_err(|e| e.to_string())?, + source: *lib + .get(b"obs_get_source_by_name\0") + .map_err(|e| e.to_string())?, + name: *lib + .get(b"obs_source_get_name\0") + .map_err(|e| e.to_string())?, + release: *lib + .get(b"obs_source_release\0") + .map_err(|e| e.to_string())?, + record: *lib + .get(b"obs_frontend_get_recording_output\0") + .map_err(|e| e.to_string())?, + stream: *lib + .get(b"obs_frontend_get_streaming_output\0") + .map_err(|e| e.to_string())?, + output_name: *lib + .get(b"obs_output_get_name\0") + .map_err(|e| e.to_string())?, + output_release: *lib + .get(b"obs_output_release\0") + .map_err(|e| e.to_string())?, + queue: *lib.get(b"obs_queue_task\0").map_err(|e| e.to_string())?, + }) + } + } + fn name_of(&self, get: GetSource, name: GetName, release: Release) -> Option { + // SAFETY: getter returns an owned OBS reference; copied name is used before release. + unsafe { + let source = get(); + if source.is_null() { + return None; + } + let text = name(source); + let result = (!text.is_null()).then(|| { + std::ffi::CStr::from_ptr(text) + .to_string_lossy() + .into_owned() + }); + release(source); + result + } + } +} +struct SceneChange { + frontend: Frontend, + name: std::ffi::CString, +} +unsafe extern "C" fn change_scene(data: *mut c_void) { + // SAFETY: synchronous graphics queue borrows the stack request until this returns. + let request = unsafe { &*data.cast::() }; + // SAFETY: source is retained across the frontend call, which itself retains queued UI data. + unsafe { + let source = (request.frontend.source)(request.name.as_ptr()); + if !source.is_null() { + (request.frontend.set)(source); + (request.frontend.release)(source); + } + } +} +impl obs_mcp::backend::AttachedFrontend for Frontend { + fn current_scene(&self) -> Option { + self.name_of(self.current, self.name, self.release) + } + fn set_scene(&self, request: &obs_mcp::tools::scenes::NameInput) -> Result<(), String> { + let mut change = SceneChange { + frontend: *self, + name: std::ffi::CString::new(request.name.as_str()).map_err(|e| e.to_string())?, + }; + // SAFETY: OBS_TASK_GRAPHICS (1) forces the frontend setter's nonblocking UI path. + // The synchronous graphics task completes before this stack request drops. Thus + // frontend EXIT can join the worker without waiting on a blocked UI callback. + unsafe { + (self.queue)(1, change_scene, (&raw mut change).cast(), true); + } + Ok(()) + } + fn output_name(&self, request: &obs_mcp::tools::outputs::OutputRequest) -> Option { + let get = match request.kind { + obs_mcp::tools::outputs::OutputKind::Record => self.record, + obs_mcp::tools::outputs::OutputKind::Stream => self.stream, + }; + self.name_of(get, self.output_name, self.output_release) + } +} diff --git a/rust/obs-mcp/Cargo.toml b/rust/obs-mcp/Cargo.toml index 5bec571a4f..ffcee04b5a 100644 --- a/rust/obs-mcp/Cargo.toml +++ b/rust/obs-mcp/Cargo.toml @@ -19,7 +19,7 @@ test = false # Binds the backend traits to libobs through obs-sys (#3283). Off by default: # it needs the libobs symbols at link time, which only the application and the # `bundled-native` contract tests provide. -libobs = ["dep:obs-sys", "dep:libc", "dep:obs-callback"] +libobs = ["dep:obs-sys"] # Test-only fault injection (with `libobs`): `host::fail_audio_mixer` makes the next start # behave as if libobs could not open its audio mixer (#3491). Enabled only by # obs-studio-rust's dev-dependency, so no shipped build can reach it; the @@ -27,7 +27,6 @@ libobs = ["dep:obs-sys", "dep:libc", "dep:obs-callback"] fault-injection = [] [dependencies] -obs-callback = { path = "../obs-callback", optional = true } schemars = { workspace = true, features = ["derive", "std"] } serde_path_to_error = { workspace = true } obs-sys = { path = "../obs-sys", optional = true } @@ -39,4 +38,4 @@ flate2 = { workspace = true, features = ["rust_backend"] } # Redirects descriptor 1 to stderr so libobs logs stay off the protocol stream. [target.'cfg(unix)'.dependencies] -libc = { workspace = true, default-features = true, optional = true } +libc = { workspace = true, default-features = true } diff --git a/rust/obs-mcp/src/backend/mod.rs b/rust/obs-mcp/src/backend/mod.rs index d4d0ec7eb1..fd6f36afa3 100644 --- a/rust/obs-mcp/src/backend/mod.rs +++ b/rust/obs-mcp/src/backend/mod.rs @@ -43,7 +43,14 @@ use crate::tools::sources::{self, ItemInfo, ItemRef, SourceBackend, SourceInfo, const MAX_SIDE: u32 = 16_384; /// The libobs-backed implementation of every backend trait. +/// Frontend capabilities supplied by an attached application. +pub trait AttachedFrontend { + fn current_scene(&self) -> Option; + fn set_scene(&self, request: &crate::tools::scenes::NameInput) -> Result<(), String>; + fn output_name(&self, request: &crate::tools::outputs::OutputRequest) -> Option; +} pub struct ObsBackend { + frontend: Option>, /// References to the scenes and sources created here, by name. owned: RefCell>, record: Option, @@ -73,7 +80,18 @@ impl ObsBackend { #[must_use] pub fn new() -> Self { crate::ffi::use_absolute_coordinates(); + Self::unconfigured() + } + /// Attach without changing global coordinate settings or owning libobs. + #[must_use] + pub fn attached(frontend: Rc) -> Self { + let mut backend = Self::unconfigured(); + backend.frontend = Some(frontend); + backend + } + fn unconfigured() -> Self { Self { + frontend: None, owned: RefCell::new(HashMap::new()), record: None, stream: None, @@ -174,8 +192,12 @@ impl ObsBackend { OutputKind::Record => ("record", &self.record), OutputKind::Stream => ("stream", &self.stream), }; - let name = name + let frontend_name = self.frontend.as_ref().and_then(|frontend| { + frontend.output_name(&crate::tools::outputs::OutputRequest { kind }) + }); + let name = frontend_name .as_deref() + .or(name.as_deref()) .ok_or_else(|| format!("the {label} output is not configured"))?; Output::by_name(name).ok_or_else(|| { Self::because( @@ -219,11 +241,19 @@ impl SceneBackend for ObsBackend { } fn current(&self) -> Option { - ffi::program().filter(Source::is_scene).map(|s| s.name()) + self.frontend.as_ref().map_or_else( + || ffi::program().filter(Source::is_scene).map(|s| s.name()), + |frontend| frontend.current_scene(), + ) } fn set_current(&self, name: &str) -> Result<(), String> { let scene = Self::scene(name)?; + if let Some(frontend) = &self.frontend { + return frontend.set_scene(&crate::tools::scenes::NameInput { + name: name.to_owned(), + }); + } ffi::set_program(Some(&scene)); Ok(()) } @@ -234,7 +264,7 @@ impl SceneBackend for ObsBackend { // A client that makes the first scene wants to see it: with no // program scene the new one becomes the program scene (#3339). if self.current().is_none() { - ffi::set_program(Some(&scene)); + self.set_current(name)?; } self.owned.borrow_mut().insert(name.to_owned(), scene); Ok(()) @@ -243,6 +273,11 @@ impl SceneBackend for ObsBackend { fn remove(&self, name: &str) -> Result<(), String> { let scene = Self::scene(name)?; if self.current().as_deref() == Some(name) { + if self.frontend.is_some() { + return Err( + "switch away from the current frontend scene before removing it".to_owned(), + ); + } ffi::set_program(None); } scene.remove(); diff --git a/rust/obs-mcp/src/ffi/control.rs b/rust/obs-mcp/src/ffi/control.rs index 3c984185a0..c50f16db90 100644 --- a/rust/obs-mcp/src/ffi/control.rs +++ b/rust/obs-mcp/src/ffi/control.rs @@ -1,7 +1,10 @@ //! Private libobs media/procedure bindings; public C headers stay unchanged. use super::{Output, Source, sys}; use crate::tools::control::{MediaState, MediaStatus, RenderStats, StageStats}; -use obs_callback::ffi::calldata::calldata; +// The layout is the stable calldata_t ABI in callback/calldata.h. Keeping +// this declaration local avoids linking callback implementations into a plugin. +#[repr(C)] +struct Calldata { stack: *mut u8, size: usize, capacity: usize, fixed: bool } use std::ffi::{CStr, c_char, c_int, c_void}; unsafe extern "C" { @@ -14,19 +17,19 @@ unsafe extern "C" { fn obs_get_total_frames() -> u32; fn obs_get_average_frame_time_ns() -> u64; fn obs_output_get_proc_handler(output: *const sys::obs_output_t) -> *mut c_void; - fn proc_handler_call(handler: *mut c_void, name: *const c_char, params: *mut calldata) -> bool; + fn proc_handler_call(handler: *mut c_void, name: *const c_char, params: *mut Calldata) -> bool; fn calldata_get_data( - data: *const calldata, + data: *const Calldata, name: *const c_char, out: *mut c_void, size: usize, ) -> bool; fn bfree(data: *mut c_void); } -struct Params(calldata); +struct Params(Calldata); impl Params { fn new() -> Self { - Self(calldata { + Self(Calldata { stack: std::ptr::null_mut(), size: 0, capacity: 0, diff --git a/rust/obs-mcp/src/host.rs b/rust/obs-mcp/src/host.rs index d9caac76c1..25fab2847a 100644 --- a/rust/obs-mcp/src/host.rs +++ b/rust/obs-mcp/src/host.rs @@ -75,14 +75,7 @@ impl StartOptions { } } -fn default_graphics_module() -> String { - if cfg!(windows) { - "libobs-d3d11" - } else { - "libobs-opengl" - } - .to_owned() -} +use crate::platform::default_graphics_module; /// A started libobs with video, audio, modules and the record and stream /// outputs set up. Every step after `obs_startup` that fails is recorded, not @@ -154,3 +147,27 @@ pub fn serve_stdio(options: &StartOptions) -> io::Result<()> { drop(backend); result } + +/// Start a headless instance on a socket until stdin closes. +/// # Errors +/// Returns startup or transport errors. +pub fn serve_socket( + options: &StartOptions, + endpoint: &crate::platform::EndpointOptions, +) -> io::Result<()> { + use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }; + let runtime = Runtime::start(options)?; + let socket = crate::platform::SocketServer::bind(endpoint)?; + let stop = Arc::new(AtomicBool::new(false)); + let stdin_stop = stop.clone(); + std::thread::spawn(move || { + let _ = io::copy(&mut io::stdin().lock(), &mut io::sink()); + stdin_stop.store(true, Ordering::Release); + }); + let backend = Rc::new(runtime.backend().with_cancellation(stop.clone())); + eprintln!("OBS control socket ready"); + socket.run(&stop, || ObsBackend::server(&backend)) +} diff --git a/rust/obs-mcp/src/platform/mod.rs b/rust/obs-mcp/src/platform/mod.rs index 512aa85d89..7862d60a67 100644 --- a/rust/obs-mcp/src/platform/mod.rs +++ b/rust/obs-mcp/src/platform/mod.rs @@ -1,5 +1,28 @@ -//! Owner-only local control transport. +//! Host boundary for local control sockets. use std::{io, path::PathBuf}; #[derive(Clone, Debug, Default)] -pub struct EndpointOptions { pub socket: Option } -pub fn endpoint(options: &EndpointOptions) -> io::Result { todo!("endpoint: {options:?}") } +pub struct EndpointOptions { + pub socket: Option, +} +/// Resolve an explicit endpoint or the per-user runtime endpoint. +/// # Errors +/// Fails if no runtime directory is configured. +pub fn endpoint(options: &EndpointOptions) -> io::Result { + options.socket.clone().map_or_else( + || { + std::env::var_os("XDG_RUNTIME_DIR") + .map(|p| PathBuf::from(p).join("obs-studio-rust/control.sock")) + .ok_or_else(|| { + io::Error::new( + io::ErrorKind::NotFound, + "XDG_RUNTIME_DIR is unset; provide a socket path", + ) + }) + }, + Ok, + ) +} +std::cfg_select! { + unix => { mod unix; pub use unix::*; } + _ => { mod unsupported; pub use unsupported::*; } +} diff --git a/rust/obs-mcp/src/platform/unix.rs b/rust/obs-mcp/src/platform/unix.rs new file mode 100644 index 0000000000..edfb6aab24 --- /dev/null +++ b/rust/obs-mcp/src/platform/unix.rs @@ -0,0 +1,257 @@ +//! Unix sockets and descriptor relay; no host code escapes this module. +#![allow( + unsafe_code, + reason = "Unix owner checks and stdin polling require libc" +)] +use super::{EndpointOptions, endpoint}; +use crate::server::Server; +use std::{ + fs, + io::{self, BufRead, BufReader, Read, Write}, + os::unix::{ + fs::{DirBuilderExt, FileTypeExt, MetadataExt, PermissionsExt}, + io::AsRawFd, + net::{UnixListener, UnixStream}, + }, + path::PathBuf, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, + time::Duration, +}; +const MAX_FRAME: usize = 16 * 1024 * 1024; +pub struct Connection { + pub reader: Box, + pub writer: Box, +} +fn owned(meta: &fs::Metadata) -> io::Result<()> { + // SAFETY: geteuid has no preconditions. + if meta.uid() != unsafe { libc::geteuid() } || meta.mode() & 0o077 != 0 { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "endpoint must be owned by this user and private", + )); + } + Ok(()) +} +fn validate(path: &std::path::Path) -> io::Result { + let meta = fs::symlink_metadata(path)?; + owned(&meta)?; + if !meta.file_type().is_socket() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "endpoint is not a socket", + )); + } + Ok(meta) +} +/// Connect without starting another OBS instance. +/// # Errors +/// Rejects unsafe endpoints and connection failures. +pub fn connect(options: &EndpointOptions) -> io::Result { + let path = endpoint(options)?; + validate(&path)?; + let stream = UnixStream::connect(path)?; + stream.set_read_timeout(Some(Duration::from_secs(310)))?; + stream.set_write_timeout(Some(Duration::from_secs(5)))?; + Ok(Connection { + reader: Box::new(BufReader::new(stream.try_clone()?)), + writer: Box::new(stream), + }) +} +pub struct SocketServer { + listener: UnixListener, + path: PathBuf, + identity: (u64, u64), +} +impl SocketServer { + /// Bind a private socket, refusing active endpoints and non-sockets. + /// # Errors + /// Fails for unsafe permissions, active endpoints or filesystem errors. + pub fn bind(options: &EndpointOptions) -> io::Result { + let path = endpoint(options)?; + let parent = path + .parent() + .ok_or_else(|| io::Error::other("socket needs a parent"))?; + match fs::DirBuilder::new().mode(0o700).create(parent) { + Ok(()) => (), + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => (), + Err(e) => return Err(e), + } + let meta = fs::symlink_metadata(parent)?; + owned(&meta)?; + if !meta.is_dir() || meta.file_type().is_symlink() { + return Err(io::Error::other("socket parent is not a directory")); + } + if fs::symlink_metadata(&path).is_ok() { + validate(&path)?; + match UnixStream::connect(&path) { + Err(e) if e.kind() == io::ErrorKind::ConnectionRefused => fs::remove_file(&path)?, + _ => { + return Err(io::Error::new( + io::ErrorKind::AddrInUse, + "control socket already active", + )); + } + } + } + let listener = UnixListener::bind(&path)?; + fs::set_permissions(&path, fs::Permissions::from_mode(0o600))?; + listener.set_nonblocking(true)?; + let meta = fs::symlink_metadata(&path)?; + Ok(Self { + listener, + path, + identity: (meta.dev(), meta.ino()), + }) + } + #[must_use] + pub fn path(&self) -> &std::path::Path { + &self.path + } + /// Multiplex clients on the owning backend thread. Rendering stays on OBS threads. + /// # Errors + /// Returns listener failures; disconnected clients are isolated. + pub fn run( + self, + stop: &Arc, + mut factory: impl FnMut() -> Server, + ) -> io::Result<()> { + struct Peer { + stream: UnixStream, + buffer: Vec, + server: Server, + } + let mut peers: Vec = Vec::new(); + while !stop.load(Ordering::Acquire) { + match self.listener.accept() { + Ok((stream, _)) => { + if peers.len() < 32 { + stream.set_nonblocking(true)?; + peers.push(Peer { + stream, + buffer: Vec::new(), + server: factory(), + }); + } + } + Err(e) if e.kind() == io::ErrorKind::WouldBlock => (), + Err(e) => return Err(e), + } + peers.retain_mut(|peer| { + let mut bytes = [0u8; 8192]; + let mut eof = false; + loop { + match peer.stream.read(&mut bytes) { + Ok(0) => { + eof = true; + break; + } + Ok(n) => { + peer.buffer.extend_from_slice(&bytes[..n]); + if peer.buffer.len() > MAX_FRAME { + return false; + } + } + Err(e) if e.kind() == io::ErrorKind::WouldBlock => break, + Err(_) => return false, + } + } + while let Some(n) = peer + .buffer + .iter() + .position(|b| *b == b'\n') + .map(|n| n + 1) + .or_else(|| (eof && !peer.buffer.is_empty()).then_some(peer.buffer.len())) + { + let line: Vec<_> = peer.buffer.drain(..n).collect(); + let mut response = Vec::new(); + if peer.server.serve(line.as_slice(), &mut response).is_err() { + return false; + } + if peer.stream.set_nonblocking(false).is_err() { + return false; + } + let result = peer + .stream + .set_write_timeout(Some(Duration::from_secs(1))) + .and_then(|()| peer.stream.write_all(&response)); + if result.is_err() || peer.stream.set_nonblocking(true).is_err() { + return false; + } + } + !eof + }); + std::thread::park_timeout(Duration::from_millis(2)); + } + Ok(()) + } +} +impl Drop for SocketServer { + fn drop(&mut self) { + if let Ok(meta) = fs::symlink_metadata(&self.path) { + if (meta.dev(), meta.ino()) == self.identity { + let _ = fs::remove_file(&self.path); + } + } + } +} +/// Relay stdio bytes to an existing instance, preserving newline framing. +/// # Errors +/// Returns connect or relay failures. +pub fn proxy(options: &EndpointOptions) -> io::Result<()> { + let path = endpoint(options)?; + validate(&path)?; + let mut stream = UnixStream::connect(path)?; + let mut stdin_open = true; + let mut stdout = io::stdout().lock(); + loop { + let mut fds = [ + libc::pollfd { + fd: if stdin_open { 0 } else { -1 }, + events: libc::POLLIN, + revents: 0, + }, + libc::pollfd { + fd: stream.as_raw_fd(), + events: libc::POLLIN, + revents: 0, + }, + ]; + // SAFETY: fds is initialized and lives across poll. + if unsafe { libc::poll(fds.as_mut_ptr(), 2, -1) } < 0 { + let e = io::Error::last_os_error(); + if e.kind() == io::ErrorKind::Interrupted { + continue; + } + return Err(e); + } + let mut bytes = [0u8; 8192]; + if fds[0].revents & (libc::POLLIN | libc::POLLHUP) != 0 { + // SAFETY: bytes has the supplied writable capacity; fd 0 is stdin. + let n = unsafe { libc::read(0, bytes.as_mut_ptr().cast(), bytes.len()) }; + if n < 0 { + return Err(io::Error::last_os_error()); + } + if n == 0 { + stdin_open = false; + stream.shutdown(std::net::Shutdown::Write)?; + } else { + stream.write_all(&bytes[..usize::try_from(n).map_err(io::Error::other)?])?; + } + } + if fds[1].revents & (libc::POLLIN | libc::POLLHUP | libc::POLLERR) != 0 { + let n = stream.read(&mut bytes)?; + if n == 0 { + return Ok(()); + } + stdout.write_all(&bytes[..n])?; + stdout.flush()?; + } + } +} +#[must_use] +pub fn default_graphics_module() -> String { + "libobs-opengl".to_owned() +} diff --git a/rust/obs-mcp/src/platform/unsupported.rs b/rust/obs-mcp/src/platform/unsupported.rs new file mode 100644 index 0000000000..f4ea84bd04 --- /dev/null +++ b/rust/obs-mcp/src/platform/unsupported.rs @@ -0,0 +1,37 @@ +//! Windows named-pipe transport is tracked in obs-rust/obs-studio#4455. +use super::EndpointOptions; +use std::io; +pub struct Connection { + pub reader: Box, + pub writer: Box, +} +fn unavailable() -> io::Error { + io::Error::new( + io::ErrorKind::Unsupported, + "local control transport unavailable; Windows named pipe: https://github.com/obs-rust/obs-studio/issues/4455", + ) +} +pub fn connect(_: &EndpointOptions) -> io::Result { + Err(unavailable()) +} +pub fn proxy(_: &EndpointOptions) -> io::Result<()> { + Err(unavailable()) +} +#[must_use] +pub fn default_graphics_module() -> String { + "libobs-d3d11".to_owned() +} + +pub struct SocketServer; +impl SocketServer { + pub fn bind(_: &EndpointOptions) -> io::Result { + Err(unavailable()) + } + pub fn run( + self, + _: &std::sync::Arc, + _: impl FnMut() -> crate::server::Server, + ) -> io::Result<()> { + Err(unavailable()) + } +} diff --git a/rust/obs-mcp/tests/mcp/transport.rs b/rust/obs-mcp/tests/mcp/transport.rs index 3adabaa1f0..a96381bf63 100644 --- a/rust/obs-mcp/tests/mcp/transport.rs +++ b/rust/obs-mcp/tests/mcp/transport.rs @@ -1,6 +1,103 @@ -use obs_mcp::platform::{endpoint, EndpointOptions}; +use obs_mcp::platform::{EndpointOptions, endpoint}; #[test] fn explicit_endpoint_is_preserved() { - let path = std::path::PathBuf::from("/test/control.sock"); - assert_eq!(endpoint(&EndpointOptions { socket:Some(path.clone()) }).unwrap(), path); + let path = std::path::PathBuf::from("/test/control.sock"); + assert_eq!( + endpoint(&EndpointOptions { + socket: Some(path.clone()) + }) + .unwrap(), + path + ); +} +#[cfg(unix)] +#[test] +fn private_socket_serves_fragmented_and_multiple_clients_and_cleans_up() { + use obs_mcp::{ + platform::{SocketServer, connect}, + server::Server, + }; + use std::{ + io::Write, + os::unix::fs::PermissionsExt, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, + }; + let directory = tempfile::tempdir().unwrap(); + std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); + let options = EndpointOptions { + socket: Some(directory.path().join("control.sock")), + }; + let socket = SocketServer::bind(&options).unwrap(); + assert_eq!( + std::fs::metadata(socket.path()) + .unwrap() + .permissions() + .mode() + & 0o777, + 0o600 + ); + assert!(SocketServer::bind(&options).is_err()); + let stop = Arc::new(AtomicBool::new(false)); + struct Guard(Arc, Option>); + impl Drop for Guard { + fn drop(&mut self) { + self.0.store(true, Ordering::Release); + self.1.take().unwrap().join().unwrap(); + } + } + let flag = stop.clone(); + let _guard = Guard( + stop, + Some(std::thread::spawn(move || { + socket.run(&flag, Server::new).unwrap() + })), + ); + let mut a = connect(&options).unwrap(); + let mut b = connect(&options).unwrap(); + a.writer + .write_all(b"{\"jsonrpc\":\"2.0\",\"id\":1,") + .unwrap(); + b.writer + .write_all(b"{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"ping\"}\n") + .unwrap(); + let mut line = String::new(); + b.reader.read_line(&mut line).unwrap(); + assert_eq!( + serde_json::from_str::(&line).unwrap()["id"], + 2 + ); + a.writer.write_all(b"\"method\":\"ping\"}\n").unwrap(); + line.clear(); + a.reader.read_line(&mut line).unwrap(); + assert_eq!( + serde_json::from_str::(&line).unwrap()["id"], + 1 + ); + drop(a); + drop(b); + drop(_guard); + assert!(!options.socket.unwrap().exists()); +} +#[cfg(unix)] +#[test] +fn refuses_non_socket_and_symlink() { + use obs_mcp::platform::SocketServer; + use std::os::unix::fs::{PermissionsExt, symlink}; + let dir = tempfile::tempdir().unwrap(); + std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); + let file = dir.path().join("file"); + std::fs::write(&file, b"keep").unwrap(); + assert!( + SocketServer::bind(&EndpointOptions { + socket: Some(file.clone()) + }) + .is_err() + ); + let link = dir.path().join("link"); + symlink(&file, &link).unwrap(); + assert!(SocketServer::bind(&EndpointOptions { socket: Some(link) }).is_err()); + assert_eq!(std::fs::read(file).unwrap(), b"keep"); } diff --git a/rust/obs-studio-rust/Cargo.toml b/rust/obs-studio-rust/Cargo.toml index e89df2e500..41feea1c5e 100644 --- a/rust/obs-studio-rust/Cargo.toml +++ b/rust/obs-studio-rust/Cargo.toml @@ -18,11 +18,11 @@ path = "src/main.rs" [features] libobs-integration = ["obs-build/libobs-integration"] -bundled-native = ["dep:obs-sys", "obs-sys/bundled", "dep:obs-mcp", "obs-mcp/libobs"] +bundled-native = ["dep:obs-sys", "obs-sys/bundled", "obs-mcp/libobs"] [dependencies] obs-sys = { path = "../obs-sys", optional = true } -obs-mcp = { path = "../obs-mcp", optional = true } +obs-mcp = { path = "../obs-mcp" } base64 = { workspace = true, features = ["std", "simd-unsafe"] } serde_json = { workspace = true, features = ["std"] } sha2 = { workspace = true, features = ["alloc", "oid"] } diff --git a/rust/obs-studio-rust/src/main.rs b/rust/obs-studio-rust/src/main.rs index ab7873b704..26a81c43b3 100644 --- a/rust/obs-studio-rust/src/main.rs +++ b/rust/obs-studio-rust/src/main.rs @@ -39,6 +39,8 @@ struct Args { password: Option, json: bool, mcp: bool, + mcp_attach: bool, + mcp_listen: bool, record_dir: Option, command: String, } @@ -52,6 +54,8 @@ fn parse_args() -> Result, String> { let mut command = None; let mut json = false; let mut mcp = false; + let mut mcp_attach = false; + let mut mcp_listen = false; let mut record_dir = None; let mut args = std::env::args().skip(1); while let Some(arg) = args.next() { @@ -73,6 +77,8 @@ fn parse_args() -> Result, String> { "--password" => password = Some(value("--password")?), "--json" => json = true, "--mcp" => mcp = true, + "--mcp-attach" => mcp_attach = true, + "--mcp-listen" => mcp_listen = true, "--record-dir" => record_dir = Some(value("--record-dir")?), _ if arg.starts_with('-') => return Err(format!("unknown option: {arg}")), _ if command.is_none() => command = Some(arg), @@ -81,9 +87,12 @@ fn parse_args() -> Result, String> { } let command = match command { Some(command) => command, - None if mcp => String::new(), + None if mcp || mcp_attach || mcp_listen => String::new(), None => return Err("missing command".to_owned()), }; + if u8::from(mcp) + u8::from(mcp_attach) + u8::from(mcp_listen) > 1 { + return Err("choose --mcp or --mcp-attach".to_owned()); + } if mcp && !command.is_empty() { return Err("--mcp takes no command".to_owned()); } @@ -93,6 +102,8 @@ fn parse_args() -> Result, String> { password, json, mcp, + mcp_attach, + mcp_listen, record_dir, command, })) @@ -141,7 +152,18 @@ fn main() -> ExitCode { return ExitCode::from(2); } }; - let result = if args.mcp { + let result = if args.mcp_listen { + mcp::listen( + args.record_dir.as_deref(), + (!args.command.is_empty()).then_some(args.command.as_str()), + ) + .map_err(Box::from) + } else if args.mcp_attach { + obs_mcp::platform::proxy(&obs_mcp::platform::EndpointOptions { + socket: (!args.command.is_empty()).then(|| args.command.clone().into()), + }) + .map_err(Box::from) + } else if args.mcp { mcp::run(args.record_dir.as_deref()).map_err(Box::from) } else { run(&args) diff --git a/rust/obs-studio-rust/src/mcp.rs b/rust/obs-studio-rust/src/mcp.rs index 750a189894..386d2999a5 100644 --- a/rust/obs-studio-rust/src/mcp.rs +++ b/rust/obs-studio-rust/src/mcp.rs @@ -28,3 +28,20 @@ pub fn run(_record_dir: Option<&str>) -> io::Result<()> { "this build has no libobs; rebuild with --features bundled-native", )) } + +/// Serve a headless socket until stdin closes. +/// # Errors +/// Fails if libobs or the socket cannot start. +#[cfg(feature = "bundled-native")] +pub fn listen(record_dir: Option<&str>, socket: Option<&str>) -> io::Result<()> { + obs_mcp::host::serve_socket( + &obs_mcp::host::StartOptions::from_env(record_dir.map(Into::into)), + &obs_mcp::platform::EndpointOptions { + socket: socket.map(Into::into), + }, + ) +} +#[cfg(not(feature = "bundled-native"))] +pub fn listen(record_dir: Option<&str>, _: Option<&str>) -> io::Result<()> { + run(record_dir) +} From c3dedb449e1185424d58e5abea00850fe8c2c2e6 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 15:40:40 -0800 Subject: [PATCH 15/39] style(mcp): satisfy socket cleanup clippy gate (#4448) --- rust/obs-mcp/src/ffi/control.rs | 7 ++++++- rust/obs-mcp/src/platform/unix.rs | 8 ++++---- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/rust/obs-mcp/src/ffi/control.rs b/rust/obs-mcp/src/ffi/control.rs index c50f16db90..7cbeaae1bc 100644 --- a/rust/obs-mcp/src/ffi/control.rs +++ b/rust/obs-mcp/src/ffi/control.rs @@ -4,7 +4,12 @@ use crate::tools::control::{MediaState, MediaStatus, RenderStats, StageStats}; // The layout is the stable calldata_t ABI in callback/calldata.h. Keeping // this declaration local avoids linking callback implementations into a plugin. #[repr(C)] -struct Calldata { stack: *mut u8, size: usize, capacity: usize, fixed: bool } +struct Calldata { + stack: *mut u8, + size: usize, + capacity: usize, + fixed: bool, +} use std::ffi::{CStr, c_char, c_int, c_void}; unsafe extern "C" { diff --git a/rust/obs-mcp/src/platform/unix.rs b/rust/obs-mcp/src/platform/unix.rs index edfb6aab24..e144fb048f 100644 --- a/rust/obs-mcp/src/platform/unix.rs +++ b/rust/obs-mcp/src/platform/unix.rs @@ -190,10 +190,10 @@ impl SocketServer { } impl Drop for SocketServer { fn drop(&mut self) { - if let Ok(meta) = fs::symlink_metadata(&self.path) { - if (meta.dev(), meta.ino()) == self.identity { - let _ = fs::remove_file(&self.path); - } + if let Ok(meta) = fs::symlink_metadata(&self.path) + && (meta.dev(), meta.ino()) == self.identity + { + let _ = fs::remove_file(&self.path); } } } From 3a96a9ddf1864479eeb5f82acaccb37d2222fa1e Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 15:42:21 -0800 Subject: [PATCH 16/39] test(mcp): RED typed client and probe transport contracts (#4449) --- ci/test_vcam_av_sync_mcp.py | 41 ++++++++++++++++++++++++++++++++ ci/vcam_av_sync.py | 10 ++++++++ rust/obs-mcp/src/client.rs | 17 +++++++++++++ rust/obs-mcp/src/lib.rs | 1 + rust/obs-mcp/tests/mcp/client.rs | 24 +++++++++++++++++++ rust/obs-mcp/tests/mcp/main.rs | 1 + 6 files changed, 94 insertions(+) create mode 100644 ci/test_vcam_av_sync_mcp.py create mode 100644 rust/obs-mcp/src/client.rs create mode 100644 rust/obs-mcp/tests/mcp/client.rs diff --git a/ci/test_vcam_av_sync_mcp.py b/ci/test_vcam_av_sync_mcp.py new file mode 100644 index 0000000000..0e06f8ab03 --- /dev/null +++ b/ci/test_vcam_av_sync_mcp.py @@ -0,0 +1,41 @@ +#!/usr/bin/env -S uv run --script +"""MCP probe transport tests, without devices, GUI or optional numerical packages.""" +import ast +import asyncio +import json +from pathlib import Path +import unittest + +# Load only the transport class: measurement dependencies are intentionally optional. +namespace = {"json": json, "asyncio": asyncio} +source = ast.parse(Path(__file__).with_name("vcam_av_sync.py").read_text()) +for node in source.body: + if isinstance(node, ast.ClassDef) and node.name == "McpSession": + exec(compile(ast.Module(body=[node], type_ignores=[]), "vcam_av_sync.py", "exec"), namespace) +McpSession = namespace["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") + +if __name__ == "__main__": unittest.main() diff --git a/ci/vcam_av_sync.py b/ci/vcam_av_sync.py index b4094938d6..99a4d795c4 100644 --- a/ci/vcam_av_sync.py +++ b/ci/vcam_av_sync.py @@ -251,3 +251,13 @@ def main(argv: list[str]) -> int: if __name__ == "__main__": sys.exit(main(sys.argv[1:])) + +class McpSession: + """Newline JSON-RPC session over the owner-only OBS socket.""" + + def __init__(self, reader, writer): + self.reader, self.writer = reader, writer + self.next_id = 0 + + async def call(self, name: str, arguments: dict | None = None) -> dict: + raise NotImplementedError("MCP tool exchange") diff --git a/rust/obs-mcp/src/client.rs b/rust/obs-mcp/src/client.rs new file mode 100644 index 0000000000..a054077476 --- /dev/null +++ b/rust/obs-mcp/src/client.rs @@ -0,0 +1,17 @@ +//! Synchronous typed local control client. +use crate::{platform::Connection, server::ToolError, tools::control::{StartInput,VcamStatus}}; +#[derive(Debug)] +pub enum Error { Io(std::io::Error), Protocol(String), Domain(ToolError) } +pub struct Client; +impl Client { + /// # Errors + /// Fails when the peer cannot initialize. + pub fn from_connection(_: Connection)->Result{todo!("client handshake")} + #[must_use] pub fn vcam(&self)->Vcam<'_>{Vcam(self)} +} +pub struct Vcam<'a>(&'a Client); +impl Vcam<'_>{ + /// # Errors + /// Returns the peer's structured domain failure. + pub fn start(&self,_:StartInput)->Result{let _=self.0;todo!("typed vcam start")} +} diff --git a/rust/obs-mcp/src/lib.rs b/rust/obs-mcp/src/lib.rs index 5279e4f382..5220eab68e 100644 --- a/rust/obs-mcp/src/lib.rs +++ b/rust/obs-mcp/src/lib.rs @@ -42,3 +42,4 @@ pub fn serve(reader: R, writer: W) -> io::Result<()> { } pub mod platform; +pub mod client; diff --git a/rust/obs-mcp/tests/mcp/client.rs b/rust/obs-mcp/tests/mcp/client.rs new file mode 100644 index 0000000000..238d3d5d51 --- /dev/null +++ b/rust/obs-mcp/tests/mcp/client.rs @@ -0,0 +1,24 @@ +use obs_mcp::{client::{Client,Error},platform::Connection,tools::control::StartInput}; +use serde_json::{Value,json}; +use std::{io::{self,Write},sync::{Arc,Mutex}}; +#[derive(Clone,Default)]struct Captured(Arc>>); +impl Write for Captured {fn write(&mut self,bytes:&[u8])->io::Result{self.0.lock().unwrap().extend_from_slice(bytes);Ok(bytes.len())}fn flush(&mut self)->io::Result<()>{Ok(())}} +fn connection(reply:Value)->(Connection,Captured){ + let output=Captured::default(); + let data=format!("{}\n{reply}\n",json!({"jsonrpc":"2.0","id":1,"result":{}})); + (Connection{reader:Box::new(io::Cursor::new(data.into_bytes())),writer:Box::new(output.clone())},output) +} +#[test]fn client_reuses_typed_inputs_and_structured_outputs(){ + let (connection,written)=connection(json!({"jsonrpc":"2.0","id":2,"result":{"structuredContent":{"configured":true,"active":true,"vmic_active":true}}})); + let client=Client::from_connection(connection).unwrap(); + assert!(client.vcam().start(StartInput{wait:true,..Default::default()}).unwrap().active); + let bytes=written.0.lock().unwrap();let requests:Vec=std::str::from_utf8(&bytes).unwrap().lines().map(|line|serde_json::from_str(line).unwrap()).collect(); + assert_eq!(requests[2]["params"]["name"],"vcam_start");assert_eq!(requests[2]["params"]["arguments"]["wait"],true); +} +#[test]fn client_preserves_domain_error_and_rejects_wrong_id(){ + let (stream,_)=connection(json!({"jsonrpc":"2.0","id":2,"result":{"isError":true,"structuredContent":{"code":207,"category":"not_ready","message":"video unavailable","retryable":true}}})); + let client=Client::from_connection(stream).unwrap(); + assert!(matches!(client.vcam().start(StartInput::default()),Err(Error::Domain(error)) if error.code==207 && error.retryable)); + let (stream,_)=connection(json!({"jsonrpc":"2.0","id":99,"result":{}}));let client=Client::from_connection(stream).unwrap(); + assert!(matches!(client.vcam().start(StartInput::default()),Err(Error::Protocol(_)))); +} diff --git a/rust/obs-mcp/tests/mcp/main.rs b/rust/obs-mcp/tests/mcp/main.rs index 91c270fa13..557ef85f18 100644 --- a/rust/obs-mcp/tests/mcp/main.rs +++ b/rust/obs-mcp/tests/mcp/main.rs @@ -31,3 +31,4 @@ mod control; mod waiting; mod transport; +mod client; From 7cfad7224fbb50d487a359879389f613d9a81f5c Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 15:49:21 -0800 Subject: [PATCH 17/39] feat(mcp): fluent typed client and automated A/V probe transport (#4449) --- ci/test_vcam_av_sync_mcp.py | 65 +++++- ci/vcam_av_sync.py | 165 ++++++++++++++-- docs/features.md | 4 + docs/rust-port/control-api.md | 21 ++ docs/rust-port/control-api.schema.json | 1 + rust/obs-mcp/src/backend/mod.rs | 17 ++ rust/obs-mcp/src/client.rs | 264 ++++++++++++++++++++++++- rust/obs-mcp/src/lib.rs | 2 +- rust/obs-mcp/src/tools/sources.rs | 31 ++- rust/obs-mcp/tests/mcp/client.rs | 91 +++++++-- rust/obs-mcp/tests/mcp/main.rs | 2 +- rust/obs-mcp/tests/mcp/sources.rs | 35 +++- 12 files changed, 641 insertions(+), 57 deletions(-) diff --git a/ci/test_vcam_av_sync_mcp.py b/ci/test_vcam_av_sync_mcp.py index 0e06f8ab03..bf8256092e 100644 --- a/ci/test_vcam_av_sync_mcp.py +++ b/ci/test_vcam_av_sync_mcp.py @@ -1,18 +1,19 @@ #!/usr/bin/env -S uv run --script """MCP probe transport tests, without devices, GUI or optional numerical packages.""" -import ast import asyncio +import importlib.util import json from pathlib import Path +import sys import unittest +from unittest.mock import AsyncMock, Mock, patch -# Load only the transport class: measurement dependencies are intentionally optional. -namespace = {"json": json, "asyncio": asyncio} -source = ast.parse(Path(__file__).with_name("vcam_av_sync.py").read_text()) -for node in source.body: - if isinstance(node, ast.ClassDef) and node.name == "McpSession": - exec(compile(ast.Module(body=[node], type_ignores=[]), "vcam_av_sync.py", "exec"), namespace) -McpSession = namespace["McpSession"] +# 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 @@ -38,4 +39,52 @@ async def test_domain_failure_and_wrong_id_are_errors(self): 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=[TimeoutError, 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) + if __name__ == "__main__": unittest.main() diff --git a/ci/vcam_av_sync.py b/ci/vcam_av_sync.py index 99a4d795c4..68605924cb 100644 --- a/ci/vcam_av_sync.py +++ b/ci/vcam_av_sync.py @@ -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 @@ -31,6 +31,9 @@ import argparse import asyncio import json +import os +import stat +import uuid import signal import subprocess import sys @@ -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.wait_for(asyncio.to_thread(recorder.wait), timeout=10) + except TimeoutError: + recorder.kill() + await asyncio.wait_for(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() @@ -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 @@ -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") @@ -251,13 +398,3 @@ def main(argv: list[str]) -> int: if __name__ == "__main__": sys.exit(main(sys.argv[1:])) - -class McpSession: - """Newline JSON-RPC session over the owner-only OBS socket.""" - - def __init__(self, reader, writer): - self.reader, self.writer = reader, writer - self.next_id = 0 - - async def call(self, name: str, arguments: dict | None = None) -> dict: - raise NotImplementedError("MCP tool exchange") diff --git a/docs/features.md b/docs/features.md index 5c77ece973..7d32519356 100644 --- a/docs/features.md +++ b/docs/features.md @@ -3069,3 +3069,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. diff --git a/docs/rust-port/control-api.md b/docs/rust-port/control-api.md index 37a247adfe..ec33519fd0 100644 --- a/docs/rust-port/control-api.md +++ b/docs/rust-port/control-api.md @@ -71,3 +71,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. diff --git a/docs/rust-port/control-api.schema.json b/docs/rust-port/control-api.schema.json index cc60c0a65a..21daa5bf21 100644 --- a/docs/rust-port/control-api.schema.json +++ b/docs/rust-port/control-api.schema.json @@ -18,6 +18,7 @@ {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"scenes_list","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Scene listing.","properties":{"scenes":{"description":"Scene names in display order.","items":{"type":"string"},"type":"array"}},"required":["scenes"],"title":"ScenesOutput","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Screenshot selection and requested size.","properties":{"height":{"description":"Height in pixels.","format":"uint32","minimum":0,"type":["integer","null"]},"source":{"description":"Source to capture; omit for program output.","type":["string","null"]},"width":{"description":"Width in pixels.","format":"uint32","minimum":0,"type":["integer","null"]}},"title":"CaptureInput","type":"object"},"name":"screenshot","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Captured PNG and its dimensions.","properties":{"data":{"description":"PNG bytes encoded in base64.","type":"string"},"height":{"description":"Height in pixels.","format":"uint32","minimum":0,"type":"integer"},"source":{"description":"Source name, or null for program output.","type":["string","null"]},"width":{"description":"Width in pixels.","format":"uint32","minimum":0,"type":"integer"}},"required":["data","width","height"],"title":"CaptureOutput","type":"object"}}, {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$defs":{"Pair":{"additionalProperties":false,"description":"Pixel position or scale factors.","properties":{"x":{"description":"Horizontal component.","format":"double","type":"number"},"y":{"description":"Vertical component.","format":"double","type":"number"}},"required":["x","y"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Source creation, optionally placing it in a scene.","properties":{"kind":{"description":"Source kind id.","type":"string"},"name":{"description":"Unique name.","type":"string"},"position":{"anyOf":[{"$ref":"#/$defs/Pair"},{"type":"null"}],"description":"Initial position (requires scene)."},"scene":{"description":"Scene receiving the source.","type":["string","null"]},"settings":{"additionalProperties":true,"description":"Kind-specific settings.","type":"object"}},"required":["kind","name","settings"],"title":"CreateInput","type":"object"},"name":"source_create","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Created source.","properties":{"item":{"description":"Created item id.","format":"int64","type":["integer","null"]},"kind":{"description":"Source kind.","type":"string"},"name":{"description":"Source name.","type":"string"},"scene":{"description":"Scene receiving the new item.","type":["string","null"]}},"required":["name","kind"],"title":"CreateOutput","type":"object"}}, + {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Remove a source by name.","properties":{"name":{"type":"string"}},"required":["name"],"title":"RemoveInput","type":"object"},"name":"source_remove","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Updated source name.","properties":{"name":{"description":"Source name.","type":"string"}},"required":["name"],"title":"NameOutput","type":"object"}}, {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Settings update.","properties":{"name":{"description":"Source name.","type":"string"},"settings":{"additionalProperties":true,"description":"Kind-specific settings to merge.","type":"object"}},"required":["name","settings"],"title":"SettingsInput","type":"object"},"name":"source_set_settings","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Updated source name.","properties":{"name":{"description":"Source name.","type":"string"}},"required":["name"],"title":"NameOutput","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"sources_list","outputSchema":{"$defs":{"SourceInfo":{"description":"A source as listed by [`SourceBackend::sources`].","properties":{"kind":{"description":"The source kind id, such as `color_source`.","type":"string"},"name":{"description":"The source's unique name.","type":"string"}},"required":["name","kind"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Source listing.","properties":{"sources":{"description":"Sources in stable order.","items":{"$ref":"#/$defs/SourceInfo"},"type":"array"}},"required":["sources"],"title":"SourcesOutput","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stats_get","outputSchema":{"$defs":{"RenderStats":{"description":"GetStats-style render counters.","properties":{"active_fps":{"description":"Actual render FPS.","format":"double","type":"number"},"average_frame_time_ns":{"description":"Average render duration, not end-to-end latency.","format":"uint64","minimum":0,"type":"integer"},"render_skipped_frames":{"description":"Frames lagged since baseline.","format":"uint64","minimum":0,"type":"integer"},"render_total_frames":{"description":"Frames rendered since baseline.","format":"uint64","minimum":0,"type":"integer"}},"required":["active_fps","average_frame_time_ns","render_total_frames","render_skipped_frames"],"type":"object"},"StageStats":{"description":"One live pipeline stage; null values are unmeasured, never synthetic zeroes.","properties":{"frames_dropped":{"description":"Dropped frames since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"frames_total":{"description":"Frames handled since the counter baseline.","format":"uint64","minimum":0,"type":["integer","null"]},"generation":{"description":"Counter generation, when the provider exposes one.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_max_ns":{"description":"Observed maximum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_min_ns":{"description":"Observed minimum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"live":{"description":"Currently running.","type":"boolean"},"xruns":{"description":"Underruns/overruns since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]}},"required":["live"],"type":"object"},"Stages":{"description":"Render and device stages.","properties":{"render":{"$ref":"#/$defs/StageStats","description":"OBS render stage."},"vcam":{"$ref":"#/$defs/StageStats","description":"Virtual Camera write stage."},"vmic":{"$ref":"#/$defs/StageStats","description":"Virtual microphone stage."}},"required":["render","vcam","vmic"],"type":"object"},"SyncStats":{"description":"End-to-end measurement provenance.","properties":{"av_offset_ms":{"description":"Measured audio minus video offset; null until independently measured.","format":"double","type":["number","null"]},"measured_from":{"description":"Measurement source; queue estimates are not end-to-end measurements.","type":"string"}},"required":["measured_from"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Typed pipeline statistics.","properties":{"end_to_end":{"$ref":"#/$defs/SyncStats","description":"End-to-end sync, with explicit provenance."},"render":{"$ref":"#/$defs/RenderStats","description":"Render counters."},"stages":{"$ref":"#/$defs/Stages","description":"Per-stage measured counters and bounds."}},"required":["stages","end_to_end","render"],"title":"StatsSnapshot","type":"object"}}, diff --git a/rust/obs-mcp/src/backend/mod.rs b/rust/obs-mcp/src/backend/mod.rs index fd6f36afa3..37267e9dd1 100644 --- a/rust/obs-mcp/src/backend/mod.rs +++ b/rust/obs-mcp/src/backend/mod.rs @@ -287,6 +287,23 @@ impl SceneBackend for ObsBackend { } impl SourceBackend for ObsBackend { + fn remove_source( + &self, + request: crate::tools::sources::RemoveInput, + ) -> Result { + let source = Source::by_name(&request.name).ok_or_else(|| { + crate::server::ToolError::not_found(format!("no source named '{}'", request.name)) + })?; + if source.is_scene() { + return Err(crate::server::ToolError::wrong_state( + "use scene_remove for scenes", + )); + } + source.remove(); + self.owned.borrow_mut().remove(&request.name); + Ok(crate::tools::sources::NameOutput { name: request.name }) + } + fn sources(&self) -> Vec { sorted(ffi::inputs()) .into_iter() diff --git a/rust/obs-mcp/src/client.rs b/rust/obs-mcp/src/client.rs index a054077476..cb56c6d257 100644 --- a/rust/obs-mcp/src/client.rs +++ b/rust/obs-mcp/src/client.rs @@ -1,17 +1,261 @@ -//! Synchronous typed local control client. -use crate::{platform::Connection, server::ToolError, tools::control::{StartInput,VcamStatus}}; +//! Synchronous typed client for an existing OBS control socket. +pub use crate::tools::control::{MediaInput, StartInput, StatsSnapshot, VcamStatus, VmicStatus}; +pub use crate::tools::waiting::Condition; +use crate::{ + platform::{self, Connection, EndpointOptions}, + server::ToolError, + tools::{self, EmptyInput as Empty}, +}; +use serde::{Serialize, de::DeserializeOwned}; +use serde_json::{Value, json}; +use std::{ + fmt, + io::{self, Write}, + sync::Mutex, +}; +/// Connection, protocol or structured domain failure. #[derive(Debug)] -pub enum Error { Io(std::io::Error), Protocol(String), Domain(ToolError) } -pub struct Client; +pub enum Error { + Io(io::Error), + Protocol(String), + Domain(ToolError), +} +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Io(e) => e.fmt(f), + Self::Protocol(e) => f.write_str(e), + Self::Domain(e) => e.fmt(f), + } + } +} +impl std::error::Error for Error {} +impl From for Error { + fn from(e: io::Error) -> Self { + Self::Io(e) + } +} +fn protocol(e: impl fmt::Display) -> Error { + Error::Protocol(e.to_string()) +} +struct State { + connection: Connection, + next_id: u64, +} +impl State { + fn request(&mut self, method: &str, params: Value) -> Result { + self.next_id = self + .next_id + .checked_add(1) + .ok_or_else(|| protocol("request ID exhausted"))?; + let id = self.next_id; + serde_json::to_writer( + &mut self.connection.writer, + &json!({"jsonrpc":"2.0","id":id,"method":method,"params":params}), + ) + .map_err(protocol)?; + self.connection.writer.write_all(b"\n")?; + self.connection.writer.flush()?; + let mut line = Vec::new(); + // Bound reads even for a peer that never sends a newline. + loop { + let buffer = self.connection.reader.fill_buf()?; + if buffer.is_empty() { + return Err(protocol("control socket closed before response")); + } + let count = buffer + .iter() + .position(|b| *b == b'\n') + .map_or(buffer.len(), |n| n + 1); + if line.len().saturating_add(count) > 32 * 1024 * 1024 { + return Err(protocol("control response exceeds 32 MiB")); + } + line.extend_from_slice(&buffer[..count]); + self.connection.reader.consume(count); + if line.last() == Some(&b'\n') { + break; + } + } + let response: Value = serde_json::from_slice(&line).map_err(protocol)?; + if response["jsonrpc"] != "2.0" || response["id"] != id { + return Err(protocol("invalid JSON-RPC version or response ID")); + } + if let Some(error) = response.get("error") { + return Err(protocol(format!("JSON-RPC error: {error}"))); + } + response + .get("result") + .cloned() + .ok_or_else(|| protocol("response has no result")) + } +} +/// Fluent, synchronous client. A mutex serializes requests and response IDs. +pub struct Client { + state: Mutex, +} impl Client { + /// Connect to an existing instance. This never spawns OBS. + /// # Errors + /// Returns endpoint, handshake or protocol failures. + pub fn attach(options: EndpointOptions) -> Result { + Self::from_connection(platform::connect(&options)?) + } + /// Initialize an already-connected byte stream (also useful for embedded peers). + /// # Errors + /// Returns handshake or I/O failures. + pub fn from_connection(connection: Connection) -> Result { + let mut state = State { + connection, + next_id: 0, + }; + state.request("initialize",json!({"protocolVersion":crate::server::PROTOCOL_VERSION,"capabilities":{},"clientInfo":{"name":"obs-mcp-rust","version":env!("CARGO_PKG_VERSION")}}))?; + serde_json::to_writer( + &mut state.connection.writer, + &json!({"jsonrpc":"2.0","method":"notifications/initialized"}), + ) + .map_err(protocol)?; + state.connection.writer.write_all(b"\n")?; + state.connection.writer.flush()?; + Ok(Self { + state: Mutex::new(state), + }) + } + fn call(&self, name: &str, input: I) -> Result { + let params = + json!({"name":name,"arguments":serde_json::to_value(input).map_err(protocol)?}); + let result = self + .state + .lock() + .map_err(protocol)? + .request("tools/call", params)?; + let content = result + .get("structuredContent") + .ok_or_else(|| protocol("tool response has no structuredContent"))?; + if result["isError"] == true { + return Err(Error::Domain( + serde_json::from_value(content.clone()).map_err(protocol)?, + )); + } + serde_json::from_value(content.clone()).map_err(protocol) + } + #[must_use] + pub fn vcam(&self) -> Vcam<'_> { + Vcam(self) + } + #[must_use] + pub fn vmic(&self) -> Vmic<'_> { + Vmic(self) + } + #[must_use] + pub fn media(&self) -> Media<'_> { + Media(self) + } + #[must_use] + pub fn stats(&self) -> Stats<'_> { + Stats(self) + } + /// Build a typed wait with the default five-second deadline. + #[must_use] + pub fn wait_for(&self, condition: tools::waiting::Condition) -> Wait<'_> { + Wait { + client: self, + input: tools::waiting::WaitInput { + condition, + timeout_ms: tools::waiting::DEFAULT_TIMEOUT_MS, + }, + } + } + /// Read the complete control pipeline. /// # Errors - /// Fails when the peer cannot initialize. - pub fn from_connection(_: Connection)->Result{todo!("client handshake")} - #[must_use] pub fn vcam(&self)->Vcam<'_>{Vcam(self)} + /// Returns a peer or domain failure. + pub fn pipeline_dump(&self) -> Result { + self.call("pipeline_dump", Empty {}) + } + /// A no-side-effect transport probe. + /// # Errors + /// Returns a protocol or I/O failure. + pub fn ping(&self) -> Result<(), Error> { + self.state + .lock() + .map_err(protocol)? + .request("ping", json!({}))?; + Ok(()) + } } pub struct Vcam<'a>(&'a Client); -impl Vcam<'_>{ +impl Vcam<'_> { + /// # Errors + /// Returns a peer or domain failure. + pub fn start( + &self, + input: tools::control::StartInput, + ) -> Result { + self.0.call("vcam_start", input) + } + /// # Errors + /// Returns a peer or domain failure. + pub fn stop(&self) -> Result { + self.0.call("vcam_stop", Empty {}) + } + /// # Errors + /// Returns a peer or domain failure. + pub fn status(&self) -> Result { + self.0.call("vcam_status", Empty {}) + } +} +pub struct Vmic<'a>(&'a Client); +impl Vmic<'_> { + /// # Errors + /// Returns a peer or domain failure. + pub fn status(&self) -> Result { + self.0.call("vmic_status", Empty {}) + } +} +pub struct Media<'a>(&'a Client); +impl Media<'_> { + /// # Errors + /// Returns a peer or domain failure. + pub fn restart( + &self, + input: tools::control::MediaInput, + ) -> Result { + self.0.call("media_restart", input) + } + /// # Errors + /// Returns a peer or domain failure. + pub fn status( + &self, + input: tools::control::MediaInput, + ) -> Result { + self.0.call("media_status", input) + } +} +pub struct Stats<'a>(&'a Client); +impl Stats<'_> { + /// # Errors + /// Returns a peer or domain failure. + pub fn get(&self) -> Result { + self.0.call("stats_get", Empty {}) + } + /// # Errors + /// Returns a peer or domain failure. + pub fn reset(&self) -> Result { + self.0.call("stats_reset", Empty {}) + } +} +pub struct Wait<'a> { + client: &'a Client, + input: tools::waiting::WaitInput, +} +impl Wait<'_> { + #[must_use] + pub fn timeout_ms(mut self, timeout_ms: u64) -> Self { + self.input.timeout_ms = timeout_ms; + self + } /// # Errors - /// Returns the peer's structured domain failure. - pub fn start(&self,_:StartInput)->Result{let _=self.0;todo!("typed vcam start")} + /// Returns a peer or domain failure. Timeout is a normal unsatisfied response. + pub fn call(self) -> Result { + self.client.call("wait_for", self.input) + } } diff --git a/rust/obs-mcp/src/lib.rs b/rust/obs-mcp/src/lib.rs index 5220eab68e..1dacb1937e 100644 --- a/rust/obs-mcp/src/lib.rs +++ b/rust/obs-mcp/src/lib.rs @@ -41,5 +41,5 @@ pub fn serve(reader: R, writer: W) -> io::Result<()> { server::Server::new().serve(reader, writer) } -pub mod platform; pub mod client; +pub mod platform; diff --git a/rust/obs-mcp/src/tools/sources.rs b/rust/obs-mcp/src/tools/sources.rs index b246af156e..39de929365 100644 --- a/rust/obs-mcp/src/tools/sources.rs +++ b/rust/obs-mcp/src/tools/sources.rs @@ -67,6 +67,15 @@ pub struct Transform { /// Methods take `&self`: libobs owns the state, so implementations use their /// own interior mutability. pub trait SourceBackend { + /// Remove an owned or application source, including its scene references. + /// # Errors + /// Reports a missing source or unsupported removal. + fn remove_source(&self, _request: RemoveInput) -> Result { + Err(ToolError::processing( + "source removal is not supported by this backend", + )) + } + /// Typed `ListSources` backend operation. /// # Errors /// Reports invalid state, a missing resource or processing failure. @@ -289,6 +298,12 @@ pub struct CreateOutput { #[serde(default, skip_serializing_if = "Option::is_none")] pub item: Option, } +/// Remove a source by name. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct RemoveInput { + pub name: String, +} /// Settings update. #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] @@ -466,6 +481,16 @@ typed_tool!( "Create a source of the given kind with a name and settings. Give `scene` (and optionally `position`) to also add it to that scene as an item.", |backend, input| { backend.create_source(input) } ); +typed_tool!( + RemoveSource, + "source_remove", + SourceBackend, + RemoveInput, + NameOutput, + MUTATING, + "Remove a source and its references from scenes.", + |backend, input| { backend.remove_source(input) } +); typed_tool!( SetSettings, "source_set_settings", @@ -516,7 +541,7 @@ typed_tool!( "Set the position, scale and/or rotation of a scene item, named by `item` (id from scene_items_list) or `source`.", |backend, input| { backend.update_transform(input) } ); -/// Registers seven typed source tools. +/// Registers typed source tools, including probe cleanup. pub fn register(registry: &mut ToolRegistry, backend: &Rc) { registry.register(Box::new(ListSources { backend: Rc::clone(backend), @@ -524,6 +549,9 @@ pub fn register(registry: &mut ToolRegistry, backend: &Rc) { registry.register(Box::new(CreateSource { backend: Rc::clone(backend), })); + registry.register(Box::new(RemoveSource { + backend: Rc::clone(backend), + })); registry.register(Box::new(SetSettings { backend: Rc::clone(backend), })); @@ -547,6 +575,7 @@ pub fn schemas() -> Vec { vec![ crate::server::tool_schema::(), crate::server::tool_schema::(), + crate::server::tool_schema::(), crate::server::tool_schema::(), crate::server::tool_schema::(), crate::server::tool_schema::(), diff --git a/rust/obs-mcp/tests/mcp/client.rs b/rust/obs-mcp/tests/mcp/client.rs index 238d3d5d51..35347e40ce 100644 --- a/rust/obs-mcp/tests/mcp/client.rs +++ b/rust/obs-mcp/tests/mcp/client.rs @@ -1,24 +1,73 @@ -use obs_mcp::{client::{Client,Error},platform::Connection,tools::control::StartInput}; -use serde_json::{Value,json}; -use std::{io::{self,Write},sync::{Arc,Mutex}}; -#[derive(Clone,Default)]struct Captured(Arc>>); -impl Write for Captured {fn write(&mut self,bytes:&[u8])->io::Result{self.0.lock().unwrap().extend_from_slice(bytes);Ok(bytes.len())}fn flush(&mut self)->io::Result<()>{Ok(())}} -fn connection(reply:Value)->(Connection,Captured){ - let output=Captured::default(); - let data=format!("{}\n{reply}\n",json!({"jsonrpc":"2.0","id":1,"result":{}})); - (Connection{reader:Box::new(io::Cursor::new(data.into_bytes())),writer:Box::new(output.clone())},output) +use obs_mcp::{ + client::{Client, Error}, + platform::Connection, + tools::control::StartInput, +}; +use serde_json::{Value, json}; +use std::{ + io::{self, Write}, + sync::{Arc, Mutex}, +}; +#[derive(Clone, Default)] +struct Captured(Arc>>); +impl Write for Captured { + fn write(&mut self, bytes: &[u8]) -> io::Result { + self.0.lock().unwrap().extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } } -#[test]fn client_reuses_typed_inputs_and_structured_outputs(){ - let (connection,written)=connection(json!({"jsonrpc":"2.0","id":2,"result":{"structuredContent":{"configured":true,"active":true,"vmic_active":true}}})); - let client=Client::from_connection(connection).unwrap(); - assert!(client.vcam().start(StartInput{wait:true,..Default::default()}).unwrap().active); - let bytes=written.0.lock().unwrap();let requests:Vec=std::str::from_utf8(&bytes).unwrap().lines().map(|line|serde_json::from_str(line).unwrap()).collect(); - assert_eq!(requests[2]["params"]["name"],"vcam_start");assert_eq!(requests[2]["params"]["arguments"]["wait"],true); +fn connection(reply: Value) -> (Connection, Captured) { + let output = Captured::default(); + let data = format!("{}\n{reply}\n", json!({"jsonrpc":"2.0","id":1,"result":{}})); + ( + Connection { + reader: Box::new(io::Cursor::new(data.into_bytes())), + writer: Box::new(output.clone()), + }, + output, + ) } -#[test]fn client_preserves_domain_error_and_rejects_wrong_id(){ - let (stream,_)=connection(json!({"jsonrpc":"2.0","id":2,"result":{"isError":true,"structuredContent":{"code":207,"category":"not_ready","message":"video unavailable","retryable":true}}})); - let client=Client::from_connection(stream).unwrap(); - assert!(matches!(client.vcam().start(StartInput::default()),Err(Error::Domain(error)) if error.code==207 && error.retryable)); - let (stream,_)=connection(json!({"jsonrpc":"2.0","id":99,"result":{}}));let client=Client::from_connection(stream).unwrap(); - assert!(matches!(client.vcam().start(StartInput::default()),Err(Error::Protocol(_)))); +#[test] +fn client_reuses_typed_inputs_and_structured_outputs() { + let (connection, written) = connection( + json!({"jsonrpc":"2.0","id":2,"result":{"structuredContent":{"configured":true,"active":true,"vmic_active":true}}}), + ); + let client = Client::from_connection(connection).unwrap(); + assert!( + client + .vcam() + .start(StartInput { + wait: true, + ..Default::default() + }) + .unwrap() + .active + ); + let bytes = written.0.lock().unwrap(); + let requests: Vec = std::str::from_utf8(&bytes) + .unwrap() + .lines() + .map(|line| serde_json::from_str(line).unwrap()) + .collect(); + assert_eq!(requests[2]["params"]["name"], "vcam_start"); + assert_eq!(requests[2]["params"]["arguments"]["wait"], true); +} +#[test] +fn client_preserves_domain_error_and_rejects_wrong_id() { + let (stream, _) = connection( + json!({"jsonrpc":"2.0","id":2,"result":{"isError":true,"structuredContent":{"code":207,"category":"not_ready","message":"video unavailable","retryable":true}}}), + ); + let client = Client::from_connection(stream).unwrap(); + assert!( + matches!(client.vcam().start(StartInput::default()),Err(Error::Domain(error)) if error.code==207 && error.retryable) + ); + let (stream, _) = connection(json!({"jsonrpc":"2.0","id":99,"result":{}})); + let client = Client::from_connection(stream).unwrap(); + assert!(matches!( + client.vcam().start(StartInput::default()), + Err(Error::Protocol(_)) + )); } diff --git a/rust/obs-mcp/tests/mcp/main.rs b/rust/obs-mcp/tests/mcp/main.rs index 557ef85f18..bbc6bf40e4 100644 --- a/rust/obs-mcp/tests/mcp/main.rs +++ b/rust/obs-mcp/tests/mcp/main.rs @@ -30,5 +30,5 @@ mod control; mod waiting; -mod transport; mod client; +mod transport; diff --git a/rust/obs-mcp/tests/mcp/sources.rs b/rust/obs-mcp/tests/mcp/sources.rs index 12ce475169..85d0acaf50 100644 --- a/rust/obs-mcp/tests/mcp/sources.rs +++ b/rust/obs-mcp/tests/mcp/sources.rs @@ -44,6 +44,18 @@ impl Fake { } impl SourceBackend for Fake { + fn remove_source( + &self, + request: obs_mcp::tools::sources::RemoveInput, + ) -> Result { + if !self.has(&request.name) { + return Err(obs_mcp::server::ToolError::not_found("source absent")); + } + self.sources + .borrow_mut() + .retain(|(source, _)| source.name != request.name); + Ok(obs_mcp::tools::sources::NameOutput { name: request.name }) + } fn sources(&self) -> Vec { self.sources .borrow() @@ -170,7 +182,7 @@ fn with_source(name: &str) -> (Rc, Server) { } #[test] -fn lists_seven_tools_with_object_schemas() { +fn lists_source_tools_with_object_schemas() { let mut s = server(&Rc::new(Fake::default())); let r = rpc(&mut s, "tools/list", &json!({})); let tools = r["result"]["tools"].as_array().unwrap(); @@ -184,6 +196,7 @@ fn lists_seven_tools_with_object_schemas() { "scene_item_set_visible", "scene_items_list", "source_create", + "source_remove", "source_set_settings", "sources_list" ] @@ -220,6 +233,26 @@ fn lists_seven_tools_with_object_schemas() { assert_eq!(xf["rotation"]["type"], json!(["number", "null"])); } +#[test] +fn probe_source_can_be_removed_through_the_typed_wire_call() { + let fake = Rc::new(Fake::default()); + let mut server = server(&fake); + assert!( + !call( + &mut server, + "source_create", + &json!({"name":"probe","kind":"color_source","settings":{}}) + ) + .0 + ); + assert_eq!( + call(&mut server, "source_remove", &json!({"name":"probe"})), + (false, json!({"name":"probe"})) + ); + assert!(fake.sources.borrow().is_empty()); + assert!(call(&mut server, "source_remove", &json!({"name":"probe"})).0); +} + #[test] fn create_and_list() { let mut s = server(&Rc::new(Fake::default())); From 3f1ef1c720507dc13ef5608da09f54d38e456ee2 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 15:51:05 -0800 Subject: [PATCH 18/39] fix(mcp): bind calldata ABI without linking OBS implementations (#4446) --- Cargo.lock | 1 - rust/obs-mcp/Cargo.toml | 3 +-- rust/obs-mcp/src/ffi/control.rs | 18 +++++++++++++----- 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 41ac77bbf1..2fe6331eb9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -658,7 +658,6 @@ dependencies = [ "base64", "flate2", "libc", - "obs-callback", "obs-sys", "schemars", "serde", diff --git a/rust/obs-mcp/Cargo.toml b/rust/obs-mcp/Cargo.toml index 5bec571a4f..c43b005d0a 100644 --- a/rust/obs-mcp/Cargo.toml +++ b/rust/obs-mcp/Cargo.toml @@ -19,7 +19,7 @@ test = false # Binds the backend traits to libobs through obs-sys (#3283). Off by default: # it needs the libobs symbols at link time, which only the application and the # `bundled-native` contract tests provide. -libobs = ["dep:obs-sys", "dep:libc", "dep:obs-callback"] +libobs = ["dep:obs-sys", "dep:libc"] # Test-only fault injection (with `libobs`): `host::fail_audio_mixer` makes the next start # behave as if libobs could not open its audio mixer (#3491). Enabled only by # obs-studio-rust's dev-dependency, so no shipped build can reach it; the @@ -27,7 +27,6 @@ libobs = ["dep:obs-sys", "dep:libc", "dep:obs-callback"] fault-injection = [] [dependencies] -obs-callback = { path = "../obs-callback", optional = true } schemars = { workspace = true, features = ["derive", "std"] } serde_path_to_error = { workspace = true } obs-sys = { path = "../obs-sys", optional = true } diff --git a/rust/obs-mcp/src/ffi/control.rs b/rust/obs-mcp/src/ffi/control.rs index 381fa0daa2..de95e2749d 100644 --- a/rust/obs-mcp/src/ffi/control.rs +++ b/rust/obs-mcp/src/ffi/control.rs @@ -1,7 +1,15 @@ //! Private libobs media/procedure bindings; public C headers stay unchanged. use super::{Output, Source, sys}; use crate::tools::control::{MediaState, MediaStatus, RenderStats, StageStats}; -use obs_callback::ffi::calldata::calldata; +// The layout is the stable calldata_t ABI in callback/calldata.h. Keeping +// this declaration local avoids linking callback implementations into a plugin. +#[repr(C)] +struct Calldata { + stack: *mut u8, + size: usize, + capacity: usize, + fixed: bool, +} use std::ffi::{CStr, c_char, c_int, c_void}; unsafe extern "C" { @@ -13,19 +21,19 @@ unsafe extern "C" { fn obs_get_total_frames() -> u32; fn obs_get_average_frame_time_ns() -> u64; fn obs_output_get_proc_handler(output: *const sys::obs_output_t) -> *mut c_void; - fn proc_handler_call(handler: *mut c_void, name: *const c_char, params: *mut calldata) -> bool; + fn proc_handler_call(handler: *mut c_void, name: *const c_char, params: *mut Calldata) -> bool; fn calldata_get_data( - data: *const calldata, + data: *const Calldata, name: *const c_char, out: *mut c_void, size: usize, ) -> bool; fn bfree(data: *mut c_void); } -struct Params(calldata); +struct Params(Calldata); impl Params { fn new() -> Self { - Self(calldata { + Self(Calldata { stack: std::ptr::null_mut(), size: 0, capacity: 0, From d70addac30db68a6d8813d439c5cb00ba6b4ae07 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 16:04:34 -0800 Subject: [PATCH 19/39] fix(mcp): type frontend capabilities and stop before scene cleanup (#4448) --- docs/rust-port/control-api.md | 5 ++-- rust/obs-mcp-module/src/platform/unix.rs | 30 +++++++++++++++++------- rust/obs-mcp/src/backend/mod.rs | 30 +++++++++++++++++------- 3 files changed, 47 insertions(+), 18 deletions(-) diff --git a/docs/rust-port/control-api.md b/docs/rust-port/control-api.md index ec33519fd0..69f3f66b55 100644 --- a/docs/rust-port/control-api.md +++ b/docs/rust-port/control-api.md @@ -57,8 +57,9 @@ mcp plus fallback. Real GUI/device validation runs only in bosn containers. Build `soldr cargo build -p obs-mcp-module` and install the resulting `libobs_mcp_module.so` in OBS's normal module search path. The module binds `$XDG_RUNTIME_DIR/obs-studio-rust/control.sock` with mode 0600 in a private -directory. It shares the app's libobs and stops its worker on frontend EXIT, -prior to libobs shutdown. It never starts a second OBS instance. +directory. It shares the app's libobs and stops its worker on frontend scripting +shutdown, before scene cleanup (EXIT is a fallback). It never starts a second +OBS instance or changes the application's global coordinate mode. `obs-studio-rust --mcp-attach [socket]` relays stdio to that instance. The same newline JSON-RPC Server handles both transports. At most 32 clients share the diff --git a/rust/obs-mcp-module/src/platform/unix.rs b/rust/obs-mcp-module/src/platform/unix.rs index 80585a19b7..ace5e0cc73 100644 --- a/rust/obs-mcp-module/src/platform/unix.rs +++ b/rust/obs-mcp-module/src/platform/unix.rs @@ -33,7 +33,8 @@ fn stop(state: &mut State) { } } unsafe extern "C" fn event(event: i32, _: *mut c_void) { - if event == 17 + // obs-frontend-api.h: stop before ClearSceneData(), with EXIT as fallback. + if matches!(event, 36 | 17) && let Ok(mut state) = STATE.lock() && let Some(state) = state.as_mut() { @@ -215,13 +216,19 @@ unsafe extern "C" fn change_scene(data: *mut c_void) { } } impl obs_mcp::backend::AttachedFrontend for Frontend { - fn current_scene(&self) -> Option { - self.name_of(self.current, self.name, self.release) + fn current_scene(&self, _: obs_mcp::tools::EmptyInput) -> obs_mcp::tools::scenes::SceneOutput { + obs_mcp::tools::scenes::SceneOutput { + name: self.name_of(self.current, self.name, self.release), + } } - fn set_scene(&self, request: &obs_mcp::tools::scenes::NameInput) -> Result<(), String> { + fn set_scene( + &self, + request: obs_mcp::tools::scenes::NameInput, + ) -> Result { let mut change = SceneChange { frontend: *self, - name: std::ffi::CString::new(request.name.as_str()).map_err(|e| e.to_string())?, + name: std::ffi::CString::new(request.name.as_str()) + .map_err(|e| obs_mcp::server::ToolError::wrong_state(e.to_string()))?, }; // SAFETY: OBS_TASK_GRAPHICS (1) forces the frontend setter's nonblocking UI path. // The synchronous graphics task completes before this stack request drops. Thus @@ -229,13 +236,20 @@ impl obs_mcp::backend::AttachedFrontend for Frontend { unsafe { (self.queue)(1, change_scene, (&raw mut change).cast(), true); } - Ok(()) + Ok(obs_mcp::tools::scenes::SceneOutput { + name: Some(request.name), + }) } - fn output_name(&self, request: &obs_mcp::tools::outputs::OutputRequest) -> Option { + fn output_name( + &self, + request: obs_mcp::tools::outputs::OutputRequest, + ) -> obs_mcp::backend::FrontendOutputName { let get = match request.kind { obs_mcp::tools::outputs::OutputKind::Record => self.record, obs_mcp::tools::outputs::OutputKind::Stream => self.stream, }; - self.name_of(get, self.output_name, self.output_release) + obs_mcp::backend::FrontendOutputName { + name: self.name_of(get, self.output_name, self.output_release), + } } } diff --git a/rust/obs-mcp/src/backend/mod.rs b/rust/obs-mcp/src/backend/mod.rs index 37267e9dd1..e20ddfd08e 100644 --- a/rust/obs-mcp/src/backend/mod.rs +++ b/rust/obs-mcp/src/backend/mod.rs @@ -45,9 +45,18 @@ const MAX_SIDE: u32 = 16_384; /// The libobs-backed implementation of every backend trait. /// Frontend capabilities supplied by an attached application. pub trait AttachedFrontend { - fn current_scene(&self) -> Option; - fn set_scene(&self, request: &crate::tools::scenes::NameInput) -> Result<(), String>; - fn output_name(&self, request: &crate::tools::outputs::OutputRequest) -> Option; + fn current_scene(&self, request: crate::tools::EmptyInput) + -> crate::tools::scenes::SceneOutput; + fn set_scene( + &self, + request: crate::tools::scenes::NameInput, + ) -> Result; + fn output_name(&self, request: crate::tools::outputs::OutputRequest) -> FrontendOutputName; +} +/// Current frontend output identity; absent while the frontend has no output. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, schemars::JsonSchema)] +pub struct FrontendOutputName { + pub name: Option, } pub struct ObsBackend { frontend: Option>, @@ -193,7 +202,9 @@ impl ObsBackend { OutputKind::Stream => ("stream", &self.stream), }; let frontend_name = self.frontend.as_ref().and_then(|frontend| { - frontend.output_name(&crate::tools::outputs::OutputRequest { kind }) + frontend + .output_name(crate::tools::outputs::OutputRequest { kind }) + .name }); let name = frontend_name .as_deref() @@ -243,16 +254,19 @@ impl SceneBackend for ObsBackend { fn current(&self) -> Option { self.frontend.as_ref().map_or_else( || ffi::program().filter(Source::is_scene).map(|s| s.name()), - |frontend| frontend.current_scene(), + |frontend| frontend.current_scene(crate::tools::EmptyInput {}).name, ) } fn set_current(&self, name: &str) -> Result<(), String> { let scene = Self::scene(name)?; if let Some(frontend) = &self.frontend { - return frontend.set_scene(&crate::tools::scenes::NameInput { - name: name.to_owned(), - }); + return frontend + .set_scene(crate::tools::scenes::NameInput { + name: name.to_owned(), + }) + .map(|_| ()) + .map_err(|error| error.message); } ffi::set_program(Some(&scene)); Ok(()) From 6ec148959aa589d7467d5400dae09e65a0819a2d Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 16:09:08 -0800 Subject: [PATCH 20/39] test(mcp): RED cancellation drops buffered socket requests (#4448) --- rust/obs-mcp/tests/mcp/transport.rs | 75 +++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/rust/obs-mcp/tests/mcp/transport.rs b/rust/obs-mcp/tests/mcp/transport.rs index a96381bf63..58fc2a12a7 100644 --- a/rust/obs-mcp/tests/mcp/transport.rs +++ b/rust/obs-mcp/tests/mcp/transport.rs @@ -101,3 +101,78 @@ fn refuses_non_socket_and_symlink() { assert!(SocketServer::bind(&EndpointOptions { socket: Some(link) }).is_err()); assert_eq!(std::fs::read(file).unwrap(), b"keep"); } + +#[cfg(unix)] +#[test] +fn shutdown_discards_requests_already_buffered_after_cancellation() { + use obs_mcp::{ + platform::{SocketServer, connect}, + server::{Server, ToolAnnotations, ToolError, ToolRegistry, TypedTool}, + tools::EmptyInput, + }; + use std::{ + io::Write, + os::unix::fs::PermissionsExt, + sync::{ + Arc, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }, + }; + struct Cancel { + stop: Arc, + calls: Arc, + } + impl TypedTool for Cancel { + type Input = EmptyInput; + type Output = EmptyInput; + const NAME: &'static str = "cancel_test"; + const ANNOTATIONS: ToolAnnotations = ToolAnnotations::MUTATING; + fn description(&self) -> &'static str { + "Cancel the test server" + } + fn call(&self, _: EmptyInput) -> Result { + self.calls.fetch_add(1, Ordering::AcqRel); + self.stop.store(true, Ordering::Release); + Ok(EmptyInput {}) + } + } + let directory = tempfile::tempdir().unwrap(); + std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); + let options = EndpointOptions { + socket: Some(directory.path().join("control.sock")), + }; + let socket = SocketServer::bind(&options).unwrap(); + let stop = Arc::new(AtomicBool::new(false)); + let calls = Arc::new(AtomicUsize::new(0)); + let flag = stop.clone(); + let count = calls.clone(); + struct Guard(Arc, Option>); + impl Drop for Guard { + fn drop(&mut self) { + self.0.store(true, Ordering::Release); + self.1.take().unwrap().join().unwrap(); + } + } + let thread = std::thread::spawn(move || { + socket + .run(&flag, || { + let mut tools = ToolRegistry::default(); + tools.register(Box::new(Cancel { + stop: flag.clone(), + calls: count.clone(), + })); + Server::with_tools(tools) + }) + .unwrap() + }); + let guard = Guard(stop, Some(thread)); + let mut connection = connect(&options).unwrap(); + connection.writer.write_all(concat!( + "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"cancel_test\",\"arguments\":{}}}\n", + "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",\"params\":{\"name\":\"cancel_test\",\"arguments\":{}}}\n" + ).as_bytes()).unwrap(); + let mut reply = String::new(); + connection.reader.read_line(&mut reply).unwrap(); + drop(guard); + assert_eq!(calls.load(Ordering::Acquire), 1); +} From c51bae5f90e9fb4ea0f72b80c71b70cdd1030251 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 16:30:25 -0800 Subject: [PATCH 21/39] test(mcp): RED bound the capture worker wait itself (#4449) --- ci/test_vcam_av_sync_mcp.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ci/test_vcam_av_sync_mcp.py b/ci/test_vcam_av_sync_mcp.py index bf8256092e..90deed5d68 100644 --- a/ci/test_vcam_av_sync_mcp.py +++ b/ci/test_vcam_av_sync_mcp.py @@ -81,10 +81,11 @@ async def test_auto_falls_back_only_when_websocket_connection_is_absent(self): 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=[TimeoutError, 0])) as wait: + 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() From bc1ba6f381270a90b056ced3d91a62e31a6ec2b3 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 16:30:44 -0800 Subject: [PATCH 22/39] fix(mcp): stop dispatching buffered requests after cancellation (#4448) --- rust/obs-mcp/src/platform/unix.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/rust/obs-mcp/src/platform/unix.rs b/rust/obs-mcp/src/platform/unix.rs index e144fb048f..82bf4da9b1 100644 --- a/rust/obs-mcp/src/platform/unix.rs +++ b/rust/obs-mcp/src/platform/unix.rs @@ -165,6 +165,9 @@ impl SocketServer { .map(|n| n + 1) .or_else(|| (eof && !peer.buffer.is_empty()).then_some(peer.buffer.len())) { + if stop.load(Ordering::Acquire) { + return false; + } let line: Vec<_> = peer.buffer.drain(..n).collect(); let mut response = Vec::new(); if peer.server.serve(line.as_slice(), &mut response).is_err() { From 492eb75b525c24c60ca8e7927445fb3e0501dbd7 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 16:30:44 -0800 Subject: [PATCH 23/39] fix(mcp): bound ffmpeg worker waits before kill and reap (#4449) --- ci/vcam_av_sync.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ci/vcam_av_sync.py b/ci/vcam_av_sync.py index 68605924cb..ec7eb1e611 100644 --- a/ci/vcam_av_sync.py +++ b/ci/vcam_av_sync.py @@ -221,10 +221,10 @@ async def stop_capture(recorder) -> None: return recorder.send_signal(signal.SIGINT) try: - await asyncio.wait_for(asyncio.to_thread(recorder.wait), timeout=10) - except TimeoutError: + await asyncio.to_thread(recorder.wait, timeout=10) + except subprocess.TimeoutExpired: recorder.kill() - await asyncio.wait_for(asyncio.to_thread(recorder.wait), timeout=5) + await asyncio.to_thread(recorder.wait, timeout=5) async def measure_mcp(args: argparse.Namespace, clip: Path, capture: Path) -> dict: From 2cc0bcc390360a624a21abbaf8d58cb2df2e34b4 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 16:04:34 -0800 Subject: [PATCH 24/39] fix(mcp): type frontend capabilities and stop before scene cleanup (#4448) --- docs/rust-port/control-api.md | 5 ++-- rust/obs-mcp-module/src/platform/unix.rs | 30 +++++++++++++++++------- rust/obs-mcp/src/backend/mod.rs | 30 +++++++++++++++++------- 3 files changed, 47 insertions(+), 18 deletions(-) diff --git a/docs/rust-port/control-api.md b/docs/rust-port/control-api.md index 37a247adfe..ec5d238380 100644 --- a/docs/rust-port/control-api.md +++ b/docs/rust-port/control-api.md @@ -57,8 +57,9 @@ mcp plus fallback. Real GUI/device validation runs only in bosn containers. Build `soldr cargo build -p obs-mcp-module` and install the resulting `libobs_mcp_module.so` in OBS's normal module search path. The module binds `$XDG_RUNTIME_DIR/obs-studio-rust/control.sock` with mode 0600 in a private -directory. It shares the app's libobs and stops its worker on frontend EXIT, -prior to libobs shutdown. It never starts a second OBS instance. +directory. It shares the app's libobs and stops its worker on frontend scripting +shutdown, before scene cleanup (EXIT is a fallback). It never starts a second +OBS instance or changes the application's global coordinate mode. `obs-studio-rust --mcp-attach [socket]` relays stdio to that instance. The same newline JSON-RPC Server handles both transports. At most 32 clients share the diff --git a/rust/obs-mcp-module/src/platform/unix.rs b/rust/obs-mcp-module/src/platform/unix.rs index 80585a19b7..ace5e0cc73 100644 --- a/rust/obs-mcp-module/src/platform/unix.rs +++ b/rust/obs-mcp-module/src/platform/unix.rs @@ -33,7 +33,8 @@ fn stop(state: &mut State) { } } unsafe extern "C" fn event(event: i32, _: *mut c_void) { - if event == 17 + // obs-frontend-api.h: stop before ClearSceneData(), with EXIT as fallback. + if matches!(event, 36 | 17) && let Ok(mut state) = STATE.lock() && let Some(state) = state.as_mut() { @@ -215,13 +216,19 @@ unsafe extern "C" fn change_scene(data: *mut c_void) { } } impl obs_mcp::backend::AttachedFrontend for Frontend { - fn current_scene(&self) -> Option { - self.name_of(self.current, self.name, self.release) + fn current_scene(&self, _: obs_mcp::tools::EmptyInput) -> obs_mcp::tools::scenes::SceneOutput { + obs_mcp::tools::scenes::SceneOutput { + name: self.name_of(self.current, self.name, self.release), + } } - fn set_scene(&self, request: &obs_mcp::tools::scenes::NameInput) -> Result<(), String> { + fn set_scene( + &self, + request: obs_mcp::tools::scenes::NameInput, + ) -> Result { let mut change = SceneChange { frontend: *self, - name: std::ffi::CString::new(request.name.as_str()).map_err(|e| e.to_string())?, + name: std::ffi::CString::new(request.name.as_str()) + .map_err(|e| obs_mcp::server::ToolError::wrong_state(e.to_string()))?, }; // SAFETY: OBS_TASK_GRAPHICS (1) forces the frontend setter's nonblocking UI path. // The synchronous graphics task completes before this stack request drops. Thus @@ -229,13 +236,20 @@ impl obs_mcp::backend::AttachedFrontend for Frontend { unsafe { (self.queue)(1, change_scene, (&raw mut change).cast(), true); } - Ok(()) + Ok(obs_mcp::tools::scenes::SceneOutput { + name: Some(request.name), + }) } - fn output_name(&self, request: &obs_mcp::tools::outputs::OutputRequest) -> Option { + fn output_name( + &self, + request: obs_mcp::tools::outputs::OutputRequest, + ) -> obs_mcp::backend::FrontendOutputName { let get = match request.kind { obs_mcp::tools::outputs::OutputKind::Record => self.record, obs_mcp::tools::outputs::OutputKind::Stream => self.stream, }; - self.name_of(get, self.output_name, self.output_release) + obs_mcp::backend::FrontendOutputName { + name: self.name_of(get, self.output_name, self.output_release), + } } } diff --git a/rust/obs-mcp/src/backend/mod.rs b/rust/obs-mcp/src/backend/mod.rs index fd6f36afa3..b0509f32f5 100644 --- a/rust/obs-mcp/src/backend/mod.rs +++ b/rust/obs-mcp/src/backend/mod.rs @@ -45,9 +45,18 @@ const MAX_SIDE: u32 = 16_384; /// The libobs-backed implementation of every backend trait. /// Frontend capabilities supplied by an attached application. pub trait AttachedFrontend { - fn current_scene(&self) -> Option; - fn set_scene(&self, request: &crate::tools::scenes::NameInput) -> Result<(), String>; - fn output_name(&self, request: &crate::tools::outputs::OutputRequest) -> Option; + fn current_scene(&self, request: crate::tools::EmptyInput) + -> crate::tools::scenes::SceneOutput; + fn set_scene( + &self, + request: crate::tools::scenes::NameInput, + ) -> Result; + fn output_name(&self, request: crate::tools::outputs::OutputRequest) -> FrontendOutputName; +} +/// Current frontend output identity; absent while the frontend has no output. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, schemars::JsonSchema)] +pub struct FrontendOutputName { + pub name: Option, } pub struct ObsBackend { frontend: Option>, @@ -193,7 +202,9 @@ impl ObsBackend { OutputKind::Stream => ("stream", &self.stream), }; let frontend_name = self.frontend.as_ref().and_then(|frontend| { - frontend.output_name(&crate::tools::outputs::OutputRequest { kind }) + frontend + .output_name(crate::tools::outputs::OutputRequest { kind }) + .name }); let name = frontend_name .as_deref() @@ -243,16 +254,19 @@ impl SceneBackend for ObsBackend { fn current(&self) -> Option { self.frontend.as_ref().map_or_else( || ffi::program().filter(Source::is_scene).map(|s| s.name()), - |frontend| frontend.current_scene(), + |frontend| frontend.current_scene(crate::tools::EmptyInput {}).name, ) } fn set_current(&self, name: &str) -> Result<(), String> { let scene = Self::scene(name)?; if let Some(frontend) = &self.frontend { - return frontend.set_scene(&crate::tools::scenes::NameInput { - name: name.to_owned(), - }); + return frontend + .set_scene(crate::tools::scenes::NameInput { + name: name.to_owned(), + }) + .map(|_| ()) + .map_err(|error| error.message); } ffi::set_program(Some(&scene)); Ok(()) From b30179dd06784b0ef0475073a127fca16fefd721 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 16:09:08 -0800 Subject: [PATCH 25/39] test(mcp): RED cancellation drops buffered socket requests (#4448) --- rust/obs-mcp/tests/mcp/transport.rs | 75 +++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/rust/obs-mcp/tests/mcp/transport.rs b/rust/obs-mcp/tests/mcp/transport.rs index a96381bf63..58fc2a12a7 100644 --- a/rust/obs-mcp/tests/mcp/transport.rs +++ b/rust/obs-mcp/tests/mcp/transport.rs @@ -101,3 +101,78 @@ fn refuses_non_socket_and_symlink() { assert!(SocketServer::bind(&EndpointOptions { socket: Some(link) }).is_err()); assert_eq!(std::fs::read(file).unwrap(), b"keep"); } + +#[cfg(unix)] +#[test] +fn shutdown_discards_requests_already_buffered_after_cancellation() { + use obs_mcp::{ + platform::{SocketServer, connect}, + server::{Server, ToolAnnotations, ToolError, ToolRegistry, TypedTool}, + tools::EmptyInput, + }; + use std::{ + io::Write, + os::unix::fs::PermissionsExt, + sync::{ + Arc, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }, + }; + struct Cancel { + stop: Arc, + calls: Arc, + } + impl TypedTool for Cancel { + type Input = EmptyInput; + type Output = EmptyInput; + const NAME: &'static str = "cancel_test"; + const ANNOTATIONS: ToolAnnotations = ToolAnnotations::MUTATING; + fn description(&self) -> &'static str { + "Cancel the test server" + } + fn call(&self, _: EmptyInput) -> Result { + self.calls.fetch_add(1, Ordering::AcqRel); + self.stop.store(true, Ordering::Release); + Ok(EmptyInput {}) + } + } + let directory = tempfile::tempdir().unwrap(); + std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); + let options = EndpointOptions { + socket: Some(directory.path().join("control.sock")), + }; + let socket = SocketServer::bind(&options).unwrap(); + let stop = Arc::new(AtomicBool::new(false)); + let calls = Arc::new(AtomicUsize::new(0)); + let flag = stop.clone(); + let count = calls.clone(); + struct Guard(Arc, Option>); + impl Drop for Guard { + fn drop(&mut self) { + self.0.store(true, Ordering::Release); + self.1.take().unwrap().join().unwrap(); + } + } + let thread = std::thread::spawn(move || { + socket + .run(&flag, || { + let mut tools = ToolRegistry::default(); + tools.register(Box::new(Cancel { + stop: flag.clone(), + calls: count.clone(), + })); + Server::with_tools(tools) + }) + .unwrap() + }); + let guard = Guard(stop, Some(thread)); + let mut connection = connect(&options).unwrap(); + connection.writer.write_all(concat!( + "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"cancel_test\",\"arguments\":{}}}\n", + "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",\"params\":{\"name\":\"cancel_test\",\"arguments\":{}}}\n" + ).as_bytes()).unwrap(); + let mut reply = String::new(); + connection.reader.read_line(&mut reply).unwrap(); + drop(guard); + assert_eq!(calls.load(Ordering::Acquire), 1); +} From 3f4ee74a746b10d17709f7a8827d7cf3cb44398a Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 16:30:44 -0800 Subject: [PATCH 26/39] fix(mcp): stop dispatching buffered requests after cancellation (#4448) --- rust/obs-mcp/src/platform/unix.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/rust/obs-mcp/src/platform/unix.rs b/rust/obs-mcp/src/platform/unix.rs index e144fb048f..82bf4da9b1 100644 --- a/rust/obs-mcp/src/platform/unix.rs +++ b/rust/obs-mcp/src/platform/unix.rs @@ -165,6 +165,9 @@ impl SocketServer { .map(|n| n + 1) .or_else(|| (eof && !peer.buffer.is_empty()).then_some(peer.buffer.len())) { + if stop.load(Ordering::Acquire) { + return false; + } let line: Vec<_> = peer.buffer.drain(..n).collect(); let mut response = Vec::new(); if peer.server.serve(line.as_slice(), &mut response).is_err() { From 65c6207d25ee64b5eb7b2bef3b6566cd6198fa0b Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 16:50:21 -0800 Subject: [PATCH 27/39] fix(mcp): preserve frontend output preparation when attached (#4448) --- rust/obs-mcp-module/src/platform/unix.rs | 44 ++++++++++++++++++++++++ rust/obs-mcp/src/backend/mod.rs | 42 ++++++++++++++++++++++ 2 files changed, 86 insertions(+) diff --git a/rust/obs-mcp-module/src/platform/unix.rs b/rust/obs-mcp-module/src/platform/unix.rs index ace5e0cc73..1925c8fb95 100644 --- a/rust/obs-mcp-module/src/platform/unix.rs +++ b/rust/obs-mcp-module/src/platform/unix.rs @@ -141,6 +141,12 @@ struct Frontend { release: Release, record: GetSource, stream: GetSource, + record_start: unsafe extern "C" fn(), + record_stop: unsafe extern "C" fn(), + record_active: unsafe extern "C" fn() -> bool, + stream_start: unsafe extern "C" fn(), + stream_stop: unsafe extern "C" fn(), + stream_active: unsafe extern "C" fn() -> bool, output_name: GetName, output_release: Release, queue: unsafe extern "C" fn(i32, unsafe extern "C" fn(*mut c_void), *mut c_void, bool), @@ -174,6 +180,24 @@ impl Frontend { output_name: *lib .get(b"obs_output_get_name\0") .map_err(|e| e.to_string())?, + record_start: *lib + .get(b"obs_frontend_recording_start\0") + .map_err(|e| e.to_string())?, + record_stop: *lib + .get(b"obs_frontend_recording_stop\0") + .map_err(|e| e.to_string())?, + record_active: *lib + .get(b"obs_frontend_recording_active\0") + .map_err(|e| e.to_string())?, + stream_start: *lib + .get(b"obs_frontend_streaming_start\0") + .map_err(|e| e.to_string())?, + stream_stop: *lib + .get(b"obs_frontend_streaming_stop\0") + .map_err(|e| e.to_string())?, + stream_active: *lib + .get(b"obs_frontend_streaming_active\0") + .map_err(|e| e.to_string())?, output_release: *lib .get(b"obs_output_release\0") .map_err(|e| e.to_string())?, @@ -216,6 +240,26 @@ unsafe extern "C" fn change_scene(data: *mut c_void) { } } impl obs_mcp::backend::AttachedFrontend for Frontend { + fn set_output( + &self, + request: obs_mcp::backend::FrontendOutputRequest, + ) -> Result { + use obs_mcp::tools::outputs::OutputKind; + let (active, command) = match (request.kind, request.active) { + (OutputKind::Record, true) => (self.record_active, self.record_start), + (OutputKind::Record, false) => (self.record_active, self.record_stop), + (OutputKind::Stream, true) => (self.stream_active, self.stream_start), + (OutputKind::Stream, false) => (self.stream_active, self.stream_stop), + }; + // SAFETY: frontend start/stop use queued Qt invocations from this worker; + // active getters read atomics. State/library outlive all worker calls. + unsafe { + if active() != request.active { + command(); + } + Ok(obs_mcp::tools::outputs::ActiveOutput { active: active() }) + } + } fn current_scene(&self, _: obs_mcp::tools::EmptyInput) -> obs_mcp::tools::scenes::SceneOutput { obs_mcp::tools::scenes::SceneOutput { name: self.name_of(self.current, self.name, self.release), diff --git a/rust/obs-mcp/src/backend/mod.rs b/rust/obs-mcp/src/backend/mod.rs index e20ddfd08e..814cc7a38d 100644 --- a/rust/obs-mcp/src/backend/mod.rs +++ b/rust/obs-mcp/src/backend/mod.rs @@ -52,6 +52,21 @@ pub trait AttachedFrontend { request: crate::tools::scenes::NameInput, ) -> Result; fn output_name(&self, request: crate::tools::outputs::OutputRequest) -> FrontendOutputName; + fn set_output( + &self, + _request: FrontendOutputRequest, + ) -> Result { + Err(crate::server::ToolError::not_ready( + "frontend output control is unavailable", + )) + } +} +/// Start or stop a frontend-managed output, preserving profile/encoder setup. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct FrontendOutputRequest { + pub kind: crate::tools::outputs::OutputKind, + pub active: bool, } /// Current frontend output identity; absent while the frontend has no output. #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, schemars::JsonSchema)] @@ -416,6 +431,12 @@ impl OutputBackend for ObsBackend { crate::tools::waiting::WaitBackend::cancelled(self) } fn start_output(&self, request: OutputRequest) -> Result { + if let Some(frontend) = &self.frontend { + return frontend.set_output(FrontendOutputRequest { + kind: request.kind, + active: true, + }); + } let output = self.output(request.kind).map_err(ToolError::not_ready)?; if !output.active() { if request.kind == OutputKind::Record { @@ -430,6 +451,12 @@ impl OutputBackend for ObsBackend { } fn stop_output(&self, request: OutputRequest) -> Result { + if let Some(frontend) = &self.frontend { + return frontend.set_output(FrontendOutputRequest { + kind: request.kind, + active: false, + }); + } let output = self.output(request.kind).map_err(ToolError::not_ready)?; if output.active() { output.stop(); @@ -440,6 +467,12 @@ impl OutputBackend for ObsBackend { } fn start(&self, kind: OutputKind) -> Result<(), String> { + if let Some(frontend) = &self.frontend { + return frontend + .set_output(FrontendOutputRequest { kind, active: true }) + .map(|_| ()) + .map_err(|error| error.message); + } let output = self.output(kind)?; if output.active() { return Err("the output is already running".to_owned()); @@ -451,6 +484,15 @@ impl OutputBackend for ObsBackend { } fn stop(&self, kind: OutputKind) -> Result<(), String> { + if let Some(frontend) = &self.frontend { + return frontend + .set_output(FrontendOutputRequest { + kind, + active: false, + }) + .map(|_| ()) + .map_err(|error| error.message); + } let output = self.output(kind)?; if !output.active() { return Err("the output is not running".to_owned()); From 5fdef587cc96519935caa7e5bb9d0d7b1d504a19 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 16:50:21 -0800 Subject: [PATCH 28/39] fix(mcp): preserve frontend output preparation when attached (#4448) --- rust/obs-mcp-module/src/platform/unix.rs | 44 ++++++++++++++++++++++++ rust/obs-mcp/src/backend/mod.rs | 42 ++++++++++++++++++++++ 2 files changed, 86 insertions(+) diff --git a/rust/obs-mcp-module/src/platform/unix.rs b/rust/obs-mcp-module/src/platform/unix.rs index ace5e0cc73..1925c8fb95 100644 --- a/rust/obs-mcp-module/src/platform/unix.rs +++ b/rust/obs-mcp-module/src/platform/unix.rs @@ -141,6 +141,12 @@ struct Frontend { release: Release, record: GetSource, stream: GetSource, + record_start: unsafe extern "C" fn(), + record_stop: unsafe extern "C" fn(), + record_active: unsafe extern "C" fn() -> bool, + stream_start: unsafe extern "C" fn(), + stream_stop: unsafe extern "C" fn(), + stream_active: unsafe extern "C" fn() -> bool, output_name: GetName, output_release: Release, queue: unsafe extern "C" fn(i32, unsafe extern "C" fn(*mut c_void), *mut c_void, bool), @@ -174,6 +180,24 @@ impl Frontend { output_name: *lib .get(b"obs_output_get_name\0") .map_err(|e| e.to_string())?, + record_start: *lib + .get(b"obs_frontend_recording_start\0") + .map_err(|e| e.to_string())?, + record_stop: *lib + .get(b"obs_frontend_recording_stop\0") + .map_err(|e| e.to_string())?, + record_active: *lib + .get(b"obs_frontend_recording_active\0") + .map_err(|e| e.to_string())?, + stream_start: *lib + .get(b"obs_frontend_streaming_start\0") + .map_err(|e| e.to_string())?, + stream_stop: *lib + .get(b"obs_frontend_streaming_stop\0") + .map_err(|e| e.to_string())?, + stream_active: *lib + .get(b"obs_frontend_streaming_active\0") + .map_err(|e| e.to_string())?, output_release: *lib .get(b"obs_output_release\0") .map_err(|e| e.to_string())?, @@ -216,6 +240,26 @@ unsafe extern "C" fn change_scene(data: *mut c_void) { } } impl obs_mcp::backend::AttachedFrontend for Frontend { + fn set_output( + &self, + request: obs_mcp::backend::FrontendOutputRequest, + ) -> Result { + use obs_mcp::tools::outputs::OutputKind; + let (active, command) = match (request.kind, request.active) { + (OutputKind::Record, true) => (self.record_active, self.record_start), + (OutputKind::Record, false) => (self.record_active, self.record_stop), + (OutputKind::Stream, true) => (self.stream_active, self.stream_start), + (OutputKind::Stream, false) => (self.stream_active, self.stream_stop), + }; + // SAFETY: frontend start/stop use queued Qt invocations from this worker; + // active getters read atomics. State/library outlive all worker calls. + unsafe { + if active() != request.active { + command(); + } + Ok(obs_mcp::tools::outputs::ActiveOutput { active: active() }) + } + } fn current_scene(&self, _: obs_mcp::tools::EmptyInput) -> obs_mcp::tools::scenes::SceneOutput { obs_mcp::tools::scenes::SceneOutput { name: self.name_of(self.current, self.name, self.release), diff --git a/rust/obs-mcp/src/backend/mod.rs b/rust/obs-mcp/src/backend/mod.rs index b0509f32f5..47c8260e0b 100644 --- a/rust/obs-mcp/src/backend/mod.rs +++ b/rust/obs-mcp/src/backend/mod.rs @@ -52,6 +52,21 @@ pub trait AttachedFrontend { request: crate::tools::scenes::NameInput, ) -> Result; fn output_name(&self, request: crate::tools::outputs::OutputRequest) -> FrontendOutputName; + fn set_output( + &self, + _request: FrontendOutputRequest, + ) -> Result { + Err(crate::server::ToolError::not_ready( + "frontend output control is unavailable", + )) + } +} +/// Start or stop a frontend-managed output, preserving profile/encoder setup. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct FrontendOutputRequest { + pub kind: crate::tools::outputs::OutputKind, + pub active: bool, } /// Current frontend output identity; absent while the frontend has no output. #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, schemars::JsonSchema)] @@ -399,6 +414,12 @@ impl OutputBackend for ObsBackend { crate::tools::waiting::WaitBackend::cancelled(self) } fn start_output(&self, request: OutputRequest) -> Result { + if let Some(frontend) = &self.frontend { + return frontend.set_output(FrontendOutputRequest { + kind: request.kind, + active: true, + }); + } let output = self.output(request.kind).map_err(ToolError::not_ready)?; if !output.active() { if request.kind == OutputKind::Record { @@ -413,6 +434,12 @@ impl OutputBackend for ObsBackend { } fn stop_output(&self, request: OutputRequest) -> Result { + if let Some(frontend) = &self.frontend { + return frontend.set_output(FrontendOutputRequest { + kind: request.kind, + active: false, + }); + } let output = self.output(request.kind).map_err(ToolError::not_ready)?; if output.active() { output.stop(); @@ -423,6 +450,12 @@ impl OutputBackend for ObsBackend { } fn start(&self, kind: OutputKind) -> Result<(), String> { + if let Some(frontend) = &self.frontend { + return frontend + .set_output(FrontendOutputRequest { kind, active: true }) + .map(|_| ()) + .map_err(|error| error.message); + } let output = self.output(kind)?; if output.active() { return Err("the output is already running".to_owned()); @@ -434,6 +467,15 @@ impl OutputBackend for ObsBackend { } fn stop(&self, kind: OutputKind) -> Result<(), String> { + if let Some(frontend) = &self.frontend { + return frontend + .set_output(FrontendOutputRequest { + kind, + active: false, + }) + .map(|_| ()) + .map_err(|error| error.message); + } let output = self.output(kind)?; if !output.active() { return Err("the output is not running".to_owned()); From 897e36c3f369092036b5b96d5d4b4fb397712df4 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 17:15:20 -0800 Subject: [PATCH 29/39] test(mcp): RED tolerate future domain error fields (#4449) --- rust/obs-mcp/tests/mcp/client.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/obs-mcp/tests/mcp/client.rs b/rust/obs-mcp/tests/mcp/client.rs index 35347e40ce..713bc51fbe 100644 --- a/rust/obs-mcp/tests/mcp/client.rs +++ b/rust/obs-mcp/tests/mcp/client.rs @@ -58,7 +58,7 @@ fn client_reuses_typed_inputs_and_structured_outputs() { #[test] fn client_preserves_domain_error_and_rejects_wrong_id() { let (stream, _) = connection( - json!({"jsonrpc":"2.0","id":2,"result":{"isError":true,"structuredContent":{"code":207,"category":"not_ready","message":"video unavailable","retryable":true}}}), + json!({"jsonrpc":"2.0","id":2,"result":{"isError":true,"structuredContent":{"code":207,"category":"not_ready","message":"video unavailable","retryable":true,"future_context":{"stage":"render"}}}}), ); let client = Client::from_connection(stream).unwrap(); assert!( From d8a50602dd4e9f10b1aea59c6860ab6ba2495e8a Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 17:19:32 -0800 Subject: [PATCH 30/39] fix(mcp): preserve domain errors with forward-compatible fields (#4449) --- docs/rust-port/control-api.schema.json | 2 +- rust/obs-mcp/src/server/typed.rs | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/rust-port/control-api.schema.json b/docs/rust-port/control-api.schema.json index 21daa5bf21..5f6e40f4bc 100644 --- a/docs/rust-port/control-api.schema.json +++ b/docs/rust-port/control-api.schema.json @@ -1,5 +1,5 @@ { - "toolError": {"$defs":{"ErrorCategory":{"description":"Domain failure category, using obs-websocket v5 status ranges.","oneOf":[{"const":"not_ready","description":"A resource is absent or not ready (ResourceNotFound/NotReady).","type":"string"},{"const":"wrong_state","description":"The current state prevents the operation (6xx).","type":"string"},{"const":"processing","description":"OBS failed to process the operation (7xx).","type":"string"}]}},"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"A domain failure, distinct from a JSON-RPC fault.","properties":{"category":{"$ref":"#/$defs/ErrorCategory","description":"Stable machine-readable category."},"code":{"description":"obs-websocket v5 RequestStatus code.","format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"message":{"description":"Human-readable context.","type":"string"},"retryable":{"description":"Whether a later retry may succeed.","type":"boolean"}},"required":["code","category","message","retryable"],"title":"ToolError","type":"object"}, + "toolError": {"$defs":{"ErrorCategory":{"description":"Domain failure category, using obs-websocket v5 status ranges.","oneOf":[{"const":"not_ready","description":"A resource is absent or not ready (ResourceNotFound/NotReady).","type":"string"},{"const":"wrong_state","description":"The current state prevents the operation (6xx).","type":"string"},{"const":"processing","description":"OBS failed to process the operation (7xx).","type":"string"}]}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"A domain failure, distinct from a JSON-RPC fault.","properties":{"category":{"$ref":"#/$defs/ErrorCategory","description":"Stable machine-readable category."},"code":{"description":"obs-websocket v5 RequestStatus code.","format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"message":{"description":"Human-readable context.","type":"string"},"retryable":{"description":"Whether a later retry may succeed.","type":"boolean"}},"required":["code","category","message","retryable"],"title":"ToolError","type":"object"}, "tools": [ {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"A media source selection.","properties":{"name":{"description":"Name of an existing media source.","type":"string"}},"required":["name"],"title":"MediaInput","type":"object"},"name":"media_restart","outputSchema":{"$defs":{"MediaState":{"description":"libobs media state.","oneOf":[{"const":"none","description":"Not a controllable media source.","type":"string"},{"const":"playing","description":"Playing.","type":"string"},{"const":"opening","description":"Opening.","type":"string"},{"const":"buffering","description":"Buffering.","type":"string"},{"const":"paused","description":"Paused.","type":"string"},{"const":"stopped","description":"Stopped.","type":"string"},{"const":"ended","description":"Playback reached the end.","type":"string"},{"const":"error","description":"Playback failed.","type":"string"}]}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Media playback snapshot, in milliseconds.","properties":{"duration_ms":{"description":"Total duration, if known.","format":"int64","type":["integer","null"]},"name":{"description":"Source name.","type":"string"},"position_ms":{"description":"Playback position, if known.","format":"int64","type":["integer","null"]},"state":{"$ref":"#/$defs/MediaState","description":"Current media state."}},"required":["name","state"],"title":"MediaStatus","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"A media source selection.","properties":{"name":{"description":"Name of an existing media source.","type":"string"}},"required":["name"],"title":"MediaInput","type":"object"},"name":"media_status","outputSchema":{"$defs":{"MediaState":{"description":"libobs media state.","oneOf":[{"const":"none","description":"Not a controllable media source.","type":"string"},{"const":"playing","description":"Playing.","type":"string"},{"const":"opening","description":"Opening.","type":"string"},{"const":"buffering","description":"Buffering.","type":"string"},{"const":"paused","description":"Paused.","type":"string"},{"const":"stopped","description":"Stopped.","type":"string"},{"const":"ended","description":"Playback reached the end.","type":"string"},{"const":"error","description":"Playback failed.","type":"string"}]}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Media playback snapshot, in milliseconds.","properties":{"duration_ms":{"description":"Total duration, if known.","format":"int64","type":["integer","null"]},"name":{"description":"Source name.","type":"string"},"position_ms":{"description":"Playback position, if known.","format":"int64","type":["integer","null"]},"state":{"$ref":"#/$defs/MediaState","description":"Current media state."}},"required":["name","state"],"title":"MediaStatus","type":"object"}}, diff --git a/rust/obs-mcp/src/server/typed.rs b/rust/obs-mcp/src/server/typed.rs index d1f3d5a4e0..b271048290 100644 --- a/rust/obs-mcp/src/server/typed.rs +++ b/rust/obs-mcp/src/server/typed.rs @@ -51,7 +51,6 @@ pub enum ErrorCategory { } /// A domain failure, distinct from a JSON-RPC fault. #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(deny_unknown_fields)] pub struct ToolError { /// obs-websocket v5 RequestStatus code. pub code: u16, From dfb1549a6cd98229befc837bf3b4687cb585b926 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 17:26:13 -0800 Subject: [PATCH 31/39] fix(mcp): preserve queued frontend start-stop ordering (#4448) --- rust/obs-mcp-module/src/platform/unix.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/rust/obs-mcp-module/src/platform/unix.rs b/rust/obs-mcp-module/src/platform/unix.rs index 1925c8fb95..715ceee5f4 100644 --- a/rust/obs-mcp-module/src/platform/unix.rs +++ b/rust/obs-mcp-module/src/platform/unix.rs @@ -254,9 +254,9 @@ impl obs_mcp::backend::AttachedFrontend for Frontend { // SAFETY: frontend start/stop use queued Qt invocations from this worker; // active getters read atomics. State/library outlive all worker calls. unsafe { - if active() != request.active { - command(); - } + // The frontend checks idempotency on the UI thread. Do not skip a + // stop based on a stale inactive sample while a start is queued. + command(); Ok(obs_mcp::tools::outputs::ActiveOutput { active: active() }) } } From 1bde274ed410f125f7195a376628a77291640673 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 17:26:13 -0800 Subject: [PATCH 32/39] fix(mcp): preserve queued frontend start-stop ordering (#4448) --- rust/obs-mcp-module/src/platform/unix.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/rust/obs-mcp-module/src/platform/unix.rs b/rust/obs-mcp-module/src/platform/unix.rs index 1925c8fb95..715ceee5f4 100644 --- a/rust/obs-mcp-module/src/platform/unix.rs +++ b/rust/obs-mcp-module/src/platform/unix.rs @@ -254,9 +254,9 @@ impl obs_mcp::backend::AttachedFrontend for Frontend { // SAFETY: frontend start/stop use queued Qt invocations from this worker; // active getters read atomics. State/library outlive all worker calls. unsafe { - if active() != request.active { - command(); - } + // The frontend checks idempotency on the UI thread. Do not skip a + // stop based on a stale inactive sample while a start is queued. + command(); Ok(obs_mcp::tools::outputs::ActiveOutput { active: active() }) } } From ba516ac229d0d07ca30e3e49d21a51ec0b0869bd Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 18:10:32 -0800 Subject: [PATCH 33/39] test(mcp): RED startup without reachable X or Wayland (#4464) --- rust/obs-studio-rust/tests/cli/mcp_stdio.rs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/rust/obs-studio-rust/tests/cli/mcp_stdio.rs b/rust/obs-studio-rust/tests/cli/mcp_stdio.rs index b8b5722910..cda685cb6c 100644 --- a/rust/obs-studio-rust/tests/cli/mcp_stdio.rs +++ b/rust/obs-studio-rust/tests/cli/mcp_stdio.rs @@ -16,7 +16,23 @@ const TIMEOUT: Duration = Duration::from_secs(60); #[test] fn mcp_flag_serves_obs_over_stdio_and_exits_on_eof() { - let mut child = Command::new(env!("CARGO_BIN_EXE_obs-studio-rust")) + exercise_mcp(false); +} + +#[test] +fn mcp_starts_without_a_reachable_x_or_wayland_display() { + exercise_mcp(true); +} + +fn exercise_mcp(no_display: bool) { + let mut command = Command::new(env!("CARGO_BIN_EXE_obs-studio-rust")); + if no_display { + command + .env("DISPLAY", ":54321") + .env("XDG_SESSION_TYPE", "wayland") + .env("WAYLAND_DISPLAY", "/nonexistent/obs-mcp-wayland"); + } + let mut child = command .arg("--mcp") .stdin(Stdio::piped()) .stdout(Stdio::piped()) From 62310aab7246f15356b3f079d3b121b7dca990ee Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 18:16:43 -0800 Subject: [PATCH 34/39] fix(mcp): GREEN start headless without an X server (#4464) --- docs/features.md | 6 ++ libobs/obs-nix.c.h | 58 +++++++++++++- rust/obs-mcp/src/ffi/host_display.rs | 112 +++++++++++++++++++++++++++ rust/obs-mcp/src/ffi/mod.rs | 12 ++- rust/obs-mcp/src/ffi/setup.rs | 1 + 5 files changed, 185 insertions(+), 4 deletions(-) create mode 100644 rust/obs-mcp/src/ffi/host_display.rs diff --git a/docs/features.md b/docs/features.md index e254acf9eb..010ff768f1 100644 --- a/docs/features.md +++ b/docs/features.md @@ -75,6 +75,12 @@ not get a line. ### Headless and automation +- **MCP starts without X11.** The headless host uses an available Wayland + compositor or X server, and serves control requests without either display. + Video operations report unavailability when no display can create graphics. + *Linux*, 2026-11-09. Issue [#4464](https://github.com/obs-rust/obs-studio/issues/4464), + PR [#4466](https://github.com/obs-rust/obs-studio/pull/4466). + - **Typed MCP control.** Existing OBS MCP tools publish input and output schemas, structured results and machine-readable domain errors. Read operations carry annotations, and repeated output start/stop calls succeed with current state. diff --git a/libobs/obs-nix.c.h b/libobs/obs-nix.c.h index 3ff47ffd17..95781ae915 100644 --- a/libobs/obs-nix.c.h +++ b/libobs/obs-nix.c.h @@ -343,21 +343,75 @@ void log_system_info(void) obs_nix_x11_log_info(); } +/* A headless host has no compositor to supply keyboard events. Keep the + * hotkey API usable without opening X11 or dereferencing a null wl_display. */ +static bool headless_hotkeys_init(struct obs_core_hotkeys *hotkeys) +{ + UNUSED_PARAMETER(hotkeys); + return true; +} + +static void headless_hotkeys_free(struct obs_core_hotkeys *hotkeys) +{ + UNUSED_PARAMETER(hotkeys); +} + +static bool headless_hotkeys_pressed(obs_hotkeys_platform_t *context, obs_key_t key) +{ + UNUSED_PARAMETER(context); + UNUSED_PARAMETER(key); + return false; +} + +static void headless_hotkeys_key_to_str(obs_key_t key, struct dstr *str) +{ + const char *name = obs_key_to_name(key); + dstr_copy(str, name ? name : ""); +} + +static obs_key_t headless_hotkeys_from_virtual(int sym) +{ + UNUSED_PARAMETER(sym); + return OBS_KEY_NONE; +} + +static int headless_hotkeys_to_virtual(obs_key_t key) +{ + UNUSED_PARAMETER(key); + return 0; +} + +static const struct obs_nix_hotkeys_vtable headless_hotkeys_vtable = { + .init = headless_hotkeys_init, + .free = headless_hotkeys_free, + .is_pressed = headless_hotkeys_pressed, + .key_to_str = headless_hotkeys_key_to_str, + .key_from_virtual_key = headless_hotkeys_from_virtual, + .key_to_virtual_key = headless_hotkeys_to_virtual, +}; + bool obs_hotkeys_platform_init(struct obs_core_hotkeys *hotkeys) { /* The X11 and Wayland key tables had Volume Up and Down swapped until * #2635. */ hotkeys->saved_volume_keys_swapped = true; + if (obs_get_nix_platform() == OBS_NIX_PLATFORM_WAYLAND && !obs_get_nix_platform_display()) { + hotkeys_vtable = &headless_hotkeys_vtable; + return hotkeys_vtable->init(hotkeys); + } + switch (obs_get_nix_platform()) { case OBS_NIX_PLATFORM_X11_EGL: hotkeys_vtable = obs_nix_x11_get_hotkeys_vtable(); break; -#ifdef ENABLE_WAYLAND case OBS_NIX_PLATFORM_WAYLAND: +#ifdef ENABLE_WAYLAND hotkeys_vtable = obs_nix_wayland_get_hotkeys_vtable(); - break; +#else + hotkeys_vtable = &headless_hotkeys_vtable; #endif + break; default: break; } diff --git a/rust/obs-mcp/src/ffi/host_display.rs b/rust/obs-mcp/src/ffi/host_display.rs new file mode 100644 index 0000000000..cdaf9b0a26 --- /dev/null +++ b/rust/obs-mcp/src/ffi/host_display.rs @@ -0,0 +1,112 @@ +//! Display ownership for a self-hosted libobs; attached GUI hosts do not use this. + +#[cfg(all(unix, not(target_os = "macos")))] +mod unix { + use std::ffi::c_void; + + const X11: i32 = 1; + const WAYLAND: i32 = 2; + type Connect = unsafe extern "C" fn(*const std::ffi::c_char) -> *mut c_void; + type Disconnect = unsafe extern "C" fn(*mut c_void); + + unsafe extern "C" { + fn obs_set_nix_platform(platform: i32); + fn obs_get_nix_platform() -> i32; + fn obs_set_nix_platform_display(display: *mut c_void); + fn obs_get_nix_platform_display() -> *mut c_void; + } + + pub struct Display { + connection: *mut c_void, + disconnect: Option, + } + + impl Display { + pub fn open() -> Self { + // SAFETY: resolve optional functions from libobs's already loaded + // display libraries. Each non-null symbol has its documented C ABI. + unsafe { + let connect = libc::dlsym(libc::RTLD_DEFAULT, c"wl_display_connect".as_ptr()); + let disconnect = libc::dlsym(libc::RTLD_DEFAULT, c"wl_display_disconnect".as_ptr()); + if !connect.is_null() && !disconnect.is_null() { + let connect: Connect = std::mem::transmute(connect); + let disconnect: Disconnect = std::mem::transmute(disconnect); + let connection = connect(std::ptr::null()); + if !connection.is_null() { + obs_set_nix_platform(WAYLAND); + obs_set_nix_platform_display(connection); + return Self { + connection, + disconnect: Some(disconnect), + }; + } + } + // Preserve the existing X11 video path when an X server really + // is available; a stale DISPLAY must not make startup fail. + let open = libc::dlsym(libc::RTLD_DEFAULT, c"XOpenDisplay".as_ptr()); + let close = libc::dlsym(libc::RTLD_DEFAULT, c"XCloseDisplay".as_ptr()); + if !open.is_null() && !close.is_null() { + let open: Connect = std::mem::transmute(open); + let close: unsafe extern "C" fn(*mut c_void) -> i32 = + std::mem::transmute(close); + let connection = open(std::ptr::null()); + if !connection.is_null() { + close(connection); + obs_set_nix_platform(X11); + return Self { + connection: std::ptr::null_mut(), + disconnect: None, + }; + } + } + obs_set_nix_platform(WAYLAND); + obs_set_nix_platform_display(std::ptr::null_mut()); + Self { + connection: std::ptr::null_mut(), + disconnect: None, + } + } + } + } + + impl Drop for Display { + fn drop(&mut self) { + // SAFETY: Libobs drops this lease after obs_shutdown, and this is + // the sole owner of the connection created by wl_display_connect. + unsafe { + obs_set_nix_platform_display(std::ptr::null_mut()); + if let Some(disconnect) = self.disconnect { + disconnect(self.connection); + } + } + } + } + + pub fn require_video_display() -> Result<(), String> { + // SAFETY: called after startup while the display lease is alive. + if unsafe { obs_get_nix_platform() == WAYLAND && obs_get_nix_platform_display().is_null() } + { + Err("video is unavailable: no reachable X11 or Wayland display".to_owned()) + } else { + Ok(()) + } + } +} + +#[cfg(all(unix, not(target_os = "macos")))] +pub use unix::{Display, require_video_display}; + +#[cfg(not(all(unix, not(target_os = "macos"))))] +pub struct Display; + +#[cfg(not(all(unix, not(target_os = "macos"))))] +impl Display { + pub fn open() -> Self { + Self + } +} + +#[cfg(not(all(unix, not(target_os = "macos"))))] +pub fn require_video_display() -> Result<(), String> { + Ok(()) +} diff --git a/rust/obs-mcp/src/ffi/mod.rs b/rust/obs-mcp/src/ffi/mod.rs index ab43faeb28..c17d81830a 100644 --- a/rust/obs-mcp/src/ffi/mod.rs +++ b/rust/obs-mcp/src/ffi/mod.rs @@ -622,6 +622,7 @@ pub fn render_rgba(source: &Source, from: (u32, u32), to: (u32, u32)) -> Result< mod stdio; pub use stdio::claim_stdout; +mod host_display; mod setup; #[cfg(feature = "fault-injection")] pub use setup::fail_audio_mixer; @@ -630,7 +631,9 @@ pub use setup::{Pipeline, configure}; /// A started libobs; dropping it shuts libobs down. /// /// Every other value from this module must be dropped first. -pub struct Libobs(()); +pub struct Libobs { + _display: host_display::Display, +} impl Libobs { /// Starts libobs with the `en-US` locale and no module search paths. @@ -639,12 +642,17 @@ impl Libobs { /// /// Returns an error when libobs refuses to start. pub fn start() -> Result { + // SAFETY: this query only reads libobs's existing startup state. + if unsafe { sys::obs_initialized() } { + return Err("libobs is already initialized".to_owned()); + } + let display = host_display::Display::open(); // SAFETY: the locale is a NUL-terminated static string; null optional // paths and name store are supported by `obs_startup`. let started = unsafe { sys::obs_startup(c"en-US".as_ptr(), std::ptr::null(), std::ptr::null_mut()) }; if started { - Ok(Self(())) + Ok(Self { _display: display }) } else { Err("obs_startup failed".to_owned()) } diff --git a/rust/obs-mcp/src/ffi/setup.rs b/rust/obs-mcp/src/ffi/setup.rs index 1ad38353a3..e6945ee978 100644 --- a/rust/obs-mcp/src/ffi/setup.rs +++ b/rust/obs-mcp/src/ffi/setup.rs @@ -187,6 +187,7 @@ fn path_c(path: &Path) -> Result { } fn reset_video(options: &StartOptions) -> Result<(), String> { + super::host_display::require_video_display()?; let module = c_string(&options.graphics_module, "graphics module")?; let mut info = sys::obs_video_info { graphics_module: module.as_ptr(), From 3b14236e223d4c0aedabed17b3db66124f3b93f2 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 18:43:01 -0800 Subject: [PATCH 35/39] ci: refresh client claim check after correcting PR reference From 1c29021959b9b1eae90918ba8f10213b32cf68ba Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 19:12:10 -0800 Subject: [PATCH 36/39] test(ci): RED require isolated transition-video scheduling (#4468) --- ci/test_sanitize_harness.py | 8 +++++++- ci/test_tier2_concurrency.py | 5 ++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/ci/test_sanitize_harness.py b/ci/test_sanitize_harness.py index 63777352cb..6d54160fe6 100644 --- a/ci/test_sanitize_harness.py +++ b/ci/test_sanitize_harness.py @@ -134,7 +134,7 @@ def write_stub(directory: Path, name: str, body: str) -> Path: TIMING_TESTS_D = ( "test_slideshow_mem_cap", ) -TIMING_TESTS_GRAPH = ("test_media_cover_art_monitor", "test_media_sync_offset_restart", "test_async_delay_audio", "test_dock_proportions", "test_dock_state_restart", "test_deinterlace_mode_load", "test_hotkey_capture_mnemonic", "test_volume_meter_ticker") +TIMING_TESTS_GRAPH = ("test_media_cover_art_monitor", "test_media_sync_offset_restart", "test_async_delay_audio", "test_dock_proportions", "test_dock_state_restart", "test_deinterlace_mode_load", "test_hotkey_capture_mnemonic", "test_volume_meter_ticker", "test_source_transition_video") TEST_GRAPH = ROOT / "test" / "cmocka" / "build" / "test-graph.json" @@ -147,6 +147,12 @@ def test_timing_tests_hold_the_timing_lock(self): for name in TIMING_TESTS_GRAPH: self.assertIn("timing", tests[name].get("resource_locks", []), name) + def test_transition_video_has_exclusive_ctest_scheduling(self): + # Its frame-bound callback assertions race a background texture trylock + # under competing native-graphics load (#4468). + test = json.loads(TEST_GRAPH.read_text(encoding="utf-8"))["tests"]["test_source_transition_video"] + self.assertTrue(test.get("run_serial"), "transition video must not compete with other CTest processes") + def test_a_resource_lock_runs_alone_in_the_pool(self): payload = json.dumps( {"tests": [{"name": "t", "command": ["/b/t"], "properties": [{"name": "RESOURCE_LOCK", "value": ["timing"]}]}]} diff --git a/ci/test_tier2_concurrency.py b/ci/test_tier2_concurrency.py index 59c3d5bf33..b22f091e48 100644 --- a/ci/test_tier2_concurrency.py +++ b/ci/test_tier2_concurrency.py @@ -22,6 +22,7 @@ "test_pipewire_screencast_shm": 90, "test_screencast_portal_teardown": 60, "test_vlc_audio_pacing": 120, + "test_source_transition_video": 120, "test_xshm_resolution_change": 60, } @@ -107,7 +108,9 @@ def test_isolated_tests_can_overlap_without_losing_timeouts_or_cases(self): name = test["name"] properties = {p["name"]: p["value"] for p in test["properties"]} with self.subTest(test=name): - exclusive = name.startswith("test_deinterlace_2x_field_order_") or (name == "test_xshm_resolution_change" and not wrapper) + exclusive = (name.startswith("test_deinterlace_2x_field_order_") + or name == "test_source_transition_video" + or (name == "test_xshm_resolution_change" and not wrapper)) self.assertEqual(bool(properties.get("RUN_SERIAL")), exclusive, "Retain timing isolation and unisolated display mutation") self.assertEqual(properties["TIMEOUT"], TIMEOUTS[name]) From 7beb525eab9db563d65030b8111c39948ee66276 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 19:12:50 -0800 Subject: [PATCH 37/39] ci: GREEN isolate transition video timing fixture (#4468) --- test/cmocka/build/test-graph.json | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/test/cmocka/build/test-graph.json b/test/cmocka/build/test-graph.json index 60dcf97315..7d49299c07 100644 --- a/test/cmocka/build/test-graph.json +++ b/test/cmocka/build/test-graph.json @@ -23874,7 +23874,11 @@ ], "suite": "graphics", "working_directory": "${runtime}", - "timeout_seconds": 120 + "timeout_seconds": 120, + "resource_locks": [ + "timing" + ], + "run_serial": true }, "test_source_video_tick_steps": { "target": "test_source_video_tick_steps", From 9b14acc81c0af49153a0db02f8360c5283f8a4f9 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 20:26:55 -0800 Subject: [PATCH 38/39] test(ci): RED keep uncached recovery in MCP plugin child (#4478) --- ci/test_tier2_build_errors.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/ci/test_tier2_build_errors.py b/ci/test_tier2_build_errors.py index e4f2106f73..4cc4e0d0eb 100644 --- a/ci/test_tier2_build_errors.py +++ b/ci/test_tier2_build_errors.py @@ -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 From fbaaaf0ad1e4b0067953a97cd56e08ccb974cd5c Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 20:27:31 -0800 Subject: [PATCH 39/39] ci: GREEN preserve uncached recovery for MCP plugin builds (#4478) --- rust/tools/linux-validate/validate.sh | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/rust/tools/linux-validate/validate.sh b/rust/tools/linux-validate/validate.sh index 672dfdf50c..322feb4a24 100755 --- a/rust/tools/linux-validate/validate.sh +++ b/rust/tools/linux-validate/validate.sh @@ -263,10 +263,10 @@ else echo 'cache-healthy=false' >>"$GITHUB_OUTPUT" fi fi - ( - if [ "$daemon_unavailable" = 1 ]; then export ZCCACHE_DISABLE=1; fi - cmake --build "$build" --target "${tier2_targets[@]}" -- -k 0 - ) >"$build.build.log" 2>&1 || + # Later MCP plugin builds run in a child shell too: keep the bypass + # in this validation process when the daemon cannot be recovered. + if [ "$daemon_unavailable" = 1 ]; then export ZCCACHE_DISABLE=1; fi + cmake --build "$build" --target "${tier2_targets[@]}" -- -k 0 >"$build.build.log" 2>&1 || { uv run --no-project "$SRC"/rust/tools/linux-validate/build_errors.py "$build.build.log"; exit 1; } else uv run --no-project "$SRC"/rust/tools/linux-validate/build_errors.py "$build.build.log"