MCPDocumentation
On this page

Voice agents with the MCP

An Autonex voice agent (LiveKit) talks to the panel only through the MCP: no webhooks, no n8n and no organization in the request body. The server generates each call's summary, title, topics, language, score, outcome and quality; the agent no longer computes them.

The Voice agents pack has two kinds of tools:

  • Call lifecycle (call_start, call_log, call_end): called by the agent's code, not its LLM. Idempotent by call_id; they cost 0 units.
  • In-call (contact_lookup, kb_search, case_open, notify_team, set_outcome…): used by the agent's LLM, through an allow-list. 1 unit each.

The agent key

Each agent has its own key of kind agent, with scope agent:runtime, bound to an agent_ref (for example joan-miro-voz):

Terminal
npm run mcp:key -- --org 39 --user none --kind agent --name "Joana (voice)" \
  --scopes agent:runtime --agent-ref joan-miro-voz --days 365
  • The organization and the agent come from the key. They are never sent as arguments.
  • Whatever the agent creates (incidents, notes) is recorded under the organization's agent account.
  • Only agent keys see these tools; a personal key does not, even with *.

The sequence of a call

Text
Agent (code)                 Autonex MCP                        Panel / jobs
────────────                 ───────────                        ────────────
joins the room ───► call_start(call_id, caller_phone…)
                     ◄── conversation_id, contact, local time, centre, kb_version
                                                                 conversation "in progress"
every turn ───────► call_log(call_id, turns[seq…])   (optional)  live transcript
LLM ──────────────► kb_search / contact_save / case_open / notify_team / set_outcome …
session closes ───► call_end(call_id, transcript, tool_calls, usage, recording)
                     ◄── conversation_id, job_id
                                                                 post-call job:
                                                                 audio → summary, topics, language,
                                                                 score and outcome → quality →
                                                                 escalation when a person is needed

call_end is authoritative: its transcript replaces call_log's. Each job step's status is stored on the conversation (processing) and shown in the panel.

Minimal example with LiveKit (Python)

Python
import os
from contextlib import AsyncExitStack
from datetime import datetime, timezone

from livekit.agents import Agent, AgentSession, JobContext, mcp
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client

MCP_URL = "https://mcp.autonexhub.es/mcp"
HEADERS = {"Authorization": f"Bearer {os.environ['AUTONEX_MCP_KEY']}"}
# What the LLM may use during the call (no other tool is offered to it).
ALLOWED = ["kb_search", "contact_lookup", "contact_save", "case_open", "notify_team", "set_outcome"]


async def entrypoint(ctx: JobContext):
    await ctx.connect()
    call_id = ctx.room.name
    started = datetime.now(timezone.utc)
    transcript, tool_calls = [], []

    # MCP client for the CODE (call lifecycle), separate from the LLM.
    stack = AsyncExitStack()
    read, write, _ = await stack.enter_async_context(streamablehttp_client(MCP_URL, headers=HEADERS))
    life = await stack.enter_async_context(ClientSession(read, write))
    await life.initialize()

    caller = next(iter(ctx.room.remote_participants.values()), None)
    start = await life.call_tool("call_start", {
        "call_id": call_id,
        "channel": "voice",
        "caller_phone": caller.attributes.get("sip.phoneNumber") if caller else None,
        "started_at": started.isoformat(),
    })
    slot = start.structuredContent  # contact, org_now, location, kb_version

    session = AgentSession(
        # ... stt, llm, tts, vad ...
        mcp_servers=[mcp.MCPServerHTTP(url=MCP_URL, headers=HEADERS, allowed_tools=ALLOWED)],
    )

    @session.on("conversation_item_added")
    def _on_item(ev):
        transcript.append({"role": ev.item.role, "text": ev.item.text_content or "",
                           "t": (datetime.now(timezone.utc) - started).total_seconds()})

    async def _on_shutdown():
        ended = datetime.now(timezone.utc)
        await life.call_tool("call_end", {
            "call_id": call_id,
            "ended_at": ended.isoformat(),
            "duration_s": int((ended - started).total_seconds()),
            "termination_reason": "user_hangup",
            "transcript": [t for t in transcript if t["role"] in ("user", "assistant")],
            "tool_calls": tool_calls,
            "usage": {"llm": [], "stt_s": 0, "tts_chars": 0},  # from metrics.UsageCollector
            "recording": {"key": f"recordings/39/joan-miro-voz/{call_id}.mp3"},
        })
        await stack.aclose()

    ctx.add_shutdown_callback(_on_shutdown)
    greeting = f"Hola {slot['contact']['name']}" if slot.get("contact") and slot["contact"].get("name") else "Hola"
    await session.start(agent=Agent(instructions=f"You are Joana. {greeting}."), room=ctx.room)
  • allowed_tools limits what the LLM sees. If your LiveKit Agents version does not have it, filter the tool list before giving it to the model.
  • The audio is uploaded by LiveKit's recording (egress) to recordings/{org}/{agent}/…; call_end only carries the key. A key outside your organization's folder is refused.

Idempotency and retries

  • call_start can be repeated: it returns the same conversation with created: false.
  • call_log ignores turns whose seq was already received. Once the call has ended it stores nothing (completed: true).
  • call_end writes once. Repeating it returns duplicate: true and the same job_id, without touching anything. If call_end fails on the network or with a 5xx, spool it to disk and retry (also when the agent restarts): it never duplicates the call.
  • A call_end without call_start (for example, if it was lost) still creates the conversation.
  • Errors that retrying does not fix: INVALID_INPUT (see issues), FORBIDDEN (key without agent_ref or without agent:runtime), NOT_FOUND from in-call tools (that call_id is not your organization's or never started).
  • RATE_LIMITED: wait retry_after seconds. The lifecycle costs no quota but counts towards the per-minute limit.

Notifying the team

notify_team(type, fields) uses your organization's notification types (those in avisos.json: interesado, queja, hablar_con_persona…). The agent sends the type and the fields; the server decides who receives it. Until the organization goes live, only the test recipients get it. If nobody attends the case within 24 hours, the server notifies again.