Mcp Postgres Query Server

Mcp Postgres Query Server

🚀 MCP PostgreSQL 查询服务器

本项目是一个模型上下文协议(MCP)服务器实现,专为以只读模式查询 PostgreSQL 数据库而设计。它能与 Claude Desktop 及其他 MCP 客户端协同工作,为用户提供安全、便捷的数据库查询服务。

🚀 快速开始

先决条件

  • Node.js(v14 或更高版本)
  • npm(随 Node.js 提供)
  • PostgreSQL 数据库(通过命令行提供的连接详细信息)

安装

# 克隆仓库
git clone https://github.com/RathodDarshil/mcp-postgres-query-server.git
cd mcp-postgres-query-server

# 安装依赖项
npm install

# 构建项目
npm run build

与 Claude Desktop 连接

您可以配置 Claude Desktop 以自动启动并连接到 MCP 服务器:

  1. 访问 Claude Desktop 的配置文件:
    • 打开 Claude Desktop
    • 转到设置 > 开发者 > 编辑配置
    • 这将在默认文本编辑器中打开配置文件
  2. claude_desktop_config.jsonmcpServers 部分添加 postgres-query-server:
{
"mcpServers": {
"postgres-query": {
"command": "node",
"args": [
"/path/to/your/mcp-postgres-query-server/dist/index.js",
"postgresql://username:password@hostname:port/database"
]
}
}
}
  1. 用实际项目目录的实际路径替换 /path/to/your/
  2. 用实际的 PostgreSQL 连接字符串替换数据库凭据
  3. 保存文件并重新启动 Claude Desktop。MCP 服务器应该现在出现在设置中的 MCP 服务器选择下拉菜单中

配置示例

以下是带有 postgres-query 的配置文件完整示例:

{
"mcpServers": {
"postgres-query": {
"command": "node",
"args": [
"/Users/darshilrathod/mcp-servers/mcp-postgres-query-server/dist/index.js",
"postgresql://user:password@localhost:5432/mydatabase"
]
}
}
}

配置更新

要更新 Claude Desktop 配置:

  1. 打开 Claude Desktop
  2. 转到设置 > 开发者 > 编辑配置
  3. 在配置文件中进行更改
  4. 保存文件
  5. 重新启动 Claude Desktop 以使更改生效
  6. 如果您已更新 MCP 服务器代码,请在重新启动之前使用 npm run build 进行重建

✨ 主要特性

  • 只读数据库访问:仅允许 SELECT 查询,确保安全
  • 查询验证:防止潜在有害的 SQL 操作
  • 超时保护:运行时间超过 10 秒的查询将被自动终止
  • MCP 协议支持:完整的模型上下文协议实现
  • JSON 响应格式化:查询结果以结构化的 JSON 格式返回

📚 详细文档

API

工具

query-postgres

对配置好的 PostgreSQL 数据库执行只读 SQL 查询。

  • 参数
    • query(字符串):要执行的 SQL SELECT 查询
  • 响应
    • JSON 对象包含:
      • rows:结果集行
      • columns:列信息
      • rowCount:行数
      • type:查询类型

示例请求

{
"procedure": "query-postgres",
"params": {
"query": "SELECT * FROM users LIMIT 10"
}
}

示例响应

{
"rows": [
{ "id": 1, "name": "Alice" },
{ "id": 2, "name": "Bob" }
],
"columns": ["id", "name"],
"rowCount": 2,
"type": "SELECT"
}

开发

配置 PostgreSQL 连接

config.js 文件中,配置 PostgreSQL 连接详细信息:

module.exports = {
host: 'localhost',
port: 5432,
user: 'yourdbuser',
password: 'yourdbpassword',
database: 'yourdatabasename'
};

运行查询

index.js 文件中,定义处理查询的逻辑:

const { Pool } = require('pg');
const pool = new Pool(require('./config'));

async function queryPostgres(query) {
try {
const result = await pool.query(query);
return {
rows: Array.from(result.rows),
columns: result.columns,
rowCount: result.rowCount,
type: result.command
};
} catch (error) {
throw new Error(`Query failed: ${error.message}`);
}
}

module.exports = { queryPostgres };

🔧 技术细节

此项目实现了以下功能的模型上下文协议(MCP)服务器:

  1. 提供安全、只读接口访问 PostgreSQL 数据库
  2. 与 Claude Desktop 通过 MCP 协议集成
  3. SQL 查询验证,确保仅执行 SELECT 查询
  4. 查询超时保护(10 秒)

📄 许可证

文档未提及相关信息,暂不展示。

⚠️ 重要提示

  • 确保 PostgreSQL 凭据安全,避免明文存储
  • 配置适当的防火墙规则以限制数据库访问
  • 定期备份数据库以防数据丢失
  • 启用 SSL 连接以加密与数据库的通信
  • 0 关注
  • 0 收藏,11 浏览
  • system 提出于 2025-09-24 19:30

相似服务问题