---
title: "Build an AI Phone Agent in Node.js with Twilio"
description: "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."
url: "https://micdrop.dev/blog/ai-phone-agent-twilio-node"
---

# 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 Compreignac](https://github.com/Godefroy)

Updated 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](https://github.com/Godefroy/micdrop/tree/main/examples/phone), 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](https://www.twilio.com/docs/voice/media-streams), a WebSocket that carries the caller’s voice to your server and your agent’s voice back.

```mermaid
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](https://www.twilio.com/try-twilio) 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](https://platform.openai.com/api-keys), 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](https://ngrok.com) or cloudflared.

## Set up the project

```bash
mkdir phone-agent && cd phone-agent
npm init -y
npm pkg set type=module
npm install @micdrop/server @micdrop/telephony @micdrop/openai @micdrop/silero onnxruntime-node ws zod
npm install -D tsx typescript @types/node @types/ws
```

`onnxruntime-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:

`server.ts`

```typescript
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 server
import '@micdrop/silero/node'

const PORT = 8102
const host = process.env.PUBLIC_HOST || `localhost:${PORT}`
const apiKey = process.env.OPENAI_API_KEY || ''

// 1. Twilio asks what to do with an incoming call
const 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 WebSocket
const 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:

*   `twilioStreamTwiml` writes the `<Connect><Stream>` TwiML. Twilio accepts no query string on the stream address, so values such as the caller’s number travel as `parameters`, and `waitForParams` hands 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:

```bash
ngrok http 8102
```

Copy the host it gives you, without `https://`, and start the server with it:

```bash
PUBLIC_HOST=abcd.ngrok.app OPENAI_API_KEY=sk-... npx tsx watch server.ts
```

In 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:

```typescript
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](/docs/server/tools) 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:

```typescript
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)](/docs/transports/phone-keypad) 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:

```typescript
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](/blog/ai-phone-call-transfer-nodejs) builds a receptionist that routes callers to sales or support, with a fallback when nobody picks up, and the [call transfer page](/docs/transports/call-transfer) 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](/blog/smart-turn-javascript) 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:

```bash
npm install @micdrop/smart-turn
```

```typescript
import { 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](/docs/server/vad) 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](/blog/rnnoise-noise-suppression-nodejs), one line in `audioFilters`, so a street or a car opens no false turn.

The [sample rate guide](/blog/audio-sample-rate-voice-agent) 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:

```typescript
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](/blog/ai-phone-call-transfer-nodejs) checks both, and [securing the webhooks](/docs/transports/telephony#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](/docs/server/idle-timeout)), and [outbound calls](/docs/transports/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](/docs/server/save-messages), switch the agent to a [speech to speech model](/docs/realtime) such as the OpenAI Realtime API, add a [fallback provider](/docs/agents/fallback) so a provider outage does not drop calls, and try Vonage, Telnyx or Plivo with the [other telephony transports](/docs/transports/telephony).

## What it costs

Twilio bills the number every month and each minute of call at its own [voice pricing](https://www.twilio.com/en-us/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](/blog/top-ai-voice-agent-platforms), or read how Micdrop compares with [Vapi](/blog/alternative-to-vapi) and [Retell AI](/blog/alternative-to-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](https://github.com/Godefroy/micdrop/tree/main/examples/phone) is the code of this tutorial with the four providers wired in, and the [telephony documentation](/docs/transports/telephony) covers each of them. The same `MicdropServer` also answers [browser calls](/docs/getting-started) and [React Native apps](/docs/react-native), so a single agent can sit behind your phone number, your website and your mobile app.

## Keep reading

[

November 29, 2026

## AI Phone Agent with Call Transfer to a Human in Node.js

Let an AI phone agent hand the caller to a person: at once, or after briefing them with a summary of the call. Complete TypeScript server with Twilio, keypad input, silence handling and signed webhooks.



](/blog/ai-phone-call-transfer-nodejs)

[![Vapi Alternative: Own the Voice Loop in TypeScript](/_astro/thumbnail.pE8hdKcx_1sPzmv.webp)

August 16, 2026

## Vapi Alternative: Own the Voice Loop in TypeScript

Vapi runs your voice agent on its servers for $0.05 a minute. Micdrop runs the same loop inside the Node server you already ship, with no platform fee.



](/blog/alternative-to-vapi)

[![Retell AI Alternative: Run the Voice Loop in Your App](/_astro/thumbnail.DSsfJSo5_2dgAa3.webp)

August 24, 2026

## Retell AI Alternative: Run the Voice Loop in Your App

Micdrop runs the voice loop in your Node server, so you pay your AI providers directly. Retell AI bills it per minute and extra concurrent calls monthly.



](/blog/alternative-to-retell-ai)

[![Audio Sampling Rate in a Voice Agent: 16, 24 or 48 kHz](/_astro/thumbnail.9EkTb0B-_Z1KtFVX.webp)

October 14, 2026

## Audio Sampling Rate in a Voice Agent: 16, 24 or 48 kHz

Browsers record at 44.1 or 48 kHz, speech models read 16 kHz and many voices speak at 24 kHz. Learn the rate each stage expects and what resampling costs.



](/blog/audio-sample-rate-voice-agent)
