--- title: "Host cameras for other processes" description: "Hold a camera in one process with CameraRuntime and let MCP clients, HTTP clients and your own code share it in turn." url: https://darkgrade.com/docs/slate/guides/runtime last_updated: 2026-12-04 docs_index: https://darkgrade.com/docs/llms.txt --- # Host cameras for other processes > Hold a camera in one process with CameraRuntime and let MCP clients, HTTP clients and your own code share it in turn. > ## Documentation Index > Fetch the complete documentation index at: https://darkgrade.com/docs/llms.txt > Use this file to discover all available pages before exploring further. Only one program can hold a camera's connection. Darkgrade Slate's `CameraRuntime` lets one process hold it while everything else goes through that process: an AI app over MCP, a web page over HTTP and your own code, all taking turns on the same camera. This is how [Studio serves its MCP tools](https://darkgrade.com/docs/ai.md). Use it to build the same thing in your own app, on a headless machine or in a rig. If all you want is the MCP tools, start with the shorter [Serve the tools yourself](https://darkgrade.com/docs/ai/server.md). ```typescript import { Camera } from '@darkgrade/slate' import { CameraRuntime } from '@darkgrade/slate/runtime' const camera = new Camera() await camera.connect() const runtime = new CameraRuntime({ discover: () => Camera.discover(), camera: () => camera, assertAllowed: () => {}, }) // Any caller: run a Camera method by name on the camera 'main'. const reply = await runtime.operation('main', 'takePhoto') console.log(reply.result) // { destination: 'card', mediaId: '…', name: 'DSC01234.JPG', … } ``` ## How it fits together | Piece | Job | | - | - | | `CameraRuntime` | Runs operations by name on the cameras your provider holds, one at a time per camera. | | [`CameraProvider`](https://darkgrade.com/docs/slate/reference/types-workflow.md#cameraprovider) | The object you write: it hands the runtime a `Camera` for an identity, and decides what is allowed. | | `createCameraMcpServer` | Serves a runtime, or any [`CameraClient`](https://darkgrade.com/docs/slate/reference/types-workflow.md#cameraclient), as the [`camera_` MCP tools](https://darkgrade.com/docs/ai/tools.md). | | `HttpCameraClient` | A `CameraClient` that calls a runtime in another process over HTTP. | | `HardwareCoordinator` | Leases, so separate processes on one computer don't open the same camera. | `createCameraMcpServer` comes from [`@darkgrade/slate/runtime/mcp`](https://darkgrade.com/docs/slate/reference/entry-points.md#darkgradeslateruntimemcp) and `HardwareCoordinator` from [`@darkgrade/slate/runtime/ownership`](https://darkgrade.com/docs/slate/reference/entry-points.md#darkgradeslateruntimeownership). The rest come from [`@darkgrade/slate/runtime`](https://darkgrade.com/docs/slate/reference/entry-points.md#darkgradeslateruntime). `CameraRuntime` and `HttpCameraClient` both implement `CameraClient`, so code written against that interface doesn't care whether the camera is in this process or another: ```typescript interface CameraClient { discover(): Promise operation( camera: string, name: string, input?: OperationInput ): Promise benchmark?(camera: string): Promise } ``` ## Write the provider The provider is the only part that knows where cameras come from. The runtime calls it for every operation. | Method | Job | | - | - | | `discover()` | The attached cameras. Usually [`Camera.discover()`](https://darkgrade.com/docs/slate/getting_started/camera.md#cameradiscover). | | `camera(identity)` | The `Camera` you hold for this identity, connected or ready for `connect()`. Called when the call's turn comes up, so you can have replaced the camera meanwhile. | | `assertAllowed(identity, operation)` | Throw to refuse an operation right now, for example [`HardwareBusyError`](#a-busy-camera) during a recording. Return to allow it. | | `saveFile(identity, file)` | Optional. Keep a returned [`OperationFile`](https://darkgrade.com/docs/slate/reference/types-workflow.md#operationfile) (a photo, a download) and return its path, which the reply then carries. | | `benchmark(identity)` | Optional. Run [`runBenchmark`](https://darkgrade.com/docs/slate/guides/telemetry.md#benchmark-a-camera), for hosts that offer it. | The *identity* is any non-empty string you choose: `'main'`, a serial number, a rig position. Callers pass it as the first argument of every call. A provider for several cameras that saves returned files: ```typescript import { writeFile } from 'node:fs/promises' import { join } from 'node:path' import { Camera } from '@darkgrade/slate' import { CameraRuntime, type CameraProvider, } from '@darkgrade/slate/runtime' const cameras = new Map() // filled as you connect each one const provider: CameraProvider = { discover: () => Camera.discover(), camera(identity) { const camera = cameras.get(identity) if (!camera) throw new Error(`No camera named ${identity}`) return camera }, assertAllowed() {}, async saveFile(identity, file) { const path = join('/tmp', `${identity}-${file.name}`) await writeFile(path, file.data) return path }, } const runtime = new CameraRuntime(provider) ``` ## Run operations ```typescript runtime.operation( camera: string, name: string, input?: OperationInput ): Promise ``` `name` is a [`Camera`](https://darkgrade.com/docs/slate/getting_started/camera.md) method name (`'takePhoto'`, `'setIso'`, `'getCapabilities'`), and `input`, an [`OperationInput`](https://darkgrade.com/docs/slate/reference/types-workflow.md#operationinput), holds its arguments by name. Both are checked when you call, before the call queues, so a bad call never reaches the camera: - An unknown operation rejects with `Unknown camera operation `. - An unknown input, a missing required input or a wrong type rejects with `OperationInputError`. ```typescript await runtime.operation('main', 'setIso', { value: 'ISO 800' }) await runtime.operation('main', 'zoomTo', { focalLengthMillimetres: 50 }) const { result } = await runtime.operation('main', 'getCapabilities') ``` `surfaceOperations()` lists every operation as a [`SurfaceOperation`](https://darkgrade.com/docs/slate/reference/types-workflow.md#surfaceoperation) with its inputs, so you can build a UI or validate a request without hard-coding the list: ```typescript import { surfaceOperations } from '@darkgrade/slate/runtime' for (const operation of surfaceOperations()) { const { name, mcpTool, cliCommand, readOnly } = operation console.log(name, mcpTool, cliCommand, readOnly) // 'takePhoto' 'camera_take_photo' 'darkgrade camera take-photo' false } ``` Each entry also has `summary`, `parameters` (name, type, choices, whether required, description) and `immediate`. The list includes `discover`, marked `static`: call `runtime.discover()` for it, not `operation()`. ### The queue - Operations on one camera run one at a time, in the order they were asked for. Different cameras don't wait for each other. - `stopRecording` and `stopZoom` are `immediate`: they never wait behind other work. - A command is sent once. If it fails or can't be confirmed, the runtime reports that and never repeats it. The errors are [`Camera`'s own](https://darkgrade.com/docs/slate/guides/errors.md). - `runtime.runExclusive(camera, fn)` puts your own work in the same queue. Use it for anything that must not interleave with clients' calls, such as connecting and disconnecting. ```typescript await runtime.runExclusive('main', async () => { await camera.disconnect() await camera.connect() }) ``` ### Replies and files An [`OperationReply`](https://darkgrade.com/docs/slate/reference/types-workflow.md#operationreply) is JSON. Any bytes the method returned (a photo, a live-view frame, a preview, a download) are moved out into `files`, and `{ file, bytes }` is left in their place in `result`. | Field | Contents | | - | - | | `result` | What the `Camera` method returned, without its bytes. | | `files` | One entry per file: `role` (`'photo'`, `'frame'`, `'overlay'`, `'preview'` or `'download'`), `name`, `mimeType`, `bytes`, and `path` when your provider's `saveFile` kept it. | | `images` | Frames, overlays and previews inline as `{ mimeType, base64 }`, for clients that show pictures. Absent when there are none. Photos and downloads are never inlined. | > [!NOTE] > > Without `saveFile`, a photo's or a download's bytes are dropped: the caller learns the file's name and size only. Provide `saveFile` if callers need the file. ## Serve MCP tools `createCameraMcpServer` turns any `CameraClient` into an MCP server with one tool per `Camera` operation. It needs the optional peer packages `@modelcontextprotocol/server` and `zod`; [Serve over HTTP](https://darkgrade.com/docs/ai/server.md#serve-over-http) has the versions that pair with them for an HTTP server. ```typescript import { createCameraMcpServer } from '@darkgrade/slate/runtime/mcp' import { serveStdio } from '@modelcontextprotocol/server/stdio' await serveStdio(() => createCameraMcpServer(runtime)) ``` [Serve the tools yourself](https://darkgrade.com/docs/ai/server.md) walks through connecting an AI app to it. Three more exports cover hosts with their own server: | Export | Use | | - | - | | `registerCameraTools(server, client)` | Adds the camera tools to an `McpServer` you already have, beside your own tools. It adds `camera_run_benchmark` when the client has `benchmark`. | | `cameraToolDefinitions(options?)` | The tool list as data: `name`, `title`, `description`, `inputSchema`, `annotations` and the `operation` each runs. With `{ cameraArgument: false }` the tools take no `camera` argument, for a host that holds one camera. | | `toolError(error)` | Formats a thrown error as an MCP tool result. A `HardwareBusyError` keeps its `code` and `retryAfterMilliseconds` in `structuredContent`. | Every generated tool carries `_meta['darkgrade/slate'].operation`, the `Camera` method it runs (the key is exported as `slateToolMeta`). ## Call a runtime in another process `HttpCameraClient` is the client half of an HTTP bridge. It opens no camera itself. ```typescript import { HttpCameraClient } from '@darkgrade/slate/runtime' const client = new HttpCameraClient('http://127.0.0.1:8080') const cameras = await client.discover() const reply = await client.operation('main', 'getBattery') ``` Slate does not ship the server half. Your host exposes three `POST` routes and answers each with the runtime's result as JSON: - `/api/cameras/discover`: answer with `await runtime.discover()`. - `/api/cameras//operations/`: the body is the operation's inputs. Answer with `await runtime.operation(camera, name, body)`. - `/api/cameras//benchmark`: answer with `await runtime.benchmark(camera)`. The rules of the exchange: - Requests are JSON with the header `X-Bench-Action: 1`. They time out after 240 seconds and do not follow redirects. - On failure, answer with a non-2xx status and `{ "error": "…" }`; the client throws that message. - For a busy camera, answer `409` with `{ "error": "…", "code": "HARDWARE_BUSY" }`; the client throws [`HardwareBusyError`](#a-busy-camera). - The URL must be `http:` or `https:` without a username or password. - The client checks an operation's name and inputs itself, so a malformed call is never sent. To send requests your own way (an added header, a test double), pass a `fetch`-shaped function as the constructor's second argument. In the Darkgrade repository, `bun run --cwd packages/slate mcp` serves the MCP tools over stdio from such a host: it reads the host's address from the `DARKGRADE_RUNTIME_URL` environment variable and refuses to start without it. > [!WARNING] > > When a request times out or the connection drops, the client can't know whether the camera acted. Its error says so. Read the camera's state before you send the operation again. ## A busy camera `HardwareBusyError` is how a host says "not now" without failing the camera. Throw it from `assertAllowed`: ```typescript import { HardwareBusyError } from '@darkgrade/slate/runtime' let recording = false function assertAllowed(_camera: string, operation: string) { if (recording && operation !== 'stopRecording') throw new HardwareBusyError('A take is recording; stop it first') } ``` It has `status` 409, `code` `'HARDWARE_BUSY'` and `retryAfterMilliseconds` 1000. Over MCP it becomes a tool error that carries the code and the retry hint. Over HTTP, your host answers with the 409 above. ## Leases between processes The runtime's queue orders calls inside one process. When several processes on one computer might open the same camera (two apps, a test run and a service), `HardwareCoordinator` makes them take turns with leases kept in a store they share. ```typescript import { HardwareCoordinator, type OwnershipStore, } from '@darkgrade/slate/runtime/ownership' // Your shared store: a database table, a lock file. declare const store: OwnershipStore const coordinator = new HardwareCoordinator(store) await coordinator.run('camera:main', 'Nightly timelapse', async () => { // Only this process holds 'camera:main' in here. }) ``` | Method | Behaviour | | - | - | | `run(resource, purpose, operation, waitMilliseconds?)` | Waits up to `waitMilliseconds` (default 15000) for the lease, runs `operation`, then releases it. Nested `run` calls inside `operation` share the lease. Throws `HardwareBusyError` when the wait runs out. | | `claim(resource, purpose)` | Takes the lease now or throws `HardwareBusyError`. Returns `{ release() }` for work that outlives one function. | | `owners()` | The store's current leases. | A lease lasts 45 seconds and is renewed every 10 while it is held, so a process that dies stops renewing and its lease lapses. You supply the store by implementing the four methods of [`OwnershipStore`](https://darkgrade.com/docs/slate/reference/types-workflow.md#ownershipstore): ```typescript interface OwnershipStore { claimHardwareResource( resource: string, owner: string, purpose: string, lifetimeMilliseconds: number ): boolean heartbeatHardwareOwner( owner: string, lifetimeMilliseconds: number ): unknown releaseHardwareOwner(owner: string): unknown hardwareOwners(): unknown[] } ``` `claimHardwareResource` must be atomic across processes: return `true` if the resource is free, expired, or already this owner's (and extend it), `false` if another owner holds it. `heartbeatHardwareOwner` extends every lease of that owner, and `releaseHardwareOwner` drops them. ## In a browser [`@darkgrade/slate/runtime/browser`](https://darkgrade.com/docs/slate/reference/entry-points.md#darkgradeslateruntimebrowser) has `CameraRuntime`, `HttpCameraClient`, `HardwareBusyError` and `surfaceOperations` without any Node.js imports, so a web page can call a host with `HttpCameraClient`. Bundlers that honour the `browser` condition pick it automatically for `@darkgrade/slate/runtime`. `HardwareCoordinator` needs Node.js and is not in the browser entry. > [card] [Serve the tools yourself](https://darkgrade.com/docs/ai/server.md) > > Connect Claude or another MCP app to your runtime. > [card] [Tool reference](https://darkgrade.com/docs/ai/tools.md) > > Every tool the MCP server offers, with its arguments.