May 20, 2026
15 min read

Connect AI to Your Database with MCP in 2026

Stop copy-pasting schemas and writing queries by hand. Connect AI directly to PostgreSQL, MySQL, SQLite, and MongoDB using MCP - the open protocol that makes it safe and simple.

MCPgee Team

MCPgee Team

MCP Expert

TutorialDatabasesPostgreSQLMySQLSQLiteMongoDBSecurity

The Problem: AI Is Blind to Your Data

You are sitting in front of Claude, Cursor, or ChatGPT, and you need help with a database query. What do you do today?

  1. Open a database client (pgAdmin, DataGrip, TablePlus)
  2. Copy your table schema
  3. Paste it into the AI chat
  4. Describe what you want to query
  5. Copy the AI-generated SQL
  6. Paste it into your database client
  7. Run it, see an error
  8. Copy the error back to the AI
  9. Repeat steps 5-8 three more times

This workflow is broken. You are the copy-paste middleware between two systems that should be talking to each other directly. Every round trip wastes time, and the AI never has the full picture - it is guessing about your schema based on whatever fragment you pasted.

There is a better way.

The Solution: Model Context Protocol (MCP)

The Model Context Protocol is an open standard that lets AI models connect directly to external tools - including your database. Instead of you being the middleman, the AI connects to your database through a lightweight server, reads your schema, understands your table relationships, and runs queries directly.

Here is what the workflow looks like with MCP:

  1. Tell the AI what you need: "Show me all users who signed up this month but haven't made a purchase"
  2. The AI reads your schema, writes the query, runs it, and shows you the results

Two steps instead of nine. No copy-pasting. No context loss. The AI sees your actual tables, columns, types, and relationships.

Before vs After: The Difference Is Night and Day

Without MCP With MCP
Manually copy schema into chat AI reads schema automatically
AI guesses column names AI knows exact columns and types
Copy-paste SQL back and forth AI runs queries directly
Error messages lose context AI sees errors and self-corrects
No understanding of relationships AI understands foreign keys and joins
5-10 minutes per query cycle 30 seconds per query

Step-by-Step: Connect AI to PostgreSQL

PostgreSQL is the most popular database for MCP. The PostgreSQL MCP server is maintained by the MCP core team and has the most features.

Step 1: Create a Read-Only Database User

Never give AI your admin credentials. Create a dedicated read-only user:

-- Connect to your database as admin
CREATE ROLE ai_readonly WITH LOGIN PASSWORD 'secure_random_password';
GRANT CONNECT ON DATABASE myapp TO ai_readonly;
GRANT USAGE ON SCHEMA public TO ai_readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO ai_readonly;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO ai_readonly;

-- Set a query timeout to prevent runaway queries
ALTER ROLE ai_readonly SET statement_timeout = '10s';

Step 2: Configure Claude Desktop

Open your Claude Desktop config file:

  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
  • Windows: %APPDATA%\Claude\claude_desktop_config.json

Add the PostgreSQL MCP server:

{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-postgres",
        "postgresql://ai_readonly:secure_random_password@localhost:5432/myapp"
      ]
    }
  }
}

Step 3: Restart Claude Desktop and Test

Restart Claude Desktop. You should see a hammer icon indicating MCP tools are available. Try these prompts:

"List all tables in my database"
"Show me the schema for the users table"
"Find the 10 most recent orders with customer names"
"How many users signed up each month this year?"

Step 4: Verify Read-Only Access

Test that the AI cannot modify your data:

"Try to delete all records from the users table"

The AI should attempt the query and receive a permission denied error, confirming your read-only user is working correctly.

Step-by-Step: Connect AI to MySQL

MySQL support comes through community-maintained MCP servers. The setup is similar to PostgreSQL.

Step 1: Create a Read-Only User

CREATE USER 'ai_readonly'@'localhost' IDENTIFIED BY 'secure_random_password';
GRANT SELECT ON myapp.* TO 'ai_readonly'@'localhost';
FLUSH PRIVILEGES;

Step 2: Configure Claude Desktop

{
  "mcpServers": {
    "mysql": {
      "command": "npx",
      "args": [
        "-y",
        "@benborla29/mcp-server-mysql"
      ],
      "env": {
        "MYSQL_HOST": "localhost",
        "MYSQL_PORT": "3306",
        "MYSQL_USER": "ai_readonly",
        "MYSQL_PASSWORD": "secure_random_password",
        "MYSQL_DATABASE": "myapp"
      }
    }
  }
}

Step 3: Test the Connection

"Show me all tables in the database"
"Describe the orders table and its indexes"
"Find duplicate email addresses in the customers table"

Step-by-Step: Connect AI to SQLite

SQLite is the easiest database to connect because it requires no server process - just a file path. The SQLite MCP server is perfect for local development and prototyping.

Step 1: Locate Your Database File

Find your .db file. Common locations:

  • Django: db.sqlite3 in your project root
  • Rails: db/development.sqlite3
  • Custom apps: wherever you configured it

Step 2: Configure Claude Desktop

{
  "mcpServers": {
    "sqlite": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-sqlite",
        "/Users/you/projects/myapp/db.sqlite3"
      ]
    }
  }
}

Step 3: Start Querying

No user creation needed. No passwords. Just restart Claude Desktop and ask:

"What tables are in this database?"
"Show me the schema and row count for each table"
"Find all products with price over 100 sorted by name"

Important: SQLite MCP has write access by default. If you want read-only access, use a read-only connection by appending ?mode=ro to the path, or set file-level read-only permissions on the database file.

Step-by-Step: Connect AI to MongoDB

The MongoDB MCP server is maintained by MongoDB Inc. and supports both local instances and MongoDB Atlas cloud deployments.

Step 1: Get Your Connection String

For local MongoDB:

mongodb://localhost:27017/myapp

For MongoDB Atlas, get the connection string from your Atlas dashboard. It looks like:

mongodb+srv://username:password@cluster0.abc123.mongodb.net/myapp

Step 2: Create a Read-Only User (Recommended)

use myapp
db.createUser({
  user: "ai_readonly",
  pwd: "secure_random_password",
  roles: [{ role: "read", db: "myapp" }]
})

Step 3: Configure Claude Desktop

{
  "mcpServers": {
    "mongodb": {
      "command": "npx",
      "args": [
        "-y",
        "mongodb-mcp-server",
        "--connectionString",
        "mongodb://ai_readonly:secure_random_password@localhost:27017/myapp"
      ]
    }
  }
}

Step 4: Explore Your Documents

"List all collections in this database"
"Show me a sample document from the orders collection"
"Find all orders over $500 from the last month with customer details"
"What's the average order value by product category?"

Step-by-Step: Connect AI to DuckDB

DuckDB is an analytical database that excels at processing large datasets. It is like SQLite for analytics - embedded, no server required, and incredibly fast for OLAP queries. If you have CSV files, Parquet files, or need to run complex aggregations, DuckDB with MCP is an excellent choice.

Step 1: Install a DuckDB MCP Server

DuckDB MCP servers are community-maintained. The most popular option uses Python:

# Install via pip
pip install mcp-server-duckdb

Step 2: Configure Claude Desktop

{
  "mcpServers": {
    "duckdb": {
      "command": "python",
      "args": [
        "-m",
        "mcp_server_duckdb",
        "--db-path", "/path/to/your/analytics.duckdb"
      ]
    }
  }
}

Step 3: Query Your Data

DuckDB shines for analytical queries and can read external files directly:

"Read the CSV file at /data/sales-2025.csv and show me monthly revenue totals"

"Import all Parquet files in /data/events/ and count events by type per day"

"What's the 90th percentile response time from the logs table, grouped by endpoint?"

DuckDB is particularly powerful because it can query CSV and Parquet files without importing them first, making it ideal for ad-hoc data analysis.

Connection String Formats for Cloud Providers

If your database is hosted on a cloud provider, here are the exact connection string formats you need:

Provider Database Connection String Format
Supabase PostgreSQL postgresql://postgres.[ref]:[password]@aws-0-[region].pooler.supabase.com:6543/postgres
Neon PostgreSQL postgresql://[user]:[password]@[endpoint].neon.tech/[dbname]?sslmode=require
PlanetScale MySQL Host: [branch].connect.psdb.cloud, Port: 3306, SSL required
MongoDB Atlas MongoDB mongodb+srv://[user]:[password]@[cluster].mongodb.net/[dbname]
ElephantSQL PostgreSQL postgresql://[user]:[password]@[host].db.elephantsql.com/[dbname]
AWS RDS PostgreSQL/MySQL postgresql://[user]:[password]@[instance].rds.[region].amazonaws.com:5432/[dbname]
Railway PostgreSQL/MySQL Available in your Railway plugin variables panel

For all cloud providers, remember to add SSL parameters when required. Most cloud PostgreSQL providers need ?sslmode=require appended to the connection string.

Real Query Examples: What You Can Actually Ask

Once connected, the power of AI + database access becomes obvious. Here are real prompts that work across all database types:

Data Exploration

"Give me an overview of this database. How many tables are there, what are the main
entities, and how are they related? Draw me a mental map of the schema."

"Find all tables that have a 'created_at' column and tell me the date range of
data in each one."

"Which tables have the most rows? Are there any that seem unusually large?"

Business Questions

"What's our monthly revenue trend for the past 12 months?"

"Who are our top 10 customers by lifetime value?"

"Show me the conversion funnel: how many users signed up, created a project,
invited a teammate, and upgraded to paid - each month."

Debugging

"I'm seeing duplicate entries in the orders table. Find all orders where the same
user has two orders within 1 second of each other - those are probably bugs."

"The users table has a 'deleted_at' column but I don't think soft deletes are
working properly. Find any users who have 'deleted_at' set but still have
active sessions in the sessions table."

Data Visualization with AI

While MCP database servers return raw query results, you can ask Claude to format data in ways that are easy to visualize or paste into a spreadsheet:

"Query monthly revenue for the past 12 months and format the results as a
markdown table with columns: Month, Revenue, Change vs Previous Month (%)."

"Get the top 10 products by units sold and create a simple ASCII bar chart
showing relative sales volume."

"Pull daily active users for the past 30 days and output the data as CSV
that I can paste into Google Sheets."

Batch Query Patterns

When you need to run multiple related queries, give Claude the full context upfront rather than asking one question at a time:

"I need a complete health check of this database. Run these checks and report
the results in a single table:
1. Total row count for each table
2. Any tables with zero rows
3. The oldest and newest created_at timestamp in the users table
4. Any foreign key columns that reference IDs that don't exist in the parent table
5. Tables that have no indexes other than the primary key"

Handling Large Result Sets

AI context windows have limits. When a query returns thousands of rows, you need strategies to keep things manageable:

  • Always use LIMIT: Ask Claude to limit results to 10-50 rows unless you specifically need more. "Show me the top 20 customers" is better than "show me all customers."
  • Use aggregation instead of raw data: Instead of "show me all orders from last month," ask "what is the total, average, and count of orders from last month grouped by product category." Aggregated results are compact and more useful.
  • Ask for summaries first: Start with a count query to understand the scale, then drill down. "How many users match this condition?" before "show me all users matching this condition."
  • Export large results: If you need more than a few hundred rows, ask Claude to write the query and save the output to a file rather than displaying it inline: "Write a query for all orders from 2025 and save the results to /tmp/orders-2025.csv."

Security: Keeping Your Database Safe

Connecting AI to your database is safe when done correctly. Here are the non-negotiable security rules:

1. Always Use Read-Only Access

Create a dedicated database user with SELECT-only permissions. Never use your admin or application credentials for the MCP server. The AI should be able to read data but never modify it unless you have a specific reason to allow writes.

2. Use Environment Variables for Credentials

Do not put passwords directly in the command args. Use the env block instead:

{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres"],
      "env": {
        "DATABASE_URL": "postgresql://ai_readonly:password@localhost:5432/myapp"
      }
    }
  }
}

Even better, reference environment variables from your system or a .env file. See our environment variables guide for details.

3. Set Query Timeouts

AI-generated queries are not optimized. A poorly written query can lock your database. Set timeouts:

-- PostgreSQL
ALTER ROLE ai_readonly SET statement_timeout = '10s';

-- MySQL
SET GLOBAL max_execution_time = 10000;  -- 10 seconds in milliseconds

4. Restrict Schema Access

If your database has sensitive tables (payment info, PII), restrict the AI user to only the tables it needs:

-- PostgreSQL: Only grant access to specific tables
REVOKE ALL ON ALL TABLES IN SCHEMA public FROM ai_readonly;
GRANT SELECT ON users, orders, products, categories TO ai_readonly;
-- The AI cannot see: payment_methods, admin_logs, api_keys

5. Enable Audit Logging

Track every query the AI runs:

-- PostgreSQL
ALTER ROLE ai_readonly SET log_statement = 'all';

Review the logs periodically to understand what the AI is querying and catch any unexpected patterns. For comprehensive security guidance, read our MCP Security Guide.

Database MCP Servers Comparison

Feature PostgreSQL MySQL SQLite MongoDB DuckDB
Maintainer MCP Core Team Community MCP Core Team MongoDB Inc. Community
Read-Only Mode Via DB role Via DB role Via ?mode=ro --readOnly flag Via flag
SSL Support Yes Yes N/A (local file) Yes (Atlas) N/A (local file)
Schema Discovery Full (tables, FK, indexes) Full (tables, indexes) Full Sampled (inferred) Full
External File Queries No No No No Yes (CSV, Parquet)
Best For Production apps WordPress, legacy apps Local dev, prototyping Document-heavy apps Analytics, data science
Setup Time 5 minutes 5 minutes 2 minutes 5 minutes 3 minutes

For a deep comparison of database MCP servers including Redis and Elasticsearch, see our Best MCP Servers for Database Access guide.

Building Simple Dashboards with AI and MCP

Once your database is connected, you can use AI to build lightweight reporting views without any dashboard software. Ask Claude to query your data and format it into structured output you can use directly:

"Create a weekly business report with these sections:
1. New user signups (total and daily breakdown)
2. Revenue summary (total, average order value, top product)
3. Support tickets opened vs resolved
4. Any anomalies or unusual patterns you notice
Format everything as a clean markdown document I can share with my team."

For more visual output, ask Claude to generate chart-ready data:

"Query daily active users for the past 90 days and output the data as a
JSON array with 'date' and 'count' fields. I'll paste this into a
charting tool."

"Create a pivot table showing revenue by product category (rows) and
month (columns) for 2025. Format as a markdown table."

This approach works well for ad-hoc reporting and quick data checks. For persistent dashboards that auto-refresh, you would still need a dedicated tool like Grafana or Metabase, but for one-off analysis and weekly reports, AI + database MCP is often faster than setting up a full BI tool.

Troubleshooting Common Issues

Connection Refused

If the MCP server cannot connect to your database, check:

  • Is the database running? (pg_isready for Postgres, mysqladmin ping for MySQL)
  • Is the host correct? Use localhost for local databases, not 127.0.0.1 (or vice versa, depending on your config)
  • Is the port correct? Default ports: PostgreSQL 5432, MySQL 3306, MongoDB 27017
  • Does your database allow connections from the MCP server? Check pg_hba.conf for Postgres

Authentication Failed

Double-check your username and password. For PostgreSQL, ensure the user has LOGIN privilege. For MongoDB Atlas, make sure your IP is whitelisted in the Network Access settings.

AI Says "No Tables Found"

The user probably does not have permission to see the tables. Grant USAGE on the schema:

-- PostgreSQL
GRANT USAGE ON SCHEMA public TO ai_readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO ai_readonly;

What's Next

You have connected AI to your database. Now explore what else you can do:

Was this helpful?

Share article:

Stay Updated with MCP Insights

Join 5,000+ developers and get weekly insights on MCP development, new server releases, and implementation strategies delivered to your inbox.

We respect your privacy. Unsubscribe at any time.

MCPgee Team

MCPgee Team

We're pioneering the future of Model Context Protocol development with comprehensive guides and tools. Our mission is to make MCP accessible to developers of all skill levels.

Frequently Asked Questions

Related Articles