Lets an AI client access, query, and manage PostgreSQL databases through tools for schema inspection and SQL execution.
Also known as kristofer84/mcp-postgres
- Stars
- 4
- Tools
- —
- Downloads, 30 days
- —
- Latest version
- —
- Last commit
- Nov 8, 2026
- License
- MIT
What is PostgreSQL MCP?
PostgreSQL lets an AI client access, query, and manage PostgreSQL databases through tools for schema inspection and SQL execution.
Summary generated from the project's README
About PostgreSQL MCP server
Connecting an AI client to your PostgreSQL databases for data analysis and schema inspection is what this server enables. It allows developers to use natural language to interact with their databases by providing tools for listing tables, describing specific table structures, and sampling row data. The server can be configured using individual environment variables like DB_HOST and DB_NAME, a single DATABASE_URL, or a local config.json file.
Security is a primary focus, offering a dedicated read-only mode via the DB_READ_ONLY setting. When active, the server hides all write and DDL tools and enforces read-only transactions at the database level to prevent accidental modifications. For users working with cloud infrastructure, the server includes specialized logic to automatically manage SSL certificates for AWS RDS endpoints, handling downloads and local caching to ensure secure connections without manual setup.
What you can do with it
- 1Inspect database structuresAsk the AI to show the columns and types for a specific table.
- 2Analyze data samplesRequest a small subset of rows from a table to understand its content.
- 3Run read-only queriesPerform SELECT statements to retrieve specific information from the database.
- 4Manage AWS RDS connectionsConnect to an Amazon RDS instance without manually configuring SSL certificates.
Written from the project's README. Every use case is checked against a quote from it.
How to install PostgreSQL MCP
Formats verified 10 Nov 2026Add to CursorAdd to GooseInstall PostgreSQL MCP in Claude Code
$ claude mcp add mcp-postgres -- npx -y mcp-postgresInstall PostgreSQL MCP in Cursor
~/.cursor/mcp.json
{
"mcpServers": {
"mcp-postgres": {
"command": "npx",
"args": [
"-y",
"mcp-postgres"
]
}
}
}Install PostgreSQL MCP in VS Code
.vscode/mcp.json
{
"servers": {
"mcp-postgres": {
"type": "stdio",
"command": "npx",
"args": [
"-y",
"mcp-postgres"
]
}
}
}Install PostgreSQL MCP in VS Code CLI
$ code --add-mcp '{"name":"mcp-postgres","type":"stdio","command":"npx","args":["-y","mcp-postgres"]}'Install PostgreSQL MCP in Claude Desktop
claude_desktop_config.json
{
"mcpServers": {
"mcp-postgres": {
"command": "npx",
"args": [
"-y",
"mcp-postgres"
]
}
}
}Install PostgreSQL MCP in Codex
$ codex mcp add mcp-postgres -- npx -y mcp-postgresInstall PostgreSQL MCP in Codex config.toml
~/.codex/config.toml
[mcp_servers.mcp-postgres] command = "npx" args = ["-y", "mcp-postgres"]
Install PostgreSQL MCP in Gemini CLI
$ gemini mcp add -s user mcp-postgres npx -- -y mcp-postgresInstall PostgreSQL MCP in Gemini settings.json
~/.gemini/settings.json
{
"mcpServers": {
"mcp-postgres": {
"command": "npx",
"args": [
"-y",
"mcp-postgres"
]
}
}
}Configuration
DATABASE_URLDB_HOSTDB_NAMEDB_PASSWORDDB_PORTDB_READ_ONLYDB_SSL_MODEDB_STATEMENT_TIMEOUTDB_USERPOSTGRES_DBPOSTGRES_HOSTPOSTGRES_PASSWORDPOSTGRES_PORTPOSTGRES_SSL_MODEPOSTGRES_USER
| Name | Description | |
|---|---|---|
| DATABASE_URL | — | |
| DB_HOST | — | |
| DB_NAME | — | |
| DB_PASSWORD | — | |
| DB_PORT | — | |
| DB_READ_ONLY | — | |
| DB_SSL_MODE | — | |
| DB_STATEMENT_TIMEOUT | — | |
| DB_USER | — | |
| POSTGRES_DB | — | |
| POSTGRES_HOST | — | |
| POSTGRES_PASSWORD | — | |
| POSTGRES_PORT | — | |
| POSTGRES_SSL_MODE | — | |
| POSTGRES_USER | — |
Automated checks
Ran Nov 14, 2026Full report →Passed our automated checks. That is not a security audit: read the code and give the server the narrowest access it needs. How checks work
- Source repository linked and reachablekristofer84/mcp-postgres is public and reachablegithub.com/kristofer84/mcp-postgres ↗Pass
- Package names this repository as its sourcemcp-postgres names kristofer84/mcp-postgres as sourcenpmjs.com/package/mcp-postgres ↗Pass
- Build provenance (Sigstore attestation)Sigstore attestation for mcp-postgresnpmjs.com/package/mcp-postgres/v/1.4.2#provenance ↗Pass
- Open source license (OSI)MITspdx.org/licenses/MIT.html ↗Pass
- Commit or release in the last yearLast commit or release 2026-11-08github.com/kristofer84/mcp-postgres ↗Pass
- OpenSSF ScorecardNot checked
- Package name not close to a popular packageNo popular package one edit away from mcp-postgresPass
- No critical advisory in the package or its dependenciesNot checked
- No hidden instructions to the model0 tool descriptions and the README read; no override phrases, credential paths or hidden charactersPass
- Destructive tools are labelledNot checked
- Remote endpoint answers the MCP handshakeNot checked
README
View on GitHubMCP PostgreSQL Server
A Model Context Protocol (MCP) server that provides PostgreSQL database access and operations.
Installation
You can use this MCP server with any MCP-compatible client by installing it via npm:
npm install -g mcp-postgres
Or run it directly with npx:
npx mcp-postgres@latest
Requires Node.js 22 or newer.
Configuration
MCP Client Configuration
Add this to your MCP client configuration (e.g., .kiro/settings/mcp.json):
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["mcp-postgres@latest"],
"env": {
"DB_HOST": "localhost",
"DB_PORT": "5432",
"DB_USER": "postgres",
"DB_PASSWORD": "your_password",
"DB_NAME": "your_database",
"DB_SSL_MODE": "require"
},
"disabled": false,
"autoApprove": ["list_tables", "get_schema"]
}
}
}
Alternative using DATABASE_URL:
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["mcp-postgres@latest"],
"env": {
"DATABASE_URL": "postgresql://username:password@localhost:5432/database_name?sslmode=require"
},
"disabled": false,
"autoApprove": ["list_tables", "get_schema"]
}
}
}
Environment Variables
The server supports multiple configuration methods:
Option 1: Individual Environment Variables (Recommended)
DB_HOST=localhost
DB_PORT=5432
DB_USER=postgres
DB_PASSWORD=your_password
DB_NAME=your_database
DB_SSL_MODE=require # Optional: require, disable, or omit for default
DB_READ_ONLY=true # Optional: disables write/DDL tools and makes the DB session read-only
DB_STATEMENT_TIMEOUT=30000 # Optional: query timeout in ms (default: 30000)
Alternative PostgreSQL-style variable names are also supported:
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_USER=postgres
POSTGRES_PASSWORD=your_password
POSTGRES_DB=your_database
POSTGRES_SSL_MODE=require # Optional: require, disable, or omit for default
Option 2: DATABASE_URL (Fallback)
DATABASE_URL=postgresql://username:password@localhost:5432/database_name?sslmode=require
Option 3: Config File
Create a config.json file in your working directory:
{
"db": {
"host": "localhost",
"port": 5432,
"user": "postgres",
"password": "your_password",
"database": "your_database",
"sslmode": "require"
}
}
SSL Configuration
The server supports SSL connections with the following modes:
require- Forces SSL connection (useful for cloud databases)disable- Explicitly disables SSL (default for local development)- Omit the SSL mode for default behavior (no SSL)
SSL can be configured via:
- Environment variables:
DB_SSL_MODEorPOSTGRES_SSL_MODE - DATABASE_URL parameter:
?sslmode=require - Config file:
"sslmode": "require"
AWS RDS Auto-Configuration
The server automatically detects AWS RDS endpoints (hosts containing .rds.amazonaws.com) and:
- Automatically downloads the AWS RDS Global Certificate Bundle from
https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem - Caches the certificate locally in
.aws-certs/directory for 30 days - Configures SSL with proper certificate validation using the downloaded bundle
- Re-downloads the certificate automatically if it's older than 30 days
- Graceful fallback to basic SSL if certificate download fails
This means you can connect to AWS RDS instances without manually downloading or configuring SSL certificates. Simply provide your RDS endpoint and the server handles the rest:
DB_HOST=mydb.cluster-xyz.us-east-1.rds.amazonaws.com
DB_USER=postgres
DB_PASSWORD=your_password
DB_NAME=your_database
# No need to set DB_SSL_MODE - automatically configured for RDS
Features:
- Persistent disk caching: Certificate is saved to
.aws-certs/rds-global-bundle.pemand persists between sessions - 30-day cache duration: Certificate is automatically refreshed after 30 days
- Cache validation: Verifies cached certificates aren't corrupted before use
- Connection retry: Automatic retry logic with 3 attempts and 2-second delays
- Error handling: Falls back to basic SSL if certificate download fails
- Performance: Certificate is cached in memory after first read to avoid repeated file operations
- Cache monitoring: Use the
check_certificate_cachetool to view cache status
The auto-configuration ensures secure, verified connections to AWS RDS while maintaining convenience and reliability.
Available Tools
list_tables
Lists all tables in the database with their types.
get_schema
Gets database schema information including tables and columns.
- Optional parameter:
table_name- Get schema for a specific table
execute_query
Executes a SQL query (SELECT statements only for safety).
- Required parameter:
query- The SQL SELECT query to execute
describe_table
Get detailed information about a specific table including indexes and constraints.
- Required parameter:
table_name- Name of the table to describe
get_table_sample
Gets a sample of rows from a table.
- Required parameter:
table_name- Name of the table to sample - Optional parameter:
limit- Number of rows to return (default: 10, max: 100)
check_certificate_cache
Checks the status of the AWS RDS certificate cache.
- Shows cache location, age, expiration status, and file details
- Useful for troubleshooting SSL connection issues with RDS
Security
Read-Only Mode
Set DB_READ_ONLY=true to disable all write and DDL tools at the server level. When enabled, the following tools are hidden from the tool list and will return an error if called:
update_datadelete_datainsert_dataexecute_raw_querycreate_tablealter_table
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["mcp-postgres@latest"],
"env": {
"DB_HOST": "localhost",
"DB_READ_ONLY": "true",
...
},
"autoApprove": ["list_tables", "get_schema"]
}
}
}
This is enforced server-side — it cannot be bypassed by the MCP client, and is independent of the client's autoApprove list.
Read-only mode is enforced at three levels:
- Write and DDL tools are hidden and rejected.
- The database session uses
default_transaction_read_only = on. - Every
query_datacall runs inside an explicitBEGIN TRANSACTION READ ONLYblock, so a query cannot switch the session back to read-write for a later statement.
In read-only mode, query_data also rejects calls to VOLATILE PostgreSQL functions. Volatile functions are the ones PostgreSQL allows to have side effects, which includes dblink_exec() and similar functions that can open a second connection and write outside the current read-only transaction. This is enforced by looking up the function in pg_proc, not by matching a fixed list of names. A few harmless volatile functions (for example random()) are also rejected while DB_READ_ONLY=true.
query_data in read-only mode is intended for ordinary SELECT queries and built-in read-only functions. If you need extension functions that are genuinely read-only, they will work when they are marked STABLE or IMMUTABLE. For the strongest isolation, still connect with a SELECT-only database role — that also covers functions, operators, or type input functions that declare themselves non-volatile while performing external actions.
Least-Privilege Database Roles (Recommended)
For defence in depth, connect with a PostgreSQL user that only has the permissions it needs. Even with DB_READ_ONLY=true, using a restricted database role ensures the server cannot accidentally or maliciously access data beyond its scope. A SELECT-only role is the strongest boundary and is the recommended setup for any server exposed to untrusted callers.
Read-only role (schema inspection + SELECT):
CREATE ROLE mcp_readonly WITH LOGIN PASSWORD 'strong_password';
-- Allow connecting to the database
GRANT CONNECT ON DATABASE your_database TO mcp_readonly;
-- Allow reading schema metadata
GRANT USAGE ON SCHEMA public TO mcp_readonly;
-- Allow SELECT on all current tables
GRANT SELECT ON ALL TABLES IN SCHEMA public TO mcp_readonly;
-- Allow SELECT on future tables too
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO mcp_readonly;
Read-write role (no DDL):
CREATE ROLE mcp_readwrite WITH LOGIN PASSWORD 'strong_password';
GRANT CONNECT ON DATABASE your_database TO mcp_readwrite;
GRANT USAGE ON SCHEMA public TO mcp_readwrite;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO mcp_readwrite;
ALTER DEFAULT PRIVILEGES IN SCHEMA public
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO mcp_readwrite;
This role can use all tools except create_table, alter_table, and execute_raw_query (which can run DDL). Consider whether those tools are needed and restrict accordingly.
What to avoid: connecting as a superuser (postgres) or a user with CREATEDB / CREATEROLE privileges. If execute_raw_query is enabled, a superuser connection has no effective guardrails.
Query Safety
Only a single SELECT statement is allowed through the query_data tool; comments and string literals are parsed before the multi-statement check, so a marker such as -- inside a string cannot hide a second statement. In read-only mode, volatile functions are rejected as described above. The execute_raw_query tool has no such restriction — disable it via DB_READ_ONLY=true or use a role without write permissions if you don't need it.
Testing
Testing with MCP Inspector
You can test the server locally using the MCP Inspector tool:
# Install the MCP inspector
npm install -g @modelcontextprotocol/inspector
# Set your database credentials
$env:DB_HOST="localhost"
$env:DB_USER="postgres"
$env:DB_PASSWORD="your_password"
$env:DB_NAME="your_database"
# Run the inspector
mcp-inspector node server.mjs
The inspector opens a web UI where you can interactively test each tool and see the responses.
Testing in Kiro IDE
Once configured in your .kiro/settings/mcp.json, you can test the tools directly:
- "List all tables in the database"
- "Show me the schema for the users table"
- "Execute this query: SELECT * FROM products WHERE price > 100"
Project Structure
server.mjs Entry point: server wiring and shutdown handling
src/
sql.mjs Pure helpers: quoting, validation, query checks
ssl.mjs AWS RDS certificate handling and SSL config
config.mjs Configuration loading
db.mjs Database connection lifecycle
tools/
index.mjs Tool definitions and dispatch
read.mjs Read-only tool handlers
write.mjs Write and DDL tool handlers
test/
sql.test.mjs Unit tests for the pure helpers
test-tools.mjs Integration tests (need a running PostgreSQL)
Run npm run test:unit for the unit tests and npm test for everything.
License
MIT
PostgreSQL MCP questions
How do I add PostgreSQL MCP to Claude Code?
Run claude mcp add mcp-postgres -- npx -y mcp-postgres in your terminal. Add --scope user to make it available in every project.
How do I add PostgreSQL MCP to Cursor?
Open ~/.cursor/mcp.json and add the server under mcpServers, using the Cursor config shown in the install section above.
How can I connect to an AWS RDS instance?
The server automatically detects AWS RDS endpoints, downloads the necessary Global Certificate Bundle, and configures SSL with proper validation.
Can I restrict the server to read-only access?
Yes, by setting the DB_READ_ONLY environment variable to true, all write and DDL tools are hidden and rejected at the server level.
What are the requirements to run this server?
You need Node.js version 22 or newer installed on your system.