npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

user-postgresql-mcp

v0.1.7

Published

A PostgreSQL MCP server built with @modelcontextprotocol/sdk.

Downloads

311

Readme

PostgreSQL MCP 服务

这是一个使用 @modelcontextprotocol/sdkpg 实现的 PostgreSQL MCP 服务器,可在 Cursor / 其他 MCP 客户端中安全地访问和管理 PostgreSQL。

  • 默认只读工具安全:查询、元数据、统计、监控等工具全部在 READ ONLY 事务中执行。
  • 写入工具始终可用:写工具(如 execute_sql / execute_mutation / create_database / create_role 等)始终可用,请仅在安全环境或具备相应权限控制的实例上使用。

当前提供的主要能力包括(不完全列表,详细见 tools.md):

  • 查询 & 性能query, explain, table_stats, index_stats, database_overview
  • 元数据 & 架构list_schemas, list_tables, describe_table, list_views, list_materialized_views, list_partitions
  • 连接 & 监控sessions, locks, current_connection_info
  • 配置 & 系统config_params, list_databases, list_tablespaces, list_extensions
  • 角色 & 权限list_roles, create_role, alter_role_password, grant_role, revoke_role
  • 数据库管理database_exists, create_database, drop_database
  • 对象存在性检查object_exists
  • 写操作执行(需开启写权限)execute_mutation, execute_sql, refresh_materialized_view

1. 环境准备

  • 前提条件
    • 已安装 Node.js(建议 18+)
    • 可访问的 PostgreSQL 实例
  • 克隆 / 放置本项目 到任意目录(例如:f:\PostgreSQL_MCP

2. 安装依赖

在项目根目录执行:

npm install

3. 配置数据库连接

本服务支持两种方式配置数据库连接:

  1. 使用连接串 PG_CONNECTION_STRING(推荐在本地开发时使用):

    set PG_CONNECTION_STRING=postgres://user:password@localhost:5432/mydb

    在 Windows PowerShell 中可以使用:

    $env:PG_CONNECTION_STRING = "postgres://user:password@localhost:5432/mydb"
  2. 使用分散的 PG* 环境变量(类似官方 @modelcontextprotocol/server-postgres 的配置):

    需要同时设置以下变量:PGHOST, PGPORT, PGDATABASE, PGUSER, PGPASSWORD

    例如在 Cursor settings.json 里使用:

    {
      "mcpServers": {
        "user-postgresql-mcp": {
          "command": "node",
          "args": ["dist/index.js"],
          "env": {
            "PGHOST": "localhost",
            "PGPORT": "5432",
            "PGDATABASE": "postgres",
            "PGUSER": "postgres",
            "PGPASSWORD": "your_password"
          }
        }
      }
    }

注意:当前 MCP 服务器只会在 READ ONLY 事务 中执行查询,不会修改数据库。

4. 构建与运行

构建 TypeScript:

npm run build

直接运行(开发调试):

npm run dev

生产运行(用于 MCP 客户端调用):

npm start

5. 在 Cursor 中配置 MCP(本地工程方式)

如果你是从源码克隆本项目并在本机运行(例如目录为 F:\PostgreSQL_MCP),可以在 项目内 创建 .cursor/mcp.json(当前仓库已经自带一个示例):

{
  "mcpServers": {
    "user-postgresql-mcp": {
      "command": "node",
      "args": ["dist/index.js"],
      "cwd": "F:/PostgreSQL_MCP",
      "env": {
        "PG_CONNECTION_STRING": "postgresql://postgres:password@localhost:5432/mydb"
      }
    }
  }
}

说明:

  • cwd:指向本项目根目录,确保 dist/index.js 能被找到。
  • PG_CONNECTION_STRING:改成你自己的连接串;也可以改用 PGHOST/PGPORT/...
  • PG_MCP_ALLOW_WRITE
    • "false":只读模式(推荐默认)。
    • "true":允许写操作(execute_sql / execute_mutation / create_database / create_role 等),请仅在安全的环境中开启。

保存后在 Cursor 中打开该项目目录,重启一次 Cursor,即可在 MCP 工具列表中看到 user-postgresql-mcp


6. 通过 npm / npx 在任意项目中使用

发布到 npm 后(假设包名为 user-postgresql-mcp),可以不再依赖本地源码目录,而是直接通过 npx 启动 MCP 服务器。

6.1 全局安装(可选)

npm install -g user-postgresql-mcp

然后在 Cursor 的用户级 MCP 配置中(例如 C:\Users\<你>\AppData\Roaming\Cursor\User\mcp.json)添加:

{
  "mcpServers": {
    "user-postgresql-mcp": {
      "command": "user-postgresql-mcp",
      "args": [],
      "env": {
        "PG_CONNECTION_STRING": "postgresql://postgres:password@localhost:5432/mydb"
      }
    }
  }
}

6.2 使用 npx(推荐)

无需全局安装,直接在任意项目的 .cursor/mcp.json 中配置:

{
  "mcpServers": {
    "user-postgresql-mcp": {
      "command": "npx",
      "args": ["-y", "user-postgresql-mcp"],
      "env": {
        "PG_CONNECTION_STRING": "postgresql://postgres:password@localhost:5432/mydb"
      }
    }
  }
}
  • Cursor 启动 MCP 时会自动通过 npx 拉取并运行 user-postgresql-mcp 包的入口(dist/index.js)。
  • 环境变量配置方式与本地工程模式相同。

7. 工具详细说明

下面列出部分常用工具的详细说明,更完整的列表可参见项目根目录的 tools.md

7.1 query —— 执行只读查询

  • 语义:对 PostgreSQL 执行 只读 SQL 查询,自动开启 BEGIN READ ONLY,禁止非 SELECT 语句。
  • 入参(JSON 对象):
    • sql (string, 必填):要执行的 SQL,只允许只读语句(必须以 SELECT 开头)
    • maxRows (integer, 可选):最多返回的行数,默认 100,最大 1000

示例:

{
  "sql": "SELECT id, name FROM users ORDER BY id DESC LIMIT 20",
  "maxRows": 20
}

返回结果是一个 JSON 文本,包含:

  • rowCount:返回行数
  • fields:字段名称及类型 ID
  • rows:具体数据行数组

你可以在对话中直接让助手调用 query 工具来做任意只读查询。


7.2 list_schemas —— 列出 schema

  • 语义:列出当前数据库中的 schema 名称。
  • 入参(JSON 对象,可全部省略):
    • includeSystemSchemas (boolean, 可选):是否包含系统 schema(pg_*information_schema),默认 false

示例:

{
  "includeSystemSchemas": false
}

返回结果 JSON 文本:

  • schemas:字符串数组,例如 ["public", "analytics"]

7.3 list_tables —— 列出某个 schema 下的表 / 视图

  • 语义:基于 information_schema.tables 列出表与视图。
  • 入参
    • schema (string, 可选):要查询的 schema 名称,默认 "public"
    • includeViews (boolean, 可选):是否包含视图,默认 true

示例:

{
  "schema": "public",
  "includeViews": true
}

返回结果 JSON 文本:

  • schema:本次查询的 schema 名称
  • tables:数组,每项形如:
    • name:表/视图名称
    • type:对应 information_schema.tables.table_type(如 "BASE TABLE" / "VIEW"

7.4 describe_table —— 查看表结构

  • 语义:基于 information_schema.columns 查看表的列信息。
  • 入参
    • schema (string, 可选):表所属的 schema,默认 "public"
    • table (string, 必填):表名

示例:

{
  "schema": "public",
  "table": "users"
}

返回结果 JSON 文本:

  • schema:schema 名称
  • table:表名
  • columns:列信息数组,每项:
    • name:列名
    • dataType:数据类型(如 integer, text, timestamp without time zone 等)
    • nullable:是否可空(布尔值)
    • default:默认值表达式或 null

7.5 explain —— 查看执行计划

  • 语义:对只读 SELECT 语句执行 EXPLAINEXPLAIN ANALYZE,用于分析执行计划和性能。
  • 入参
    • sql (string, 必填):要分析的 SQL,只允许 SELECT 开头
    • analyze (boolean, 可选):是否使用 EXPLAIN ANALYZE,默认 false

示例:

{
  "sql": "SELECT * FROM users WHERE email LIKE '%@example.com'",
  "analyze": false
}

返回结果为 EXPLAIN 的文本输出(多行字符串),你可以直接在对话里查看执行计划。

建议

  • 对大表或复杂查询,先使用 analyze: false 看逻辑计划;
  • 确认安全后再考虑 EXPLAIN ANALYZE 以获取实际运行时间。

7.6 table_stats —— 表统计与大小

  • 语义:基于 pg_stat_all_tables / pg_class / pg_namespace 等视图,查看表的行数估算、扫描次数以及磁盘大小。
  • 入参
    • schema (string, 可选):要过滤的 schema 名称,默认 "public"
    • table (string, 可选):要过滤的表名;不填则返回该 schema 下所有普通表 / 分区表

示例:

{
  "schema": "public"
}

返回结果 JSON 文本:

  • schema:本次查询的 schema 名称
  • table:如果有按表过滤则为表名,否则省略
  • tables:数组,每项包含:
    • schema:schema 名称
    • name:表名
    • kind:表类型(普通表 / 分区表等)
    • estimatedRows:估算行数(来自 reltuples
    • seqScan / idxScan:顺序扫描 / 索引扫描次数
    • liveTuples / deadTuples:活元组 / 死元组估算
    • tableSizeBytes / indexSizeBytes / totalSizeBytes:表/索引/总大小(字节数)

7.7 index_stats —— 索引统计与大小

  • 语义:基于 pg_stat_all_indexes / pg_indexes / pg_index 等视图,查看索引使用情况与大小。
  • 入参
    • schema (string, 可选):要过滤的 schema 名称,默认 "public"
    • table (string, 可选):要过滤的表名

示例:

{
  "schema": "public",
  "table": "users"
}

返回结果 JSON 文本:

  • schema:本次查询的 schema 名称
  • table:如果有按表过滤则为表名,否则省略
  • indexes:数组,每项包含:
    • schema:schema 名称
    • table:表名
    • name:索引名
    • idxScan / idxTupRead / idxTupFetch:索引扫描次数及读/取行数
    • sizeBytes:索引大小(字节)
    • isUnique / isPrimary:是否唯一索引 / 主键索引
    • definition:索引定义(CREATE INDEX ... 语句)

7.8 sessions —— 当前会话(pg_stat_activity)

  • 语义:基于 pg_stat_activity 查看当前连接到数据库的会话信息,用于排查热点查询、长事务等问题。
  • 入参
    • state (string, 可选):按会话状态过滤,如 "active" / "idle" / "idle in transaction" 等;不填则不过滤
    • limit (integer, 可选):最多返回的会话数量,默认 50,最大 200

示例:

{
  "state": "active",
  "limit": 20
}

返回结果 JSON 文本:

  • state:当前使用的状态过滤(如有)
  • limit:返回条数上限
  • sessions:数组,对应 pg_stat_activity 的精简列(pid, usename, datname, state, query 等)

7.9 locks —— 当前锁信息(pg_locks)

  • 语义:基于 pg_lockspg_stat_activity 等视图,查看数据库中的锁情况,帮助排查死锁或等待问题。
  • 入参
    • limit (integer, 可选):最多返回的锁记录数,默认 100,最大 200

示例:

{
  "limit": 100
}

返回结果 JSON 文本:

  • limit:返回条数上限
  • locks:数组,每项包含锁类型、模式、是否已授予、相关表/事务 ID、以及可能关联的会话信息(应用名、用户名、SQL 语句等)。

7.10 database_overview —— 数据库整体概况

  • 语义:汇总当前数据库的一些关键指标,例如数据库大小、表数量、连接数等。
  • 入参
    • 无入参,调用时可传空对象 {}

示例:

{}

返回结果 JSON 文本:

  • database:当前数据库名
  • sizeBytes:数据库总大小(字节)
  • tableCount:非系统 schema 下的表数量
  • connectionCount:当前连接到该数据库的会话数量
  • activeConnections:其中处于 active 状态的会话数量

7.11 config_params —— 配置参数(pg_settings)

  • 语义:基于 pg_settings 查看实例级配置参数,方便分析性能 / 行为(例如 work_mem, shared_buffers 等)。
  • 入参
    • pattern (string, 可选):按参数名做模糊匹配,例如 "work_mem";不填则返回全部参数。

示例:

{
  "pattern": "work_mem"
}

返回结果 JSON 文本:

  • pattern:当前使用的过滤关键词(如有)
  • parameters:数组,每项对应一行 pg_settings 的精简信息(name, setting, unit, vartype, short_desc, source, boot_val, reset_val, pending_restart)。