How to Integrate MCP Servers with LiveKit Agents: A Complete Guide
You can integrate MCP servers with LiveKit Agents by passing an MCPServer instance to the mcp_servers parameter of AgentSession, which automatically converts remote MCP tools into callable LLM functions.
The Model Context Protocol (MCP) enables AI agents to discover and invoke tools exposed by external servers. In the livekit/agents repository, the framework provides first-class support for MCP integration, allowing voice agents to seamlessly call remote capabilities during conversations. This guide covers the architecture, implementation steps, and practical examples for connecting your LiveKit agents to MCP servers.
Understanding the MCP Integration Architecture
The MCP integration in LiveKit Agents is built on a clean abstraction layer that handles transport, tool discovery, and execution.
Core Classes in livekit/agents/llm/mcp.py
The primary implementation resides in livekit/agents/llm/mcp.py, which defines three key components:
MCPServer– The abstract base class that defines the interface for all MCP connections. It handles the lifecycle of the connection and provides methods for initialization and tool listing.MCPServerHTTP– A concrete implementation that communicates with remote MCP servers using HTTP transport. It automatically detects between Server-Sent Events (SSE) and streamable-HTTP based on the URL path, or you can force a specific transport via thetransport_typeparameter.MCPServerStdio– For local MCP servers, this class spawns the server as a subprocess and communicates over STDIO, useful for development or local tool chains.
How AgentSession Handles MCP Servers
In livekit/agents/voice/agent_session.py, the AgentSession class accepts a list of MCPServer instances through the mcp_servers parameter. When session.start() is called, the framework:
- Initializes each server by calling
MCPServer.initialize(). - Discovers tools via
MCPServer.list_tools()and converts them to LiveKit function tools using thefunction_toolutility fromlivekit/agents/llm/tool_context.py. - Registers these tools with the LLM context, making them available for invocation during the conversation.
Any errors returned by the MCP server are raised as ToolError exceptions within the agent framework.
Installation and Setup
The MCP client library is not included in the base installation. You must install the optional mcp extra:
# Using pip
pip install "livekit-agents[mcp]"
# Or using uv from the repository root
uv sync --all-extras --dev
Connecting to MCP Servers
LiveKit Agents supports two primary transport mechanisms for MCP integration.
HTTP/SSE Transport with MCPServerHTTP
For remote MCP servers accessible via HTTP, use MCPServerHTTP. The class automatically detects the transport protocol based on the URL:
from livekit.agents import mcp
# Auto-detect SSE vs streamable-HTTP
http_srv = mcp.MCPServerHTTP(url="https://my-mcp.example.com/mcp")
# Force specific transport
http_srv = mcp.MCPServerHTTP(
url="https://my-mcp.example.com/mcp",
transport_type="streamable_http" # or "sse"
)
Local Subprocess with MCPServerStdio
For local development or running MCP servers as binaries on the same machine:
# Run a local MCP server binary
stdio_srv = mcp.MCPServerStdio(
command="my-mcp-binary",
args=["--port", "8000"]
)
Filtering Available Tools
You can restrict which remote tools are exposed to the LLM using the allowed_tools parameter:
http_srv = mcp.MCPServerHTTP(
url="https://my-mcp.example.com/mcp",
allowed_tools=["search", "weather", "calendar"]
)
Complete Integration Example
Here is a complete implementation showing how to integrate an HTTP MCP server into a voice agent:
import logging
from dotenv import load_dotenv
from livekit.agents import Agent, AgentServer, AgentSession, JobContext, cli, inference, mcp
from livekit.plugins import silero
from livekit.plugins.turn_detector.multilingual import MultilingualModel
logging.getLogger("mcp-agent").setLevel(logging.INFO)
load_dotenv()
class MyAgent(Agent):
def __init__(self) -> None:
super().__init__(
instructions=(
"You can retrieve data via the MCP server. "
"Answer user questions using the remote tools."
),
)
async def on_enter(self):
self.session.generate_reply(
instructions="Hi! Ask me anything.",
allow_interruptions=True
)
# Create the MCP server connection
mcp_srv = mcp.MCPServerHTTP(url="http://localhost:8000/mcp")
# Assemble the voice session with MCP integration
session = AgentSession(
vad=silero.VAD.load(),
stt=inference.STT("deepgram/nova-3", language="multi"),
llm=inference.LLM("openai/gpt-4.1-mini"),
tts=inference.TTS("cartesia/sonic-3"),
turn_detection=MultilingualModel(),
mcp_servers=[mcp_srv], # Integrate MCP here
)
server = AgentServer()
@server.rtc_session()
async def entrypoint(ctx: JobContext):
await session.start(agent=MyAgent(), room=ctx.room)
if __name__ == "__main__":
cli.run_app(server)
Source: examples/voice_agents/mcp/mcp-agent.py in the livekit/agents repository.
Real-World Use Case: Zapier Integration
For production deployments, you might want to configure MCP servers dynamically via environment variables. This example shows integration with Zapier's MCP server:
import os
import logging
from dotenv import load_dotenv
from livekit.agents import Agent, AgentServer, AgentSession, JobContext, cli, inference, mcp, metrics
from livekit.plugins import silero
from livekit.plugins.turn_detector.multilingual import MultilingualModel
load_dotenv(dotenv_path=".env.local")
logger = logging.getLogger("voice-agent")
class Assistant(Agent):
def __init__(self) -> None:
super().__init__(
instructions=(
"You are a voice assistant that can trigger Zapier automations via MCP. "
"Keep answers short and clear."
),
stt=inference.STT("deepgram/nova-3"),
llm=inference.LLM("google/gemini-2.5-flash"),
tts=inference.TTS("rime/arcana"),
turn_detection=MultilingualModel(),
)
async def on_enter(self):
self.session.generate_reply(
instructions="Hey, how can I help you today?",
allow_interruptions=True
)
server = AgentServer()
@server.rtc_session()
async def entrypoint(ctx: JobContext):
# Dynamic configuration via environment variable
zapier_url = os.getenv("ZAPIER_MCP_SERVER")
mcp_servers = [mcp.MCPServerHTTP(url=zapier_url)] if zapier_url else []
session = AgentSession(
vad=silero.VAD.load(),
mcp_servers=mcp_servers,
)
await session.start(agent=Assistant(), room=ctx.room)
if __name__ == "__main__":
cli.run_app(server)
Source: examples/voice_agents/zapier_mcp_integration.py in the livekit/agents repository.
Summary
To successfully integrate MCP servers with LiveKit Agents, remember these key points:
- Install the MCP extra: Use
pip install "livekit-agents[mcp]"to get the required client libraries. - Choose your transport: Use
MCPServerHTTPfor remote HTTP/SSE endpoints orMCPServerStdiofor local subprocesses. - Pass to AgentSession: Supply your server instances via the
mcp_serversparameter when constructingAgentSession. - Tool filtering: Use
allowed_toolsto restrict which remote capabilities your agent can access. - Automatic conversion: The framework handles initialization, tool discovery, and conversion to LiveKit function tools automatically.
Frequently Asked Questions
What is the Model Context Protocol (MCP) in LiveKit Agents?
The Model Context Protocol (MCP) is an open standard that allows AI agents to connect to external data sources and tools. In LiveKit Agents, MCP integration enables voice agents to discover and invoke remote tools exposed by MCP servers as if they were native functions, handled through the MCPServer abstraction in livekit/agents/llm/mcp.py.
How do I choose between MCPServerHTTP and MCPServerStdio?
Use MCPServerHTTP when connecting to remote MCP servers accessible via HTTP endpoints, supporting both Server-Sent Events (SSE) and streamable-HTTP transports. Use MCPServerStdio when running a local MCP server binary on the same machine, where the framework spawns the process and communicates over standard input/output. The HTTP variant is preferred for production deployments, while STDIO suits local development.
Can I restrict which tools from an MCP server are available to the agent?
Yes. When constructing an MCPServerHTTP instance, pass the allowed_tools parameter with a list of tool names to expose. For example: MCPServerHTTP(url="https://api.example.com/mcp", allowed_tools=["search", "weather"]). Only the specified tools will be converted to LiveKit function tools and registered with the LLM, providing security and reducing token usage.
What happens if the MCP server returns an error during tool execution?
If an MCP server returns an error during tool invocation, the LiveKit Agents framework raises a ToolError exception. This error propagates through the agent's execution context, allowing you to handle failures gracefully within your agent logic or let the framework manage the error response to the LLM, maintaining robust conversation flow even when external tools fail.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →