pg-mcp
pg-mcp is a PostgreSQL MCP server that enables AI assistants to securely interact with PostgreSQL databases, with built-in read-only protection by default.
pg_connect: Connect to a PostgreSQL database via a connection URL or individual parameters (host, port, user, password, database), with optional SSL and read-only mode settings.pg_disconnect: Close and clean up an existing database connection by its connection ID.pg_query: Execute SQL queries against a connected database, with support for parameterized/prepared statements.pg_list_schemas: List all schemas available in the connected database.pg_get_ddl: Retrieve the complete DDL for a database (CREATE TABLE statements, indexes, constraints, foreign keys, sequences, and views), optionally filtered by schema.Read-only mode: Enabled by default, blocking DML (INSERT, UPDATE, DELETE, TRUNCATE, MERGE) and DDL/DCL operations (CREATE, ALTER, DROP, GRANT, REVOKE). Can be explicitly disabled per connection.
Auto-connect: Automatically connects on startup if
DATABASE_URLor standard libpq environment variables are set, using connection ID"default".
Enables querying of PostgreSQL databases, schema inspection, and retrieval of DDL with built-in read-only protection. It provides tools for connecting to databases, executing SQL queries, listing schemas, and fetching complete DDL structures.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@pg-mcp list all tables in the public schema"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
pg-mcp
MCP server for PostgreSQL. Query databases, inspect schemas, backup data, and manage dumps — with built-in read-only protection.
Quick Start
npm install -g @shedyhs/pg-mcpAdd to your AI provider config:
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["-y", "@shedyhs/pg-mcp"],
"env": {
"DATABASE_URL": "postgres://user:pass@localhost:5432/mydb"
}
}
}
}With DATABASE_URL or PGHOST/PGDATABASE set, the server auto-connects as "default" on startup.
Set PG_MCP_READ_ONLY=false in env to allow write operations (read-only by default).
Related MCP server: PostgreSQL MCP Server
Named Connections
To reach more than one database, give each connection a name. Every tool takes a connectionId, and pg_list_connections shows what is open.
Connections file (recommended)
Create ~/.config/pg-mcp/connections.json:
{
"connections": [
{ "id": "prod", "url": "postgres://app:${PROD_PW}@prod.example.com:5432/app", "readOnly": true },
{ "id": "staging", "url": "postgres://app:${STG_PW}@stg.example.com:5432/app", "readOnly": true },
{ "id": "local", "url": "postgres://dev:dev@localhost:5432/app", "readOnly": false }
]
}The path is fixed — no env var is needed to point at it. Each entry takes:
Field | Required | Meaning |
| yes | Name to pass as |
| yes | PostgreSQL connection URL |
| no | Falls back to |
Unknown keys are rejected rather than ignored, so a misspelled raedOnly fails loudly instead of silently leaving the connection read-only.
Since the file holds connection targets, chmod 600 ~/.config/pg-mcp/connections.json — the server warns on stderr if it is world-writable.
${VAR} expansion
URLs expand ${VAR} from the environment, so the file can be committed without the passwords in it:
{ "id": "prod", "url": "postgres://app:${PROD_PW}@prod.example.com:5432/app" }Two rules matter:
A reference inside a larger URL is percent-encoded. A password containing
@,/or#would otherwise close the userinfo section and re-parse as a different host — silently pointing the connection somewhere else. Escaping means a var cannot span URL components, so"${HOST}"holdingdb:5432becomesdb%3A5432; use"${HOST}:5432"instead.A reference that is the whole value is used verbatim, because it stands for a complete URL:
{ "id": "prod", "url": "${PROD_DATABASE_URL}" }
A variable that is unset or empty is an error: that one connection is skipped and reported on stderr, the others still open.
Passwords in a separate file
${VAR} moves the password from the config file to the environment — but in an MCP setup that environment is usually the env block of your client config, which is plaintext all the same. To keep connections.json free of secrets, put the passwords in ~/.config/pg-mcp/credentials.json instead — a flat map of connection id to password:
{
"prod": "the-real-password",
"staging": "another-password"
}chmod 600 ~/.config/pg-mcp/credentials.jsonThen leave the password out of the URL entirely:
{
"connections": [
{ "id": "prod", "url": "postgres://app@prod.example.com:5432/app", "readOnly": true }
]
}The password is injected into the URL at startup, percent-encoded, so @, /, # and : in a password are safe. It applies to connections from any source, so {"default": "..."} covers one declared through DATABASE_URL too.
Three cases get reported on stderr instead of looking like a wrong password:
an id in
credentials.jsonthat matches no connection (a typo)a credential for a connection that has no URL to inject into
a contested id — if two sources declare the same id, the password is refused, not applied.
credentials.jsonis a0600file, but an environment variable can claim any id; applying the password anyway would hand a secret meant for one host to a URL declared somewhere less trusted. Rename one of them to resolve it.
pg_dump and pg_restore receive the password through PGPASSWORD, never as a command-line argument: on Linux /proc/PID/cmdline is world-readable (mode 444) so anything in argv shows up in ps for every user on the machine, while /proc/PID/environ is mode 600.
The file is still plaintext — this separates the secret from the config so the latter can be committed, it does not encrypt anything. The server warns if the file is readable beyond its owner, and chmod 600 silences that. (libpq's ~/.pgpass also still works, if you already keep passwords there: omit the password and the driver finds it.)
Inline via env
The same list can go in a single PG_MCP_CONNECTIONS env var, as a JSON array:
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["-y", "@shedyhs/pg-mcp"],
"env": {
"PG_MCP_CONNECTIONS": "[{\"id\":\"prod\",\"url\":\"postgres://app:${PROD_PW}@prod:5432/app\",\"readOnly\":true}]",
"PROD_PW": "..."
}
}
}
}Precedence
All three sources are merged by id, later ones winning:
~/.config/pg-mcp/connections.jsonPG_MCP_CONNECTIONSDATABASE_URL, orPGHOST/PGDATABASE— these always own the iddefault
Passwords from credentials.json are applied after the merge, to whichever connection ended up with each id.
Connections open concurrently at startup and are registered in declaration order. When a higher-precedence source takes over an id, the override is reported on stderr, so a stray DATABASE_URL repointing a reviewed connection is visible rather than silent.
A database being unreachable never stops the server: each attempt is bounded by a 10s timeout — covering both the connect and the health check, so a host that accepts TCP but never answers cannot stall startup — and the failure goes to stderr while the other connections stay usable.
Tools
Tool | Description | Requires |
| List open connections with target and read-only mode (never returns credentials) | — |
| Connect to a PostgreSQL database (URL, params, or libpq env vars) | — |
| Disconnect from a database | — |
| Execute SQL queries with read-only protection | — |
| List all user schemas | — |
| Get complete DDL (tables, indexes, constraints, FKs, sequences, enums, views) | — |
| Backup specific rows as INSERT statements before destructive operations | — |
| Dump a database or specific tables to a file |
|
| Restore a database from a dump file (custom, directory, or tar format) |
|
Where to Put the Config
Provider | Config file |
Claude Desktop |
|
Claude Code |
|
Cursor |
|
Windsurf |
|
Codex |
|
All providers above use the same JSON format from Quick Start.
GitHub Copilot (VS Code) uses a slightly different format in .vscode/mcp.json:
{
"servers": {
"postgres": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@shedyhs/pg-mcp"],
"env": {
"DATABASE_URL": "postgres://user:pass@localhost:5432/mydb"
}
}
}
}From source — replace command/args with "command": "node", "args": ["/path/to/pg-mcp/dist/index.js"].
Installing pg_dump & pg_restore
Only needed if you use pg_dump or pg_restore. All other tools work without external dependencies.
OS | Command |
macOS |
|
Debian/Ubuntu |
|
RHEL/Fedora |
|
Windows |
|
Verify with pg_dump --version.
Installation from Source
git clone https://github.com/shedyhs/pg-mcp
cd pg-mcp
npm install && npm run buildLicense
MIT
Available Tools
5 toolspg_connectB
Connect to a PostgreSQL database using a URL or individual parameters
Inputs: connectionId (required), url, host, port, +5 more.
pg_disconnectB
Disconnect from a PostgreSQL database
Inputs: connectionId (required).
pg_get_ddlA
Get the complete DDL (Data Definition Language) of the database including CREATE TABLE statements, indexes, constraints, foreign keys, sequences, and views
Inputs: connectionId (required), schema.
pg_list_schemasA
List all schemas in the database
Inputs: connectionId (required).
pg_queryC
Execute a SQL query on a PostgreSQL database
Inputs: connectionId (required), sql (required), params.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 5 tools
Each tool has a distinct purpose: connection management, schema listing, DDL retrieval, and arbitrary query execution. No overlap or ambiguity.
All tools use the 'pg_' prefix followed by a verb_noun pattern (connect, disconnect, get_ddl, list_schemas, query). Naming is consistent and predictable.
With 5 tools, the server covers essential database operations without being too sparse or overwhelming. The count is well-scoped for its purpose.
The server provides core functionality for connecting, exploring schemas, viewing DDL, and running queries. It lacks dedicated tools for listing tables or indexes, but the SQL query tool can compensate.
Maintenance
Related MCP Connectors
Safe, read-only Postgres and MySQL access for AI agents. Audit log + column-level controls.
Query PostgreSQL databases in plain English — LLM-generated, safety-validated SQL.
PostgreSQL, MySQL, and SQL Server in one session. 26 read-only MCP tools for AI agents.
Query Postgres, MySQL, SQL Server, Oracle, BigQuery, ClickHouse and Redshift from your AI client.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables AI agents to interact with PostgreSQL databases through the Model Context Protocol, providing database schema exploration, table structure inspection, and SQL query execution capabilities.15MIT
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to safely interact with PostgreSQL databases through read-only operations, providing schema discovery, table inspection, and query execution capabilities with structured context awareness.MIT
- AlicenseNot gradedqualityDmaintenanceEnables AI agents to query, explore, and analyze PostgreSQL databases through the Model Context Protocol. It provides robust security features including read-only mode, schema restrictions, and query timeouts for safe data interaction.MIT
- FlicenseNot gradedqualityDmaintenanceEnables AI assistants to interact with PostgreSQL databases by executing SQL queries and inspecting database schemas. It provides tools to facilitate database exploration and management through the Model Context Protocol.-