---
title: "Examples: drive OBS Studio Rust from code"
source: https://obs-rust.com/examples/
commit: 524486a44c81ef30b039f10ab955bc778f39e225
tier: core
tokens_est: 1996
---
# Examples: drive OBS Studio Rust from code

Generated from https://obs-rust.com/examples/. Every snippet targets obs-websocket v5 on `ws://localhost:4455` unless it says MCP.

## Examples

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

### Hello, OBS

**Rust**

Install: `cargo add obws tokio --features tokio/full`

```rust
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(())
}
```

**Python**

Install: `uv add obsws-python`

```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")
```

**JavaScript**

Install: `npm i obs-websocket-js`

```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](https://obs-rust.com/websocket/), and you can try one live from that page before you write any code.

### Listen to events

Events arrive as op 5 messages. Choose which categories you receive with the [EventSubscription](https://obs-rust.com/websocket/#EventSubscription) bitmask when you identify.

**JavaScript**

```js
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'}`));
```

**Python**

```python
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")
```

### 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).

Install: `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())
```

### 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](https://obs-rust.com/websocket/#RequestBatchExecutionType).

### 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](https://github.com/obs-rust/obs-studio/blob/master/docs/rust-port/mcp.md) and [control-api.md](https://github.com/obs-rust/obs-studio/blob/master/docs/rust-port/control-api.md) (tools, schemas, metrics).

### 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](https://obs-rust.com/ai/docs/docs-sphinx-scripting.md) and [frontend API](https://obs-rust.com/ai/docs/docs-sphinx-reference-frontend-api.md).

### Native plugins

The libobs C ABI is a compatibility contract. Plugins already compiled for OBS load in obs-studio-rust without a rebuild, and new plugins are written the same way.

- [Plugin template](https://github.com/obs-rust/obs-plugintemplate): CMake skeleton with CI for Windows, macOS and Linux.

- [Plugin guide](https://obs-rust.com/ai/docs/docs-sphinx-plugins.md): Sources, outputs, encoders and services: the module lifecycle and the registration structs.

- [obs-avip](https://github.com/obs-rust/obs-avip): An NDI® source and output written in Rust, a drop-in for DistroAV. Use it as a reference plugin in Rust.

### Client libraries

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

| Language | Library | Install |
|---|---|---|
| Rust | [obws](https://github.com/dnaka91/obws) | `cargo add obws` |
| JavaScript / TS | [obs-websocket-js](https://github.com/obs-websocket-community-projects/obs-websocket-js) | `npm i obs-websocket-js` |
| Python | [obsws-python](https://github.com/aatikturk/obsws-python) | `uv add obsws-python` |
| Python (async) | [simpleobsws](https://github.com/IRLToolkit/simpleobsws) | `uv add simpleobsws` |
| Go | [goobs](https://github.com/andreykaipov/goobs) | `go get github.com/andreykaipov/goobs` |
| C# / .NET | [obs-websocket-dotnet](https://github.com/BarRaider/obs-websocket-dotnet) | `dotnet add package obs-websocket-dotnet` |

Upstream's full list is in the [obs-websocket README](https://github.com/obsproject/obs-websocket#language-apis).
