WebSocket
Chat with agents over a WebSocket connection, with streamed answers, progress events, and files.
On this page
| Modes | Sync |
| YAML type | websocket |
| Credentials | None. connic generates the secret. |
| Bridge | Not supported |
| Custom domain | Supported |
| Linked agents | One or more. A message starts every linked agent, one after another, unless it names agents. |
| While paused | New connections are refused. An open connection gets a CONNECTOR_INACTIVE error on its next message and closes. |
Set up
Open the agent. In Connector Flow, click Add inbound connector, then Create New Connector, and select WebSocket.
Change the settings you need, such as Streaming Responses or Session Timeout (seconds), and click Create. The details drawer shows the WebSocket URL and Secret Key. To reopen it, hover over the connector in the flow and click the eye icon.
Connect to the WebSocket URL from your client, send the secret, and send messages.
In code
Declare the connector in connectors/*.yaml. The first deploy generates its URL and secret, which then appear in the details drawer.
type: websocket
config:
streaming: true
progress_events: true
session_timeout: 1800
rate_limit:
per_ip: 30
agents:
- support-agentConfiguration
The fields of a WebSocket connector, the same in connectors/*.yaml, the REST API, and connic MCP. The descriptions name the matching setting in the dashboard. Connectors in code describes the fields every connector shares, such as agents and environments.
| Field | Type | Status | Description |
|---|---|---|---|
| type | string | Required | websocket. |
| domain | string | Optional | Hostname or ID of an active custom domain for the WebSocket URL. |
| apps_only | boolean | Optional | Only in connectors/*.yaml. Accept connections only from the apps that list this connector, through their /_connic/c/<key> path. The WebSocket URL then refuses direct connections, the secret isn't used, and the first message is a chat message.Default: false |
| config | object | Optional | WebSocket settings. |
| streaming | boolean | Optional | Sends each answer in chunks while the model writes it. See Streaming. Dashboard: Streaming Responses.Default: true |
| progress_events | boolean | Optional | Also sends events for model calls, tool calls, and approvals. Applies only with streaming on; connic lint rejects it in a file that turns streaming off. See Progress events. Dashboard: Progress Events.Default: false |
| require_auth | boolean | Optional | Clients must send the secret. Dashboard: Require Authentication.Default: true |
| session_timeout | integer | Optional | Seconds a connection can stay idle before connic closes it, a whole number from 60 to 86,400. connic rejects other values. Dashboard: Session Timeout (seconds).Default: 3600 |
| max_messages_per_session | integer | Optional | Messages one connection can send, a whole number from 1 to 10,000; the next one closes it. connic rejects other values. Dashboard: Max Messages per Session.Default: 100 |
| rate_limit | object | Optional | Messages per minute, each from 0 to 1,000; 0 turns a limit off. See Rate limits. Dashboard: Rate Limits. |
| total | integer | Optional | Messages from all connections together. Dashboard: Total per Minute.Default: 0 |
| per_ip | integer | Optional | Messages from one client IP address. Dashboard: Per IP per Minute.Default: 0 |
| key | string | Optional | Payload field to count per_key by, as a dot path such as context.user_id. Required with per_key. Dashboard: Rate Limit Key. |
| per_key | integer | Optional | Messages with the same value in key. Dashboard: Per Key per Minute.Default: 0 |
Changed settings apply to new connections; an open connection keeps the settings it connected with.
Generated values
connic creates these when the connector is created and keeps them across updates and deploys. Copy them from the details drawer. Leave them out of YAML files; connic lint rejects them.
| Value | Modes | Description |
|---|---|---|
| WebSocket URL | Sync | The address clients connect to. It uses the connector's custom domain when one is set. |
| Secret Key | Sync | The secret clients send while Require Authentication is on. |
Connect
Open a WebSocket connection to the WebSocket URL and send the secret. Once the connection is authenticated, connic sends a connected event:
const ws = new WebSocket("<websocket-url>");
ws.onopen = () => {
ws.send(JSON.stringify({ secret: "<secret>" }));
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === "connected") {
console.log("Agents:", data.agents);
}
};{
"type": "connected",
"connection_id": "6f1c2a9e-0b7d-4c55-9a51-2f3e8d7c1b40",
"connector_run_id": "550e8400-e29b-41d4-a716-446655440000",
"agents": ["support-agent"],
"config": {
"message_limit": 100,
"session_timeout": 3600
}
}connector_run_id identifies the connector run that records this connection. The connector's runs list one entry per connection, with its message count and its last 10 messages. config shows the message limit and idle timeout that apply to the connection.
Authenticate
While Require Authentication is on, the default, the client sends the connector's secret in one of three places: an X-Connic-Secret or Authorization: Bearer header on the connection request, the secret query parameter, or a first message {"secret": "<secret>"} within 30 seconds of connecting. Browsers can't set headers on a WebSocket request, so browser clients send the first message. Prefer a header or the first message to the query parameter, which ends up in access logs.
# Header on the connection request
X-Connic-Secret: <secret>
Authorization: Bearer <secret>
# Query parameter (ends up in access logs)
<websocket-url>?secret=<secret>
# First message after connecting
{"secret": "<secret>"}A wrong secret in a header or the URL isn't rejected right away; connic then waits for the secret as the first message. A wrong or missing secret ends the connection with an error event and close code 4003. Code that runs in a browser exposes the secret to everyone who uses the page. With Require Authentication off, any client can connect, and connic treats the first message as a chat message.
Reconnect
Add a connection ID of your choice to the WebSocket URL as one more path segment, as in <websocket-url>/<connection id>. The connected event returns it in connection_id. A connection without one gets a generated ID and can't be resumed.
A connection with the ID of an open one replaces it: connic sends the open connection a CONNECTION_REPLACED error and closes it with code 4009. connic can't tell a dropped connection from one that's still open, so the connection that comes last keeps the ID. Give each tab or device its own ID, and don't reconnect automatically after code 4009, or two clients keep taking the ID from each other.
Runs keep going when a connection drops. Answers that finished while the client was gone arrive right after the connected event of its next connection with the same ID, and answers that finish later arrive on the new connection. connic sends the event that ends each answer, response or stream_end with the full response or the error, under the message's original id; chunks and progress events aren't sent again. An answer counts as missed once the client has closed the connection or connected again. An answer connic sent on a connection that broke off without connic noticing isn't sent again.
Missed answers only go to the same client. With Require Authentication on, that's any client with the secret. On an apps_only connector, it's the same end user of the same app: each end user has their own connection IDs, so visitors who choose the same ID neither replace each other nor get each other's answers. With Require Authentication off, anyone can use an ID, so connic keeps no missed answers.
Send messages
Send each message as a JSON object:
ws.send(JSON.stringify({
type: "message",
id: "msg-001",
payload: {
message: "Where is my order?",
conversation_id: "conv-42",
context: { order_id: "A-1001" }
}
}));| Field | Description |
|---|---|
| type | message, the default, ping, pong, or stop. See Stop an answer. |
| id | Optional. Every event for this message carries it. connic generates one when it's missing. |
| payload | The agent input, a JSON object or a string. When it's missing, connic uses message, then content. |
| agents | Optional. Names of linked agents; the message then starts only these agents. |
connic confirms each message with an ack event that carries its id and its number on this connection, then sends the responses. Each connection handles one message at a time, in the order received. A message sent while a response is still running waits until every agent has answered.
A response can take as long as the run timeout. Time paused for an approval or queued by a concurrency rule doesn't count, so an approval-gated tool holds the turn until someone decides or the client stops it, and later messages wait. Keep approval.timeout short on chat agents.
Stop an answer
Send {"type": "stop"} while an answer is running, for example from a Stop button in your chat. connic cancels the run of the agent that is answering, as Cancel on the run in the dashboard does, also while the run waits for an approval. The answer then ends with stream_end or response carrying the error Run cancelled, usually within two seconds. A few chunks can still arrive before it. Agents of the message that haven't started yet don't run.
stopButton.onclick = () => {
ws.send(JSON.stringify({ type: "stop", id: "msg-001" }));
};With an id, the stop only ends the answer to the message with that id, so a stop that arrives after its answer has ended can't stop the next one. Without an id, it ends whichever answer is running. A stop that matches no running answer does nothing and gets no reply.
Agent input
Each message starts one run per agent, and the run's input is the message's payload. Middleware reads it in context["payload"]. The payload can be a JSON object or a string: for {"message": "Hello!"} without payload, the input is the string Hello!. Send an object when a session key or rate limit key reads a field from it.
Files
Add a files array to the payload. Each entry has a name, a mime_type, and the base64-encoded bytes in data.
ws.send(JSON.stringify({
id: "msg-002",
payload: {
message: "Summarize this document",
files: [
{
name: "invoice.pdf",
mime_type: "application/pdf",
data: "<base64-bytes>"
}
]
}
}));An input takes up to 50 files, at most 32 MiB combined. A file with missing or invalid fields is omitted on its own. At the first file over a limit, connic keeps the complete files before it and accepts no further files. Each omitted file is described in file_issues in the payload. The model receives each accepted file as its own part, and the payload without files as text. Middleware can add or remove file parts in before().
connic doesn't check file types for WebSocket messages. Whether the model can read a type depends on the model, and a file it can't read fails the run; see file input for connic/* models.
Files are optional by default. Turn on Files required for an agent in the connector's details drawer, or set files_required: true on its link in YAML, to fail the run before it starts when a file is missing or was omitted.
Responses
connic sends each agent's answer as events on the connection. With several agents, the answers come one after another, and every event names its agent.
Streaming
With Streaming Responses on, the default, each answer arrives as stream_start, one or more stream_chunk events with partial text, and stream_end with the full response and the run's token_usage.
{ "type": "ack", "id": "msg-001", "message_number": 1 }
{ "type": "stream_start", "id": "msg-001", "agent": "support-agent" }
{ "type": "stream_chunk", "id": "msg-001", "agent": "support-agent", "chunk": "Your order " }
{ "type": "stream_chunk", "id": "msg-001", "agent": "support-agent", "chunk": "ships today." }
{
"type": "stream_end",
"id": "msg-001",
"agent": "support-agent",
"full_response": "Your order ships today.",
"token_usage": { "input_tokens": 45, "output_tokens": 15, "total_tokens": 60 }
}Agents with output guardrails always send their answer as a single stream_chunk after the run completes: no partial text is sent before the guardrails have checked the full response. Build clients against the event sequence, not a fixed number of chunks.
Progress events
With Progress Events and streaming on, the connection also reports what the agent is doing before and between text chunks. Each event carries the message id and the agent:
{ "type": "thinking", "id": "msg-001", "agent": "support-agent" }
{ "type": "tool_call", "id": "msg-001", "agent": "support-agent", "tool": "lookup_order" }
{ "type": "tool_result", "id": "msg-001", "agent": "support-agent", "tool": "lookup_order" }
{ "type": "tool_call", "id": "msg-001", "agent": "support-agent", "tool": "cancel_order" }
{ "type": "approval_pending", "id": "msg-001", "agent": "support-agent", "tool": "cancel_order" }
{ "type": "approval_resolved", "id": "msg-001", "agent": "support-agent", "tool": "cancel_order", "decision": "approved" }thinking: a model call starts.tool_callandtool_result: a tool is called and returns, successfully or with an error.toolis the tool name, never its arguments or result. For a discoverable tool, it names the tool that runs.approval_pendingandapproval_resolved: the run pauses for an approval and receives the decision,approved,rejected, ortimeout. An approved tool then reportstool_callandtool_resultwhen it runs.
Agents with output guardrails send progress events too, while their text still arrives in one chunk after the run. The client decides how to label each event.
Without streaming
With Streaming Responses off, each answer arrives as a single response event:
{ "type": "ack", "id": "msg-001", "message_number": 1 }
{
"type": "response",
"id": "msg-001",
"agent": "support-agent",
"response": "Your order ships today.",
"token_usage": { "input_tokens": 45, "output_tokens": 15, "total_tokens": 60 }
}Failed runs
When a run fails, stream_end or response carries error instead of the answer. The error is timeout when the run hasn't finished within the run timeout. When connic can't start or follow a run, it sends an error event with the code DISPATCH_ERROR.
Python client
A client that authenticates, sends one message, and prints the streamed answer. Install the library with pip install websockets.
import asyncio
import json
import websockets
async def chat():
async with websockets.connect("<websocket-url>") as ws:
await ws.send(json.dumps({"secret": "<secret>"}))
print(json.loads(await ws.recv())) # connected event
await ws.send(json.dumps({"payload": {"message": "Hello!", "conversation_id": "conv-42"}}))
while True:
event = json.loads(await ws.recv())
if event["type"] == "stream_chunk":
print(event["chunk"], end="", flush=True)
elif event["type"] == "stream_end":
print(event.get("error", ""))
break
elif event["type"] == "error":
print(event["error"])
break
asyncio.run(chat())Conversation history
Each message starts its own run. Messages share conversation history only when the agent has a persistent session. Set session.key to a payload field that identifies the conversation, such as input.conversation_id, and send that field with every message. Without a key, all conversations of the agent share one session.
session:
key: input.conversation_id
ttl: 86400History belongs to the conversation, not the connection. Reconnecting with the same conversation_id continues it, and closing the connection doesn't end it. Use ttl to expire inactive sessions. Connections don't wait for each other: when several connections can send messages for the same conversation at once, add a concurrency rule on the conversation field.
Rate limits
Rate limits cap the messages a connector accepts per minute, across all its connections. Set them under Rate Limits in the dashboard or in config.rate_limit. All three are off by default.
totalcounts messages from all connections together.per_ipcounts messages from one client IP address. IPv6 addresses count per /64 network.per_keycounts messages with the same value in the payload field named bykey. Messages without that field skip this limit.
A message over a limit gets an error event with the code RATE_LIMITED and retry_after in seconds. The connection stays open. The message starts no run, uses no Project credit, and doesn't count toward Max Messages per Session. Messages rejected per IP or per key don't count toward the total.
Limits and errors
| Limit | Value |
|---|---|
| Authentication | The secret message must arrive within 30 seconds and be at most 4 KiB. |
| Idle time | Session Timeout, 60 to 86,400 seconds, default 3,600. The timer restarts with each accepted message, ping, pong, or stop from the client and when a response ends. connic closes the connection within a minute after it runs out. |
| Messages per connection | Max Messages per Session, 1 to 10,000, default 100. Messages rejected with an error event before the ack don't count. Once the limit is used up, the next message gets MESSAGE_LIMIT and closes the connection. |
| Response time | The run timeout. Time paused for an approval or queued by a concurrency rule doesn't count. |
| Files | 50 per message, at most 32 MiB combined. |
| Missed answers | Up to 20 per connection ID, kept for the Session Timeout after the latest missed answer. An answer larger than 256 KiB arrives with the error Response too large to replay instead. |
| Keepalive | After 60 seconds without a message from the client, connic sends {"type": "ping"}. It needs no answer; an answer of {"type": "pong"} counts as activity. To keep an idle connection open, send {"type": "ping"} yourself; connic answers {"type": "pong"}. |
Errors arrive as events with "type": "error", a readable error, and a code. The connection stays open unless the table says otherwise. connic closes with code 1000 when the idle time runs out and after MESSAGE_LIMIT or CONNECTOR_INACTIVE. A connection to an unknown or paused connector, or to one without linked agents, is refused during the handshake with HTTP 403.
| Code | Meaning |
|---|---|
| AUTH_FAILED | The secret is wrong. Closes the connection with code 4003. |
| AUTH_TIMEOUT | No secret arrived within 30 seconds. Closes the connection with code 4003. |
| AUTH_INVALID | The first message isn't a JSON object or is larger than 4 KiB, or, on an apps_only connector, the connection didn't come from one of its apps. Closes the connection with code 4003. |
| PARSE_ERROR | A message isn't a JSON object. |
| UNKNOWN_TYPE | type is none of message, ping, pong, and stop. |
| EMPTY_MESSAGE | The message has no payload, message, or content. |
| NO_AGENTS | None of the names in agents is a linked agent. |
| RATE_LIMITED | A rate limit is reached. Retry after the seconds in retry_after. |
| DISPATCH_ERROR | connic couldn't start or follow the run of the agent named in agent. |
| MESSAGE_LIMIT | The connection has used up Max Messages per Session. Closes the connection. |
| CONNECTOR_INACTIVE | The connector was paused or deleted. Closes the connection. |
| CONNECTION_REPLACED | A newer connection with the same connection ID replaced this one. Closes the connection with code 4009. See Reconnect. |