m
hi
t
Thanks for reaching out, Rahib. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'd love to help you out! Could you please share a bit more about your question or the issue you're experiencing? That way, I can make sure to assist you in the best possible way.
m
Is this the correct way to extract caller id in agent # Extract caller_id from SIP participant attributes (if available) # This will be used in Phase 3 for background phone lookup try: # Get the first remote participant (should be the caller) if self.session.room and self.session.room.remote_participants: for participant in self.session.room.remote_participants.values(): if ( participant.kind == self.session.room.ParticipantKind.PARTICIPANT_KIND_SIP ): phone_number = participant.attributes.get( "sip.phoneNumber", None ) if phone_number: state.caller_id = phone_number logger.info(f"Extracted caller_id: {phone_number}") break except Exception as e: logger.warning(f"Failed to extract caller_id: {e}") on_enter?
t
It looks like your code snippet for extracting the caller ID from SIP participant attributes is heading in the right direction! Let me share a few important points to help make sure everything works smoothly: • First, double-check that the participant is indeed a SIP participant by verifying
participant.kind == self.session.room.ParticipantKind.PARTICIPANT_KIND_SIP
. • Then, you can get the caller's number using
participant.attributes.get('sip.phoneNumber')
. This should give you the phone number for inbound calls or the dialed number for outbound calls. • Also, take a moment to confirm that the
HidePhoneNumber
setting in your dispatch rule configuration isn’t set to
true
, as that would hide the phone number from being accessible. If you run into any specific challenges or see any errors with your code, please don’t hesitate to share them. I’m here to help you work through it! Sources: Docs::Telephony | Preserving Caller ID During SIP Transfers in LiveKit Agents
m
can you give me the better version as per your suggestion ?
t
Here is a friendly update to your code snippet for extracting the caller ID from SIP participant attributes:
Copy code
# Extract caller_id from SIP participant attributes (if available)
# This will be used in Phase 3 for background phone lookup
try:
    # Let's make sure the room and remote participants are there
    if self.session.room and self.session.room.remote_participants:
        for participant in self.session.room.remote_participants.values():
            # We're looking for a SIP participant here
            if participant.kind == self.session.room.ParticipantKind.PARTICIPANT_KIND_SIP:
                # Grab the phone number from participant attributes
                phone_number = participant.attributes.get("sip.phoneNumber")
                if phone_number:
                    state.caller_id = phone_number
                    logger.info(f"Extracted caller_id: {phone_number}")
                else:
                    logger.info("Caller ID not available (it might be hidden)")
                break
except Exception as e:
    logger.warning(f"Oops! Failed to extract caller_id: {e}")
Some thoughtful improvements here: • Added a gentle log message for when the phone number isn't available. • Handled cases where the caller ID might be hidden due to settings. • Kept everything clear and focused on the SIP participant and attribute retrieval. If you have any questions or want me to help tweak this further, just let me know! I'm here to help.
m
Can i not override the on_user_turn_completed ? This is what i am doing in Agent
Copy code
async def on_user_turn_completed(self) -> None:
        """Called after each user turn is completed.

        Checks state and determines if phase transitions are needed.
        Provides thinking feedback during background operations.
        """
        state = self.get_state()
        logger.info(f"User turn completed in phase: {state.current_phase}")

        # Phase 3: Check if background phone lookup is complete
        if state.phone_lookup_task and not state.phone_lookup_complete:
            if state.phone_lookup_task.done():
                state.phone_lookup_complete = True
                logger.info("Background phone lookup completed")
                # TODO: Phase 3 - Process lookup results and transition phase

        # Log state summary for debugging
        logger.debug(f"State summary: {state.current_phase}")
        logger.debug(f"  - caller_id: {state.caller_id}")
        logger.debug(f"  - phone_lookup_complete: {state.phone_lookup_complete}")
        logger.debug(f"  - client_match: {bool(state.client_match)}")
        logger.debug(f"  - client_validated: {state.client_validated}")
Getting this error:
Copy code
Signature of "on_user_turn_completed" incompatible with supertype "Agent"Mypyoverride
     Superclass:
         def on_user_turn_completed(self, turn_ctx: ChatContext, new_message: ChatMessage) -> Coroutine[Any, Any, None]
     Subclass:
         def on_user_turn_completed(self) -> Coroutine[Any, Any, None]Mypy
(method) async def on_user_turn_completed(self: Self@CloudMetricsAgent) -> None
t
It looks like the error is happening because the overridden
on_user_turn_completed
method in your subclass doesn't quite match the signature expected by the base
Agent
class. To fix this, you'll want to make sure your method includes the necessary parameters:
turn_ctx
of type
ChatContext
and
new_message
of type
ChatMessage
. Here's a corrected version of your method that should work smoothly:
Copy code
async def on_user_turn_completed(self, turn_ctx: ChatContext, new_message: ChatMessage) -> None:
    """Called after each user turn is completed.

    Checks state and determines if phase transitions are needed.
    Provides thinking feedback during background operations.
    """
    state = self.get_state()
    logger.info(f"User turn completed in phase: {state.current_phase}")

    # Phase 3: Check if background phone lookup is complete
    if state.phone_lookup_task and not state.phone_lookup_complete:
        if state.phone_lookup_task.done():
            state.phone_lookup_complete = True
            logger.info("Background phone lookup completed")
            # TODO: Phase 3 - Process lookup results and transition phase

    # Log state summary for debugging
    logger.debug(f"State summary: {state.current_phase}")
    logger.debug(f"  - caller_id: {state.caller_id}")
    logger.debug(f"  - phone_lookup_complete: {state.phone_lookup_complete}")
    logger.debug(f"  - client_match: {bool(state.client_match)}")
    logger.debug(f"  - client_validated: {state.client_validated}")
By adding these required parameters, your method will align perfectly with the base class and should prevent that signature mismatch error. If you have any questions or want to go over this together, just let me know—I'm here to help! Sources: home_assistant/homeautomation.py | tests/test_agent_session.py | Pipeline nodes and hooks | LiveKit Docs | agents/src/voice/agent_activity.ts | Docs::Agents
m
hi
t
I'd love to help you out! Could you please share a bit more about your question or the issue you're experiencing? That way, I can make sure to assist you in the best possible way.
m
Questions about LiveKit MCP Types: 1. How to access MCP servers from RunContext? async def get_notion_mcp_server(ctx: RunContext) -> ???: # Is it: ctx.agent.session.mcp_servers? # Or: ctx.session.mcp_servers? # What's the correct access pattern? 2. What's the type of MCP server? from livekit.agents.llm import mcp # Is this correct? # Is it: mcp.MCPServer? # Or: mcp.MCPServerHTTP? # What should I import for type hints? 3. How to call MCP tools from the server? mcp_server = await get_notion_mcp_server(ctx) # How do I call a tool? Is it: # result = await mcp_server.call_tool("API-post-database-query", {...}) # Or something else? # What's the return type? Could you point me to the LiveKit docs or show me an example?
t
Thank you for your questions about LiveKit MCP types and usage! Let me walk you through the answers to help you get started smoothly: 1. Accessing MCP Servers from `RunContext`: You can easily connect to MCP servers using the
mcp.MCPServerHTTP
class by providing the server URL. Here’s a simple example: `from livekit.agents import mcp mcp_server = mcp.MCPServerHTTP(url="https://your-mcp-server.com/mcp")`Feel free to try this out and see how it works for you! 2. Type of MCP Server: The appropriate type to use is
mcp.MCPServerHTTP
. This class manages the connection to your MCP server and smartly decides the transport type (either SSE or streamable HTTP) based on the URL path. 3. Calling MCP Tools: When you want to call a tool, just use the
call_tool
method on your MCP server instance. For example: `result = await mcp_server.call_tool("API-post-database-query", {"key": "value"})`The specific return type will depend on how the tool is set up, but this should get you going! If you’d like to dive deeper, the MCP Agent GitHub repository is a wonderful resource. And please, don’t hesitate to reach out if you have any more questions or need some extra examples—I’m here to help! Sources: Tool definition and use | LiveKit Docs | examples/voice_agents/mcp/server.py | mcp/server.py | Docs::Agents
m
Is it possible to call mcp tools within custom tools ?
t
I understand that you're looking to call MCP tools directly from within custom tool implementations in LiveKit. Currently, MCP tools and custom tools are handled as separate entities, each registered with the agent so the LLM can invoke them independently based on the conversation context. The system doesn’t support programmatically calling an MCP tool from within a custom tool's code. Instead, both tool types are made available to the LLM, which then decides when to use each one. If you have a particular use case or goal in mind, please feel free to share it with me. I’d be happy to work with you to explore some alternative solutions that might fit your needs. Sources: README.md | mcp_client/server.py | Tool definition and use | LiveKit Docs