🐫 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 to_mcp and example in workforce (#2550)
Xiaotian Jindf8e8705a7cd
diff --git a/camel/societies/workforce/role_playing_worker.py b/camel/societies/workforce/role_playing_worker.pyindex cc9b5664e..0990aef46 100644--- a/camel/societies/workforce/role_playing_worker.py+++ b/camel/societies/workforce/role_playing_worker.py@@ -48,7 +48,7 @@ class RolePlayingWorker(Worker):initialize the summarize agent, like the model name, etc.(default: :obj:`None`)chat_turn_limit (int): The maximum number of chat turns in the role- playing. (default: :obj:`3`)+ playing. (default: :obj:`20`)"""def __init__(@@ -59,7 +59,7 @@ class RolePlayingWorker(Worker):assistant_agent_kwargs: Optional[Dict] = None,user_agent_kwargs: Optional[Dict] = None,summarize_agent_kwargs: Optional[Dict] = None,- chat_turn_limit: int = 3,+ chat_turn_limit: int = 20,) -> None:super().__init__(description)self.summarize_agent_kwargs = summarize_agent_kwargsdiff --git a/camel/societies/workforce/workforce.py b/camel/societies/workforce/workforce.pyindex 3c222a253..0518218af 100644--- a/camel/societies/workforce/workforce.py+++ b/camel/societies/workforce/workforce.py@@ -15,6 +15,7 @@ from __future__ import annotationsimport asyncioimport json+import uuidfrom collections import dequefrom typing import Deque, Dict, List, Optional@@ -42,6 +43,7 @@ from camel.societies.workforce.worker import Workerfrom camel.tasks.task import Task, TaskStatefrom camel.toolkits import CodeExecutionToolkit, SearchToolkit, ThinkingToolkitfrom camel.types import ModelPlatformType, ModelType+from camel.utils import dependencies_requiredlogger = get_logger(__name__)@@ -621,3 +623,380 @@ class Workforce(BaseNode):continuereturn new_instance++ @dependencies_required("mcp")+ def to_mcp(+ self,+ name: str = "CAMEL-Workforce",+ description: str = (+ "A workforce system using the CAMEL AI framework for "+ "multi-agent collaboration."+ ),+ dependencies: Optional[List[str]] = None,+ host: str = "localhost",+ port: int = 8001,+ ):+ r"""Expose this Workforce as an MCP server.++ Args:+ name (str): Name of the MCP server.+ (default: :obj:`CAMEL-Workforce`)+ description (str): Description of the workforce. If+ None, a generic description is used. (default: :obj:`A+ workforce system using the CAMEL AI framework for+ multi-agent collaboration.`)+ dependencies (Optional[List[str]]): Additional+ dependencies for the MCP server. (default: :obj:`None`)+ host (str): Host to bind to for HTTP transport.+ (default: :obj:`localhost`)+ port (int): Port to bind to for HTTP transport.+ (default: :obj:`8001`)++ Returns:+ FastMCP: An MCP server instance that can be run.+ """+ from mcp.server.fastmcp import FastMCP++ # Combine dependencies+ all_dependencies = ["camel-ai[all]"]+ if dependencies:+ all_dependencies.extend(dependencies)++ mcp_server = FastMCP(+ name,+ dependencies=all_dependencies,+ host=host,+ port=port,+ )++ # Store workforce reference+ workforce_instance = self++ # Define functions first+ def process_task(task_content, task_id=None, additional_info=None):+ r"""Process a task using the workforce.++ Args:+ task_content (str): The content of the task to be processed.+ task_id (str, optional): Unique identifier for the task. If+ None, a UUID will be automatically generated.+ (default: :obj:`None`)+ additional_info (str, optional): Additional information or+ context for the task. (default: :obj:`None`)++ Returns:+ Dict[str, Any]: A dictionary containing the processing result+ with the following keys:+ - status (str): "success" or "error"+ - task_id (str): The ID of the processed task+ - state (str): Final state of the task+ - result (str): Task result content+ - subtasks (List[Dict]): List of subtask information+ - message (str): Error message if status is "error"++ Example:+ >>> result = process_task("Analyze market trends", "task_001")+ >>> print(result["status"]) # "success" or "error"+ """+ task = Task(+ content=task_content,+ id=task_id or str(uuid.uuid4()),+ additional_info=additional_info or "",+ )++ try:+ result_task = workforce_instance.process_task(task)+ return {+ "status": "success",+ "task_id": result_task.id,+ "state": str(result_task.state),+ "result": result_task.result or "",+ "subtasks": [+ {+ "id": subtask.id,+ "content": subtask.content,+ "state": str(subtask.state),+ "result": subtask.result or "",+ }+ for subtask in (result_task.subtasks or [])+ ],+ }+ except Exception as e:+ return {+ "status": "error",+ "message": str(e),+ "task_id": task.id,+ }++ # Reset tool+ def reset():+ r"""Reset the workforce to its initial state.++ Clears all pending tasks, resets all child nodes, and returns+ the workforce to a clean state ready for new task processing.++ Returns:+ Dict[str, str]: A dictionary containing the reset result with:+ - status (str): "success" or "error"+ - message (str): Descriptive message about the operation++ Example:+ >>> result = reset()+ >>> print(result["message"]) # "Workforce reset successfully"+ """+ try:+ workforce_instance.reset()+ return {+ "status": "success",+ "message": "Workforce reset successfully",+ }+ except Exception as e:+ return {"status": "error", "message": str(e)}++ # Workforce info resource and tool+ def get_workforce_info():+ r"""Get comprehensive information about the workforce.++ Retrieves the current state and configuration of the workforce+ including its ID, description, running status, and task queue+ information.++ Returns:+ Dict[str, Any]: A dictionary containing workforce information:+ - node_id (str): Unique identifier of the workforce+ - description (str): Workforce description+ - mcp_description (str): MCP server description+ - children_count (int): Number of child workers+ - is_running (bool): Whether the workforce is active+ - pending_tasks_count (int): Number of queued tasks+ - current_task_id (str or None): ID of the active task++ Example:+ >>> info = get_workforce_info()+ >>> print(f"Running: {info['is_running']}")+ >>> print(f"Children: {info['children_count']}")+ """+ info = {+ "node_id": workforce_instance.node_id,+ "description": workforce_instance.description,+ "mcp_description": description,+ "children_count": len(workforce_instance._children),+ "is_running": workforce_instance._running,+ "pending_tasks_count": len(workforce_instance._pending_tasks),+ "current_task_id": (+ workforce_instance._task.id+ if workforce_instance._task+ else None+ ),+ }+ return info++ # Children info resource and tool+ def get_children_info():+ r"""Get information about all child nodes in the workforce.++ Retrieves comprehensive information about each child worker+ including their type, capabilities, and configuration details.++ Returns:+ List[Dict[str, Any]]: A list of dictionaries, each containing+ child node information with common keys:+ - node_id (str): Unique identifier of the child+ - description (str): Child node description+ - type (str): Type of worker (e.g., "SingleAgentWorker")++ Additional keys depend on worker type:++ For SingleAgentWorker:+ - tools (List[str]): Available tool names+ - role_name (str): Agent's role name++ For RolePlayingWorker:+ - assistant_role (str): Assistant agent role+ - user_role (str): User agent role+ - chat_turn_limit (int): Maximum conversation turns++ For Workforce:+ - children_count (int): Number of nested children+ - is_running (bool): Whether the nested workforce is active++ Example:+ >>> children = get_children_info()+ >>> for child in children:+ ... print(f"{child['type']}: {child['description']}")+ """+ children_info = []+ for child in workforce_instance._children:+ child_info = {+ "node_id": child.node_id,+ "description": child.description,+ "type": type(child).__name__,+ }++ if isinstance(child, SingleAgentWorker):+ child_info["tools"] = list(child.worker.tool_dict.keys())+ child_info["role_name"] = child.worker.role_name+ elif isinstance(child, RolePlayingWorker):+ child_info["assistant_role"] = child.assistant_role_name+ child_info["user_role"] = child.user_role_name+ child_info["chat_turn_limit"] = child.chat_turn_limit+ elif isinstance(child, Workforce):+ child_info["children_count"] = len(child._children)+ child_info["is_running"] = child._running++ children_info.append(child_info)++ return children_info++ # Add single agent worker+ def add_single_agent_worker(+ description,+ system_message=None,+ role_name="Assistant",+ agent_kwargs=None,+ ):+ r"""Add a single agent worker to the workforce.++ Creates and adds a new SingleAgentWorker to the workforce with+ the specified configuration. The worker cannot be added while+ the workforce is currently running.++ Args:+ description (str): Description of the worker's role and+ capabilities.+ system_message (str, optional): Custom system message for the+ agent. If None, a default message based on role_name is+ used. (default: :obj:`None`)+ role_name (str, optional): Name of the agent's role.+ (default: :obj:`"Assistant"`)+ agent_kwargs (Dict, optional): Additional keyword arguments+ to pass to the ChatAgent constructor, such as model+ configuration, tools, etc. (default: :obj:`None`)++ Returns:+ Dict[str, str]: A dictionary containing the operation result:+ - status (str): "success" or "error"+ - message (str): Descriptive message about the operation+ - worker_id (str): ID of the created worker (on success)++ Example:+ >>> result = add_single_agent_worker(+ ... "Data Analyst",+ ... "You are a data analysis expert.",+ ... "Analyst"+ ... )+ >>> print(result["status"]) # "success" or "error"+ """+ try:+ if workforce_instance._running:+ return {+ "status": "error",+ "message": "Cannot add workers while workforce is running", # noqa: E501+ }++ # Create agent with provided configuration+ sys_msg = BaseMessage.make_assistant_message(+ role_name=role_name,+ content=system_message or f"You are a {role_name}.",+ )++ agent = ChatAgent(sys_msg, **(agent_kwargs or {}))+ workforce_instance.add_single_agent_worker(description, agent)++ return {+ "status": "success",+ "message": f"Single agent worker '{description}' added",+ "worker_id": workforce_instance._children[-1].node_id,+ }+ except Exception as e:+ return {"status": "error", "message": str(e)}++ # Add role playing worker+ def add_role_playing_worker(+ description,+ assistant_role_name,+ user_role_name,+ chat_turn_limit=20,+ assistant_agent_kwargs=None,+ user_agent_kwargs=None,+ summarize_agent_kwargs=None,+ ):+ r"""Add a role playing worker to the workforce.++ Creates and adds a new RolePlayingWorker to the workforce that+ uses two agents in a conversational role-playing setup. The+ worker cannot be added while the workforce is currently running.++ Args:+ description (str): Description of the role playing worker's+ purpose and capabilities.+ assistant_role_name (str): Name/role of the assistant agent+ in the role playing scenario.+ user_role_name (str): Name/role of the user agent in the+ role playing scenario.+ chat_turn_limit (int, optional): Maximum number of+ conversation turns between the two agents.+ (default: :obj:`20`)+ assistant_agent_kwargs (Dict, optional): Keyword arguments+ for configuring the assistant ChatAgent, such as model+ type, tools, etc. (default: :obj:`None`)+ user_agent_kwargs (Dict, optional): Keyword arguments for+ configuring the user ChatAgent, such as model type,+ tools, etc. (default: :obj:`None`)+ summarize_agent_kwargs (Dict, optional): Keyword arguments+ for configuring the summarization agent used to process+ the conversation results. (default: :obj:`None`)++ Returns:+ Dict[str, str]: A dictionary containing the operation result:+ - status (str): "success" or "error"+ - message (str): Descriptive message about the operation+ - worker_id (str): ID of the created worker (on success)++ Example:+ >>> result = add_role_playing_worker(+ ... "Design Review Team",+ ... "Design Critic",+ ... "Design Presenter",+ ... chat_turn_limit=5+ ... )+ >>> print(result["status"]) # "success" or "error"+ """+ try:+ if workforce_instance._running:+ return {+ "status": "error",+ "message": "Cannot add workers while workforce is running", # noqa: E501+ }++ workforce_instance.add_role_playing_worker(+ description=description,+ assistant_role_name=assistant_role_name,+ user_role_name=user_role_name,+ chat_turn_limit=chat_turn_limit,+ assistant_agent_kwargs=assistant_agent_kwargs,+ user_agent_kwargs=user_agent_kwargs,+ summarize_agent_kwargs=summarize_agent_kwargs,+ )++ return {+ "status": "success",+ "message": f"Role playing worker '{description}' added",+ "worker_id": workforce_instance._children[-1].node_id,+ }+ except Exception as e:+ return {"status": "error", "message": str(e)}++ # Now register everything using decorators+ mcp_server.tool()(process_task)+ mcp_server.tool()(reset)+ mcp_server.tool()(add_single_agent_worker)+ mcp_server.tool()(add_role_playing_worker)++ mcp_server.resource("workforce://")(get_workforce_info)+ mcp_server.tool()(get_workforce_info)++ mcp_server.resource("children://")(get_children_info)+ mcp_server.tool()(get_children_info)++ return mcp_serverdiff --git a/docs/mintlify/reference/camel.societies.workforce.workforce.mdx b/docs/mintlify/reference/camel.societies.workforce.workforce.mdxindex 493a0ab62..2ee515986 100644--- a/docs/mintlify/reference/camel.societies.workforce.workforce.mdx+++ b/docs/mintlify/reference/camel.societies.workforce.workforce.mdx@@ -259,3 +259,32 @@ Creates a new instance of Workforce with the same configuration.**Returns:**Workforce: A new instance of Workforce with the same configuration.++<a id="camel.societies.workforce.workforce.Workforce.to_mcp"></a>++### to_mcp++```python+def to_mcp(+ self,+ name: str = 'CAMEL-Workforce',+ description: str = 'A workforce system using the CAMEL AI framework for multi-agent collaboration.',+ dependencies: Optional[List[str]] = None,+ host: str = 'localhost',+ port: int = 8001+):+```++Expose this Workforce as an MCP server.++**Parameters:**++- **name** (str): Name of the MCP server. (default: :obj:`CAMEL-Workforce`)+- **description** (str): Description of the workforce. If None, a generic description is used. (default: :obj:`A workforce system using the CAMEL AI framework for multi-agent collaboration.`)+- **dependencies** (Optional[List[str]]): Additional dependencies for the MCP server. (default: :obj:`None`)+- **host** (str): Host to bind to for HTTP transport. (default: :obj:`localhost`)+- **port** (int): Port to bind to for HTTP transport. (default: :obj:`8001`)++**Returns:**++ FastMCP: An MCP server instance that can be run.diff --git a/examples/workforce/simple_workforce_mcp.py b/examples/workforce/simple_workforce_mcp.pynew file mode 100644index 000000000..3403a46d9--- /dev/null+++ b/examples/workforce/simple_workforce_mcp.py@@ -0,0 +1,70 @@+# ========= 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. =========++"""+Simple example showing how to run a Workforce as an MCP server.++To test this example:+1. Install dependencies: pip install mcp camel-ai[all]+2. Run this script: python simple_workforce_mcp.py+3. The server will start on localhost:8001+4. Use an MCP client to connect and test the tools++Example MCP client usage:+- Call process_task with task_content="Analyze market trends"+- Call get_workforce_info to see workforce status+- Call add_single_agent_worker to add new workers+"""++from camel.agents import ChatAgent+from camel.messages import BaseMessage+from camel.societies.workforce import Workforce+++def main():+ """Create and run a simple workforce MCP server."""++ # Create a basic workforce+ workforce = Workforce(description="Simple Analysis Team")++ # Add a basic analyst worker+ analyst_msg = BaseMessage.make_assistant_message(+ role_name="Analyst",+ content="You are a helpful analyst who can process various tasks.",+ )+ analyst = ChatAgent(system_message=analyst_msg)+ workforce.add_single_agent_worker(+ description="General purpose analyst", worker=analyst+ )++ print("Creating Workforce MCP server...")+ print("Server will be available at: http://localhost:8001")+ print("Press Ctrl+C to stop the server")++ # Convert to MCP server and run+ mcp_server = workforce.to_mcp(+ name="Simple-Workforce",+ description="A simple workforce for task processing",+ port=8001,+ )++ try:+ # This will start the server and block+ mcp_server.run()+ except KeyboardInterrupt:+ print("\nServer stopped.")+++if __name__ == "__main__":+ main()