obs-mcp 0.2.0

OBS Studio control server for AI assistants via MCP and the OBS WebSocket protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
//! OBS WebSocket v5 client.
//!
//! Implements the obs-websocket protocol over `ws://` (TLS `wss://` is not
//! supported): the Hello handshake, SHA-256 challenge authentication, the
//! Identify exchange, and correlated request/response with per-request
//! timeouts. The connection runs in a background task that reconnects
//! automatically when OBS is restarted or the socket drops.

use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::{Duration, Instant};

use anyhow::{anyhow, Result};
use base64::Engine;
use futures_util::{SinkExt, StreamExt};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use tokio::sync::{mpsc, oneshot, Mutex};
use tokio::time::timeout;
use tokio_tungstenite::{
    MaybeTlsStream, WebSocketStream, connect_async,
    tungstenite::{Message, client::IntoClientRequest},
};

/// Per-request timeout, mirroring the reference client.
const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
/// Deadline for the full connect + identify handshake.
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(5);
/// Delay between automatic reconnection attempts.
const RECONNECT_DELAY: Duration = Duration::from_millis(1000);

type WsStream = WebSocketStream<MaybeTlsStream<tokio::net::TcpStream>>;

/// Commands sent from tool handlers to the connection task.
enum Command {
    Request {
        id: u64,
        request_type: String,
        data: Option<Value>,
        tx: oneshot::Sender<Result<Value, String>>,
    },
}

/// Outcome of the connection task's main loop.
enum LoopExit {
    Shutdown,
    Retry,
}

/// Live connection metadata reported by `obs-get-status`.
#[derive(Debug, Clone, Serialize)]
pub struct ConnectionStatus {
    pub connected: bool,
    pub identified: bool,
    pub url: String,
    pub has_password: bool,
    pub auto_start_configured: bool,
    pub auto_start_triggered: bool,
    pub obs_studio_version: Option<String>,
    pub obs_web_socket_version: Option<String>,
    pub rpc_version: Option<u64>,
}

#[derive(Default)]
struct SharedInfo {
    connected: bool,
    identified: bool,
    obs_studio_version: Option<String>,
    obs_web_socket_version: Option<String>,
    rpc_version: Option<u64>,
}

struct ClientState {
    task: Option<tokio::task::JoinHandle<()>>,
    cmd_tx: Option<mpsc::Sender<Command>>,
}

/// A cheaply cloneable handle to the OBS WebSocket connection.
#[derive(Clone)]
pub struct ObsClient {
    url: String,
    password: Option<String>,
    start_command: Option<String>,
    start_triggered: Arc<AtomicBool>,
    next_id: Arc<AtomicU64>,
    info: Arc<Mutex<SharedInfo>>,
    state: Arc<Mutex<ClientState>>,
}

impl ObsClient {
    /// Build a client from the standard environment variables.
    pub fn from_env() -> Self {
        let url = std::env::var("OBS_WEBSOCKET_URL")
            .unwrap_or_else(|_| "ws://localhost:4455".to_string());
        let password = std::env::var("OBS_WEBSOCKET_PASSWORD").ok();
        let start_command = std::env::var("OBS_START_COMMAND")
            .ok()
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty());
        Self {
            url,
            password,
            start_command,
            start_triggered: Arc::new(AtomicBool::new(false)),
            next_id: Arc::new(AtomicU64::new(1)),
            info: Arc::new(Mutex::new(SharedInfo::default())),
            state: Arc::new(Mutex::new(ClientState {
                task: None,
                cmd_tx: None,
            })),
        }
    }

    /// Launch OBS once, on the first failed connection attempt, when
    /// `OBS_START_COMMAND` is configured. The command runs detached via
    /// `sh -c` so the server never blocks on it.
    fn maybe_start_obs(&self) {
        let Some(command) = &self.start_command else {
            return;
        };
        if self.start_triggered.swap(true, Ordering::SeqCst) {
            return;
        }
        tracing::info!("OBS not reachable; launching via OBS_START_COMMAND: {command}");
        let mut child = tokio::process::Command::new("sh")
            .arg("-c")
            .arg(command)
            .stdin(std::process::Stdio::null())
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .kill_on_drop(false)
            .spawn();
        if let Err(e) = &mut child {
            tracing::warn!("failed to start OBS via OBS_START_COMMAND: {e}");
        } else {
            // Detach: let the child outlive this connection task.
            drop(child);
        }
    }

    /// Send one request and wait for its correlated response.
    pub async fn send_request(&self, request_type: &str, data: Option<Value>) -> Result<Value> {
        let tx = self.ensure_connected().await?;
        let id = self.next_id.fetch_add(1, Ordering::SeqCst);
        let (rtx, rrx) = oneshot::channel();
        tx.send(Command::Request {
            id,
            request_type: request_type.to_string(),
            data,
            tx: rtx,
        })
        .await
        .map_err(|_| anyhow!("OBS WebSocket connection is closed"))?;

        match timeout(REQUEST_TIMEOUT, rrx).await {
            Ok(Ok(Ok(resp))) => Ok(resp),
            Ok(Ok(Err(e))) => Err(anyhow!("{e}")),
            Ok(Err(_)) => Err(anyhow!("OBS WebSocket task stopped")),
            Err(_) => Err(anyhow!(
                "request {request_type} timed out after {} ms",
                REQUEST_TIMEOUT.as_millis()
            )),
        }
    }

    /// Snapshot of the connection state for status reporting.
    pub async fn status(&self) -> ConnectionStatus {
        let info = self.info.lock().await;
        ConnectionStatus {
            connected: info.connected,
            identified: info.identified,
            url: self.url.clone(),
            has_password: self.password.is_some(),
            auto_start_configured: self.start_command.is_some(),
            auto_start_triggered: self.start_triggered.load(Ordering::SeqCst),
            obs_studio_version: info.obs_studio_version.clone(),
            obs_web_socket_version: info.obs_web_socket_version.clone(),
            rpc_version: info.rpc_version,
        }
    }

    /// Status as a JSON object, used by the obs-get-status tool.
    pub async fn status_json(&self) -> Value {
        let s = self.status().await;
        json!({
            "server": {
                "name": env!("CARGO_PKG_NAME"),
                "version": env!("CARGO_PKG_VERSION"),
                "status": "running",
            },
            "obs": {
                "connected": s.connected,
                "identified": s.identified,
                "url": s.url,
                "hasPassword": s.has_password,
                "autoStartConfigured": s.auto_start_configured,
                "autoStartTriggered": s.auto_start_triggered,
                "obsStudioVersion": s.obs_studio_version,
                "obsWebSocketVersion": s.obs_web_socket_version,
                "rpcVersion": s.rpc_version,
            },
        })
    }

    /// Make sure a connection task exists and is identified; return the
    /// command channel to it. Waits up to the handshake deadline so a
    /// freshly started OBS has time to come up. When `OBS_START_COMMAND`
    /// is configured, the wait is longer: the first failure triggers the
    /// launch and OBS needs a few seconds to boot.
    async fn ensure_connected(&self) -> Result<mpsc::Sender<Command>> {
        let boot_grace = if self.start_command.is_some() {
            Duration::from_secs(25)
        } else {
            HANDSHAKE_TIMEOUT
        };
        let deadline = Instant::now() + boot_grace;
        loop {
            {
                let mut state = self.state.lock().await;
                let alive = state.task.as_ref().is_some_and(|t| !t.is_finished());
                let identified = self.info.lock().await.identified;
                if alive && identified {
                    if let Some(tx) = state.cmd_tx.clone() {
                        return Ok(tx);
                    }
                }
                if !alive {
                    let (cmd_tx, cmd_rx) = mpsc::channel(64);
                    let client = self.clone();
                    let task = tokio::spawn(async move {
                        client.run_connection(cmd_rx).await;
                    });
                    state.task = Some(task);
                    state.cmd_tx = Some(cmd_tx.clone());
                }
            }
            if Instant::now() > deadline {
                return Err(anyhow!(
                    "could not connect to OBS WebSocket at {}: connection not established",
                    self.url
                ));
            }
            tokio::time::sleep(Duration::from_millis(100)).await;
        }
    }

    /// The connection task: connect, identify, then serve requests, with
    /// automatic reconnect until shutdown.
    async fn run_connection(&self, mut cmd_rx: mpsc::Receiver<Command>) {
        loop {
            self.info.lock().await.connected = false;
            self.info.lock().await.identified = false;

            let ws = match timeout(HANDSHAKE_TIMEOUT, self.handshake()).await {
                Ok(Ok(ws)) => ws,
                Ok(Err(e)) => {
                    tracing::warn!("OBS WebSocket handshake failed: {e}");
                    self.maybe_start_obs();
                    tokio::time::sleep(RECONNECT_DELAY).await;
                    continue;
                }
                Err(_) => {
                    tracing::warn!("OBS WebSocket handshake timed out");
                    self.maybe_start_obs();
                    tokio::time::sleep(RECONNECT_DELAY).await;
                    continue;
                }
            };

            {
                let mut info = self.info.lock().await;
                info.connected = true;
                info.identified = true;
            }
            tracing::info!("connected to OBS WebSocket at {}", self.url);

            match self.main_loop(ws, &mut cmd_rx).await {
                LoopExit::Shutdown => return,
                LoopExit::Retry => {
                    tracing::warn!("OBS WebSocket connection lost; reconnecting");
                    tokio::time::sleep(RECONNECT_DELAY).await;
                }
            }
        }
    }

    /// Perform the Hello/Identify handshake; returns the open socket.
    async fn handshake(&self) -> Result<WsStream> {
        let request = self
            .url
            .clone()
            .into_client_request()
            .map_err(|e| anyhow!("invalid WebSocket URL '{}': {e}", self.url))?;
        let (ws, _resp) = connect_async(request)
            .await
            .map_err(|e| anyhow!("connect to {} failed: {e}", self.url))?;
        let mut ws = ws;

        let hello: HelloMessage = serde_json::from_value(
            read_json(&mut ws)
                .await?
                .ok_or_else(|| anyhow!("connection closed during handshake"))?,
        )
        .map_err(|e| anyhow!("invalid Hello from OBS: {e}"))?;
        if hello.op != 0 {
            return Err(anyhow!(
                "expected Hello (op 0) from OBS, got op {}",
                hello.op
            ));
        }

        let auth = match (&hello.d.authentication, &self.password) {
            (Some(a), Some(pw)) => Some(auth_string(pw, &a.salt, &a.challenge)?),
            (Some(_), None) => {
                return Err(anyhow!(
                    "OBS WebSocket requires a password; set OBS_WEBSOCKET_PASSWORD"
                ))
            }
            (None, _) => None,
        };

        let rpc_version = hello.d.rpc_version.min(1);
        let mut identify = json!({
            "op": 1,
            "d": {
                "rpcVersion": rpc_version,
                "eventSubscriptions": 0,
            }
        });
        if let Some(auth) = auth {
            identify["d"]["authentication"] = Value::String(auth);
        }
        ws.send(Message::Text(identify.to_string().into()))
            .await
            .map_err(|e| anyhow!("failed to send Identify: {e}"))?;

        // Wait for the Identified (op 2) acknowledgement.
        loop {
            let msg = read_json(&mut ws)
                .await?
                .ok_or_else(|| anyhow!("connection closed waiting for Identified"))?;
            match msg.get("op").and_then(|v| v.as_u64()) {
                Some(2) => {
                    {
                        let mut info = self.info.lock().await;
                        info.obs_studio_version = Some(hello.d.obs_studio_version.clone());
                        info.obs_web_socket_version = Some(hello.d.obs_web_socket_version.clone());
                        info.rpc_version = Some(hello.d.rpc_version);
                    }
                    return Ok(ws);
                }
                Some(other) => {
                    tracing::debug!("ignoring op {other} during handshake");
                }
                None => {
                    return Err(anyhow!("message without op code during handshake"));
                }
            }
        }
    }

    /// Read/route loop over a live connection.
    async fn main_loop(
        &self,
        mut ws: WsStream,
        cmd_rx: &mut mpsc::Receiver<Command>,
    ) -> LoopExit {
        let mut pending: HashMap<u64, oneshot::Sender<Result<Value, String>>> = HashMap::new();

        loop {
            tokio::select! {
                incoming = ws.next() => {
                    match incoming {
                        Some(Ok(Message::Text(text))) => {
                            if let Ok(msg) = serde_json::from_str::<Value>(&text) {
                                if msg.get("op").and_then(|v| v.as_u64()) == Some(7) {
                                    // RequestResponse
                                    let id: u64 = msg["d"]["requestId"]
                                        .as_str()
                                        .and_then(|s| s.parse().ok())
                                        .unwrap_or(0);
                                    if let Some(tx) = pending.remove(&id) {
                                        let ok = msg["d"]["requestStatus"]["result"]
                                            .as_bool()
                                            .unwrap_or(false);
                                        let resp = if ok {
                                            Ok(msg["d"]["responseData"].clone())
                                        } else {
                                            let code = msg["d"]["requestStatus"]["code"].as_i64().unwrap_or(-1);
                                            let comment = msg["d"]["requestStatus"]["comment"]
                                                .as_str()
                                                .unwrap_or("unknown error");
                                            Err(format!("OBS error {code}: {comment}"))
                                        };
                                        let _ = tx.send(resp);
                                    }
                                }
                                // Events (op 5) and other messages are ignored.
                            }
                        }
                        Some(Ok(Message::Close(_))) | None => {
                            flush_pending(&mut pending, "connection closed");
                            return LoopExit::Retry;
                        }
                        Some(Ok(_)) => {}
                        Some(Err(e)) => {
                            flush_pending(&mut pending, &format!("connection error: {e}"));
                            return LoopExit::Retry;
                        }
                    }
                }
                cmd = cmd_rx.recv() => {
                    match cmd {
                        Some(Command::Request { id, request_type, data, tx }) => {
                            let message = json!({
                                "op": 6,
                                "d": {
                                    "requestType": request_type,
                                    "requestId": id.to_string(),
                                    "requestData": data,
                                }
                            });
                            if let Err(e) = ws
                                .send(Message::Text(message.to_string().into()))
                                .await
                            {
                                let _ = tx.send(Err(format!("send failed: {e}")));
                                flush_pending(&mut pending, "connection error");
                                return LoopExit::Retry;
                            }
                            pending.insert(id, tx);
                        }
                        None => {
                            flush_pending(&mut pending, "server shutting down");
                            return LoopExit::Shutdown;
                        }
                    }
                }
            }
        }
    }
}

/// Fail every pending request with a reason (used on disconnect).
fn flush_pending(pending: &mut HashMap<u64, oneshot::Sender<Result<Value, String>>>, why: &str) {
    for (_, tx) in pending.drain() {
        let _ = tx.send(Err(why.to_string()));
    }
}

/// Read one JSON message from the socket, tolerating non-text frames.
async fn read_json(ws: &mut WsStream) -> Result<Option<serde_json::Value>> {
    loop {
        match ws.next().await {
            Some(Ok(Message::Text(text))) => {
                return serde_json::from_str(&text)
                    .map(Some)
                    .map_err(|e| anyhow!("invalid JSON from OBS: {e}"))
            }
            Some(Ok(_)) => continue,
            Some(Err(e)) => return Err(anyhow!("read error: {e}")),
            None => return Ok(None),
        }
    }
}

/// Compute the obs-websocket authentication string:
/// `base64(sha256(base64(sha256(password + salt)) + challenge))`.
fn auth_string(password: &str, salt: &str, challenge: &str) -> Result<String> {
    let secret = Sha256::digest(format!("{password}{salt}").as_bytes());
    let secret_b64 = base64::engine::general_purpose::STANDARD.encode(secret);
    let auth = Sha256::digest(format!("{secret_b64}{challenge}").as_bytes());
    Ok(base64::engine::general_purpose::STANDARD.encode(auth))
}

#[derive(Debug, Deserialize)]
struct HelloMessage {
    op: u8,
    d: HelloData,
}

#[derive(Debug, Deserialize)]
struct HelloData {
    #[serde(rename = "obsStudioVersion")]
    obs_studio_version: String,
    #[serde(rename = "obsWebSocketVersion")]
    obs_web_socket_version: String,
    #[serde(rename = "rpcVersion")]
    rpc_version: u64,
    authentication: Option<HelloAuth>,
}

#[derive(Debug, Deserialize)]
struct HelloAuth {
    challenge: String,
    salt: String,
}

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

    #[test]
    fn auth_string_matches_obs_websocket_algorithm() {
        // The algorithm is: secret = base64(sha256(password + salt)),
        // auth = base64(sha256(secret + challenge)). Verified against the
        // reference TypeScript client.
        let password = "hunter2";
        let salt = "4E79jP7Wtd0lUqdyQzLzaWY";
        let challenge = "yTfS08Wq3gGRMSbv9FcdVxSJzN21H2Yc";
        let auth = auth_string(password, salt, challenge).unwrap();
        assert_eq!(auth.len(), 44, "base64 sha256 is 44 chars");
        // Deterministic: same inputs, same output.
        assert_eq!(auth, auth_string(password, salt, challenge).unwrap());
        // Different password, different output.
        assert_ne!(auth, auth_string("hunter3", salt, challenge).unwrap());
    }
}