Skip to main content
Glama
krishamehta09

Postgres Analytics MCP Server

Postgres Analytics MCP Server

一个模型上下文协议(MCP)服务器,让 AI 助手(Claude、Cursor 及其他兼容 MCP 的客户端)能够安全地检查和查询 PostgreSQL 数据库——具备强制只读、行数/超时限制以及完整的审计日志。

它旨在回答一个简单的问题:如何让 AI 代理接触真实数据库,却不给它破坏任何东西的能力?

它能做什么

连接后,AI 客户端可以提出如下问题:

  • “我的数据库里有哪些表?”

  • “显示最近 10 笔订单。”

  • “为什么这个查询很慢?”

  • “哪些表缺少索引?”

服务器通过 MCP 暴露 5 个工具:

Tool

Purpose

list_schemas

列出所有非系统模式

list_tables

列出指定模式中的表

run_query

执行只读 SQL 查询(仅 SELECT/WITH)

explain_query

返回查询执行计划并标记是否缓慢

get_table_stats

返回表的行数估算及索引/顺序扫描计数

Related MCP server: PostgreSQL MCP Server

为什么存在

企业正越来越多地将 AI 代理连接到内部系统(数据库、Kubernetes、API),而难点在于如何安全地做到这一点。本项目就是一个小而具体的示例:在 AI 客户端与生产级数据库之间架起一座受保护的桥梁。

设计决策

默认只读,双重保障:每个查询都会对照黑名单进行校验,并且必须以 SELECT、WITH 或 EXPLAIN 开头。数据库连接本身也以只读模式打开,作为第二道防线。

行数限制与查询超时:每个查询都设有可配置的行数上限和语句超时,因此不会返回无界数据或挂起服务器。

认证信息存放在进程环境中,而非对话中:API 密钥通过 MCP 客户端配置以环境变量的方式设置,AI 模型永远不会直接看到或处理它。

审计日志:每次工具调用都会记录时间戳、工具名称、参数和结果。

设置

要求:Python 3.11+、PostgreSQL

  1. 创建虚拟环境并安装依赖: python -m venv venv venv\Scripts\Activate.ps1 pip install -r requirements.txt

  2. 创建数据库并加载示例模式: psql -U postgres -c "CREATE DATABASE sampledb;" psql -U postgres -d sampledb -f seed.sql

  3. 将 .env.example 复制为 .env 并填入你自己的值。

  4. 直接运行以进行快速检查: python -m server.main

连接 Claude Desktop

添加到 claude_desktop_config.json(Claude Desktop -> Settings -> Developer -> Edit Config):

"mcpServers": {
  "postgres-analytics": {
    "command": "C:\\path\\to\\venv\\Scripts\\python.exe",
    "args": ["-m", "server.main"],
    "env": {
      "PYTHONPATH": "C:\\path\\to\\project",
      "MCP_API_KEY": "same-value-as-in-.env"
    }
  }
}

技术栈

Python、PostgreSQL、MCP Python SDK、psycopg2

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables AI assistants to safely interact with PostgreSQL databases through read-only operations, providing schema discovery, table inspection, and query execution capabilities with structured context awareness.
    MIT
  • A
    license
    Not graded
    quality
    D
    maintenance
    Provides read-only access to PostgreSQL databases, enabling users to list tables, view table structures and statistics, and execute SELECT queries safely through natural language.
    161 npm
    MIT
  • F
    license
    A
    quality
    D
    maintenance
    Enables AI agents to inspect and query PostgreSQL databases safely, with features like listing tables, retrieving schemas, and running read-only SQL queries.
    3
    -
  • F
    license
    Not graded
    quality
    D
    maintenance
    Enables AI assistants to safely interact with PostgreSQL databases, perform queries, inspect schemas, and analyze query performance.
    2
    -