Skip to content

Thread unsafe singleton pattern in MCPManager #812

@kbhujbal

Description

@kbhujbal

Description

The MCPManager class in qwen_agent/tools/mcp_manager.py uses a singleton pattern that is not thread-safe:

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

In a multi-threaded environment (e.g., when serving multiple users via Gradio WebUI or any ASGI server), two threads can both evaluate cls._instance is None as True simultaneously, resulting in two separate instances being created. This breaks the singleton guarantee and can lead to duplicated MCP server connections, inconsistent state, or resource leaks.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions