전용 도구, 스키마 인트로스펙션, 복잡한 작업을 위한 보안 V8 isolate를 사용하여 AI agent가 PostgreSQL 데이터베이스와 상호작용할 수 있도록 합니다.
다른 이름 neverinfamous/postgres-mcp, postgres-mcp
- 스타
- 12
- Tools
- 25
- 다운로드, 30일
- —
- 최신 버전
- 1.2.0
- 마지막 커밋
- 2026년 9월 28일
- 라이선스
- MIT
PostgreSQL MCP란?
PostgreSQL은(는) MCP server입니다. 전용 도구, 스키마 인트로스펙션, 복잡한 작업을 위한 보안 V8 isolate를 사용하여 AI agent가 PostgreSQL 데이터베이스와 상호작용할 수 있도록 합니다. 25개 도구를 제공합니다. 예: codemode, core, transactions.
프로젝트 README에서 생성된 요약
PostgreSQL MCP server 정보
이 서버는 복잡한 데이터 관리를 위해 AI agent를 PostgreSQL 데이터베이스에 연결하는 기능을 제공합니다. 토큰 오버헤드를 줄이고 정확도를 높이기 위해 설계된 278개의 방대한 전용 도구 세트를 제공합니다. 개발자는 Node.js를 통해 로컬에서 사용하거나 Docker를 통해 사용할 수 있으며, 표준 연결 문자열을 사용하여 로컬, 컨테이너화된 데이터베이스 또는 AWS RDS, Google Cloud SQL, Supabase와 같은 원격 클라우드 데이터베이스에 연결할 수 있습니다.
주요 특징은 worker_threads를 통해 보안 V8 isolate를 활용하여 다단계 작업을 실행하는 Code Mode입니다. 이 방식은 기존의 반복적인 도구 호출 방식과 비교했을 때 AI 토큰 소비를 최대 90%까지 줄일 수 있습니다. 또한 스키마 인트로스펙션, 마이그레이션 추적, pgvector, PostGIS, pg_cron을 포함한 다양한 확장을 지원합니다. 보안은 세분화된 스코프를 가진 OAuth 2.1을 통해 관리되며, 결정론적 오류 처리는 원시 SQL 예외를 agent를 위한 실행 가능한 조언으로 변환합니다.
활용 사례
- 1복잡한 다단계 데이터베이스 작업 실행Code Mode를 사용하여 보안 V8 isolate 내에서 정교한 로직을 실행하고 토큰 비용을 절감합니다.
- 2데이터베이스 스키마 변경 안전하게 관리AI agent에게 스키마 업데이트의 영향을 시뮬레이션하고 마이그레이션 이력을 추적하도록 요청합니다.
- 3데이터베이스 상태 및 성능 모니터링AI agent에게 실시간 메트릭을 제공하여 데이터베이스 문제를 진단합니다.
프로젝트의 README를 바탕으로 작성되었습니다. 모든 활용 사례는 해당 내용의 인용문과 대조하여 확인합니다.
PostgreSQL MCP 설치 방법
형식 확인: 2026년 11월 10일Cursor에 추가Goose에 추가Claude Code에 PostgreSQL MCP 설치
$ claude mcp add postgres-mcp -- docker run -i --rm docker.io/writenotenow/postgres-mcp-enhanced:v1.2.0Cursor에 PostgreSQL MCP 설치
~/.cursor/mcp.json
{
"mcpServers": {
"postgres-mcp": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"docker.io/writenotenow/postgres-mcp-enhanced:v1.2.0"
]
}
}
}VS Code에 PostgreSQL MCP 설치
.vscode/mcp.json
{
"servers": {
"postgres-mcp": {
"type": "stdio",
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"docker.io/writenotenow/postgres-mcp-enhanced:v1.2.0"
]
}
}
}VS Code CLI에 PostgreSQL MCP 설치
$ code --add-mcp '{"name":"postgres-mcp","type":"stdio","command":"docker","args":["run","-i","--rm","docker.io/writenotenow/postgres-mcp-enhanced:v1.2.0"]}'Claude Desktop에 PostgreSQL MCP 설치
claude_desktop_config.json
{
"mcpServers": {
"postgres-mcp": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"docker.io/writenotenow/postgres-mcp-enhanced:v1.2.0"
]
}
}
}Codex에 PostgreSQL MCP 설치
$ codex mcp add postgres-mcp -- docker run -i --rm docker.io/writenotenow/postgres-mcp-enhanced:v1.2.0Codex config.toml에 PostgreSQL MCP 설치
~/.codex/config.toml
[mcp_servers.postgres-mcp] command = "docker" args = ["run", "-i", "--rm", "docker.io/writenotenow/postgres-mcp-enhanced:v1.2.0"]
Gemini CLI에 PostgreSQL MCP 설치
$ gemini mcp add -s user postgres-mcp docker -- run -i --rm docker.io/writenotenow/postgres-mcp-enhanced:v1.2.0Gemini settings.json에 PostgreSQL MCP 설치
~/.gemini/settings.json
{
"mcpServers": {
"postgres-mcp": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"docker.io/writenotenow/postgres-mcp-enhanced:v1.2.0"
]
}
}
}PostgreSQL MCP 도구 25
README에서 감지됨codemodecoretransactionsjsonbtextperformanceadminmonitoringbackupschemaintrospectionmigration
| codemode | — | |
| core | — | |
| transactions | — | |
| jsonb | — | |
| text | — | |
| performance | — | |
| admin | — | |
| monitoring | — | |
| backup | — | |
| schema | — | |
| introspection | — | |
| migration | — |
도구 25개 모두 보기도구 수 줄이기
partitioningstatsvectorpostgiscronpartmankcachecitextltreepgcryptosecurityrolesdocstore
| partitioning | — | |
| stats | — | |
| vector | — | |
| postgis | — | |
| cron | — | |
| partman | — | |
| kcache | — | |
| citext | — | |
| ltree | — | |
| pgcrypto | — | |
| security | — | |
| roles | — | |
| docstore | — |
구성
MCP_AUTH_TOKENPOSTGRES_DATABASEPOSTGRES_HOSTPOSTGRES_PASSWORDPOSTGRES_PORTPOSTGRES_USER
| 이름 | 설명 | 유형 |
|---|---|---|
| MCP_AUTH_TOKEN | — | |
| POSTGRES_DATABASE | — | |
| POSTGRES_HOST | — | |
| POSTGRES_PASSWORD | — | |
| POSTGRES_PORT | — | |
| POSTGRES_USER | — |
자동 검사
2026년 11월 12일에 실행됨전체 보고서 →자동 검사를 통과했습니다. 이는 보안 감사가 아닙니다. 코드를 직접 읽고 서버에 필요한 최소한의 권한만 부여하십시오. 검사 방식
- 소스 저장소 연결 및 접근 가능통과
- 오픈 소스 라이선스 (OSI)통과
- 최근 1년 내 커밋 또는 릴리스통과
- 패키지 이름이 인기 패키지와 유사하지 않음검사되지 않음
- 원격 엔드포인트가 HTTPS 사용검사되지 않음
- 파괴적인 도구에 라벨 표시됨통과
- 모델에 대한 숨겨진 지침 없음통과
- 패키지 및 해당 종속성에 중요한 보안 권고 없음검사되지 않음
README
GitHub에서 보기postgres-mcp
PostgreSQL MCP Server binding the Model Context Protocol to a secure PostgreSQL sandbox.
Features Code Mode — a revolutionary approach that provides access to all 278 tools through a secure, true V8 isolate (worker_threads), eliminating the massive token overhead of multi-step tool calls. Also includes schema introspection, migration tracking, smart tool filtering, deterministic error handling, connection pooling, HTTP/SSE Transport, OAuth 2.1 authentication, and extension support for citext, ltree, pgcrypto, pg_cron, pg_stat_kcache, pgvector, PostGIS, and HypoPG.
278 Specialized Tools · 24 Resources · 21 AI-Powered Prompts
Docker Hub • npm Package • MCP Registry • Wiki • Tool Reference • Changelog
🎯 What Sets Us Apart
| Feature | Description |
|---|---|
| Code Mode (V8 Isolate) | Massive Token Savings: Execute complex, multi-step operations inside a secure, true V8 isolate (worker_threads). Stop burning tokens on back-and-forth tool calls and reduce your AI overhead by up to 90%. |
| Deterministic Error Handling | No more cryptic database errors causing AI hallucinations. We intercept and translate raw SQL exceptions into clear, actionable advice so your agent knows exactly how to recover without guessing. |
| 278 Token-Optimized Tools | The largest PostgreSQL toolset on the MCP registry. Every query uses zero-cost token estimation and smart dataset truncation, ensuring agents always see the big picture without blowing their context windows. |
| OAuth 2.1 + Granular Control | Real enterprise security. Authenticate via OAuth 2.1 and control exactly who can read, write, or administer your database with precision scopes mapped down to the specific tool layer. |
| Audit Trails & Semantic Diffing | Total accountability. Track exactly what your AI is doing with detailed JSON logs, automatically snapshot schemas before mutations, and confidently review semantic row-by-row diffs before restoring data. |
| 24 Resources & 21 Prompts | Instant database meta-awareness. Agents automatically read real-time health, performance, and replication metrics, and can invoke built-in prompt workflows for query tuning and schema design. |
| Introspection & Migrations | Prevent costly mistakes. Let your AI simulate the cascade impact of schema changes, safely order foreign-key updates, and track migration history automatically. |
| 8 Extension Ecosystems | Ready for advanced workloads. First-class API support for pgvector (AI search), PostGIS (geospatial), pg_cron, pgcrypto, and more—all strictly typed and validated out of the box. |
| Smart Tool Filtering | Give your agent exactly what it needs without overflowing IDE limits. Dynamically compile your server with any combination of our 25 distinct tool groups. |
| Enterprise Infrastructure | Built for production. Blazing fast (millions of ops/sec), protected against SQL injection, features high-performance connection pooling, and supports both Streamable HTTP and Legacy SSE protocols simultaneously. |
Suggested Rule (Add to AGENTS.md, GEMINI.md, etc)
MCP TOKEN MANAGEMENT:
- Token Visibility: When interacting with
postgres-mcp, always monitor the_meta.tokenEstimate(ormetrics.tokenEstimatein Code Mode) returned in tool responses. - Audit Resource: Use the
postgres://auditresource to review session-level token consumption and identify high-cost operations. - Proactive Efficiency: If operations are consuming high token counts, prefer code mode and proactively use
limitparameters.
🚀 Quick Start
Prerequisites
- PostgreSQL 12-18 (tested with PostgreSQL 18.1)
- Docker (recommended) or Node.js 24+ (LTS)
Docker (Recommended)
docker pull writenotenow/postgres-mcp:latest
Add to your ~/.cursor/mcp.json or Claude Desktop config:
{
"mcpServers": {
"postgres-mcp": {
"command": "docker",
"args": [
"run",
"--rm",
"-i",
"-e",
"POSTGRES_HOST",
"-e",
"POSTGRES_PORT",
"-e",
"POSTGRES_USER",
"-e",
"POSTGRES_PASSWORD",
"-e",
"POSTGRES_DATABASE",
"writenotenow/postgres-mcp:latest",
"--tool-filter",
"codemode",
"--audit-log",
"/tmp/postgres-logs/audit.jsonl"
],
"env": {
"POSTGRES_HOST": "host.docker.internal",
"POSTGRES_PORT": "5432",
"POSTGRES_USER": "your_username",
"POSTGRES_PASSWORD": "your_password",
"POSTGRES_DATABASE": "your_database"
}
}
}
}
Note for Docker: Use
host.docker.internalto connect to PostgreSQL running on your host machine.
📖 Full Docker guide: DOCKER_README.md · Docker Hub
npm
npm install -g @neverinfamous/postgres-mcp
postgres-mcp --transport stdio --postgres postgres://user:password@localhost:5432/database
From Source
git clone https://github.com/neverinfamous/postgres-mcp.git
cd postgres-mcp
npm install
npm run build
node dist/cli.js --transport stdio --postgres postgres://user:password@localhost:5432/database
Development
See From Source above for setup. After cloning:
npm run lint && npm run typecheck # Run checks
npm run bench # Run performance benchmarks
node dist/cli.js info # Test CLI
node dist/cli.js list-tools # List available tools
Benchmarks
Run npm run bench to execute the performance benchmark suite (10 files, 93+ scenarios) powered by Vitest Bench. Use npm run bench:verbose for detailed table output.
Performance Highlights (Node.js 24, Windows 11):
| Area | Benchmark | Throughput |
|---|---|---|
| Tool Dispatch | Map.get() single tool lookup | ~6.9M ops/sec |
| WHERE Validation | Simple clause (combined regex fast-path) | ~3.7M ops/sec |
| Identifier Sanitization | validateIdentifier() | ~4.4M ops/sec |
| Auth — Token Extraction | extractBearerToken() | ~2.7M ops/sec |
| Auth — Scope Checking | hasScope() | ~5.3M ops/sec |
| Rate Limiting | Single IP check | ~2.3M ops/sec |
| Logger | Filtered debug (no-op path) | ~5.4M ops/sec |
| Schema Parsing | MigrationInitSchema.parse() | ~2.1M ops/sec |
| Metadata Cache | Cache hit + miss pattern | ~1.7M ops/sec |
| Sandbox Creation | CodeModeSandbox.create() cold start | ~863 ops/sec |
Full benchmark results and methodology are available on the Performance wiki page.
🔗 Database Connection Scenarios
| Scenario | Host to Use | Example Connection String |
|---|---|---|
| PostgreSQL on host machine | localhost or host.docker.internal |
postgres://user:pass@localhost:5432/db |
| PostgreSQL in Docker | Container name or network | postgres://user:pass@postgres-container:5432/db |
| Remote/Cloud PostgreSQL | Hostname or IP | postgres://user:pass@db.example.com:5432/db |
| Provider | Example Hostname |
|---|---|
| AWS RDS PostgreSQL | your-instance.xxxx.us-east-1.rds.amazonaws.com |
| Google Cloud SQL | project:region:instance (via Cloud SQL Proxy) |
| Azure PostgreSQL | your-server.postgres.database.azure.com |
| Supabase | db.xxxx.supabase.co |
| Neon | ep-xxx.us-east-1.aws.neon.tech |
🛠️ Tool Filtering
[!IMPORTANT] All tool groups include Code Mode (
pg_execute_code) by default. To exclude it, add-codemodeto your filter:--tool-filter cron,pgcrypto,-codemode
💡 Code Mode (
--tool-filter codemode) is the recommended configuration — it exposespg_execute_code, a secure, true V8 isolate sandbox providing access to all 278 tools' worth of capability with up to 90% token savings. See Tool Filtering for alternatives.
- Requires
adminOAuth scope — execution is logged for audit
📖 See Full Installation Guide →
What Can You Filter?
The --tool-filter argument accepts groups or tool names — mix and match freely:
| Filter Pattern | Example | Description |
|---|---|---|
| Groups only | core,jsonb,transactions |
Combine individual groups |
| Tool names | pg_read_query,pg_explain |
Custom tool selection |
| Group + Tool | core,+pg_stat_statements |
Extend a group |
| Group - Tool | core,-pg_drop_table |
Remove specific tools |
Tool Groups (25 Available)
| Group | Tools | Description |
|---|---|---|
codemode |
1 | Code Mode (sandboxed code execution) 🌟 Recommended |
core |
21 | Read/write queries, tables, indexes, convenience/drop tools |
transactions |
9 | BEGIN, COMMIT, ROLLBACK, savepoints, status |
jsonb |
21 | JSONB manipulation, queries, and pretty-print |
text |
14 | Full-text search, fuzzy matching |
performance |
25 | EXPLAIN, query analysis, optimization, diagnostics, anomaly detection |
admin |
12 | VACUUM, ANALYZE, REINDEX, insights |
monitoring |
12 | Database sizes, connections, status |
backup |
13 | pg_dump, COPY, restore, audit backups |
schema |
13 | Schemas, views, sequences, functions, triggers |
introspection |
7 | Dependency graphs, cascade simulation, schema analysis |
migration |
7 | Schema migration tracking and management |
partitioning |
7 | Native partition management |
stats |
20 | Statistical analysis, window functions, outlier detection |
vector |
17 | pgvector (AI/ML similarity search) |
postgis |
16 | PostGIS (geospatial) |
cron |
9 | pg_cron (job scheduling) |
partman |
11 | pg_partman (auto-partitioning) |
kcache |
8 | pg_stat_kcache (OS-level stats) |
citext |
7 | citext (case-insensitive text) |
ltree |
9 | ltree (hierarchical data) |
pgcrypto |
10 | pgcrypto (encryption, UUIDs) |
security |
10 | Security auditing, SSL, firewall, data masking, privilege analysis |
roles |
13 | Role management, privileges, membership, RLS |
docstore |
10 | JSONB document collections (NoSQL-style CRUD, indexing) |
Syntax Reference
| Prefix | Target | Example | Effect |
|---|---|---|---|
| (none) | Group | core |
Whitelist Mode: Enable ONLY this group |
| (none) | Tool | pg_read_query |
Whitelist Mode: Enable ONLY this tool |
+ |
Group | +vector |
Add tools from this group to current set |
- |
Group | -admin |
Remove tools in this group from current set |
+ |
Tool | +pg_explain |
Add one specific tool |
- |
Tool | -pg_drop_table |
Remove one specific tool |
🌐 HTTP/SSE Transport (Remote Access)
For remote access, web-based clients, or HTTP-compatible MCP hosts, use the HTTP transport:
node dist/cli.js \
--transport http \
--port 3000 \
--postgres "postgres://user:pass@localhost:5432/db"
Docker:
docker run --rm -p 3000:3000 \
-e POSTGRES_URL=postgres://user:pass@host:5432/db \
writenotenow/postgres-mcp:latest \
--transport http --port 3000
The server supports two MCP transport protocols simultaneously, enabling both modern and legacy clients to connect:
Streamable HTTP (Recommended)
Modern protocol (MCP 2025-03-26) — single endpoint, session-based:
| Method | Endpoint | Purpose |
|---|---|---|
POST |
/mcp |
JSON-RPC requests (initialize, tools/list, etc.) |
GET |
/mcp |
SSE stream for server notifications |
DELETE |
/mcp |
Session termination |
Sessions are managed via the Mcp-Session-Id header.
Stateless Mode
For serverless/stateless deployments where sessions are not needed:
node dist/cli.js --transport http --port 3000 --stateless --postgres "postgres://..."
In stateless mode: GET /mcp returns 405, DELETE /mcp returns 204, /sse and /messages return 404. Each POST /mcp creates a fresh transport.
Legacy SSE (Backward Compatibility)
Legacy protocol (MCP 2024-11-05) — for clients like Python mcp.client.sse:
| Method | Endpoint | Purpose |
|---|---|---|
GET |
/sse |
Opens SSE stream, returns /messages?sessionId=<id> endpoint |
POST |
/messages?sessionId=<id> |
Send JSON-RPC messages to the session |
Utility Endpoints
| Method | Endpoint | Purpose |
|---|---|---|
GET |
/health |
Health check (bypasses rate limiting, always available for monitoring) |
🔐 Authentication
postgres-mcp supports two authentication mechanisms for HTTP transport:
Simple Bearer Token (--auth-token)
Lightweight authentication for development or single-tenant deployments:
node dist/cli.js --transport http --port 3000 --auth-token my-secret --postgres "postgres://..."
# Or via environment variable
export MCP_AUTH_TOKEN=my-secret
node dist/cli.js --transport http --port 3000 --postgres "postgres://..."
Clients must include Authorization: Bearer my-secret on all requests. /health and / are exempt. Unauthenticated requests receive 401 with WWW-Authenticate: Bearer headers per RFC 6750.
OAuth 2.1 (Enterprise)
Full OAuth 2.1 with RFC 9728/8414 compliance for production multi-tenant deployments:
node dist/cli.js \
--transport http \
--port 3000 \
--postgres "postgres://user:pass@localhost:5432/db" \
--oauth-enabled \
--oauth-issuer http://localhost:8080/realms/postgres-mcp \
--oauth-audience postgres-mcp-client
Additional flags:
--oauth-jwks-uri <url>(auto-discovered if omitted),--oauth-clock-tolerance <seconds>(default: 60).
OAuth Scopes
Access control is managed through OAuth scopes:
| Scope | Access Level |
|---|---|
read |
Read-only queries (SELECT, EXPLAIN) |
write |
Read + write operations |
admin |
Full administrative access |
full |
Grants all access |
db:{name} |
Access to specific database |
schema:{name} |
Access to specific schema |
table:{schema}:{table} |
Access to specific table |
RFC Compliance
This implementation follows:
- RFC 9728 — OAuth 2.1 Protected Resource Metadata
- RFC 8414 — OAuth 2.1 Authorization Server Metadata
- RFC 7591 — OAuth 2.1 Dynamic Client Registration
The server exposes metadata at /.well-known/oauth-protected-resource.
Note for Keycloak users: Add an Audience mapper to your client (Client → Client scopes → dedicated scope → Add mapper → Audience) to include the correct
audclaim in tokens.
[!NOTE] Per-tool scope enforcement: Scopes are enforced at the tool level — each tool group maps to a required scope (
read,write, oradmin). When OAuth is enabled, every tool invocation checks the calling token's scopes before execution. When OAuth is not configured, scope checks are skipped entirely.
[!WARNING] HTTP without authentication: When using
--transport httpwithout enabling OAuth or--auth-token, all clients have full unrestricted access. Always enable authentication for production HTTP deployments. See SECURITY.md for details.
Priority: When both
--auth-tokenand--oauth-enabledare set, OAuth 2.1 takes precedence. If neither is configured, the server warns and runs without authentication.
🔧 Configuration
PostgreSQL MCP 질문
PostgreSQL MCP를 Claude Code에 추가하려면 어떻게 하나요?
터미널에서 claude mcp add postgres-mcp -- docker run -i --rm docker.io/writenotenow/postgres-mcp-enhanced:v1.2.0를 실행합니다. 모든 프로젝트에서 사용할 수 있게 하려면 --scope user를 추가합니다.
PostgreSQL MCP를 Cursor에 추가하려면 어떻게 하나요?
~/.cursor/mcp.json를 열고 mcpServers 아래에 서버를 추가합니다. 위 설치 섹션에 표시된 Cursor 구성을 사용합니다.
PostgreSQL MCP는 어떤 도구를 제공하나요?
25개 도구를 제공합니다. 예: codemode, core, transactions, jsonb, text.
복잡한 데이터베이스 작업을 수행할 때 토큰 사용량을 어떻게 줄일 수 있나요?
'Code Mode'를 사용할 수 있습니다. 이 모드는 보안 V8 isolate 내부에서 작업을 실행하여 AI 오버헤드를 최대 90%까지 줄여줍니다.
이 서버는 AI agent를 위한 데이터베이스 오류를 어떻게 처리하나요?
결정론적 오류 처리(deterministic error handling)를 사용하여 원시 SQL 예외를 가로채고, 이를 명확하고 실행 가능한 조언으로 변환함으로써 AI의 환각 현상을 방지합니다.
AI가 사용할 수 있는 도구를 제한할 수 있나요?
네, --tool-filter 인자를 사용하여 특정 도구 그룹이나 개별 도구 이름으로 서버를 동적으로 컴파일할 수 있습니다.