š« 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: Refactor MCPToolkits (#3095)
Ol1ver0413d83a79e10bbe
diff --git a/camel/toolkits/edgeone_pages_mcp_toolkit.py b/camel/toolkits/edgeone_pages_mcp_toolkit.pyindex f17c02ffd..2a81ac1a1 100644--- a/camel/toolkits/edgeone_pages_mcp_toolkit.py+++ b/camel/toolkits/edgeone_pages_mcp_toolkit.py@@ -12,14 +12,12 @@# limitations under the License.# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========-from typing import List, Optional--from camel.toolkits import BaseToolkit, FunctionTool+from typing import Optionalfrom .mcp_toolkit import MCPToolkit-class EdgeOnePagesMCPToolkit(BaseToolkit):+class EdgeOnePagesMCPToolkit(MCPToolkit):r"""EdgeOnePagesMCPToolkit provides an interface for interacting withEdgeOne pages using the EdgeOne Pages MCP server.@@ -38,32 +36,14 @@ class EdgeOnePagesMCPToolkit(BaseToolkit):timeout (Optional[float]): Connection timeout in seconds.(default: :obj:`None`)"""- super().__init__(timeout=timeout)-- self._mcp_toolkit = MCPToolkit(- config_dict={- "mcpServers": {- "edgeone-pages-mcp-server": {- "command": "npx",- "args": ["edgeone-pages-mcp"],- }+ config_dict = {+ "mcpServers": {+ "edgeone-pages-mcp-server": {+ "command": "npx",+ "args": ["edgeone-pages-mcp"],}- },- timeout=timeout,- )-- async def connect(self):- r"""Explicitly connect to the EdgeOne Pages MCP server."""- await self._mcp_toolkit.connect()+ }+ }- async def disconnect(self):- r"""Explicitly disconnect from the EdgeOne Pages MCP server."""- await self._mcp_toolkit.disconnect()-- def get_tools(self) -> List[FunctionTool]:- r"""Returns a list of tools provided by the EdgeOnePagesMCPToolkit.-- Returns:- List[FunctionTool]: List of available tools.- """- return self._mcp_toolkit.get_tools()+ # Initialize parent MCPToolkit with EdgeOne Pages configuration+ super().__init__(config_dict=config_dict, timeout=timeout)diff --git a/camel/toolkits/google_drive_mcp_toolkit.py b/camel/toolkits/google_drive_mcp_toolkit.pyindex 797200a9b..468549327 100644--- a/camel/toolkits/google_drive_mcp_toolkit.py+++ b/camel/toolkits/google_drive_mcp_toolkit.py@@ -12,14 +12,12 @@# limitations under the License.# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========-from typing import List, Optional--from camel.toolkits import BaseToolkit, FunctionTool+from typing import Optionalfrom .mcp_toolkit import MCPToolkit-class GoogleDriveMCPToolkit(BaseToolkit):+class GoogleDriveMCPToolkit(MCPToolkit):r"""GoogleDriveMCPToolkit provides an interface for interacting withGoogle Drive using the Google Drive MCP server.@@ -41,33 +39,16 @@ class GoogleDriveMCPToolkit(BaseToolkit):credentials_path (Optional[str]): Path to the Google Drivecredentials file. (default: :obj:`None`)"""- super().__init__(timeout=timeout)- self._mcp_toolkit = MCPToolkit(- config_dict={- "mcpServers": {- "gdrive": {- "command": "npx",- "args": ["-y", "@modelcontextprotocol/server-gdrive"],- "env": {"GDRIVE_CREDENTIALS_PATH": credentials_path},- }+ config_dict = {+ "mcpServers": {+ "gdrive": {+ "command": "npx",+ "args": ["-y", "@modelcontextprotocol/server-gdrive"],+ "env": {"GDRIVE_CREDENTIALS_PATH": credentials_path},}- },- timeout=timeout,- )-- async def connect(self):- r"""Explicitly connect to the Google Drive MCP server."""- await self._mcp_toolkit.connect()-- async def disconnect(self):- r"""Explicitly disconnect from the Google Drive MCP server."""- await self._mcp_toolkit.disconnect()+ }+ }- def get_tools(self) -> List[FunctionTool]:- r"""Returns a list of tools provided by the GoogleDriveMCPToolkit.-- Returns:- List[FunctionTool]: List of available tools.- """- return self._mcp_toolkit.get_tools()+ # Initialize parent MCPToolkit with Playwright configuration+ super().__init__(config_dict=config_dict, timeout=timeout)diff --git a/camel/toolkits/notion_mcp_toolkit.py b/camel/toolkits/notion_mcp_toolkit.pyindex aa38ce9c8..d214a7403 100644--- a/camel/toolkits/notion_mcp_toolkit.py+++ b/camel/toolkits/notion_mcp_toolkit.py@@ -14,12 +14,12 @@from typing import Any, ClassVar, Dict, List, Optional, Set-from camel.toolkits import BaseToolkit, FunctionTool+from camel.toolkits import FunctionToolfrom .mcp_toolkit import MCPToolkit-class NotionMCPToolkit(BaseToolkit):+class NotionMCPToolkit(MCPToolkit):r"""NotionMCPToolkit provides an interface for interacting with Notionthrough the Model Context Protocol (MCP).@@ -75,31 +75,21 @@ class NotionMCPToolkit(BaseToolkit):timeout (Optional[float]): Connection timeout in seconds.(default: :obj:`None`)"""- super().__init__(timeout=timeout)-- self._mcp_toolkit = MCPToolkit(- config_dict={- "mcpServers": {- "notionMCP": {- "command": "npx",- "args": [- "-y",- "mcp-remote",- "https://mcp.notion.com/mcp",- ],- }+ config_dict = {+ "mcpServers": {+ "notionMCP": {+ "command": "npx",+ "args": [+ "-y",+ "mcp-remote",+ "https://mcp.notion.com/mcp",+ ],}- },- timeout=timeout,- )-- async def connect(self):- r"""Explicitly connect to the Notion MCP server."""- await self._mcp_toolkit.connect()+ }+ }- async def disconnect(self):- r"""Explicitly disconnect from the Notion MCP server."""- await self._mcp_toolkit.disconnect()+ # Initialize parent MCPToolkit with Notion configuration+ super().__init__(config_dict=config_dict, timeout=timeout)def get_tools(self) -> List[FunctionTool]:r"""Returns a list of tools provided by the NotionMCPToolkit.@@ -108,7 +98,7 @@ class NotionMCPToolkit(BaseToolkit):List[FunctionTool]: List of available tools."""all_tools = []- for client in self._mcp_toolkit.clients:+ for client in self.clients:try:original_build_schema = client._build_tool_schemadiff --git a/camel/toolkits/origene_mcp_toolkit.py b/camel/toolkits/origene_mcp_toolkit.pyindex a4378dd18..a8e95aa57 100644--- a/camel/toolkits/origene_mcp_toolkit.py+++ b/camel/toolkits/origene_mcp_toolkit.py@@ -12,12 +12,12 @@# limitations under the License.# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========-from typing import Dict, List, Optional+from typing import Dict, Optional-from camel.toolkits import BaseToolkit, FunctionTool, MCPToolkit+from .mcp_toolkit import MCPToolkit-class OrigeneToolkit(BaseToolkit):+class OrigeneToolkit(MCPToolkit):r"""OrigeneToolkit provides an interface for interacting withOrigene MCP server.@@ -43,55 +43,14 @@ class OrigeneToolkit(BaseToolkit):Args:config_dict (Optional[Dict]): Configuration dictionary for MCP- servers. If None, uses default configuration for chembl_mcp.+ servers. If None, raises ValueError as configuration is required.(default: :obj:`None`)timeout (Optional[float]): Connection timeout in seconds.(default: :obj:`None`)"""- super().__init__(timeout=timeout)-- # Use default configuration if none provided+ # Validate that config_dict is providedif config_dict is None:raise ValueError("config_dict must be provided")- self._mcp_toolkit = MCPToolkit(- config_dict=config_dict,- timeout=timeout,- )-- async def connect(self):- r"""Explicitly connect to the Origene MCP server."""- await self._mcp_toolkit.connect()-- async def disconnect(self):- r"""Explicitly disconnect from the Origene MCP server."""- await self._mcp_toolkit.disconnect()-- async def __aenter__(self) -> "OrigeneToolkit":- r"""Async context manager entry point.-- Returns:- OrigeneToolkit: The connected toolkit instance.-- Example:- async with OrigeneToolkit(config_dict=config) as toolkit:- tools = toolkit.get_tools()- """- 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 Origene MCP server.- """- await self.disconnect()- return None-- def get_tools(self) -> List[FunctionTool]:- r"""Returns a list of tools provided by the Origene MCP server.-- Returns:- List[FunctionTool]: List of available tools.- """- return self._mcp_toolkit.get_tools()+ # Initialize parent MCPToolkit with provided configuration+ super().__init__(config_dict=config_dict, timeout=timeout)diff --git a/camel/toolkits/playwright_mcp_toolkit.py b/camel/toolkits/playwright_mcp_toolkit.pyindex dcb95dc9c..6f61ec7c6 100644--- a/camel/toolkits/playwright_mcp_toolkit.py+++ b/camel/toolkits/playwright_mcp_toolkit.py@@ -14,12 +14,12 @@from typing import List, Optional-from camel.toolkits import BaseToolkit, FunctionTool+from camel.toolkits import FunctionToolfrom .mcp_toolkit import MCPToolkit-class PlaywrightMCPToolkit(BaseToolkit):+class PlaywrightMCPToolkit(MCPToolkit):r"""PlaywrightMCPToolkit provides an interface for interacting with webbrowsers using the Playwright automation library through the Model ContextProtocol (MCP).@@ -51,33 +51,18 @@ class PlaywrightMCPToolkit(BaseToolkit):`["--cdp-endpoint=http://localhost:9222"]`.(default: :obj:`None`)"""- super().__init__(timeout=timeout)-- self._mcp_toolkit = MCPToolkit(- config_dict={- "mcpServers": {- "playwright": {- "command": "npx",- "args": ["@playwright/mcp@latest"]- + (additional_args or []),- }+ # Create config for Playwright MCP server+ config_dict = {+ "mcpServers": {+ "playwright": {+ "command": "npx",+ "args": ["@playwright/mcp@latest"]+ + (additional_args or []),}- },- timeout=timeout,- )-- async def connect(self):- r"""Explicitly connect to the Playwright MCP server."""- await self._mcp_toolkit.connect()+ }+ }++ # Initialize parent MCPToolkit with Playwright configuration+ super().__init__(config_dict=config_dict, timeout=timeout)- async def disconnect(self):- r"""Explicitly disconnect from the Playwright MCP server."""- await self._mcp_toolkit.disconnect()- def get_tools(self) -> List[FunctionTool]:- r"""Returns a list of tools provided by the PlaywrightMCPToolkit.-- Returns:- List[FunctionTool]: List of available tools.- """- return self._mcp_toolkit.get_tools()diff --git a/examples/toolkits/edgeone_pages_mcp_toolkit.py b/examples/toolkits/edgeone_pages_mcp_toolkit.pyindex c1fb5dda3..f75d610a5 100644--- a/examples/toolkits/edgeone_pages_mcp_toolkit.py+++ b/examples/toolkits/edgeone_pages_mcp_toolkit.py@@ -38,6 +38,8 @@ async def main():response = await chat_agent.astep("write a hello world page",)++ print("=== Model Response ===")print(response.msg.content)# disconnect from edgeone pages mcp@@ -50,7 +52,14 @@ if __name__ == "__main__":"""==============================================================================-I have created a "Hello, World!" web page for you. You can view it here:-https://mcp.edgeone.site/share/7D8SNj2ftY9SRtPrWZ5rW+I've created a Hello World page for you! The page has been deployed and is now live at:++**https://mcp.edgeone.site/share/M-MXzJzHJ3mGc013OQNIM**++The page features:+- A modern, gradient background+- Centered "Hello World!" heading+- Clean, responsive design+- A welcome message below the main heading=============================================================================="""diff --git a/examples/toolkits/goole_drive_mcp_toolkit.py b/examples/toolkits/google_drive_mcp_toolkit.pysimilarity index 97%rename from examples/toolkits/goole_drive_mcp_toolkit.pyrename to examples/toolkits/google_drive_mcp_toolkit.pyindex 060d168a2..19a568cf4 100644--- a/examples/toolkits/goole_drive_mcp_toolkit.py+++ b/examples/toolkits/google_drive_mcp_toolkit.py@@ -40,6 +40,8 @@ async def main():response = await chat_agent.astep("what is the name of the file in the root of my drive?",)++ print("=== Model Response ===")print(response.msg.content)# disconnect from google drive mcpdiff --git a/examples/toolkits/notion_mcp_tookit.py b/examples/toolkits/notion_mcp_tookit.pyindex 48dce5a5d..f35bc2c48 100644--- a/examples/toolkits/notion_mcp_tookit.py+++ b/examples/toolkits/notion_mcp_tookit.py@@ -36,9 +36,12 @@ async def main():)response = await chat_agent.astep(- """create a new page in my notion named 'CAMEL-AI Notion MCP Toolkit- Test'""",+ """create a new page in my notion named 'Camel Introduction'+and add some content describing Camel as a lightweight multi-agent framework+that supports role-driven collaboration and modular workflows.""")++ print("=== Model Response ===")print(response.msg.content)# disconnect from notion mcp@@ -48,11 +51,19 @@ async def main():# Run the async main functionif __name__ == "__main__":asyncio.run(main())-""""++"""===========================================================================-I have created a new page in your Notion named 'CAMEL-AI Notion MCP Toolkit-Test'. You can access it here: https://www.notion.so/-23720ddf035c8146812bf34c9b8d30c5 Is there anything else you would like to do-with this page?+[681981] [RemoteāLocal] 0+[681981] [LocalāRemote] notifications/initialized+[681981] [LocalāRemote] tools/list+[681981] [RemoteāLocal] 1+/home/lyz/Camel/camel/camel/memories/blocks/chat_history_block.py:73: UserWarning: The `ChatHistoryMemory` is empty.+ warnings.warn("The `ChatHistoryMemory` is empty.")+[681981] [LocalāRemote] tools/call+[681981] [RemoteāLocal] 2+I have created the page "Camel Introduction" for you. You can view it here: https://www.notion.so/2626be7b2793819aaf2cfe686a554bdd+[681981]+Shutting down...============================================================================"""diff --git a/examples/toolkits/playwright_mcp_toolkit.py b/examples/toolkits/playwright_mcp_toolkit.pyindex 1606c470a..6a558ea9f 100644--- a/examples/toolkits/playwright_mcp_toolkit.py+++ b/examples/toolkits/playwright_mcp_toolkit.py@@ -20,11 +20,11 @@ from camel.models import ModelFactoryfrom camel.toolkits import PlaywrightMCPToolkitfrom camel.types import ModelPlatformType, ModelType-async def main():+ # Create PlaywrightMCPToolkit (now inherits directly from MCPToolkit)playwright_mcp_toolkit = PlaywrightMCPToolkit()- # connect to playwright mcp+ # Connect to playwright mcp (inherited method from MCPToolkit)await playwright_mcp_toolkit.connect()model = ModelFactory.create(@@ -32,23 +32,25 @@ async def main():model_type=ModelType.DEFAULT,)- # pydantic basemodel as input params format+ # Pydantic basemodel as input params formatclass AgentResponse(BaseModel):url: str = Field(description="Url of the repository")stars: int = Field(description="Stars of the repository")chat_agent = ChatAgent(model=model,- tools=playwright_mcp_toolkit.get_tools(),+ tools=playwright_mcp_toolkit.get_tools(), # Inherited method)-+response = await chat_agent.astep(- "search for camel-ai using google search, how many stars does it has?",+ "Navigate to https://github.com/camel-ai/camel and get the star count.",response_format=AgentResponse,)++ print("=== Model Response ===")print(response.msg.content)- # disconnect from playwright mcp+ # Disconnect from playwright mcp (inherited method from MCPToolkit)await playwright_mcp_toolkit.disconnect()@@ -58,6 +60,9 @@ if __name__ == "__main__":"""==============================================================================-{"url":"https://github.com/camel-ai/camel","stars":12900}+{+ "url": "https://github.com/camel-ai/camel",+ "stars": 14040+}==============================================================================-"""+"""\ No newline at end of file