공유된 스키마 컨텍스트 파일을 활용하여 AI agent가 PostgreSQL 데이터베이스에서 안전하게 읽기 전용 분석을 수행할 수 있도록 지원합니다.
다른 이름 contextflo/postgres-mcp, postgres-mcp, @contextflo/postgres-mcp
- 스타
- 4
- Tools
- 4
- 다운로드, 30일
- 937
- 최신 버전
- 0.1.4
- 마지막 커밋
- 2026년 9월 28일
- 라이선스
- MIT
Postgres (read-only) MCP란?
Postgres (read-only)은(는) MCP server입니다. 공유된 스키마 컨텍스트 파일을 활용하여 AI agent가 PostgreSQL 데이터베이스에서 안전하게 읽기 전용 분석을 수행할 수 있도록 지원합니다. 4개 도구를 제공합니다. 예: query, list_tables, get_table_context.
프로젝트 README에서 생성된 요약
Postgres (read-only) MCP server 정보
이 MCP server는 AI agent를 사용하는 개발자가 PostgreSQL 데이터베이스에서 안전하게 읽기 전용 분석을 수행할 수 있도록 지원합니다. 데이터베이스 역할과 Postgres parser를 포함한 네 가지 독립적인 계층을 통해 읽기 전용 제약을 강제함으로써, 기존 구현에서 발견되던 SQL injection 취약점을 방지하고 매우 안전한 환경을 제공합니다. 사용자는 명령줄 인자나 DATABASE_URL 환경 변수를 통해 연결 문자열을 제공하여 연결할 수 있습니다.
이 server는 Claude Code, Cursor, Claude Desktop과 같은 도구와 함께 작동하도록 설계되었습니다. 공유 마크다운 컨텍스트 파일을 사용하여, 매출 컬럼이 총매출인지 순매출인지와 같은 특정 비즈니스 로직을 AI가 이해할 수 있도록 합니다. agent는 add_table_context 도구를 사용하여 새로운 발견 사항을 이 파일에 직접 기록하고 사람이 검토할 수 있습니다. 데이터 양과 성능을 관리하기 위해 서버에는 기본 30초 문장 타임아웃이 포함되어 있으며 결과는 1000행으로 제한됩니다.
활용 사례
- 1비즈니스 컨텍스트를 포함한 데이터베이스 스키마 분석컨텍스트 파일에 저장된 정제된 비즈니스 정의를 사용하여 AI agent에게 특정 테이블 컬럼에 대해 설명하도록 요청합니다.
- 2패턴 매칭을 이용한 테이블 탐색agent에게 revenue와 같은 특정 키워드와 관련된 모든 테이블을 찾도록 요청합니다.
프로젝트의 README를 바탕으로 작성되었습니다. 모든 활용 사례는 해당 내용의 인용문과 대조하여 확인합니다.
Postgres (read-only) MCP 설치 방법
형식 확인: 2026년 11월 10일Cursor에 추가Goose에 추가Claude Code에 Postgres (read-only) MCP 설치
$ claude mcp add --env 'DATABASE_URL=<YOUR_DATABASE_URL>' postgres-mcp -- npx -y @contextflo/postgres-mcpCursor에 Postgres (read-only) MCP 설치
~/.cursor/mcp.json
{
"mcpServers": {
"postgres-mcp": {
"command": "npx",
"args": [
"-y",
"@contextflo/postgres-mcp"
],
"env": {
"DATABASE_URL": "<YOUR_DATABASE_URL>"
}
}
}
}VS Code에 Postgres (read-only) MCP 설치
.vscode/mcp.json
{
"servers": {
"postgres-mcp": {
"type": "stdio",
"command": "npx",
"args": [
"-y",
"@contextflo/postgres-mcp"
],
"env": {
"DATABASE_URL": "<YOUR_DATABASE_URL>"
}
}
}
}VS Code CLI에 Postgres (read-only) MCP 설치
$ code --add-mcp '{"name":"postgres-mcp","type":"stdio","command":"npx","args":["-y","@contextflo/postgres-mcp"],"env":{"DATABASE_URL":"<YOUR_DATABASE_URL>"}}'Claude Desktop에 Postgres (read-only) MCP 설치
claude_desktop_config.json
{
"mcpServers": {
"postgres-mcp": {
"command": "npx",
"args": [
"-y",
"@contextflo/postgres-mcp"
],
"env": {
"DATABASE_URL": "<YOUR_DATABASE_URL>"
}
}
}
}Codex에 Postgres (read-only) MCP 설치
$ codex mcp add postgres-mcp --env 'DATABASE_URL=<YOUR_DATABASE_URL>' -- npx -y @contextflo/postgres-mcpCodex config.toml에 Postgres (read-only) MCP 설치
~/.codex/config.toml
[mcp_servers.postgres-mcp] command = "npx" args = ["-y", "@contextflo/postgres-mcp"] [mcp_servers.postgres-mcp.env] DATABASE_URL = "<YOUR_DATABASE_URL>"
Gemini CLI에 Postgres (read-only) MCP 설치
$ gemini mcp add -s user -e 'DATABASE_URL=<YOUR_DATABASE_URL>' postgres-mcp npx -- -y @contextflo/postgres-mcpGemini settings.json에 Postgres (read-only) MCP 설치
~/.gemini/settings.json
{
"mcpServers": {
"postgres-mcp": {
"command": "npx",
"args": [
"-y",
"@contextflo/postgres-mcp"
],
"env": {
"DATABASE_URL": "<YOUR_DATABASE_URL>"
}
}
}
}Postgres (read-only) MCP 도구 4
README에서 감지됨querylist_tablesget_table_contextadd_table_context
| query | — | |
| list_tables | — | |
| get_table_context | — | |
| add_table_context | — |
구성
DATABASE_URL필수비밀Postgres connection string. Use a read-only role.
TEST_DATABASE_URL
| 이름 | 설명 | 유형 |
|---|---|---|
| DATABASE_URL | Postgres connection string. Use a read-only role. | 필수비밀 |
| TEST_DATABASE_URL | — |
자동 검사
2026년 11월 13일에 실행됨전체 보고서 →자동 검사를 통과했습니다. 이는 보안 감사가 아닙니다. 코드를 직접 읽고 서버에 필요한 최소한의 권한만 부여하십시오. 검사 방식
- 소스 저장소 연결 및 접근 가능contextflo/postgres-mcp is public and reachablegithub.com/contextflo/postgres-mcp ↗통과
- 패키지가 이 저장소를 소스로 명시@contextflo/postgres-mcp names contextflo/postgres-mcp as sourcenpmjs.com/package/@contextflo/postgres-mcp ↗통과
- 빌드 출처(Sigstore 증명)Sigstore attestation for @contextflo/postgres-mcpnpmjs.com/package/@contextflo/postgres-mcp/v/0.1.4#provenanc ↗통과
- 오픈 소스 라이선스 (OSI)MITspdx.org/licenses/MIT.html ↗통과
- 최근 1년 내 커밋 또는 릴리스Last commit or release 2026-09-28github.com/contextflo/postgres-mcp ↗통과
- OpenSSF Scorecard검사되지 않음
- 패키지 이름이 인기 패키지와 유사하지 않음No popular package one edit away from @contextflo/postgres-mcp통과
- 패키지 및 해당 종속성에 중요한 보안 권고 없음116 resolved dependencies checked; no critical advisoryosv.dev ↗통과
- 모델에 대한 숨겨진 지침 없음4 tool descriptions and the README read; no override phrases, credential paths or hidden characters통과
- 파괴적인 도구에 라벨 표시됨No tool named like delete, drop or exec통과
- 원격 엔드포인트가 MCP 핸드셰이크에 응답검사되지 않음
README
GitHub에서 보기@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.
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:
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:
DATABASE_URL='postgresql://mcp_readonly:change-me@db.example.com: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:
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:
claude mcp add postgres --scope project -- npx -y @contextflo/postgres-mcp
--scope project writes .mcp.json into the folder instead of your global config.
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:
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["-y", "@contextflo/postgres-mcp", "--context-file", "/path/to/project/.contextflo/context.md"],
"env": { "DATABASE_URL": "postgresql://mcp_readonly:change-me@db.example.com: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
| Tool | What it does |
|---|---|
query |
Runs one read-only statement: SELECT, WITH ... SELECT, EXPLAIN, or SHOW. |
list_tables |
Lists readable tables with descriptions. pattern matches anywhere in the name or description. |
get_table_context |
Describes tables: columns, types, keys, foreign key targets, enum values, curated descriptions. |
add_table_context |
Lets 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:
SELECT table_schema, table_name, column_name
FROM information_schema.columns
WHERE 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:
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:
- Multi-statement SQL and
SET/RESETare rejected with a clear error. On the archived server these "worked", and that was the vulnerability. - 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.
- 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.
- All non-system schemas are visible, not only
public, and column descriptions come through fromCOMMENT 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
# Database context
Revenue means gross, before refunds.
"Active customer" means an order in the last 90 days.
## Tables
### public.orders
One 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
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
npm install
npm run build
npm test
npm run db:up # throwaway Postgres for the integration suite (needs Docker)
TEST_DATABASE_URL=postgres://postgres:postgres@localhost:55432/postgres npm test
npm 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
Postgres (read-only) MCP 질문
Postgres (read-only) MCP를 Claude Code에 추가하려면 어떻게 하나요?
터미널에서 claude mcp add --env 'DATABASE_URL=<YOUR_DATABASE_URL>' postgres-mcp -- npx -y @contextflo/postgres-mcp를 실행합니다. 모든 프로젝트에서 사용할 수 있게 하려면 --scope user를 추가합니다.
Postgres (read-only) MCP를 Cursor에 추가하려면 어떻게 하나요?
~/.cursor/mcp.json를 열고 mcpServers 아래에 서버를 추가합니다. 위 설치 섹션에 표시된 Cursor 구성을 사용합니다.
Postgres (read-only) MCP는 어떤 도구를 제공하나요?
4개 도구를 제공합니다. 예: query, list_tables, get_table_context, add_table_context.
읽기 전용 제한은 어떻게 적용되나요?
확장 쿼리 프로토콜, 연결 레벨의 읽기 전용 설정, Postgres C parser를 사용한 구문 허용 목록, 그리고 전용 읽기 전용 데이터베이스 역할 등 네 가지 독립적인 계층을 통해 적용됩니다.
AI agent가 데이터베이스 스키마 컨텍스트를 업데이트할 수 있나요?
네, agent는 add_table_context 도구를 사용하여 스키마에 관한 노트를 마크다운 컨텍스트 파일에 추가할 수 있으며, 이후 사람이 이를 검토할 수 있습니다.
쿼리가 너무 크거나 실행 시간이 너무 길어지면 어떻게 되나요?
과도한 리소스 사용을 방지하기 위해 서버에 기본 30초 문장 타임아웃이 설정되어 있으며, 결과는 1000행 및 50,000자 이내로 제한됩니다.
연결 문자열로 서버를 설정하려면 어떻게 해야 하나요?
연결 문자열을 명령줄 인자로 제공하거나 프로젝트 디렉토리의 .env 파일에 DATABASE_URL 변수를 설정하면 됩니다.