Voice AI Agent Architecture: Turn Calls Into MCP Tools

By Hasnain Nisar · · Developer Guides

Learn voice AI agent architecture with MCP: turn phone calls into stateful tools for Claude Code, n8n, and other frameworks. Practical guide for developers.

Last updated: 2026-07-08

Voice AI Agent Architecture: Turn Calls Into MCP Tools

TL;DR: - MCP's Tasks extension lets voice AI agents run as long-lived, stateful tools that any AI framework can trigger and monitor - Speka's webhook + session model maps cleanly to MCP tool definitions—no custom bridge code required - Claude Code can now place phone calls by calling an MCP server that talks to Speka's API - Developers get bidirectional voice (speech-in, speech-out) with full conversation state, not just fire-and-forget API calls - The pattern works with n8n, LangChain, and any MCP client—not just Claude Code

You want your AI assistant to actually make phone calls. Not log them in a CRM. Not queue them for later. Dial a number, have a conversation, handle objections, book an appointment—and report back what happened.

That's been possible with Speka for a while. What's new is MCP's Tasks extension (release candidate, July 2025), which turns any long-running operation into a first-class tool that Claude Code, n8n, or your own agent framework can invoke, poll, and cancel. This article shows you the exact architecture: how Speka's voice sessions become MCP tools, what the state machine looks like, and where most implementations break.

Who this is for: Developers building with voice AI who are tired of duct-taping together webhooks, polling loops, and opaque session IDs. If you've ever lost track of a call's status or built a fragile while not done: sleep(1) loop, this is for you.


What Is a Voice AI Agent, Really?

Voice ai agent architecture mcp tools mistakes checklist

A voice AI agent is software that handles a phone conversation end-to-end: listening to speech, deciding what to say, generating synthetic voice, and managing turn-taking without a human in the loop. According to Gartner's 2025 Hype Cycle for AI, voice agents moved from the "Peak of Inflated Expectations" into the "Slope of Enlightenment" as latency dropped below 800ms and hallucination rates fell to acceptable levels for scripted domains.

The gap most guides skip: a voice agent isn't just text-to-speech + LLM + speech-to-text. It's a stateful, real-time system with strict latency budgets, interruption handling, and telephony integration. Treat it like a CRUD API and you'll build something that works in a demo and falls apart on the third call.

Speka's architecture handles the telephony, streaming, and interruption layers. MCP's Tasks extension handles the orchestration—so your calling code doesn't need to know what a "call leg" is.


How Does a Voice AI Agent Work on a Website?

Voice ai agent architecture mcp tools state machine

Most voice AI platforms offer two modes: embedded widget (JavaScript on your page) or API-only (you bring your own frontend). Speka does both, but the website widget is where most businesses start.

Here's the flow:

  1. User clicks the mic button on your site
  2. Browser captures audio via WebRTC and streams to Speka
  3. Speka runs the conversation loop: STT → LLM prompt → TTS → audio back
  4. Actions fire (book meeting, check order status) via webhooks you define
  5. Session ends, transcript and recording land in your dashboard

The website-specific constraint: browsers don't let you hold open a WebSocket forever. Speka uses a session token model—refreshable, scoped, and revocable—so a voice conversation survives page refreshes and tab switches. That's critical for long-form interactions like mortgage applications or medical intake.

For developers who want the same agent logic in a phone call rather than a browser, the underlying conversation engine is identical. The difference is the transport: WebRTC vs. PSTN/SIP trunk.


What Is MCP and Why Does It Matter for Voice?

MCP (Model Context Protocol) is an open standard, originally from Anthropic, for connecting AI assistants to external tools. Think of it as a USB-C port for AI capabilities—one protocol that works across Claude, ChatGPT, Cursor, and anything else that speaks MCP.

The Tasks extension (spec v2025-07, release candidate) adds support for long-running, stateful operations. Before this, MCP tools were assumed to return in seconds. A 12-minute phone call with hold music, transfers, and voicemail detection didn't fit.

What changed:

Before Tasks With Tasks Extension
Synchronous return Async job with lifecycle
No standard status Standard states: queued, running, completed, failed, cancelled
Client polls blindly Server pushes status via SSE or client polls /tasks/{id}
No cancellation DELETE /tasks/{id} cancels mid-flight
Result in response body Result fetched separately; can be large (recordings, transcripts)

For voice AI, this is the difference between a hack and a real integration. Your agent can now say "call this customer and let me know when you're done"—and MCP handles the bookkeeping.


The Architecture: Speka as an MCP Server

Here's how to expose Speka's call capability as an MCP tool. We'll use the Tasks extension throughout.

Core Components

1. The MCP Server - Registers one tool: make_outbound_call - Accepts parameters: phone_number, script_id, customer_context (JSON), webhook_url (optional) - Returns immediately with a task_id

2. Speka Session - Receives the call request via Speka's REST API - Creates a call session, returns session_id - Maps to MCP's task_id (1:1, stored in your state store)

3. State Machine

MCP Task State    ↔    Speka Call State
─────────────────────────────────────────
queued            →    call.initiated
running           →    call.in_progress
completed         →    call.finished (success)
failed            →    call.failed or call.no_answer
cancelled         →    call.cancelled (via API)

4. Webhook Bridge - Speka fires webhooks on state changes - Your MCP server updates task status - Client polls or receives SSE push

The part most guides skip: you need idempotency keys on the Speka side. If your MCP server retries the call creation (network blip, 504 from Speka), you don't want two calls to the same customer. Speka supports Idempotency-Key headers—use them.

The Tool Definition (JSON)

{
  "name": "make_outbound_call",
  "description": "Place an outbound phone call using a Speka voice agent. Returns a task ID to track progress.",
  "inputSchema": {
    "type": "object",
    "properties": {
      "phone_number": {"type": "string", "description": "E.164 format, e.g. +14155551234"},
      "script_id": {"type": "string", "description": "Speka conversation script to use"},
      "customer_context": {"type": "object", "description": "Key-value pairs passed to the agent"},
      "webhook_url": {"type": "string", "description": "Override default webhook for this call"}
    },
    "required": ["phone_number", "script_id"]
  },
  "returns": {
    "task_id": "string"
  }
}

Step-by-Step: Build the Claude Code Voice Agent

This is the practical integration. You'll build an MCP server that Claude Code can call to place phone calls through Speka.

Prerequisites

Step 1: Scaffold the MCP Server

# Python
uv init speka-mcp-server
cd speka-mcp-server
uv add mcp httpx

# Node
mkdir speka-mcp-server && cd speka-mcp-server
npm init -y
npm install @modelcontextprotocol/sdk axios

Step 2: Implement the Tool with Tasks

The key is implementing call_tool to return a task immediately, plus get_task to poll status.

Python (FastMCP pattern):

from mcp.server.fastmcp import FastMCP
import httpx
import uuid

mcp = FastMCP("speka-voice")
TASKS = {}  # In production, use Redis/Postgres

@mcp.tool()
async def make_outbound_call(phone_number: str, script_id: str, 
                             customer_context: dict = None) -> dict:
    task_id = str(uuid.uuid4())

    # Create call in Speka
    async with httpx.AsyncClient() as client:
        resp = await client.post(
            "https://api.speka.online/v1/calls",
            headers={"Authorization": f"Bearer {SPEKA_API_KEY}",
                     "Idempotency-Key": task_id},
            json={
                "phone_number": phone_number,
                "script_id": script_id,
 caller_id": "+15551234567",
                "webhook_url": f"https://your-server.com/webhook/{task_id}",
                "context": customer_context or {}
            }
        )
        session = resp.json()

    TASKS[task_id] = {
        "status": "queued",
        "speka_session_id": session["id"],
        "result": None
    }

    return {"task_id": task_id, "status": "queued"}

@mcp.tool()
async def get_task_status(task_id: str) -> dict:
    return TASKS.get(task_id, {"status": "unknown"})

Step 3: Handle Speka Webhooks

from fastapi import FastAPI, Request

app = FastAPI()

@app.post("/webhook/{task_id}")
async def speka_webhook(task_id: str, request: Request):
    payload = await request.json()

    if task_id not in TASKS:
        return {"ok": False}

    status_map = {
        "call.initiated": "running",
        "call.completed": "completed",
        "call.failed": "failed",
        "call.cancelled": "cancelled"
    }

    TASKS[task_id]["status"] = status_map.get(payload["event"], "running")

    if payload["event"] == "call.completed":
        TASKS[task_id]["result"] = {
            "recording_url": payload["data"].get("recording_url"),
            "transcript": payload["data"].get("transcript"),
            "duration_seconds": payload["data"].get("duration"),
            "outcome": payload["data"].get("disposition")  # e.g., "appointment_set"
        }

    return {"ok": True}

The gotcha that wastes an afternoon: Speka's call.completed webhook fires when the call ends, but the recording and transcript may take 10-30 seconds to process. If you mark the task completed immediately, Claude Code might fetch the result before the recording is ready.

Fix: use a processing sub-state, or have get_task_status check whether recording_url is still pending and return running until it's ready.

Step 4: Connect to Claude Code

Create claude_mcp_config.json:

{
  "mcpServers": {
    "speka-voice": {
      "command": "uv",
      "args": ["run", "server.py"],
      "env": {
        "SPEKA_API_KEY": "sk_..."
      }
    }
  }
}

Start Claude Code with the config. Now you can type:

"Call +14155551234 using the 'demo-booking' script and tell me what happened."

Claude will invoke make_outbound_call, poll get_task_status until completed, then present the transcript and outcome.

Grab the ready-made server scaffold in the free download below—it includes the idempotency handling, webhook verification, and a Docker setup for deployment.


Common Mistakes When Bridging Voice to MCP

Mistake 1: Treating voice calls like instant functions A call takes minutes, not milliseconds. Without the Tasks extension, you'd timeout or lose the result. Always use task_id + polling.

Mistake 2: Ignoring telephony edge cases No-answer, busy, voicemail, and "press 1 to continue" all happen. Your MCP server should surface these as meaningful task states, not just failed.

Mistake 3: Forgetting to cancel If the user aborts in Claude Code, you must propagate DELETE /tasks/{id} to Speka's cancel endpoint. Otherwise the call continues invisibly.

Mistake 4: Leaking PII in task results Transcripts contain names, addresses, payment details. Your MCP server should redact or tokenize before returning to the LLM context.

Mistake 5: No retry on webhook delivery Speka retries webhooks, but your endpoint must be idempotent. The same task_id + event combo should not trigger duplicate processing.


Can I Add a Voice Assistant to My Website Without Coding?

Yes. Speka's no-code embed handles the full browser-to-voice pipeline: microphone permission, WebRTC connection, conversation state, and action webhooks. You paste a script tag, configure in the dashboard, and deploy.

The developer value-add is integration. The same conversation script you build in Speka's UI can be referenced by script_id in the MCP tool above. Marketing teams iterate on the script; developers don't touch code. That's the architecture working: clean separation between conversation design and infrastructure.

For a deeper no-code setup, see our no-code voice AI n8n build guide.


How Much Does a Voice AI Agent Cost?

Typical ranges as of 2025, based on publicly listed pricing from major platforms:

Component Typical Cost Notes
Telephony (per-minute) $0.02–$0.05 Twilio, Telnyx, Vonage; inbound often cheaper
STT (per-minute) $0.004–$0.036 Deepgram, AssemblyAI, Whisper API
LLM (per 1K tokens) $0.0005–$0.03 GPT-4o-mini to Claude 3.5 Sonnet
TTS (per 1M chars) $4–$16 ElevenLabs, PlayHT, Cartesia
Platform fee (Speka) From $49/mo Includes orchestration, scripts, analytics

A 3-minute call at moderate scale: roughly $0.08–$0.25 in hard costs, plus platform fees. The efficiency win is coverage: one agent handles 20–40 concurrent calls vs. a human's one.

For agencies and resellers, our white-label voice AI platform guide breaks down margin structures.


Voice AI Agents for Developers: Beyond the Basics

The MCP integration above is infrastructure plumbing. The interesting work happens in the conversation layer:

Speka exposes these via webhook events and session context that persists across the call. Your MCP server can read the final context and decide what downstream actions to trigger.

For developers building with n8n, the same pattern works: an n8n workflow receives the webhook, polls the task, and branches on outcome. See our n8n voice agent CRM integration for the full flow.


Free download

To make this actionable, we built a free resource you can grab right now — no signup:

Frequently Asked Questions

What is a voice AI agent? A voice AI agent is software that conducts spoken conversations over phone or web, using speech recognition, language models, and text-to-speech to understand and respond without human intervention.

How does a voice AI agent work on a website? It runs as an embedded widget that captures microphone input, streams audio to a server, processes it through STT → LLM → TTS, and returns synthesized speech—typically via WebRTC for low latency.

Can I add a voice assistant to my website without coding? Yes. Speka and similar platforms offer script-tag embeds where you configure the agent in a dashboard and paste code into your page. No backend code required for basic implementations.

How much does a voice AI agent cost? At scale, hard costs run $0.08–$0.25 per minute of conversation (telephony + STT + LLM + TTS), plus platform fees starting around $49/month. Volume discounts apply above 10,000 minutes.

What is MCP and why use it for voice? MCP (Model Context Protocol) is an open standard for AI tool integration. Its Tasks extension lets voice calls—long, stateful, interruptible—behave like native tools that Claude Code and other agents can invoke and monitor.


Conclusion

Voice AI agent architecture isn't about picking the right LLM. It's about orchestration: bridging the gap between a synchronous AI assistant and an asynchronous, stateful phone call. MCP's Tasks extension finally gives developers a standard for that bridge.

Speka handles the voice layer—telephony, streaming, interruption, conversation state. MCP handles the tool contract. Your code stays clean: one tool definition, one webhook handler, one polling loop you didn't have to write.

Not everyone needs this. If you're running a simple appointment reminder, Speka's built-in scheduler and CRM integration are faster. But if you're building an AI agent that reasons about when to call, what to say, and what to do with the result—MCP + Speka is the architecture that scales.

Start building with Speka — or grab the ready-made MCP server scaffold and deploy in an hour.

Create your free Speka agent · More articles