From d01ff2af750bf74c5c08b44a4f4764429534b5d4 Mon Sep 17 00:00:00 2001 From: Abdelhadi Salmaoui Date: Wed, 25 Mar 2026 05:13:10 +0100 Subject: [PATCH] fix(tools): add thread-safe lock to MCPManager singleton 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/Qwen-Agent#812 --- qwen_agent/tools/mcp_manager.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/qwen_agent/tools/mcp_manager.py b/qwen_agent/tools/mcp_manager.py index 9920978f..fcd0cf6c 100644 --- a/qwen_agent/tools/mcp_manager.py +++ b/qwen_agent/tools/mcp_manager.py @@ -30,10 +30,12 @@ class MCPManager: _instance = None # Private class variable to store the unique instance + _lock = threading.Lock() # Lock to ensure thread-safe singleton creation def __new__(cls, *args, **kwargs): - if cls._instance is None: - cls._instance = super(MCPManager, cls).__new__(cls, *args, **kwargs) + with cls._lock: + if cls._instance is None: + cls._instance = super(MCPManager, cls).__new__(cls, *args, **kwargs) return cls._instance def __init__(self):