From bacccf85ce33879bc0eb4644422db7d4345f287c Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 13:31:23 -0800 Subject: [PATCH 01/13] 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/13] 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/13] 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/13] 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/13] 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/13] 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/13] 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/13] 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/13] 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/13] 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/13] 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/13] 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 3f1ef1c720507dc13ef5608da09f54d38e456ee2 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 15:51:05 -0800 Subject: [PATCH 13/13] 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,