pg-mcp
Provides tools for interacting with PostgreSQL databases, including on-demand connection registration, schema and table exploration, read-only query execution, execution plan explanation, and controlled write operations.
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
PostgreSQL MCP
Global MCP server for PostgreSQL. Install it once, and agents register database connections on demand with use_connection, so you never need a .mcp entry (or a DATABASE_URL) per project. Queries run in read-only transactions by default; writes are refused, confirmed by the human, or allowed, depending on a setting.
What it does
Most PostgreSQL MCP servers read one connection string from the environment, which forces a separate MCP configuration for every project. PG MCP is configured once, globally. The agent decides which database it needs, registers it, and queries it by id.
Built with @modelcontextprotocol/sdk and pg, it provides:
On-demand connections: call
use_connectionwith a database URL, or point at an environment variable or a.envfile so the password never appears in the conversationSchema exploration: schemas, tables, a search by name across the whole database, and a full table description (columns, primary key, foreign keys, indexes, enum values, estimated row count), each from one catalog query
Read-only by default:
queryruns inside aREAD ONLYtransaction enforced by the server, with a statement timeout and a row cap that the server applies, so a huge result is never loaded into memoryExecution plans:
explainshows how PostgreSQL would run a statement, even a write, without running itControlled writes:
executeis refused, asks the human through MCP elicitation, or runs directly, depending onPG_MCP_WRITESNo secrets in output: passwords are masked in every result and error, and are not written to disk when you use an environment variable or a
.envfile
Related MCP server: Postgres Scout MCP
Requirements
Node.js >= 18
A reachable PostgreSQL server. The catalog queries use only features available since PostgreSQL 9.5 and are tested against PostgreSQL 16
pnpm: only if you develop or contribute to this repo
Usage with an MCP client
Register the server in your MCP client's config (stdio). Shape varies slightly by client; the examples below use a common mcpServers layout.
Recommended (npm):
{
"mcpServers": {
"pg-mcp": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@fqueis/pg-mcp"]
}
}
}With Claude Code you can register it once for every project:
claude mcp add -s user pg-mcp -- npx -y @fqueis/pg-mcpOptional: allow writes without asking (see Write policy):
{
"mcpServers": {
"pg-mcp": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@fqueis/pg-mcp"],
"env": {
"PG_MCP_ENABLE_WRITES": "1"
}
}
}
}Local development / contributors
cd /path/to/pg-mcp
pnpm install
pnpm build
pnpm testBuilt JS:
{
"mcpServers": {
"pg-mcp": {
"type": "stdio",
"command": "node",
"args": ["/path/to/pg-mcp/dist/index.js"]
}
}
}Dev (TypeScript via tsx):
{
"mcpServers": {
"pg-mcp": {
"type": "stdio",
"command": "npx",
"args": ["tsx", "/path/to/pg-mcp/src/index.ts"]
}
}
}Integration tests run against a real PostgreSQL and are skipped unless PG_MCP_TEST_URL is set. Use a disposable database; the spec creates and drops its own schema:
docker run --rm -d --name pg-mcp-test -e POSTGRES_PASSWORD=pgmcp -p 55432:5432 postgres:16-alpine
PG_MCP_TEST_URL=postgres://postgres:pgmcp@localhost:55432/postgres pnpm testTypical agent flow
use_connectionwithenvFile+envKey(orenvVar, ordatabaseUrl) and an optionalidlist_schemas/list_tables/describe_tableto learn the structure, orsearch_schemato find where a table or column livesqueryto read data (read-only, parameterized with$1,$2andparams), andexplainto check the plan of a heavy statement firstexecuteto change data, subject to the write policyforget_connectionorclear_connectionsto drop registrations;refresh_connectionto reopen a connection after the password or the.envfile changed
If no credential source is given, the tool returns a clear error so the agent can ask the user. Registered connections are shared by every project and every agent session on the machine, and expire after a period of disuse (see Optional env).
Tools
Tool | Purpose |
| Register or renew a connection and verify it ( |
| List non-expired connections (never a password) |
| Remove one connection and close its pool |
| Remove every connection and close every pool |
| Reopen a connection, resolving its credential source again |
| User schemas of the database |
| Tables and views of one schema (default |
| Columns (with enum values), primary key, foreign keys, indexes, estimated rows |
| Find tables and columns whose name contains a term (case-insensitive) |
| Run one statement in a read-only transaction, reading at most the row limit |
| Execution plan of a statement as JSON; planned only, unless |
| Run one statement that changes data, subject to the write policy |
Write policy
PG_MCP_WRITES controls execute. PG_MCP_ENABLE_WRITES=1 is a shortcut for on.
Mode | Behavior |
| Every write is refused. |
| The human is asked before each write. The question shows the connection, the exact SQL, and the parameters. |
| Writes run without asking. |
In ask mode the server uses MCP elicitation: the client shows a form with an approval checkbox. Declining, cancelling, or any failure to reach the human counts as "no".
If the client does not support elicitation, execute refuses and tells the agent to show the human the connection and the exact SQL, get an explicit yes in chat, and repeat the call with confirmedByUser: true. This fallback is a soft guard, because the agent controls that flag. When the client can ask, the flag never bypasses the question.
Reads never need approval. query cannot write: the server rejects any change inside a read-only transaction, however the SQL is phrased.
Credentials and security
Source | What is stored in the registry file | Password in the conversation |
| The variable name only | No |
| The file path and key only | No |
| The full URL, in a file readable only by you | Yes |
Prefer envVar or envFile so the password never appears in agent transcripts or on disk. Reference sources are resolved on every connect, so refresh_connection picks up a rotated password.
Passwords are masked (
postgres://user:***@host/db) in every tool result and errorThe registry file is written atomically and with owner-only permissions (
0600; best effort on Windows)Pass options such as
sslmodein the connection string; they go to the driver unchangedGive the agent a database role with only the privileges it needs. A read-only role is the strongest guarantee
Optional env
MCP client configs (mcp.json and equivalents) pass env into the server process. Those values are always strings (same as OS/process.env). Write "1" or "30000", not bare JSON booleans or numbers. Invalid numbers and unknown write modes fall back to the defaults.
Variable | Default | Meaning |
|
| Registry file path |
|
| Sliding TTL of a registered connection (7 days) |
|
| Write policy: |
| unset | When |
|
| Maximum rows a query returns, read from the server (then flagged |
|
| The server cancels a statement that runs longer |
PG_MCP_WRITES, when set, wins over PG_MCP_ENABLE_WRITES.
Architecture
For the communication flow between the MCP client, the service layer, the registry, and PostgreSQL (including Mermaid diagrams), see ARCHITECT.md.
Release history lives in CHANGELOG.md. GitHub Release notes are taken from the matching version section when present.
License
MIT © fqueis. See LICENSE.md.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Safe, read-only Postgres and MySQL access for AI agents. Audit log + column-level controls.
Deterministic safety, correctness & cost gate that vets Postgres SQL before your AI agent runs it.
Query PostgreSQL databases in plain English — LLM-generated, safety-validated SQL.
Query Postgres, MySQL, SQL Server, Oracle, BigQuery, ClickHouse and Redshift from your AI client.
Related MCP Servers
- AlicenseAqualityDmaintenanceEnables AI assistants to interact with PostgreSQL databases using natural language queries, providing secure read-only access to database schemas and SQL translation capabilities.69 npmISC
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to safely explore, analyze, and maintain PostgreSQL databases with read-only mode by default, SQL injection prevention, query performance analysis, and optional write operations.87 npmApache 2.0
- AlicenseNot gradedqualityNot gradedmaintenanceProvides AI assistants with safe, controlled access to PostgreSQL databases with read-only defaults, granular permissions, query safety features, and schema introspection capabilities.1-
- FlicenseAqualityDmaintenanceEnables AI agents to inspect and query PostgreSQL databases safely, with features like listing tables, retrieving schemas, and running read-only SQL queries.3-