MCPBridge
Connects AI assistants to PostgreSQL databases with production-grade safety features including query validation, guarded writes, rate limiting, and audit logging.
README
MCPBridge
A production-grade Model Context Protocol server that connects AI assistants (Claude Desktop, Cursor, Windsurf, Claude Code, โฆ) to PostgreSQL โ with the guardrails a real database deserves.
Most database MCP servers are thin wrappers around pool.query(). MCPBridge adds the missing production layer:
- ๐ก๏ธ Query safety validation โ DDL and multi-statement payloads are blocked; comments, string literals and dollar-quoted strings are stripped before keyword analysis so nothing can be smuggled past the validator; reads additionally run inside
READ ONLYtransactions as defence in depth. - โ Two-phase guarded writes โ
write_dbnever executes anything. It stages the statement, estimates the affected rows via the planner, assigns a risk level, and returns aconfirmation_id. Execution happens only throughconfirm_write; high-risk operations (bulk deletes,UPDATEwithoutWHERE) require an explicitacknowledge_risk=true. Unconfirmed writes expire after 10 minutes. - ๐ Result limiting โ
SELECTwithoutLIMITis automatically capped (default 100 rows) with a warning, soSELECT * FROM eventscan't flood the context window. - ๐งพ Audit logging โ every operation (success, error, blocked, rate-limited) is appended to a JSONL audit trail with timing, row counts and client identity. Credentials are redacted from every log line and error message. Logs rotate at 10 MB.
- ๐ฆ Rate limiting โ sliding-window limiter (default 100 requests/minute per client) that rejects before a database connection is consumed.
- ๐ง Schema intelligence โ row estimates from planner statistics (never
COUNT(*)), foreign-key relationship maps with cardinality, index inventories, column statistics, sample rows โ all behind a 5-minute TTL cache.
Architecture
Feature-based architecture combined with DDD. Each core feature is a bounded context living in its own folder under src/, with its Gherkin specification (.feature), its tests, and DDD layering inside (domain โ application โ infrastructure / presentation). Dependencies point inward within a feature; features depend only on shared/, platform/, and other features' public modules โ never on the composition root.
features/ # Gherkin specifications (Cucumber convention) โ one .feature file per feature
src/
โโโ querying/ # Feature: safe read-only querying
โ โโโ domain/ # SQL lexing, classification, validation, result limiting
โ โโโ application/ # ExecuteQuery, ExplainQuery use cases
โ โโโ presentation/ # query_db / explain_query tools, optimize-query prompt
โ โโโ tests/
โโโ schema-exploration/ # Feature: schema intelligence
โ โโโ domain/ # Table/column/relationship/statistics types
โ โโโ application/ # SchemaService (TTL cache), ListTables, DescribeTable
โ โโโ infrastructure/ # PostgreSQL catalog introspector
โ โโโ presentation/ # list_tables / describe_table tools + schema:// table:// stats:// relations:// resources
โโโ guarded-writes/ # Feature: two-phase confirmed writes
โ โโโ domain/ # PendingWrite aggregate, RiskAssessor
โ โโโ application/ # RequestWrite, ConfirmWrite, RejectWrite
โ โโโ infrastructure/ # In-memory pending-write store
โ โโโ presentation/ # write_db / confirm_write / reject_write tools
โ โโโ tests/
โโโ search/ # Feature: natural-language search
โ โโโ application/ # SearchData use case, SqlGenerator port
โ โโโ infrastructure/ # MCP-sampling SQL generator
โ โโโ presentation/ # search_data tool
โโโ audit/ # Feature: audit trail (JSONL logger, rotation, redaction)
โโโ throttling/ # Feature: rate limiting (sliding window + OperationGate)
โโโ shared/ # Shared kernel: Clock, errors, result envelope, TTL cache, formatting, test fakes
โโโ platform/ # Cross-feature plumbing: zod config, pg pool + gateway, MCP assembly, HTTP transport, composition root
โโโ main.ts # Entrypoint
docker/ # Dockerfile, Dockerfile.dockerignore, docker-compose.yml
docs/ # Architecture, folder structure, setup, development guides
Full documentation lives in docs/: architecture ยท folder structure ยท setup ยท development guidelines.
Tools
| Tool | Description |
|---|---|
query_db |
Execute read-only SQL. Unbounded queries are capped with a warning. |
explain_query |
Show the execution plan (optionally EXPLAIN ANALYZE) with performance warnings. |
list_tables |
Tables/views with estimated row counts and comments. |
describe_table |
Columns, PK/FKs, indexes, relationships, sample rows, column stats. |
search_data |
Natural-language question โ SQL (via MCP sampling) โ validated โ executed. |
write_db |
Stage an INSERT/UPDATE/DELETE; returns impact preview + confirmation_id. |
confirm_write |
Execute a staged write (high-risk requires acknowledge_risk=true). |
reject_write |
Cancel a staged write. |
Resources & Prompts
schema://{schemaName}โ full schema snapshot (5-minute TTL cache)table://{name}/stats://{table}/relations://{table}โ per-table structure, statistics, relationship map- Prompts:
analyze-table,optimize-query
Quick start
npm install
npm run build
Claude Desktop / Claude Code
Add to claude_desktop_config.json (or .mcp.json for Claude Code):
{
"mcpServers": {
"mcpbridge": {
"command": "node",
"args": ["/absolute/path/to/mcpbridge/dist/main.js"],
"env": {
"DATABASE_URL": "postgresql://user:password@localhost:5432/mydb",
"MCPBRIDGE_MODE": "read-only"
}
}
}
}
Restart the client โ MCPBridge and its 8 tools appear immediately. Set MCPBRIDGE_MODE=read-write to enable the guarded write flow.
Remote (Streamable HTTP)
MCPBRIDGE_TRANSPORT=http MCPBRIDGE_HTTP_PORT=3920 node dist/main.js
# MCP endpoint: http://localhost:3920/mcp
Docker
All Docker assets live in docker/:
docker compose -f docker/docker-compose.yml up # PostgreSQL with sample data + MCPBridge on :3920
docker build -f docker/Dockerfile -t mcpbridge . # image only (repo root as context)
Configuration
Everything is environment-driven (see .env.example):
| Variable | Default | Purpose |
|---|---|---|
DATABASE_URL |
โ | PostgreSQL connection string (or use PGHOST/PGDATABASE/PGUSER/PGPASSWORD/PGPORT) |
MCPBRIDGE_MODE |
read-only |
read-only disables write_db entirely; read-write enables guarded writes |
MCPBRIDGE_DEFAULT_SCHEMA |
public |
Schema used by tools and resources by default |
MCPBRIDGE_MAX_ROWS |
100 |
Cap applied to SELECTs without a LIMIT |
MCPBRIDGE_RATE_LIMIT |
100 |
Requests allowed per window per client |
MCPBRIDGE_RATE_WINDOW_SECONDS |
60 |
Rate-limit window |
MCPBRIDGE_QUERY_TIMEOUT_MS |
30000 |
statement_timeout for every query |
MCPBRIDGE_CONFIRMATION_TTL_SECONDS |
600 |
How long a staged write waits for confirmation |
MCPBRIDGE_SCHEMA_CACHE_TTL_SECONDS |
300 |
Schema cache TTL |
MCPBRIDGE_HIGH_RISK_ROW_THRESHOLD |
100 |
Estimated affected rows at which a write becomes high-risk |
MCPBRIDGE_MAX_CONNECTIONS |
10 |
Connection pool size |
MCPBRIDGE_AUDIT_LOG |
mcpbridge-audit.jsonl |
Audit trail path (rotates at 10 MB) |
MCPBRIDGE_BLOCKED_TABLES |
โ | Comma-separated extra tables to block (system credential catalogs are always blocked) |
MCPBRIDGE_TRANSPORT |
stdio |
stdio or http |
MCPBRIDGE_HTTP_PORT |
3920 |
Port for the HTTP transport |
Safety model
- Domain validation (fail closed). Statements are lexed (comments/strings blanked), classified by kind, and checked against forbidden keywords (
DROP,TRUNCATE,ALTER,CREATE,GRANT,COPY, โฆ), credential catalogs (pg_shadow,pg_authid, โฆ), multi-statement payloads, and CTE-smuggled writes (WITH x AS (DELETE โฆ) SELECT โฆ). Anything unclassifiable is rejected. - Transactional enforcement. Reads run in
BEGIN TRANSACTION READ ONLYโ PostgreSQL itself rejects any write that slips through. Writes run in their own transaction and roll back on failure. - Human confirmation. Writes are staged, previewed (operation, target table, planner row estimate, risk level) and only executed on explicit confirmation โ twice for high-risk operations.
- Redaction everywhere. Known secrets, connection-string passwords and
password=pairs are scrubbed from every error message and audit line.
Development
npm run dev # run from source (tsx)
npm test # 65 unit tests (vitest), co-located per feature in <feature>/tests/
npm run typecheck
node scripts/smoke.mjs # end-to-end MCP protocol smoke test over stdio
Behavioural specifications live in features/ as Gherkin files โ one per feature (features/safe-querying.feature, features/guarded-writes.feature, โฆ), following the standard Cucumber layout. They document the expected behaviour scenario by scenario and are the reference for the unit tests. See docs/development.md for the full workflow and guidelines.
License
MIT
Acknowledgements
MCPBridge is inspired by Claude Desktop and Cursor and their guarded database access flows. It is not affiliated with either product. PostgreSQL is a registered trademark of the PostgreSQL Global Development Group. MCPBridge is not affiliated with the PostgreSQL project. Project by @manulthanura
Recommended Servers
playwright-mcp
A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.
Magic Component Platform (MCP)
An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.
Audiense Insights MCP Server
Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.
VeyraX MCP
Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.
graphlit-mcp-server
The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.
Kagi MCP Server
An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.
E2B
Using MCP to run code via e2b.
Neon Database
MCP server for interacting with Neon Management API and databases
Exa Search
A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.
Qdrant Server
This repository is an example of how to create a MCP server for Qdrant, a vector search engine.