Skip to main content
Glama

pg-context

Model Context Protocol (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

クイックスタート

pg-context は、手動インストールなしで npx を使って直接実行できます:

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