mcp-postgresdb-readonly
This MCP server lets you inspect PostgreSQL schemas and tables and run safe, read-only SELECT queries across configured environments.
List configured environments (
staging,test,prod) and their read-only status.List visible user-defined schemas with base table counts.
List visible base tables and column counts, optionally filtered by schema.
Describe a table’s columns, types, nullability, and defaults.
Run one parameterized, read-only
SELECTper call with bounded rows, row counts, returned fields, and truncation reporting.Connect via local stdio or Streamable HTTP with optional bearer-token auth, host validation, rate limits, and query timeouts.
Provides read-only access to PostgreSQL databases, allowing querying (SELECT only), listing tables, describing table schemas, listing schemas, and listing configured environments. Supports multiple environments (staging, test, prod) with configurable protection limits.
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., "@mcp-postgresdb-readonly show me the users table 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.
mcp-postgresdb-readonly
Explore PostgreSQL schemas and run read-only queries from any compatible Model Context Protocol client over local stdio or Streamable HTTP.
Quick start
Requires Node.js 22.12 or later and a dedicated, non-administrative PostgreSQL reader. Configure one connection with POSTGRES_TEST_HOST, POSTGRES_TEST_DATABASE, POSTGRES_TEST_USER and POSTGRES_TEST_PASSWORD, then run:
npx -y @nayzo/mcp-postgresdb-readonlyThis starts a stdio MCP server. A client normally launches it for you. The executable is mcp-postgresdb-readonly; pass --version to print the installed version. For reproducible deployments, append the published version to the package name.
The executable reads the process environment. For a source checkout, copy .env.dist to .env, fill in the connection settings, build, then run node --env-file=.env dist/index.js. Docker Compose loads .env automatically. Keep real credentials out of shared client configs and version control.
Related MCP server: Postgres MCP Server
Tools
Tool | Arguments | Result |
| none | Logical names of configured environments and their read-only status. |
|
| Visible user-defined schemas and base table counts. |
|
| Visible base tables and column counts. |
|
| Column names, types, nullability and defaults. |
|
| One read-only |
For example, the query tool accepts:
{
"env": "test",
"sql": "SELECT id, label FROM reporting.items WHERE status = $1 ORDER BY id",
"params": ["active"]
}Client setup (stdio)
Replace the example connection values before use. Keep credential-bearing configuration files local and protected. For desktop clients, make sure npx is on the application's PATH, or use its absolute path.
Claude Code
Register the command below, then run Claude Code from an environment that already has the database variables:
claude mcp add --transport stdio postgresdb-readonly -- npx -y @nayzo/mcp-postgresdb-readonlyClaude Desktop
Add this to claude_desktop_config.json via Settings > Developer > Edit Config, then restart the client:
{
"mcpServers": {
"postgresdb-readonly": {
"command": "npx",
"args": ["-y", "@nayzo/mcp-postgresdb-readonly"],
"env": {
"POSTGRES_TEST_HOST": "db.example.com",
"POSTGRES_TEST_DATABASE": "sample",
"POSTGRES_TEST_USER": "mcp_reader",
"POSTGRES_TEST_PASSWORD": "REPLACE_ME"
}
}
}
}Cursor
Add this to your private ~/.cursor/mcp.json:
{
"mcpServers": {
"postgresdb-readonly": {
"command": "npx",
"args": ["-y", "@nayzo/mcp-postgresdb-readonly"],
"env": {
"POSTGRES_TEST_HOST": "db.example.com",
"POSTGRES_TEST_DATABASE": "sample",
"POSTGRES_TEST_USER": "mcp_reader",
"POSTGRES_TEST_PASSWORD": "REPLACE_ME"
}
}
}
}OpenCode
Add this to your private ~/.config/opencode/opencode.json:
{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"postgresdb-readonly": {
"type": "local",
"command": ["npx", "-y", "@nayzo/mcp-postgresdb-readonly"],
"environment": {
"POSTGRES_TEST_HOST": "db.example.com",
"POSTGRES_TEST_DATABASE": "sample",
"POSTGRES_TEST_USER": "mcp_reader",
"POSTGRES_TEST_PASSWORD": "REPLACE_ME"
}
}
}
}Streamable HTTP
Set PORT, for example PORT=3000, to enable HTTP. The default listener is 127.0.0.1. The /mcp endpoint accepts one JSON-RPC message per POST, returns JSON, and does not allocate MCP sessions or expose a GET event stream. /health returns {"status":"ok"} without checking the database.
For Docker, copy .env.dist to .env, fill in the database settings, and set MCP_AUTH_TOKEN to a random value generated with openssl rand -hex 32. Run docker compose up -d --build and check make health. Compose runs a non-root image, binds inside the container, and publishes port 3000 only on the host loopback. make deploy, make logs and make stop manage the local service.
For remote clients, terminate TLS on a trusted reverse proxy. Set MCP_AUTH_TOKEN on the backend and MCP_ALLOWED_HOSTS to the public hostname, for example mcp.example.com, and forward the original Host and Authorization headers. An nginx template is included. Install valid certificates before enabling the template. Keep the backend unreachable from outside the proxy and never send a bearer token to a remote plain HTTP endpoint.
The sample .docker/nginx.conf limits each client to 10 requests per second (burst 20) and 10 concurrent connections, and returns 429 beyond that. Adjust these limits to your traffic, or enforce equivalent limits in your load balancer or API gateway.
If PostgreSQL uses a private certificate authority, mount its PEM file read only and point NODE_EXTRA_CA_CERTS to the path inside the container. docker-compose.yml contains a commented example using /run/certs/postgres-ca.pem.
The client connects to https://mcp.example.com/mcp with Authorization: Bearer <token>. For Claude Code, start with a private shell environment containing MCP_AUTH_TOKEN:
claude mcp add --transport http postgresdb-http https://mcp.example.com/mcp \
--header 'Authorization: Bearer ${MCP_AUTH_TOKEN}'Configuration
Configure up to three targets: POSTGRES_TEST_*, POSTGRES_STAGING_* or POSTGRES_PROD_*. Set HOST to enable a target. env in tool calls is the corresponding lowercase name.
Variable | Default | Purpose |
| unset | PostgreSQL hostname. |
|
| PostgreSQL TCP port. |
| required | Database name. |
| required | Dedicated PostgreSQL reader. |
| required | PostgreSQL password. |
|
| Verify TLS certificates and hostnames. Use |
| unset | Default metadata filter for |
| unset | HTTP port, |
|
| Listener IP, such as |
| unset | Shared bearer token, 32 to 256 characters ( |
| unset | Additional comma-separated Host names without ports. Loopback names are always allowed. Requires a token. |
|
| Sliding-window limit for database tool calls across all environments and clients, |
|
| PostgreSQL statement, lock and idle-in-transaction timeout in milliseconds, |
|
| Maximum returned rows per tool call, |
Security and limits
PostgreSQL privileges come first. Create a login with only
CONNECT,USAGEandSELECTon approved objects. Do not use a database, schema or table owner. Remove inherited write privileges and unnecessaryPUBLICgrants, includingTEMPand access to side-effectful functions or extensions. AuditSECURITY DEFINERfunctions, views and foreign data wrappers exposed to the role. The server rejects elevated role attributes and membership in known administrative roles. It cannot prove that all locally installed functions are safe or prevent their external side effects. For high assurance, use a dedicated read replica and expose only the datasets clients need.Read-only execution. PostgreSQL starts each connection with
default_transaction_read_only=on. Each call runs on that connection in aREPEATABLE READ READ ONLYtransaction, takes a snapshot before caller SQL, and uses an extended-protocol portal for exactly one statement. The SQL parser rejects writes, data-modifying CTEs,SELECT INTO, row locks and transaction commands. Successful calls roll back and reset session state before returning the connection to the pool; failed or cancelled calls discard it.Bounded work. There are at most five database connections per target and a five-second connection or checkout limit. SQL is limited to 16 KiB, parameter arrays to 16 scalar values, and individual strings to 4 KiB. Portal fetching enforces
MAX_ROWS, including for an explicit SQLLIMIT. Result content is bounded to about 1 MiB before MCP serialization; truncation is reported. A row cap is not a database scan budget, and a single large row can still be materialized by PostgreSQL and the driver.HTTP protection. HTTP is opt-in, requires a valid token when configured, validates Host headers, and rejects requests with an
Originheader. It accepts up to 128 KiB of uncompressed JSON, uses short header and body timeouts, and limits simultaneous connections. A token grants access to all configured targets. Use separate instances for different trust scopes. Do not publish a tokenless loopback backend through a proxy.Sensitive information. The server does not log SQL, parameters, identifiers, tokens, credentials or raw driver errors.
list-environmentsreturns only logical environment names. SQL results are data visible to the configured database role, so grant access only to information your MCP clients should receive.
Development and tests
npm ci
npm run lint
npm run build
npm test
npm audit --omit=dev
npm pack --dry-runUse a current patch release of Node 22 or 24 for development. Tests use node:test and the official MCP client over stdio and real HTTP. To run database integration tests, point PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE and TEST_DATABASE_URL at the same disposable PostgreSQL instance. The fixture needs a database administrator to create isolated roles and schema objects. Without the connection variables, database tests skip cleanly. CI runs both Node majors with PostgreSQL 17.
Releases
See CHANGELOG.md for migration notes. The release workflow validates v<version> tags and uses npm Trusted Publishing with the npm GitHub environment and workflow filename ci.yml. The maintainer must establish the package on npm and configure its trusted publisher before relying on tag-triggered releases.
License and author
MIT. Maintained by Ala Eddine Khefifi.
Available Tools
5 toolsdescribe-tableBRead-only
Describe the columns, types, nullability and defaults of a visible table.
Inputs: env (required), table (required), schema.
list-environmentsBRead-only
List the names of configured PostgreSQL environments.
Inputs: no named parameters.
list-schemasBRead-only
List visible user-defined schemas and their base table counts.
Inputs: env (required).
list-tablesBRead-only
List visible base tables and their column counts.
Inputs: env (required), schema.
queryARead-only
Run one read-only PostgreSQL SELECT. Use schema-qualified names and bind values with $1, $2, and so on.
Inputs: env (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: environment discovery, schema listing, table listing, table description, and SQL execution. The only mild overlap is between query and the introspection tools, but descriptions clearly separate them.
All tool names use kebab-case, which is consistent. However, 'query' is a bare verb while the other tools follow a verb_noun pattern, a minor deviation.
Five tools is well-scoped for a read-only PostgreSQL server. Each tool covers a distinct and necessary part of database exploration and querying.
The surface covers environment discovery, schema/table introspection, column description, and read-only querying, which are the core needs. Minor gaps include no explicit view/index listing or query explanation/plan tool, but agents can work around these via SQL.
Maintenance
Related MCP Connectors
Managed Postgres MCP: projects, SQL, docs search, and storage buckets via OAuth.
PostgreSQL, MySQL, and SQL Server in one session. 26 read-only MCP tools for AI agents.
Query your org's data in natural language — read-only MCP access to SQL, NoSQL, files & warehouses.
Safe, read-only Postgres and MySQL access for AI agents. Audit log + column-level controls.
Related MCP Servers
- AlicenseAqualityCmaintenanceEnables secure querying of PostgreSQL databases through MCP-compatible clients. Supports read-only SQL execution, table exploration, and connection management with built-in security validation.344 npm9MIT
- FlicenseNot gradedqualityDmaintenanceEnables interaction with PostgreSQL databases through MCP, allowing users to explore database structures, inspect table schemas, and execute read-only SQL queries.-
- FlicenseAqualityCmaintenanceEnables inspecting database schemas and executing read-only SQL queries on a PostgreSQL database via MCP tools.3-
- AlicenseNot gradedqualityDmaintenanceProvides read-only access to PostgreSQL databases via MCP, enforcing least-privilege roles, row-level security, masked views, and SQL AST guardrails to prevent data leakage and unauthorized operations, enabling AI agents to safely query sensitive production data.MIT