Postgres MCP

io.github.edelciomolina由 GitHub 帳號 edelciomolina 發布v1.7.0更新於 Oct 25, 2026

PostgreSQL MCP wrapper with .env credential mapping, tool selection, and safe read-only defaults.

已驗證STDIO僅桌面資料庫資料與分析

概覽

AI 產生的概覽

一個本機 MCP 伺服器,為 AI 助理提供結構化、預設唯讀的 PostgreSQL 資料庫介面,包含結構檢視與查詢風險判斷。

可以做什麼
執行受保護的唯讀查詢(SELECT、COUNT、EXISTS),並檢視 EXPLAIN 計畫與以 pg_stat_statements 為基礎的慢查詢統計。檢視結構與 ENUM 型別,取得各平台的設定說明。分析效能、設定與儲存,監控連線、鎖定、查詢與複寫狀態。建立包含結構、資料表、欄位、外鍵與推斷關聯的資料庫知識圖譜,描述資料表的語意與風險,並找出相關資料表。在不執行的情況下判斷查詢的風險等級。可選擇啟用寫入工具,用於結構、索引、限制條件、函式、觸發程序、RLS、使用者、資料異動與任意 SQL。
適用情境
當助理需要安全地瀏覽或查詢 PostgreSQL 資料庫、在撰寫查詢前了解其結構,或診斷效能與鎖定問題時使用。適合希望預設唯讀、對任何修改操作明確開啟的團隊。
執行需求
需要 Node.js 18 或更新版本,透過 npx 在本機執行或安裝該 npm 套件。需要一個包含資料庫憑證的 .env 檔案,從工作目錄往上尋找,或以 env-file 參數指定。env 區塊將 MCP_KEY_HOST、MCP_KEY_PORT、MCP_KEY_NAME、MCP_KEY_SSLMODE、MCP_KEY_USER 與 MCP_KEY_PASS 對應到該檔案中的變數名稱,或以 MCP_KEY_URL 對應連線字串。寫入工具還需設定 POSTGRES_MCP_ALLOW_WRITE=true 並明確傳入 tool= 參數。
安裝前請注意
.env 檔案保存真實的資料庫憑證,包括透過 MCP_KEY_PASS 對應的密碼或透過 MCP_KEY_URL 對應的完整連線字串,請勿提交到版本控制。寫入類工具可以建立、修改與刪除資料表、索引、限制條件、函式、觸發程序、原則與使用者,並執行 INSERT、UPDATE、DELETE 或任意 SQL;它們需要 POSTGRES_MCP_ALLOW_WRITE=true 與明確的 tool= 選擇。除非確實需要寫入,否則建議使用唯讀資料庫使用者。

安裝

在 SourceWeft 中

  1. 開啟 儀表板中的 Postgres MCP,將其新增到工作區。
  2. 為需要使用其工具的對話啟用該服務。

Desktop only,透過 STDIO。 STDIO 服務會啟動本機處理程序,因此需要 SourceWeft 桌面主機。

其他 MCP 客戶端

參照 儲存庫 中的啟動說明。

README

English | 🌐 Português

[Postgres MCP Icon]

Postgres MCP

🔌 Native MCP server for PostgreSQL - reads credentials from .env at runtime with flexible key mapping, configurable tool selection, and read-only mode by default.

[npm version] [license] [CI]

✨ What it does

Most LLMs interact with databases by guessing - assuming table names, inventing column names, and writing queries that may fail or expose sensitive data. Postgres MCP solves this by giving the LLM a structured, safe interface to actually understand the database before touching it.

Built with @modelcontextprotocol/sdk and pg, it provides:

  • 🧠 Semantic knowledge graph - the LLM gets a complete map of schemas, tables, columns, foreign keys, inferred relations, risk levels, and business domains - built from the real schema, not invented
  • 🛡️ Read-only by default - no writes, no DDL, no arbitrary SQL unless you explicitly opt in; pg_classify_query_risk lets the LLM check a query's safety before running it
  • 🔐 Runtime credential resolution - credentials are read from .env at startup; nothing sensitive lives in mcp.json
  • 🎯 Explicit tool selection - every tool is opt-in via tool=<name> args, so the LLM only sees what you choose to expose

📋 Requirements

  • ⚙️ Node.js >= 18
  • 📄 A .env file with database credentials (anywhere in the project tree - see .env Discovery)

🚀 Installation

There are two ways to use this package. Choose the one that best fits your workflow.

Option 1 - No installation (via npx, recommended for quick start)

No installation needed. npx downloads and runs the package on demand. Add -y as the first argument to skip the confirmation prompt.

json
{  "servers": {    "Postgres Tools": {      "type": "stdio",      "command": "npx",      "args": [        "-y",        "@edelciomolina/postgres-mcp"      ],      "env": {        "MCP_KEY_HOST":    "DB_HOST",        "MCP_KEY_PORT":    "DB_PORT",        "MCP_KEY_NAME":    "DB_NAME",        "MCP_KEY_SSLMODE": "DB_SSLMODE",        "MCP_KEY_USER":    "DB_USER",        "MCP_KEY_PASS":    "DB_PASS"      }    }  }}

This starts the server with the default read-only tool set - no tool= arguments needed. To enable write-capable tools, see Write-capable tools.

💡 Using Supabase, Neon, Railway or another platform that only provides a connection string? Use MCP_KEY_URL pointing to DATABASE_URL (or whatever variable name the platform uses). The server will prioritize the URL and ignore the individual variables. See Connection via URL.


Option 2 - Install via VS Code (MCP extension marketplace)

VS Code supports discovering and installing MCP servers directly in the editor, without using the terminal.

  1. Open the Command Palette (Cmd+Shift+P on Mac / Ctrl+Shift+P on Windows/Linux)
  2. Run MCP: Add Server
  3. Choose "Browse MCP Servers" (or "From registry", depending on your VS Code version)
  4. Search for postgres-mcp or edelciomolina
  5. Select Postgres MCP and follow the instructions - VS Code will add the entry to your mcp.json automatically

💡 You can also open the MCP Servers panel via Copilot chat icon → Manage MCP Servers to browse, enable, or disable servers at any time.

After installing, edit the generated entry in .vscode/mcp.json to add your tool= arguments and env key mappings as shown in the Usage section below.


🚀 Usage in VS Code (mcp.json)

Read-only (default - no tool= arguments needed):

json
{  "servers": {    "Postgres Tools": {      "type": "stdio",      "command": "npx",      "args": ["@edelciomolina/postgres-mcp"],      "env": {        "MCP_KEY_HOST":    "DB_HOST",        "MCP_KEY_PORT":    "DB_PORT",        "MCP_KEY_NAME":    "DB_NAME",        "MCP_KEY_SSLMODE": "DB_SSLMODE",        "MCP_KEY_USER":    "DB_USER",        "MCP_KEY_PASS":    "DB_PASS"      }    }  }}

With write tools (explicit opt-in required):

json
{  "servers": {    "Postgres Tools": {      "type": "stdio",      "command": "npx",      "args": [        "@edelciomolina/postgres-mcp",        "tool=pg_manage_schema",        "tool=pg_manage_indexes"      ],      "env": {        "POSTGRES_MCP_ALLOW_WRITE": "true",        "MCP_KEY_HOST":    "DB_HOST",        "MCP_KEY_PORT":    "DB_PORT",        "MCP_KEY_NAME":    "DB_NAME",        "MCP_KEY_SSLMODE": "DB_SSLMODE",        "MCP_KEY_USER":    "DB_USER",        "MCP_KEY_PASS":    "DB_PASS"      }    }  }}

⚠️ Write-capable tools require POSTGRES_MCP_ALLOW_WRITE=true in env. Without it, the server exits at startup.

The corresponding .env file at the root of your project:

env
DB_HOST=db.your-project.supabase.coDB_PORT=5432DB_NAME=postgresDB_SSLMODE=requireDB_USER=readonly_userDB_PASS=your_password

⚙️ How mcp.json configuration works

🗝️ env - credential key mapping

The env block does not contain the actual credentials. It maps each MCP_KEY_* to the variable name in your .env file.

Key in envPoints to .env variableExample value
MCP_KEY_URLDATABASE_URLpostgresql://user:pass@host:5432/db?sslmode=require
MCP_KEY_HOSTDB_HOSTdb.example.supabase.co
MCP_KEY_PORTDB_PORT5432
MCP_KEY_NAMEDB_NAMEpostgres
MCP_KEY_SSLMODEDB_SSLMODErequire
MCP_KEY_USERDB_USERreadonly_user
MCP_KEY_PASSDB_PASSsecret

Priority: when MCP_KEY_URL (or DATABASE_URL) is present, the server uses the URL directly and ignores the individual credential keys.

This indirection lets you use any variable name in your .env - useful when sharing a .env across multiple services with different naming conventions.

🔧 args - tool selection via tool= prefix

Each enabled MCP tool is declared as a separate argument in the format tool=<name>:

json
"args": [  "-y",  "@edelciomolina/postgres-mcp",  "tool=pg_manage_schema",  "tool=pg_manage_indexes"]

This makes the tool list explicit and auditable directly in mcp.json - no hidden configuration files. 🔍


🔗 Connection via URL (DATABASE_URL)

In addition to individual credentials, you can provide a full connection string - the standard format on platforms like Supabase, Neon, and Railway.

.env:

env
DATABASE_URL=postgresql://user:password@host:5432/database?sslmode=require

mcp.json:

json
{  "servers": {    "Postgres Tools": {      "type": "stdio",      "command": "npx",      "args": ["-y", "@edelciomolina/postgres-mcp"],      "env": {        "MCP_KEY_URL": "DATABASE_URL"      }    }  }}

The variable mapped by MCP_KEY_URL has priority over the other keys (MCP_KEY_HOST, MCP_KEY_PORT, etc.). If the URL is present, the other variables are ignored.

If the platform uses a different name (e.g. DB_URL), just adjust the mapping:

json
"MCP_KEY_URL": "DB_URL"

🛡️ Why read-only is the default

If you omit all tool= arguments, the server starts with a curated read-only set - all tools that can retrieve, analyze, or explain data, but nothing that can modify it.

✅ Included in defaults (read-only):

pg_execute_query       pg_manage_query        pg_inspect_schemapg_get_setup_instructions                     pg_analyze_databasepg_monitor_database                           pg_debug_databasepg_inspect_database_graph                     pg_describe_table_semanticspg_find_related_tables                        pg_classify_query_risk

💡 pg_execute_query rejects INSERT, UPDATE, DELETE, DDL, ANALYZE, VACUUM, EXPLAIN ANALYZE and other write/maintenance commands before the database is queried.

💡 pg_inspect_schema provides read-only schema introspection (get_info, get_enums). For DDL operations, use pg_manage_schema with explicit opt-in.

⚠️ Excluded from defaults - require tool= argument AND POSTGRES_MCP_ALLOW_WRITE=true:

ToolOperations
pg_manage_schemaCREATE TABLE, ALTER TABLE, CREATE TYPE
pg_manage_indexesCREATE INDEX, DROP INDEX, REINDEX
pg_manage_constraintsADD CONSTRAINT, DROP CONSTRAINT
pg_manage_functionsCREATE FUNCTION, DROP FUNCTION
pg_manage_triggersCREATE TRIGGER, DROP TRIGGER, enable/disable
pg_manage_rlsENABLE/DISABLE RLS, CREATE/ALTER/DROP POLICY
pg_manage_usersCREATE/DROP/ALTER USER, GRANT, REVOKE
pg_execute_mutationINSERT / UPDATE / DELETE / UPSERT
pg_execute_sqlArbitrary SQL with transaction support

📍 .env file discovery

The server resolves the .env file in this order:

  1. env-file=<path> argument - explicit path relative to cwd; takes priority over everything
  2. Upward search - starting from cwd, searches each parent directory until a .env is found or the filesystem root is reached

If no .env is found, the server exits with a clear error message.

Monorepos and subfolders

When VS Code starts the MCP process, cwd is typically the workspace root. If your .env is in a subfolder (e.g. functions/.env), use env-file= to point to it explicitly:

json
{  "servers": {    "Postgres Tools": {      "type": "stdio",      "command": "npx",      "args": [        "-y",        "@edelciomolina/postgres-mcp",        "env-file=functions/.env"      ],      "env": {        "MCP_KEY_HOST":    "DB_HOST",        "MCP_KEY_PORT":    "DB_PORT",        "MCP_KEY_NAME":    "DB_NAME",        "MCP_KEY_SSLMODE": "DB_SSLMODE",        "MCP_KEY_USER":    "DB_USER",        "MCP_KEY_PASS":    "DB_PASS"      }    }  }}

💡 The upward search behavior handles the common case automatically. Use env-file= when you need explicit control (CI, monorepos, Docker bind-mounts).


🧰 Available tools

Read-only (enabled by default)

ToolDescription
pg_execute_querySELECT / COUNT / EXISTS with write and multi-statement guards
pg_manage_queryEXPLAIN plans, slow query analysis, pg_stat_statements
pg_inspect_schemaSchema info and ENUM types (read-only introspection)
pg_get_setup_instructionsSetup instructions per platform
pg_analyze_databasePerformance, configuration, and storage analysis
pg_monitor_databaseReal-time monitoring of connections, queries, locks, and replication
pg_debug_databaseDiagnose connections, locks, performance, and replication
pg_inspect_database_graphBuild a full knowledge graph of the database: schemas, tables, columns, FKs, indexes, inferred relations, and business domains
pg_describe_table_semanticsDescribe a table with semantic context: risk level, column roles, sensitive columns, and related tables
pg_find_related_tablesFind tables related to a given table via explicit FKs and inferred naming patterns, with path explanation
pg_classify_query_riskClassify query risk (safe / warning / review / blocked) without executing it

Write-capable (opt-in via tool= argument + POSTGRES_MCP_ALLOW_WRITE=true)

ToolDescription
pg_manage_schemaSchema info, create/alter tables, manage ENUMs
pg_manage_indexesList, create, drop, reindex, analyze index usage
pg_manage_constraintsList, create, and drop constraints and foreign keys
pg_manage_functionsList, create, and drop functions and procedures
pg_manage_triggersList, create, drop, enable/disable triggers
pg_manage_rlsRow-Level Security policies
pg_manage_usersUser permissions, create/drop/alter users, grant/revoke
pg_execute_mutationINSERT / UPDATE / DELETE / UPSERT with parameterized queries
pg_execute_sqlArbitrary SQL execution with optional transaction support

🧠 Semantic Layer

The four pg_*_graph / pg_*_semantics / pg_*_risk tools build an in-memory knowledge graph of your database at runtime. This gives the LLM a structured map - schemas, tables, columns, foreign keys, inferred relations, risk levels, and business domains - without executing any query against your data.

All inferred fields (column semantic roles, table probable types, inferred relations) are clearly tagged so the LLM knows to treat them as hints, not schema facts.

Optional configuration (mcp-config.json)

Place a mcp-config.json file beside your .env to tune the semantic layer and security limits. All fields are optional - omitting the file applies safe defaults.

json
{  "security": {    "defaultLimit": 100,    "maxLimit": 1000,    "blockedSchemas": ["pg_catalog", "information_schema"],    "blockedTables": [],    "requireLimit": true  },  "semanticLayer": {    "enabled": true,    "inferRelationsWithoutForeignKeys": true,    "inferBusinessEntities": true,    "sensitiveKeywords": ["password", "secret", "token", "api_key", "ssn", "hash"]  }}

🏗️ Architecture

For a detailed view of the communication flow between the MCP client, the proxy, and PostgreSQL - including the full sequence diagram - see ARCHITECT.md.


📄 License

MIT © Edelcio Molina

來源:README.md,提交 6e2fb2e

工具

0
SourceWeft 尚未在沙箱中啟動過該軟體包,因此其工具未知。

版本歷史

1
  1. v1.7.0最新Sep 16, 2026

評分

已滿足適用檢查項的 40%

該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。

  • 近 30 天內可連通25 分

    請保持端點能夠回應 MCP 握手;SourceWeft 每 30 天探測一次。

  • 已宣告認證方式10 分

    請在註冊中心條目中宣告憑證請求標頭,或保持端點能夠回應探測,以便判定其認證方式。

  • 已列出工具15 分

    請讓伺服器在無憑證時回應 tools/list,或發布可在沙箱中無憑證啟動的軟體包。

  • 描述必需15 分
  • 圖示10 分
  • 文件15 分
  • 授權條款10 分

    請在儲存庫或註冊中心條目中宣告授權條款。