postgresdb-mcp
by nayzo
README.md
# postgresdb-mcp
[](https://github.com/nayzo/postgresdb-mcp/actions/workflows/ci.yml)
[](https://www.npmjs.com/package/@nayzo/postgresdb-mcp)
[](LICENSE)
[](https://nodejs.org/)
A [Model Context Protocol](https://modelcontextprotocol.io/) (MCP) server for inspecting and querying multiple PostgreSQL environments over stdio, with writes disabled by default.
## Quick start
Install and start the server with one command (Node.js 22.12 or later):
```sh
npx --yes @nayzo/postgresdb-mcp --env /absolute/path/to/postgres.env
```
Create the configuration file first (see below). The server speaks MCP over stdin/stdout; use one of the client configurations below rather than typing SQL into its terminal. For reproducible deployments, pin the npm package version in the command.
## Tools
| Tool | Arguments | Result |
| --- | --- | --- |
| `list-environments` | none | Environment names, schema scope, TLS status, and write policy. |
| `list-schemas` | `env` | Visible user schemas and their relation counts. |
| `list-tables` | `env`, optional `schema` | Visible tables and views with column counts. |
| `describe-table` | `env`, `table`, optional `schema` | Column types, nullability, and defaults. |
| `query` | `env`, `sql`, optional `params` and `confirm_write` | `queryType`, `duration`, `rowCount`, `rows`, `fields`, and `truncated`. |
For metadata tools, the default schema is the first configured schema, or `public` if no scope is set. To address a mixed-case identifier, include double quotes in the value as you would in SQL. `query` accepts scalar parameters (`string`, finite `number`, `boolean`, or `null`), e.g. `{"env":"local","sql":"SELECT id FROM public.items WHERE id = $1","params":[42]}`.
## Client setup
Replace `/absolute/path/to/postgres.env` with the path to your configuration file. Keep credentials out of client settings.
### Claude Code
```sh
claude mcp add --transport stdio postgresdb -- npx --yes @nayzo/postgresdb-mcp --env /absolute/path/to/postgres.env
```
### Claude Desktop
Add this entry to `claude_desktop_config.json`, then restart Claude Desktop:
```json
{
"mcpServers": {
"postgresdb": {
"command": "npx",
"args": ["--yes", "@nayzo/postgresdb-mcp", "--env", "/absolute/path/to/postgres.env"]
}
}
}
```
### Cursor
Add this to `.cursor/mcp.json` in your project, or `~/.cursor/mcp.json` for all projects:
```json
{
"mcpServers": {
"postgresdb": {
"command": "npx",
"args": ["--yes", "@nayzo/postgresdb-mcp", "--env", "/absolute/path/to/postgres.env"]
}
}
}
```
### OpenCode
Add this to `opencode.json`:
```json
{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"postgresdb": {
"type": "local",
"command": ["npx", "--yes", "@nayzo/postgresdb-mcp", "--env", "/absolute/path/to/postgres.env"],
"enabled": true
}
}
}
```
## Configuration
Use a private dotenv file outside shared workspaces and restrict its file permissions. With `--env`, only the named file is loaded. Without it, the server tries `.env` in the current working directory and falls back to process variables only if the file does not exist. Use [`.env.dist`](.env.dist) as a starting point.
```dotenv
POSTGRES_LOCAL_HOST=127.0.0.1
POSTGRES_LOCAL_DATABASE=example
POSTGRES_LOCAL_USER=example_reader
POSTGRES_LOCAL_PASSWORD=replace-me
POSTGRES_LOCAL_SCHEMA=public
POSTGRES_LOCAL_ALLOW_WRITES=false
```
Each `POSTGRES_<ENV>_HOST` defines an environment, where `<ENV>` contains 1 to 32 uppercase ASCII letters or digits. Use the lowercase label in tool calls, such as `local`. Avoid putting private information in these labels or in exposed schemas.
| Suffix | Default | Meaning |
| --- | --- | --- |
| `HOST` | Required | PostgreSQL hostname or local socket directory. |
| `PORT` | `5432` | PostgreSQL port (`1` to `65535`). |
| `DATABASE` | Required | Database name. |
| `USER` | Required | Dedicated database role. |
| `PASSWORD` | Required | Role password. |
| `SCHEMA` | Unset | Up to 32 comma-separated schema identifiers. Unquoted names are folded to lowercase; double-quoted names are case-sensitive. An empty list is invalid. |
| `SSL` | `false` | Set to `true` for TLS on remote connections. |
| `SSL_REJECT_UNAUTHORIZED` | `true` | Verify the server certificate when TLS is enabled. Keep enabled for remote connections. |
| `ALLOW_WRITES` | `false` | `true` enables only supported DML and row-locking queries with exact `confirm_write="WRITE"`. |
| `STATEMENT_TIMEOUT_MS` | `5000` | Server-side PostgreSQL statement timeout (`1` to `60000` ms). A client-side deadline also covers execution and cleanup. |
| `MAX_ROWS` | `200` | Maximum rows per result (`1` to `1000`). |
In dotenv files, wrap a schema list containing double-quoted identifiers in single quotes, for example `POSTGRES_LOCAL_SCHEMA='public,"MixedCase"'`.
## Security and limits
- **Write protection:** the PostgreSQL parser must recognize exactly one allowed statement. Reads always use `BEGIN READ ONLY`, including on writable environments and when confirmation is supplied. `INSERT`, `UPDATE`, `DELETE`, `MERGE`, data-modifying CTEs, and row locks require both write gates. The `WRITE` argument is a tool-level control, not proof of human approval; use your client's approval controls for write access.
- **Supported SQL:** `SELECT` (including `WITH`, `VALUES`, and `TABLE`), selected `SHOW` settings, and non-executing `EXPLAIN` for reads. SQL batches, session or transaction commands, DDL, `COPY`, `DO`, `SELECT INTO`, and `EXPLAIN ANALYZE` are unsupported, even with confirmation. Direct function calls are limited to selected PostgreSQL built-ins, such as `count`, `sum`, `lower`, and `generate_series`. Use `pg_catalog.<name>` if an unqualified call is ambiguous.
- **Schema scope:** the server filters metadata, checks syntactic schema references, and uses a transaction-local search path with `pg_catalog` first. System catalog lookups remain available subject to PostgreSQL grants. This is an additional safeguard, not a database permission boundary. Views, triggers, operators, casts, extensions, and functions can access objects indirectly and may have effects outside normal table writes.
- **Database roles:** use a read replica or dedicated PostgreSQL role with minimal grants. For isolated schemas, limit `USAGE` and object privileges in PostgreSQL and review `PUBLIC` grants, including schema creation, `TEMP`, and function execution. Avoid using an owner, superuser, or role with elevated privileges. Separate read and write roles and keep production writes disabled unless necessary.
- **Sensitive data:** connection settings are not included in tool metadata, raw errors, or logs. Tool outputs still contain database data the role can see. Keep secrets out of queryable tables, view definitions, and column defaults, and review access to catalog data and extensions before granting access. Do not put secrets in SQL text or argument names.
- **Resource limits:** each environment has its own pool of up to five connections. Query results are fetched in batches, with caps on returned rows and serialized row data. `truncated` means additional rows or row data were omitted. For reads, `rowCount` is the number of returned rows; for confirmed writes it is PostgreSQL's command count, which can exceed the output cap. Large individual PostgreSQL values can still be expensive to receive. Use explicit limits and narrow SELECT lists for large datasets. If a write fails during a network interruption, verify its outcome before retrying.
## Development
Use a current Node.js 22 or 24 release (ESLint requires Node.js 22.13 or later in the 22.x line):
```sh
npm ci
npm run lint
npm run build
npm test
npm audit --omit=dev
```
Tests use the Node.js test runner and the official MCP client. Set `TEST_DATABASE_URL` or all five of `PGHOST`, `PGPORT`, `PGUSER`, `PGPASSWORD`, and `PGDATABASE` to run the stdio integration suite against a disposable PostgreSQL database. If all five variables and the URL are set, the variables take precedence. The test role needs permission to create schemas in that database; the suite creates and removes its own fixtures. Without database configuration, the suite skips cleanly. CI runs against PostgreSQL 17 on Node.js 22 and 24.
The tagged release job uses npm Trusted Publishing. Configure `nayzo/postgresdb-mcp`, workflow `ci.yml`, and the GitHub environment `npm` as the package's trusted publisher. The tag must match `package.json`, and versions already present on npm are skipped. If the package does not yet exist and npm does not allow a publisher to be configured for it, establish the package and its trusted publisher before using the tag workflow.
## License
[MIT](LICENSE), by [Ala Eddine Khefifi](https://github.com/nayzo).
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessOutdated data