Skip to content

fix: Add thread-safe singleton pattern for MCPManager#819

Open
Jah-yee wants to merge 1 commit intoQwenLM:mainfrom
Jah-yee:fix/mcp-manager-thread-safety
Open

fix: Add thread-safe singleton pattern for MCPManager#819
Jah-yee wants to merge 1 commit intoQwenLM:mainfrom
Jah-yee:fix/mcp-manager-thread-safety

Conversation

@Jah-yee
Copy link
Copy Markdown

@Jah-yee Jah-yee commented Mar 10, 2026

Description

The MCPManager class in qwen_agent/tools/mcp_manager.py uses a singleton pattern that is not thread-safe. In a multi-threaded environment (e.g., Gradio WebUI or ASGI server), two threads can both evaluate cls._instance is None as True simultaneously, resulting in duplicate MCP server connections and inconsistent state.

Fix

This PR adds a threading.Lock to ensure only one instance is created even when multiple threads access __new__ concurrently.

class MCPManager:
    _instance = None
    _lock = threading.Lock()  # Lock for thread-safe singleton pattern

    def __new__(cls, *args, **kwargs):
        with cls._lock:
            if cls._instance is None:
                cls._instance = super(MCPManager, cls).__new__(cls, *args, **kwargs)
        return cls._instance

Related Issue

Fixes #812

The MCPManager class used a singleton pattern that was not thread-safe.
In a multi-threaded environment (e.g., Gradio WebUI or ASGI server),
two threads could both evaluate cls._instance is None as True simultaneously,
resulting in duplicate MCP server connections and inconsistent state.

This fix adds a threading.Lock to ensure only one instance is created
even when multiple threads access __new__ concurrently.
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.

Thread unsafe singleton pattern in MCPManager

1 participant