Skip to main content

Model Context Protocol (MCP)

Use MCP servers to expose tools to your agent.

On this page

Overview

LiveKit Agents has first-class support for Model Context Protocol (MCP)  servers.

To use MCP, install the optional dependencies:

uv add livekit-agents[mcp]~=1.8
pnpm add @livekit/agents@^1.9.4 @modelcontextprotocol/client

The @modelcontextprotocol/client package is an optional peer dependency of @livekit/agents and requires Node.js 20 or later.

Wrap an MCP server in an MCPToolset and pass it to the agent's tools parameter:

from livekit.agents import Agent, mcp
class MyAgent(Agent):
def __init__(self):
super().__init__(
instructions="You are a helpful assistant.",
tools=[
mcp.MCPToolset(
id="my-mcp-server",
mcp_server=mcp.MCPServerHTTP("https://your-mcp-server.com/mcp"),
)
],
)
import { llm, voice } from '@livekit/agents';
const agent = voice.Agent.create({
instructions: 'You are a helpful assistant.',
tools: [
new llm.MCPToolset({
id: 'my-mcp-server',
mcpServer: new llm.MCPServerHTTP({ url: 'https://your-mcp-server.com/mcp' }),
}),
],
});
Deprecated parameter

In Python, the mcp_servers parameter on AgentSession and Agent is deprecated. Use MCPToolset in the tools parameter instead. When mcp_servers is used, the SDK auto-generates toolset IDs that aren't stable across sessions, so switching to explicit MCPToolset gives you predictable IDs.

HTTP servers

Use MCPServerHTTP to connect to a remote MCP server over HTTP:

from livekit.agents import AgentSession, mcp
session = AgentSession(
# ... other arguments ...
tools=[
mcp.MCPToolset(
id="my-api",
mcp_server=mcp.MCPServerHTTP(
"https://your-mcp-server.com/tools",
transport_type="streamable_http",
),
)
],
)
import { llm, voice } from '@livekit/agents';
const session = new voice.AgentSession({
// ... other options ...
tools: [
new llm.MCPToolset({
id: 'my-api',
mcpServer: new llm.MCPServerHTTP({
url: 'https://your-mcp-server.com/tools',
transportType: 'streamable_http',
}),
}),
],
});

In Node.js, MCPServerHTTP requires an https: URL and throws an error for any other protocol. To connect to a trusted local development server over plain HTTP, set allowInsecureHttp: true.

Transport auto-detection

The transport type is auto-detected from the URL path. URLs ending in /mcp use streamable HTTP transport, and all other URLs use Server-Sent Events (SSE) transport. To override auto-detection, set transport_type in Python or transportType in Node.js, as shown in the preceding example.

Local servers (stdio)

Use MCPServerStdio to launch a local MCP server process and communicate over stdin/stdout. This is useful for MCP servers distributed as CLI tools:

from livekit.agents import AgentSession, mcp
session = AgentSession(
# ... other arguments ...
tools=[
mcp.MCPToolset(
id="filesystem",
mcp_server=mcp.MCPServerStdio(
command="npx",
args=["-y", "@modelcontextprotocol/server-filesystem", "/path/to/dir"],
),
)
],
)
import { llm, voice } from '@livekit/agents';
const session = new voice.AgentSession({
// ... other options ...
tools: [
new llm.MCPToolset({
id: 'filesystem',
mcpServer: new llm.MCPServerStdio({
command: 'npx',
args: ['-y', '@modelcontextprotocol/server-filesystem', '/path/to/dir'],
}),
}),
],
});

The env and cwd parameters let you customize the child process environment and working directory.

Authentication

Pass authentication headers to an MCP server with the headers parameter:

import os
from livekit.agents import AgentSession, mcp
session = AgentSession(
# ... other arguments ...
tools=[
mcp.MCPToolset(
id="zapier",
mcp_server=mcp.MCPServerHTTP(
"https://actions.zapier.com/mcp/sse",
headers={
"Authorization": f"Bearer {os.environ['ZAPIER_API_KEY']}"
},
),
)
],
)
import { llm, voice } from '@livekit/agents';
const session = new voice.AgentSession({
// ... other options ...
tools: [
new llm.MCPToolset({
id: 'zapier',
mcpServer: new llm.MCPServerHTTP({
url: 'https://actions.zapier.com/mcp/sse',
headers: {
Authorization: `Bearer ${process.env.ZAPIER_API_KEY}`,
},
}),
}),
],
});

Filtering tools

Limit which tools from an MCP server are exposed to the LLM. Use server-level filtering when you know the exact tool names, or toolset-level filtering when you need to inspect tools after they load.

Server-level filtering

Use the allowed_tools parameter in Python or allowedTools in Node.js to filter by tool name. Tools not in the list are excluded.

The following example creates an MCPToolset instance that wraps an MCPServerHTTP instance with an allowed list of search_products and get_product_details. Only those two tools are available, and everything else the server exposes is excluded.

from livekit.agents import AgentSession, mcp
session = AgentSession(
# ... other arguments ...
tools=[
mcp.MCPToolset(
id="products",
mcp_server=mcp.MCPServerHTTP(
"https://your-mcp-server.com/mcp",
allowed_tools=["search_products", "get_product_details"],
),
)
],
)
import { llm, voice } from '@livekit/agents';
const session = new voice.AgentSession({
// ... other options ...
tools: [
new llm.MCPToolset({
id: 'products',
mcpServer: new llm.MCPServerHTTP({
url: 'https://your-mcp-server.com/mcp',
allowedTools: ['search_products', 'get_product_details'],
}),
}),
],
});

Toolset-level filtering

Use filter_tools() in Python or filterTools() in Node.js for more control. The method accepts a filter function and keeps only the tools that match.

In Python, MCPToolset.filter_tools() filters the loaded tools in place, so call it after setup. The following example manually calls setup() to connect and fetch tools, then calls filter_tools() with a lambda that only keeps tools with names that contain search.

from livekit.agents import mcp
toolset = mcp.MCPToolset(
id="my-api",
mcp_server=mcp.MCPServerHTTP("https://your-mcp-server.com/mcp"),
)
# When using outside of AgentSession, call setup() manually
await toolset.setup()
toolset.filter_tools(lambda tool: "search" in tool.id)

The filter doesn't persist. Calling setup(reload=True) fetches the tools again and discards the filtered list, so call filter_tools() again after a reload.

In Node.js, MCPToolset.filterTools() stores the filter function and applies it every time the toolset loads tools, including after a reconnect. You can call it before you pass the toolset to the session, or while the session is running to change which tools are exposed. The following example only keeps tools with names that contain search.

import { llm, voice } from '@livekit/agents';
const toolset = new llm.MCPToolset({
id: 'my-api',
mcpServer: new llm.MCPServerHTTP({ url: 'https://your-mcp-server.com/mcp' }),
});
toolset.filterTools((tool) => tool.name.includes('search'));
const session = new voice.AgentSession({
// ... other options ...
tools: [toolset],
});

To reload the tool list from the server while the session is running, call await toolset.refresh(). The promise resolves after the session applies the updated tools.

Metadata filtering

MCP servers can attach a _meta object to each tool. The SDK keeps this metadata on the tool so a toolset-level filter function can read it. Each server defines its own metadata keys. The following example drops tools that a server marks with an internal key:

toolset.filter_tools(
lambda tool: not tool.info.raw_schema.get("meta", {}).get("internal")
)
toolset.filterTools((tool) => !tool.meta?.internal);

Transforming tool results

Use the tool_result_resolver parameter in Python or toolResultResolver in Node.js to transform MCP tool results before they reach the LLM. The resolver receives an MCPToolResultContext with the tool name, arguments, and result. The resolver can be sync or async.

By default, the SDK serializes content items to JSON. This example truncates large results instead:

import json
from livekit.agents import mcp
MAX_CHARS = 4000
async def truncating_resolver(ctx: mcp.MCPToolResultContext) -> str:
"""Truncate large MCP tool results to avoid excessive LLM context usage."""
if len(ctx.result.content) == 1:
text = str(ctx.result.content[0].model_dump_json(by_alias=True))
elif len(ctx.result.content) > 1:
text = json.dumps(
[item.model_dump(by_alias=True) for item in ctx.result.content],
ensure_ascii=False,
)
else:
return "Tool returned no content."
if len(text) > MAX_CHARS:
text = text[:MAX_CHARS] + "\n... [truncated]"
return text
session = AgentSession(
# ... other arguments ...
tools=[
mcp.MCPToolset(
id="my-api",
mcp_server=mcp.MCPServerHTTP(
"https://your-mcp-server.com/mcp",
tool_result_resolver=truncating_resolver,
),
)
],
)
import { llm, voice } from '@livekit/agents';
const MAX_CHARS = 4000;
// Truncate large MCP tool results to avoid excessive LLM context usage.
const truncatingResolver: llm.MCPToolResultResolver = ({ result }) => {
if (result.content.length === 0) {
return 'Tool returned no content.';
}
const text = JSON.stringify(result.content.length === 1 ? result.content[0] : result.content);
return text.length > MAX_CHARS ? `${text.slice(0, MAX_CHARS)}\n... [truncated]` : text;
};
const session = new voice.AgentSession({
// ... other options ...
tools: [
new llm.MCPToolset({
id: 'my-api',
mcpServer: new llm.MCPServerHTTP({
url: 'https://your-mcp-server.com/mcp',
toolResultResolver: truncatingResolver,
}),
}),
],
});

The resolver is available on all MCP server types and is only called for successful tool calls. Errors raise a ToolError before the resolver runs.

Per-tool options

The MCPToolset class is an async toolset, so you can configure individual MCP tools the same way you configure a function tool. Pass tool_options in Python or toolOptions in Node.js, keyed by tool name, with an MCPToolOptions value for each tool you want to configure. Tools you don't list run as plain blocking calls.

The following example makes a long-running book_flight tool cancellable, requires confirmation before a duplicate call runs, and forwards the server's progress notifications to the user:

from livekit.agents import AgentSession, mcp
from livekit.agents.llm import ToolFlag
session = AgentSession(
# ... other arguments ...
tools=[
mcp.MCPToolset(
id="mcp",
mcp_server=mcp.MCPServerHTTP(
"https://your-mcp-server.com/mcp",
# book_flight runs longer than the default per-request timeout.
client_session_timeout_seconds=120,
),
tool_options={
"book_flight": mcp.MCPToolOptions(
flags=ToolFlag.CANCELLABLE,
on_duplicate="confirm",
report_progress=True,
),
},
)
],
)
import { llm, voice } from '@livekit/agents';
const session = new voice.AgentSession({
// ... other options ...
tools: [
new llm.MCPToolset({
id: 'mcp',
mcpServer: new llm.MCPServerHTTP({
url: 'https://your-mcp-server.com/mcp',
// book_flight runs longer than the default per-request timeout.
clientSessionTimeout: 120_000,
}),
toolOptions: {
book_flight: {
flags: llm.ToolFlag.CANCELLABLE,
onDuplicate: 'confirm',
reportProgress: true,
},
},
}),
],
});

In Node.js, clientSessionTimeout is in milliseconds, defaults to 5000, and must be a whole number.

Both SDKs support the following independent options in MCPToolOptions:

flagsToolFlagDefault: ToolFlag.NONE

Sets flags that change how the tool runs, using the same flags as function tools. Use ToolFlag.CANCELLABLE to let the LLM cancel the tool while it runs, or ToolFlag.IGNORE_ON_ENTER to skip the tool during on_enter in Python or onEnter in Node.js.

When any tool is ToolFlag.CANCELLABLE, the lk_agents_get_running_tasks and lk_agents_cancel_task tools are automatically exposed to the LLM so it can list and cancel running calls. See Cancellation for details.

on_duplicate / onDuplicateDuplicateModeDefault: allow

Controls how duplicate calls to a running tool are handled. Uses the same values as function tools. To learn more, see Duplicate-call handling.

Valid values are allow, reject, replace, or confirm.

report_progress / reportProgressboolDefault: false

Forwards progress notifications from the MCP server to ctx.update() when true. The tool runs in the background so the agent can narrate progress while it works. To learn more, see Progress updates.

For complete examples, see examples/voice_agents/mcp/  in Python, which includes an MCP server that emits progress notifications, and examples/src/mcp_agent.ts  in Node.js.

Multiple servers

Pass multiple MCPToolset instances in the tools list. You can combine different server types, and all servers are initialized in parallel:

from livekit.agents import AgentSession, mcp
session = AgentSession(
# ... other arguments ...
tools=[
mcp.MCPToolset(
id="api-server",
mcp_server=mcp.MCPServerHTTP("https://api.example.com/mcp"),
),
mcp.MCPToolset(
id="filesystem",
mcp_server=mcp.MCPServerStdio(
command="npx",
args=["-y", "@modelcontextprotocol/server-filesystem", "/data"],
),
),
],
)
import { llm, voice } from '@livekit/agents';
const session = new voice.AgentSession({
// ... other options ...
tools: [
new llm.MCPToolset({
id: 'api-server',
mcpServer: new llm.MCPServerHTTP({ url: 'https://api.example.com/mcp' }),
}),
new llm.MCPToolset({
id: 'filesystem',
mcpServer: new llm.MCPServerStdio({
command: 'npx',
args: ['-y', '@modelcontextprotocol/server-filesystem', '/data'],
}),
}),
],
});

If an individual server fails to connect, the error is logged but does not prevent the agent from starting.

Combining MCP tools with function tools

Your agent can use both MCP-provided tools and locally defined function tools. Pass them together in the tools list.

In the following example, the LLM can call both the MCP server's tools and the save_note function tool.

from livekit.agents import Agent, function_tool, RunContext, mcp
class MyAgent(Agent):
def __init__(self):
super().__init__(
instructions="You are a helpful assistant with access to a knowledge base and local tools.",
tools=[
mcp.MCPToolset(
id="knowledge-base",
mcp_server=mcp.MCPServerHTTP("https://your-mcp-server.com/sse"),
)
],
)
@function_tool()
async def save_note(self, context: RunContext, text: str) -> str:
"""Save a note for the user.
Args:
text: The note content to save.
"""
# your custom logic here
return "Note saved successfully."
import { llm, voice } from '@livekit/agents';
import { z } from 'zod';
const saveNote = llm.tool({
name: 'save_note',
description: 'Save a note for the user.',
parameters: z.object({
text: z.string().describe('The note content to save.'),
}),
execute: async ({ text }) => {
// your custom logic here
return 'Note saved successfully.';
},
});
const agent = voice.Agent.create({
instructions: 'You are a helpful assistant with access to a knowledge base and local tools.',
tools: [
new llm.MCPToolset({
id: 'knowledge-base',
mcpServer: new llm.MCPServerHTTP({ url: 'https://your-mcp-server.com/sse' }),
}),
saveNote,
],
});

Agent vs AgentSession placement

You can pass an MCPToolset instance to the tools parameter of either an Agent or the AgentSession. The active agent's tools are added to the AgentSession tools, so the LLM sees both. The toolset lifecycle depends on where you place it. Agent toolsets close when the session switches to a different agent, and session toolsets close when the session ends. For details on toolset lifecycles, see Toolsets.

Prefer session-level toolsets

Set toolsets on the AgentSession when every agent in a workflow needs the same tools. Set toolsets on a specific Agent only for tools that only that agent needs.