---
title: "AI Phone Agent with Call Transfer to a Human in Node.js"
description: "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."
url: "https://micdrop.dev/blog/ai-phone-call-transfer-nodejs"
---

# Transfer an AI phone call to a human, cold or warm, in Node.js with Twilio

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.

November 29, 2026

[Godefroy de Compreignac](https://github.com/Godefroy)

Key takeaways

*   A cold transfer sends the call to a number at once. A warm transfer calls the person first, reads them a summary the model wrote, and only then connects the caller.
*   With Micdrop, \`transferCallTool()\` gives the model a tool that transfers once its announcement has been played, through the API of Twilio, Vonage, Telnyx or Plivo.
*   When nobody picks up in a warm transfer, the assistant keeps the caller and the model hears why, busy or no answer, so it can offer another way to help.
*   The same transfer runs from your own code with \`transport.transfer()\` and \`transport.warmTransfer()\`, for rules that should not depend on the model.
*   A production phone agent also reads the keypad, checks in when the caller goes silent and refuses webhooks that Twilio did not sign. Each is one function of \`@micdrop/telephony\` or \`@micdrop/server\`.

Every AI phone agent meets a caller it cannot help: a complaint that needs a manager, a question outside its tools, or someone who simply asks for a person. What the agent does at that moment decides whether the caller remembers a smooth handoff or a dead end.

This tutorial builds the handoff in your own Node.js server, in TypeScript, with a Twilio number and [Micdrop](/), the open source library this site publishes. It picks up where the [Twilio phone agent tutorial](/blog/ai-phone-agent-twilio-node) stops: the agent there answers calls, and here it learns to pass them on.

## Cold and warm transfers

Call centers use two words for two experiences:

Mode

What the caller lives

What the person hears

Cold

“I’m transferring you”, then the phone rings on the other side

A call that starts from nothing

Warm

“Please hold, I’m getting a colleague”, while the assistant stays on the line

A summary of the call, then the caller joins

A cold transfer is fast and fits a switchboard: sales, support, accounting. A warm transfer costs a few seconds of hold but spares the caller from repeating everything, and lets the assistant take the call back when nobody answers.

## How a transfer runs with Micdrop

`transferCallTool()` from `@micdrop/telephony` gives the model a tool named `transfer_call`. The model decides when to use it, from what the caller says and from the description of the tool:

1.  The model says a sentence that announces the transfer, then calls the tool.
2.  The server waits until that sentence has been played on the line, so the caller hears it in full.
3.  The transport transfers the call through the API of its provider. On Twilio, a cold transfer updates the call with a `<Dial>`, and a warm one calls the person into a conference with a `<Say>` of the summary before the caller joins.
4.  The transport emits `Transferred` and leaves the call. The server emits `End`, while the caller goes on talking with the person.

The transport needs the credentials of the account to act on the call, since the Media Stream alone carries only audio:

```typescript
import { TwilioTransport } from '@micdrop/telephony'

const transport = new TwilioTransport(socket, {
  accountSid: process.env.TWILIO_ACCOUNT_SID,
  authToken: process.env.TWILIO_AUTH_TOKEN,
})
```

## A cold transfer

```typescript
import { endCallTool } from '@micdrop/server'
import { transferCallTool } from '@micdrop/telephony'

const agent = new OpenaiAgent({
  apiKey,
  systemPrompt: 'You answer the phone for Acme...',
  tools: [endCallTool(), transferCallTool({ to: '+14155550100' })],
})
```

The destination is a phone number in E.164 format or a SIP URI, such as `sip:desk@pbx.example.com` for a desk phone on your PBX. Anything else throws when the tool is created, so a typo shows at startup rather than in front of a caller.

## A warm transfer with a briefing

```typescript
transferCallTool({ to: '+14155550100', mode: 'warm' })
```

In warm mode, the tool asks the model for one more parameter, a summary of the call in one or two sentences: who calls and what for. Twilio reads it to the person with its own voice once they pick up, then the caller joins them. The person starts the conversation knowing the case.

While the phone rings, the caller stays with the assistant. If nobody picks up, the line is busy or the person hangs up before joining, the transfer returns the reason to the server, which tells the model:

> The transfer to default did not go through (no-answer). The user is still on the line with you: tell them, and offer another way to help.

The assistant then answers in its own words, offers to take a message or to call back, and the call goes on. That fallback is what makes a warm transfer safe to offer outside office hours.

Two options of `TwilioTransport` shape the waiting. `holdMusicUrl` plays an audio file or TwiML to the caller while the person hears the summary, Twilio playing its own hold music by default and `''` keeping the line silent. `transferFallbackTwiml` is what the caller hears if the person hangs up after the summary, an apology and a hang up by default.

## Several destinations

A receptionist routes calls to more than one team. With `destinations`, the model picks one by name, guided by its description:

```typescript
transferCallTool({
  mode: 'warm',
  destinations: [
    { name: 'sales', to: '+14155550100', description: 'to buy or upgrade a plan' },
    { name: 'support', to: '+14155550199', description: 'for a problem with the service' },
  ],
})
```

`timeout` sets how long the phone rings, 30 seconds by default, `from` the number the person sees, and `description` replaces the default wording that tells the model when to transfer.

## Let the caller press 0 for a person

Many callers know the reflex of pressing 0. `dtmfInput()` from `@micdrop/server` turns the keys of the keypad into a message of the conversation, and its `format` option chooses the words. The model reads that message and calls the transfer tool, announcement included:

```typescript
import { dtmfInput } from '@micdrop/server'

dtmfInput(server, {
  format: (digits) =>
    digits === '0'
      ? 'The user pressed 0 to talk to a person.'
      : `The user typed ${digits} on the keypad.`,
})
```

The first key stops the assistant if it was speaking, as speaking over it does. An input ends with `#`, after a pause of 3 seconds, or after `maxDigits` keys, so the same helper also reads a customer number typed on the keypad.

## Transfer from your own code

Some transfers should follow a rule rather than the judgment of a model: a caller on a priority list, a case your CRM flags, a duration past which a person takes over. The transport transfers without the tool:

```typescript
// Cold: resolves once the call left the assistant
await transport.transfer({ to: '+14155550100' })

// Warm: resolves with the outcome
const result = await transport.warmTransfer({
  to: '+14155550100',
  briefing: 'Jane Doe, about a refund on order 1234.',
})
if (!result.transferred) {
  console.log(result.reason) // busy, no-answer, voicemail, failed or hung-up
}
```

`Transferred` fires with the destination either way, which is the place to log the handoff in your CRM:

```typescript
transport.on('Transferred', (to) => console.log(`Call handed to ${to}`))
```

## A caller who stops answering

A transfer starts a conversation. The opposite case ends one: a caller who walked away, or a line that dropped on their side. `idleTimeout()` asks whether they are still there after a silence, then says goodbye and hangs up once its prompts went unanswered:

```typescript
import { idleTimeout } from '@micdrop/server'

idleTimeout(server, {
  timeout: 10000,
  prompts: ['Are you still there?', 'Hello? Can you hear me?'],
})
```

The silence counts from the moment the answer has been played, so a long answer or a slow tool never counts against the caller.

## The complete server

The server below answers a Twilio number, refuses requests Twilio did not sign, and runs each call with a warm transfer, keypad input and the idle check. It is the [phone example of the repository](https://github.com/Godefroy/micdrop/tree/main/examples/phone) reduced to Twilio.

```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
npm install -D tsx typescript @types/node @types/ws
```

`server.ts`

```typescript
import { createServer } from 'node:http'
import { OpenaiAgent, OpenaiSTT, OpenaiTTS } from '@micdrop/openai'
import {
  dtmfInput,
  endCallTool,
  idleTimeout,
  MicdropServer,
  waitForParams,
} from '@micdrop/server'
import {
  transferCallTool,
  twilioStreamTwiml,
  TwilioTransport,
  validateTwilioSignature,
} from '@micdrop/telephony'
import { WebSocket, WebSocketServer } from 'ws'
// Loads Silero, which finds the turns of the caller on the server
import '@micdrop/silero/node'

const PORT = 8102
const env = process.env
const host = env.PUBLIC_HOST || `localhost:${PORT}`
const apiKey = env.OPENAI_API_KEY || ''
const twilio = {
  accountSid: env.TWILIO_ACCOUNT_SID || '',
  authToken: env.TWILIO_AUTH_TOKEN || '',
}

// The voice webhook of the number: connects the call to the stream
const http = createServer(async (request, response) => {
  if (request.url !== '/twilio/voice') return response.writeHead(404).end()

  // Kept as received, since the signature covers it
  let body = ''
  for await (const chunk of request) body += chunk
  const form = new URLSearchParams(body)

  const signed = validateTwilioSignature({
    authToken: twilio.authToken,
    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()

  response.writeHead(200, { 'Content-Type': 'text/xml' })
  response.end(
    twilioStreamTwiml({
      url: `wss://${host}/twilio/stream`,
      parameters: { caller: form.get('From') ?? '' },
    })
  )
})

// Twilio signs the opening of its Media Stream too
const wss = new WebSocketServer({ noServer: true })
http.on('upgrade', (request, socket, head) => {
  const signed =
    request.url === '/twilio/stream' &&
    validateTwilioSignature({
      authToken: twilio.authToken,
      signature: request.headers['x-twilio-signature'] as string | undefined,
      url: `wss://${host}${request.url}`,
    })
  if (!signed) return socket.destroy()
  wss.handleUpgrade(request, socket, head, (ws) => {
    runCall(ws).catch((error) => {
      console.error(error)
      ws.close(1011)
    })
  })
})

async function runCall(socket: WebSocket) {
  // The credentials let the transport act on the call: transfer, hang up
  const transport = new TwilioTransport(socket, twilio)
  const { caller } = await waitForParams(transport, (params) => params)

  const server = new MicdropServer(transport, {
    turns: { vad: 'silero' },
    firstMessage: 'Hello, thanks for calling Acme. How can I help you?',
    agent: new OpenaiAgent({
      apiKey,
      systemPrompt: `You answer the phone for Acme. Your answers are spoken on a phone line, so keep them short. The caller's number is ${caller}. When the caller asks for a person, or presses 0, transfer the call.`,
      tools: [
        endCallTool(),
        transferCallTool({
          mode: 'warm',
          destinations: [
            {
              name: 'sales',
              to: env.SALES_NUMBER || '',
              description: 'to buy or upgrade a plan',
            },
            {
              name: 'support',
              to: env.SUPPORT_NUMBER || '',
              description: 'for a problem with the service',
            },
          ],
        }),
      ],
    }),
    stt: new OpenaiSTT({ apiKey, language: 'en' }),
    tts: new OpenaiTTS({ apiKey, voice: 'alloy' }),
  })

  // Keys pressed on the phone become what the caller said
  dtmfInput(server, {
    format: (digits) =>
      digits === '0'
        ? 'The user pressed 0 to talk to a person.'
        : `The user typed ${digits} on the keypad.`,
  })

  // "Are you still there?" after 10 s of silence, then goodbye
  idleTimeout(server, { timeout: 10000 })

  transport.on('Transferred', (to) => console.log(`Transferred to ${to}`))
  server.on('End', ({ duration }) =>
    console.log(`Call ended for the assistant after ${duration} s`)
  )
}

http.listen(PORT, () => console.log(`Listening on http://localhost:${PORT}`))
```

Run it behind a tunnel, with two numbers that can take calls:

```bash
ngrok http 8102
PUBLIC_HOST=abcd.ngrok.app OPENAI_API_KEY=sk-... \
TWILIO_ACCOUNT_SID=AC... TWILIO_AUTH_TOKEN=... \
SALES_NUMBER=+14155550100 SUPPORT_NUMBER=+14155550199 \
npx tsx server.ts
```

Set the voice webhook of your Twilio number to `https://abcd.ngrok.app/twilio/voice`, call it, and ask for sales. Your phone rings, you hear the summary, then the caller joins you. Leave it ringing, and the assistant comes back to the caller with the news.

## Other phone providers

The tool and the code stay the same on the other transports of `@micdrop/telephony`. Each one transfers through the API of its provider:

Provider

Cold

Warm

Twilio

Updates the call with a `<Dial>`

Conference, with a `<Say>` of the summary

Vonage

Moves the call to a `connect` NCCO

Named conversation, after a `talk` of the summary

Telnyx

The `transfer` command of Call Control

Dials the person, speaks the summary, bridges both calls

Plivo

Transfers to the XML of a `transferUrl`

Not available

The [call transfer documentation](/docs/transports/call-transfer) details the credentials and the webhooks each one needs.

## What hosted platforms add

Hosted voice platforms sell transfers as a setting, with a dashboard for the destinations and analytics on the handoffs. Here the transfer is a tool in your code: the rules, the numbers and the logs live next to the rest of your backend, and you pay Twilio and your AI providers with no fee per minute in between. The trade is that the dashboard is yours to build. The comparisons with [Vapi](/blog/alternative-to-vapi) and [Retell AI](/blog/alternative-to-retell-ai) weigh both sides.

## Frequently asked questions

### What is the difference between a cold and a warm transfer?

A cold transfer sends the call to the destination at once, and the person picks up with no context. A warm transfer calls the person first, gives them a summary of the call, then connects the caller, and keeps the caller with the assistant when nobody answers.

### Can an AI agent transfer a Twilio call to a SIP phone?

Yes. A destination of `transferCallTool()` is either a phone number in E.164 format or a SIP URI such as `sip:desk@pbx.example.com`, which Twilio dials like any other destination.

### What happens if nobody answers a warm transfer?

The assistant keeps the call. The server tells the model why the transfer failed, busy, no answer or a hang up, and the model offers the caller another way to help, such as taking a message.

### Does the assistant keep listening after the transfer?

No. The transport closes its stream without hanging up, the server emits `End`, and the call continues between the caller and the person. Nothing more reaches your AI providers.

### Can I transfer without letting the model decide?

Yes. `transport.transfer()` and `transport.warmTransfer()` run from your own code, for instance on a key press or a rule of your CRM, and `warmTransfer()` returns whether the person took the call.

## Going further

The [call transfer](/docs/transports/call-transfer), [keypad](/docs/transports/phone-keypad) and [idle timeout](/docs/server/idle-timeout) pages document every option. To place calls rather than answer them, with voicemail detection, read [outbound calls](/docs/transports/outbound-calls). On a noisy line, [RNNoise on the server](/blog/rnnoise-noise-suppression-nodejs) keeps the street out of the transcript.

## Keep reading

[

November 29, 2026

## Build an AI Phone Agent in Node.js with Twilio

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.



](/blog/ai-phone-agent-twilio-node)

[![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)
