fix: Handle SSE Disconnects Properly When use starlette middleware

Draft
WE
6mo ago
+26-20

Motivation and Context

When using the Starlette middleware capabilities, if the SSE client disconnects, the current server will return starlette.responses.Response, and the Response will send a message of type "http.response.start", which will cause the following error:

File "/opt/anaconda3/lib/python3.12/contextlib.py", line 158, in __exit__
    self.gen.throw(value)
  File "/Users/wangwenxue/code/gitlab/sofapyapp/myenv/lib/python3.12/site-packages/starlette/_utils.py", line 83, in collapse_excgroups
    raise exc
  File "/Users/wangwenxue/code/gitlab/sofapyapp/myenv/lib/python3.12/site-packages/starlette/middleware/base.py", line 185, in __call__
    await response(scope, wrapped_receive, send)
  File "/Users/wangwenxue/code/gitlab/sofapyapp/myenv/lib/python3.12/site-packages/starlette/middleware/base.py", line 223, in __call__
    async for chunk in self.body_iterator:
  File "/Users/wangwenxue/code/gitlab/sofapyapp/myenv/lib/python3.12/site-packages/starlette/middleware/base.py", line 169, in body_stream
    assert message["type"] == "http.response.body", f"Unexpected message: {message}"
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: Unexpected message: {'type': 'http.response.start', 'status': 200, 'headers': [(b'content-length', b'0')]}

There are several issues that should be related to this PR, such as:

https://github.com/modelcontextprotocol/python-sdk/issues/883
https://github.com/jlowin/fastmcp/issues/858

How Has This Been Tested?

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

Breaking Changes

No

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