Build an AI Database Query Assistant with Natural Language SQL (MCP Recipe)
🍳 MCP Recipe
- What you'll build: An AI assistant that converts natural language to SQL and queries databases
- MCP servers used: Supabase MCP Server
- Time to complete: 45-60 minutes
- Difficulty: Intermediate
Imagine asking "Show me all users who signed up last month" and getting instant results—without writing a single line of SQL. That's what you'll build in this recipe.
This AI Database Query Assistant lets anyone query your database using natural language. Perfect for:
- Non-technical team members who need data insights
- Quick ad-hoc queries without opening database tools
- Building chatbots that answer data questions
- Creating internal tools for business intelligence
What You'll Build
By the end of this recipe, you'll have an AI assistant that can:
| Input (Natural Language) | Output (SQL Query + Results) |
|---|---|
| "How many users signed up this week?" | SELECT COUNT(*) FROM users WHERE created_at >= NOW() - INTERVAL '7 days' |
| "Show me the top 10 products by sales" | SELECT product_name, SUM(amount) as total_sales FROM orders GROUP BY product_name ORDER BY total_sales DESC LIMIT 10 |
| "What's the average order value for customers in California?" | SELECT AVG(total) FROM orders WHERE customer_state = 'CA' |
Architecture Overview
The system works in three steps:
"Show me active users"
SELECT * FROM users WHERE status = 'active'
Query results formatted nicely
How it works:
- You ask: "What are the top selling products this month?"
- AI analyzes: Understands intent, identifies tables (products, orders), determines filters (this month)
- AI generates SQL: Creates optimized query using Supabase MCP tools
- MCP executes: Runs query against your Supabase database
- AI formats: Returns results in a readable format with insights
Prerequisites
Free tier works perfectly
With at least one table
From Supabase dashboard
Claude Desktop or Cursor
Step 1: Set Up Your Supabase Project
If you don't have a Supabase project yet:
- Go to supabase.com and sign up (free)
- Create a new project (choose a region close to you)
- Wait 2-3 minutes for the project to initialize
Create Sample Data (Optional but Recommended)
For testing, let's create a simple users table. In your Supabase SQL Editor, run:
-- Create users table
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
email TEXT UNIQUE NOT NULL,
name TEXT,
status TEXT DEFAULT 'active',
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
last_login TIMESTAMP WITH TIME ZONE
);
-- Create orders table
CREATE TABLE orders (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES users(id),
product_name TEXT NOT NULL,
amount DECIMAL(10, 2) NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- Insert sample data
INSERT INTO users (email, name, status) VALUES
('alice@example.com', 'Alice Smith', 'active'),
('bob@example.com', 'Bob Jones', 'active'),
('charlie@example.com', 'Charlie Brown', 'inactive');
INSERT INTO orders (user_id, product_name, amount) VALUES
((SELECT id FROM users WHERE email = 'alice@example.com'), 'Product A', 99.99),
((SELECT id FROM users WHERE email = 'alice@example.com'), 'Product B', 149.99),
((SELECT id FROM users WHERE email = 'bob@example.com'), 'Product A', 99.99);
Step 2: Get Your Supabase Credentials
You'll need two values from your Supabase dashboard:
- Project URL: Found in Settings → API → Project URL
- Looks like:
https://xxxxx.supabase.co
- Looks like:
- Service Role Key: Found in Settings → API → Service Role Key
- ⚠️ Keep this secret! It has full database access
- Starts with:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
⚠️ Security Warning
The Service Role Key bypasses Row Level Security (RLS). Only use it in secure environments. For production, consider using an API key with limited permissions or implementing RLS policies.
Step 3: Install Supabase MCP Server
The Supabase MCP Server is available as a remote server, so no local installation is needed. You can test it directly in the MCP Playground first.
Test in MCP Playground
- Go to MCP Playground
- Enter the Supabase MCP URL:
https://mcp.supabase.com/mcp - Add authentication header:
Bearer YOUR_SERVICE_ROLE_KEY - Click "Connect" and explore available tools
You should see tools like:
execute_sql— Run SQL querieslist_tables— Get all tables in your databasedescribe_table— Get table schemalist_projects— List your Supabase projects
Step 4: Configure Supabase MCP in Your Client
For Claude Desktop
Edit your Claude Desktop config file:
- macOS:
~/Library/Application Support/Claude/claude_desktop_config.json - Windows:
%APPDATA%\Claude\claude_desktop_config.json
Add the Supabase server configuration:
{
"mcpServers": {
"supabase": {
"url": "https://mcp.supabase.com/mcp",
"headers": {
"Authorization": "Bearer YOUR_SERVICE_ROLE_KEY_HERE"
}
}
}
}
For Cursor IDE
Open Cursor Settings → Tools & MCP, then add:
| Field | Value |
|---|---|
| Name | supabase |
| Type | streamableHttp |
| URL | https://mcp.supabase.com/mcp |
| Headers | {"Authorization": "Bearer YOUR_SERVICE_ROLE_KEY"} |
Step 5: Restart and Verify
- Restart your AI client (Claude Desktop or Cursor)
- Verify connection: Ask "What Supabase tools do you have access to?"
- Test basic query: "List all tables in my database"
âś… Checkpoint
If the AI can list your tables, you're ready to start querying with natural language!
Step 6: Query Your Database with Natural Language
Now the fun part! Ask questions in plain English:
Basic Queries
How many users are in the database?
Show me all active users
What's the total revenue from orders?
Filtered Queries
Show me users who signed up in the last 30 days
Find all orders over $100
List inactive users
Aggregations
What's the average order value?
How many orders did each user make?
Show me the top 5 products by sales
Complex Queries
Show me users who haven't logged in for 30 days and their total order value
What's the monthly revenue trend for the last 6 months?
Find users with more than 5 orders and calculate their lifetime value
Step 7: Understanding How It Works
When you ask a question, here's what happens behind the scenes:
- Schema Discovery: AI uses
list_tablesanddescribe_tableto understand your database structure - Query Generation: AI converts your natural language into optimized SQL
- Execution: Uses
execute_sqlto run the query - Formatting: AI presents results in a readable format with insights
Example: "Show me active users"
What the AI does:
- Calls
list_tables→ Finds "users" table - Calls
describe_table→ Sees columns: id, email, name, status, created_at - Generates SQL:
SELECT * FROM users WHERE status = 'active' - Executes query via
execute_sql - Formats results as a table or list
Advanced: Custom Prompts for Better Results
You can guide the AI to generate better queries with context:
When querying my database:
- Always use proper SQL syntax for PostgreSQL
- Include relevant WHERE clauses to filter data
- Use JOINs when querying related tables
- Format dates as YYYY-MM-DD
- Limit results to 100 rows unless I specify otherwise
- Explain what the query does before executing
Now, show me users who signed up this month.
Best Practices
| Practice | Why It Matters |
|---|---|
| Be specific | "Users from last month" is better than "recent users" |
| Mention table names | "Show orders" is clearer than "show sales" |
| Specify limits | "Top 10 products" prevents large result sets |
| Review generated SQL | AI can make mistakes—verify complex queries |
| Use read-only mode | Prevent accidental data modifications |
Security Considerations
đź”’ Security Best Practices
- Never share your Service Role Key — It has full database access
- Use Row Level Security (RLS) — Limit what queries can access
- Create read-only users — For production, use a dedicated read-only database user
- Monitor query logs — Review what queries are being executed
- Set query timeouts — Prevent long-running queries
- Whitelist allowed operations — Only allow SELECT queries if possible
Troubleshooting
Connection errors or "Unauthorized"
Check that:
- Your Service Role Key is correct (no extra spaces)
- The Authorization header format is:
Bearer YOUR_KEY - Your Supabase project is active (not paused)
- You're using the correct project URL
AI generates incorrect SQL
If queries fail or return wrong results:
- Ask the AI to describe the table schema first: "What columns are in the users table?"
- Provide context: "The status column can be 'active' or 'inactive'"
- Ask to see the SQL before executing: "Show me the SQL query for..."
- Correct the AI: "That's wrong, try using a JOIN instead"
Queries are too slow
Optimize performance:
- Add indexes on frequently queried columns
- Limit result sets: "Show top 50..." instead of "Show all..."
- Use specific date ranges instead of "all time"
- Ask for aggregations instead of raw data when possible
Can't find tables or columns
Help the AI discover your schema:
- Ask: "List all tables in my database"
- Then: "Describe the [table_name] table"
- Provide table/column names explicitly in your questions
Real-World Use Cases
1. Business Intelligence Dashboard
Create a chatbot that answers business questions:
"What's our monthly recurring revenue?"
"How many new customers did we get this quarter?"
"What's the customer churn rate?"
2. Customer Support Tool
Support agents can quickly look up customer data:
"Show me all orders for customer alice@example.com"
"What's the total amount this customer has spent?"
"List all support tickets for this user"
3. Analytics Assistant
Product managers can explore data without SQL:
"What features are most used?"
"Show me user engagement trends"
"Which marketing channels drive the most signups?"
What You Built
Congratulations! You now have an AI assistant that:
- âś… Connects to Supabase via MCP
- âś… Converts natural language to SQL
- âś… Executes queries and returns formatted results
- âś… Understands your database schema
- âś… Handles complex queries with joins and aggregations
Next Steps
- Add more databases: Connect PostgreSQL MCP for direct database access
- Build a web interface: Create a simple UI that uses this assistant
- Add query caching: Cache frequent queries for faster responses
- Create query templates: Save common queries as reusable prompts
- Set up monitoring: Track query performance and errors
Test Supabase MCP Server Now
Try the Supabase MCP tools in our online playground
Open MCP Playground →Related Recipes
Frequently Asked Questions
Can this work with other databases besides Supabase?
Is it safe to let AI generate SQL queries?
What if the AI generates incorrect SQL?
Can I use this with production data?
How accurate are the SQL queries?
Does this work with Supabase Edge Functions?
Nikhil Tiwari
15+ years of experience in product development, AI enthusiast, and passionate about building innovative solutions that bridge the gap between technology and real-world applications. Specializes in creating developer tools and platforms that make complex technologies accessible to everyone.