psql-mcp

psql-mcp

A hardened, read-only Postgres MCP server that enables LLMs to safely query databases without write, DDL, shell, or credential exposure.

Category
访问服务器

README

psql-mcp

A hardened, read-only Postgres MCP server. Give an LLM (Claude Code, etc.) safe query access to one or more databases — without giving it the ability to write, run DDL, shell out, read server files, or see your connection credentials.

Extracted and generalized from a per-repo server used in production. The security core (psql_mcp/hardening.py) is unit-tested and unchanged from that origin.

What it guarantees

Every query is validated and then wrapped so the Postgres engine itself — not this Python — enforces read-only:

SET default_transaction_read_only = on;
BEGIN READ ONLY;
  <your SQL>
;
ROLLBACK;

On top of that, pre-flight validation rejects:

  • psql meta-commands (\!, \copy, \g, \gexec, …) anywhere they'd be interpreted — including mid-line after SQL — closing the \! shell-escape.
  • Read-only escapes: RESET, DISCARD, SET SESSION AUTHORIZATION, SET ... READ WRITE, transaction_read_only, SESSION CHARACTERISTICS, and transaction control (BEGIN/COMMIT/ROLLBACK/SAVEPOINT/START TRANSACTION). CASE … END is unaffected.
  • Filesystem / shell reach: COPY … PROGRAM, non-STDOUT COPY, pg_read_file and the pg_ls_*dir family, lo_import/lo_export.
  • Obfuscation: U&'…' unicode-escape introducers and dynamic-SQL executors (dblink*, query_to_xml*) that could assemble a blocked name at runtime.

Output is streamed under a 60 KB cap and a 60s timeout, killing the whole psql process group (not just a wrapping bash) so a runaway SELECT can't exhaust memory or hang the server. stderr is always surfaced so a blocked write never looks like a silent no-op.

These are defence-in-depth guardrails, not a substitute for least privilege. Point each environment at a role that only has SELECT; the server then just keeps the model from fighting that role.

Install

Requires psql on PATH. Then either:

# one-off, no install (recommended for MCP configs)
uvx --from psql-mcp psql-mcp        # once published
uvx --from /path/to/psql-mcp psql-mcp   # from a local checkout

# or install into an environment
pip install psql-mcp

Configure

A config declares named environments; the server exposes one query_<name> tool per environment. Provide it via PSQL_MCP_CONFIG (a JSON file path) or PSQL_MCP_ENVIRONMENTS (inline JSON). See templates/config.example.json.

{
  "server_name": "my-psql",
  "environments": {
    "dev": { "wrapper": ".claude/scripts/psql-dev.sh" },
    "prd": { "wrapper": ".claude/scripts/psql-prd.sh", "production": true }
  }
}

Each environment picks exactly one credential source:

Key Secrecy Where the DSN lives
wrapper highest inside a shell script the model can't read (see below)
url_env medium an env var read at query time — not in the config file
dsn lowest inline in the config — anything that reads the config sees it

Add "production": true to mark an environment; its tool's description warns the model to prefer dev.

In url_env / dsn mode the DSN is passed straight to psql, so Prisma/JDBC-only query params that libpq rejects (?readOnly=true, ?schema=…, connection_limit, …) are stripped automatically; libpq-valid params (sslmode, connect_timeout, …) are preserved. In wrapper mode the shell script is responsible for the DSN, so do the same stripping there if your connection string carries such params (the wrapper template notes this).

Credential isolation (wrapper mode)

The point of wrapper mode: the connection string never appears in the config, this process's environment, or any tool output. The server executes the script but never reads it, and you configure your harness to deny the model from reading it. Copy templates/psql-wrapper.sh, point it at your read-only DSN (inline, or by sourcing an existing gitignored env file), and chmod +x it. Contract: SQL arrives on stdin, psql flags arrive as "$@" and must be forwarded verbatim.

Wire into Claude Code

.mcp.json:

{
  "mcpServers": {
    "my-psql": {
      "command": "uvx",
      "args": ["--from", "/path/to/psql-mcp", "psql-mcp"],
      "env": { "PSQL_MCP_CONFIG": "${workspaceFolder}/.claude/psql-mcp.json" }
    }
  }
}

.claude/settings.json — enable the server, allow its tools, and (for wrapper mode) deny the escape routes so the isolation actually holds:

{
  "enabledMcpjsonServers": ["my-psql"],
  "permissions": {
    "allow": ["mcp__my-psql__query_dev", "mcp__my-psql__query_prd"],
    "deny": [
      "Read(.claude/scripts/**)",
      "Bash(bash .claude/scripts/psql-dev.sh:*)",
      "Bash(bash .claude/scripts/psql-prd.sh:*)"
    ]
  }
}

Changes to .mcp.json take effect on the next session (or after re-approving the server).

Verifying a release

Every release is built by a pinned GitHub Actions workflow and published to PyPI with Trusted Publishing — no long-lived API token exists to be stolen. Four independent artifacts back that claim:

What Where Proves
PEP 740 attestation PyPI, per file PyPI itself verified the upload came from this repo's publish.yml via OIDC
SLSA build provenance GitHub attestation store these exact bytes were built by this workflow, at a named commit
CycloneDX SBOM release asset + attestation the full runtime dependency set, signed
Sigstore bundle release asset (.sigstore.json) keyless signature over each artifact

To check a release yourself, first download an artifact — from the GitHub release, or straight from PyPI (pip download --no-deps psql-mcp==0.1.0):

gh release download v0.1.0 --repo maxswjeon/psql-mcp \
  --pattern 'psql_mcp-*.whl'

# SLSA build provenance
gh attestation verify psql_mcp-0.1.0-py3-none-any.whl --repo maxswjeon/psql-mcp

# CycloneDX SBOM attestation
gh attestation verify psql_mcp-0.1.0-py3-none-any.whl --repo maxswjeon/psql-mcp \
  --predicate-type https://cyclonedx.org/bom

Both exit 0 on success. gh only prints its "Verification succeeded" banner to a terminal, so in a script or CI log the exit status is the result. Pass --format json to see which workflow, git ref, and commit produced the artifact.

The .sigstore.json bundles attached to the release verify offline, without the GitHub API:

uvx --from sigstore sigstore verify identity \
  --bundle psql_mcp-0.1.0-py3-none-any.whl.sigstore.json \
  --cert-identity 'https://github.com/maxswjeon/psql-mcp/.github/workflows/publish.yml@refs/tags/v0.1.0' \
  --cert-oidc-issuer https://token.actions.githubusercontent.com \
  psql_mcp-0.1.0-py3-none-any.whl

The PyPI attestation is shown per-file under the release's "Download files" → Provenance on pypi.org/project/psql-mcp, and is checked by PyPI at upload time — a package uploaded from anywhere else would be rejected.

The release pipeline verifies its own provenance before publishing, and the upload to PyPI requires a human approval on a protected environment.

Develop

uv run --with pytest pytest        # run the hardening test suite
uv run --with mcp psql-mcp         # run the server against your config

Caveat

The Bash deny stops casual direct invocation of a wrapper, but a determined caller could spawn it from a python -c / node -e subprocess (the harness only gates the top-level command). That path still leaks nothing: a well-written wrapper only returns query rows and never echoes its DSN. The real guarantees are the Read(...) deny on the script plus the shell-escape filter.

License

MIT

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选