Chatbot example: clean up servers in correct order#353
Chatbot example: clean up servers in correct order#353ihrpr merged 1 commit intomodelcontextprotocol:mainfrom
Conversation
|
Can confirm that this fixes the issues like - #252, but this will cleanup the servers sequentially |
490c114 to
04624ea
Compare
04624ea to
031fb82
Compare
There was a problem hiding this comment.
Thank you for your contribution!
Suggestion: APPROVE
Comment: This PR correctly addresses issue #252 by ensuring servers are cleaned up in the reverse order they were initialized, which is a fundamental requirement when working with async context managers. The error occurs because the original code was using asyncio.gather to clean up servers in parallel, potentially violating the LIFO (Last-In-First-Out) principle of async context stack management.
The solution is simple but effective - replacing the parallel cleanup with a sequential cleanup in reverse order using reversed(self.servers). This approach respects the async context lifecycle and prevents the "Attempted to exit cancel scope in a different task than it was entered in" error.
While there is a minor performance trade-off by cleaning up servers sequentially instead of in parallel, correctness must take precedence over performance in this case. The change is minimal, well-tested, and directly addresses the reported issue without introducing new risks.
The servers's async context must be exited in the reverse order it was entered, unrolling the context stack.
Motivation and Context
Fixes #252
How Has This Been Tested?
Breaking Changes
No
Types of changes
Checklist
Additional context