CAMEL Cookbook: SQL MCP Server
You can also check this cookbook in Google Colab.
⭐ Star us on GitHub, join our Discord, or follow us on X
This cookbook demonstrates how to use CAMEL AI agents to interact with an SQL database using natural language. We’ll achieve this by connecting CAMEL to a local SQL Model Control Protocol (MCP) server that you provide. This setup allows the CAMEL agent to leverage MCP for database operations like querying data, listing tables, and describing schemas, all triggered by conversational prompts.
Key Learnings:
- Understanding the role of MCP in CAMEL for tool usage.
- Setting up the CAMEL environment and necessary API keys.
- Preparing a local Python script (
sql_server_mcp.py
) to act as your SQL MCP server. - Configuring CAMEL to connect to and utilize this local MCP server.
- Creating a sample SQLite database.
- Interacting with the database using natural language queries through a CAMEL agent.
This approach focuses on using CAMEL with an MCP server that runs as a separate Python process, managed by CAMEL’s _MCPServer
utility.
📦 Installation
First, install the CAMEL package with all its dependencies:
🔑 Setting Up API Keys
This cookbook uses OpenRouter as the model provider, which gives us access to various LLMs including Claude and Gemini. You’ll need an OpenRouter API key.
- Sign up at OpenRouter
- Get your API key from the dashboard
- The script will prompt you for the API key when running
Required Configuration Files
Before running the code, you need to set up two important configuration files in your working directory:
1. MCP Configuration File (mcp_config.json
)
Create a file named mcp_config.json
with the following content:
This configuration tells CAMEL how to start and communicate with your SQL MCP server.
2. SQL MCP Server Script (sql_server_mcp.py
)
Create a file named sql_server_mcp.py
in your working directory. This script will handle all database operations:
You can download and configure the script here
Understanding MCP and Your Local SQL MCP Server
What is MCP?
MCP (Model Control Protocol) is a specification that allows Large Language Models (LLMs) to interact with external tools and services in a standardized way. In CAMEL, MCPToolkit
enables agents to discover and use tools exposed by MCP-compliant servers. This cookbook focuses on using a Python-based MCP server that you’ll run locally.
Your sql_server_mcp.py
Script
For this cookbook to function, you need to have a Python script named sql_server_mcp.py
in the same directory as this notebook (or where you execute the Python code derived from this markdown).
This script is responsible for the direct database interactions. It should:
- Use
mcp.server.fastmcp.FastMCP
(from themodelcontextprotocol
Python SDK) to define an MCP server instance (e.g.,mcp = FastMCP("sqldb")
). - Define Python functions for database operations, such as:
execute_query(connection_string: str, query: str) -> str
: Executes a given SQL query.list_tables(connection_string: str) -> str
: Lists tables in a database.describe_table(connection_string: str, table_name: str) -> str
: Describes a table’s schema.
- Decorate these functions with
@mcp.tool()
to expose them as tools to the LLM. Each tool should also have aninputSchema
defined to guide the LLM on how to use it. - Include a
main
section (if __name__ == "__main__":
) that runs the MCP server (e.g.,mcp.run(transport='stdio')
).## Understanding MCP and Your Local SQL MCP Server
This tool handles:
- Connecting to a SQLite database
- Executing a SQL query
- Handling different types of queries (SELECT vs. non-SELECT)
- Formatting results as JSON
- Error handling
The inputSchema
defines the required parameters and provides descriptions that help the LLM understand how to use the tool.
This simple tool creates empty SQLite databases that can later be populated with tables and data.
This cookbook will demonstrate how CAMEL’s _MCPServer
utility launches and communicates with your sql_server_mcp.py
script using the Python interpreter.
Creating a Sample Database
Let’s create a local SQLite database (sample.db
) that our agent will interact with. This database will contain employees
and departments
tables.
Creating the CAMEL Agent
Now let’s create our CAMEL agent that will interact with the database. Save this as mcp_camel.py
:
Running the Example
-
Make sure you have all three required files in your directory:
mcp_config.json
sql_server_mcp.py
mcp_camel.py
-
Create and populate the database by running the database setup code
-
Run the CAMEL agent:
-
When prompted, enter your OpenRouter API key
The agent will then:
- Connect to the local MCP server
- Use the provided tools to interact with the database
- Display the results in a human-readable format
Example Output -
Enter your OpenRouter API key: Agent: I’ll help you explore the database by first listing all tables and then examining their contents.
Let’s start by listing the tables in the database:
Based on the response, the database contains the following tables:
- customers
- orders
- products
Now, let’s examine the schema of each table to understand their structure:
The customers table has the following columns:
- id (INTEGER): Primary key
- name (TEXT): Customer name
- email (TEXT): Customer email
- address (TEXT): Customer address
The orders table has the following columns:
- id (INTEGER): Primary key
- customer_id (INTEGER): Foreign key referencing customers
- product_id (INTEGER): Foreign key referencing products
- quantity (INTEGER): Order quantity
- order_date (TEXT): Date of the order
The products table has the following columns:
- id (INTEGER): Primary key
- name (TEXT): Product name
- price (REAL): Product price
- category (TEXT): Product category
To summarize:
- The database contains 3 tables: customers, products, and orders
- The customers table has 5 customers with their contact information
- The products table has 6 products with pricing and category information
- The orders table has 10 orders linking customers to products with quantity and date information
Example Queries
You can modify the user_question
in mcp_camel.py
to ask different questions, such as:
- “What tables are in the database?”
- “Show me all customers and their orders”
- “How many products do we have in stock?”
- “List all orders with their items and total amounts”
Conclusion
In this cookbook, you’ve learned how to:
- Set up a complete MCP-based database interaction system
- Create and configure the necessary files (
mcp_config.json
andsql_server_mcp.py
) - Build a CAMEL agent that can understand and execute database operations
- Use OpenRouter to access powerful language models
- Handle database operations safely through MCP tools
This pattern can be extended to other types of databases or services by modifying the MCP server implementation while keeping the same CAMEL agent interface.
That’s everything: Got questions about 🐫 CAMEL-AI? Join us on Discord! 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! 🤝
Check out some of our other work:
-
🐫 Creating Your First CAMEL Agent free Colab
-
Graph RAG Cookbook free Colab
-
🧑⚖️ Create A Hackathon Judge Committee with Workforce free Colab
-
🔥 3 ways to ingest data from websites with Firecrawl & CAMEL free Colab
-
🦥 Agentic SFT Data Generation with CAMEL and Mistral Models, Fine-Tuned with Unsloth free Colab
Thanks from everyone at 🐫 CAMEL-AI
⭐ Star us on GitHub, join our Discord, or follow us on X