Copy · paste · stream

Examples

Working starting points for everything that talks to OBS: WebSocket clients, agents over MCP, scripts and native plugins.

01

Hello, OBS

cargo add obws tokio --features tokio/full
use obws::Client;

#[tokio::main]
async fn main() -> obws::error::Result<()> {
    let client = Client::connect("127.0.0.1", 4455, Some("password")).await?;

    let v = client.general().version().await?;
    println!("OBS {} · websocket {}", v.obs_version, v.obs_web_socket_version);

    for scene in client.scenes().list().await?.scenes {
        println!("scene: {}", scene.id.name);
    }
    Ok(())
}
uv add obsws-python
import obsws_python as obs

cl = obs.ReqClient(host="127.0.0.1", port=4455, password="password", timeout=3)

v = cl.get_version()
print(f"OBS {v.obs_version} · websocket {v.obs_web_socket_version}")

for scene in cl.get_scene_list().scenes:
    print("scene:", scene["sceneName"])

cl.set_current_program_scene("BRB")
npm i obs-websocket-js
import OBSWebSocket from 'obs-websocket-js';

const obs = new OBSWebSocket();
await obs.connect('ws://127.0.0.1:4455', 'password');

const { obsVersion, obsWebSocketVersion } = await obs.call('GetVersion');
console.log(`OBS ${obsVersion} · websocket ${obsWebSocketVersion}`);

const { scenes } = await obs.call('GetSceneList');
scenes.forEach(s => console.log('scene:', s.sceneName));

await obs.call('SetCurrentProgramScene', { sceneName: 'BRB' });

Connect, authenticate, read the version and switch scenes. Enable the server first under Tools → WebSocket Server Settings (default port 4455).

Every request name and field is in the API reference, and you can try one live from that page before you write any code.

02

Listen to events

Events arrive as op 5 messages. Choose which categories you receive with the EventSubscription bitmask when you identify.

obs.on('CurrentProgramSceneChanged', ({ sceneName }) => console.log('live:', sceneName));
obs.on('StreamStateChanged', ({ outputActive, outputState }) => console.log(outputState));
obs.on('InputMuteStateChanged', ({ inputName, inputMuted }) =>
  console.log(`${inputName} ${inputMuted ? 'muted' : 'live'}`));
import obsws_python as obs

ev = obs.EventClient(host="127.0.0.1", port=4455, password="password")

def on_current_program_scene_changed(data):
    print("live:", data.scene_name)

ev.callback.register(on_current_program_scene_changed)
input("listening, press Enter to quit\n")
03

Raw handshake

No client library needed. Here is the whole v5 protocol in about 25 lines: Hello (op 0), a SHA-256 challenge, Identify (op 1), Identified (op 2), and then requests (op 6) and responses (op 7).

uv run --with websockets raw.py
import asyncio, base64, hashlib, json, websockets

def b64sha(s: str) -> str:
    return base64.b64encode(hashlib.sha256(s.encode()).digest()).decode()

async def main(url="ws://127.0.0.1:4455", password="password"):
    async with websockets.connect(url) as ws:
        hello = json.loads(await ws.recv())                  # op 0
        ident = {"rpcVersion": 1}
        if auth := hello["d"].get("authentication"):
            secret = b64sha(password + auth["salt"])
            ident["authentication"] = b64sha(secret + auth["challenge"])
        await ws.send(json.dumps({"op": 1, "d": ident}))      # Identify
        print(json.loads(await ws.recv()))                     # op 2 Identified

        await ws.send(json.dumps({"op": 6, "d": {"requestType": "GetStats", "requestId": "1"}}))
        while (msg := json.loads(await ws.recv()))["op"] != 7:
            pass                                                # skip events
        print(json.dumps(msg["d"]["responseData"], indent=2))

asyncio.run(main())
04

Batch requests

op 8 sends several requests in one message, and OBS can run them on frame boundaries. Sleep with sleepFrames makes timed sequences: here, a cut to a scene, a wait of 60 frames, and a recording start.

{
  "op": 8,
  "d": {
    "requestId": "intro",
    "executionType": 1,            // SerialFrame
    "requests": [
      { "requestType": "SetCurrentProgramScene", "requestData": { "sceneName": "Intro" } },
      { "requestType": "Sleep", "requestData": { "sleepFrames": 60 } },
      { "requestType": "StartRecord" }
    ]
  }
}

Execution types are in RequestBatchExecutionType.

05 · obs-studio-rust only

MCP for agents

obs-studio-rust includes a Model Context Protocol server. An AI agent can list typed tools, start and stop outputs, inspect sources and wait for output, media or metric conditions, without screenshots or a GUI. It runs headless on Linux with Wayland or X11, and without either for control-only use.

# from an obs-studio checkout: build the libobs-enabled app, then talk JSON-RPC over stdio
./mcp --build
printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | ./mcp --mcp

# or serve on a unix socket and attach clients to it
./mcp --mcp-listen /run/user/1000/obs-control.sock
./mcp --mcp-attach /run/user/1000/obs-control.sock

The repo's .mcp.json already wires this up for Claude Code. Details: mcp.md and control-api.md (tools, schemas, metrics).

06

OBS scripts

Python and Lua scripts load from Tools → Scripts. The scripting API is unchanged, so existing scripts keep working.

import obspython as obs

def script_description():
    return "Logs every scene change."

def on_event(event):
    if event == obs.OBS_FRONTEND_EVENT_SCENE_CHANGED:
        scene = obs.obs_frontend_get_current_scene()
        print("scene:", obs.obs_source_get_name(scene))
        obs.obs_source_release(scene)

def script_load(settings):
    obs.obs_frontend_add_event_callback(on_event)

Reference: scripting and frontend API.

08

Client libraries

Any obs-websocket v5 client library should work. A few well-maintained ones:

LanguageLibraryInstall
Rustobwscargo add obws
JavaScript / TSobs-websocket-jsnpm i obs-websocket-js
Pythonobsws-pythonuv add obsws-python
Python (async)simpleobswsuv add simpleobsws
Gogoobsgo get github.com/andreykaipov/goobs
C# / .NETobs-websocket-dotnetdotnet add package obs-websocket-dotnet

Upstream's full list is in the obs-websocket README.