Build an AI phone agent in Node.js with Twilio and TypeScript
Answer a Twilio phone number with an AI voice agent running in your own Node.js server: TwiML, Media Streams, turn detection, tools and hang up, in one TypeScript file.
November 29, 2026
Godefroy de CompreignacUpdated on November 29, 2026
Key takeaways
- A Twilio number answered by an AI agent needs three things on your side: a webhook that returns TwiML, a WebSocket that receives the call audio, and the voice loop that turns the caller's speech into an answer.
- With Micdrop the whole agent fits in one TypeScript file on a Node server, with OpenAI for speech to text, the LLM and the voice. Swap any of the three for another provider without touching the phone code.
- A phone streams the caller continuously, so the server finds the turns itself, with Silero VAD and optionally the Smart Turn model.
- You pay Twilio for the number and the minutes, and each AI provider for what the call uses. Nothing sits in between.
An AI phone agent answers a phone number with a voice model: the caller talks, the agent understands, looks things up through your code and answers out loud. Hosted platforms sell this as a product. This tutorial builds it in your own Node.js server, in TypeScript, with a Twilio number, OpenAI and Micdrop, the open source library this site publishes. The finished server is a single file of about 70 lines, and the first call works in under half an hour.
Everything here uses packages that ship today: @micdrop/telephony for the
Twilio side, @micdrop/server for the conversation, @micdrop/silero for the
turns. The same code runs in the
phone example of the repository,
which also covers Vonage, Telnyx and Plivo.
How a phone call reaches your agent
Twilio connects the public phone network to your server in two steps. When a call comes in, it asks a webhook of yours what to do. Your answer is a short TwiML document that tells Twilio to open a Media Stream, a WebSocket that carries the caller’s voice to your server and your agent’s voice back.
graph LR A[Caller] -->|phone network| B[Twilio number] B -->|1. POST /twilio/voice| C[Your Node server] C -->|TwiML: connect a stream| B B <-->|2. WebSocket, ÎĽ-law 8 kHz| C C <--> D[Speech to text, LLM, text to speech]
On the WebSocket, Micdrop takes over. TwilioTransport decodes the ÎĽ-law audio
at 8 kHz and brings it to 16 kHz for the speech to text. Silero VAD hears when
the caller starts and stops speaking. The agent writes the answer, the text to
speech reads it sentence by sentence, and the transport sends it back down to
the line. When the caller speaks over the agent, the server stops the answer
and asks Twilio to drop the audio it still holds, so the agent goes quiet at
once.
What you need
- Node.js 20 or later.
- A Twilio account with a phone number that accepts voice calls. A trial account is enough to test, within the limits Twilio puts on trials.
- An OpenAI API key, used for speech to text, the LLM and the voice. Any other provider Micdrop supports works the same way.
- A tunnel that gives your machine a public address, such as ngrok or cloudflared.
Set up the project
mkdir phone-agent && cd phone-agentnpm init -ynpm pkg set type=modulenpm install @micdrop/server @micdrop/telephony @micdrop/openai @micdrop/silero onnxruntime-node ws zodnpm install -D tsx typescript @types/node @types/wsonnxruntime-node runs the Silero model that finds the caller’s turns, on the
CPU of your server.
Write the server
The server answers the Twilio webhook with TwiML, then runs each call on the WebSocket Twilio opens:
import { createServer } from 'node:http'import { OpenaiAgent, OpenaiSTT, OpenaiTTS } from '@micdrop/openai'import { endCallTool, MicdropServer, waitForParams } from '@micdrop/server'import { TwilioTransport, twilioStreamTwiml } from '@micdrop/telephony'import { WebSocketServer } from 'ws'// Loads Silero, which finds the turns of the caller on the serverimport '@micdrop/silero/node'
const PORT = 8102const host = process.env.PUBLIC_HOST || `localhost:${PORT}`const apiKey = process.env.OPENAI_API_KEY || ''
// 1. Twilio asks what to do with an incoming callconst http = createServer(async (request, response) => { if (request.url !== '/twilio/voice') return response.writeHead(404).end()
let body = '' for await (const chunk of request) body += chunk const form = new URLSearchParams(body)
response.writeHead(200, { 'Content-Type': 'text/xml' }) response.end( twilioStreamTwiml({ url: `wss://${host}/twilio/stream`, parameters: { caller: form.get('From') ?? '' }, }) )})
// 2. Twilio streams the call to this WebSocketconst wss = new WebSocketServer({ server: http, path: '/twilio/stream' })
wss.on('connection', async (socket) => { const transport = new TwilioTransport(socket) const { caller } = await waitForParams(transport, (params) => params) console.log('Call from', caller)
const server = new MicdropServer(transport, { // No app on the line to say when a sentence ends: the server listens turns: { vad: 'silero' }, firstMessage: 'Hello, thanks for calling. How can I help you?', agent: new OpenaiAgent({ apiKey, systemPrompt: 'You answer the phone for a small company. Your answers are spoken on a phone line, so keep them short and conversational.', // Lets the agent hang up once the caller says goodbye tools: [endCallTool()], }), stt: new OpenaiSTT({ apiKey, language: 'en' }), tts: new OpenaiTTS({ apiKey, voice: 'alloy' }), })
server.on('End', ({ duration }) => console.log(`Call ended after ${duration} s`))})
http.listen(PORT, () => console.log(`Listening on http://localhost:${PORT}`))Three details carry the phone specific part:
twilioStreamTwimlwrites the<Connect><Stream>TwiML. Twilio accepts no query string on the stream address, so values such as the caller’s number travel asparameters, andwaitForParamshands them to you on the other side.turns: { vad: 'silero' }makes the server find the turns. In a browser call the client does it, on a phone line nobody else can.endCallTool()lets the model end the call. The transport waits until Twilio confirms the goodbye has played, then closes the stream, and the call hangs up.
Expose it and point your number to it
Start a tunnel to port 8102:
ngrok http 8102Copy the host it gives you, without https://, and start the server with it:
PUBLIC_HOST=abcd.ngrok.app OPENAI_API_KEY=sk-... npx tsx watch server.tsIn the Twilio console, open your number, and under Voice configuration set
A call comes in to the webhook https://abcd.ngrok.app/twilio/voice, with
the HTTP POST method. Save, call the number and talk. Say goodbye, and the
agent hangs up.
Give the agent something to do
An agent that only chats is a demo. Tools are how it reaches your systems, your calendar, your orders, your CRM. Each tool is a typed function on your server, and the model decides when to call it:
import { z } from 'zod'
const agent = new OpenaiAgent({ apiKey, systemPrompt: `You answer the phone for a bakery. The caller's number is ${caller}.`, tools: [ endCallTool(), { name: 'find_order', description: 'Find the latest order placed from a phone number', inputSchema: z.object({ phone: z.string() }), execute: async ({ phone }) => db.orders.findLatest({ phone }), }, ],})The caller hears silence while a tool runs, so keep tools fast, or have the model say “let me check” first. The tools page covers the timing of a tool call and what happens when the caller interrupts it.
Read the keypad
The keys the caller presses arrive as Dtmf events of the transport.
dtmfInput() gathers them until #, a count or a pause, adds them to the
conversation and lets the agent answer, so a caller can type a customer number
while the agent follows:
import { dtmfInput } from '@micdrop/server'
dtmfInput(server, { maxDigits: 8 })// The conversation gets: "The user typed 12345678 on the keypad."The first key stops the assistant if it was speaking. Keypad (DTMF) covers the options, and how the agent presses keys itself in a phone menu.
Transfer the call to a person
transferCallTool() lets the model hand the call to a person, at once or
after briefing them with a summary, once it has told the caller. The
transport then needs the credentials of your account:
import { transferCallTool, TwilioTransport } from '@micdrop/telephony'
const transport = new TwilioTransport(socket, { accountSid: process.env.TWILIO_ACCOUNT_SID, authToken: process.env.TWILIO_AUTH_TOKEN,})// ...tools: [endCallTool(), transferCallTool({ to: '+14155550100', mode: 'warm' })]The call transfer tutorial builds a receptionist that routes callers to sales or support, with a fallback when nobody picks up, and the call transfer page documents every option.
Hold the turn while the caller thinks
Silero hears silence, and a caller who pauses to find a word goes silent too. The Smart Turn model listens to the end of the sentence and keeps the turn open while it sounds unfinished. It runs on the server next to Silero:
npm install @micdrop/smart-turnimport { SmartTurn } from '@micdrop/smart-turn'import '@micdrop/smart-turn/node'
const server = new MicdropServer(transport, { turns: { vad: 'silero', detector: new SmartTurn() }, // ... agent, stt, tts})The agent then answers sooner after a finished question and waits longer after a hesitation. Turn detection on the server explains the settings.
Make it sound good on a phone line
A phone line carries 8 kHz audio, the band of a classic call. The transport filters the agent’s voice down to the line, so a voice synthesized at 24 kHz reaches the caller without a metallic hiss. A few choices help further:
- Pick a speech to text model that handles phone audio well. Several providers train models on it, and a model tuned to your language beats a bigger generic one.
- Write the prompt for the ear: short sentences, numbers spelled out, no lists.
- Expect 100 to 200 ms of extra latency from the phone network compared with a browser call, and choose fast providers for the rest.
- Remove the noise around the caller with
RNNoise on the server, one line in
audioFilters, so a street or a car opens no false turn.
The sample rate guide explains what 8 kHz does to a voice agent and how to compensate.
Secure the webhook
Anyone who finds your webhook address could open calls on your server. Twilio
signs each request with an X-Twilio-Signature header, and
validateTwilioSignature() from @micdrop/telephony checks it, with no other
dependency. In the webhook, before answering:
import { validateTwilioSignature } from '@micdrop/telephony'
const signed = validateTwilioSignature({ authToken: process.env.TWILIO_AUTH_TOKEN || '', signature: request.headers['x-twilio-signature'] as string | undefined, // The address as configured at Twilio, behind any tunnel or proxy url: `https://${host}${request.url}`, params: form,})if (!signed) return response.writeHead(403).end()Twilio signs the opening of its Media Stream too, with the wss:// address
of the stream and no fields. The
call transfer tutorial checks both, and
securing the webhooks
covers Vonage, Telnyx and Plivo.
Go to production
The server above is already the production shape: one Node process answers
many calls at once, each with its own MicdropServer, and the Silero model is
loaded once and shared by every call of the process. Deploy it where your other
Node services run, behind HTTPS, and point the number to its real address.
Two helpers make the call behave well when the caller does not: idleTimeout()
asks “Are you still there?” after a silence and hangs up once its prompts go
unanswered (idle timeout), and
outbound calls place calls with voicemail
detection.
From there, the usual next steps live in your own code: save the conversation of each call in your database as it happens with the conversation events, switch the agent to a speech to speech model such as the OpenAI Realtime API, add a fallback provider so a provider outage does not drop calls, and try Vonage, Telnyx or Plivo with the other telephony transports.
What it costs
Twilio bills the number every month and each minute of call at its own voice pricing. OpenAI bills the transcription, the tokens of the LLM and the characters of the voice at its API prices. Micdrop is MIT licensed and adds nothing per minute, so the bill of a call is the sum of those lines.
A hosted platform adds its own fee per minute on top of the same providers, and brings in exchange a dashboard, call analytics, campaigns and compliance certifications. If those matter more than owning the code, compare the hosted voice agent platforms, or read how Micdrop compares with Vapi and Retell AI.
Frequently asked questions
Can I build an AI phone agent with Node.js?
Yes. Twilio streams the call audio to a WebSocket of your Node.js server, and a library such as Micdrop runs the conversation on it: speech to text, an LLM and text to speech, or a speech to speech model. The whole agent is TypeScript, in the same codebase as the rest of your backend.
Do I need Twilio ConversationRelay for an AI agent?
No. ConversationRelay is Twilio’s managed option, which runs the speech to text and the voice on Twilio’s side and sends text to your server. Media Streams, used here, send the raw audio, so you choose every provider and keep the voice loop in your own code.
Which AI providers can answer the phone with Micdrop?
Any combination Micdrop supports: OpenAI, Gemini, Mistral or any model of the Vercel AI SDK for the LLM; Gladia, OpenAI, Gradium, Mistral or a local Whisper for speech to text; ElevenLabs, Cartesia, OpenAI, Gradium or a local voice for text to speech; or the OpenAI Realtime and Gemini Live speech to speech models.
Does it work with other phone providers than Twilio?
Yes. @micdrop/telephony also has transports for Vonage, Telnyx and
Plivo, and SignalWire speaks the Twilio protocol. Only the webhook and
the transport change, the agent stays the same.
How many calls can one server handle?
Each call holds a WebSocket, an audio buffer and a few streams to the AI providers, so a Node process holds many calls at once. Silero takes well under a millisecond per 32 ms window of audio, and one copy of the model serves every call. Measure with your providers and your hardware before you size the fleet.
Getting started
The phone example
is the code of this tutorial with the four providers wired in, and the
telephony documentation covers each of them. The
same MicdropServer also answers browser calls and
React Native apps, so a single agent can sit behind your
phone number, your website and your mobile app.