Skip to main content
AdvancedHost cameras for other processes

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

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

PieceJob
CameraRuntimeRuns operations by name on the cameras your provider holds, one at a time per camera.
CameraProviderThe object you write: it hands the runtime a Camera for an identity, and decides what is allowed.
createCameraMcpServerServes a runtime, or any CameraClient, as the camera_ MCP tools.
HttpCameraClientA CameraClient that calls a runtime in another process over HTTP.
HardwareCoordinatorLeases, so separate processes on one computer don't open the same camera.

createCameraMcpServer comes from @darkgrade/slate/runtime/mcp and HardwareCoordinator from @darkgrade/slate/runtime/ownership. The rest come from @darkgrade/slate/runtime.

CameraRuntime and HttpCameraClient both implement CameraClient, so code written against that interface doesn't care whether the camera is in this process or another:

interface CameraClient {
    discover(): Promise<DiscoveredCamera[]>
    operation(
        camera: string,
        name: string,
        input?: OperationInput
    ): Promise<OperationReply>
    benchmark?(camera: string): Promise<unknown>
}

Write the provider

The provider is the only part that knows where cameras come from. The runtime calls it for every operation.

MethodJob
discover()The attached cameras. Usually Camera.discover().
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 during a recording. Return to allow it.
saveFile(identity, file)Optional. Keep a returned OperationFile (a photo, a download) and return its path, which the reply then carries.
benchmark(identity)Optional. Run runBenchmark, 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:

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<string, Camera>() // 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

runtime.operation(
    camera: string,
    name: string,
    input?: OperationInput
): Promise<OperationReply>

name is a Camera method name ('takePhoto', 'setIso', 'getCapabilities'), and input, an 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 <name>.
  • An unknown input, a missing required input or a wrong type rejects with OperationInputError.
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 with its inputs, so you can build a UI or validate a request without hard-coding the list:

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.
  • 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.
await runtime.runExclusive('main', async () => {
    await camera.disconnect()
    await camera.connect()
})

Replies and files

An 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.

FieldContents
resultWhat the Camera method returned, without its bytes.
filesOne entry per file: role ('photo', 'frame', 'overlay', 'preview' or 'download'), name, mimeType, bytes, and path when your provider's saveFile kept it.
imagesFrames, overlays and previews inline as { mimeType, base64 }, for clients that show pictures. Absent when there are none. Photos and downloads are never inlined.

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 has the versions that pair with them for an HTTP server.

import { createCameraMcpServer } from '@darkgrade/slate/runtime/mcp'
import { serveStdio } from '@modelcontextprotocol/server/stdio'

await serveStdio(() => createCameraMcpServer(runtime))

Serve the tools yourself walks through connecting an AI app to it. Three more exports cover hosts with their own server:

ExportUse
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.

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/<camera>/operations/<name>: the body is the operation's inputs. Answer with await runtime.operation(camera, name, body).
  • /api/cameras/<camera>/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.
  • 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.

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:

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.

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.
})
MethodBehaviour
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:

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

⌘I