Skip to main content
RapidDev - Software Development Agency
mcp-tutorial

How to use the PostgreSQL MCP server

The PostgreSQL MCP server connects your AI assistant to a live Postgres database so it can run read-only SQL queries, explore schemas, list tables, and analyze data through natural language prompts. Configure it with a single connection string in your MCP host, and your AI can instantly answer questions about your data, generate reports, and help debug query performance — without you writing any SQL yourself.

What you'll learn

  • How to install and configure the PostgreSQL MCP server
  • How to create a read-only database user for safe AI access
  • How to query and explore your database through natural language
  • How to configure the server for Claude Desktop, Cursor, and VS Code
Book a free consultation
4.9Clutch rating
600+Happy partners
17+Countries served
190+Team members
Intermediate7 min read15 minutesClaude Desktop, Cursor, Windsurf, VS Code (Copilot)March 2026RapidDev Engineering Team
TL;DR

The PostgreSQL MCP server connects your AI assistant to a live Postgres database so it can run read-only SQL queries, explore schemas, list tables, and analyze data through natural language prompts. Configure it with a single connection string in your MCP host, and your AI can instantly answer questions about your data, generate reports, and help debug query performance — without you writing any SQL yourself.

Let Your AI Assistant Query PostgreSQL Databases Directly

The @modelcontextprotocol/server-postgres MCP server gives your AI assistant direct, read-only access to a PostgreSQL database. It exposes tools to run SQL queries, list tables, describe schemas, and explore relationships. The server connects using a standard PostgreSQL connection string and enforces read-only mode by default, so your AI cannot accidentally modify or delete data. This is especially powerful for data exploration, report generation, debugging queries, and understanding unfamiliar database schemas.

Prerequisites

  • Node.js 18 or later installed on your machine
  • A running PostgreSQL database (local or remote)
  • A PostgreSQL user with read-only permissions (recommended)
  • Claude Desktop, Cursor, or another MCP-compatible AI host
  • The database connection string (host, port, user, password, database name)

Step-by-step guide

1

Create a read-only PostgreSQL user

Before connecting your AI to a database, create a dedicated read-only user. This ensures the AI cannot modify data even if the MCP server has a bug or the read-only enforcement fails. Connect to your database as an admin and run the following SQL commands to create a user with SELECT-only permissions on all existing and future tables.

typescript
1-- Connect to your database as admin and run:
2CREATE ROLE mcp_readonly WITH LOGIN PASSWORD 'your_secure_password';
3GRANT CONNECT ON DATABASE mydb TO mcp_readonly;
4GRANT USAGE ON SCHEMA public TO mcp_readonly;
5GRANT SELECT ON ALL TABLES IN SCHEMA public TO mcp_readonly;
6ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO mcp_readonly;

Expected result: A new PostgreSQL user named mcp_readonly exists with SELECT-only access to all tables in the public schema.

2

Add the Postgres MCP server to your configuration

Open your MCP host's configuration file and add a postgres entry. The connection string is the last argument in the args array. Format it as postgresql://user:password@host:port/database. For Claude Desktop and Cursor, use the mcpServers key. For VS Code, use the servers key.

typescript
1{
2 "mcpServers": {
3 "postgres": {
4 "command": "npx",
5 "args": [
6 "-y",
7 "@modelcontextprotocol/server-postgres",
8 "postgresql://mcp_readonly:your_secure_password@localhost:5432/mydb"
9 ]
10 }
11 }
12}

Expected result: Your configuration file contains the Postgres MCP server entry with a valid connection string.

3

Restart your AI host and verify the connection

Fully quit and reopen Claude Desktop, Cursor, or VS Code. The server will attempt to connect to your database on startup. If the connection fails (wrong credentials, database not running, network issues), the server will show as disconnected. Check your host's MCP server status to confirm a successful connection.

Expected result: The Postgres MCP server shows as connected in your AI host with its tools available.

4

Explore your database schema through natural language

Start by asking the AI to describe your database. It will use the server's schema inspection tools to list tables, columns, data types, and relationships. This is a safe way to confirm the connection works and understand what data is available before running queries.

typescript
1Example prompts:
2
3"What tables are in my database and what columns does each have?"
4
5"Describe the schema of the users table including data types and constraints"
6
7"Show me the foreign key relationships between tables"

Expected result: The AI returns a description of your database schema including tables, columns, types, and relationships.

5

Query your data with natural language

Ask questions about your data in plain English. The AI translates your questions into SQL, executes them through the MCP server, and presents the results in a readable format. You can ask for aggregations, filtering, joins, and complex analysis without writing SQL yourself.

typescript
1Example prompts:
2
3"How many users signed up in the last 30 days, broken down by week?"
4
5"What are the top 10 products by total revenue this quarter?"
6
7"Find all orders that were placed but never fulfilled, and show the customer email for each"

Expected result: The AI generates and executes SQL queries, returning formatted results with your requested data.

6

Configure for remote and cloud databases

For remote databases (AWS RDS, Supabase, Neon, Railway), update the connection string with the remote host, port, and credentials. For SSL-required connections, append ?sslmode=require to the connection string. Make sure your database's firewall rules allow connections from your local machine.

typescript
1{
2 "mcpServers": {
3 "postgres": {
4 "command": "npx",
5 "args": [
6 "-y",
7 "@modelcontextprotocol/server-postgres",
8 "postgresql://mcp_readonly:pass@db.example.com:5432/mydb?sslmode=require"
9 ]
10 }
11 }
12}

Expected result: Your AI assistant can query the remote database through the MCP server with SSL encryption.

Complete working example

claude_desktop_config.json
1{
2 "mcpServers": {
3 "postgres": {
4 "command": "npx",
5 "args": [
6 "-y",
7 "@modelcontextprotocol/server-postgres",
8 "postgresql://mcp_readonly:your_secure_password@localhost:5432/mydb"
9 ]
10 }
11 }
12}
13
14// VS Code variant (.vscode/mcp.json):
15// {
16// "servers": {
17// "postgres": {
18// "command": "npx",
19// "args": [
20// "-y",
21// "@modelcontextprotocol/server-postgres",
22// "postgresql://mcp_readonly:pass@localhost:5432/mydb"
23// ]
24// }
25// }
26// }
27
28// Remote database with SSL:
29// "postgresql://user:pass@db.example.com:5432/mydb?sslmode=require"
30
31// SQL to create read-only user:
32// CREATE ROLE mcp_readonly WITH LOGIN PASSWORD 'secure_pass';
33// GRANT CONNECT ON DATABASE mydb TO mcp_readonly;
34// GRANT USAGE ON SCHEMA public TO mcp_readonly;
35// GRANT SELECT ON ALL TABLES IN SCHEMA public TO mcp_readonly;
36// ALTER DEFAULT PRIVILEGES IN SCHEMA public
37// GRANT SELECT ON TABLES TO mcp_readonly;
38
39// Available tools:
40// - query: Run read-only SQL queries
41// - list_tables: List all tables in the database
42// - describe_table: Get column details for a table
43// - get_schema: Get full schema information

Common mistakes when using the PostgreSQL MCP server

Why it's a problem: Using a database admin user instead of a read-only user

How to avoid: Always create a dedicated read-only user for MCP access. Even though the server enforces read-only mode, defense in depth is critical. A read-only database user prevents data modification even if the server's safeguards fail.

Why it's a problem: Including the password in a committed config file

How to avoid: Never commit database credentials to version control. Add your MCP config file to .gitignore, or use environment variable references if your host supports them.

Why it's a problem: Forgetting to add ?sslmode=require for cloud databases

How to avoid: Most cloud PostgreSQL providers (Supabase, Neon, AWS RDS) require SSL connections. Append ?sslmode=require to your connection string or the connection will be rejected.

Why it's a problem: Connecting to a database with many large tables and asking broad questions

How to avoid: Start with schema exploration before querying data. Ask the AI to list tables and describe schemas first, then ask targeted questions about specific tables. This prevents accidentally running expensive queries.

Best practices

  • Always use a dedicated read-only database user for MCP connections
  • Start by exploring the schema before running data queries
  • Use SSL connections for any remote or cloud-hosted database
  • Ask the AI to explain the SQL it generates so you can learn and verify correctness
  • Set statement timeouts on the read-only user to prevent long-running queries
  • Never put production database credentials in shared configuration files
  • Combine with the filesystem MCP server to have the AI save query results to files
  • Test with a development database before connecting to production

Still stuck?

Copy one of these prompts to get a personalized, step-by-step explanation.

ChatGPT Prompt

I want to set up the PostgreSQL MCP server so my AI assistant can query my Postgres database. Walk me through creating a read-only user, configuring the connection string, and setting it up in Claude Desktop. My database is on localhost:5432 and named myapp_dev.

MCP Prompt

List all tables in the database, then show me the schema of the orders table, and finally run a query to find the total revenue by month for the last 6 months.

Frequently asked questions

Can the AI modify or delete data in my database?

The server enforces read-only mode by default, wrapping queries in a read-only transaction. Combined with a read-only database user, this provides two layers of protection against data modification. The AI can only run SELECT queries.

Does it work with Supabase, Neon, or other managed PostgreSQL?

Yes. Any PostgreSQL-compatible database works. Use the connection string from your provider's dashboard and add ?sslmode=require for cloud databases. For Supabase specifically, you might prefer the dedicated Supabase MCP server which adds auth, storage, and edge function management.

How do I connect to multiple databases?

Add multiple entries in your mcpServers config with different names, such as postgres-prod and postgres-staging. Each entry has its own connection string and connects to a separate database.

What if my queries are slow or timing out?

Set a statement timeout on your read-only user with ALTER ROLE mcp_readonly SET statement_timeout = '30s'. This prevents the AI from accidentally running expensive queries that lock up the database.

Is my database password visible to the AI?

The connection string including the password is passed as a command-line argument to the server process. The AI does not see the connection string directly — it only interacts with the query and schema tools. However, the password is visible in your config file, so protect that file accordingly.

Can the AI help me optimize slow database queries?

Yes. Ask the AI to run EXPLAIN ANALYZE on a query to see the execution plan. It can suggest index additions, query rewrites, and schema changes. For complex database optimization projects, RapidDev can help with comprehensive performance audits and schema redesigns.

RapidDev

Talk to an Expert

Our team has built 600+ apps. Get personalized help with your project.

Book a free consultation

Need help with your project?

Our experts have built 600+ apps and can accelerate your development. Book a free consultation — no strings attached.

Book a free consultation

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We'll discuss your project and provide a custom quote at no cost.