obs-mcp 0.2.0

OBS Studio control server for AI assistants via MCP and the OBS WebSocket protocol
Documentation
//! Tool definitions, JSON-schema building and dispatch for obs-mcp.
//!
//! Every MCP tool is a thin, declarative wrapper around one request of the
//! OBS WebSocket v5 protocol. The full catalog lives in [`tools_table`]
//! (generated by `scripts/gen_tools_table.py`); this module defines the
//! building blocks and the generic dispatch that turns a tool call into an
//! OBS request.

use std::borrow::Cow;
use std::sync::Arc;

use rmcp::{
    ErrorData,
    handler::server::tool::ToolCallContext,
    model::{CallToolResponse, CallToolResult, ContentBlock},
};
use serde_json::{Map, Value, json};

use crate::obs::ObsClient;
use crate::server::ObsMcpServer;

/// The JSON type of a tool parameter.
#[derive(Debug, Clone, Copy)]
pub enum ParamKind {
    Str,
    Num,
    Bool,
    Obj,
    /// A closed set of string values.
    Enum(&'static [&'static str]),
}

/// One tool parameter: name, type, help text and requiredness.
#[derive(Debug, Clone, Copy)]
pub struct Param {
    pub name: &'static str,
    pub kind: ParamKind,
    pub desc: &'static str,
    pub required: bool,
}

/// Build a [`Param`] (short alias used by the generated table).
pub const fn p(
    name: &'static str,
    kind: ParamKind,
    desc: &'static str,
    required: bool,
) -> Param {
    Param {
        name,
        kind,
        desc,
        required,
    }
}

/// A declarative tool row: name, description, OBS request type, parameters
/// and any parameter renames between the tool argument name and the OBS
/// request field name.
#[derive(Debug, Clone)]
pub struct ToolDef {
    pub name: &'static str,
    pub desc: &'static str,
    pub request_type: &'static str,
    pub params: Vec<Param>,
    pub renames: Vec<(&'static str, &'static str)>,
}

impl ToolDef {
    pub fn new(name: &'static str, desc: &'static str, request_type: &'static str) -> Self {
        Self {
            name,
            desc,
            request_type,
            params: Vec::new(),
            renames: Vec::new(),
        }
    }

    pub fn with_params(mut self, params: Vec<Param>) -> Self {
        self.params = params;
        self
    }

    pub fn with_renames(mut self, renames: Vec<(&'static str, &'static str)>) -> Self {
        self.renames = renames;
        self
    }

    /// JSON Schema (draft 2020-12 subset) for the tool input object.
    pub fn input_schema(&self) -> Map<String, Value> {
        let mut properties = Map::new();
        let mut required = Vec::new();
        for param in &self.params {
            let mut prop = json!({ "type": param_json_type(param.kind) });
            if let ParamKind::Enum(variants) = param.kind {
                prop["enum"] = Value::Array(
                    variants.iter().map(|v| Value::String((*v).to_string())).collect(),
                );
            }
            prop["description"] = Value::String(param.desc.to_string());
            properties.insert(param.name.to_string(), prop);
            if param.required {
                required.push(param.name.to_string());
            }
        }
        let mut schema = Map::new();
        schema.insert("type".into(), Value::String("object".into()));
        schema.insert("properties".into(), Value::Object(properties));
        if !required.is_empty() {
            schema.insert(
                "required".into(),
                Value::Array(required.into_iter().map(Value::String).collect()),
            );
        }
        schema.insert("additionalProperties".into(), Value::Bool(true));
        schema
    }
}

fn param_json_type(kind: ParamKind) -> &'static str {
    match kind {
        ParamKind::Str | ParamKind::Enum(_) => "string",
        ParamKind::Num => "number",
        ParamKind::Bool => "boolean",
        ParamKind::Obj => "object",
    }
}

/// Entry point for a tool call: build the OBS request data from the raw
/// tool arguments (applying renames), send it, and format the response.
pub async fn dispatch(
    client: &ObsClient,
    def: &ToolDef,
    ctx: ToolCallContext<'_, ObsMcpServer>,
) -> Result<CallToolResponse, ErrorData> {
    let args = ctx.arguments.unwrap_or_default();

    // obs-get-status reports local server + connection state, not an OBS
    // request result.
    if def.name == "obs-get-status" {
        return Ok(CallToolResult::success(vec![ContentBlock::text(
            serde_json::to_string_pretty(&client.status_json().await).unwrap_or_default(),
        )])
        .into());
    }

    let mut data: Map<String, Value> = args;
    for (from, to) in &def.renames {
        if let Some(v) = data.remove(*from) {
            data.insert(to.to_string(), v);
        }
    }

    let payload = if data.is_empty() {
        None
    } else {
        Some(Value::Object(data))
    };

    match client.send_request(def.request_type, payload).await {
        Ok(resp) => Ok(CallToolResult::success(vec![ContentBlock::text(
            serde_json::to_string_pretty(&resp).unwrap_or_else(|_| "{}".to_string()),
        )])
        .into()),
        Err(e) => Ok(CallToolResult::error(vec![ContentBlock::text(format!(
            "request {} failed: {e}",
            def.request_type
        ))])
        .into()),
    }
}

/// Register every tool from the generated table into the given router.
pub fn register_tools(
    router: &mut rmcp::handler::server::tool::ToolRouter<ObsMcpServer>,
    client: &ObsClient,
) {
    for def in crate::tools_table::all_tools() {
        let schema = Arc::new(def.input_schema());
        let desc = Cow::Borrowed(def.desc);
        let def = Arc::new(def);
        let client = client.clone();
        router.add_route(rmcp::handler::server::router::tool::ToolRoute::new_dyn(
            rmcp::model::Tool::new(def.name, desc, schema),
            move |ctx| {
                let client = client.clone();
                let def = Arc::clone(&def);
                Box::pin(async move { dispatch(&client, &def, ctx).await })
            },
        ));
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn schema_builder_marks_required_and_optional() {
        let def = ToolDef::new("obs-set-input-mute", "d", "SetInputMute").with_params(vec![
            p("inputName", ParamKind::Str, "Name of the input.", true),
            p("inputMuted", ParamKind::Bool, "True to mute.", true),
        ]);
        let schema = def.input_schema();
        assert_eq!(schema["type"], "object");
        let required = schema["required"].as_array().unwrap();
        assert_eq!(required.len(), 2);
        assert_eq!(schema["properties"]["inputName"]["type"], "string");
        assert_eq!(schema["properties"]["inputMuted"]["type"], "boolean");
    }

    #[test]
    fn enum_params_expose_variants() {
        let def = ToolDef::new("obs-trigger-media-input-action", "d", "TriggerMediaInputAction")
            .with_params(vec![p(
                "mediaAction",
                ParamKind::Enum(&["OBS_MEDIA_STATE_PLAYING", "OBS_MEDIA_STATE_PAUSED"]),
                "Action to trigger.",
                true,
            )]);
        let schema = def.input_schema();
        let variants = schema["properties"]["mediaAction"]["enum"].as_array().unwrap();
        assert_eq!(variants.len(), 2);
        assert_eq!(variants[0], "OBS_MEDIA_STATE_PLAYING");
    }

    #[test]
    fn generated_table_is_complete_and_unique() {
        let tools = crate::tools_table::all_tools();
        // The count is derived from the table itself; no literal is pinned.
        // The floor guards against a broken generator silently shrinking
        // the catalog.
        assert!(tools.len() > 100, "catalog unexpectedly small: {}", tools.len());
        let mut names: Vec<&str> = tools.iter().map(|t| t.name).collect();
        names.sort();
        names.dedup();
        assert_eq!(names.len(), tools.len(), "tool names must be unique");
        // Every tool declares a non-empty request type.
        for t in &tools {
            assert!(!t.request_type.is_empty());
        }
    }
}