Webhook and WebSocket quick-start: answer phone calls with your own agent
CallNode is the phone layer under your AI agent. It owns the number, the carrier connection and speech recognition. Your code decides what to say. This guide covers the two ways to drive a call:
- Conversational webhook: one JSON POST per caller turn. You reply with text, and CallNode speaks it. This works with anything that can answer an HTTP request.
- Realtime WebSocket: one socket per call, with transcripts streamed as the caller speaks. For code where turn latency matters.
You'll build a webhook agent, check it locally, connect it to a number, check your status webhooks with a test key, place a first live call to your own phone, and then try the WebSocket.
What you'll need
- A CallNode account and one number (US/Canada local, $2.99 a month)
- Node.js 18 or later
- A public HTTPS URL for your server (any host or tunnel you already use)
Part 1: The conversational webhook
How it works
CallNode POSTs JSON to your webhook URL once when the call connects (call_started), then once per turn: each time the caller finishes speaking (user_speech) or finishes typing digits on the keypad (user_dtmf). Your endpoint returns a JSON object. The same contract applies to inbound and outbound calls.
Here's what a user_speech request looks like (from the docs):
{
"callId": "cn-ob-7f3a18a2-9b40-4e1e-9c4e-1b8b9b8e6b3a",
"event": { "type": "user_speech" },
"transcript": "I'd like to book a demo for next Wednesday at 10 AM.",
"conversationHistory": [
{ "role": "assistant", "content": "Hi, this is Hal from CallNode...", "timestamp": 1780173386556 },
{ "role": "user", "content": "Yes, I'm interested.", "timestamp": 1780173401200 }
],
"meta": {
"from": "+15145550199",
"to": "+16135551234",
"callId": "cn-ob-7f3a18a2-9b40-4e1e-9c4e-1b8b9b8e6b3a"
}
}
conversationHistory holds the full turn log, so your agent can be stateless.
Your reply can be as simple as text. CallNode speaks replyText in the voice chosen on the number:
| Field | What it does |
|---|---|
replyText | The text to speak. If you also send an audio URL, this text is only logged. |
publicAudioUrl | Your own HTTPS MP3 or WAV to play instead of CallNode speaking the text |
hangup (alias endCall) | true: play the reply, then end the call |
transfer + transferDestination | Play the reply, then connect the caller to an E.164 number or a sip: URI |
Return a bare JSON object: no markdown fences and no wrapper keys.
Step 1: Write the webhook
This is a minimal Node.js server with no dependencies. It greets the caller, repeats what they said, and hangs up when they say goodbye. Replace the marked line with a call to your own agent or LLM.
// server.js: a minimal CallNode conversational webhook (Node.js 18+, no dependencies)
const http = require('http');
const TOKEN = process.env.WEBHOOK_TOKEN; // the bearer token you set on the number in Step 3
function reply(res, obj) {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(obj));
}
http.createServer((req, res) => {
if (req.method !== 'POST') { res.writeHead(405); return res.end(); }
if (TOKEN && req.headers.authorization !== `Bearer ${TOKEN}`) { res.writeHead(401); return res.end(); }
let body = '';
req.on('data', (chunk) => (body += chunk));
req.on('end', () => {
let evt;
try { evt = JSON.parse(body); } catch { res.writeHead(400); return res.end(); }
const type = evt.event && evt.event.type;
if (type === 'call_started') {
return reply(res, { replyText: 'Hi, thanks for calling. How can I help?' });
}
const said = (evt.transcript || '').trim(); // speech, or keypad digits on user_dtmf
if (/\b(bye|goodbye)\b/i.test(said)) {
return reply(res, { replyText: 'Thanks for calling. Goodbye!', hangup: true });
}
// Replace this line with your agent: pass `said` and evt.conversationHistory to your LLM.
return reply(res, { replyText: `You said: ${said}` });
});
}).listen(process.env.PORT || 3000, () => console.log('webhook listening'));
Run it:
WEBHOOK_TOKEN=change-me node server.js
Keep each turn fast. The caller is waiting in silence while your agent works. From the docs: "The bridge waits up to 30 seconds, but the caller hears nothing while it waits." Aim for a few seconds, and keep replies short.
Retries. "If your endpoint fails, times out or returns non-2xx, the bridge tries twice more, one second apart (an HTTP 401 is not retried)". So make your handler safe to run twice for the same turn, and make sure your auth token matches: a wrong token fails the turn straight away.
Step 2: Check it locally
Send it the docs' call_started event:
curl -s -X POST http://localhost:3000 \
-H 'Authorization: Bearer change-me' \
-H 'Content-Type: application/json' \
--data-binary '{"callId":"cn-ob-7f3a18a2-9b40-4e1e-9c4e-1b8b9b8e6b3a","event":{"type":"call_started"},"meta":{"from":"+15145550199","to":"+16135551234","callId":"cn-ob-7f3a18a2-9b40-4e1e-9c4e-1b8b9b8e6b3a"}}'
You should get back {"replyText":"Hi, thanks for calling. How can I help?"}.
Step 3: Point a number at it
- Create an account (no credit card needed) and buy a number from Phone Numbers → Purchase.
- Deploy
server.jsbehind your public HTTPS URL. - In Dashboard → Phone Numbers, open the number and set its webhook URL to your server. Set auth to bearer with the same token. (Supported auth types: none, basic, bearer, or a custom header.)
- Call the number from your own phone. You'll hear the greeting, and the server repeats what you say.
What it costs: inbound minutes are $0.02 each, per whole minute rounded up. When CallNode speaks your replyText (rather than playing your own audio), the call also bills the spoken-replies rate per started minute. That's the realtime rate, $0.02 a minute with Standard Voice, shown as a "Spoken replies" line on Billing → History.
Part 2: Check your status webhooks with a test key
Test keys (cn_test_…) "never reach a carrier". There's no wallet charge, and your status webhooks fire as they would live. Create a test key under API Keys in the dashboard. Requests are signed with HMAC-SHA256 over timestamp + "\n" + body.
A test call checks your status webhooks only. From callnode.io/docs/test-mode: "Only the status webhooks above fire. Nothing is dialled and nobody speaks, so a test call never reaches the call's conversational webhookUrl: no call_started and no user_message events. To hear your agent answer, place a call with a live key to a phone you own." Step 2 below covers that live call.
Step 1: Place a test call
This is the Node.js example from callnode.io/docs/quickstart. Only the comments are ours:
const crypto = require('crypto');
async function placeCall({ apiKey, apiSecret, to, from, leadId }) {
const payload = {
to, from,
metadata: { leadId },
statusWebhookUrl: 'https://yourcrm.example.com/voice/events'
};
const body = JSON.stringify(payload);
const ts = Math.floor(Date.now() / 1000).toString();
const sig = crypto.createHmac('sha256', apiSecret)
.update(ts + '\n' + body)
.digest('hex');
const res = await fetch('https://api.callnode.io/api/v1/outbound/calls', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Api-Key': apiKey,
'X-Timestamp': ts,
'X-Signature': sig,
'X-Idempotency-Key': crypto.randomUUID()
},
body
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(`[${res.status}] ${err.error || 'unknown'}: ${err.message || res.statusText}`);
}
return res.json(); // { callId, status, createdAt }
}
placeCall({
apiKey: process.env.CALLNODE_KEY, // cn_test_... for this step
apiSecret: process.env.CALLNODE_SECRET,
to: '+16135551234',
from: '+15145550199', // your CallNode number
leadId: 'lead_abc123'
}).then(console.log).catch(console.error);
With a test key:
- The API answers
202 Acceptedwith acallId. About 2 seconds later,call.answeredreaches yourstatusWebhookUrl, and about 5 seconds latercall.completedarrives (costUsd: "0.00"). - To test your failure handling, call a sentinel number instead:
+15005550001firescall.failedwithno_answer, and+15005550002firescall.failedwithcarrier_rejected. - The real validation checks still run, so a test call outside 8am–9pm at the called number's local time is refused with
tcpa_window_violation, as a live one would be. Test calls skip the caller-ID check, because nothing is dialled.
Step 2: Your first live call, to your own phone
To hear your Part 1 agent on a real call, switch to a live key and call a phone you own. You need:
- A live key (
cn_live_…) and a wallet balance of at least $0.10 (the pre-auth hold). - A
fromnumber verified as a caller ID (Numbers, open the number, Caller ID card; verification is automatic and takes about a minute). An unverified number is refused with403 caller_id_not_verified. toset to your own phone, called between 8am and 9pm at its local time.webhookUrlpointing at your Part 1 server, andwebhookAuthcarrying the same bearer token. WithoutwebhookAuth, the Part 1 server answers 401 and every turn fails (a 401 isn't retried).
Use the same placeCall function with these two fields added to the payload:
const payload = {
to, from,
metadata: { leadId },
webhookUrl: 'https://your-server.example.com/', // your agent from Part 1
webhookAuth: { type: 'bearer', value: process.env.WEBHOOK_TOKEN }, // same token as server.js
statusWebhookUrl: 'https://yourcrm.example.com/voice/events'
};
Run it with CALLNODE_KEY set to your live key and to set to your own number. Your phone rings with your CallNode number as caller ID. When you answer, your server's greeting plays, and it repeats what you say. The call bills like any outbound call: $0.02 a minute to the US and Canada, plus the spoken-replies rate from Part 1.
Part 3: The realtime WebSocket
When you write the agent in code and want faster turns, switch the number to realtime mode. CallNode opens one WebSocket to your server per call and streams:
session.start: the call is answeredtranscript.partial/transcript.final: what the caller is saying, as they say itturn: the settled utterance. Most integrations act only on this framedtmf: one keypad digitsession.end: the last frame
You send back say (text CallNode speaks, up to 1,000 characters), audio.out (your own audio), transfer, hangup or clear. Every frame is a JSON text message with a type field. The caller can interrupt, and you're told when they do.
Step 1: Run the reference server
CallNode publishes a complete Node.js reference server with one dependency, ws: callnode-realtime-echo.js. With RT_SAY=1 it greets the caller, repeats what they said with say, hangs up when they press 9, and transfers when they press 5 (if you set a destination).
npm i ws
curl -O https://callnode.io/api/downloads/callnode-realtime-echo.js
RT_SAY=1 RT_TOKEN=change-me node callnode-realtime-echo.js
Other settings it reads: RT_PORT (default 8765), RT_TLS_CERT / RT_TLS_KEY (PEM paths for wss://, or leave them out and run behind your own TLS proxy), RT_WANT_AUDIO=1 (receive the caller's raw audio) and RT_TRANSFER_TO.
Your server must be reachable from the internet over TLS (wss://) on a public hostname.
The core of a realtime handler, exactly as callnode.io/docs/realtime prints it (replace myAgent with your own agent):
const WebSocket = require('ws');
// Your agent: what the caller said in, the text to speak out.
async function myAgent(text) {
return 'You said: ' + text;
}
const wss = new WebSocket.Server({ port: 8765 });
wss.on('connection', (ws, req) => {
const callId = req.headers['x-callnode-call-id'];
ws.on('message', async (raw) => {
const f = JSON.parse(raw);
if (f.type === 'session.start') {
ws.send(JSON.stringify({ type: 'session.options', audioIn: false }));
ws.send(JSON.stringify({ type: 'say', id: 'greeting', text: 'Hi, how can I help?' }));
}
if (f.type === 'turn') {
// f.text is what the caller said; answer with text (say) or your own audio (audio.out)
const reply = await myAgent(f.text);
ws.send(JSON.stringify({ type: 'say', id: 'reply', text: reply }));
}
if (f.type === 'dtmf' && f.digit === '9') {
ws.send(JSON.stringify({ type: 'say', text: 'Goodbye.' }));
ws.send(JSON.stringify({ type: 'hangup' })); // waits for the goodbye to finish
}
});
});
Step 2: Turn realtime on for the number
On the number's page, open Realtime WebSocket (advanced), enter your wss:// URL, and set bearer auth with your RT_TOKEN. Inbound calls to the number then use the socket. (The same setting is available through the API, as voice.realtime on the number. See the docs.)
Keep the webhook from Part 1 configured. It's the fallback: if your socket can't be reached or drops mid-call, the call continues on the webhook. A number with neither ends the call with a busy tone, not silence.
What it costs: realtime mode adds $0.02 per started minute of socket time on top of the call. Socket time is "drawn from your wallet and never from included minutes". That rate covers speech for say frames too. Premium Voice, where it's offered on your account, is $0.04 a minute.
Which should you use?
| Conversational webhook | Realtime WebSocket | |
|---|---|---|
| Works with | n8n, Flowise, cloud functions, any HTTP endpoint | Code you write |
| Per turn | One HTTP round trip | Frames stream both ways; no audio file hosting |
| Extra cost | Spoken-replies rate when CallNode speaks your text; nothing extra if you return your own audio | $0.02 a minute of socket time |
| Fallback | n/a | Falls back to the webhook |
Next steps
- Let your assistant use the same number: Give your Claude, ChatGPT or Cursor agent a phone number via MCP
- Why CallNode is the phone layer and not the agent: A phone number for your AI agent
- Full reference: Conversational webhook · Realtime WebSocket · Test mode