Skip to content

fix(mcp): prevent MCPClient from hanging on exit#1847

Open
giulio-leone wants to merge 1 commit intostrands-agents:mainfrom
giulio-leone:fix/mcp-client-hang-on-exit-1732
Open

fix(mcp): prevent MCPClient from hanging on exit#1847
giulio-leone wants to merge 1 commit intostrands-agents:mainfrom
giulio-leone:fix/mcp-client-hang-on-exit-1732

Conversation

@giulio-leone
Copy link

Bug

MCPClient.stop() hangs indefinitely when the background thread cannot be stopped, causing scripts to freeze on exit.

Reported in: #1732

Root cause

_background_thread.join() was called without a timeout. When stop() is triggered from Agent.__del__() (garbage collector) or during interpreter shutdown, the event loop may already be closed, so run_coroutine_threadsafe(_set_close_event(), loop) silently fails (raises RuntimeError). The background thread never receives the shutdown signal, and join() blocks forever.

Fix

  1. Add cleanup_timeout parameter (default 5.0 seconds) to MCPClient.__init__()
  2. Use join(timeout=cleanup_timeout) instead of indefinite join()
  3. Catch RuntimeError from run_coroutine_threadsafe when the event loop is already closed
  4. Log a warning when the thread doesn't stop in time, but proceed with cleanup anyway

Testing

  • Added test_stop_does_not_hang_when_background_thread_unresponsive — verifies timeout prevents hang
  • Added test_stop_handles_closed_event_loop — verifies graceful handling of closed event loop
  • Updated existing join() assertions to verify timeout parameter
  • All 54 MCP client tests pass

Fixes #1732

…ad is unresponsive

MCPClient.stop() called _background_thread.join() without a timeout,
causing the process to hang indefinitely when the background thread
could not be signaled (e.g., event loop already closed during
interpreter shutdown or finalizer invocation).

Changes:
- Add cleanup_timeout parameter (default 5.0s) to MCPClient.__init__
- Use timeout in _background_thread.join() to prevent indefinite hangs
- Catch RuntimeError from run_coroutine_threadsafe when the event
  loop is already closed
- Log a warning when the thread does not stop within the timeout

Fixes strands-agents#1732

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] Managed MCPClient integration hangs on exit

1 participant