From 59f20127c53f999e637dbd617f28e72884cf59a7 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 13:31:23 -0800 Subject: [PATCH 01/11] 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 eca653e09c853beeaee912985eeb7ea7cc707856 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 13:43:10 -0800 Subject: [PATCH 02/11] 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 4d6a02470563ac34cf95d049a7ad6c360731d818 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 13:43:49 -0800 Subject: [PATCH 03/11] 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 45721416395f59322e4f6a1312956706cc03c91e Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 13:47:25 -0800 Subject: [PATCH 04/11] 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 8adc952dbda668a77c0f0fd049bdf7da1bd9359c Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 13:53:52 -0800 Subject: [PATCH 05/11] 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 a62df0153f1cba450e4cdf6fa18aa2daaea86516 Mon Sep 17 00:00:00 2001 From: Zachary Vorhies Date: Mon, 9 Nov 2026 23:16:20 +0000 Subject: [PATCH 06/11] ci: fix master self-tests broken by unchecked merges (#4453) * ci: fix master self-tests broken by unchecked merges #4387 re-added obs-hotkey-update-atomic.c.h to libobs.core+ after #4220 moved it to its ported group, so the C body was compiled twice (test_build_groups, test_ported_sources, test_conversion_measure). #4136 gave ci/hooks/pre_commit_fmt.py a bare python3 shebang (test_uv_run). Both landed through admin merges without CI on 2026-11-09. * libobs: clang-format two files from unchecked merges --- ci/hooks/pre_commit_fmt.py | 2 +- libobs/build/libobs.core+.h.c | 1 - libobs/obs-internal.h | 1 - libobs/obs-output.c.h | 2 -- 4 files changed, 1 insertion(+), 5 deletions(-) diff --git a/ci/hooks/pre_commit_fmt.py b/ci/hooks/pre_commit_fmt.py index 8f87ed665d..ba1909014a 100644 --- a/ci/hooks/pre_commit_fmt.py +++ b/ci/hooks/pre_commit_fmt.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python3 +#!/usr/bin/env -S uv run --no-project --script """The pre-commit hook body: format the Rust tree before it is committed. Installed by `./install-hooks` (or `./push --install-hooks`). It runs the same diff --git a/libobs/build/libobs.core+.h.c b/libobs/build/libobs.core+.h.c index e256e54d44..e91925f016 100644 --- a/libobs/build/libobs.core+.h.c +++ b/libobs/build/libobs.core+.h.c @@ -17,7 +17,6 @@ #include "libobs/obs-hotkey-owned-translations.c.h" #include "libobs/obs-hotkey-routed-callback.c.h" #include "libobs/obs-hotkey-routing-controls.c.h" -#include "libobs/obs-hotkey-update-atomic.c.h" #include "libobs/obs-hotkey.c.h" #include "libobs/obs-module-init.c.h" #include "libobs/obs-module-lists.c.h" diff --git a/libobs/obs-internal.h b/libobs/obs-internal.h index 996ded9520..25b02e4c8e 100644 --- a/libobs/obs-internal.h +++ b/libobs/obs-internal.h @@ -2347,7 +2347,6 @@ struct obs_encoder_preferred_range_fields { }; struct obs_encoder_preferred_range_fields obs_encoder_preferred_range_fields(const obs_encoder_t *encoder); - /* Borrowed scaled-axis addresses, with no ownership or value conversion. */ struct obs_encoder_scaling_enabled_fields { const uint32_t *width; diff --git a/libobs/obs-output.c.h b/libobs/obs-output.c.h index 091d881d3f..c91d46e780 100644 --- a/libobs/obs-output.c.h +++ b/libobs/obs-output.c.h @@ -2561,8 +2561,6 @@ const char *obs_get_output_supported_audio_codecs(const char *id) return info ? info->encoded_audio_codecs : NULL; } - - /* File-local macros: keep them out of the next source of a unity build. */ #undef get_weak From f0cc31459ffe458dd7b9cecb0971ffad0a0419a3 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 13:31:23 -0800 Subject: [PATCH 07/11] 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 64d6b1809d24324c107f214bf4f24559ffc5eb66 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 13:43:10 -0800 Subject: [PATCH 08/11] 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 c06cafb9b97fed011b68a760f427ff7debcd71d7 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 13:43:49 -0800 Subject: [PATCH 09/11] 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 992a7a9fb65529f5b03ce58dab3a4a8798f43d57 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 13:47:25 -0800 Subject: [PATCH 10/11] 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 3f045ed3225bee060b38b30ab34cf9938dbc4de5 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Mon, 9 Nov 2026 13:53:52 -0800 Subject: [PATCH 11/11] 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,