Skip to main content
Glama

pg-context

模型上下文协议 (MCP) 服务器,为 AI 编码助手提供深度 PostgreSQL 上下文:实时的模式以 DDL 形式呈现、索引健康状况、外键关联、查询执行计划和性能统计。

pg-context 以只读模式直接连接到您的 PostgreSQL 数据库,并为 Cursor、Claude Code、Cline 和 Antigravity 等 AI 助手提供工具和资源。


为什么选择 pg-context?

通用的 SQL 工具通常执行任意查询,却不向 AI 助手提供结构上下文。这会导致模型猜测列名、臆造关系并生成无效的连接。

pg-context 通过以下方式解决这一问题:

  • 零猜测模式上下文:以 PostgreSQL CREATE TABLE DDL 语句的形式导出真实的表结构,包含外键注释和索引定义。

  • 只读安全:自动在每个客户端连接上设置 default_transaction_read_only = ON,并拒绝修改数据的 SQL 语句(例如 DROP、DELETE、UPDATE、INSERT、TRUNCATE、ALTER)。

  • 优化洞察:检测未建立索引的外键、高顺序扫描比率、未使用的索引,以及来自 pg_stat_statements 的慢查询。

  • 扩展感知:识别 PostGIS、TimescaleDB 和 pgvector 扩展。


Related MCP server: PostgreSQL MCP Server

快速开始

您可以通过 npx 直接运行 pg-context,无需手动安装:

npx -y pg-context-mcp

或者全局安装:

npm install -g pg-context-mcp
pg-context-mcp

配置

pg-context 从环境变量或标准 PostgreSQL 连接字符串中读取连接参数:

变量

描述

默认值

DATABASE_URL

标准 PostgreSQL 连接 URI

undefined

PGHOST

数据库主机

localhost

PGPORT

数据库端口

5432

PGDATABASE

数据库名称

postgres

PGUSER

数据库用户

postgres

PGPASSWORD

数据库密码

""

PGSSL

启用 SSL 连接(true/false)

false

PG_SCHEMAS

逗号分隔的目标模式列表

public

PG_MAX_CONNECTIONS

连接池大小

5

PG_CACHE_TTL

模式缓存 TTL(秒)

60

PG_QUERY_LIMIT

read_query 的默认行数限制

100

PG_QUERY_LIMIT_MAX

read_query 的硬性上限

1000


客户端集成

1. Claude Desktop 与 Antigravity

将以下条目添加到您的 claude_desktop_config.json 或 Antigravity MCP 设置中:

{
  "mcpServers": {
    "pg-context": {
      "command": "npx",
      "args": ["-y", "pg-context-mcp"],
      "env": {
        "DATABASE_URL": "postgresql://user:password@localhost:5432/my_database"
      }
    }
  }
}

2. Cursor

将以下内容添加到您的 Cursor MCP 配置中(.cursor/mcp.json 或 Cursor 设置 > 功能 > MCP):

{
  "mcpServers": {
    "pg-context": {
      "command": "npx",
      "args": ["-y", "pg-context-mcp"],
      "env": {
        "DATABASE_URL": "postgresql://user:password@localhost:5432/my_database"
      }
    }
  }
}

3. Cline(VS Code 扩展)

将此配置添加到 cline_mcp_settings.json 中:

{
  "mcpServers": {
    "pg-context": {
      "command": "npx",
      "args": ["-y", "pg-context-mcp"],
      "env": {
        "DATABASE_URL": "postgresql://user:password@localhost:5432/my_database"
      }
    }
  }
}

工具参考

pg-context 提供 12 个 MCP 工具:

工具

参数

描述

list_schemas

无

列出数据库中所有非系统模式。

list_tables

schema(默认:"public")

列出表和视图及其大小、估计行数和注释。

describe_table

table、schema(默认:"public")

返回表的完整结构 DDL,包括列、类型、默认值、NOT NULL、外键和索引。

list_foreign_keys

schema(默认:"public")、table(可选)

以可读的 source -> target 关联形式显示外键关系。

list_indexes

schema(默认:"public")、table(可选)

显示索引、定义、大小和扫描计数。

suggest_indexes

schema(默认:"public")、table(可选)

识别未建立索引的外键、顺序扫描警告和未使用的索引。

read_query

sql、limit(可选)

以强制限制执行只读查询,并返回 Markdown 表格。

explain_query

sql、analyze(布尔值,默认:false)

从 PostgreSQL 的 EXPLAIN 或 EXPLAIN ANALYZE 返回查询执行计划。

get_database_info

无

返回 PostgreSQL 版本、数据库总大小、连接计数和缓冲区设置。

get_table_stats

schema(默认:"public")、table(可选)

返回顺序扫描与索引扫描、活动行、死行以及维护日期。

get_slow_queries

limit(默认:15)

获取由 pg_stat_statements 记录的耗时最长的前若干查询。

list_extensions

无

列出已安装的 PostgreSQL 扩展,并标记 PostGIS、TimescaleDB 和 pgvector 的能力。


资源参考

pg-context 提供 3 个 MCP 资源:

资源 URI

MIME 类型

描述

pg://schema/full

text/x-sql

所有已配置模式中所有表的完整 DDL 转储。

pg://schema/{tableName}

text/x-sql

单个表的 DDL 定义。

pg://stats/overview

text/markdown

数据库健康概览:存储大小、死行和优化警报。


开发

# Clone the repository
git clone https://github.com/mewsyy/pg-context.git
cd pg-context

# Install dependencies
npm install

# Run test suite
npm test

# Build TypeScript
npm run build

# Start local server
npm start

许可证

MIT (c) Semen

Available Tools

12 tools
describe_tableB

Get full structural details of a table as CREATE TABLE DDL, including columns, data types, constraints, foreign keys, and indexes

Inputs: table (required), schema.

explain_queryB

Get query execution plan via PostgreSQL EXPLAIN (or EXPLAIN ANALYZE) to debug performance bottlenecks

Inputs: sql (required), analyze.

get_database_infoA

Get high-level PostgreSQL database runtime information: version, size, active connection count, and server settings

Inputs: no named parameters.

get_slow_queriesB

Retrieve top slowest queries recorded by pg_stat_statements extension (if enabled in PostgreSQL)

Inputs: limit.

get_table_statsA

Get scan statistics, tuple counts, dead row accumulation, and maintenance history for tables

Inputs: table, schema.

list_extensionsA

List installed PostgreSQL extensions with version information and specialized framework detection (PostGIS, TimescaleDB, pgvector)

Inputs: no named parameters.

list_foreign_keysA

List foreign key relationships between tables to understand data model associations and joins

Inputs: table, schema.

list_indexesA

List indexes on tables with sizes and scan usage statistics to evaluate index health

Inputs: table, schema.

list_schemasA

List all available database schemas (excluding system schemas like pg_catalog and information_schema)

Inputs: no named parameters.

list_tablesA

List all tables and views in a given schema with estimated row counts, sizes, and comments

Inputs: schema.

read_queryA

Execute a safe read-only SQL query (SELECT, WITH, SHOW) with strict LIMIT enforcement and formatting

Inputs: sql (required), limit.

suggest_indexesB

Analyze query patterns, scan ratios, and missing foreign key indexes to provide index recommendations

Inputs: table, schema.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4/5.0

    Scored across 12 tools

    Disambiguation5/5

    Each tool targets a distinct aspect of PostgreSQL database introspection: schemas, tables, relationships, indexes, query execution, performance stats, and extensions. There is no overlap in purpose.

    Naming Consistency5/5

    All tools follow a consistent verb_noun pattern in snake_case (e.g., list_schemas, describe_table, read_query), making the API predictable and easy to navigate.

    Tool Count5/5

    With 12 tools, the server covers the key areas of database analysis without being bloated. Each tool serves a distinct role, and the count is appropriate for the domain.

    Completeness5/5

    The set covers schema exploration, table details, indexing, query analysis, performance monitoring, and extension information. No obvious gaps for a read-only database context server.

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      A Model Context Protocol server that provides AI assistants with secure, read-only access to PostgreSQL databases while offering comprehensive tools for schema exploration, query validation, and performance optimization.
      MIT
    • F
      license
      Not graded
      quality
      D
      maintenance
      An MCP server that enables AI assistants to interact with PostgreSQL databases by executing SQL queries and inspecting database schemas. It provides tools for standardized database exploration and management through the Model Context Protocol.
      -
    • A
      license
      A
      quality
      C
      maintenance
      An MCP server that gives AI agents direct read-only access to PostgreSQL databases, enabling natural language analytics through tools for schema exploration, querying, trend analysis, and data quality checks.
      11
      5
      MIT
    • A
      license
      A
      quality
      D
      maintenance
      A Model Context Protocol (MCP) server that gives AI assistants deep visibility into databases, inspecting schemas, detecting index problems, analyzing table bloat, and explaining query plans across PostgreSQL, MySQL, and SQLite.
      9
      21 npm
      1
      MIT