DBShield Database Guardrail & Sandboxing MCP Server

io.github.RitualDev-Lab由 GitHub 帳號 RitualDev-Lab 發布v0.2.1更新於 Nov 7, 2026

Safety-first Database Guardrail & Sandboxing MCP Server for AI Coding Agents

概覽

AI 產生的概覽

本機 MCP 伺服器,在 AI 程式開發代理與 PostgreSQL、MySQL 或 SQLite 資料庫之間加一層安全防護,攔截高風險 SQL 並遮蔽敏感資料。

可以做什麼
  • 查看閘道狀態、安全等級與資料庫統計資訊
  • 在不讀取資料列的情況下檢視資料表、欄位、限制條件與關聯
  • 執行讀取與寫入查詢,具備 PII 去識別化、成本閘門與 DDL 檢查
  • 在自動回滾交易中試跑變更,再以簽章授權權杖提交
  • 分析查詢計畫、驗證遷移腳本、檢查結構漂移並比對意圖與 SQL
  • 跨多個儲存模擬並提交,讀取已去識別化的稽核日誌
適用情境
當 AI 代理需要存取資料庫,但你希望防止無條件刪除、破壞性 DDL、超量變更以及 PII 流入模型上下文時使用。適合本機開發與預備環境,正式環境應搭配最小權限資料庫角色使用。
執行需求
以 npm 套件形式透過 stdio 在本機執行,通常以 npx 啟動。需透過 DBSHIELD_DB_URL 提供目標資料庫連線位址或檔案路徑,並以 DBSHIELD_DIALECT 指定方言(postgres、mysql 或 sqlite)。可選設定檔可設定安全等級、資料列上限與 PII 去識別化。代理、儀表板及 Docker/Helm 模式需要本機連接埠與連往上游資料庫的網路。
安裝前請注意
它持有資料庫憑證且可執行寫入,安全等級設定不當或使用寬鬆模式會擴大影響範圍,建議使用最小權限資料庫角色。儀表板與代理會監聽本機連接埠,儀表板還提供變更的核准/拒絕按鈕。稽核日誌與錯誤訊息會去識別化,但仍需確認遮蔽涵蓋你的敏感欄位。README 中的企業 SLA 與合規聲明在此未經獨立驗證。

安裝

在 SourceWeft 中

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

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

其他 MCP 客戶端

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

README

[DBShield Logo]

🛡️ DBShield

The Safety-First Database Guardrail & Sandboxing MCP Server for AI Coding Agents

[License: MIT] [npm version] [OpenSSF Scorecard] [SOC 2 Audit Ready] [Website] [Documentation Guide] [Threat Model] [IDE Extension] [MCP Protocol] [TypeScript] [Node.js] [CI] [Docker Image] [Helm Chart] [Prometheus] [Biome]

Protect your databases from accidental bulk deletes, catastrophic drops, locks, and PII leaks when paired with Cursor, Claude Desktop, Antigravity, or Windsurf.


[DBShield Terminal Interactive Demo]


⚡ The Problem: AI Agents Writing Raw SQL

When autonomous AI coding agents interact directly with databases:

  1. Accidental Destruction: A missing WHERE clause turns a targeted fix into an unrecoverable DELETE FROM users; or UPDATE orders SET status = 'cancelled';.
  2. Catastrophic DDL: Agents dropping staging or production tables (DROP TABLE, TRUNCATE) instead of running non-destructive migrations.
  3. PII & Credential Leaks: Customer emails, passwords, SSNs, and API keys are streamed in plaintext directly into model contexts and chat transcripts.
  4. Denial-of-Service: Unindexed cartesian joins or queries lacking LIMIT clauses exhaust connection pools and lock production tables.

DBShield sits between your AI Agent and your Database as an intelligent, zero-overhead safety firewall.


🤖 Frequently Answered Questions (AEO & AI Search Reference)

What is DBShield?

DBShield is an open-source database guardrail, virtual schema masking proxy, and MCP server designed to protect relational databases (PostgreSQL, SQLite, MySQL) from accidental bulk mutations, schema corruption, and PII leaks when queried by autonomous AI coding agents.

How does DBShield prevent accidental data deletion?

DBShield operates with a Two-Phase Distributed Dry-Run Engine:

  1. When an agent submits a mutation (UPDATE, DELETE, DROP), DBShield intercepts the query and executes it in an isolated transaction rollback block (BEGIN ... ROLLBACK).
  2. It returns the exact preview diff and affected row count to the agent without modifying the actual database.
  3. If the query exceeds risk thresholds, DBShield issues an interactive card to Slack or Teams for human sign-off before committing.

What is Virtual Schema Masking?

When AI coding agents run introspection queries like SELECT * FROM information_schema.tables, DBShield intercepts the wire protocol and rewrites catalog responses. Sensitive internal tables (credentials, sessions, api_keys) and restricted columns are hidden entirely from the agent's view.


🚀 Key Capabilities

  • 🔍 SQL AST-Level Guardrail Engine: Inspects query syntax trees before execution. Intercepts dangerous mutations, tautologies (WHERE 1=1), and unconstrained deletes.
  • 🧪 Dry-Run Auto-Rollback Sandboxing: Executes writes in an isolated transaction block (BEGIN ... ROLLBACK). Previews exact row impacts without altering the real database state.
  • 🔒 Dynamic Zero-Leak PII Masking: Automatically detects sensitive fields (passwords, emails, phone numbers, tokens) and masks them before streaming back to LLM context.
  • 📐 Safe Schema Introspection: Exposes rich table definitions, foreign keys, and indexes without exposing data rows.
  • 🎛️ Granular Safety Tiers: Choose between STRICT (read-only / 1-row limits), BALANCED (production guardrails), or PERMISSIVE (custom rules).
  • 🎭 Virtual Schema Masking & Column-Level RBAC: Hides sensitive internal tables (credentials, internal_audit, admin_*) from information_schema / catalog introspection and masks restricted columns from agent context.
  • ⚡ Missing Index & Query Plan Regressive Advisor: Detects full-table sequential scans on unindexed tables and automatically synthesizes optimal CREATE INDEX [CONCURRENTLY] DDL statements with cost regression alerting.
  • 📺 Real-time Live Query Approval Feed: Zero-dependency web dashboard (:3100) streaming live agent queries, risk scores, and PII redactions, featuring 1-click "Approve / Reject" buttons for sensitive mutations.
  • 🌐 Multi-Store Distributed Dry-Run: Extends the two-phase commit token manager to coordinate atomic simulations and commits across distributed multi-store stacks (PostgreSQL + Redis + SQLite).
  • 🔌 Universal MCP Protocol: Drop-in compatible with Claude Desktop, Cursor, Antigravity, Windsurf, and custom Agent frameworks.

📦 Quickstart

1. Claude Desktop Setup (1-Click)

Run the auto-installer to configure your local Claude Desktop:

bash
npx @ritualdev-lab/dbshield install-claude

Or manually add to claude_desktop_config.json:

json
{  "mcpServers": {    "dbshield": {      "command": "npx",      "args": ["-y", "@ritualdev-lab/dbshield", "start"]    }  }}

2. Cursor IDE Setup (1-Click)

Run inside your workspace to create or update .cursor/mcp.json:

bash
npx @ritualdev-lab/dbshield install-cursor

3. PostgreSQL Wire-Protocol Proxy (Zero Client Config)

Run DBShield as a transparent TCP wire proxy on :5433 (or :5432). Any ORM (Prisma, Drizzle, SQLAlchemy), AI agent, or CLI connects directly:

bash
npx @ritualdev-lab/dbshield proxy --port 5433 --upstream-host 127.0.0.1 --upstream-port 5432

In your application or .env:

env
DATABASE_URL="postgres://user:[email protected]:5433/production_db"

4. Terminal CLI & Status

bash
# Check status and inspect connected databasenpx @ritualdev-lab/dbshield status
# Initialize starter configuration filenpx @ritualdev-lab/dbshield init

5. Live Query Approval Feed & Web Dashboard

Start the real-time query approval web interface (:3100):

bash
npx @ritualdev-lab/dbshield dashboard --port 3100

Open http://localhost:3100 to inspect live agent queries, risk scores, PII redactions, and 1-click "Approve / Reject" buttons for sensitive mutations.


⚙️ Configuration (dbshield.config.json)

json
{  "$schema": "https://raw.githubusercontent.com/RitualDev-Lab/DBShield/main/schema.json",  "dialect": "sqlite",  "storagePath": "./dev.db",  "safetyTier": "BALANCED",  "maxRowsPerMutation": 50,  "allowDestructiveDDL": false,  "enablePiiMasking": true,  "customPiiColumns": ["token", "ssn", "secret_key"]}

Safety Tiers

TierMutation LimitDestructive DDLDry-Run RequiredPII MaskingBest For
STRICTMax 1 row❌ Blocked✅ Always Required🔒 EnforcedProduction, Staging
BALANCEDMax 50 rows❌ Blocked✅ On Bulk Writes🔒 EnforcedLocal Dev, Team Collaboration
PERMISSIVEMax 500 rows⚠️ WarnedOptionalOptionalSandbox Benchmarks

🛠️ MCP Tools Reference

ToolDescription
db_statusInspect gateway connectivity, active safety tier, cost gate, and database statistics.
db_describe_schemaSafe introspection of tables, columns, constraints, and relations.
db_querySafe read and mutation query execution with automatic PII redaction, cost gate, and DDL checks.
db_dry_runTest mutation inside an auto-rollback transaction with row delta preview and intent verification.
db_commitExecute verified mutation accompanied by cryptographic authorization token.
db_explain_queryAnalyze query execution plans, detect unindexed full-table scans, and receive index hints.
db_audit_logRetrieve compliance query audit trail, blocked operations, and risk scores.
db_validate_migrationValidate DDL migration scripts for lock hazards and generate zero-downtime execution recipes.
db_check_schema_driftAudit live database foreign keys for missing indexes and detect structural schema drift.
db_check_semantic_intentCheck stated English user intent against SQL AST target columns to stop unauthorized privilege/financial mutations.
db_distributed_dry_runSimulate atomic mutations across multi-store environments (Postgres, SQLite, Redis) and receive unified token.
db_distributed_commitExecute two-phase distributed commit across multi-store environments with cryptographic tamper verification.

🛡️ Matrix of Supported SQL & Enforced Guarantees

DBShield enforces rigorous runtime guarantees across the SQL lifecycle. Guarantees are verified transactionally, ensuring mutations never exceed approved scope even if database state drifts:

SQL OperationClassification MechanismStatic AST GuardrailExecution Boundary & RollbackData Masking & Privacy
SELECTPrepared-statement column reflection (stmt.columns())Detects missing LIMIT in STRICT tier; warns if limit exceeds server capStreaming iterator (stmt.iterate()) caps memory; truncates at maxRowsPerReadZero-leak dynamic PII masking on result rows
WITH ... (CTE)Prepared-statement column reflection & recursive AST analysisRecursively extracts underlying mutated tables & verifies read safetyStreaming iterator (stmt.iterate()) with hard read ceilingZero-leak dynamic PII masking on result rows
UPDATE (Targeted)AST evaluation & tautology checker (evaluateWhereClause)Blocks unconstrained updates, WHERE 1=1, WHERE true, tautological ORAtomic transaction; rolls back if affected rows exceed maxMutationRowsLiteral masking in logs & database errors
DELETE (Targeted)AST evaluation & tautology checker (evaluateWhereClause)Blocks unconstrained deletes, WHERE 1=1, tautological ORAtomic transaction; rolls back if affected rows exceed maxMutationRowsLiteral masking in logs & database errors
INSERTAST evaluation & dialect parserPre-flight dry run simulation required under STRICT tierAtomic transaction; rolls back if inserted rows exceed maxMutationRowsRedacts sensitive literals in (cols) VALUES (vals)
DROP TABLE / TRUNCATEAST statement opcode inspectionCRITICAL BLOCK: Intercepted before database touch unless explicitly overriddenDirect execution blockedAudit log records blocked attempt with high risk score
ALTER TABLE DROP COLUMNAST expression visitor (expr.action)BLOCKED: Intercepted before database touch to prevent schema data lossDirect execution blockedAudit log records blocked attempt
EXPLAIN / PRAGMAPrepared-statement column reflectionSafe read-only inspectionRead capped at maxRowsPerReadSanitized output

Enforced Guarantees Breakdown

  1. Parameter-Bound Commit Invariance (B1):
    • Commit authorization tokens are cryptographically signed (HMAC-SHA256) binding the exact normalized SQL query text, typed parameters (params), database identity (storagePath), safety tier, and simulated affected row count.
    • Any query tampering, bound parameter alteration, or cross-database replay attempt is instantly rejected (PARAMS_MISMATCH, QUERY_TAMPERED).
  2. Hard Mutation Ceilings & Transactional Rollbacks (B2):
    • Exceeding maxRowsPerMutation is a hard safety limit across all safety tiers (STRICT, BALANCED, PERMISSIVE), immediately refusing dry-run authorization (EXCESSIVE_BLAST_RADIUS).
    • Mutations executed directly or committed through db_commit run inside an atomic transaction block: if actual row modifications exceed the authorized ceiling, DBShield immediately executes ROLLBACK; and aborts.
  3. Simulation Delta Drift Prevention (B2):
    • Protects against concurrent modifications between dry run and commit: if underlying database rows change such that actual affected rows differ from simulated rows (simulatedAffectedRows != actualChanges), DBShield rolls back the transaction with [SIMULATION_DELTA_DRIFT].
  4. Audit Log & Error Message Sanitization (B3):
    • Raw SQL strings have sensitive literals (passwords, tokens, API keys, emails, phone numbers, SSNs, credit cards) masked before being written to disk or the in-memory circular buffer.
    • Database engine errors (e.g., SQLite constraint failures) are sanitized prior to returning to the agent or storing in audit records.
    • db_audit_log returns strictly sanitized compliance records.
  5. Memory-Safe Streaming Read Row Capping (B4):
    • SQLite row reads are streamed lazily using Node.js stmt.iterate().
    • Results are capped at maxRowsPerRead without buffering the full dataset into Node.js heap memory, returning agent-friendly pagination metadata (totalReturned, isTruncated, maxAllowedRows, hasMore, warning).
  6. Robust Statement Classification & CTE Support (B5):
    • Replaced naive string prefix checks with SQLite prepared-statement column metadata (stmt.columns() > 0) and recursive AST extraction.
    • Complex CTEs (WITH active AS (...) SELECT ...) and leading single-line (--) or multi-line (/* */) comments are correctly classified and executed without error.

🔒 Production Deployment & Least-Privilege Guide

For production and shared environments, DBShield should be paired with database-level least privilege:

1. SQLite Filesystem Hardening

  • File Permissions: Restrict database file permissions so only the DBShield process UID has access:
    bash
    chmod 600 /var/data/production.dbchown dbshield:dbshield /var/data/production.db
  • Read-Only Connections: For read-only agent workloads, mount SQLite with read-only flags or initialize with SQLite read-only mode:
    json
    {  "storagePath": "file:/var/data/production.db?mode=ro",  "safetyTier": "STRICT"}

2. Relational Database Least Privilege (PostgreSQL / MySQL)

  • Create a dedicated database role for DBShield with minimal necessary grants:
    sql
    -- Create isolated roleCREATE ROLE agent_user WITH LOGIN PASSWORD 'strong_random_password';
    -- Grant only targeted DML on application tables (NO DROP, TRUNCATE, or ALTER)GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO agent_user;REVOKE ALL ON SCHEMA public FROM PUBLIC;

3. Policy Enforcement vs Human Approval

  • Deterministic Policy Enforcement: DBShield's dry-run authorization token guarantees that a query adheres to automated safety policies (blast radius thresholds, tautology checks, parameter binding).
  • Human Approval Hand-Off: In sensitive production workflows, db_dry_run outputs can be piped to an external human-in-the-loop review system (Slack, Teams, or ticketing webhook) before the token is submitted to db_commit.

🐳 Docker & Kubernetes Helm Packaging

DBShield is packaged as an enterprise container with an unprivileged non-root user (UID 10001), native Prometheus metrics exporter, and a production Kubernetes Helm chart:

PostgreSQL Clients / AI Agents ──► DBShield Wire Proxy (:5433) ──► Upstream PostgreSQL (:5432)                                             │                                             └──► Prometheus Scraper (:9090/metrics)                                             └──► Kubernetes Probes (:9090/healthz, /ready)

1. Docker Compose (Zero-Config Full Stack)

Launch PostgreSQL, DBShield Wire Proxy, and Prometheus in one command:

bash
docker compose up -d
  • PostgreSQL Proxy: 127.0.0.1:5433 (Targeting PostgreSQL on :5432)
  • Prometheus Dashboard: http://localhost:9091
  • Metrics Endpoint: http://localhost:9090/metrics
  • Health Endpoint: http://localhost:9090/healthz

2. Standalone Docker Container

bash
docker run -d \  --name dbshield-proxy \  -p 5433:5433 \  -p 9090:9090 \  -e DBSHIELD_UPSTREAM_HOST=postgres.internal \  -e DBSHIELD_UPSTREAM_PORT=5432 \  -e DBSHIELD_SAFETY_TIER=BALANCED \  ghcr.io/ritualdev-lab/dbshield:0.2.0

3. Kubernetes Deployment via Helm

Deploy high-availability DBShield replicas (with HorizontalPodAutoscaler and Prometheus ServiceMonitor):

bash
# Add or install local charthelm install dbshield ./charts/dbshield \  --set proxy.upstreamHost="my-db.postgres.database.azure.com" \  --set proxy.safetyTier="BALANCED" \  --set replicaCount=2 \  --set autoscaling.enabled=true
Metrics Exponent in Prometheus (/metrics)
  • dbshield_up: Proxy health status (1 = healthy)
  • dbshield_connections_active: Real-time active client connections
  • dbshield_queries_total{status, safety_tier, operation}: Total queries evaluated
  • dbshield_queries_blocked_total{rule, severity}: Queries intercepted and prevented
  • dbshield_query_duration_seconds: Histogram measuring query evaluation latency
  • dbshield_cost_savings_dollars_total: Estimated cloud spend saved from blocked runaway queries

🏛️ Enterprise Compliance & SLA Guarantees

DBShield provides deterministic, zero-data-custody database protection backed by enterprise contractual assurances:

  • Formal Enterprise Service Level Agreement: ENTERPRISE_SLA.md
    Guaranteed response times: < 1 hour for P1 critical outages (24/7/365 coverage), < 4 hours for P2 high severity, 99.95% availability SLA.
  • SOC 2 Type II & ISO/IEC 27001:2022 Readiness Matrix: SOC2_ISO27001_COMPLIANCE.md
    Comprehensive AICPA Trust Services Criteria (CC1–CC9, A1, C1, PI1, P1–P8) and ISO 27001 Annex A mapping for enterprise procurement audits.
  • Autonomous AI Coding Agent Skill Definition: SKILL.md
    Standardized instructions and tool-calling directives for Antigravity, Cursor, Windsurf, and Claude Code.
  • GitHub Action CI/CD Migration Gate: action.yml
    Pre-merge migration validation and unindexed cascade lock detection (uses: RitualDev-Lab/[email protected]).

Enterprise Contact & Incident Triage


📄 License

MIT © RitualDev Lab

來源:README.md,提交 d609629

工具

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

版本歷史

1
  1. v0.2.1最新Nov 7, 2026

評分

已滿足適用檢查項的 50%

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

  • 近 30 天內可連通25 分

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

  • 已宣告認證方式10 分

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

  • 已列出工具15 分

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

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