AI Agent
This documentation explains the concepts of AI Agents and the Model Context Protocol (MCP), and how you can leverage them with AI2sql for advanced data intelligence and automation.
What You'll Learn
- AI Agents - Autonomous software entities that can perceive, reason, and take actions to achieve specific goals.
- Model Context Protocol (MCP) - A standardized framework for structuring AI interactions with data and queries.
- Practical Implementation - How to use these technologies with AI2sql to generate optimized database queries.
Key Benefits
- Simplified Data Access - Query databases using natural language without SQL expertise
- Improved Query Quality - Generate optimized SQL with intelligent context handling
- Consistent Results - Standardized protocols ensure reliable query generation
- Enhanced Productivity - Reduce time spent writing and debugging complex queries
What is an AI Agent?
An AI Agent is an autonomous software entity that can perceive its environment, reason about it, and take actions to achieve specific goals. In the context of data and analytics, AI Agents can:
- Interpret user queries in natural language
- Generate and optimize SQL queries
- Interact with databases and APIs
- Learn from feedback and improve over time
- Automate complex workflows across multiple systems
- Make context-aware decisions based on historical data and current inputs
Types of AI Agents
AI Agents come in various forms, each with specific capabilities tailored to different use cases:
Query Agents
Specialized in interpreting natural language questions and translating them into database queries. AI2sql uses this type of agent to generate accurate SQL from your questions.
Autonomous Agents
These agents can perform complex multi-step tasks with minimal supervision, making them ideal for data pipeline automation and continuous monitoring.
Assistant Agents
Interactive agents that engage with users through conversation, helping to refine queries, explain results, and guide data exploration processes.
Specialized Agents
Domain-specific agents with deep expertise in particular industries or data types, such as financial analytics, healthcare data, or marketing metrics.
How AI Agents Work
AI Agents follow a structured workflow to process and respond to user requests:
- Perception: The agent receives input from the user or environment (e.g., a natural language query).
- Reasoning: Using advanced language models, the agent processes the input to understand intent and required actions.
- Knowledge Application: The agent applies domain knowledge and context about databases, SQL syntax, and data structures.
- Action Generation: Based on its understanding, the agent generates the appropriate SQL query or other response.
- Feedback Processing: The agent learns from each interaction, improving its performance over time.
AI Agents vs. Traditional Software
Unlike traditional software with predetermined responses, AI Agents can adapt to new situations, learn from experience, and handle ambiguity. They blend the structured logic of traditional programming with the flexibility and learning capabilities of modern AI systems.
These intelligent agents enable organizations to democratize data access, allowing non-technical users to perform complex data operations without specialized SQL knowledge, while still maintaining data quality and integrity.
Learn more about AI Agents in our comprehensive guide or explore advanced agent configurations in our documentation.
What is MCP Model Context Protocol?
The MCP Model Context Protocol is a standardized framework for structuring how AI Agents process and respond to user queries. The protocol consists of three critical components:
- Model: The underlying AI or language model (e.g., GPT-4, Claude, PaLM) that powers the agent's reasoning and generation capabilities.
- Context: The relevant information, data schema, user history, and environmental factors provided to the model to inform its responses.
- Protocol: The standardized method for formatting and structuring the interaction between the model and the context, ensuring consistent, accurate results.
Key Benefits of Model Context Protocol
- Consistency: Standardized approach ensures reliable results across different queries and databases.
- Accuracy: By structuring the context properly, the protocol reduces ambiguity and misinterpretation.
- Efficiency: Streamlines the process of translating natural language to SQL, reducing the computational overhead.
- Adaptability: Can be customized for different database schemas and query types while maintaining the core structure.
- Scalability: Supports integration with various database systems and can handle increasing complexity in user queries.
- Explainability: Provides transparency into how the AI derives its SQL results, enhancing user trust.
Components of the Model Context Protocol
Schema Context
Detailed information about database tables, columns, relationships, and constraints that helps the AI understand the data structure.
Query Intent
Analysis of the user's natural language request to determine the type of information needed and the operations to perform.
User Context
Information about the user's role, permissions, past queries, and preferences that helps personalize responses.
Execution Context
Parameters related to query performance, timing constraints, and output formatting requirements.
How MCP Works
The Model Context Protocol works by creating a structured information flow between your query and the AI system:
- Your query is analyzed to determine intent and required information.
- Relevant database schema and metadata are gathered as context.
- This information is formatted according to the protocol's guidelines.
- The formatted input is processed by the AI model.
- The model generates optimized SQL based on the structured input.
- The generated SQL is validated against the database schema to ensure correctness.
- The final query is presented to the user with explanations of the transformations applied.
Technical Implementation
The Model Context Protocol is implemented as a standardized JSON structure that includes:
{
"model_version": "string",
"user_query": "string",
"database": {
"type": "string",
"schema": [
{
"table_name": "string",
"columns": [
{
"name": "string",
"type": "string",
"description": "string",
"constraints": ["string"]
}
],
"relationships": [
{
"from_column": "string",
"to_table": "string",
"to_column": "string",
"type": "string"
}
]
}
]
},
"user_context": {
"role": "string",
"preferences": {},
"history": []
},
"execution_parameters": {
"timeout": "number",
"max_rows": "number",
"format": "string"
}
}
Pro Tip
The more specific your natural language query is, the better the Model Context Protocol can match it to your database schema, resulting in more accurate SQL generation. Include specific table names, column references, and time periods when possible.
By carefully managing the MCP context, AI Agents can deliver highly accurate, relevant, and actionable results tailored to each user's needs.
Dive deeper into the technical details of the Model Context Protocol in our technical documentation or learn about customizing MCP for your specific use cases.
How to Use AI Agent & Model Context Protocol with AI2sql
- Connect Your Database: Use the dashboard to securely connect your data warehouse (e.g., Snowflake, BigQuery, Redshift, PostgreSQL, MySQL).
- Ask Questions in Natural Language: Enter your data questions in plain English. The AI Agent will interpret your intent.
- Model Context Protocol Construction: The system automatically builds the MCP context by combining your prompt, relevant schema, and user history.
- AI2sql Generation: The AI Agent uses the Model Context Protocol to generate optimized SQL queries tailored to your data and intent.
- Review & Execute: Preview, edit, and run the generated SQL. Visualize results and iterate as needed.
Advanced Usage Techniques
Context Enrichment
Add custom metadata to your database schema to help the AI better understand domain-specific terminology and relationships.
Query Templates
Create and save query templates for common analytics tasks that can be reused with different parameters.
Collaborative Queries
Share and collaborate on natural language queries with team members, building a library of effective questions.
Query Chaining
Use the results of one query as context for follow-up questions, enabling complex multi-step analysis.
Best Practices
- Be Specific: Include relevant details in your queries, such as time periods, metrics, and specific entities.
- Use Business Terms: Phrase questions using familiar business terminology rather than technical database terms.
- Provide Context: When asking follow-up questions, reference previous queries or results for clarity.
- Refine Iteratively: Start with broad questions and refine based on initial results.
- Document Insights: Save successful queries and their explanations for future reference.
Example Query Flow:
Initial Query: "Show me the top 10 products by sales in Q1 2024"
MCP Context: Includes product and sales schema, user role, and prompt above.
Generated SQL: SELECT p.product_name, SUM(s.amount) AS total_sales FROM sales s JOIN products p ON s.product_id = p.id WHERE s.sale_date BETWEEN '2024-01-01' AND '2024-03-31' GROUP BY p.product_name ORDER BY total_sales DESC LIMIT 10;
Follow-up Query: "How do these compare to Q1 2023?"
MCP Context: Includes previous query context plus the new comparative intent.
Generated SQL: SELECT p.product_name, SUM(CASE WHEN s.sale_date BETWEEN '2024-01-01' AND '2024-03-31' THEN s.amount ELSE 0 END) AS sales_2024_q1, SUM(CASE WHEN s.sale_date BETWEEN '2023-01-01' AND '2023-03-31' THEN s.amount ELSE 0 END) AS sales_2023_q1, (SUM(CASE WHEN s.sale_date BETWEEN '2024-01-01' AND '2024-03-31' THEN s.amount ELSE 0 END) - SUM(CASE WHEN s.sale_date BETWEEN '2023-01-01' AND '2023-03-31' THEN s.amount ELSE 0 END)) / NULLIF(SUM(CASE WHEN s.sale_date BETWEEN '2023-01-01' AND '2023-03-31' THEN s.amount ELSE 0 END), 0) * 100 AS growth_percentage FROM sales s JOIN products p ON s.product_id = p.id WHERE s.sale_date BETWEEN '2023-01-01' AND '2024-03-31' GROUP BY p.product_name ORDER BY sales_2024_q1 DESC LIMIT 10;
Ready to try it yourself? Head to the Query Builder and start asking questions in natural language, or check out our step-by-step tutorial for more guidance.
Need Help?
Our team is available to help you optimize your AI Agent and MCP implementation. Contact support for personalized assistance or join our community forum to connect with other users.
Related Resources
Explore these additional resources to deepen your understanding of AI Agents and the Model Context Protocol, and to see practical applications of these technologies with AI2sql.
Interactive Demos
Experience AI Agents in action with our interactive demos showcasing various use cases and capabilities.
Documentation
Detailed guides, API references, and technical specifications for working with AI Agents and MCP.
MCP-AI2SQL Repository
MCP-AI2SQL
A Python project that provides tools for generating SQL queries through a FastMCP server interface in Cursor IDE.
Features
- SQL Query Generation: Generate SQL queries based on natural language requests
- FastMCP Server: Runs as a server that can be queried for these tools
- Cursor Integration: Works seamlessly with Cursor IDE through MCP configuration
- Claude Integration: Compatible with Claude AI assistant for natural language SQL query generation
Prerequisites
- Python 3.10 or higher
- UV package manager
- Dependencies listed in
pyproject.toml - Cursor IDE
Installation
Using UV Package Manager (Recommended)
-
Create a new project
uv init mcp-ai2sql cd mcp-ai2sql -
Create and activate virtual environment
# Create virtual env uv venv # Activate for macOS/Linux source .venv/bin/activate # Activate for Windows .venv\Scripts\activate -
Install dependencies
uv add "mcp[cli]" dotenv
Alternative Installation Method
-
Clone this repository
git clone https://github.com/yourusername/mcp-ai2sql.git cd mcp-ai2sql -
Set up a virtual environment
python -m venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate -
Install dependencies
pip install -e .
Usage
Run the MCP server:
python main.py
Cursor IDE Integration
To use MCP-AI2SQL with Cursor IDE, configure the MCP server in ~/.cursor/mcp.json:
{
"mcpServers": {
"mcp-ai2sql": {
"command": "/path/to/your/python/uv",
"args": [
"--directory",
"/path/to/mcp-ai2sql",
"run",
"main.py"
]
}
}
}
Replace the paths with your actual Python/UV path and project directory.
Claude App Integration
MCP-AI2SQL can be used with Claude AI assistant for more intuitive SQL query generation:
- Make sure your MCP server is running
- In Claude's interface, you can request SQL queries in natural language
- Claude will utilize the MCP-AI2SQL tool to generate accurate SQL based on your descriptions
Example prompt for Claude:
Use the AI2SQL tool to create a query that finds all customers who placed orders in the last month.
Claude will process this request and generate the appropriate SQL using the MCP-AI2SQL backend.
Available Tools
SQL Generator Tool
Generate SQL queries from natural language:
generate_sql(
request="find all users",
table_name="users",
columns="id, name, email"
)
Supports various SQL operations:
- SELECT queries
- CREATE TABLE statements
- INSERT statements
- UPDATE statements
- DELETE statements
- DROP TABLE statements
Video Tutorials
Community Resources
Join Our Community
Connect with other AI2sql users, share your experiences, and get help from our team.
Learn from Others
Explore case studies, blog posts, and user-contributed tutorials.