Skip to content

MCP error handling uses str() instead of extracting .text from content items #4503

@muhammadkhalid-03

Description

@muhammadkhalid-03

Bug Description

When an MCP tool returns an error (isError: true), the error content is incorrectly serialized using Python's str() function instead of extracting the .text attribute from content items where the .text is part of the return value from my MCP tool definition.

Expected Behavior

The error message text should be extracted properly:
<Error message>

Reproduction Steps

1. Create an MCP server with a tool that returns an error:

  return {
    isError: true,
    content: [
      {
        type: 'text',
        text: 'error message',
      },
    ],
  };
2.Invoke the tool that returns the error
3.Catch the ToolError and inspect the message which gives the output: `type='text' text='This is the error message' annotations=None meta=None`
...
- Sample code snippet, or a GitHub Gist link -

Operating System

macOS Sequoia 15.6.1

Models Used

OpenAI GPT

Package Versions

livekit-agents~=1.3.6

Session/Room/Call IDs

No response

Proposed Solution

In agents/llm/mcp.py:

if tool_result.isError:
    error_str = "\n".join(
        part.text if hasattr(part, 'text') else str(part)
        for part in tool_result.content
    )
    raise ToolError(error_str)

Additional Context

I added a print statement to show the result from unpacking the tool call from Livekit's FunctionToolsExecutedEvent

    async def on_function_tools_executed(
        self, event: FunctionToolsExecutedEvent
    ) -> None:
        """
        Called after any tool is executed
        """
        for call, result in event.zipped():
        ...
        print(result)

I got the following output (Note that the output field contains the result of python's repr method which means I can't parse the output without using regex):

    output='{"type":"text","text":"Error: Cast to date failed for value \\"Hello\\" (type string) at path \\"scheduledFor\\"","annotations":null,"meta":null}'
    is_error=False created_at=1768202534.7133088

Screenshots and Recordings

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions