{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [] }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "markdown", "source": [ "# CAMEL MCP Cookbook" ], "metadata": { "id": "ymsq1Lw0VEqT" } }, { "cell_type": "markdown", "source": [ "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1A5SOw99OslgHt0ibX3Y9Zywive3hu-G1?usp=sharing) (Use the colab share link)" ], "metadata": { "id": "7V3aV16AmY0K" } }, { "cell_type": "markdown", "source": [ "
" ], "metadata": { "id": "UvHRdXwflAz-" } }, { "cell_type": "markdown", "source": [ "This notebook demonstrates how to set up and leverage CAMEL's MCP function module.\n", "\n", "In this notebook, you'll explore:\n", "\n", "* **CAMEL**: A powerful multi-agent framework that enables Retrieval-Augmented Generation and multi-agent role-playing scenarios, allowing for sophisticated AI-driven tasks.\n", "* **MCP**: Model Context Protocol, introduced by Anthropic in 2024 to formalize tool interaction using JSON-RPC 2.0 standard.\n", "\n", "\n", "This setup not only demonstrates a practical application but also serves as a flexible framework that can be adapted for various scenarios requiring using MCP tools." ], "metadata": { "id": "G5gE04UuPUWj" } }, { "cell_type": "markdown", "source": [ "## 📦 Installation" ], "metadata": { "id": "0J0_iW-YVcq2" } }, { "cell_type": "markdown", "source": [ "First, install the CAMEL package with all its dependencies:" ], "metadata": { "id": "7p-JjpyNVcCT" } }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "id": "0GXs2pruU9Vl" }, "outputs": [], "source": [ "!pip install \"camel-ai[all]==0.2.58\"" ] }, { "cell_type": "markdown", "source": [ "## 🔑 Setting Up API Keys" ], "metadata": { "id": "lfNvFbhD6o8B" } }, { "cell_type": "markdown", "source": [ "You'll need to set up your API keys for OpenAI. This ensures that the tools can interact with external services securely." ], "metadata": { "id": "jqV12oQfQTyl" } }, { "cell_type": "markdown", "source": [ "You can go to [here](https://app.agentops.ai/signin) to get **free** API Key from AgentOps\n" ], "metadata": { "id": "Sc3MAQwiH9Pd" } }, { "cell_type": "code", "source": [ "import os\n", "from getpass import getpass" ], "metadata": { "id": "HQ_yOT5_Hyt4" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "Your can go to [here](https://console.mistral.ai/api-keys/) to get API Key from Mistral AI with **free** credits." ], "metadata": { "id": "czxWvnvnAimt" } }, { "cell_type": "code", "source": [ "# Prompt for the API key securely\n", "openai_api_keys = getpass('Enter your API key: ')\n", "os.environ[\"OPENAI_API_KEY\"] = openai_api_keys" ], "metadata": { "id": "T0FBl1WF6jFs", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "7583b638-9c7f-4190-a34e-ad8beb1f4c60" }, "execution_count": null, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter your API key: ··········\n" ] } ] }, { "cell_type": "markdown", "source": [ "## PART I: Understanding the Model Context Protocol (MCP)" ], "metadata": { "id": "NEUciNquON9_" } }, { "cell_type": "markdown", "source": [ "### Brief History of Function Calling" ], "metadata": { "id": "46Irp_SurLaV" } }, { "cell_type": "markdown", "source": [ "- **Pre-2023 - When LLMs Lacked Environmental Awareness**:\n", " - Tool usage implemented via prompt engineering\n", " - Support provided at framework level (e.g., LangChain, CAMEL agents)\n", " - No native capabilities; relied on parsing unstructured model outputs\n", "- **June 2023 – OpenAI Launches Native Function Calling**:\n", " - Introduced in GPT-4 and GPT-3.5-turbo\n", " - Utilized structured JSON outputs to call tools and pass arguments\n", " - Enabled significantly more reliable and scalable tool integration\n", "- **Nov 2024 – Anthropic Proposes MCP (Model Context Protocol)**:\n", " - Formalizes tool interaction using JSON-RPC 2.0 standard\n", " - Standardizes communication between AI systems and external tools/resources\n", "- **2025 – Industry-Wide Adoption**:\n", " - OpenAI, DeepMind, and other major players adopt MCP\n", " - Function calling becomes a core capability for advanced agentic AI systems" ], "metadata": { "id": "QVB-Xra8QIU1" } }, { "cell_type": "markdown", "source": [ "The MCP empowers the standardization of the function calling:" ], "metadata": { "id": "Ca9WEHP_P0of" } }, { "cell_type": "markdown", "source": [ "" ], "metadata": { "id": "DkSMWPqTBvGT" } }, { "cell_type": "markdown", "source": [ "### How Does MCP Work?" ], "metadata": { "id": "sDPlOQSVQq_5" } }, { "cell_type": "markdown", "source": [ "- **MCP Hosts**: Claude Desktop App, CAMEL agents, and other deployment environments\n", "- **MCP Clients**: Internal protocol engines that handle sending/receiving JSON-RPC messages\n", "- **MCP Servers**: Programs that process incoming messages from clients and return structured responses" ], "metadata": { "id": "gnHdjJcGQlN4" } }, { "cell_type": "markdown", "source": [ "" ], "metadata": { "id": "bn-W7gG9QyEW" } }, { "cell_type": "markdown", "source": [ "### MCP Ecosystem\n", "\n", "MCP is gradually becoming a standard. Here are some useful MCP repositories:\n", "\n", "- ACI.dev\n", "- Smithery\n", "- Composio\n", "- mcp.run\n", "- ModelScope\n", "- Awesome MCP Servers\n" ], "metadata": { "id": "GA_DVZU8TCPb" } }, { "cell_type": "markdown", "source": [ "# PART II: CAMEL's Integration Efforts with MCP\n", "\n", "## CAMEL's Integration with MCP\n", "\n", "In this section, we'll explore how CAMEL is integrating with the Model Context Protocol to create a more powerful and flexible agent framework. Here's what we'll cover:\n", "\n", "1. Agent using MCP tools\n", "2. Export CAMEL existing tools as MCP servers\n", "3. MCP search toolkits/ MCP search agents\n", "4. Export CAMEL agents as MCP servers\n", "5. Future plans\n", "\n", "Let's dive into each of these areas to understand how CAMEL is embracing the MCP ecosystem." ], "metadata": { "id": "6RCQWFdnTJ7h" } }, { "cell_type": "markdown", "source": [ "## Hands-on with CAMEL Agents and Tools" ], "metadata": { "id": "3GuqmGe0TRM7" } }, { "cell_type": "code", "source": [ "from camel.models import ModelFactory\n", "from camel.agents import ChatAgent\n", "from camel.types import ModelPlatformType, ModelType\n", "from camel.configs import ChatGPTConfig" ], "metadata": { "id": "kc5gIQZ6VS3X" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "from camel.toolkits import FunctionTool\n", "\n", "def my_weird_add(a: int, b: int) -> int:\n", " r\"\"\"Adds two numbers and includes a constant offset.\n", " Args:\n", " a (int): The first number to be added.\n", " b (int): The second number to be added.\n", " Returns:\n", " integer: The sum of the two numbers plus 7.\n", " \"\"\"\n", " return a + b + 7\n", "\n", "model = ModelFactory.create(\n", " model_platform=ModelPlatformType.OPENAI,\n", " model_type=ModelType.GPT_4O,\n", " api_key = openai_api_keys\n", ")\n", "\n", "agent = ChatAgent(\n", " model=model,\n", " tools=[FunctionTool(my_weird_add)]\n", ")\n", "\n", "response = agent.step(\"What is 15+15\")\n", "print(response.msgs[0].content)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "GwmfU6OvVV_h", "outputId": "af162aa8-b5e8-43cc-8918-dd854ea37f1c" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "15 + 15 is 30. However, using a specific calculation with an added constant offset, the result is 37.\n" ] } ] }, { "cell_type": "markdown", "source": [ "### Hands-on with CAMEL Agents using MCP Servers" ], "metadata": { "id": "vsS2Noj_v3nv" } }, { "cell_type": "markdown", "source": [ "Here, we will use Time MCP Server as an example.\n", "\n", "First, we need to provide config file for the agent, stored in a separated file, in this case:" ], "metadata": { "id": "OZS8WpGOwFrj" } }, { "cell_type": "markdown", "source": [ "```{json}\n", "{\n", " \"mcpServers\": {\n", " \"time\": {\n", " \"command\": \"uvx\",\n", " \"args\": [\"mcp-server-time\", \"--local-timezone=Asia/Riyadh\"]\n", " }\n", " }\n", "}\n", "```" ], "metadata": { "id": "sbkuAbm6wI8m" } }, { "cell_type": "code", "source": [ "import asyncio\n", "from camel.toolkits.mcp_toolkit import MCPToolkit\n", "\n", "async def run_time_example():\n", " # Initialize the MCPToolkit with your configuration file\n", " mcp_toolkit = MCPToolkit(config_path=\"config/time.json\")\n", " # Connect to all configured MCP servers\n", " await mcp_toolkit.connect()\n", " camel_agent = ChatAgent(\n", " model=model,\n", " tools=[*mcp_toolkit.get_tools()],\n", " )\n", " response = await camel_agent.astep(\"What time is it now?\")\n", " print(response.msgs[0].content)\n", " print(response.info['tool_calls'])\n", " # Disconnect from all servers\n", " await mcp_toolkit.disconnect()" ], "metadata": { "id": "wSXWTriDwAAL" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "Since Jupyter does not support file I/O, we put the expected results here, you can try to run this async function locally:\n", "\n", "The current local time in Riyadh is 15:57 (3:57 PM).\n", "\n", "[ToolCallingRecord(tool_name='get_current_time', args={'timezone': 'Asia/Riyadh'}, result='{\\n \"timezone\": \"Asia/Riyadh\",\\n \"datetime\": \"2025-05-01T15:57:59+03:00\",\\n \"is_dst\": false\\n}', tool_call_id='toolu_01Gwdy3Ppzf2z42t6YL7n7cE')]" ], "metadata": { "id": "Rl2mNFimydjL" } }, { "cell_type": "markdown", "source": [ "### Creating an MCP Server from a Toolkit\n", "\n", "This functionality is for converting existing CAMEL toolkits to MCP servers, using just a few lines of code\n", "\n", "```{python}\n", "toolkit = ArxivToolkit(timeout=args.timeout) # existing toolkit\n", " # Run the toolkit as an MCP server\n", " toolkit.mcp.run(args.mode)\n", "```\n", "\n", "For more details you can see here:\n", "Converting CAMEL Tools to MCP Tools" ], "metadata": { "id": "6Kk-DC9Ryy88" } }, { "cell_type": "markdown", "source": [ "### MCP Search Toolkits (using Pulse)" ], "metadata": { "id": "NexAMDTjzbep" } }, { "cell_type": "markdown", "source": [ "There are tons of MCP servers implemented, now we need tools to search for the useful ones! In CAMEL, we can do it by using `MCPSearchToolkit`" ], "metadata": { "id": "9JFVy5CQ3ufQ" } }, { "cell_type": "markdown", "source": [ "```\n", "search_toolkit = PulseMCPSearchToolkit()\n", "search_toolkit.search_mcp_servers(\n", " query=\"Slack\",\n", " package_registry=\"npm\", # Only search for servers registered in npm\n", " top_k=1,\n", ")\n", "```" ], "metadata": { "id": "xfedee1Z0MdI" } }, { "cell_type": "markdown", "source": [ "Expected output:\n", "```\n", "{\n", " \"name\": \"Slack\",\n", " \"url\": \"https://www.pulsemcp.com/servers/slack\",\n", " \"external_url\": null,\n", " \"short_description\": \"Send messages, manage channels, and access workspace history.\",\n", " \"source_code_url\": \"https://github.com/modelcontextprotocol/servers/tree/HEAD/src/slack\",\n", " \"github_stars\": 41847,\n", " \"package_registry\": \"npm\",\n", " \"package_name\": \"@modelcontextprotocol/server-slack\",\n", " \"package_download_count\": 188989,\n", " \"EXPERIMENTAL_ai_generated_description\": \"This Slack MCP Server, developed by the Anthropic team, provides a robust interface for language models to interact with Slack workspaces. It enables AI agents to perform a wide range of Slack-specific tasks including listing channels, posting messages, replying to threads, adding reactions, retrieving channel history, and accessing user information. The implementation distinguishes itself by offering comprehensive Slack API integration, making it ideal for AI-driven workplace communication and automation. By leveraging Slack's Bot User OAuth Tokens, it ensures secure and authorized access to workspace data. This tool is particularly powerful for AI assistants designed to enhance team collaboration, automate routine communication tasks, and provide intelligent insights from Slack conversations.\"\n", "}\n", "```" ], "metadata": { "id": "C35hlrU70SQD" } }, { "cell_type": "markdown", "source": [ "### MCP Search Agents\n", "\n", "The MCP search agents are more than just searching for MCP tools, but also able to execute them. Here we use - Smithery MCP registry as the example.\n", "\n", "It can automatically search and connects to the Brave MCP servers, and use it to help us search information!" ], "metadata": { "id": "KWmfBmpmziZU" } }, { "cell_type": "markdown", "source": [ "\n", "```\n", "from camel.agents import MCPAgent, MCPRegistryConfig, MCPRegistryType\n", "smithery_config = MCPRegistryConfig(\n", " type=MCPRegistryType.SMITHERY,\n", " api_key=os.getenv(\"SMITHERY_API_KEY\")\n", ")\n", "\n", "# Create MCPAgent with registry configurations\n", "agent = MCPAgent(\n", " model=model,\n", " registry_configs=[smithery_config]\n", ")\n", "\n", "async with agent:\n", " message = \"Use Brave API to search info about CAMEL-AI.org\"\n", " response = await agent.astep(message)\n", " print(f\"\\nResponse from {message}:\")\n", " print(response.msgs[0].content)\n", "```" ], "metadata": { "id": "E-dtNYHj1ax8" } }, { "cell_type": "markdown", "source": [ "Expected output:" ], "metadata": { "id": "-93zZd0j14oi" } }, { "cell_type": "markdown", "source": [], "metadata": { "id": "FXT4Su2J6fAh" } }, { "cell_type": "code", "source": [ "Response from Use Brave MCP search tools to search info about CAMEL-AI.org.:\n", " # CAMEL-AI.org: Information and Purpose\n", " Based on my search results, here's what I found about CAMEL-AI.org:\n", " ## Organization Overview\n", " CAMEL-AI.org is the first LLM (Large Language Model) multi-agent framework and\n", " an open-source community. The name CAMEL stands for \"Communicative Agents for\n", " Mind Exploration of Large Language Model Society.\"\n", " ## Core Purpose\n", " The organization is dedicated to \"Finding the Scaling Law of Agents\" - this\n", " appears to be their primary research mission, focusing on understanding how\n", " agent-based AI systems scale and develop.\n", " ## Research Focus\n", " CAMEL-AI is a research-driven organization that explores:\n", " - Scalable techniques for autonomous cooperation among communicative agents\n", " - Multi-agent frameworks for AI systems\n", " - Data generation for AI training\n", " - AI society simulations\n", " ## Community and Collaboration\n", " - They maintain an active open-source community\n", " - They invite contributors and collaborators through platforms like Slack and\n", " Discord\n", " - The organization has a research collaboration questionnaire for those\n", " interested in building or researching environments for LLM-based agents\n", " ## Technical Resources\n", " - Their code is available on GitHub (github.com/camel-ai) with 18 repositories\n", " - They provide documentation for developers and researchers at\n", " docs.camel-ai.org\n", " - They offer tools and cookbooks for working with their agent framework\n", " ## Website and Online Presence\n", " - Main website: https://www.camel-ai.org/\n", " - GitHub: https://github.com/camel-ai\n", " - Documentation: https://docs.camel-ai.org/\n", " The organization appears to be at the forefront of research on multi-agent AI\n", " systems, focusing on how these systems can cooperate autonomously and scale\n", " effectively." ], "metadata": { "id": "ntVWxZHJ1gYv" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "### Agent as MCP servers" ], "metadata": { "id": "xYyMdH1V18TZ" } }, { "cell_type": "markdown", "source": [ "Now you can ship your favourite CAMEL agents as MCP servers! Then you can use other MCP clients to interact with it, like Claude, Cursor, etc." ], "metadata": { "id": "Y3aJTSOY4TCy" } }, { "cell_type": "code", "source": [ "# In services/agent_config.py\n", "# Create a default chat agent - customize as needed\n", "chat_agent = ChatAgent()\n", "chat_agent_description = \"A general-purpose assistant that can answer questions and help with various tasks.\"\n", "\n", "reasoning_agent = ChatAgent(\n", " model=ModelFactory.create(\n", " model_platform=ModelPlatformType.OPENAI,\n", " model_type=\"gpt-4o-mini\",\n", " )\n", ")\n", "reasoning_agent_description = \"A specialized assistant focused on logical reasoning and problem-solving.\"\n", "\n", "# Create another agent for searching the web\n", "from camel.toolkits import SearchToolkit\n", "search_agent = ChatAgent(\n", " model=ModelFactory.create(\n", " model_platform=ModelPlatformType.OPENAI,\n", " model_type=\"gpt-4o\",\n", " ),\n", " tools=[FunctionTool(SearchToolkit().search_brave)],\n", ")\n", "search_agent_description = \"A research assistant capable of retrieving information from the web.\"\n", "\n", "# Provide a list of agents with names\n", "agents_dict = {\n", " \"general\": chat_agent,\n", " \"search\": search_agent,\n", " \"reasoning\": reasoning_agent,\n", "}\n", "\n", "# Provide descriptions for each agent\n", "description_dict = {\n", " \"general\": chat_agent_description,\n", " \"search\": search_agent_description,\n", " \"reasoning\": reasoning_agent_description,\n", "}" ], "metadata": { "id": "FAb-BjQj2A1s" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "Provide config file to the MCP clients, in this cookbook, we use Claude Desktop as example:" ], "metadata": { "id": "Mr4C5Imf2SbZ" } }, { "cell_type": "markdown", "source": [ "```\n", "\"camel-chat-agent\": {\n", " \"command\": \"/Users/jinx0a/micromamba/bin/python\",\n", " \"args\": [\n", " \"/Users/jinx0a/Repo/camel/services/agent_mcp_server.py\"\n", " ],\n", " \"env\": {\n", " \"OPENAI_API_KEY\": \"...\",\n", " \"OPENROUTER_API_KEY\": \"...\",\n", " \"BRAVE_API_KEY\": \"...\"\n", " }\n", "}\n", "```" ], "metadata": { "id": "HIQAH6D82ZVo" } }, { "cell_type": "markdown", "source": [ "After Claude successfully loaded the tools, now you can use Claude to interact with CAMEL Agents! Attached are some screenshots of calling agents inside Claude." ], "metadata": { "id": "geAlgGLy2f1_" } }, { "cell_type": "markdown", "source": [ "" ], "metadata": { "id": "96vaSC9j2dIT" } }, { "cell_type": "markdown", "source": [ "" ], "metadata": { "id": "B7SOQ3yt2uov" } }, { "cell_type": "markdown", "source": [ "" ], "metadata": { "id": "lEiSFX9I2xBO" } }, { "cell_type": "markdown", "source": [ "### Ongoing MCP Developments\n", "\n", "- **MCP Search Agents**: Integration with additional MCP registries, e.g., ACI.dev, Composio\n", "- **MCP Hub**: Hosting and validating our own repository of MCP servers\n", "- **Role-Playing/Workforce as MCP Servers**: Transforming CAMEL's multi-agent module into MCP servers" ], "metadata": { "id": "nQG70LLG245T" } }, { "cell_type": "markdown", "source": [ "## 🌟 Highlights" ], "metadata": { "id": "flYNal6-R4yR" } }, { "cell_type": "markdown", "source": [ "This notebook has guided you through the MCP related functions and modules in CAMEL, including:" ], "metadata": { "id": "SmkXhy4JR726" } }, { "cell_type": "markdown", "source": [ "- Agent using MCP servers\n", "- Convert tools into MCP servers\n", "- MCP search toolkits / agents\n", "- Agent as MCP servers\n", "\n", "In the future, we will have more MCP features coming!!" ], "metadata": { "id": "WgDsfd953F2W" } }, { "cell_type": "markdown", "source": [ "That's everything: Got questions about 🐫 CAMEL-AI? Join us on [Discord](https://discord.camel-ai.org)! Whether you want to share feedback, explore the latest in multi-agent systems, get support, or connect with others on exciting projects, we’d love to have you in the community! 🤝\n", "\n", "Check out some of our other work:\n", "\n", "1. 🐫 Creating Your First CAMEL Agent [free Colab](https://docs.camel-ai.org/cookbooks/create_your_first_agent.html)\n", "\n", "2. Graph RAG Cookbook [free Colab](https://colab.research.google.com/drive/1uZKQSuu0qW6ukkuSv9TukLB9bVaS1H0U?usp=sharing)\n", "\n", "3. 🧑⚖️ Create A Hackathon Judge Committee with Workforce [free Colab](https://colab.research.google.com/drive/18ajYUMfwDx3WyrjHow3EvUMpKQDcrLtr?usp=sharing)\n", "\n", "4. 🔥 3 ways to ingest data from websites with Firecrawl & CAMEL [free Colab](https://colab.research.google.com/drive/1lOmM3VmgR1hLwDKdeLGFve_75RFW0R9I?usp=sharing)\n", "\n", "5. 🦥 Agentic SFT Data Generation with CAMEL and Mistral Models, Fine-Tuned with Unsloth [free Colab](https://colab.research.google.com/drive/1lYgArBw7ARVPSpdwgKLYnp_NEXiNDOd-?usp=sharingg)\n", "\n", "Thanks from everyone at 🐫 CAMEL-AI\n", "\n", "\n", "\n" ], "metadata": { "id": "s6Det-fcMb9A" } } ] }