Skip to content

Commit 2a02388

Browse files
davidpadburyDavid Padburydbschmigelski
authored
fix(mcp): close mcp client event loop (#1321)
--------- Co-authored-by: David Padbury <padbury@amazon.com> Co-authored-by: Dean Schmigelski <dbschmigelski+github@gmail.com>
1 parent 60bd291 commit 2a02388

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/strands/tools/mcp/mcp_client.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -330,6 +330,9 @@ async def _set_close_event() -> None:
330330
self._log_debug_with_thread("waiting for background thread to join")
331331
self._background_thread.join()
332332

333+
if self._background_thread_event_loop is not None:
334+
self._background_thread_event_loop.close()
335+
333336
self._log_debug_with_thread("background thread is closed, MCPClient context exited")
334337

335338
# Reset fields to allow instance reuse

tests/strands/tools/mcp/test_mcp_client.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -524,6 +524,33 @@ def test_stop_with_background_thread_but_no_event_loop():
524524
assert client._background_thread is None
525525

526526

527+
def test_stop_closes_event_loop():
528+
"""Test that stop() properly closes the event loop when it exists."""
529+
client = MCPClient(MagicMock())
530+
531+
# Mock a background thread with event loop
532+
mock_thread = MagicMock()
533+
mock_thread.join = MagicMock()
534+
mock_event_loop = MagicMock()
535+
mock_event_loop.close = MagicMock()
536+
537+
client._background_thread = mock_thread
538+
client._background_thread_event_loop = mock_event_loop
539+
540+
# Should close the event loop and join the thread
541+
client.stop(None, None, None)
542+
543+
# Verify thread was joined
544+
mock_thread.join.assert_called_once()
545+
546+
# Verify event loop was closed
547+
mock_event_loop.close.assert_called_once()
548+
549+
# Verify cleanup occurred
550+
assert client._background_thread is None
551+
assert client._background_thread_event_loop is None
552+
553+
527554
def test_mcp_client_state_reset_after_timeout():
528555
"""Test that all client state is properly reset after timeout."""
529556

0 commit comments

Comments
 (0)