🐫 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: Agent to mcp (#2457)
Xiaotian Jin2ea62bfae053
diff --git a/camel/agents/chat_agent.py b/camel/agents/chat_agent.pyindex dc6b3a2ad..22be47d71 100644--- a/camel/agents/chat_agent.py+++ b/camel/agents/chat_agent.py@@ -75,7 +75,10 @@ from camel.types import (RoleType,)from camel.types.agents import ToolCallingRecord-from camel.utils import get_model_encoding+from camel.utils import (+ get_model_encoding,+ model_from_json_schema,+)if TYPE_CHECKING:from camel.terminators import ResponseTerminator@@ -1706,3 +1709,147 @@ class ChatAgent(BaseAgent):return (f"ChatAgent({self.role_name}, {self.role_type}, {self.model_type})")++ def to_mcp(+ self,+ name: str = "CAMEL-ChatAgent",+ description: str = "A helpful assistant using the CAMEL AI framework.",+ dependencies: Optional[List[str]] = None,+ host: str = "localhost",+ port: int = 8000,+ ):+ r"""Expose this ChatAgent as an MCP server.++ Args:+ name (str): Name of the MCP server.+ (default: :obj:`CAMEL-ChatAgent`)+ description (Optional[List[str]]): Description of the agent. If+ None, a generic description is used. (default: :obj:`A helpful+ assistant using the CAMEL AI framework.`)+ 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:`8000`)++ Returns:+ FastMCP: An MCP server instance that can be run.+ """+ try:+ from mcp.server.fastmcp import FastMCP+ except ImportError:+ raise ImportError(+ "The 'mcp' package is required to use the to_mcp method. "+ "Install it with 'pip install mcp'."+ )++ # 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 agent reference+ agent_instance = self++ # Define functions first+ async def step(message, response_format=None):+ r"""Execute a single step in the chat session with the agent."""+ format_cls = None+ if response_format:+ format_cls = model_from_json_schema(+ "DynamicResponseFormat", response_format+ )+ response = await agent_instance.astep(message, format_cls)+ return {+ "status": "success",+ "messages": [msg.to_dict() for msg in response.msgs],+ "terminated": response.terminated,+ "info": response.info,+ }++ # Reset tool+ def reset():+ r"""Reset the chat agent to its initial state."""+ agent_instance.reset()+ return {"status": "success", "message": "Agent reset successfully"}++ # Set language tool+ def set_output_language(language):+ r"""Set the output language for the chat agent."""+ agent_instance.output_language = language+ return {+ "status": "success",+ "message": f"Output language set to '{language}'",+ }++ # Agent info resource and tool+ def get_agent_info():+ r"""Get information about the agent."""+ info = {+ "agent_id": agent_instance.agent_id,+ "model_type": str(agent_instance.model_type),+ "role_name": agent_instance.role_name,+ "role_type": str(agent_instance.role_type),+ "output_language": agent_instance.output_language or "None",+ "description": description,+ }+ return info++ # Chat history resource and tool+ def get_chat_history():+ r"""Get the chat history for the agent."""+ # Convert messages to simple serializable format+ messages = []+ for msg in agent_instance.chat_history:+ # Create a simplified version of each message+ msg_dict = {+ "role": msg.get("role", ""),+ "content": msg.get("content", ""),+ }+ # Include function calls if present+ if "function_call" in msg:+ msg_dict["function_call"] = {+ "name": msg["function_call"].get("name", ""),+ "arguments": msg["function_call"].get("arguments", ""),+ }+ messages.append(msg_dict)+ return messages++ # Available tools resource and tool+ def get_available_tools():+ r"""Get a list of available internal tools."""+ tool_info = {}+ for name, tool in agent_instance.tool_dict.items():+ tool_info[name] = {+ "name": name,+ "description": tool.get_function_description() or "",+ "parameters": [+ {"name": param_name, "type": str(param_type)}+ for param_name, param_type in tool.get_parameters().items() # noqa: E501+ ],+ }+ return tool_info++ # Now register everything using decorators+ mcp_server.tool()(step)+ mcp_server.tool()(reset)+ mcp_server.tool()(set_output_language)++ mcp_server.resource("agent://")(get_agent_info)+ mcp_server.tool()(get_agent_info)++ mcp_server.resource("history://")(get_chat_history)+ mcp_server.tool()(get_chat_history)++ mcp_server.resource("tools://")(get_available_tools)+ mcp_server.tool()(get_available_tools)++ return mcp_serverdiff --git a/examples/agent/mcp/agent_to_mcp.py b/examples/agent/mcp/agent_to_mcp.pynew file mode 100644index 000000000..1090e5faf--- /dev/null+++ b/examples/agent/mcp/agent_to_mcp.py@@ -0,0 +1,28 @@+# ========= 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. =========+from camel.agents import ChatAgent++# Create a chat agent with a model+agent = ChatAgent(model="gpt-4o-mini")+++# Create an MCP server from the agent+mcp_server = agent.to_mcp(+ name="demo", description="A demonstration of ChatAgent to MCP conversion"+)++# Run the server+if __name__ == "__main__":+ print("Starting MCP server on http://localhost:8000")+ mcp_server.run(transport="streamable-http")