🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
feat: add argument for using Dict as config in MCP toolkit (#2218)
Xiaotian Jin6c831bd040b2
diff --git a/camel/toolkits/mcp_toolkit.py b/camel/toolkits/mcp_toolkit.pyindex f8c37a3e7..856cbb434 100644--- a/camel/toolkits/mcp_toolkit.py+++ b/camel/toolkits/mcp_toolkit.py@@ -399,17 +399,20 @@ class MCPToolkit(BaseToolkit):Args:servers (Optional[List[MCPClient]]): List of MCPClient- instances to manage.+ instances to manage. (default: :obj:`None`)config_path (Optional[str]): Path to a JSON configuration file- defining MCP servers.+ defining MCP servers. (default: :obj:`None`)+ config_dict (Optional[Dict[str, Any]]): Dictionary containing MCP+ server configurations in the same format as the config file.+ (default: :obj:`None`)strict (Optional[bool]): Whether to enforce strict mode for thefunction call. (default: :obj:`False`)Note:- Either `servers` or `config_path` must be provided. If both are- provided, servers from both sources will be combined.+ Either `servers`, `config_path`, or `config_dict` must be provided.+ If multiple are provided, servers from all sources will be combined.- For web servers in the config file, you can specify authorization+ For web servers in the config, you can specify authorizationheaders using the "headers" field to connect to protected MCP serverendpoints.@@ -438,14 +441,19 @@ class MCPToolkit(BaseToolkit):self,servers: Optional[List[MCPClient]] = None,config_path: Optional[str] = None,+ config_dict: Optional[Dict[str, Any]] = None,strict: Optional[bool] = False,):super().__init__()- if servers and config_path:+ sources_provided = sum(+ 1 for src in [servers, config_path, config_dict] if src is not None+ )+ if sources_provided > 1:logger.warning(- "Both servers and config_path are provided. "- "Servers from both sources will be combined."+ "Multiple configuration sources provided "+ f"({sources_provided}). Servers from all sources "+ "will be combined.")self.servers: List[MCPClient] = servers or []@@ -455,6 +463,9 @@ class MCPToolkit(BaseToolkit):self._load_servers_from_config(config_path, strict))+ if config_dict:+ self.servers.extend(self._load_servers_from_dict(config_dict))+self._exit_stack = AsyncExitStack()self._connected = False@@ -484,9 +495,25 @@ class MCPToolkit(BaseToolkit):logger.warning(f"Config file not found: '{config_path}'")raise e+ return self._load_servers_from_dict(config=data, strict=strict)++ def _load_servers_from_dict(+ self, config: Dict[str, Any], strict: Optional[bool] = False+ ) -> List[MCPClient]:+ r"""Loads MCP server configurations from a dictionary.++ Args:+ config (Dict[str, Any]): Dictionary containing server+ configurations.+ strict (bool): Whether to enforce strict mode for the+ function call. (default: :obj:`False`)++ Returns:+ List[MCPClient]: List of configured MCPClient instances.+ """all_servers = []- mcp_servers = data.get("mcpServers", {})+ mcp_servers = config.get("mcpServers", {})if not isinstance(mcp_servers, dict):logger.warning("'mcpServers' is not a dictionary, skipping...")mcp_servers = {}@@ -505,11 +532,16 @@ class MCPToolkit(BaseToolkit):)continue+ # Include headers if provided in the configuration+ headers = cfg.get("headers", {})++ cmd_or_url = cast(str, cfg.get("command") or cfg.get("url"))server = MCPClient(- command_or_url=cast(str, cfg.get("command") or cfg.get("url")),+ command_or_url=cmd_or_url,args=cfg.get("args", []),env={**os.environ, **cfg.get("env", {})},timeout=cfg.get("timeout", None),+ headers=headers,strict=strict,)all_servers.append(server)diff --git a/examples/toolkits/mcp/mcp_toolkit.py b/examples/toolkits/mcp/mcp_toolkit.pyindex bd0f5203d..fd2f15b54 100644--- a/examples/toolkits/mcp/mcp_toolkit.py+++ b/examples/toolkits/mcp/mcp_toolkit.py@@ -40,8 +40,25 @@ from camel.types import ModelPlatformType, ModelTypeasync def main():+ # Use either config path or config dict to initialize the MCP toolkit.+ # 1. Use config path:config_path = Path(__file__).parent / "mcp_servers_config.json"mcp_toolkit = MCPToolkit(config_path=str(config_path))+ # 2. Use config dict:+ # config_dict = {+ # "mcpServers": {+ # "filesystem": {+ # "command": "npx",+ # "args": [+ # "-y",+ # "@modelcontextprotocol/[email protected]",+ # "."+ # ]+ # }+ # },+ # "mcpWebServers": {}+ # }+ # mcp_toolkit = MCPToolkit(config_dict=config_dict)# Connect to all MCP servers.await mcp_toolkit.connect()