← Back to Blog
AI Integration10 min read

Supabase MCP Server: Complete Setup Guide for AI-Powered Database Workflows

Erik Budanov·
Supabase MCP Server: Complete Setup Guide for AI-Powered Database Workflows

Why Connect Supabase to an MCP Server?

Supabase gives you a full Postgres database with a REST API, authentication, real-time subscriptions, and storage — all out of the box. But until MCP, connecting an AI agent to your Supabase database required custom API wrappers, authentication middleware, and a lot of glue code.

With an MCP server, your AI agent (Claude, Cursor, Windsurf, or any MCP-compatible client) can directly query tables, insert records, update data, and run SQL — all through a standardized protocol. No custom API. No webhook chains. No middleware.

What this enables:

Natural language database queries — Ask "show me all users who signed up this week" and the AI translates that to the right SQL query, executes it against your Supabase database, and returns formatted results.

Automated data entry — An AI agent processing emails can extract structured data and insert it directly into your Supabase tables. Invoice arrives → data gets parsed → row gets created in your invoices table.

AI-powered reporting — "Generate a summary of Q1 revenue by product category" → the agent queries your sales table, aggregates the data, and produces a formatted report.

Real-time data validation — An AI agent can check new form submissions against existing records, flag duplicates, and enforce business rules before data enters your system.

Prerequisites

Before starting, make sure you have:

  • A Supabase project (free tier works fine for development)
  • Node.js 18+ installed
  • An MCP-compatible client (Claude Desktop, Cursor, VS Code with Copilot, or similar)
  • Basic familiarity with SQL and environment variables

Option 1: Using the Official Supabase MCP Server

Supabase provides an official MCP server package that handles the connection and exposes your database through the MCP protocol.

Step 1: Get Your Supabase Credentials

Log into your Supabase dashboard. Navigate to Project Settings → API. You need two values:

Project URL — looks like https://abcdefgh.supabase.co

Service Role Key — the service_role key (not the anon key). This gives full database access, so treat it like a database password.

Important: Never use the service role key in client-side code. It bypasses all Row Level Security policies. In an MCP context, the AI agent runs server-side, so this is acceptable — but still, restrict access to only the tables the agent needs.

Step 2: Install and Configure

For Claude Desktop, add this to your claude_desktop_config.json:

{

"mcpServers": {

"supabase": {

"command": "npx",

"args": ["-y", "@supabase/mcp-server-supabase@latest", "--supabase-url", "https://YOUR_PROJECT.supabase.co", "--supabase-key", "YOUR_SERVICE_ROLE_KEY"]

}

}

}

For Cursor or VS Code, the configuration goes in your MCP settings file (usually .cursor/mcp.json or equivalent):

{

"mcpServers": {

"supabase": {

"command": "npx",

"args": ["-y", "@supabase/mcp-server-supabase@latest", "--supabase-url", "https://YOUR_PROJECT.supabase.co", "--supabase-key", "YOUR_SERVICE_ROLE_KEY"]

}

}

}

Step 3: Verify the Connection

Restart your MCP client. You should see "supabase" listed as an available MCP server. Try a simple query:

"List all tables in my Supabase database"

The agent should return your table names, confirming the connection works.

Option 2: Building a Custom MCP Server for Supabase

The official server exposes your entire database. Sometimes you want more control — limiting which tables are accessible, adding business logic, or combining Supabase with other data sources.

When to Build Custom

You want read-only access — The official server allows writes. A custom server can restrict to SELECT queries only.

You need business logic — Before returning data, you want to transform it, filter sensitive fields, or combine data from multiple tables into a single response.

You want to combine data sources — Your custom server can query Supabase AND a third-party API, merging the results before responding to the AI agent.

You need audit logging — Track every query the AI agent makes, who triggered it, and what data was accessed.

Basic Custom Server Structure

import { createClient } from "@supabase/supabase-js";

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";

import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";

import { z } from "zod";

const supabase = createClient(

process.env.SUPABASE_URL!,

process.env.SUPABASE_SERVICE_ROLE_KEY!

);

const server = new McpServer({

name: "supabase-custom",

version: "1.0.0",

});

// Tool: Query any table with filters

server.tool(

"query_table",

"Query a Supabase table with optional filters",

{

table: z.string().describe("Table name"),

select: z.string().optional().describe("Columns to select (default: *)"),

filters: z.record(z.string()).optional().describe("Key-value filters"),

limit: z.number().optional().describe("Max rows to return"),

},

async ({ table, select, filters, limit }) => {

let query = supabase

.from(table)

.select(select || "*");

if (filters) {

for (const [key, value] of Object.entries(filters)) {

query = query.eq(key, value);

}

}

if (limit) query = query.limit(limit);

const { data, error } = await query;

if (error) {

return { content: [{ type: "text", text: "Error: " + error.message }] };

}

return {

content: [{ type: "text", text: JSON.stringify(data, null, 2) }],

};

}

);

// Tool: Insert a record

server.tool(

"insert_record",

"Insert a new record into a Supabase table",

{

table: z.string().describe("Table name"),

data: z.record(z.unknown()).describe("Record data as key-value pairs"),

},

async ({ table, data }) => {

const { data: result, error } = await supabase

.from(table)

.insert(data)

.select();

if (error) {

return { content: [{ type: "text", text: "Error: " + error.message }] };

}

return {

content: [{ type: "text", text: "Inserted: " + JSON.stringify(result) }],

};

}

);

// Start the server

const transport = new StdioServerTransport();

await server.connect(transport);

Running the Custom Server

npx tsx src/index.ts

Configure your MCP client to point to this custom server instead of the official one.

Security Best Practices

Connecting AI to your database is powerful but requires careful security:

1. Use a Dedicated Database Role

Don't use the service_role key for production. Create a dedicated Postgres role with specific table permissions:

CREATE ROLE mcp_agent WITH LOGIN PASSWORD 'secure_password';

GRANT SELECT ON customers, orders, products TO mcp_agent;

GRANT INSERT ON ai_logs TO mcp_agent;

-- No UPDATE or DELETE permissions

2. Implement Row Level Security

Even with a restricted role, add RLS policies that limit what the AI agent can access:

ALTER TABLE customers ENABLE ROW LEVEL SECURITY;

CREATE POLICY "mcp_agent_read" ON customers

FOR SELECT

TO mcp_agent

USING (is_active = true);

3. Log Every Query

Your custom MCP server should log every tool call — timestamp, tool name, parameters, and result count. This creates an audit trail for compliance and debugging.

4. Rate Limit

Add a simple rate limiter to prevent runaway AI loops from hammering your database:

const RATE_LIMIT = 60; // max queries per minute

let queryCount = 0;

setInterval(() => { queryCount = 0; }, 60_000);

// In each tool handler:

if (++queryCount > RATE_LIMIT) {

return { content: [{ type: "text", text: "Rate limit exceeded" }] };

}

5. Never Expose Credentials in Client Code

MCP servers run server-side. The AI client never sees your database credentials. But make sure your credentials are in environment variables, not hardcoded in config files that get committed to git.

Real-World Use Cases

Case 1: AI-Powered Customer Support Dashboard

A customer support team uses Claude to answer "how many tickets are unresolved?" or "show me all critical issues from this week." The Supabase MCP server queries the tickets table, filters by status and priority, and returns structured results that Claude formats into a readable summary.

Case 2: Automated Lead Qualification

New leads arrive via a web form and get stored in Supabase. An AI agent with MCP access scores each lead by checking: company size (from enrichment data), industry match, budget range, and historical conversion rates for similar profiles. The agent updates the lead_score column and moves qualified leads to the sales pipeline.

Case 3: Inventory Monitoring

An e-commerce company uses Supabase to track inventory. Their AI agent runs hourly checks: "find all products where stock_count < reorder_threshold." When it finds low-stock items, it creates purchase orders and notifies the procurement team via Slack (using a Slack MCP server in the same chain).

Troubleshooting Common Issues

"Permission denied for table"

Your database role doesn't have access to the requested table. Grant the needed permissions:

GRANT SELECT ON table_name TO mcp_agent;

"Connection refused"

Check that your Supabase project URL is correct and the project is active. Free-tier projects pause after 7 days of inactivity — wake them from the Supabase dashboard.

"Rate limit exceeded" from Supabase

Supabase free tier allows 500 requests per minute. If your AI agent is making rapid-fire queries, add batching logic or upgrade to a paid plan.

AI Agent Returns Wrong Data

Usually a SQL interpretation issue. Add table schemas as MCP resources so the agent knows your column names and types:

server.resource(

"schema://customers",

"Customer table schema",

async () => ({

contents: [{

uri: "schema://customers",

text: "customers table: id (uuid), name (text), email (text), created_at (timestamp), is_active (bool), plan (text: free|pro|enterprise)"

}]

})

);

What's Next

Once you have Supabase connected via MCP, the natural next step is chaining it with other MCP servers — Slack for notifications, Gmail for email triggers, or a custom CRM server for pipeline management. The power of MCP is composability: each server handles one data source, and the AI agent orchestrates across all of them.

If you want help building a custom Supabase MCP server for your specific use case, or connecting it with other tools in your stack, book a free consultation. We specialize in exactly this kind of AI integration for mid-size companies.

Ready to put this into practice?

Book a free consultation and let's discuss how we can help your business.

Book a Free Consultation →