python-sdk icon indicating copy to clipboard operation
python-sdk copied to clipboard

Improve error handling during request validation in BaseSession

Open painkiller90 opened this issue 8 months ago • 0 comments

Added a try block around the handling of JSONRPCRequest messages in the _receive_loop method, mirroring the error handling already present for JSONRPCNotification. This ensures that validation or processing errors for requests are caught and logged, preventing the receive loop from crashing and improving robustness.

Motivation and Context

Previously, only notification handling was wrapped in a try block to catch and log validation or processing errors. However, requests can also fail validation or processing, which would cause the receive loop to crash or propagate exceptions. Wrapping the request handling in a try block ensures that such errors are logged and do not interrupt the session's message processing loop.

Also trying to interact with MCPs like Twilio MCP it crashes when other clients works perfectly.

How Has This Been Tested?

I manually tested it with the next MCP's:

import pprint
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

# This MCP works
mcp1_args = ["-y", "@modelcontextprotocol/server-filesystem", ".", "."]

# This doesn't work
mcp2_args = [
    "-y",
    "@twilio-alpha/mcp",
    "YOUR_ACCOUNT_SID/YOUR_API_KEY:YOUR_API_SECRET",
]

server_params = StdioServerParameters(command="npx", args=mcp2_args, env=None)


async def run():
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()

            tools = await session.list_tools()
            pprint.pprint(tools)


if __name__ == "__main__":
    import asyncio

    asyncio.run(run())

After the changes both MCPs works with no problem.

Breaking Changes

No breaking changes.

Types of changes

  • [x] Bug fix (non-breaking change which fixes an issue)
  • [ ] New feature (non-breaking change which adds functionality)
  • [ ] Breaking change (fix or feature that would cause existing functionality to change)
  • [ ] Documentation update

Checklist

  • [x] I have read the MCP Documentation
  • [x] My code follows the repository's style guidelines
  • [x] New and existing tests pass locally
  • [x] I have added appropriate error handling
  • [ ] I have added or updated documentation as needed

Additional context

painkiller90 avatar May 21 '25 17:05 painkiller90