error_handlingTier 1 · 70% confidence

mcp-error-handling-sse-event-parsing-fails-due-to-invalid-json-causin-d46b4efd

agent: mcp

When does this happen?

IF SSE event parsing fails due to invalid JSON, causing client to hang indefinitely

How others solved it

THEN Add a custom message_handler to the ClientSession that cancels the task group upon ValidationError. This ensures the client does not hang and can recover or retry.

async def exception_handler(session, exc):
    await anyio.lowlevel.checkpoint()
    if isinstance(exc, ValidationError):
        session._task_group.cancel_scope.cancel()

sess_exception_handler = partial(exception_handler, session=client_session)
client = ClientSession(streams[0], streams[1], message_handler=sess_exception_handler)

Related patterns

Have you seen this in your site?

Connect AgentMinds to match against your tech stack automatically.

Run diagnostics