Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

feat: add MCP search agent (#2222)

Xiaotian Jin6e3486bda685
diff --git a/camel/agents/chat_agent.py b/camel/agents/chat_agent.py
index fe9caa48c..13211b830 100644
--- a/camel/agents/chat_agent.py
+++ b/camel/agents/chat_agent.py
@@ -442,6 +442,11 @@ class ChatAgent(BaseAgent):
new_tool = convert_to_function_tool(tool)
self._internal_tools[new_tool.get_function_name()] = new_tool
+ def add_tools(self, tools: List[Union[FunctionTool, Callable]]) -> None:
+ r"""Add a list of tools to the agent."""
+ for tool in tools:
+ self.add_tool(tool)
+
def add_external_tool(
self, tool: Union[FunctionTool, Callable, Dict[str, Any]]
) -> None:
@@ -462,6 +467,11 @@ class ChatAgent(BaseAgent):
return True
return False
+ def remove_tools(self, tool_names: List[str]) -> None:
+ r"""Remove a list of tools from the agent by name."""
+ for tool_name in tool_names:
+ self.remove_tool(tool_name)
+
def remove_external_tool(self, tool_name: str) -> bool:
r"""Remove an external tool from the agent by name.
diff --git a/camel/agents/mcp_agent.py b/camel/agents/mcp_agent.py
index 427c77256..49bf803c6 100644
--- a/camel/agents/mcp_agent.py
+++ b/camel/agents/mcp_agent.py
@@ -12,18 +12,26 @@
# limitations under the License.
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+import asyncio
import json
+import platform
import re
-from typing import Optional
+from typing import Any, Callable, Dict, List, Optional, Union, cast
from camel.agents import ChatAgent
from camel.logger import get_logger
from camel.messages import BaseMessage
-from camel.models import BaseModelBackend
+from camel.models import BaseModelBackend, ModelFactory
from camel.prompts import TextPrompt
from camel.responses import ChatAgentResponse
-from camel.toolkits import MCPToolkit
-from camel.types import RoleType
+from camel.toolkits import FunctionTool, MCPToolkit
+from camel.types import (
+ BaseMCPRegistryConfig,
+ MCPRegistryType,
+ ModelPlatformType,
+ ModelType,
+ RoleType,
+)
# AgentOps decorator setting
try:
@@ -38,6 +46,7 @@ except (ImportError, AttributeError):
logger = get_logger(__name__)
+
SYS_MSG_CONTENT = """
You are a helpful assistant, and you prefer to use tools provided by the user
to solve problems.
@@ -80,22 +89,62 @@ Please answer me according to the result directly.
@track_agent(name="MCPAgent")
class MCPAgent(ChatAgent):
+ r"""A specialized agent designed to interact with MCP registries.
+ The MCPAgent enhances a base ChatAgent by integrating MCP tools from
+ various registries for search capabilities.
+
+ Attributes:
+ system_message (Optional[str]): The system message for the chat agent.
+ (default: :str:`"You are an assistant with search capabilities
+ using MCP tools."`)
+ model (BaseModelBackend): The model backend to use for generating
+ responses. (default: :obj:`ModelPlatformType.DEFAULT` with
+ `ModelType.DEFAULT`)
+ registry_configs (List[BaseMCPRegistryConfig]): List of registry
+ configurations (default: :obj:`None`)
+ local_config (Optional[Dict[str, Any]]): The local configuration for
+ the MCP agent. (default: :obj:`None`)
+ local_config_path (Optional[str]): The path to the local configuration
+ file for the MCP agent. (default: :obj:`None`)
+ function_calling_available (bool): Flag indicating whether the
+ model is equipped with the function calling ability.
+ (default: :obj:`True`)
+ **kwargs: Inherited from ChatAgent
+ """
+
def __init__(
self,
- config_path: str,
+ system_message: Optional[Union[str, BaseMessage]] = (
+ "You are an assistant with search capabilities using MCP tools."
+ ),
model: Optional[BaseModelBackend] = None,
- function_calling_available: bool = False,
- ) -> None:
- r"""A class for the MCP agent that assists using MCP tools.
+ registry_configs: Optional[
+ Union[List[BaseMCPRegistryConfig], BaseMCPRegistryConfig]
+ ] = None,
+ local_config: Optional[Dict[str, Any]] = None,
+ local_config_path: Optional[str] = None,
+ tools: Optional[List[Union[FunctionTool, Callable]]] = None,
+ function_calling_available: bool = True,
+ **kwargs,
+ ):
+ if model is None:
+ model = ModelFactory.create(
+ model_platform=ModelPlatformType.DEFAULT,
+ model_type=ModelType.DEFAULT,
+ )
+
+ if isinstance(registry_configs, BaseMCPRegistryConfig):
+ self.registry_configs = [registry_configs]
+ else:
+ self.registry_configs = registry_configs or []
+
+ if local_config_path:
+ with open(local_config_path, 'r') as f:
+ local_config = json.load(f)
+
+ self.local_config = local_config
+ self.function_calling_available = function_calling_available
- Args:
- config_path (str): Path to the MCP configuration file.
- model (Optional[BaseModelBackend]): Model backend for the agent.
- (default: :obj:`None`)
- function_calling_available (bool): Flag indicating whether the
- model is equipped with the function calling ability.
- (default: :obj:`False`)
- """
if function_calling_available:
sys_msg_content = "You are a helpful assistant, and you prefer "
"to use tools provided by the user to solve problems."
@@ -109,63 +158,182 @@ class MCPAgent(ChatAgent):
content=sys_msg_content,
)
- super().__init__(system_message, model=model)
+ # Initialize the toolkit if configuration is provided
+ self.mcp_toolkit = self._initialize_mcp_toolkit()
+
+ super().__init__(
+ system_message=system_message,
+ model=model,
+ tools=tools,
+ **kwargs,
+ )
+
+ def _initialize_mcp_toolkit(self) -> MCPToolkit:
+ r"""Initialize the MCP toolkit from the provided configuration."""
+ config_dict = {}
+ for registry_config in self.registry_configs:
+ config_dict.update(registry_config.get_config())
- self._mcp_toolkit = MCPToolkit(config_path=config_path)
- self._function_calling_available = function_calling_available
- self._text_tools = None
+ if self.local_config:
+ config_dict.update(self.local_config)
- async def connect(self):
- r"""Explicitly connect to all MCP servers."""
- await self._mcp_toolkit.connect()
+ return MCPToolkit(config_dict=config_dict)
- async def close(self):
- r"""Explicitly disconnect from all MCP servers."""
- await self._mcp_toolkit.disconnect()
+ def add_registry(self, registry_config: BaseMCPRegistryConfig) -> None:
+ r"""Add a new registry configuration to the agent.
- def add_mcp_tools(self):
- r"""Get the MCP tools and wrap into the models"""
+ Args:
+ registry_config (BaseMCPRegistryConfig): The registry
+ configuration to add.
+ """
+ self.registry_configs.append(registry_config)
+ # Reinitialize the toolkit with the updated configurations
+ self.mcp_toolkit = self._initialize_mcp_toolkit()
+
+ # If already connected, reconnect to apply changes
+ if self.mcp_toolkit and self.mcp_toolkit.is_connected():
+ try:
+ asyncio.run(self.disconnect())
+ asyncio.run(self.connect())
+ except RuntimeError as e:
+ # Handle case where we're already in an event loop
+ logger.warning(
+ f"Could not reconnect synchronously: {e}. "
+ f"Manual reconnection may be required."
+ )
+
+ @classmethod
+ async def create(
+ cls,
+ config_path: Optional[str] = None,
+ registry_configs: Optional[
+ Union[List[BaseMCPRegistryConfig], BaseMCPRegistryConfig]
+ ] = None,
+ model: Optional[BaseModelBackend] = None,
+ function_calling_available: bool = False,
+ **kwargs,
+ ) -> "MCPAgent":
+ r"""Create and connect an MCPAgent instance.
+
+ Args:
+ config_path (Optional[str]): Path to the MCP configuration file.
+ If provided, will load registry configs from this file.
+ (default: :obj:`None`)
+ registry_configs (Optional[Union[List[BaseMCPRegistryConfig],
+ BaseMCPRegistryConfig]]): Registry configurations to use.
+ Can be a single config or list of configs. If both config_path
+ and registry_configs are provided, configs from both sources
+ will be combined. (default: :obj:`None`)
+ model (Optional[BaseModelBackend]): The model backend to use.
+ If None, will use the default model. (default: :obj:`None`)
+ function_calling_available (bool): Whether the model supports
+ function calling. (default: :obj:`False`)
+ **kwargs: Additional arguments to pass to MCPAgent constructor.
- if not self._mcp_toolkit.is_connected():
- raise RuntimeError("The MCP server is not connected")
+ Returns:
+ MCPAgent: A connected MCPAgent instance ready to use.
+
+ Example:
+ >>> agent = await MCPAgent.create(
+ ... config_path="path/to/config.json",
+ ... function_calling_available=True
+ ... )
+ >>> response = await agent.run("Hello!")
+ """
+ # Initialize registry_configs list
+ final_registry_configs = []
- prompt = TextPrompt(TOOLS_PROMPT)
- self._text_tools = prompt.format(
- tools=self._mcp_toolkit.get_text_tools()
+ # Add configs from registry_configs argument if provided
+ if registry_configs is not None:
+ if isinstance(registry_configs, BaseMCPRegistryConfig):
+ final_registry_configs.append(registry_configs)
+ else:
+ final_registry_configs.extend(registry_configs)
+
+ # Load additional configs from file if provided
+ if config_path:
+ try:
+ with open(config_path, 'r') as f:
+ config_data = json.load(f)
+
+ # Create registry configs from the loaded data
+ for _, server_config in config_data.get(
+ "mcpServers", {}
+ ).items():
+ # Create a custom registry config for each server
+ registry_config = BaseMCPRegistryConfig(
+ type=MCPRegistryType.CUSTOM,
+ os=platform.system().lower(), # type: ignore [arg-type]
+ **server_config,
+ )
+ final_registry_configs.append(registry_config)
+ except Exception as e:
+ logger.error(f"Failed to load config from {config_path}: {e}")
+ raise
+
+ # Create the agent instance
+ agent = cls(
+ registry_configs=final_registry_configs,
+ model=model,
+ function_calling_available=function_calling_available,
+ **kwargs,
)
- if self._function_calling_available:
- tools = self._mcp_toolkit.get_tools()
- for tool in tools:
- self.add_tool(tool)
- async def run(
- self,
- prompt: str,
+ # Connect to MCP servers
+ try:
+ await agent.connect()
+ except Exception as e:
+ logger.error(f"Failed to connect to MCP servers: {e}")
+ await agent.disconnect() # Clean up if connection fails
+ raise
+
+ return agent
+
+ async def connect(self) -> None:
+ r"""Connect to the MCP servers."""
+ if self.mcp_toolkit:
+ await self.mcp_toolkit.connect()
+ if self.function_calling_available:
+ self.add_tools(
+ cast(
+ list[FunctionTool | Callable[..., Any]],
+ self.mcp_toolkit.get_tools(),
+ )
+ )
+ else:
+ prompt = TextPrompt(TOOLS_PROMPT)
+ self._text_tools = prompt.format(
+ tools=self.mcp_toolkit.get_text_tools()
+ )
+
+ async def disconnect(self) -> None:
+ r"""Disconnect from the MCP servers."""
+ if self.mcp_toolkit:
+ await self.mcp_toolkit.disconnect()
+
+ async def astep(
+ self, input_message: Union[BaseMessage, str], *args, **kwargs
) -> ChatAgentResponse:
- r"""Run the agent to interact with the MCP tools.
+ r"""Asynchronous step function. Make sure MCP toolkit is connected
+ before proceeding.
Args:
- prompt (str): The user's input prompt or query to be processed by
- the agent.
+ input_message (Union[BaseMessage, str]): The input message.
+ *args: Additional arguments.
+ **kwargs: Additional keyword arguments.
Returns:
- ChatAgentResponse: The agent's response after processing the
- prompt and potentially executing MCP tool calls.
-
- Raises:
- RuntimeError: If the MCP server is not connected when attempting
- to run.
+ ChatAgentResponse: The response from the agent.
"""
+ if self.mcp_toolkit and not self.mcp_toolkit.is_connected():
+ await self.connect()
- if not self._mcp_toolkit.is_connected():
- raise RuntimeError("The MCP server is not connected")
-
- if self._function_calling_available:
- response = await self.astep(prompt)
- return response
+ if self.function_calling_available:
+ return await super().astep(input_message, *args, **kwargs)
else:
- task = f"## Task:\n {prompt}"
- response = await self.astep(str(self._text_tools) + task)
+ task = f"## Task:\n {input_message}"
+ input_message = str(self._text_tools) + task
+ response = await super().astep(input_message, *args, **kwargs)
content = response.msgs[0].content.lower()
tool_calls = []
@@ -193,12 +361,45 @@ class MCPAgent(ChatAgent):
else:
tools_results = []
for tool_call in tool_calls:
- server_idx = tool_call['server_idx']
- tool_name = tool_call['tool_name']
- tool_args = tool_call['tool_args']
- server = self._mcp_toolkit.servers[server_idx]
- result = await server.call_tool(tool_name, tool_args)
- tools_results.append({tool_name: result.content[0].text})
+ try:
+ server_idx = tool_call.get('server_idx')
+ tool_name = tool_call.get('tool_name')
+ tool_args = tool_call.get('tool_args', {})
+
+ # Validate required fields
+ if server_idx is None or tool_name is None:
+ logger.warning(
+ f"Missing required fields in tool "
+ f"call: {tool_call}"
+ )
+ continue
+
+ # Check server index is valid
+ if (
+ not isinstance(server_idx, int)
+ or server_idx < 0
+ or server_idx >= len(self.mcp_toolkit.servers)
+ ):
+ logger.warning(
+ f"Invalid server index: {server_idx}"
+ )
+ continue
+
+ server = self.mcp_toolkit.servers[server_idx]
+ result = await server.call_tool(tool_name, tool_args)
+
+ # Safely access content
+ if result.content and len(result.content) > 0:
+ tools_results.append(
+ {tool_name: result.content[0].text}
+ )
+ else:
+ tools_results.append(
+ {tool_name: "No result content available"}
+ )
+ except Exception as e:
+ logger.error(f"Error processing tool call: {e}")
+ tools_results.append({"error": str(e)})
results = json.dumps(tools_results)
final_prompt = TextPrompt(FINAL_RESPONSE_PROMPT).format(
results=results
@@ -206,28 +407,40 @@ class MCPAgent(ChatAgent):
response = await self.astep(final_prompt)
return response
- @classmethod
- async def create(
- cls,
- config_path: str,
- model: Optional[BaseModelBackend] = None,
- function_calling_available: bool = False,
- ) -> "MCPAgent":
- r"""Factory method to create and initialize an MCPAgent.
+ def step(
+ self, input_message: Union[BaseMessage, str], *args, **kwargs
+ ) -> ChatAgentResponse:
+ r"""Synchronous step function. Make sure MCP toolkit is connected
+ before proceeding.
Args:
- config_path (str): Path to the MCP configuration file that contains
- server settings and other configuration parameters.
- model (Optional[BaseModelBackend]): Model backend for the agent.
- If None, the default model will be used. (default: :obj:`None`)
- function_calling_available (bool): Flag indicating whether the
- model is equipped with function calling ability. This affects
- the system message content. (default: :obj:`False`)
+ input_message (Union[BaseMessage, str]): The input message.
+ *args: Additional arguments.
+ **kwargs: Additional keyword arguments.
Returns:
- MCPAgent: A fully initialized MCPAgent instance ready for use.
+ ChatAgentResponse: The response from the agent.
"""
- agent = cls(config_path, model, function_calling_available)
- await agent.connect()
- agent.add_mcp_tools()
- return agent
+ try:
+ loop = asyncio.get_running_loop()
+ except RuntimeError:
+ loop = None
+
+ if loop and loop.is_running():
+ # Running inside an existing loop (e.g., Jupyter/FastAPI)
+ # Use create_task and run with a future
+ coro = self.astep(input_message, *args, **kwargs)
+ future = asyncio.ensure_future(coro)
+ return asyncio.run_coroutine_threadsafe(future, loop).result()
+ else:
+ # Safe to run normally
+ return asyncio.run(self.astep(input_message, *args, **kwargs))
+
+ async def __aenter__(self):
+ r"""Async context manager entry."""
+ await self.connect()
+ return self
+
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
+ r"""Async context manager exit."""
+ await self.disconnect()
diff --git a/camel/toolkits/mcp_toolkit.py b/camel/toolkits/mcp_toolkit.py
index d285477b8..71ed0b44c 100644
--- a/camel/toolkits/mcp_toolkit.py
+++ b/camel/toolkits/mcp_toolkit.py
@@ -54,6 +54,37 @@ class MCPClient(BaseToolkit):
3. streamable-http mode: Connects via HTTP for persistent, streamable
interactions.
+ Connection Lifecycle:
+ There are three ways to manage the connection lifecycle:
+
+ 1. Using the async context manager:
+ ```python
+ async with MCPClient(command_or_url="...") as client:
+ # Client is connected here
+ result = await client.some_tool()
+ # Client is automatically disconnected here
+ ```
+
+ 2. Using the factory method:
+ ```python
+ client = await MCPClient.create(command_or_url="...")
+ # Client is connected here
+ result = await client.some_tool()
+ # Don't forget to disconnect when done!
+ await client.disconnect()
+ ```
+
+ 3. Using explicit connect/disconnect:
+ ```python
+ client = MCPClient(command_or_url="...")
+ await client.connect()
+ # Client is connected here
+ result = await client.some_tool()
+ # Don't forget to disconnect when done!
+ await client.disconnect()
+ ```
+
+
Attributes:
command_or_url (str): URL for SSE mode or command executable for stdio
mode. (default: :obj:`None`)
@@ -396,6 +427,70 @@ class MCPClient(BaseToolkit):
def session(self) -> Optional["ClientSession"]:
return self._session
+ @classmethod
+ async def create(
+ cls,
+ command_or_url: str,
+ args: Optional[List[str]] = None,
+ env: Optional[Dict[str, str]] = None,
+ timeout: Optional[float] = None,
+ headers: Optional[Dict[str, str]] = None,
+ ) -> "MCPClient":
+ r"""Factory method that creates and connects to the MCP server.
+
+ This async factory method ensures the connection to the MCP server is
+ established before the client object is fully constructed.
+
+ Args:
+ command_or_url (str): URL for SSE mode or command executable
+ for stdio mode.
+ args (Optional[List[str]]): List of command-line arguments if
+ stdio mode is used. (default: :obj:`None`)
+ env (Optional[Dict[str, str]]): Environment variables for
+ the stdio mode command. (default: :obj:`None`)
+ timeout (Optional[float]): Connection timeout.
+ (default: :obj:`None`)
+ headers (Optional[Dict[str, str]]): Headers for the HTTP request.
+ (default: :obj:`None`)
+
+ Returns:
+ MCPClient: A fully initialized and connected MCPClient instance.
+
+ Raises:
+ RuntimeError: If connection to the MCP server fails.
+ """
+ client = cls(
+ command_or_url=command_or_url,
+ args=args,
+ env=env,
+ timeout=timeout,
+ headers=headers,
+ )
+ try:
+ await client.connect()
+ return client
+ except Exception as e:
+ # Ensure cleanup on initialization failure
+ await client.disconnect()
+ logger.error(f"Failed to initialize MCPClient: {e}")
+ raise RuntimeError(f"Failed to initialize MCPClient: {e}") from e
+
+ async def __aenter__(self) -> "MCPClient":
+ r"""Async context manager entry point. Automatically connects to the
+ MCP server when used in an async with statement.
+
+ Returns:
+ MCPClient: Self with active connection.
+ """
+ await self.connect()
+ return self
+
+ async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
+ r"""Async context manager exit point. Automatically disconnects from
+ the MCP server when exiting an async with statement.
+ """
+ await self.disconnect()
+
class MCPToolkit(BaseToolkit):
r"""MCPToolkit provides a unified interface for managing multiple
@@ -405,6 +500,36 @@ class MCPToolkit(BaseToolkit):
offers a centralized configuration mechanism for both local and remote
MCP services.
+ Connection Lifecycle:
+ There are three ways to manage the connection lifecycle:
+
+ 1. Using the async context manager:
+ ```python
+ async with MCPToolkit(config_path="config.json") as toolkit:
+ # Toolkit is connected here
+ tools = toolkit.get_tools()
+ # Toolkit is automatically disconnected here
+ ```
+
+ 2. Using the factory method:
+ ```python
+ toolkit = await MCPToolkit.create(config_path="config.json")
+ # Toolkit is connected here
+ tools = toolkit.get_tools()
+ # Don't forget to disconnect when done!
+ await toolkit.disconnect()
+ ```
+
+ 3. Using explicit connect/disconnect:
+ ```python
+ toolkit = MCPToolkit(config_path="config.json")
+ await toolkit.connect()
+ # Toolkit is connected here
+ tools = toolkit.get_tools()
+ # Don't forget to disconnect when done!
+ await toolkit.disconnect()
+ ```
+
Args:
servers (Optional[List[MCPClient]]): List of MCPClient
instances to manage. (default: :obj:`None`)
diff --git a/camel/types/__init__.py b/camel/types/__init__.py
index 27d1c4902..25490e830 100644
--- a/camel/types/__init__.py
+++ b/camel/types/__init__.py
@@ -29,6 +29,12 @@ from .enums import (
VectorDistance,
VoiceType,
)
+from .mcp_registries import (
+ ACIRegistryConfig,
+ BaseMCPRegistryConfig,
+ MCPRegistryType,
+ SmitheryRegistryConfig,
+)
from .openai_types import (
NOT_GIVEN,
ChatCompletion,
@@ -79,4 +85,8 @@ __all__ = [
'GeminiEmbeddingTaskType',
'NOT_GIVEN',
'NotGiven',
+ 'BaseMCPRegistryConfig',
+ 'MCPRegistryType',
+ 'SmitheryRegistryConfig',
+ 'ACIRegistryConfig',
]
diff --git a/camel/types/mcp_registries.py b/camel/types/mcp_registries.py
new file mode 100644
index 000000000..f5f07c3b4
--- /dev/null
+++ b/camel/types/mcp_registries.py
@@ -0,0 +1,157 @@
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+import os
+import platform
+from enum import Enum, auto
+from typing import Any, Dict, List, Literal, Optional
+
+from pydantic import BaseModel, Field, model_validator
+
+
+class MCPRegistryType(Enum):
+ r"""Enum for different types of MCP registries."""
+
+ SMITHERY = auto()
+ ACI = auto()
+ CUSTOM = auto()
+
+
+class BaseMCPRegistryConfig(BaseModel):
+ r"""Base configuration for an MCP registry.
+
+ Attributes:
+ type (MCPRegistryType): The type of the registry.
+ os (Literal["darwin", "linux", "windows"]): The operating system. It
+ is automatically set to "darwin" for MacOS, "linux" for Linux, and
+ "windows" for Windows.
+ api_key (Optional[str]): API key for the registry.
+ """
+
+ type: MCPRegistryType
+ os: Literal["darwin", "linux", "windows"]
+ api_key: Optional[str] = None
+
+ def get_config(self) -> Dict[str, Any]:
+ r"""Generate configuration based on registry type and API key.
+
+ Returns:
+ Dict[str, Any]: The complete configuration for the registry.
+ """
+ return {}
+
+ @model_validator(mode='before')
+ @classmethod
+ def set_default_os(cls, values: Dict) -> Dict:
+ r"""Set the default OS based on the current platform if not provided.
+
+ Args:
+ values (Dict): The values dictionary from the model validation.
+
+ Returns:
+ Dict: The updated values dictionary with the OS set.
+
+ Raises:
+ ValueError: If the current system is not supported.
+ """
+ if 'os' not in values or values['os'] is None:
+ system = platform.system().lower()
+ if system in ('darwin', 'linux', 'windows'):
+ values['os'] = system
+ else:
+ raise ValueError(f"Unsupported system: {system}")
+ return values
+
+ def _prepare_command_args(
+ self, command: str, args: List[str]
+ ) -> Dict[str, Any]:
+ r"""Prepare command and arguments based on OS.
+
+ Args:
+ command (str): The base command to run.
+ args (List[str]): The arguments for the command.
+
+ Returns:
+ Dict[str, Any]: Command configuration with OS-specific adjustments.
+ """
+ if self.os == "windows":
+ return {"command": "cmd", "args": ["/c", command, *args]}
+ else: # darwin or linux
+ return {"command": command, "args": args}
+
+
+class SmitheryRegistryConfig(BaseMCPRegistryConfig):
+ r"""Configuration for Smithery registry."""
+
+ type: MCPRegistryType = MCPRegistryType.SMITHERY
+ profile: str = Field(
+ ..., description="The profile to use for the registry."
+ )
+
+ def get_config(self) -> Dict[str, Any]:
+ r"""Generate configuration for Smithery registry.
+
+ Returns:
+ Dict[str, Any]: The complete configuration for the registry.
+ """
+ api_key = self.api_key or os.environ.get("SMITHERY_API_KEY")
+
+ args = [
+ "-y",
+ "@smithery/cli@latest",
+ "run",
+ "@smithery/toolbox",
+ "--key",
+ api_key,
+ "--profile",
+ self.profile,
+ ]
+
+ cmd_config = self._prepare_command_args("npx", args) # type: ignore[arg-type]
+
+ return {"mcpServers": {"toolbox": cmd_config}}
+
+
+class ACIRegistryConfig(BaseMCPRegistryConfig):
+ r"""Configuration for ACI registry."""
+
+ type: MCPRegistryType = MCPRegistryType.ACI
+ linked_account_owner_id: str = Field(
+ ..., description="The owner ID of the linked account."
+ )
+
+ def get_config(self) -> Dict[str, Any]:
+ r"""Generate configuration for ACI registry.
+
+ Returns:
+ Dict[str, Any]: The complete configuration for the registry.
+ """
+ api_key = self.api_key or os.environ.get("ACI_API_KEY")
+
+ args = [
+ "aci-mcp",
+ "unified-server",
+ "--linked-account-owner-id",
+ self.linked_account_owner_id,
+ ]
+
+ cmd_config = self._prepare_command_args("uvx", args)
+
+ return {
+ "mcpServers": {
+ "aci-mcp-unified": {
+ **cmd_config,
+ "env": {"ACI_API_KEY": api_key},
+ }
+ }
+ }
diff --git a/examples/agents/mcp_agent/mcp_agent_using_registry.py b/examples/agents/mcp_agent/mcp_agent_using_registry.py
new file mode 100644
index 000000000..07836a0a7
--- /dev/null
+++ b/examples/agents/mcp_agent/mcp_agent_using_registry.py
@@ -0,0 +1,167 @@
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+
+import asyncio
+import logging
+import os
+
+from camel.agents import MCPAgent
+from camel.models import ModelFactory
+from camel.types import (
+ ACIRegistryConfig,
+ BaseMCPRegistryConfig,
+ ModelPlatformType,
+ ModelType,
+ # SmitheryRegistryConfig,
+)
+
+# Configure logging
+logging.basicConfig(
+ level=logging.INFO,
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
+)
+logger = logging.getLogger('camel')
+logger.setLevel(logging.DEBUG)
+
+
+async def example_with_registry_config(
+ message: str, registry_config: BaseMCPRegistryConfig
+):
+ r"""Example using MCPAgent with registry configurations."""
+
+ # Create a model
+ model = ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_4O,
+ )
+
+ # Create MCPAgent with registry configurations
+ agent = MCPAgent(
+ model=model,
+ registry_configs=[registry_config],
+ )
+
+ await agent.connect()
+
+ # Use agent with async context manager
+ async with agent:
+ response = await agent.astep(message)
+ print(f"\nResponse from {message}:")
+ print(response.msgs[0].content)
+
+ await agent.disconnect()
+
+
+async def main():
+ r"""Run examples."""
+ # smithery_config = SmitheryRegistryConfig(
+ # api_key=os.getenv("SMITHERY_API_KEY"),
+ # profile=os.getenv("SMITHERY_PROFILE"),
+ # os="darwin",
+ # )
+ aci_config = ACIRegistryConfig(
+ api_key=os.getenv("ACI_API_KEY"),
+ linked_account_owner_id=os.getenv("ACI_LINKED_ACCOUNT_OWNER_ID"),
+ )
+ # Registry configuration example
+ message = "What MCP tools I can use for connecting to the Gmail?"
+ # message = "Use Brave MCP search tools to search info about Camel-AI.org."
+ await example_with_registry_config(
+ message=message,
+ registry_config=aci_config,
+ # registry_config=smithery_config,
+ )
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
+
+"""
+===========================================================================
+Response from What MCP tools I can use for connecting to the Gmail?:
+I found several MCP tools that can connect to Gmail. Here are the options:
+
+1. **Google Workspace Server** (@rishipradeep-think41/gsuite-mcp)
+ - Manage emails and calendar events through Gmail and Calendar APIs
+ - [Configure here](https://smithery.ai/server/@rishipradeep-think41/gsuite-mcp/config)
+
+2. **VeyraX MCP** (@VeyraX/veyrax-mcp)
+ - Connects to 70+ tools including Gmail and Calendar
+ - [Configure here](https://smithery.ai/server/@VeyraX/veyrax-mcp/config)
+
+3. **Google Workspace MCP Server** (google-workspace-server)
+ - Interact with Gmail and Calendar APIs
+ - [Configure here](https://smithery.ai/server/google-workspace-server/config)
+
+4. **Headless Gmail Server** (@baryhuang/mcp-headless-gmail)
+ - Access and send emails through Gmail without local credential setup
+ - [Configure here](https://smithery.ai/server/@baryhuang/mcp-headless-gmail/config)
+
+5. **Google Workspace Server** (@rishipradeep-think41/gmail-backupmcp)
+ - Another option for managing Gmail and Calendar
+
+Each of these tools requires configuration before it can be used. You'll need
+to click on one of the configuration links above to set up the tool with your
+Gmail credentials. Once you've completed the configuration, let me know which
+tool you've chosen, and I can help you use it to connect to your Gmail account.
+===========================================================================
+"""
+
+"""
+===========================================================================
+Response from Use Brave MCP search tools to search info about Camel-AI.org.:
+# CAMEL-AI.org: Information and Purpose
+
+Based on my search results, here's what I found about CAMEL-AI.org:
+
+## Organization Overview
+CAMEL-AI.org is the first LLM (Large Language Model) multi-agent framework and
+an open-source community. The name CAMEL stands for "Communicative Agents for
+Mind Exploration of Large Language Model Society."
+
+## Core Purpose
+The organization is dedicated to "Finding the Scaling Law of Agents" - this
+appears to be their primary research mission, focusing on understanding how
+agent-based AI systems scale and develop.
+
+## Research Focus
+CAMEL-AI is a research-driven organization that explores:
+- Scalable techniques for autonomous cooperation among communicative agents
+- Multi-agent frameworks for AI systems
+- Data generation for AI training
+- AI society simulations
+
+## Community and Collaboration
+- They maintain an active open-source community
+- They invite contributors and collaborators through platforms like Slack and
+Discord
+- The organization has a research collaboration questionnaire for those
+interested in building or researching environments for LLM-based agents
+
+## Technical Resources
+- Their code is available on GitHub (github.com/camel-ai) with 18 repositories
+- They provide documentation for developers and researchers at
+docs.camel-ai.org
+- They offer tools and cookbooks for working with their agent framework
+
+## Website and Online Presence
+- Main website: https://www.camel-ai.org/
+- GitHub: https://github.com/camel-ai
+- Documentation: https://docs.camel-ai.org/
+
+The organization appears to be at the forefront of research on multi-agent AI
+systems, focusing on how these systems can cooperate autonomously and scale
+effectively.
+===========================================================================
+"""
diff --git a/examples/agents/mcp_agent/mcp_agent.py b/examples/agents/mcp_agent/mcp_agent_without_function_calling.py
similarity index 93%
rename from examples/agents/mcp_agent/mcp_agent.py
rename to examples/agents/mcp_agent/mcp_agent_without_function_calling.py
index ad331806c..c4c069053 100644
--- a/examples/agents/mcp_agent/mcp_agent.py
+++ b/examples/agents/mcp_agent/mcp_agent_without_function_calling.py
@@ -29,7 +29,7 @@ async def main():
# Initialize the agent using the factory method (recommended)
mcp_agent = await MCPAgent.create(
- config_path=str(config_path),
+ local_config_path=str(config_path),
model=model,
function_calling_available=False,
)
@@ -38,12 +38,12 @@ async def main():
"I have 5 boxes, each of them containing 50 apples, "
"how many apples in total."
)
- response = await mcp_agent.run(user_msg)
+ response = await mcp_agent.astep(user_msg)
print(response.msgs[0].content)
# Disconnect from all MCP servers and clean up resources.
- await mcp_agent.close()
+ await mcp_agent.disconnect()
if __name__ == "__main__":