关于 read-only-local-postgres-mcp-server
read-only-local-postgres-mcp-server 让 Claude Desktop 和 Claude Code 通过自然语言查询 PostgreSQL,适合需要安全读取数据库信息的用户。它支持运行时切换连接,并以语句校验和数据库只读事务限制查询。
主要功能
- 01执行只读 SQL 查询
- 02运行时连接不同 PostgreSQL 数据库
- 03切换连接或执行单次查询
- 04返回 JSON 格式结果
- 05校验语句并使用只读事务
适用场景
- 01查看数据库中的表和结构
- 02统计订单或销售记录
- 03在默认库与临时目标库间查询
MCP 相关
该 MCP 服务向 Claude Desktop 和 Claude Code 提供 connect、disconnect 和 query 工具。客户端可查询默认或运行时指定的 PostgreSQL 数据库;查询受到只读限制。
配置
本地服务的配置在各客户端中通用,复制后粘贴到客户端的 MCP 配置文件即可。
工具
3收录的工具列表 · 更新于 2 周前
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| connectionString | string | 是 | PostgreSQL 连接字符串(例如,postgres://user:password@host:5432/database?sslmode=require) |
详细介绍
PostgreSQL MCP 服务
一个模型上下文协议(MCP)服务,可让 Claude Desktop 通过自然语言查询与 PostgreSQL 数据库交互。
功能
- 通过 Claude Desktop 或 Claude Code 执行只读 SQL 查询
- 动态数据库连接 - 可在运行时连接到任意 PostgreSQL 数据库
- 内置安全机制:语句验证,以及由数据库强制执行的
READ ONLY事务 - 轻松集成 Claude Desktop 和 Claude Code
- 以 JSON 格式返回查询结果
- 基于环境变量的默认配置,并支持运行时覆盖
快速开始
Claude Code 用户(推荐 - 最简单的方法)
claude mcp add postgres -s user -- npx -y @hovecapital/read-only-postgres-mcp-server
然后设置数据库环境变量:
export DB_HOST=localhost
export DB_PORT=5432
export DB_DATABASE=your_database_name
export DB_USERNAME=your_username
export DB_PASSWORD=your_password
完成! 重启 Claude Code,然后询问:“我的数据库中有哪些表?”
Claude Desktop 用户(手动配置)
1. 打开配置文件:
# macOS
open ~/Library/Application\ Support/Claude/claude_desktop_config.json
# Windows
notepad %APPDATA%\Claude\claude_desktop_config.json
2. 添加以下配置:
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["-y", "@hovecapital/read-only-postgres-mcp-server"],
"env": {
"DB_HOST": "localhost",
"DB_PORT": "5432",
"DB_DATABASE": "your_database_name",
"DB_USERNAME": "your_username",
"DB_PASSWORD": "your_password"
}
}
}
}
3. 保存、重启 Claude Desktop 并测试!
前提条件
- Node.js(v16 或更高版本)- 如果使用 mise,请相应更新命令路径
- PostgreSQL 数据库服务
- Claude Desktop 应用
安装
选项 1:从 MCP Registry 安装(推荐)
此服务已作为 capital.hove/read-only-local-postgres-mcp-server 发布到 Model Context Protocol Registry。
方法 A:Claude Code CLI(最简单!)
claude mcp add postgres -s user -- npx -y @hovecapital/read-only-postgres-mcp-server
然后使用环境变量配置数据库凭据。重启 Claude Code 即可完成!
优点:
- 一条命令即可安装
- 无需手动编辑 JSON
- 自动配置
方法 B:手动配置 JSON
对于 Claude Desktop:
编辑 ~/Library/Application Support/Claude/claude_desktop_config.json(macOS)或 %APPDATA%\Claude\claude_desktop_config.json(Windows):
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["-y", "@hovecapital/read-only-postgres-mcp-server"],
"env": {
"DB_HOST": "localhost",
"DB_PORT": "5432",
"DB_DATABASE": "your_database_name",
"DB_USERNAME": "your_username",
"DB_PASSWORD": "your_password"
}
}
}
}
对于 Claude Code:
编辑 ~/.config/claude-code/settings.json(macOS/Linux)或 %APPDATA%\claude-code\settings.json(Windows):
{
"mcp": {
"servers": {
"postgres": {
"command": "npx",
"args": ["-y", "@hovecapital/read-only-postgres-mcp-server"],
"env": {
"DB_HOST": "localhost",
"DB_PORT": "5432",
"DB_DATABASE": "your_database_name",
"DB_USERNAME": "your_username",
"DB_PASSWORD": "your_password"
}
}
}
}
}
选项 2:从 npm 安装
npm install -g @hovecapital/read-only-postgres-mcp-server
选项 3:使用 Claude Code 安装
如果你使用 Claude Code,可以轻松安装此 MCP 服务:
# Clone the repository
git clone https://github.com/hovecapital/read-only-local-postgres-mcp-server.git
cd read-only-local-postgres-mcp-server
# Install dependencies and build
npm install
npm run build
然后将配置添加到 MCP 设置中,以配置 Claude Code。
选项 4:手动安装
1. 克隆或下载
将仓库保存到系统中的某个目录:
mkdir ~/mcp-servers/postgres
cd ~/mcp-servers/postgres
git clone https://github.com/hovecapital/read-only-local-postgres-mcp-server.git .
2. 安装依赖
npm install
npm run build
配置
注意: 如果你通过选项 1(使用 npx 从 MCP Registry 安装)完成安装,则已配置好所有内容!本节适用于选择选项 2、3 或 4(npm 或手动安装)的用户。
Claude Code 配置
如果你使用 Claude Code 手动安装,请将 PostgreSQL 服务添加到 MCP 设置中:
-
打开 Claude Code 设置(通常位于 macOS/Linux 的
~/.config/claude-code/settings.json或 Windows 的%APPDATA%\claude-code\settings.json) -
添加 PostgreSQL MCP 服务配置:
{
"mcp": {
"servers": {
"postgres": {
"command": "node",
"args": ["/absolute/path/to/read-only-local-postgres-mcp-server/dist/index.js"],
"env": {
"DB_HOST": "localhost",
"DB_PORT": "5432",
"DB_DATABASE": "your_database_name",
"DB_USERNAME": "your_username",
"DB_PASSWORD": "your_password"
}
}
}
}
}
- 重启 Claude Code 以使更改生效。
Claude Desktop 配置
如果你使用 Claude Desktop 手动安装,请打开 Claude Desktop 配置文件:
macOS:
~/Library/Application Support/Claude/claude_desktop_config.json
Windows:
%APPDATA%\Claude\claude_desktop_config.json
添加 PostgreSQL 服务配置:
{
"mcpServers": {
"postgres": {
"command": "node",
"args": ["/absolute/path/to/read-only-local-postgres-mcp-server/dist/index.js"],
"env": {
"DB_HOST": "localhost",
"DB_PORT": "5432",
"DB_DATABASE": "your_database_name",
"DB_USERNAME": "your_username",
"DB_PASSWORD": "your_password"
}
}
}
}
使用 mise 管理 Node.js
如果你使用 mise 管理 Node.js 版本,请确保在配置中使用 Node.js 可执行文件的完整路径。
环境变量
| 变量 | 描述 | 默认值 |
|---|---|---|
DB_HOST | PostgreSQL 服务主机名 | localhost |
DB_PORT | PostgreSQL 服务端口 | 5432 |
DB_DATABASE | 数据库名称 | postgres |
DB_USERNAME | PostgreSQL 用户名 | postgres |
DB_PASSWORD | PostgreSQL 密码 | (空) |
DB_SSL | 启用 SSL 连接 | false |
DB_ALLOWED_HOSTS | 逗号分隔的 host:port 对,运行时连接字符串除 DB_HOST:DB_PORT 外还可指定这些目标 | (空) |
工具
此 MCP 服务提供三个工具,Claude 可通过它们与 PostgreSQL 数据库交互。
connect
使用连接字符串连接到 PostgreSQL 数据库。此连接会持续用于后续查询,直到更改或断开连接。目标必须是 DB_HOST:DB_PORT 或列在 DB_ALLOWED_HOSTS 中。
参数:
| 参数 | 类型 | 必填 | 描述 |
|---|---|---|---|
connectionString | string | 是 | PostgreSQL 连接字符串 |
连接字符串格式:
postgres://username:password@host:port/database?sslmode=require
postgresql://username:password@host:port/database
支持的 SSL 模式:
sslmode=require- 要求使用 SSL(建议用于远程连接)sslmode=verify-full- 要求使用 SSL 并验证证书- 不设置 sslmode 参数 - 不使用 SSL(用于本地连接)
使用示例(自然语言):
"Connect to postgres://myuser:[email protected]:5432/production"
"Connect to this database: postgres://admin:secret@localhost/analytics"
响应:
{
"status": "connected",
"host": "db.example.com",
"port": 5432,
"database": "production",
"user": "myuser",
"ssl": true
}
disconnect
断开与当前运行时数据库的连接,并恢复为由默认环境配置的连接。
参数: 无
使用示例(自然语言):
"Disconnect from the current database"
"Go back to the default database"
响应:
{
"status": "disconnected",
"message": "Reverted to default environment connection",
"host": "localhost",
"database": "postgres"
}
query
对当前连接的数据库运行只读 SQL 查询。也可以为单次查询指定其他连接。
参数:
| 参数 | 类型 | 必填 | 描述 |
|---|---|---|---|
sql | string | 是 | 要执行的 SQL 查询(仅限 SELECT) |
connectionString | string | 否 | 仅为此次查询指定其他连接 |
使用示例(自然语言):
"Show me all tables in the database"
"SELECT * FROM users LIMIT 10"
"Run this query on postgres://other:pass@host/db: SELECT count(*) FROM orders"
响应:
[
{ "id": 1, "name": "Alice", "email": "[email protected]" },
{ "id": 2, "name": "Bob", "email": "[email protected]" }
]
面向大模型的工具参考
使用此 MCP 服务时,Claude 可以:
-
查询默认数据库(通过环境变量配置):
User: "What tables are in my database?" Claude: [Uses query tool with SQL: "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'"] -
动态连接到其他数据库:
User: "Connect to postgres://user:pass@newhost/newdb and show me the users table" Claude: [Uses connect tool first, then query tool] -
对其他数据库执行单次查询(不切换活动连接):
User: "How many records are in the orders table on postgres://user:pass@analytics/warehouse?" Claude: [Uses query tool with connectionString parameter] -
恢复默认连接:
User: "Go back to my local database" Claude: [Uses disconnect tool]
使用方法
- 更新配置后重启 Claude Desktop/Code
- 开始与 Claude 聊天,询问有关数据库的问题
查询示例
基本查询(使用默认/活动连接):
"Show me all tables in my database"
"What's the structure of the users table?"
"Get the first 10 records from the products table"
"How many orders were placed last month?"
"Show me users with email addresses ending in @gmail.com"
动态连接示例:
"Connect to postgres://analyst:[email protected]:5432/warehouse"
"Now show me all the tables"
"What's the total revenue in the sales table?"
"Disconnect and go back to my local database"
对其他数据库执行单次查询:
"Run SELECT count(*) FROM users on postgres://admin:[email protected]/app"
"Check the orders table on my staging database: postgres://dev:dev@staging/app"
Claude 会自动将你的自然语言请求转换为适当的 SQL 查询,并对数据库执行这些查询。
安全功能
只读操作
服务器通过三层机制,对所有连接(包括通过环境变量配置的连接和运行时动态连接)强制执行只读访问:
- 由数据库强制执行的只读事务。 每个查询都在
BEGIN READ ONLY中运行,之后连接会关闭,因此不会提交任何内容。PostgreSQL 本身会拒绝INSERT、UPDATE、DELETE、MERGE、DDL、SELECT INTO、nextval()、大对象写入,以及隐藏在 CTE(WITH x AS (INSERT ...) SELECT ...)或函数体中的任何写入,无论语句采用何种写法。 - 每个查询只能包含一条语句。 查询通过扩展查询协议发送,PostgreSQL 会将其限制为一条语句,因此服务器会拒绝
SELECT 1; DROP TABLE ...。 - 执行前验证语句。 移除开头的注释后,如果查询以以下任一语句关键字开头,则会被拒绝:
- 数据操作 -
INSERT、UPDATE、DELETE、TRUNCATE、COPY、MERGE - 架构 / DDL -
CREATE、ALTER、DROP、COMMENT、RENAME、REASSIGN - 权限 -
GRANT、REVOKE、SECURITY - 会话 / 配置 -
SET、RESET、DISCARD、LOAD - 过程 / 动态执行 -
CALL、DO、EXECUTE、PREPARE、DEALLOCATE - 游标 -
DECLARE、FETCH、MOVE、CLOSE - 事务控制 -
BEGIN、START、COMMIT、ROLLBACK、SAVEPOINT、RELEASE、LOCK - 维护 -
VACUUM、ANALYZE、REINDEX、CLUSTER、REFRESH、CHECKPOINT - 异步通知 -
NOTIFY、LISTEN、UNLISTEN
只有以读取类动词(例如 SELECT、WITH、EXPLAIN、SHOW、TABLE、VALUES)开头的语句才会获准执行。由于 EXPLAIN ANALYZE 会执行其包装的语句,因此也会验证内部语句。
只读事务无法阻止会访问服务器文件系统、运行任意 SQL 或更改进程状态的函数。因此,如果查询文本中任何位置包含以下任一内容,也会被拒绝:pg_read_file、pg_read_binary_file、pg_stat_file、pg_ls_*、pg_file_*、pg_logdir_ls、pg_logfile_rotate、lo_import、lo_export、dblink*、query_to_xml*、crosstab*、connectby、set_config、pg_terminate_backend、pg_cancel_backend、pg_reload_conf、pg_rotate_logfile、pg_sleep*。Unicode 转义标识符(U&"...")也会被拒绝,因为它们可能以其他形式写出上述名称。
函数名称匹配采用拒绝列表,无法涵盖所有情况。下面介绍的专用只读角色会移除文件操作所需的底层权限(pg_write_server_files、pg_read_server_files、超级用户权限),建议使用此配置。
动态连接安全性
使用 connect 工具或 connectionString 参数时:
- 主机允许列表 - 运行时连接字符串只能指向
DB_HOST:DB_PORT或DB_ALLOWED_HOSTS中列出的host:port地址。其他目标会在打开任何套接字之前被拒绝,因此无法使用这些工具扫描主机或其网络上的端口。 - 仍会强制执行只读限制 - 无论连接来源如何,都会验证所有查询
- 不会记录凭据 - 包含密码的连接字符串绝不会写入日志
- 响应会进行脱敏 -
connect工具的响应不包含密码 - 基于会话 - 运行时连接只在当前 MCP 会话中保持有效
推荐的数据库设置
为增强安全性,请为 MCP 服务创建专用的只读用户:
-- Create a read-only user
CREATE USER claude_readonly WITH PASSWORD 'secure_password';
-- Grant only SELECT permissions on your specific schema
GRANT USAGE ON SCHEMA public TO claude_readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO claude_readonly;
-- Grant permissions for future tables (optional)
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO claude_readonly;
故障排除
连接问题
- 确认 PostgreSQL 正在运行:检查 PostgreSQL 服务器是否处于活动状态
- 检查凭据:确保用户名和密码正确
- 网络连接:确认 Claude Desktop 可以连接到 PostgreSQL 服务器
配置问题
- 需要重启:配置更改后,务必重启 Claude Desktop
- 路径准确性:确保
dist/index.js的绝对路径正确 - JSON 语法:验证
claude_desktop_config.json格式
调试模式
如需查看服务日志,可以手动运行服务:
node dist/index.js
文件结构
~/mcp-servers/postgres/
├── src/
│ └── index.ts
├── dist/
│ ├── index.js
│ └── index.d.ts
├── package.json
├── tsconfig.json
└── node_modules/
依赖项
- @modelcontextprotocol/sdk:MCP 协议实现
- pg:Node.js 的 PostgreSQL 客户端
贡献
欢迎提交问题和改进建议!
许可证
本项目为开源项目,采用 MIT License。
支持
如果遇到问题:
- 查看上方的故障排除部分
- 独立验证 PostgreSQL 连接
- 确保 Claude Desktop 已更新到最新版本
- 查看 Claude Desktop MCP 文档
注意:此服务专为开发和分析用途而设计。用于生产环境时,请考虑采取额外的安全措施并进行监控。
评论
一个开放协议,规定了 AI 应用如何以统一方式连接外部工具与数据源。客户端负责与模型对话,MCP 服务负责提供工具、资源和提示模板,两者通过标准消息通信,同一个服务可以被不同客户端复用。