How to Build an AI Calling Agent With Claude Code and Twilio (and the Consent Rules)

Build an AI calling agent with Claude Code and Twilio ConversationRelay. Current Twilio per-minute rates are included, plus the TCPA consent rules.

By Archit Tamrakar · LinkedIn · · 10 min read

Quick answer: Use Twilio's ConversationRelay to handle speech-to-text and text-to-speech, and run a small WebSocket server where Claude writes each reply. Claude Code can generate that server for you. Free? Partly: Twilio's trial gives 75 voice minutes, but Claude API use is billed. Time: one sitting, since the code is two short files. Before any real call, get documented consent, because the FCC says AI-generated voices count as "artificial" under the TCPA.

This is a build guide, not legal advice. The code below is adapted from Twilio's published tutorial and its Call API docs. It has not been run by the author, so test it on your own verified number first.

What do you need before you start?

You need a Twilio account, an Anthropic API key, Node.js, a tunnelling tool and, most important, written proof that each person you call agreed to be called. Twilio's Claude tutorial lists Node.js 23+, a voice-capable Twilio number, an Anthropic API key and ngrok (or a similar tunnel).

  • Twilio account. Sign-up needs a verified email and phone number. Per Twilio's trial docs, no credit card is needed and the trial lasts 30 days.
  • Anthropic account. Claude Code needs a Claude subscription or an Anthropic Console account, per the Claude Code docs.
  • Claude Code installed. See our install guide, or what Claude Code is if it is new to you.
  • A consent record. A list of numbers, when and how each person agreed, and their time zone. The script below refuses to dial anyone not on it.

How do you build an AI calling agent with Claude Code and Twilio? (Method 1: write the server)

You set up Twilio, ask Claude Code to build a WebSocket server and an outbound-call script, then run both. ConversationRelay connects the call to a wss:// server. Your app receives the caller's words as text and sends text back, which Twilio speaks.

  1. Open the Twilio Console, then go to Communications > Voice > Settings > Privacy & Security. Accept the terms under These features are subject to the predictive and generative AI/ML features addendum and click Save. Twilio's onboarding guide requires this before ConversationRelay works.
  2. Get a voice-capable Twilio phone number. Verify this step: the menu may differ. As of 16 October 2026, Twilio lists US local numbers at $1.15 a month. Trial accounts use a Twilio trial number, per the trial docs.
  3. On a trial account, verify the phone you will call. Verify this step: the menu may differ. The trial allows up to 5 verified recipients.
  4. Install Claude Code. On macOS, Linux or WSL run curl -fsSL https://claude.ai/install.sh | bash. On Windows PowerShell run irm https://claude.ai/install.ps1 | iex. Open a new terminal and run claude --version (docs).
  5. Create a folder, cd into it, and run claude. Log in when prompted.
  6. Paste this prompt: "Build a Node.js ESM project with Fastify, @fastify/websocket, @anthropic-ai/sdk, twilio and dotenv. server.js hosts a /ws WebSocket for Twilio ConversationRelay and answers with Claude. call.js places one outbound call using client.calls.create with a twiml parameter. call.js must refuse to dial unless the number is in consent.json, is not in dnc.json, and it is between 8 a.m. and 9 p.m. in the person's time zone. The greeting must say it is an AI, name the business, give a callback number and explain how to opt out. Add opt-out by saying stop or pressing 9."
  7. Compare what Claude Code writes with the reference code below, or use that code directly.

Install and configure:

npm init -y
npm pkg set type="module"
npm install fastify @fastify/websocket @anthropic-ai/sdk twilio dotenv

Create .env with placeholders, never real keys in a repo:

ANTHROPIC_API_KEY="YOUR_ANTHROPIC_API_KEY"
TWILIO_ACCOUNT_SID="YOUR_ACCOUNT_SID"
TWILIO_AUTH_TOKEN="YOUR_AUTH_TOKEN"
TWILIO_FROM_NUMBER="+15550000000"
NGROK_URL="your-subdomain.ngrok.app"
BUSINESS_NAME="Example Dental"
CALLBACK_SPOKEN="five five five, zero one zero zero"
CLAUDE_MODEL="claude-haiku-5-5"

Create consent.json. The entry is an example: record real consent for each number.

{
  "+15551234567": {
    "consentedAt": "2026-10-01T10:00:00Z",
    "source": "signed web form",
    "timeZone": "America/New_York"
  }
}

server.js (adapted from Twilio's tutorial, with opt-out handling added):

import Fastify from "fastify";
import fastifyWs from "@fastify/websocket";
import Anthropic from "@anthropic-ai/sdk";
import dotenv from "dotenv";
import fs from "node:fs";
dotenv.config();

const MODEL = process.env.CLAUDE_MODEL || "claude-haiku-5-5";
const STOP = /\b(stop|do not call|don't call|remove me|opt out|unsubscribe|take me off)\b/i;
const SYSTEM_PROMPT =
  "You are a phone assistant and you are an AI. Say so if asked. Keep replies to one or two short sentences. " +
  "Spell out numbers, for example twenty not 20. No emojis, bullet points or special symbols. " +
  "If the person asks you to stop calling, agree politely.";
const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
const sessions = new Map();

function readList(file) {
  try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch { return []; }
}
function addToDnc(number) {
  const list = readList("dnc.json");
  if (number && !list.includes(number)) {
    list.push(number);
    fs.writeFileSync("dnc.json", JSON.stringify(list, null, 2));
  }
}
async function aiResponse(messages) {
  const res = await anthropic.messages.create({
    model: MODEL, max_tokens: 300, system: SYSTEM_PROMPT, messages,
  });
  return res.content[0].text;
}
function say(ws, text) {
  ws.send(JSON.stringify({ type: "text", token: text, last: true }));
}
function optOut(ws) {
  addToDnc(ws.callee);
  say(ws, "Understood. We will not call you again. Goodbye.");
  // Delay so the goodbye can be spoken before the session ends. Test this.
  setTimeout(() => ws.send(JSON.stringify({ type: "end" })), 6000);
}

const fastify = Fastify();
fastify.register(fastifyWs);
fastify.register(async (app) => {
  app.get("/ws", { websocket: true }, (ws) => {
    ws.on("message", async (raw) => {
      const msg = JSON.parse(raw.toString());
      if (msg.type === "setup") {
        ws.callSid = msg.callSid;
        ws.callee = msg.customParameters?.callee;
        sessions.set(ws.callSid, []);
      } else if (msg.type === "dtmf" && msg.digit === "9") {
        optOut(ws);
      } else if (msg.type === "prompt") {
        if (STOP.test(msg.voicePrompt)) return optOut(ws);
        const convo = sessions.get(ws.callSid);
        convo.push({ role: "user", content: msg.voicePrompt });
        try {
          const reply = await aiResponse(convo);
          convo.push({ role: "assistant", content: reply });
          say(ws, reply);
        } catch (err) {
          console.error(err);
          say(ws, "Sorry, I have a technical problem. Goodbye.");
          setTimeout(() => ws.send(JSON.stringify({ type: "end" })), 5000);
        }
      }
    });
    ws.on("close", () => sessions.delete(ws.callSid));
  });
});
await fastify.listen({ port: process.env.PORT || 8080, host: "0.0.0.0" });
console.log("Listening. Tunnel with: ngrok http 8080");

call.js (uses the client.calls.create pattern from Twilio's Call docs):

import twilio from "twilio";
import dotenv from "dotenv";
import fs from "node:fs";
dotenv.config();

const to = process.argv[2];
const read = (f, d) => { try { return JSON.parse(fs.readFileSync(f, "utf8")); } catch { return d; } };
const record = read("consent.json", {})[to];
const dnc = read("dnc.json", []);

if (!record) { console.error("No consent record. Not calling."); process.exit(1); }
if (dnc.includes(to)) { console.error("Number is on your do-not-call list."); process.exit(1); }

const hour = Number(new Intl.DateTimeFormat("en-US", {
  hour: "numeric", hourCycle: "h23", timeZone: record.timeZone,
}).format(new Date()));
if (hour < 8 || hour >= 21) { console.error("Outside 8am-9pm local time."); process.exit(1); }

const greeting =
  `Hello, this is an A I assistant calling for ${process.env.BUSINESS_NAME}. ` +
  `You can reach us at ${process.env.CALLBACK_SPOKEN}. ` +
  "To stop all calls, say stop or press nine. How can I help?";

const response = new twilio.twiml.VoiceResponse();
const relay = response.connect().conversationRelay({
  url: `wss://${process.env.NGROK_URL}/ws`,
  welcomeGreeting: greeting,
  dtmfDetection: true,
});
relay.parameter({ name: "callee", value: to });

const client = twilio(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
const call = await client.calls.create({
  from: process.env.TWILIO_FROM_NUMBER, to, twiml: response.toString(),
});
console.log("Call started:", call.sid);

Run it:

  1. In one terminal, run node server.js.
  2. In a second terminal, run ngrok http 8080. Copy the address without https:// into NGROK_URL in .env, then restart the server.
  3. In a third terminal, run node call.js +15551234567 with your own verified number.

Twilio's tutorial used claude-sonnet-4-20250514 and said it also worked with Haiku. As of 16 October 2026, Anthropic's model table lists claude-haiku-5-5 as the fastest model and claude-sonnet-5-5 as "Fast". Set CLAUDE_MODEL to switch.

Can Claude Code write the Twilio parts for you? (Method 2: MCP and Skills)

Yes, partly. Twilio publishes an MCP server and a Skills plugin for Claude Code, which give Claude Twilio's API specs and recommended patterns. This reduces guessing, but it does not replace the consent checks above.

  • MCP server: claude mcp add --transport http twilio-docs https://mcp.twilio.com/docs (Twilio docs).
  • Skills: claude plugin install twilio-developer-kit (Twilio docs).

Twilio's 7 May 2026 announcement lists launching an AI voice agent with ConversationRelay as an example. For general MCP setup, see our Claude Code MCP guide.

Which method should you choose?

Choose Method 1 if you want to see and control every line. Choose Method 2 if you want Claude Code to look up Twilio specifics as it builds. They combine well.

MethodCostDifficultyLimitsBest for
1. Paste or generate the serverTwilio and Claude API usageMediumYou maintain the codeFirst working call
2. Claude Code with Twilio MCP and SkillsSame, plus Claude Code accessMediumOutput still needs your reviewExtending an existing project

What does it cost, and what is free?

Your cost per call depends on call length, Claude token use and which Twilio charges apply to your account. As of 16 October 2026, Twilio lists US and Canada outbound calls at $0.0140 a minute and ConversationRelay at $0.07 a minute.

ItemPrice as of 16 October 2026Source
Outbound call, US and Canada$0.0140 per minuteTwilio
ConversationRelay$0.07 per minuteTwilio
US local number$1.15 per monthTwilio
Claude Haiku 5.5from $0.10 input, from $0.50 output per million tokensAnthropic
Claude Sonnet 5.5$2 input, $10 output per million tokensAnthropic
Twilio trial75 voice minutes, 30 days, 5 verified recipientsTwilio

What can go wrong, and how do you fix it?

Most failures come from the tunnel address, provider settings or trial limits.

  • Call connects, then drops. Twilio's docs show error 39001, "Network connection to WebSocket server failed". Check that the tunnel is running and NGROK_URL has no https://. The url must start with wss://.
  • Session ends with an error. An invalid pairing of speech model, voice or provider makes ConversationRelay send an error and disconnect. Remove custom provider settings first.
  • Call will not place on a trial account. Trial calls go only to verified numbers, and only in your sign-up country.
  • The agent reads out symbols. Keep the system prompt rule about spelling out numbers and avoiding symbols.
  • Anyone can connect to your WebSocket. Twilio sends an X-Twilio-Signature header on the handshake. Validate it with your auth token and reject invalid connections.
  • Model name error. Confirm the current ID in Anthropic's model table and set CLAUDE_MODEL to match.

In the US, calling someone with an AI voice needs their prior express consent, and telemarketing needs prior express written consent. The FCC's declaratory ruling, adopted 2 February 2024 and released 8 February 2024, confirmed that the TCPA's "artificial or prerecorded voice" rules cover current AI technologies that generate human voices.

The ruling also says the TCPA allows no carve-out for technology that purports to be the equivalent of a live agent. The key rules in 47 CFR 64.1200 (eCFR, current as of 14 October 2026):

RuleWhat it says
Consent, generalCalls to cellular and other listed lines using an artificial or prerecorded voice need the called party's prior express consent (emergency calls excepted)
Consent, telemarketingCalls that include an advertisement or constitute telemarketing need prior express written consent
Written consentA signed agreement naming the number; valid e-signatures count
IdentificationThe message must state at the start who is responsible for the call, and give a callback number during or after
Calling hoursNo telephone solicitation to residential subscribers before 8 a.m. or after 9 p.m. local time
Do-not-callNo solicitation to numbers on the national registry (listed safe harbours apply)
Revoking consentAny reasonable method works; a key-press opt-out on a call counts per se; honour within ten business days

Twilio's own stance matches this. Twilio says customers using AI on outbound calls must obtain prior express consent, identify themselves, and offer an opt-out for telemarketing. It also says non-compliance results in suspension of services. Twilio's US voice guidelines state they are not legal advice.

What's still unclear?

Revocation rules are changing. The FCC adopted a Report and Order on 30 September 2026 in a 3-0 vote, according to Crowell and Kelley Drye. It narrows the "revoke all" rule and lets callers designate an exclusive revocation method. Kelley Drye says the changes take effect 30 days after a notice is published in the Federal Register. Before that, Hunton reported the global revocation rule was delayed to 31 January 2027. The eCFR text above may therefore change soon.

Other open points:

  • Twilio's trial page does not say whether ConversationRelay is available on trial accounts.
  • It is unconfirmed that sending the end message right after a text message lets the goodbye finish. The 6-second delay in the code is a workaround to test.
  • This post does not cover state laws, recording consent or penalty amounts. Ask a lawyer before calling real customers.
  • The stop-word list in the code is deliberately broad and will end some calls early.

Last checked: 16 October 2026.

Frequently asked questions

Is it legal to make AI voice calls in the US?

Only with the right consent. The FCC ruled in February 2024 that AI-generated voices are covered by the TCPA's rules on artificial or prerecorded voices, so you need the called party's prior express consent. Telemarketing calls need prior express written consent. Rules are changing and this is not legal advice, so check with a lawyer before calling real customers.

How much does one AI call cost with Twilio and Claude?

As of 16 October 2026, Twilio lists US and Canada outbound calls at $0.0140 a minute and ConversationRelay at $0.07 a minute. Claude token costs are extra and depend on the model and how much is said.

Can I test an AI calling agent for free?

Partly. Twilio's trial lasts 30 days and includes 75 voice minutes, needs no credit card, and lets you call only verified numbers, up to 5 recipients. Calls are limited to your sign-up country. Claude API usage is billed separately, and Twilio's trial page does not say whether ConversationRelay is available on trial accounts.

Which Claude model should a phone agent use?

Phone calls need quick replies. As of 16 October 2026, Anthropic's model table lists claude-haiku-5-5 as the fastest model and claude-sonnet-5-5 as fast, with Sonnet billed at $2 input and $10 output per million tokens. The code in this guide defaults to Haiku and reads the model from the CLAUDE_MODEL setting, so you can switch.

What must an AI call say at the start?

Under 47 CFR 64.1200(b), artificial or prerecorded voice messages must state at the beginning who is responsible for the call, using the registered business name, and give a callback number during or after the message. Twilio also says telemarketing AI calls must offer an opt-out. The sample greeting here covers identity, number and opt-out.

What happens if someone asks to stop the calls?

Honour it. Under the eCFR text current as of 14 October 2026, a key-press opt-out on a call counts as a valid revocation, and requests must be honoured within ten business days. The FCC adopted changes on 30 September 2026 that are not yet effective, so the sample code adds the number to a do-not-call file immediately.

Sources

  1. FCC 24-17 Declaratory Ruling, Implications of Artificial Intelligence Technologies on Protecting Consumers from Unwanted Robocalls and Robotexts, Federal Communications Commission (2024-02-08)
  2. 47 CFR 64.1200 Delivery restrictions, eCFR (2026-10-14)
  3. TwiML Voice: ConversationRelay, Twilio Docs (2026-09-30)
  4. Conversation Relay Onboarding, Twilio Docs (2026-10-16)
  5. Integrate Claude, Anthropic's AI Assistant, with Twilio Voice Using ConversationRelay, Twilio (2025-05-13)
  6. Call resource, Twilio Docs (2026-10-16)
  7. Voice Pricing, United States, Twilio (2026-10-16)
  8. Twilio trial account, Twilio Docs (2026-10-16)
  9. Business Impact of the FCC Ruling on AI-Generated Voices, Twilio (2024-02-15)
  10. United States: Voice Guidelines, Twilio (2026-10-16)
  11. Claude Code overview, Anthropic (Claude Code Docs) (2026-10-16)
  12. Models overview, Anthropic (Claude Platform Docs) (2026-10-16)
  13. Twilio MCP server, Twilio Docs (2026-10-16)
  14. Twilio Skills for AI coding agents, Twilio Docs (2026-07-09)
  15. Twilio Brings Customer Engagement Workflows into Claude by Anthropic, Twilio (2026-05-07)
  16. FCC Officially Adopts Amendments to TCPA Rules, Crowell & Moring (2026-10-16)
  17. FCC Revises TCPA Consent Revocation Rules, Kelley Drye & Warren (2026-10-16)
  18. FCC's TCPA Global Revocation Rules Now Effective January 2027, Hunton Andrews Kurth (2026-01-15)