Build Your OmniagentTools

WebSocket Tools

Every message exchanged between the platform and your functions server over a WebSocket tool's connection

For an explicit tool with a wss:// URL, the platform opens a WebSocket to your functions server when the session starts and keeps it open for the whole session. This page covers every message on that connection, from session setup and tool calls to the live conversation feed and the messages your server can push back.

The initialize message

When the WebSocket connection opens at the start of a session, the platform sends an initialize message. It identifies the session, lists the WebSocket-based tools attached to it, and carries the session's metadata — so your server can set up any per-session state before the first tool call arrives.

{
  "type": "initialize",
  "data": {
    "session_id": "ws_abc123",
    "functions": [
      {
        "name": "get_order_status",
        "flow": "explicit"
      }
    ],
    "metadata": {
      "tags": {
        "key": "value"
      },
      "external_client_id": "client_id",
      "external_client_profile": {
        "key": "value"
      }
    }
  }
}
FieldTypeDescription
session_idstringThe connection id returned when the session was created.
functionsarrayThe WebSocket tools on this connection, each with its name and flow.
metadataobjectThe session's metadata: tags, external_client_id, and external_client_profile.

metadata is always included. It carries the context your backend set when it created the connection, so your server can tie the session to your own user, tenant, or profile without a separate lookup. Fields you didn't set when you created the connection are null. This is the only place it arrives on the tool socket: function_call messages don't carry it. See Executing Tools — Session metadata for what each field holds and how it's set.

Tool calls and results

When the agent calls your tool, the platform sends a function_call message on the socket:

{
  "session_id": "ws_abc123",
  "type": "function_call",
  "data": {
    "item_id": "item_001",
    "call_id": "call_abc123",
    "name": "get_order_status",
    "arguments": {
      "order_id": "ORD-7890"
    }
  }
}
FieldTypeDescription
session_idstringThe connection id returned when the session was created. It sits next to data, not inside it.
data.item_idstringThe ID of the function-call item in the conversation.
data.call_idstringA unique identifier for this call. Send it back with the result.
data.namestringThe name of the tool being invoked.
data.argumentsobjectThe parameters the agent populated for the tool call.

The call carries no metadata. It arrived once, in the initialize message.

Send the result back on the same socket as a function_response with the same call_id:

{
  "type": "function_response",
  "data": {
    "call_id": "call_abc123",
    "content": {
      "status": "shipped",
      "tracking_number": "1Z999AA10123456784"
    },
    "delay": false
  }
}
FieldTypeRequiredDescription
call_idstringYesThe call_id from the function_call message.
contentobject | stringYesThe result passed back to the agent: a JSON object or a JSON-encoded string.
delaybooleanNotrue holds the result until the agent finishes speaking. false (default) handles it right away, which can interrupt the agent mid-sentence.

If your server doesn't send a function_response in time, the platform tells the agent the call failed and sends a function_call_timeout on the socket:

{
  "type": "function_call_timeout",
  "data": {
    "call_id": "call_abc123",
    "function_name": "get_order_status"
  }
}
FieldTypeDescription
data.call_idstringThe call_id of the call that timed out.
data.function_namestringThe name of the tool that was called.

For work that takes longer, return an interim result and deliver the outcome later with context_update.

The tool socket silently ignores any message type it doesn't recognize. A common mistake is answering with send_function_output, the client-side command for implicit tools. The tool socket drops it, so the call times out.

Connection behavior

The platform opens the socket to your server at session start — and your server might be slow to accept, or down. The tool's connectionBehavior setting controls what the session does in each case. Set it when you create the tool (POST /public/functions), or update an existing tool with PUT /public/functions/{functionId}:

{
  "connectionBehavior": {
    "waitBeforeStart": false,
    "abortOnFailure": false
  }
}
Flagtruefalse (default)
waitBeforeStartThe session waits for your socket to be fully connected before starting.The session starts after a short wait and lets your tool join late.
abortOnFailureThe whole session is aborted if your socket fails to connect. If waitBeforeStart is also true, your client receives an error event first.The session starts anyway.

Use waitBeforeStart: true when the agent's first responses depend on your tool being reachable; use abortOnFailure: true when a session without your tool is worthless. For everything else, the defaults favor fast session starts.

Previously, every session behaved as if both flags were true. To restore that behavior, set both to true. See What's new — August 12, 2026.

To see how each tool's connection actually went — connected when, failed why, canceled by the user leaving — read the session's functionStates.

Receiving the live conversation (receiveMessages)

Set receiveMessages to true on a tool to stream the conversation to your server as it happens, not only when the tool is called. By the time the agent calls your tool, your server has the full context, which helps tools that need more than the arguments the agent filled in.

Each line of the conversation, from the user, the agent, or a system message, arrives as a notify_message:

{
  "type": "notify_message",
  "data": {
    "item_id": "item_002",
    "role": "user",
    "content": "Where's my order?"
  }
}
FieldTypeDescription
data.item_idstringThe ID of the message in the conversation.
data.rolestringWho said it: "user", "assistant", or "system".
data.contentstringThe full text of the message.

Only completed lines arrive, never partial text, and tool calls and their results aren't included. The user's line arrives before any function_call it triggers. Messages injected with context_update, including your own, arrive too, with the role they were sent with. This is the tool socket's counterpart to the client's message_received event, which the tool socket never sends.

In audio sessions, the same tools also receive speech events. Each one carries the item_id and role of the message it belongs to:

{
  "type": "speech_started",
  "data": {
    "item_id": "item_003",
    "role": "user"
  }
}
typeSent when
speech_startedSomeone starts speaking.
speech_stoppedSomeone stops speaking.
cancelledA response is cancelled, for example because the user interrupted the agent.

The server events your client receives describe the same moments in more detail.

Pushing UI state to the client (ui_update)

Sometimes the conversation changes something the page should reflect, and the change happens on your backend, where the client can't see it. For example:

  • Your tool handler completes a booking, and the page should show a confirmation card, not only have the agent read out the details.
  • A tool starts a long-running job, and the page should show its progress while the agent keeps talking.

With ui_update, your server pushes a message to the end user's client through the tool connection. The platform relays it over whichever session channel is in use (the WebRTC data channel or the client WebSocket). The payload isn't validated or modified, and your client renders it however it wants.

Send from your functions server — for example from an explicit tool handler after completing an action:

{
  "type": "ui_update",
  "data": { "view": "booking-confirmation", "bookingId": "bk_123" }
}

The client receives it as a server event:

{
  "event": "ui_update",
  "data": { "view": "booking-confirmation", "bookingId": "bk_123" }
}

data can be any JSON, and the message isn't tied to a tool call: send it whenever you want while your WebSocket is connected.

ui_update is one-way and fire-and-forget: no acknowledgement, and updates are not stored — a client that connects mid-session won't receive earlier updates.

Updating the conversation context (context_update)

context_update lets your functions server add information to the conversation itself. Where ui_update targets the page, context_update is injected into the session's context — the agent reads it as if it were part of the conversation, and can act on it or respond to it. It's the server-side counterpart of the client's send_message command, and like everything on this page, it works regardless of the session channel — WebRTC included.

The canonical use case is the deferred tool result. Tool calls time out quickly — but some tools do real work that takes longer: generating a report, calling a slow third-party API, waiting on a human approval. You can't keep the agent (and the user) hanging while it runs:

  1. The agent calls your tool. Your handler returns an interim result right away — for example "Started. Tell the user the result will be ready shortly." — so the conversation isn't blocked.
  2. Your server does the slow work.
  3. When it completes, your server sends context_update with the outcome — the agent picks it up and tells the user.
{
  "type": "context_update",
  "data": {
    "previous_item_id": null,
    "role": "system",
    "trigger_response": false,
    "content": "The export the user asked for has finished. 1,204 rows, download link sent by email."
  }
}
FieldTypeRequiredDescription
contentstringYesThe text to inject into the conversation context.
rolestringNoWho the injected message is from: "system" (default) or "user".
trigger_responsebooleanNotrue — the agent responds to the injection immediately. false (default) — the context is added silently and informs the agent from its next turn.
delaybooleanNoApplies only when trigger_response is true. true holds the message until the agent finishes its current response. false (default) sends it right away, which can interrupt the agent mid-response.
previous_item_idstring | nullNoThread position for the injected message; null appends at the end of the conversation.

For a deferred result you'll usually want trigger_response: true, so the agent announces the outcome the moment it lands; with false the agent simply knows, and works it into the conversation naturally when the user next speaks. If the agent may be speaking when the result arrives, add delay: true so it finishes its sentence before announcing the result.

context_update isn't limited to tool results, though — it can be sent at any time while the WebSocket is connected and doesn't have to follow a tool call. Use it whenever your backend knows something the agent should too: fresh instructions, changed account state, an event that happened outside the conversation.

Receiving data from the client (client_data_call)

Your client can send arbitrary JSON straight to your functions server, without going through the agent. The client sends a client_data_call command:

{
  "type": "client_data_call",
  "data": {
    "data": { "cartId": "cart_456", "items": 3 }
  }
}

The platform forwards it to every WebSocket tool in the session:

{
  "type": "client_data_call",
  "data": {
    "data": { "cartId": "cart_456", "items": 3 }
  }
}
FieldTypeDescription
data.dataany JSONThe value the client sent, unchanged.

The agent doesn't see this data. To make it part of the conversation, send a context_update from your server. client_data_call is the reverse of ui_update: one carries data from the client to your server, the other from your server to the client.

Errors

The platform reports problems on the tool socket with these messages:

FailureWhat the platform sends
Your server doesn't answer a function_call within 10 secondsfunction_call_timeout
Your server sends a function_response after the call timed outNothing. The response is dropped and doesn't reach the agent.
A context_update has an invalid role, or a non-boolean trigger_response or delayerror
Your server sends anything else the platform can't process: invalid JSON, a missing required field, or an unrecognized typeNothing. The message is dropped silently.

An error names the message that failed and why. For example, a context_update with a non-boolean trigger_response:

{
  "type": "error",
  "data": {
    "message": "An error occurred while processing 'context_update' message: 'trigger_response' field must contain a boolean value."
  }
}

Example server

This server puts the pieces on this page together for two tools. It checks the tool's headers when the platform connects, stores the initialize message, answers get_order_status right away, and handles the slow export_orders by answering within the timeout and delivering the result later with context_update.

Requires the ws package (npm install ws).

import { WebSocketServer } from "ws";

const wss = new WebSocketServer({ port: 8080 });

wss.on("connection", (socket, request) => {
  // The platform connects with the headers you set on the tool
  if (request.headers["x-api-key"] !== process.env.TOOL_API_KEY) {
    socket.close(1008, "Unauthorized");
    return;
  }

  let session;
  const send = (type, data) => socket.send(JSON.stringify({ type, data }));

  socket.on("message", async (raw) => {
    const message = JSON.parse(raw);

    switch (message.type) {
      case "initialize":
        session = message.data;
        break;

      case "function_call": {
        const { call_id, name, arguments: args } = message.data;

        if (name === "get_order_status") {
          const order = await getOrder(args.order_id);
          send("function_response", { call_id, content: order });
        }

        if (name === "export_orders") {
          // Answer within the timeout, then deliver the result when it's ready
          send("function_response", {
            call_id,
            content: "Export started. Tell the user it will be ready shortly.",
          });
          const rows = await exportOrders(session.metadata.external_client_id);
          send("context_update", {
            role: "system",
            content: `The order export finished: ${rows} rows, emailed to the user.`,
            trigger_response: true,
            delay: true,
          });
        }
        break;
      }

      case "function_call_timeout":
        console.warn(`${message.data.function_name} timed out`);
        break;
    }
  });
});

// Replace these with your own lookups
async function getOrder(orderId) {
  return { order_id: orderId, status: "shipped" };
}

async function exportOrders(userId) {
  await new Promise((resolve) => setTimeout(resolve, 15000));
  return 1204;
}

Requires the websockets package, version 13 or later (pip install websockets).

import asyncio
import json
import os

from websockets.asyncio.server import serve


async def handler(websocket):
    # The platform connects with the headers you set on the tool
    if websocket.request.headers.get("x-api-key") != os.environ["TOOL_API_KEY"]:
        await websocket.close(1008, "Unauthorized")
        return

    session = None

    async def send(type_, data):
        await websocket.send(json.dumps({"type": type_, "data": data}))

    async for raw in websocket:
        message = json.loads(raw)

        if message["type"] == "initialize":
            session = message["data"]

        elif message["type"] == "function_call":
            call = message["data"]

            if call["name"] == "get_order_status":
                order = await get_order(call["arguments"]["order_id"])
                await send("function_response", {"call_id": call["call_id"], "content": order})

            elif call["name"] == "export_orders":
                # Answer within the timeout, then deliver the result when it's ready
                await send("function_response", {
                    "call_id": call["call_id"],
                    "content": "Export started. Tell the user it will be ready shortly.",
                })
                asyncio.create_task(finish_export(send, session))

        elif message["type"] == "function_call_timeout":
            print(f"{message['data']['function_name']} timed out")


async def finish_export(send, session):
    rows = await export_orders(session["metadata"]["external_client_id"])
    await send("context_update", {
        "role": "system",
        "content": f"The order export finished: {rows} rows, emailed to the user.",
        "trigger_response": True,
        "delay": True,
    })


# Replace these with your own lookups
async def get_order(order_id):
    return {"order_id": order_id, "status": "shipped"}


async def export_orders(user_id):
    await asyncio.sleep(15)
    return 1204


async def main():
    async with serve(handler, "0.0.0.0", 8080) as server:
        await server.serve_forever()


asyncio.run(main())

The platform must be able to reach your server at the tool's wss:// URL, so deploy it behind TLS or, for local testing, expose it through a tunnel.

Next steps

On this page