Skip to content

fix(tools): add thread-safe lock to MCPManager singleton#845

Open
abdelhadi703 wants to merge 1 commit intoQwenLM:mainfrom
abdelhadi703:fix/threadsafe-mcp-singleton
Open

fix(tools): add thread-safe lock to MCPManager singleton#845
abdelhadi703 wants to merge 1 commit intoQwenLM:mainfrom
abdelhadi703:fix/threadsafe-mcp-singleton

Conversation

@abdelhadi703
Copy link
Copy Markdown

Summary

Add thread-safety to the MCPManager singleton pattern.

Problem: The singleton used __new__ without a mutex lock. In multi-threaded environments, two threads can simultaneously evaluate cls._instance is None before either creates the instance, resulting in two instances being created and breaking the singleton pattern.

Fix: Add threading.Lock() as a class variable and wrap the instance creation in a with cls._lock: block.

Changes

  • qwen_agent/tools/mcp_manager.py:
    • Add _lock = threading.Lock() class variable
    • Wrap singleton creation in with cls._lock:

Security/Reliability

  • Prevents race conditions in multi-threaded environments
  • No new dependencies — threading is part of Python stdlib
  • threading is already imported in the file

Contribution by abdelhadisalmaoui0909@outlook.fr

The MCPManager singleton uses __new__ without a mutex lock.
In a multi-threaded environment, two threads can simultaneously
evaluate 'cls._instance is None' before either creates the
instance, resulting in two instances being created and breaking
the singleton pattern.

Add threading.Lock() to ensure thread-safe singleton creation.

Fixes QwenLM#812
@abdelhadi703 abdelhadi703 force-pushed the fix/threadsafe-mcp-singleton branch from d957c23 to d01ff2a Compare March 25, 2026 13:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant