Postgres (read-only)

io.github.contextflo由 GitHub 帳號 contextflo 發布v0.1.4更新於 Oct 24, 2026

Read-only Postgres: drop-in for the archived server-postgres, with schema context.

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

概覽

AI 產生的概覽

在本機執行的唯讀 Postgres 伺服器,讓助理執行 SELECT 查詢、檢視資料表結構,並維護一份共用的資料表說明脈絡檔案。

可以做什麼
  • 一次執行一條唯讀語句:SELECT、WITH ... SELECT、EXPLAIN 或 SHOW,並受列數與輸出上限限制。
  • 列出可讀取的資料表,並依名稱或描述中的樣式篩選。
  • 詳細描述資料表:欄位、型別、鍵、外鍵目標、列舉值與人工撰寫的說明。
  • 把關於資料表與欄位的注意事項附加到 markdown 脈絡檔案,後續工作階段會提供給模型。
  • 將資料表結構以 postgres:// 資源形式提供,供依賴這些 URI 的用戶端使用。
適用情境
當助理需要探索或查詢 Postgres 資料庫進行分析,且希望從設計上阻擋寫入時使用。適合希望模型透過可納入版本控管的脈絡檔案了解業務定義與資料表陷阱的團隊。它也是已封存的 server-postgres 的直接替代品。
執行需求
需要本機 Node.js 執行環境,因為它以 npm 套件形式透過 npx 與 stdio 執行。需要 DATABASE_URL 中的 Postgres 連線字串,最好放在工作目錄的 .env 檔案中,或作為參數傳入。建議使用唯讀資料庫角色。選用參數可設定列數上限、語句逾時、脈絡檔案路徑、查詢日誌,以及搭配 AUTH_TOKEN 的 HTTP 模式。
安裝前請注意
連線字串是機密資訊,應放在 .env 而非命令列上。唯讀不等於低負載:助理的查詢可能造成全表掃描,建議指向唯讀複本或分支。角色能讀到什麼,模型就能讀到什麼,只授予希望助理看到的資料。助理可以附加脈絡檔案內容,請審閱這些變更。將 HTTP 綁定到 0.0.0.0 會暴露一個即時資料庫連線,應設定 AUTH_TOKEN 並使用私有網路。

安裝

在 SourceWeft 中

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

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

其他 MCP 客戶端

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

README

@contextflo/postgres-mcp

The analytics MCP server for Postgres. Read-only by construction, with a context file you and the agent both write to, so the model answers the way your team would.

Built and maintained by Contextflo.

A drop-in replacement for the archived @modelcontextprotocol/server-postgres, which shipped with a SQL injection vulnerability that let COMMIT; DROP SCHEMA public CASCADE walk straight out of its read-only transaction.

Watch the 100-second demo: setup, the agent working out that an events table is not what it looks like and saving that as a note, and a DROP the server refuses.

bash
npx @contextflo/postgres-mcp postgresql://localhost/mydb

Why this one

Read-only that holds up. The archived server enforced read-only as a property of the SQL string. Here it is a property of the wire protocol, the connection, the Postgres parser, and the database role: four independent layers, each of which stops that payload on its own. The exploit is a test case in this repo.

Answers that make sense. A model that does not know fct_orders_v2 is the table your team actually uses, or that revenue is gross rather than net, writes confident, wrong SQL. .contextflo/context.md is a markdown file you edit and this server hands to the model, with nothing behind it but the file. The agent adds to it too: when it learns something the schema does not say, add_table_context appends a note, which you review in a diff like any other change.

Setup

1. Create a read-only role. Run this as the database owner, in psql or your provider's SQL editor. Use your database name and a real password, and repeat the schema lines for each schema the agent should see:

sql
CREATE ROLE mcp_readonly LOGIN PASSWORD 'change-me';GRANT CONNECT ON DATABASE mydb TO mcp_readonly;GRANT USAGE ON SCHEMA public TO mcp_readonly;GRANT SELECT ON ALL TABLES IN SCHEMA public TO mcp_readonly;ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO mcp_readonly;

This makes read-only a property of the database, not just of this server's code.

2. Put that role's connection string in .env in your project folder:

bash
DATABASE_URL='postgresql://mcp_readonly:[email protected]:5432/mydb'

Keep the quotes: hosted providers add ?sslmode=require&..., and the & needs them. The server reads DATABASE_URL from .env in the directory it starts in, so the connection string never appears on a command line.

Point it at a read replica or a branch rather than your primary if you can. Read-only stops writes, not load: an agent exploring your data can run a full-table scan or a heavy join, and on the primary that competes with your application. Neon and Supabase can branch or replicate a database in a few clicks, and RDS, Cloud SQL, and most other hosts offer read replicas. The statement timeout (30 seconds by default, --statement-timeout) and the row cap limit how long one query runs and how much it returns; they do not make it cheap.

3. Generate the context file:

bash
npx @contextflo/postgres-mcp init

That writes .contextflo/context.md, seeded from your COMMENT ON values. Edit it: the business definitions section is where the value is.

4. Add it to your client. Claude Code starts servers in your project folder, so it finds .env and the context file on its own:

bash
claude mcp add postgres --scope project -- npx -y @contextflo/postgres-mcp

--scope project writes .mcp.json into the folder instead of your global config.

Cursor, Claude Desktop, VS Code

Other clients may start servers outside your project folder (Claude Desktop starts them in /), so give them the connection string and the context file explicitly:

json
{  "mcpServers": {    "postgres": {      "command": "npx",      "args": ["-y", "@contextflo/postgres-mcp", "--context-file", "/path/to/project/.contextflo/context.md"],      "env": { "DATABASE_URL": "postgresql://mcp_readonly:[email protected]:5432/mydb" }    }  }}

Cursor uses .cursor/mcp.json. Claude Desktop uses claude_desktop_config.json (macOS: ~/Library/Application Support/Claude/, Windows: %APPDATA%\Claude\). VS Code uses .vscode/mcp.json, with servers in place of mcpServers.

Tools

ToolWhat it does
queryRuns one read-only statement: SELECT, WITH ... SELECT, EXPLAIN, or SHOW.
list_tablesLists readable tables with descriptions. pattern matches anywhere in the name or description.
get_table_contextDescribes tables: columns, types, keys, foreign key targets, enum values, curated descriptions.
add_table_contextLets the agent write down a gotcha it found (amount is in cents, status has an undocumented value) in the context file.

There is no separate search tool, and that is deliberate. information_schema and pg_catalog are ordinary tables, so anything more specific, like finding every column named like %revenue% or listing tables with no primary key, is a query the model can write itself:

sql
SELECT table_schema, table_name, column_nameFROM information_schema.columnsWHERE column_name ILIKE '%revenue%';

Table schemas are also exposed as postgres://<host>/<table>/schema resources, matching the archived server, for anything pinned to those URIs. Most clients never fetch resources on their own, which is why discovery lives in the tools.

How read-only is enforced

Four layers. Each one stops the archived server's exploit by itself.

1. Extended query protocol. User SQL goes through pg-cursor, which always issues Parse/Bind/Execute, so Postgres itself rejects multi-statement input. The archived server called client.query(sql) with a bare string; node-postgres only prepares a statement when there are bind values, so that took the simple protocol path, where ; separates statements. That is the whole bug.

2. Connection-level read-only. default_transaction_read_only=on is set in the startup packet, and every statement runs inside an explicit BEGIN READ ONLY that always ends in ROLLBACK, never COMMIT. The rollback also undoes any SET made inside the transaction, so a statement cannot leave a pooled connection weakened for whoever gets it next.

3. A statement allowlist on the real Postgres parser. libpg-query is the actual Postgres C parser compiled to WASM, not a JavaScript approximation of SQL. The whole parse tree is walked rather than just the top-level node, which is what catches a data-modifying CTE:

sql
WITH x AS (INSERT INTO users VALUES (1) RETURNING *) SELECT * FROM x

That parses as a SelectStmt. A validator checking only the statement type runs it. Unknown node types fail closed.

Functions are checked against the database's own catalog. Postgres labels every function immutable, stable, or volatile, and only volatile ones can have side effects, so a volatile function is refused unless it is on a short list of harmless ones analysis needs (random(), clock_timestamp(), the table size functions). That covers dblink, pg_logical_emit_message (which writes to the WAL even in a read-only transaction), advisory locks, statistics resets, and whatever a future Postgres adds, without anyone having to name them. SECURITY DEFINER functions, which run with their owner's privileges, are refused whatever their label. A fixed list of known escapes is checked as well.

4. A read-only database role. The layers above are code, and code has bugs. A role that cannot write is enforced by Postgres regardless, which is why creating one is the first step of Setup. The server warns on startup if you connect as a superuser, and init prints the role snippet if the role it connects as can write.

What this does not protect against. The function check sees the functions a query calls directly, and it trusts how each is labelled. A user-defined function declared STABLE that writes anyway is allowed, and so is a function reached indirectly: inside a view, behind an operator, or through a type cast. The read-only transaction still refuses anything that changes table data that way; what can slip through is the rarer kind of side effect, such as a message written to the WAL. Layer 4 is what stops those, which is why the read-only role is the recommended setup rather than an optional extra. Read-only is also not confidentiality: anything the connected role can read, a model can read, so grant it only what you want an agent to see.

Migrating from @modelcontextprotocol/server-postgres

Swap the package name. The tool is still called query, still takes sql, still returns JSON rows, and the connection string is still the first argument.

Four deliberate differences:

  1. Multi-statement SQL and SET/RESET are rejected with a clear error. On the archived server these "worked", and that was the vulnerability.
  2. Results are capped at 1000 rows and 50,000 characters by default, and single values over 2,000 characters are shortened. Truncation is stated in the output, never silent. Rows come back one per line rather than pretty-printed, which roughly halves their token cost; it is still a JSON array. Dates and timestamps are exactly what Postgres sent, not re-rendered in the server's timezone.
  3. Schema discovery is a tool, not just a resource. Most clients do not auto-attach resources, which is why models using the old server so often did not know the schema.
  4. All non-system schemas are visible, not only public, and column descriptions come through from COMMENT ON.

Options

--max-rows <n>            Maximum rows returned per query (default: 1000)--max-output-chars <n>    Character budget for one query result (default: 50000)--statement-timeout <ms>  Server-side statement timeout (default: 30000)--context-file <path>     Curated schema context (default: .contextflo/context.md)--no-context-writes       Do not offer add_table_context; the context file is only read--log-file <path>         Query audit log (default: .contextflo/log.md once that directory exists)--no-log                  Never write a query log--http                    Serve over streamable HTTP instead of stdio--port <n>                HTTP port (default: 8080)--host <addr>             HTTP bind address (default: 127.0.0.1)

DATABASE_URL supplies the connection string if you do not pass one, from the environment or from .env in the current directory. The server connects on first use: without a connection string it still starts and lists its tools, and each tool call says what is missing. AUTH_TOKEN, with --http, requires that value as a bearer token.

Connection poolers. PgBouncer (and so the pooled connection strings from Supabase, Neon, and others) refuses the startup parameters this server normally sends. When that happens it reconnects without them and says so on stderr. Nothing is weakened: every statement still runs in BEGIN READ ONLY with its own statement timeout, and CI runs the read-only suite through PgBouncer in transaction mode.

The context file

markdown
# Database context
Revenue means gross, before refunds."Active customer" means an order in the last 90 days.
## Tables
### public.ordersOne row per customer order. Source of truth for revenue, not `orders_legacy`.
- revenue_usd: Gross revenue, before refunds. Net lives in `order_refunds`.- status: One of pending, paid, refunded.

Everything above ## Tables is handed to the model: as server instructions, and again at the top of list_tables, because several clients never show the model server instructions. HTML comments are left out. Under ## Tables, a ### heading names a table, the prose beneath describes it, and - column: meaning lines describe columns (a dash separator works too). Your text wins over COMMENT ON. Edits take effect on the next tool call; no restart.

A relative --context-file resolves against the directory the client starts the server in. Claude Desktop starts servers in /, so there it falls back to your home directory (~/.contextflo/context.md). For a file that lives in a repo, pass an absolute path. The server prints the path it is using on startup.

The agent adds to it. When the model finds something the schema does not say (amount is in cents, status also holds 'void' on old rows, every query needs deleted_at IS NULL), add_table_context appends it to this file, and every later session starts knowing it. Notes are only ever appended, never substituted for what you wrote, and only for tables and columns that exist. Treat them like any other change: keep the file in git and read the diff. A model can be wrong, and text inside your data can steer what it writes, so a note is a suggestion until someone has looked at it. --no-context-writes turns the tool off.

init seeds this from existing comments, and only for columns that already have one. A file with a blank placeholder for all 4000 columns is a file nobody edits.

Richer context generated from your code and docs, and shared across a team, is what contextflo.com does.

Query log

Once .contextflo/ exists, every statement is appended to .contextflo/log.md with its outcome, row count, and duration. It is written for you, not fed back to the model. --no-log turns it off.

Docker

bash
docker run -i --rm ghcr.io/contextflo/postgres-mcp postgresql://host.docker.internal/mydb

For a remote endpoint, see docker-compose.example.yml. Note what you are doing before you bind 0.0.0.0: that is a live database connection on a port. Set AUTH_TOKEN, keep it inside a private network, and terminate TLS in front of it, because the token is plaintext on the wire otherwise. The server prints a warning when it is exposed without a token.

On the default loopback bind, requests whose Host or Origin is not local are refused. That is what stops a web page from using DNS rebinding to reach a server on 127.0.0.1 through your browser.

Development

bash
npm installnpm run buildnpm test
npm run db:up   # throwaway Postgres for the integration suite (needs Docker)TEST_DATABASE_URL=postgres://postgres:postgres@localhost:55432/postgres npm testnpm run db:down

The integration suite deliberately bypasses the parser and drives the database directly, so it proves the wire and transaction layers rather than the validator. It skips without TEST_DATABASE_URL and is required to run in CI.

Security

Please report vulnerabilities privately. See SECURITY.md.

License

MIT

來源:README.md,提交 f370d7d

工具

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

版本歷史

1
  1. v0.1.4最新Sep 28, 2026

評分

已滿足適用檢查項的 50%

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

  • 近 30 天內可連通25 分

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

  • 已宣告認證方式10 分

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

  • 已列出工具15 分

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

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