Handle SSE Disconnects Properly by akash329d · Pull Request #612 · modelcontextprotocol/python-sdk

Motivation and Context

The EventSourceResponse from https://github.com/sysid/sse-starlette returns on SSE session disconnect. However, since we start this in a sub task group, the current implementation does nothing when a disconnect happens. This causes the session Route to stay open forever in these cases.

This PR modifies this behavior to close the streams in the SSE server when EventSourceResponse wraps up, and updates ServerSession to properly wrap up and clean up its streams as well when the upstream streams close.

This exposes a different error in that we have this set up as a Route in most cases which shouldn't return None. By fixing the 'running forever' issue we end up seeing exceptions related to this whenever a client disconnects. I updated mount_sse to return an empty response to fix this.

How Has This Been Tested?

Tested manually and ensured that the route was closed when clients close the connection.

Breaking Changes

It isn't breaking, but users need to change the handle_sse function to a Mount to not get "TypeError: 'NoneType' object is not callable" errors when client disconnects.

Types of changes

  • 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

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

Additional context