i want mcp_servers + function tool in livekit agen...
# ask-ai
a
i want mcp_servers + function tool in livekit agent
t
Thanks for reaching out, Parth. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — you're asking to use both
mcp_servers
and a
function_tool
in a LiveKit agent. I can help set that up. Quick clarification so I give the right instructions: • Are you using Python or Node.js for your agent? • Do you want MCP to load external tools from a remote MCP server, or do you also want to register local function tools in the agent (or both)? If Python, I can show the exact
AgentSession
+
mcp_servers
snippet plus a
@function_tool
example. If Node.js, I can show how to add an MCP server and register an
llm.tool()
in your agent constructor. Which environment do you want me to show? Sources: Tool definition and use | LiveKit docs
a
yes python code
t
Great — below is a concise Python example showing how to use
mcp_servers
with
AgentSession
and define a local tool using
@function_tool
so both external MCP tools and your own function tools are available to the agent.
Copy code
from typing import Any
import asyncio

from livekit.agents import mcp, Agent, AgentSession, function_tool, RunContext

# Example function tool (local)
class MyAgent(Agent):
    @function_tool()
    async def get_weather(self, context: RunContext, location: str) -> dict[str, Any]:
        """Return weather for a location (example)."""
        # Replace with real API calls if desired
        return {"location": location, "weather": "sunny", "temperature_f": 70}


async def main():
    # Create AgentSession and point to one or more MCP servers
    session = AgentSession(
        # your usual session args (api_key, model, etc.) as needed
        mcp_servers=[
            mcp.MCPServerHTTP("https://your-mcp-server.com"),  # MCP server URL
            # you can add more MCP servers if needed:
            # mcp.MCPServerHTTP("https://another-mcp.example")
        ],
    )

    # Instantiate your agent and register local tools via the class definition above
    agent = MyAgent(session=session)

    # Example: run the agent with an input prompt that may use both MCP and function tools
    result = await agent.run("What is the weather in Seattle and list any MCP tools available?")
    print(result)

if __name__ == "__main__":
    asyncio.run(main())
Notes: • Install MCP support with:
uv add livekit-agents[mcp]~=1.2
. • MCP tools from the configured
mcp_servers
are loaded automatically into the agent. • Local tools declared with
@function_tool()
(like
get_weather
) are available to the model alongside MCP-provided tools. • Replace session args and URLs with your real configuration. Would you like a variant that calls an external weather API inside the function tool or an example showing how to inspect the loaded MCP tools programmatically?
a
yes please and end call as tool
t
Below is a concise Python example that: • Loads MCP tools via
mcp_servers
. • Defines a custom
@function_tool
that calls an external weather API, generates a spoken reply, waits for playout, and ends the call by deleting the room. Replace placeholders (API keys, MCP URL) with your values.
Copy code
import asyncio
from typing import Any
import aiohttp

from livekit.agents import (
    Agent,
    AgentSession,
    function_tool,
    RunContext,
    get_job_context,
    mcp,
)

class WeatherAgent(Agent):
    @function_tool()
    async def get_weather_and_end_call(self, context: RunContext, location: str) -> dict[str, Any]:
        """Fetch weather, speak the result, wait for playout, then end the call."""
        # Fetch weather from an external API
        weather_info = f"Could not retrieve weather for {location}."
        async with aiohttp.ClientSession() as http:
            async with http.get(f"https://wttr.in/{location}?format=3") as resp:
                if resp.status == 200:
                    text = await resp.text()
                    weather_info = f"Weather for {location}: {text}"

        # Send reply (agent TTS/speech) so user hears result
        await context.session.generate_reply(instructions=weather_info)

        # Wait for any speech playback to finish to avoid abrupt cut-off
        await context.session.wait_for_playout()

        # End the call by deleting the room via job context API
        job_ctx = get_job_context()
        if job_ctx:
            await job_ctx.api.room.delete_room(
                job_ctx.api.room.DeleteRoomRequest(room=job_ctx.room.name)
            )

        return {"location": location, "result": weather_info}

async def main():
    session = AgentSession(
        # fill required session args (e.g., api_key, model) as needed
        mcp_servers=[
            mcp.MCPServerHTTP("https://your-mcp-server.com"),
        ],
    )

    agent = WeatherAgent(session=session)

    # Example run: LLM may choose to call the tool
    res = await agent.run("Please get the weather for Seattle and then end the call.")
    print(res)

if __name__ == "__main__":
    asyncio.run(main())
Would you like this example adapted to use a different weather API (JSON response parsing) or to log/inspect loaded MCP tools programmatically? Sources: Tool definition and use | LiveKit docs | Agents telephony integration | LiveKit docs
a
add call transfer function but it depend on active that function or not
t
I'll provide a concise Python example that adds a conditional call transfer tool to your existing agent (with MCP and your weather+end-call tool). The transfer tool only executes when an
transfer_active
flag is true; you can enable/disable it via tools callable by the LLM or external controls.
Copy code
import asyncio
from typing import Any
import aiohttp

from livekit.agents import (
    Agent,
    AgentSession,
    function_tool,
    RunContext,
    get_job_context,
    mcp,
)

class MyAgent(Agent):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.transfer_active = False  # control flag

    @function_tool()
    async def get_weather_and_end_call(self, context: RunContext, location: str) -> dict[str, Any]:
        # fetch simple weather text
        weather_info = f"Could not retrieve weather for {location}."
        async with aiohttp.ClientSession() as http:
            async with http.get(f"https://wttr.in/{location}?format=3") as resp:
                if resp.status == 200:
                    text = await resp.text()
                    weather_info = f"Weather for {location}: {text}"

        await context.session.generate_reply(instructions=weather_info)
        await context.session.wait_for_playout()

        job_ctx = get_job_context()
        if job_ctx:
            await job_ctx.api.room.delete_room(job_ctx.api.room.DeleteRoomRequest(room=job_ctx.room.name))

        return {"location": location, "result": weather_info}

    @function_tool()
    async def transfer_call(self, context: RunContext, phone_number: str) -> str:
        """Transfer the active call to phone_number only if transfer_active is True."""
        if not self.transfer_active:
            return "Call transfer is currently disabled."

        job_ctx = get_job_context()
        if not job_ctx:
            return "No job context; cannot perform transfer."

        try:
            room = job_ctx.room
            participant_identity = room.local_participant.identity

            await job_ctx.api.sip.transfer_sip_participant(
                job_ctx.api.sip.TransferSIPParticipantRequest(
                    room_name=room.name,
                    participant_identity=participant_identity,
                    transfer_to=f"tel:{phone_number}",
                    play_dialtone=True,
                )
            )
            return f"Call transferred successfully to {phone_number}."
        except Exception as e:
            return f"Failed to transfer call: {e}"

    @function_tool()
    async def activate_transfer_function(self, context: RunContext) -> str:
        self.transfer_active = True
        return "Call transfer function enabled."

    @function_tool()
    async def deactivate_transfer_function(self, context: RunContext) -> str:
        self.transfer_active = False
        return "Call transfer function disabled."

async def main():
    session = AgentSession(
        # add required session args (api_key, model, etc.)
        mcp_servers=[mcp.MCPServerHTTP("https://your-mcp-server.com")],
    )

    agent = MyAgent(session=session)

    # Example run where LLM may call activate, transfer, etc.
    res = await agent.run("Enable transfer, then transfer the call to +15551234567.")
    print(res)

if __name__ == "__main__":
    asyncio.run(main())
Would you like: • the transfer to auto-deactivate after one use, • the activation to require an auth token or PIN, • or a version that logs/inspects loaded MCP tools before allowing transfer? Sources: Agents telephony integration | LiveKit docs | Preserving Caller ID During SIP Transfers in LiveKit Agents | Tool definition and use | LiveKit docs | Agents and handoffs | LiveKit docs