11import logging
2+ from contextlib import AsyncExitStack
23from datetime import timedelta
34from typing import Any , Callable , Generic , TypeVar
45
@@ -180,13 +181,20 @@ def __init__(
180181 self ._read_timeout_seconds = read_timeout_seconds
181182 self ._in_flight = {}
182183
184+ self ._exit_stack = AsyncExitStack ()
183185 self ._incoming_message_stream_writer , self ._incoming_message_stream_reader = (
184186 anyio .create_memory_object_stream [
185187 RequestResponder [ReceiveRequestT , SendResultT ]
186188 | ReceiveNotificationT
187189 | Exception
188190 ]()
189191 )
192+ self ._exit_stack .push_async_callback (
193+ lambda : self ._incoming_message_stream_reader .aclose ()
194+ )
195+ self ._exit_stack .push_async_callback (
196+ lambda : self ._incoming_message_stream_writer .aclose ()
197+ )
190198
191199 async def __aenter__ (self ) -> Self :
192200 self ._task_group = anyio .create_task_group ()
@@ -195,6 +203,7 @@ async def __aenter__(self) -> Self:
195203 return self
196204
197205 async def __aexit__ (self , exc_type , exc_val , exc_tb ):
206+ await self ._exit_stack .aclose ()
198207 # Using BaseSession as a context manager should not block on exit (this
199208 # would be very surprising behavior), so make sure to cancel the tasks
200209 # in the task group.
@@ -222,6 +231,9 @@ async def send_request(
222231 ](1 )
223232 self ._response_streams [request_id ] = response_stream
224233
234+ self ._exit_stack .push_async_callback (lambda : response_stream .aclose ())
235+ self ._exit_stack .push_async_callback (lambda : response_stream_reader .aclose ())
236+
225237 jsonrpc_request = JSONRPCRequest (
226238 jsonrpc = "2.0" ,
227239 id = request_id ,
@@ -255,9 +267,6 @@ async def send_request(
255267 raise McpError (response_or_error .error )
256268 else :
257269 return result_type .model_validate (response_or_error .result )
258- finally :
259- await response_stream .aclose ()
260- await response_stream_reader .aclose ()
261270
262271 async def send_notification (self , notification : SendNotificationT ) -> None :
263272 """
0 commit comments