Connect devices
This guide is for the backend engineer of a device vendor: you hold an Organization API Key, run your own channel to your devices, such as MQTT or WebSocket, and want the model to operate them. The examples use the official TypeScript SDK, @tidblink/server 0.5.0; Without the SDK describes the protocol for other languages.
How the pieces fit
Section titled “How the pieces fit” app ──typed message──▶ your backend (SDK) ◀──Backend Connection──▶ TiDB Link │ ▲ ▲ device channel │ │ presence, talk button │ audio (MQTT, ...) ▼ │ │ device ─────────Realtime WebSocket (grant)──────┘- Your Application Server, the backend process that holds the Organization API Key, talks to TiDB Link on behalf of your devices. Devices never hold the Key; see authentication.
- The channel between your backend and your devices is your own. TiDB Link has no device registry and receives no device status: you declare a device’s tools on its Session, and the model learns the device’s state from tool results.
- A device reaches TiDB Link only for audio, with a short-lived connect token that your backend obtains for it.
- A function that runs on the device is a Client Tool, declared on the device’s Session; a function that your cloud services provide to every Session, such as a warranty lookup, is a Connector, which your backend declares on its Backend Connection and a Template references; serving one with the SDK needs
@tidblink/server0.5.0 or later.
A typical layout is one End User per app user, created with organization.createEndUser({ externalId }), and one Session per device, created from a Template with createSession({ templateId, idempotencyKey }). Typed messages and voice then share one conversation.
Connect to the core
Section titled “Connect to the core”Your backend opens a Backend Connection: one WebSocket from your process to the TiDB Link core, which carries the events, tool calls and messages of many Sessions. Your backend dials out, so it needs no public endpoint. The SDK opens and maintains these connections; it requires Node.js 22.12 or later.
npm install --save-exact @tidblink/server@0.5.0Attach a device’s Session when the device comes online, and keep it attached while the device stays online:
import { OrganizationClient } from '@tidblink/server';
const organization = new OrganizationClient({ baseUrl: process.env.AGENT_SERVICE_URL, apiKey: process.env.ORGANIZATION_API_KEY,});const online = new Map(); // deviceId -> SessionConnectionconst presence = new Map(); // deviceId -> its latest presence change
// Apply one device's presence changes in order, so that a late "offline" closes what a pending// "online" opened. A retained presence message may arrive twice.function onPresence(deviceId, isOnline) { const next = (presence.get(deviceId) ?? Promise.resolve()) .then(() => (isOnline ? attach(deviceId) : detach(deviceId))) .catch((error) => log.warn(error)); presence.set(deviceId, next); return next;}
async function attach(deviceId) { if (online.has(deviceId)) return; const { userId, sessionId } = await db.binding(deviceId); const conn = await organization .user(userId) .session(sessionId) .connect({ tools: lampTools(deviceId), // see the next section cursor: (await db.cursor(sessionId)) ?? undefined, onError: (error) => log.warn(error), }); online.set(deviceId, conn); // Save the resume point now and then, and when the connection ends. const timer = setInterval(() => db.saveCursor(sessionId, conn.cursor), 5_000); conn.closed.then(async (end) => { clearInterval(timer); if (online.get(deviceId) === conn) online.delete(deviceId); await db.saveCursor(sessionId, conn.cursor); log.info(`Session of ${deviceId} ended: ${end.reason}`); });}
async function detach(deviceId) { const conn = online.get(deviceId); online.delete(deviceId); await conn?.close();}An idle attachment costs the core one row and no polling, so attach when the device comes online rather than when a call arrives. A call made while no connection executes the Session is reported to the model as not performed at once and never reaches you.
A connection attaches a Session in one of two kinds:
| Executing (default) | Observing (observe: true) |
|
|---|---|---|
| Receives | The Session’s events and its Client Tool calls | The Session’s events only |
| Declares tools | Yes, with tools |
No |
| Per Session | At most one. An executing attach from another process or OrganizationClient takes the Session over, and this connection’s closed resolves { reason: "superseded" } |
Any number; never takes a Session over |
| Use it in | The process that operates the device | Another process that only follows the conversation, such as one serving your app |
One OrganizationClient holds at most one connection per Session; reuse it rather than connecting the same Session twice. onEvent receives every event of the Session in order; Session events and recovery describes them.
Declare the device’s tools
Section titled “Declare the device’s tools”tools maps each tool name to its declaration and a run function:
const lampTools = (deviceId) => ({ set_light: { description: 'Turn the lamp on or off, or set its brightness', parameters: { type: 'object', properties: { on: { type: 'boolean' }, brightness: { type: 'integer', minimum: 1, maximum: 100 }, }, additionalProperties: false, }, run: async (args, { callId, signal }) => { // Fail at once when the device is offline, so the model does not wait. if (!devices.isOnline(deviceId)) throw new Error('The lamp is offline'); const state = await devices.request(deviceId, 'set_light', args, { callId, signal }); return state.on ? `On at ${state.brightness}%` : 'Off'; }, },});devices stands for your device channel.
- Each attach replaces the Session’s whole Client Tool set with these declarations, without a revision check, and so does each re-attach the SDK makes after a reconnect or drain. A change made through the REST route
PUT /api/v1/org/users/{userId}/sessions/{id}/tools, which requiresIf-Match, is therefore overwritten by the next attach; keep the device’s tool set in the connection that executes it. - Omit
toolsto keep the stored set. An executing connection still receives the Session’s calls, and a call of a tool without arunfunction on that connection fails with a message saying so. - A tool name is 1 to 64 letters, digits,
_or-; names that start withmcp_, contain__or equal a platform tool name are reserved. Names are unique within the set, which holds at most 64 tools. Adescriptionholds 1 to 4,096 characters, and eachparametersis a JSON Schema withtype: "object"of at most 16 KiB and 16 levels of nesting. The whole set serializes to at most 64 KiB; that limit is checked again when a Turn starts, with theasyncproperty added to every tool, and a set over it refuses the message withvalidation_error, so stay well below it. Theasyncargument is reserved: the model uses it to choose whether to wait for a call, andrunnever receives it. - A Turn freezes the set when it starts. A change applies from the next Turn; the running Turn, and messages that steer it, keep the set it started with.
- Text Turns, audio Turns, voice task Turns and Standing Task Turns use the Session’s Client Tools. Scheduler-started Turns and Template Tests use none.
Handle calls
Section titled “Handle calls”When the model calls a tool, the core sends the call to the Session’s executing connection. The SDK first claims it, asking the core for the right to execute it, and runs run only after the core grants the claim. It then submits what run returned, or the message of what it threw, as the call’s result. Nothing runs without a granted claim, so a call that the core reports as not performed was never executed.
The Session event agent.session.turn.requires_action also records the calls sent to you, but it authorizes nothing: execute calls only through run, never from an event.
run(args, context) receives the model’s arguments and a context with callId, sessionId, userId, turnId, name, deadlineAt and signal. A returned string is what the model receives, and other values are sent as JSON, up to 65,536 characters. A thrown error becomes a failure whose message the model sees.
| Situation | Core’s outcome | The model sees |
|---|---|---|
| No executing attachment when the call is made | Not performed, at once; the call never reaches you | client_tool_not_delivered, effect did_not_happen |
| Not claimed within the 5-second claim window | Not performed | client_tool_not_delivered, effect did_not_happen |
| Claimed, with a result within 60 seconds of the call | Succeeded or failed | Your output, or your error message |
| Claimed, without a result 60 seconds after the call | Result unknown | client_tool_result_unknown, effect unknown |
| A claim or result after the core has decided | Refused | Unchanged |
If the Turn ends first, an unclaimed call is reported not performed and a claimed call without a result as unknown. The model then decides whether it can still complete the task.
- Deduplicate by
callId. After a reconnect the core may send an unclaimed call again; the SDK runs eachcallIdat most once per connection. PasscallIddown your device channel as the command’s identity, so that a retry there does not act twice. - Fail at once when the device is offline. Throw instead of waiting: the model learns it at once and can tell the user. A call that waits for an absent device holds the Turn until its deadline and ends with an unknown effect.
- Stop at the deadline.
signalaborts atdeadlineAt, 60 seconds after the call, and the SDK reports a timeout; the core tells the model that the effect is unknown. Passsignalto your device request. - Lost answers. If the core’s answer to a claim is lost, the SDK does not run the call and closes it with an error result, since the claim may have been granted. After a transient failure, a result is retried over this
OrganizationClient’s Backend Connections until the call’s deadline. A failure that retrying cannot fix, such as a revoked Key, goes toonError, and the call ends with an unknown effect. - Refused results. A result that the core does not accept, for example after the deadline, reaches
onErroras aClientToolResultRefusedErrorwith the core’sreason.
Hand files to the device
Section titled “Hand files to the device”A device often needs a file the Agent produced, such as firmware it built. The Agent announces the file in its Session’s Drive with the notify_file tool, a File Notification that every attachment receives as an event (Receive files the Agent hands over), then passes the file’s path and version to one of your Client Tools. Declare that tool, and tell the model in the Template’s instructions to write the firmware it hands over into a saved folder such as out/, for example with -o out/firmware.bin, and to call the tool after notify_file. Files in build/, dist/, target/ and similar build folders stay in the Agent’s sandbox and never reach the Session’s Drive, so the Agent cannot hand them over (notify_file refuses them with local_only). Saved folders do not keep the executable bit, though a script still runs from out/ through its interpreter, such as sh out/tool.sh. When the Agent must also run a compiled image, have it build and run in build/, then copy the final image into out/ and hand over the copy:
flash_device: { description: 'Flash a firmware image onto the lamp. Call notify_file first and pass its path and version.', parameters: { type: 'object', properties: { path: { type: 'string' }, version: { type: 'string' } }, required: ['path', 'version'], additionalProperties: false, }, run: async ({ path, version }, { callId, userId, sessionId, signal }) => { const ticket = await createDownloadTicket(userId, sessionId, { path, version }); const url = new URL(ticket.url, process.env.AGENT_SERVICE_URL).href; // relative to the API origin const result = await devices.request(deviceId, 'flash', { url }, { callId, signal }); return result.ok ? 'Flashed' : `Flash failed: ${result.error}`; },},createDownloadTicket stands for a POST to the Session’s files/download-tickets route with your Organization API Key, described in Files in a Session’s Drive. The device downloads the URL without a key, as often as it needs within its 60 seconds, and gets exactly the announced version; the download fails once the Agent has rewritten the file. The model receives run’s result in the same Turn and can fix the build and call the tool again. When flashing takes longer than the call’s 60-second deadline, return that it started and declare a second tool that reports its progress, or let the Turn end and send the device’s result as the next message. A build that writes a large image into the Drive takes time, roughly minutes for tens of MiB, so wait for the Turn accordingly and keep the device’s Backend Connection attached until the Turn ends.
Send messages
Section titled “Send messages”conn.send(text, options) sends a user message over the connection and resolves with the result once the Turn finishes:
const reply = await conn.send(text, { clientEventId: savedMessageId, // optional; persist it to recover after a crash onProgress: (draft) => app.show(deviceId, draft),});return reply.text;- The message starts a Turn on an idle Session, or steers the Turn that is running;
send()waits for that Turn either way.onProgressreceives the complete draft each time it grows: replace what you show instead of appending. - Wait for the idle event. A Turn’s terminal event and result arrive a moment before the Session releases the Turn. Until the release, another message steers the finished Turn or is refused, and an audio Turn or Template switch is refused as busy. The Session event
agent.session.idlereports the release.send()normally resolves after it, so the nextsend(), audio Turn or Template switch can start at once; if the release does not arrive within 5 seconds after the Turn finished,send()resolves anyway, and the next command may still meet the finished Turn. A Template switch is also refused withsession_switch_busywhile a Realtime connection is live. Without the SDK, wait foragent.session.idleyourself. clientEventIdidentifies the message in the Session, in the same namespace as REST commands; without one the SDK generates a UUID. After a reconnect the SDK sends the message again with the sameclientEventId, which the core deduplicates.- Unknown outcomes. Once the message has gone out, the core may already have accepted it, so
send()reports a stop as an unknown outcome:TurnWaitTimeoutErrorwhen the localtimeoutMs, 60 seconds by default, passes, andOutcomeUnknownErrorwhen yoursignalstops the call or the SDK cannot tell whether the core accepted the message.TurnWaitTimeoutErroris a kind ofOutcomeUnknownError; both carry the message’sclientEventIdasinputId, and neither cancels the Turn. A call stopped before the message went out, for example while it waits for a lost connection to be restored, throws the reason it was stopped with, such as aTimeoutError, withoutinputId: the message did not reach the core. - Recover an unknown outcome through the Session, which needs no connection:
organization.user(userId).session(sessionId).waitForResult(clientEventId). Or send again with the sameclientEventId; onceconn.closedhas resolved, connect again first, sincesend()on an ended connection throws. - A rejected message raises
InputNotAppliedError; a failed or interrupted Turn raisesTurnFailedErrororTurnInterruptedError. A refused message command raisesBackendRequestErrorwith the core’sreason, such assession_read_only.
To answer a message typed in your app while the device is not attached in this process, connect the Session with observe: true for that message and close the connection afterwards. An observing connection can send messages but never takes the Session from the process that executes it; while no process executes the Session, the device’s tool calls are reported not performed at once.
The device talks to TiDB Link directly; your backend only authorizes it:
const grant = await conn.realtimeGrant(); // { websocketUrl, connectToken, connectTokenExpiresAt }devices.send(deviceId, 'voice_grant', grant);The device opens the Realtime WebSocket with the grant, and audio never passes through your backend. The token is short-lived, so ask for a new grant each time the device wants to talk. When a Realtime connection is already live, realtimeGrant() returns a new token for it.
Voice uses the same Client Tools. A spoken request that needs the device runs as a Turn that freezes the Session’s tools, and its calls reach your executing connection like a text Turn’s; this is another reason to stay attached while the device is online. onTranscript and onResponse receive completed voice transcripts and responses, for example to show the conversation in your app.
The Realtime voice guide covers the device side: the WebSocket protocol, audio formats, interruption and reconnects.
Reconnects and scale
Section titled “Reconnects and scale”- Cursors.
conn.cursoris the cursor of the last event whose callbacks have completed, andonCursorreceives each one. The SDK awaitsonCursorbefore it delivers the next event, so save the cursor now and then and when the connection ends, as above, rather than on every event, and keep it per Session. Pass it back ascursorafter a restart: the core replays the events after it, then continues live, without gaps or repeats; events processed after the last save arrive again. Without a cursor, delivery starts after the Session’s latest event and history is not replayed. - Automatic recovery. After a lost connection, or when the core asks a connection to drain before a restart, the SDK re-attaches each Session on another connection from the last processed event.
- Calls do not wait for you. Events survive a disconnect, but calls survive only within their claim window. After a reconnect the core sends a still-unclaimed call to the new executing attachment while its claim window is open; a call whose window has passed was already reported not performed. For up to 10 seconds after a connection drops, the core still counts its attachment as executing, so calls made then get the claim window instead of failing at once.
- Capacity. A connection holds at most the
maxSessionsthe core announces, 1024 today. The SDK opens another connection when one is full; the load balancer may place it on another core replica. - Takeover. A Session has one executing attachment. When another process attaches it for execution, this connection’s
closedresolves{ reason: "superseded" }, and the SDK does not take the Session back.closedalso resolves withclosedafterclose()ororganization.close(), withsession_deleted, and witherrorwhen the connection cannot be restored, for example after a Key revocation. - Key revocation. When the Organization API Key is revoked or rotated, or its Organization stops being active, the core closes the Key’s Backend Connections with close code
4001: a connection on which it refuses a request withauthentication_requiredat once, the others at its next authority check, within about a second. The refused request fails withBackendRequestErrorandreason: "authentication_required"when the core could still send the refusal; on a busy connection it fails instead with theBackendConnectionClosedErrorwith code4001, and asend()then throwsOutcomeUnknownError. Each Session connection on a closed connection ends with{ reason: "error" }, and the SDK does not restore it. TheOrganizationClientitself stays open, so a laterconnect()orserveConnector()on it dials again with the revoked Key: callorganization.close(), create a newOrganizationClientwith a valid Key, and connect again. - Sharding. How you spread devices across backend processes is up to you: each process is an ordinary caller with the Organization API Key, and the protocol has no shard concept. Route each device to one process, so that its Session has one executor.
Without the SDK
Section titled “Without the SDK”The protocol is public, so a backend in any language can implement it. Open a WebSocket to /api/v1/org/backend/ws with the tidb-link.backend.v1 subprotocol and Authorization: Bearer <Organization API Key>; the Key never goes in the URL. Each text frame carries one JSON-RPC 2.0 message. The core sends hello first; send nothing before it. backend-connection-v1.schema.json defines every message, field, refusal reason and close code as JSON Schema; the API reference summarizes them. A device integration uses these messages:
| Direction | Message | Purpose |
|---|---|---|
| core → backend | hello |
Connection parameters: connectionId, maxSessions, claimWindowMs, heartbeatMs, maxFrameBytes |
| backend → core | session.attach |
Attach a Session with userId, sessionId and optional kind (executing or observing), tools and cursor; answers generation and cursor |
| backend → core | session.detach |
Release this connection’s attachment of a Session |
| backend → core | session.send |
Submit a user message with sessionId, clientEventId and data; answers the message receipt |
| backend → core | tool.claim |
Ask to execute a call; answers claimed: true, or claimed: false with a reason |
| backend → core | tool.result |
Submit a claimed call’s output or error; answers accepted |
| backend → core | ping |
Probe liveness when your WebSocket cannot observe ping frames |
| core → backend | session.event |
One Session event with its cursor |
| core → backend | tool.call |
One call to execute: callId, sessionId, userId, turnId, name, arguments, claimBy, deadlineAt |
| core → backend | session.detached |
The core ended an attachment, with reason superseded or session_deleted |
| core → backend | connection.drain |
Move your attachments to a new connection; the core closes this one after closeAfterMs |
Without the SDK, you implement what it does:
- Execute a call only after
tool.claimanswersclaimed: true. If that answer is lost, do not execute the call; submit an error result instead. - Deduplicate
tool.callbycallId: the core sends a call at most once per attachment, but again to a later executing attachment while the call is unclaimed. - Keep the
cursorof the lastsession.eventyou processed, and attach with it after a reconnect. - A refused request answers error
-32000witherror.data.reason. Onconnection_full, attach on another connection. Afterconnection.drain, open a new connection and attach there beforecloseAfterMspasses. - Send the next
session.sendafter theagent.session.idleevent that follows the Turn. - The core sends WebSocket ping frames, which most clients answer automatically. A client that cannot observe them, such as the global
WebSocketof Node.js, sends thepingrequest when nothing has arrived forheartbeatMs. - A refusal with reason
authentication_requiredand close code4001mean the same: the Key is invalid, revoked or rotated, or its Organization is inactive, and reconnecting with the same Key cannot help. Stop using the Key on either one. The core usually sends the refusal and then closes with4001, but under backlog it closes without sending the refusal, and a connection that was already closing keeps its earlier close code; see Key revocation.
Example: a smart lamp
Section titled “Example: a smart lamp”The SDK repository’s smart lamp example is a complete backend of this kind. Each lamp has one Session, shared by messages typed in an app and by speaking to the lamp; the lamp’s functions are Client Tools forwarded over MQTT; and the lamp receives a Realtime grant for voice. Its specification and tools.json apply to every SDK. The TypeScript implementation, lamp-backend.mjs, ships in the package. The repository also holds the same example in Python, whose SDK is not published yet.
createLampBackend takes a Template per lamp model and your device channel:
import { createLampBackend } from '@tidblink/server/examples/lamp-backend.mjs';
const lamps = createLampBackend({ baseUrl: process.env.AGENT_SERVICE_URL, organizationApiKey: process.env.ORGANIZATION_API_KEY, templates: { standard: standardTemplateId, pro: proTemplateId }, device: mqttDevices(broker), // your channel to the lamps});
// The user binds a lamp in the app: one End User per app user, one Session per lamp.await lamps.bindDevice(appUserId, deviceId, 'standard');
broker.subscribe('lamp/+/presence');broker.subscribe('lamp/+/talk');broker.on('message', (topic, payload) => { const [, deviceId, kind] = topic.split('/'); const done = kind === 'presence' ? payload.toString() === 'online' ? lamps.onDeviceOnline(deviceId) : lamps.onDeviceOffline(deviceId) : kind === 'talk' ? lamps.onDeviceWantsToTalk(deviceId) : undefined; done?.catch((error) => log.warn(error)); // an unhandled rejection ends a Node.js process});app.post('/devices/:id/messages', async (req, res, next) => { try { res.json({ text: await lamps.onAppMessage(req.params.id, req.body.text) }); } catch (error) { next(error); // such as TurnFailedError }});deviceprovidesisOnline(deviceId),request(deviceId, command, args, { signal }), which rejects when the lamp reports a failure, andsend(deviceId, topic, payload).requestreceives nocallId, so give each request your own ID and let the lamp answer a repeated ID with its first result, as the firmware below does.- An optional
storekeeps lamp bindings and event cursors; the default keeps them in memory, so pass one backed by your database in production. - The tools
set_light,get_statusandset_timerfail at once withThe lamp is offlinewhen the lamp is not on the channel. onDeviceOnlinereturns at once when the lamp is already connected in this process. It does not order a lateofflineafter a pendingonline; serialize each lamp’s presence changes as in Connect to the core when that can happen.onAppMessageuses a temporary executing connection while the lamp is not connected in this process, which takes the Session from any other process executing it; use an observing one, as in Send messages, when other processes may hold the lamp.changeModel(deviceId, model)moves the lamp’s Session to another model’s Template while keeping its history. It is refused withsession_switch_busywhile a Turn runs or the lamp’s Realtime connection is live.
The lamp itself does not use the SDK. Its firmware, in pseudo-code:
mqtt_connect(broker, will = { "lamp/{id}/presence", "offline", retain });mqtt_publish("lamp/{id}/presence", "online", retain);
on_message("lamp/{id}/cmd", msg) { // a Client Tool call, forwarded if (done(msg.requestId)) { reply(msg.requestId, ok, result_of(msg.requestId)); return; } // a retry switch (msg.command) { case "set_light": apply(msg.args); reply(msg.requestId, ok, state()); break; case "get_status": reply(msg.requestId, ok, { ...state(), ambientLux: lux() }); break; case "set_timer": timer_start(msg.args.minutes * 60, led_off); reply(msg.requestId, ok, {}); break; default: reply(msg.requestId, error, "unknown command"); }}
on_button_press() { mqtt_publish("lamp/{id}/talk", ""); }
on_message("lamp/{id}/voice_grant", grant) { // audio goes to TiDB Link directly ws = websocket_connect(grant.websocketUrl, subprotocol = "tidb-link.realtime.v1"); ws.send_json({ type: "session.connect", connect_token: grant.connectToken, endpointing: { mode: "client" } }); formats = wait_for(ws, "session.ready").audio; // send nothing else before it ws.send_json({ type: "input_audio.activity", kind: "start" }); while (button_held()) ws.send_audio(mic_read(20ms)); ws.send_json({ type: "input_audio.activity", kind: "end" }); while (ws.open) if (ws.has_audio()) speaker_play(ws.recv());}The Realtime voice guide defines the handshake, the audio frame formats, server endpointing and when a socket may reconnect.