Skip to main content
Glama
mcp-postgresdb-readonly

mcp-postgresdb-readonly

by nayzo

mcp-postgresdb-readonly

CI npm License: MIT Node.js

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-readonly

This 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

list-environments

none

Logical names of configured environments and their read-only status.

list-schemas

env

Visible user-defined schemas and base table counts.

list-tables

env, optional schema

Visible base tables and column counts.

describe-table

env, table, optional schema

Column names, types, nullability and defaults.

query

env, sql, optional params

One read-only SELECT with positional parameters. Returns rows, fields, returned row count and a truncated flag.

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-readonly

Claude 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

POSTGRES_{ENV}_HOST

unset

PostgreSQL hostname.

POSTGRES_{ENV}_PORT

5432

PostgreSQL TCP port.

POSTGRES_{ENV}_DATABASE

required

Database name.

POSTGRES_{ENV}_USER

required

Dedicated PostgreSQL reader.

POSTGRES_{ENV}_PASSWORD

required

PostgreSQL password.

POSTGRES_{ENV}_SSL

true

Verify TLS certificates and hostnames. Use NODE_EXTRA_CA_CERTS for a private CA. Set false only on a trusted local connection.

POSTGRES_{ENV}_SCHEMA

unset

Default metadata filter for list-tables and describe-table. Without it, these tools search visible non-system schemas. This is not a permissions boundary.

PORT

unset

HTTP port, 1 to 65535. Unset selects stdio.

MCP_HTTP_HOST

127.0.0.1

Listener IP, such as ::1 for IPv6 loopback.

MCP_AUTH_TOKEN

unset

Shared bearer token, 32 to 256 characters (A-Z, a-z, 0-9, ., _, ~, -). Required on non-loopback listeners and for proxies.

MCP_ALLOWED_HOSTS

unset

Additional comma-separated Host names without ports. Loopback names are always allowed. Requires a token.

RATE_LIMIT_PER_MINUTE

60

Sliding-window limit for database tool calls across all environments and clients, 1 to 600.

QUERY_TIMEOUT_MS

30000

PostgreSQL statement, lock and idle-in-transaction timeout in milliseconds, 1 to 60000.

MAX_ROWS

1000

Maximum returned rows per tool call, 1 to 10000.

Security and limits

  • PostgreSQL privileges come first. Create a login with only CONNECT, USAGE and SELECT on approved objects. Do not use a database, schema or table owner. Remove inherited write privileges and unnecessary PUBLIC grants, including TEMP and access to side-effectful functions or extensions. Audit SECURITY DEFINER functions, 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 a REPEATABLE READ READ ONLY transaction, 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 SQL LIMIT. 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 Origin header. 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-environments returns 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-run

Use 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 tools
describe-tableB
Read-only

Describe the columns, types, nullability and defaults of a visible table.

Inputs: env (required), table (required), schema.

list-environmentsB
Read-only

List the names of configured PostgreSQL environments.

Inputs: no named parameters.

list-schemasB
Read-only

List visible user-defined schemas and their base table counts.

Inputs: env (required).

list-tablesB
Read-only

List visible base tables and their column counts.

Inputs: env (required), schema.

queryA
Read-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

    A3.5/5.0

    Scored across 5 tools

    Disambiguation4/5

    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.

    Naming Consistency4/5

    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.

    Tool Count5/5

    Five tools is well-scoped for a read-only PostgreSQL server. Each tool covers a distinct and necessary part of database exploration and querying.

    Completeness4/5

    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

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      C
      maintenance
      Enables secure querying of PostgreSQL databases through MCP-compatible clients. Supports read-only SQL execution, table exploration, and connection management with built-in security validation.
      3
      44 npm
      9
      MIT
    • F
      license
      Not graded
      quality
      D
      maintenance
      Enables interaction with PostgreSQL databases through MCP, allowing users to explore database structures, inspect table schemas, and execute read-only SQL queries.
      -
    • A
      license
      Not graded
      quality
      D
      maintenance
      Provides 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