Skip to content

Commit d01ff2a

Browse files
committed
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 #812
1 parent 31a4d36 commit d01ff2a

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

qwen_agent/tools/mcp_manager.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,12 @@
3030

3131
class MCPManager:
3232
_instance = None # Private class variable to store the unique instance
33+
_lock = threading.Lock() # Lock to ensure thread-safe singleton creation
3334

3435
def __new__(cls, *args, **kwargs):
35-
if cls._instance is None:
36-
cls._instance = super(MCPManager, cls).__new__(cls, *args, **kwargs)
36+
with cls._lock:
37+
if cls._instance is None:
38+
cls._instance = super(MCPManager, cls).__new__(cls, *args, **kwargs)
3739
return cls._instance
3840

3941
def __init__(self):

0 commit comments

Comments
 (0)