Why Connect a Database to Claude?
Imagine asking Claude "show me all customers who signed up last month" and getting the actual answer from your live database - no copy-pasting schemas, no writing SQL by hand, no switching between tools. That is exactly what Model Context Protocol (MCP) database servers enable. They give Claude direct, secure access to your database through a standardized interface.
This guide walks you through connecting PostgreSQL, SQLite, MongoDB, and MySQL to Claude Desktop and Claude Code CLI. Every step includes the exact commands and configuration files you need. No guesswork, no ambiguity - just a working database connection in under 10 minutes.
By the end, you will be able to ask Claude natural language questions about your data and get real answers pulled directly from your database. This works for analytics, debugging, data exploration, migration planning, and more.
Prerequisites
Before you start, make sure you have the following installed on your machine:
- Node.js 18 or later - MCP database servers run on Node.js. Download from
nodejs.orgor install via your package manager. Verify withnode --version. - Claude Desktop (latest version) or Claude Code CLI - the AI client that will talk to your database through MCP.
- A running database - PostgreSQL, SQLite, MongoDB, or MySQL. You need the connection string or file path ready.
If you do not have Node.js installed, here is how to get it on each operating system:
# macOS (Homebrew)
brew install node
# Windows (winget)
winget install OpenJS.NodeJS.LTS
# Ubuntu / Debian
sudo apt update && sudo apt install nodejs npm
# Verify installation
node --version # Should show v18.x or later
npx --version # Should show 9.x or later
Step 1: Choose Your Database Server
MCP has dedicated servers for each database type. Here is the full comparison of every database MCP server available:
| Database | MCP Server Package | Install Method | Auth Required | Maintainer | Schema Discovery |
|---|---|---|---|---|---|
| PostgreSQL | @modelcontextprotocol/server-postgres |
npx | Connection string | MCP Core Team | Full (tables, FK, indexes) |
| SQLite | @modelcontextprotocol/server-sqlite |
npx | File path only | MCP Core Team | Full |
| MongoDB | mongodb-mcp-server |
npx | Connection string | MongoDB Inc. | Sampled (inferred) |
| MySQL | @benborla29/mcp-server-mysql |
npx | Env variables | Community | Full (tables, indexes) |
| Redis | @modelcontextprotocol/server-redis |
npx / Docker | Connection string | Community | Key scanning |
| Elasticsearch | @modelcontextprotocol/server-elasticsearch |
npx / Docker | API key or basic auth | Community | Index mapping |
For a deep dive into each server's strengths and weaknesses, see our Best MCP Servers for Database Access guide.
Step 2: Get Your Connection String
Each database type uses a different connection format. Here is exactly what you need for each one:
PostgreSQL Connection String
The PostgreSQL connection string follows the standard URI format. You will need your host, port, username, password, and database name:
# Format
postgresql://USERNAME:PASSWORD@HOST:PORT/DATABASE_NAME
# Local development (default settings)
postgresql://postgres:postgres@localhost:5432/myapp
# Remote server
postgresql://admin:s3cur3p4ss@db.example.com:5432/production
# With SSL (common for cloud providers)
postgresql://admin:password@db.example.com:5432/mydb?sslmode=require
To find your connection string for popular providers: Supabase shows it in Settings > Database > Connection string. Railway has it in your Postgres plugin variables. Neon displays it on the dashboard after creating a project. AWS RDS uses the endpoint from the RDS console combined with your credentials.
MySQL Connection String
The MySQL MCP server uses environment variables rather than a single connection string. You will need these values:
# Connection details
Host: localhost (or your remote host)
Port: 3306 (default)
User: your_username
Password: your_password
Database: your_database_name
To find your MySQL credentials: PlanetScale shows them in the connection details panel after creating a branch. AWS RDS MySQL uses the endpoint from the RDS console. Local XAMPP/MAMP/WAMP installations typically use root with no password on localhost:3306.
SQLite File Path
SQLite databases are just files on your computer. You need the absolute path to the .db or .sqlite file:
# macOS / Linux
/Users/yourname/projects/myapp/database.db
/home/yourname/data/analytics.sqlite
# Windows
C:\Users\yourname\projects\myapp\database.db
Not sure where your SQLite file is? Search for it: find / -name "*.db" -o -name "*.sqlite" 2>/dev/null on macOS/Linux, or use Everything search on Windows.
MongoDB Connection String
# Local MongoDB
mongodb://localhost:27017/myapp
# MongoDB Atlas (cloud)
mongodb+srv://username:password@cluster0.abc123.mongodb.net/mydb
# With authentication database
mongodb://admin:password@localhost:27017/mydb?authSource=admin
Step 3: Find Your Claude Desktop Config File
Claude Desktop uses a JSON configuration file to know which MCP servers to start. The file location depends on your operating system:
| Operating System | Config File Path |
|---|---|
| macOS | ~/Library/Application Support/Claude/claude_desktop_config.json |
| Windows | %APPDATA%\Claude\claude_desktop_config.json |
| Linux | ~/.config/Claude/claude_desktop_config.json |
If the file does not exist yet, create it. If it already exists with other MCP servers configured, you will add your database server to the existing mcpServers object. For more details on config issues, see our Claude Desktop MCP Not Working troubleshooting guide.
Step 4: Configure the Database MCP Server
Open your claude_desktop_config.json file and add the appropriate server configuration. Here is the exact JSON for each database type:
PostgreSQL Configuration
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-postgres",
"postgresql://username:password@localhost:5432/mydb"
]
}
}
}
Replace the connection string with your actual PostgreSQL credentials. The -y flag tells npx to automatically install the package without prompting. For detailed PostgreSQL setup, see the PostgreSQL MCP server page.
MySQL Configuration
{
"mcpServers": {
"mysql": {
"command": "npx",
"args": [
"-y",
"@benborla29/mcp-server-mysql"
],
"env": {
"MYSQL_HOST": "localhost",
"MYSQL_PORT": "3306",
"MYSQL_USER": "username",
"MYSQL_PASSWORD": "password",
"MYSQL_DATABASE": "mydb"
}
}
}
}
Unlike PostgreSQL which uses a single connection string, the MySQL MCP server takes credentials through separate environment variables. This is a community-maintained server, but it is stable and widely used. If you are connecting to a remote MySQL instance or a cloud service like PlanetScale, change MYSQL_HOST to your remote hostname and ensure your firewall allows connections from your machine.
SQLite Configuration
{
"mcpServers": {
"sqlite": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-sqlite",
"/absolute/path/to/your/database.db"
]
}
}
}
The SQLite server only needs the absolute file path - no credentials required. This makes it the easiest database to connect. See the SQLite MCP server page for advanced options.
MongoDB Configuration
{
"mcpServers": {
"mongodb": {
"command": "npx",
"args": [
"-y",
"mcp-mongo-server",
"mongodb://localhost:27017/mydb"
]
}
}
}
For MongoDB Atlas, use your mongodb+srv:// connection string instead. Make sure your IP is whitelisted in Atlas Network Access settings. See the MongoDB MCP server page for Atlas-specific setup.
Connecting Multiple Databases
You can connect multiple databases simultaneously by adding multiple entries to the mcpServers object:
{
"mcpServers": {
"postgres-prod": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://admin:pass@prod.example.com:5432/app"]
},
"sqlite-local": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-sqlite", "/Users/dev/projects/app/dev.db"]
},
"mongodb-analytics": {
"command": "npx",
"args": ["-y", "mcp-mongo-server", "mongodb://localhost:27017/analytics"]
}
}
}
Step 5: Create a Read-Only Database User
Before restarting Claude Desktop, create a dedicated read-only user for the MCP server. Never give AI your admin or root credentials. Here is the exact SQL for every database type:
PostgreSQL Read-Only User
-- Connect as your admin user, then run:
CREATE ROLE claude_readonly WITH LOGIN PASSWORD 'your_secure_password';
GRANT CONNECT ON DATABASE mydb TO claude_readonly;
GRANT USAGE ON SCHEMA public TO claude_readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO claude_readonly;
-- Also grant access to future tables automatically:
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO claude_readonly;
-- Set a query timeout to prevent runaway queries:
ALTER ROLE claude_readonly SET statement_timeout = '10s';
MySQL Read-Only User
-- Connect as root, then run:
CREATE USER 'claude_readonly'@'localhost' IDENTIFIED BY 'your_secure_password';
GRANT SELECT ON mydb.* TO 'claude_readonly'@'localhost';
-- If connecting from a remote host, use '%' instead of 'localhost':
-- CREATE USER 'claude_readonly'@'%' IDENTIFIED BY 'your_secure_password';
-- GRANT SELECT ON mydb.* TO 'claude_readonly'@'%';
FLUSH PRIVILEGES;
MongoDB Read-Only User
// Connect to your database with admin access, then run:
use mydb
db.createUser({
user: "claude_readonly",
pwd: "your_secure_password",
roles: [{ role: "read", db: "mydb" }]
})
SQLite Read-Only Access
SQLite does not have user accounts. Instead, control access at the file system level or by using a read-only connection mode:
# Option 1: Make the file read-only at the OS level
chmod 444 /path/to/database.db
# Option 2: Use the read-only URI parameter (append to path in config)
# Some SQLite MCP servers support ?mode=ro
Step 6: Restart Claude Desktop
After saving your config file, you must fully restart Claude Desktop for the changes to take effect. Simply closing the window is not enough - you need to quit the application completely:
- macOS: Right-click the Claude icon in the dock, select Quit, then reopen.
- Windows: Right-click the Claude icon in the system tray, select Exit, then reopen.
- Linux: Close all Claude windows and verify the process is stopped with
pkill -f claude, then reopen.
After restart, you should see a small hammer icon or MCP indicator in the Claude Desktop interface. This confirms that MCP servers are loaded. If you do not see it, check the Claude Desktop MCP Not Working troubleshooting guide.
Step 7: Test Your Connection
With Claude Desktop restarted, test your database connection by typing one of these prompts:
# For PostgreSQL, MySQL, or SQLite
"Show me all tables in the database"
# For MongoDB
"List all collections in the database"
# More specific tests
"Describe the schema of the users table"
"How many records are in the orders table?"
"Show me the last 5 entries in the logs collection"
If Claude responds with actual table names and data from your database, the connection is working. Claude can now run queries, explore schemas, help you write SQL, analyze data patterns, and even suggest optimizations - all through natural language.
Example Conversation
Here is what a successful interaction looks like after connecting a PostgreSQL database:
You: "Show me all tables in the database"
Claude: "I can see the following tables in your database:
- users (12,450 rows) - id, email, name, created_at, role
- orders (45,230 rows) - id, user_id, total, status, created_at
- products (890 rows) - id, name, price, category, stock
- reviews (23,100 rows) - id, user_id, product_id, rating, text"
You: "Which products have the lowest average rating?"
Claude: "Based on querying your reviews and products tables, here are
the products with the lowest average ratings:
1. Widget Pro (2.1 avg, 45 reviews)
2. Basic Adapter (2.4 avg, 12 reviews)
3. Cable Extension (2.7 avg, 89 reviews)"
Query Examples: What to Ask Claude
Once your database is connected, here are practical prompts organized by use case that work across all database types:
Data Exploration
"Give me an overview of this database. What tables exist, how many rows
does each have, and how are they related through foreign keys?"
"Show me the schema for the users table including column types and
which columns have indexes."
"What are the most common values in the status column of the orders table?
Show me a frequency distribution."
Business Analytics
"Calculate monthly revenue for the past 12 months and show the trend.
Is revenue growing or declining?"
"Who are the top 20 customers by total spend? Include their signup date
and number of orders."
"Show me the conversion funnel: users who signed up, users who added
something to cart, users who completed checkout, and users who returned
for a second purchase. Break it down by month."
Debugging and Data Quality
"Find all duplicate email addresses in the users table."
"Check for orphaned records - orders that reference a user_id that
does not exist in the users table."
"Find all rows in the payments table where amount is negative or zero.
Are these refunds or data errors?"
Schema and Migration Help
"Generate the SQL migration to add a 'phone' column to the users table
and a 'tracking_number' column to the orders table."
"Compare the schema of the users table with this definition I'm about
to paste. What columns are different?"
"Suggest indexes for the orders table based on the foreign keys and
columns that are likely used in WHERE clauses."
Index and Performance Tips
AI-generated queries are not always optimized. Here are ways to keep your database performing well when Claude is querying it:
- Set query timeouts. Always configure a statement timeout for the MCP user (shown in the read-only user creation section above). This prevents poorly optimized queries from locking your database for minutes.
- Ask Claude to explain its queries. After Claude runs a query, ask "explain the query plan for the SQL you just ran." Claude can read the EXPLAIN output and suggest missing indexes.
- Create indexes for common access patterns. If you frequently ask Claude about orders by date or users by email, make sure those columns are indexed. Ask Claude: "Based on the queries I have been asking, what indexes would you recommend creating?"
- Use LIMIT in exploratory queries. When you are exploring data, tell Claude to limit results: "Show me 10 sample rows from the events table" rather than "show me all rows." Claude usually adds LIMIT on its own, but being explicit helps.
- Monitor slow query logs. Enable slow query logging on your database and periodically ask Claude to review the slow query log and suggest optimizations.
-- PostgreSQL: Enable slow query logging for the AI user
ALTER ROLE claude_readonly SET log_min_duration_statement = '1000'; -- Log queries over 1 second
-- MySQL: Check slow query log
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 1; -- Seconds
Alternative: Claude Code CLI
If you use Claude Code (the command-line interface), you can add database MCP servers without editing config files. Use the claude mcp add command:
# Add PostgreSQL
claude mcp add postgres -- npx -y @modelcontextprotocol/server-postgres "postgresql://user:pass@localhost:5432/mydb"
# Add MySQL
claude mcp add mysql -- npx -y @benborla29/mcp-server-mysql
# Add SQLite
claude mcp add sqlite -- npx -y @modelcontextprotocol/server-sqlite "/path/to/database.db"
# Add MongoDB
claude mcp add mongodb -- npx -y mcp-mongo-server "mongodb://localhost:27017/mydb"
# Verify it was added
claude mcp list
Claude Code picks up MCP servers immediately - no restart required. This makes it faster for development workflows where you frequently switch between databases. For MySQL via Claude Code, you will still need to set the environment variables (MYSQL_HOST, MYSQL_USER, etc.) in your shell before starting Claude Code.
Troubleshooting Common Issues
If your database connection is not working, work through these common problems:
Error: spawn ENOENT
This means Claude cannot find the npx command. Node.js is either not installed or not in your system PATH. Fix it by installing Node.js and ensuring the installation directory is in your PATH. See our detailed spawn ENOENT troubleshooting guide for OS-specific solutions.
Error: Connection Refused
Your database is not running or is not accepting connections on the specified host and port. Verify your database is running: pg_isready for PostgreSQL, mysqladmin ping for MySQL, mongosh --eval "db.runCommand({ping:1})" for MongoDB. Check that the port matches your database configuration.
Error: Authentication Failed
The username or password in your connection string is incorrect. Double-check your credentials. For PostgreSQL, verify you can connect directly: psql "postgresql://user:pass@localhost:5432/mydb". For MySQL, try: mysql -u user -p -h localhost mydb. For MongoDB Atlas, make sure you have created a database user (not the same as your Atlas account).
Error: SSL Required
Many cloud database providers require SSL connections. Add ?sslmode=require to your PostgreSQL connection string or ?tls=true to your MongoDB connection string. For MySQL, add "MYSQL_SSL": "true" to the env block.
Claude Desktop Shows No MCP Indicator
Your config file likely has a JSON syntax error. Validate it at jsonlint.com or with cat claude_desktop_config.json | python3 -m json.tool. Common mistakes include trailing commas, missing quotes, and unescaped backslashes in Windows paths (use \\ or forward slashes /).
Server Starts But Queries Fail
The MCP server connected to your database but the AI cannot execute queries. This usually means the database user lacks permissions. For PostgreSQL, grant read access: GRANT SELECT ON ALL TABLES IN SCHEMA public TO your_user;. For MySQL, run: GRANT SELECT ON mydb.* TO 'your_user'@'localhost';. For security best practices, see our MCP Server Security Guide.
Security Best Practices
Connecting AI to your database is powerful but comes with responsibility. Follow these guidelines to keep your data safe:
- Use read-only credentials. Create a dedicated database user with SELECT-only permissions (see Step 5 above). Never give the MCP server your admin or root credentials.
- Never connect to production directly. Use a read replica or a staging copy of your production database. This prevents any accidental writes and avoids performance impact on your live application.
- Keep connection strings out of version control. Use environment variables instead of hardcoding credentials in your config file.
- Monitor query logs. Enable query logging on your database to see exactly what the AI is running. This gives you an audit trail and helps catch unexpected queries.
- Restrict network access. If using a cloud database, whitelist only your machine's IP address in the database firewall rules.
For a comprehensive security overview, read our MCP Server Security Guide.
What Can Claude Do With Your Database?
Once connected, here are the most useful things you can ask Claude to do:
- Data exploration: "Show me the schema", "How many users signed up this week?", "What are the most common values in the status column?"
- Query writing: "Write a query to find duplicate email addresses", "Create a report of monthly revenue by product category"
- Performance analysis: "Which tables are the largest?", "Suggest indexes for this slow query"
- Migration planning: "Compare the schema of these two databases", "Generate ALTER TABLE statements to add these columns"
- Data validation: "Find all rows where the email field is null", "Check for orphaned records in the orders table"
For more ways to use AI with databases, explore our Connect AI to Your Database deep dive.
Next Steps
Now that your database is connected to Claude, here are some ways to go further:
- Explore the full list of PostgreSQL, SQLite, and MongoDB MCP server features.
- Compare all available database servers in our Best MCP Servers for Database Access review.
- Set up additional MCP servers for file access, web scraping, and more.
- Learn about building your own custom MCP server if you need specialized database access patterns.
