dry-run 샌드박싱, 의도와 결과 간의 차이 분석, PII 마스킹을 통해 관계형 데이터베이스를 AI agent로부터 보호합니다.
다른 이름 RitualDev-Lab/DBShield, dbshield, @ritualdev-lab/dbshield
- 스타
- 1
- Tools
- 12
- 다운로드, 30일
- —
- 최신 버전
- 0.2.1
- 마지막 커밋
- 2026년 11월 12일
- 라이선스
- MIT
DBShield MCP란?
dry-run 샌드박싱, 의도와 결과 간의 차이 분석, PII 마스킹을 통해 관계형 데이터베이스를 AI agent로부터 보호합니다. 12개 도구를 제공합니다. 예: db_status, db_describe_schema, db_query.
프로젝트 README에서 생성된 요약
DBShield MCP server 정보
DBShield는 자율형 AI 코딩 agent와 PostgreSQL, MySQL, SQLite와 같은 관계형 데이터베이스 사이에서 보안 방화벽 역할을 합니다. Cursor, Claude Desktop, Antigravity 또는 Windsurf와 같은 도구를 사용하면서 실수로 인한 데이터 파괴나 민감 정보 유출을 방지해야 하는 개발자를 위해 설계되었습니다. 이 server는 쿼리를 가로채어 agent가 명시한 목표와 일치하는지 확인하는 지능형 wire proxy로 작동합니다.
이 시스템은 BEGIN 및 ROLLBACK 패턴을 사용하여 격리된 트랜잭션 범위 내에서 변형을 실행하는 dry-run 샌드박싱 메커니즘을 활용합니다. 이를 통해 변경 사항이 운영 환경에 반영되기 전에 영향을 받는 행 수와 컬럼 변형을 포함한 정확한 영향 범위를 계산할 수 있습니다. 또한 SQLite OS 페이지 레벨 VFS shim을 탑재하여 승인되지 않은 직접적인 파일 시스템 접근을 차단합니다.
보안은 우회 전술을 방지하기 위한 AST lexical normalizer와 비밀번호 또는 이메일 같은 민감한 필드를 삭제하는 동적 PII 마스킹 엔진을 포함한 여러 전문 컴포넌트를 통해 유지됩니다. 위험도가 높은 작업의 경우, server는 Slack 또는 Teams를 통해 2인 승인 규칙을 트리거하여 커밋이 완료되기 전 사람의 개입을 요구할 수 있습니다.
활용 사례
- 1실수로 인한 대량 삭제 방지AI agent가 레코드를 삭제하려고 시도할 때 의도보다 훨씬 더 큰 범위의 운영 데이터를 대상으로 삼는 경우를 방지합니다.
- 2SQL 결과와 agent 의도 검증개발자는 샌드박스를 사용하여 agent의 SQL 명령이 실행되기 전에 명시된 목표와 일치하는지 확인할 수 있습니다.
- 3LLM 컨텍스트에서 PII 삭제고객 이메일과 전화번호를 자동으로 마스킹하여 AI 모델의 채팅 기록으로 스트리밍되지 않도록 합니다.
프로젝트의 README를 바탕으로 작성되었습니다. 모든 활용 사례는 해당 내용의 인용문과 대조하여 확인합니다.
DBShield MCP 설치 방법
형식 확인: 2026년 11월 10일Cursor에 추가Goose에 추가Claude Code에 DBShield MCP 설치
$ claude mcp add dbshield -- npx -y @ritualdev-lab/dbshieldCursor에 DBShield MCP 설치
~/.cursor/mcp.json
{
"mcpServers": {
"dbshield": {
"command": "npx",
"args": [
"-y",
"@ritualdev-lab/dbshield"
]
}
}
}VS Code에 DBShield MCP 설치
.vscode/mcp.json
{
"servers": {
"dbshield": {
"type": "stdio",
"command": "npx",
"args": [
"-y",
"@ritualdev-lab/dbshield"
]
}
}
}VS Code CLI에 DBShield MCP 설치
$ code --add-mcp '{"name":"dbshield","type":"stdio","command":"npx","args":["-y","@ritualdev-lab/dbshield"]}'Claude Desktop에 DBShield MCP 설치
claude_desktop_config.json
{
"mcpServers": {
"dbshield": {
"command": "npx",
"args": [
"-y",
"@ritualdev-lab/dbshield"
]
}
}
}Codex에 DBShield MCP 설치
$ codex mcp add dbshield -- npx -y @ritualdev-lab/dbshieldCodex config.toml에 DBShield MCP 설치
~/.codex/config.toml
[mcp_servers.dbshield] command = "npx" args = ["-y", "@ritualdev-lab/dbshield"]
Gemini CLI에 DBShield MCP 설치
$ gemini mcp add -s user dbshield npx -- -y @ritualdev-lab/dbshieldGemini settings.json에 DBShield MCP 설치
~/.gemini/settings.json
{
"mcpServers": {
"dbshield": {
"command": "npx",
"args": [
"-y",
"@ritualdev-lab/dbshield"
]
}
}
}DBShield MCP 도구 12
README에서 감지됨db_statusdb_describe_schemadb_querydb_dry_rundb_commitdb_explain_querydb_audit_logdb_validate_migrationdb_check_schema_driftdb_check_semantic_intentdb_distributed_dry_rundb_distributed_commit
| db_status | — | |
| db_describe_schema | — | |
| db_query | — | |
| db_dry_run | — | |
| db_commit | — | |
| db_explain_query | — | |
| db_audit_log | — | |
| db_validate_migration | — | |
| db_check_schema_drift | — | |
| db_check_semantic_intent | — | |
| db_distributed_dry_run | — | |
| db_distributed_commit | — |
구성
DATABASE_URLDBSHIELD_DB_URLConnection URL or file path for target database
DBSHIELD_DIALECTTarget database dialect (postgres, mysql, sqlite)
| 이름 | 설명 | 유형 |
|---|---|---|
| DATABASE_URL | — | |
| DBSHIELD_DB_URL | Connection URL or file path for target database | |
| DBSHIELD_DIALECT | Target database dialect (postgres, mysql, sqlite) |
자동 검사
2026년 11월 12일에 실행됨전체 보고서 →자동 검사를 통과했습니다. 이는 보안 감사가 아닙니다. 코드를 직접 읽고 서버에 필요한 최소한의 권한만 부여하십시오. 검사 방식
- 소스 저장소 연결 및 접근 가능통과
- 오픈 소스 라이선스 (OSI)통과
- 최근 1년 내 커밋 또는 릴리스통과
- 패키지 이름이 인기 패키지와 유사하지 않음통과
- 원격 엔드포인트가 HTTPS 사용검사되지 않음
- 파괴적인 도구에 라벨 표시됨통과
- 모델에 대한 숨겨진 지침 없음통과
- 패키지 및 해당 종속성에 중요한 보안 권고 없음통과
README
GitHub에서 보기🛡️ DBShield
The Safety-First Database Guardrail & Sandboxing MCP Server for AI Coding Agents
Protect your databases from accidental bulk deletes, catastrophic drops, locks, and PII leaks when paired with Cursor, Claude Desktop, Antigravity, or Windsurf.
[!IMPORTANT]
💡 The Core Thesis: Bridging Intent vs. Effect
"Dry-run sandboxing is the piece that stands out. Guardrails and masking catch known bad patterns, but a sandbox shows what an agent's query would actually do before production. That gap between intent and effect is where most agent database incidents begin."
🎯 The "Intent vs. Effect" Problem in Autonomous AI Coding
When an AI coding agent acts on your database, static AST rules and regex patterns only catch known bad syntax (like DROP TABLE or WHERE 1=1). They cannot catch semantically plausible queries where the effect completely diverges from the user's intent:
┌──────────────────────────────────────┐ ┌────────────────────────────────────────────────────────────┐
│ AGENT'S STATED INTENT │ │ AGENT'S EMITTED SQL │
│ "Update avatar for user #402" │ ──► │ UPDATE users SET role = 'admin' WHERE id = 402; │
│ Expected Effect: 1 row, non-sens col │ │ Simulated Effect: Privilege escalation to superadmin! │
└──────────────────────────────────────┘ └────────────────────────────────────────────────────────────┘
▲
│
🚨 INTENT VS. EFFECT GAP DETECTED (BLOCKED)
┌──────────────────────────────────────┐ ┌────────────────────────────────────────────────────────────┐
│ AGENT'S STATED INTENT │ │ AGENT'S EMITTED SQL │
│ "Archive test trial accounts" │ ──► │ DELETE FROM accounts WHERE created_at < '2026-01-01'; │
│ Expected Blast Radius: ~5 rows │ │ Simulated Effect: 14,820 customer production accounts lost │
└──────────────────────────────────────┘ └────────────────────────────────────────────────────────────┘
▲
│
🚨 BLAST RADIUS GAP DETECTED (BLOCKED & ROLLED BACK)
🔬 How DBShield Closes the Gap via Dry-Run Sandboxing
sequenceDiagram
autonumber
actor Developer as LLM Agent / Developer
participant Proxy as DBShield Wire Proxy (:5432)
participant Guard as AST Normalizer & Intent Guard
participant Sandbox as Shadow Dry-Run Sandbox
participant OS as SQLite VFS OS Shim
participant Approvals as ChatOps (Slack / Teams)
participant DB as Production Database
Developer->>Proxy: SQL Mutation + Stated Intent Context
Proxy->>Guard: Lexical Normalization & Semantic Intent Check
alt In-line Comment Evasion / Unicode Smuggling
Guard-->>Developer: ❌ [BLOCKED] Query normalization violation
end
Guard->>Sandbox: Execute in Isolated Transaction Envelope (BEGIN ... ROLLBACK)
Sandbox->>OS: Page-Level Write Interception (Token Verified)
OS-->>Sandbox: Intercepted OS Page Diffs & Computed Row Mutations
Sandbox-->>Guard: Exact Blast Radius (Affected Rows, Column Mutations, DDL)
Guard->>Guard: Gap Analysis: Compare Intent vs. Effect
alt Gap Detected (Row Count Regressed OR Column Privilege Mismatch)
Guard->>Approvals: Dispatch Two-Man Approval Card (Slack / Teams)
Approvals-->>Developer: ⏸️ Mutation Paused Pending Human Sign-Off
else Intent Aligned & Safe Blast Radius
Guard->>DB: Monotonic Fencing Token Commit
DB-->>Developer: ✅ Committed Successfully with HMAC-SHA256 Audit Trail
end
flowchart TD
A["Agent Intent: 'Update Profile'"] --> B["Emitted SQL: 'UPDATE users SET role=admin'"]
B --> C["DBShield Wire Proxy (:5432 / :3306)"]
C --> D{"AST Lexical Normalizer<br/>(Strip Evasion & Comment Injection)"}
D -->|Passed| E["Shadow Sandbox Simulation<br/>(BEGIN ... ROLLBACK)"]
D -->|Violation| Block1["❌ Terminate with Security Alert"]
E --> F["OS Page-Level VFS Shim Interception"]
F --> G["Calculate Exact Mutation Blast Radius<br/>(Rows Mutated, Columns Modified)"]
G --> H{"Intent vs. Effect Gap Analyzer"}
H -->|"GAP DETECTED!<br/>(Privilege escalation or row explosion)"| I["🚨 Route to Slack / Teams Two-Man Rule"]
H -->|"INTENT ALIGNED<br/>(Blast radius matches intent)"| J["Sign with Monotonic Fencing Token"]
J --> K["Commit to Production Database"]
I -->|Human Approves| K
I -->|Human Rejects| L["Atomic Rollback & HMAC Ledger Alert"]
⚡ The Problem: AI Agents Writing Raw SQL
When autonomous AI coding agents interact directly with databases:
- Accidental Destruction: A missing
WHEREclause turns a targeted fix into an unrecoverableDELETE FROM users;orUPDATE orders SET status = 'cancelled';. - Catastrophic DDL: Agents dropping staging or production tables (
DROP TABLE,TRUNCATE) instead of running non-destructive migrations. - PII & Credential Leaks: Customer emails, passwords, SSNs, and API keys are streamed in plaintext directly into model contexts and chat transcripts.
- Denial-of-Service: Unindexed cartesian joins or queries lacking
LIMITclauses 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:
- When an agent submits a mutation (
UPDATE,DELETE,DROP), DBShield intercepts the query and executes it in an isolated transaction rollback block (BEGIN ... ROLLBACK). - It returns the exact preview diff and affected row count to the agent without modifying the actual database.
- 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
- 🧪 Dry-Run Auto-Rollback Sandboxing & Intent vs. Effect Gap Engine: Executes writes in an isolated transaction envelope (
BEGIN TRANSACTION READ ONLY; ... ROLLBACK;). Calculates the exact difference between the agent's stated intent and actual row/column impact before anything touches production. - 📁 SQLite OS Page-Level VFS Shim (
SqliteVfsShim): Intercepts OS disk page read/write operations (4096-byte pages), blocking agents from altering.sqliteor.dbfiles via direct filesystem access outside the DBShield wire proxy (UNAUTHORIZED_DIRECT_FS_WRITE). - 🔄 Multi-Replica Raft Consensus & Monotonic Fencing Tokens: Distributed state machine coordinator (
RaftConsensusCoordinator) synchronizing transaction isolation leases and two-phase commit votes across clustered proxies to eliminate split-brain mutations. - 🔏 Append-Only HMAC-SHA256 Audit Ledger (
HmacAuditLedger): Meets PCI-DSS v4.0 Requirement 10 and SOC 2 CC6.8. Implements strictly contiguous monotonic sequence numbers, query payload hashing, and Merkle tree root calculation for tamper-evident compliance exports. - 🔍 SQL AST Lexical Normalizer: Neutralizes zero-width unicode smuggling, comment-evasion tricks (e.g.
SEL/**/ECT), multi-statement injection, and unconstrained deletes. - 🔒 Dynamic Zero-Leak PII Masking: Automatically detects sensitive fields (passwords, emails, phone numbers, tokens) and masks them before streaming back to LLM context.
- 🎭 Virtual Schema Masking & Column-Level RBAC: Hides sensitive internal tables (
credentials,internal_audit,admin_*) frominformation_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:
npx @ritualdev-lab/dbshield install-claude
Or manually add to claude_desktop_config.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:
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:
npx @ritualdev-lab/dbshield proxy --port 5433 --upstream-host 127.0.0.1 --upstream-port 5432
In your application or .env:
DATABASE_URL="postgres://user:password@127.0.0.1:5433/production_db"
4. Terminal CLI & Status
# Check status and inspect connected database
npx @ritualdev-lab/dbshield status
# Initialize starter configuration file
npx @ritualdev-lab/dbshield init
5. Live Query Approval Feed & Web Dashboard
Start the real-time query approval web interface (:3100):
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)
{
"$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
| Tier | Mutation Limit | Destructive DDL | Dry-Run Required | PII Masking | Best For |
|---|---|---|---|---|---|
STRICT |
Max 1 row | ❌ Blocked | ✅ Always Required | 🔒 Enforced | Production, Staging |
BALANCED |
Max 50 rows | ❌ Blocked | ✅ On Bulk Writes | 🔒 Enforced | Local Dev, Team Collaboration |
PERMISSIVE |
Max 500 rows | ⚠️ Warned | Optional | Optional | Sandbox Benchmarks |
🛠️ MCP Tools Reference
| Tool | Description |
|---|---|
db_status |
Inspect gateway connectivity, active safety tier, cost gate, and database statistics. |
db_describe_schema |
Safe introspection of tables, columns, constraints, and relations. |
db_query |
Safe read and mutation query execution with automatic PII redaction, cost gate, and DDL checks. |
db_dry_run |
Test mutation inside an auto-rollback transaction with row delta preview and intent verification. |
db_commit |
Execute verified mutation accompanied by cryptographic authorization token. |
db_explain_query |
Analyze query execution plans, detect unindexed full-table scans, and receive index hints. |
db_audit_log |
Retrieve compliance query audit trail, blocked operations, and risk scores. |
db_validate_migration |
Validate DDL migration scripts for lock hazards and generate zero-downtime execution recipes. |
db_check_schema_drift |
Audit live database foreign keys for missing indexes and detect structural schema drift. |
db_check_semantic_intent |
Check stated English user intent against SQL AST target columns to stop unauthorized privilege/financial mutations. |
db_distributed_dry_run |
Simulate atomic mutations across multi-store environments (Postgres, SQLite, Redis) and receive unified token. |
db_distributed_commit |
Execute 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 Operation | Classification Mechanism | Static AST Guardrail | Execution Boundary & Rollback | Data Masking & Privacy |
|---|---|---|---|---|
| SELECT | Prepared-statement column reflection (stmt.columns()) |
Detects missing LIMIT in STRICT tier; warns if limit exceeds server cap |
Streaming iterator (stmt.iterate()) caps memory; truncates at maxRowsPerRead |
Zero-leak dynamic PII masking on result rows |
| WITH ... (CTE) | Prepared-statement column reflection & recursive AST analysis | Recursively extracts underlying mutated tables & verifies read safety | Streaming iterator (stmt.iterate()) with hard read ceiling |
Zero-leak dynamic PII masking on result rows |
| UPDATE (Targeted) | AST evaluation & tautology checker (evaluateWhereClause) |
Blocks unconstrained updates, WHERE 1=1, WHERE true, tautological OR |
Atomic transaction; rolls back if affected rows exceed maxMutationRows |
Literal masking in logs & database errors |
| DELETE (Targeted) | AST evaluation & tautology checker (evaluateWhereClause) |
Blocks unconstrained deletes, WHERE 1=1, tautological OR |
Atomic transaction; rolls back if affected rows exceed maxMutationRows |
Literal masking in logs & database errors |
| INSERT | AST evaluation & dialect parser | Pre-flight dry run simulation required under STRICT tier | Atomic transaction; rolls back if inserted rows exceed maxMutationRows |
Redacts sensitive literals in (cols) VALUES (vals) |
| DROP TABLE / TRUNCATE | AST statement opcode inspection | CRITICAL BLOCK: Intercepted before database touch unless explicitly overridden | Direct execution blocked | Audit log records blocked attempt with high risk score |
| ALTER TABLE DROP COLUMN | AST expression visitor (expr.action) |
BLOCKED: Intercepted before database touch to prevent schema data loss | Direct execution blocked | Audit log records blocked attempt |
| EXPLAIN / PRAGMA | Prepared-statement column reflection | Safe read-only inspection | Read capped at maxRowsPerRead |
Sanitized output |
Enforced Guarantees Breakdown
- 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).
- Commit authorization tokens are cryptographically signed (HMAC-SHA256) binding the exact normalized SQL query text, typed parameters (
- Hard Mutation Ceilings & Transactional Rollbacks (B2):
- Exceeding
maxRowsPerMutationis 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_commitrun inside an atomic transaction block: if actual row modifications exceed the authorized ceiling, DBShield immediately executesROLLBACK;and aborts.
- Exceeding
- 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].
- Protects against concurrent modifications between dry run and commit: if underlying database rows change such that actual affected rows differ from simulated rows (
- 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_logreturns strictly sanitized compliance records.
- Memory-Safe Streaming Read Row Capping (B4):
- SQLite row reads are streamed lazily using Node.js
stmt.iterate(). - Results are capped at
maxRowsPerReadwithout buffering the full dataset into Node.js heap memory, returning agent-friendly pagination metadata (totalReturned,isTruncated,maxAllowedRows,hasMore,warning).
- SQLite row reads are streamed lazily using Node.js
- 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.
- Replaced naive string prefix checks with SQLite prepared-statement column metadata (
🔒 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:
chmod 600 /var/data/production.db chown 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:
{ "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:
-- Create isolated role CREATE 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_runoutputs can be piped to an external human-in-the-loop review system (Slack, Teams, or ticketing webhook) before the token is submitted todb_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:
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
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):
# Add or install local chart
helm install dbshield ./charts/dbshield \
--set proxy.upstreamHost="my-db.postgres.database.azure.com" \
--set proxy.safetyTier="BALANCED" \
--set replicaCount=2 \
--set autoscaling.enabled=true
DBShield MCP 질문
DBShield MCP를 Claude Code에 추가하려면 어떻게 하나요?
터미널에서 claude mcp add dbshield -- npx -y @ritualdev-lab/dbshield를 실행합니다. 모든 프로젝트에서 사용할 수 있게 하려면 --scope user를 추가합니다.
DBShield MCP를 Cursor에 추가하려면 어떻게 하나요?
~/.cursor/mcp.json를 열고 mcpServers 아래에 서버를 추가합니다. 위 설치 섹션에 표시된 Cursor 구성을 사용합니다.
DBShield MCP는 어떤 도구를 제공하나요?
12개 도구를 제공합니다. 예: db_status, db_describe_schema, db_query, db_dry_run, db_commit.
DBShield란 무엇인가요?
DBShield는 AI agent가 쿼리를 실행할 때 발생할 수 있는 실수로 인한 데이터 변형 및 PII 유출로부터 관계형 데이터베이스를 보호하도록 설계된 오픈 소스 데이터베이스 가드레일, 가상 스키마 마스킹 프록시 및 MCP server입니다.
가상 스키마 마스킹(Virtual Schema Masking)이란 무엇인가요?
introspection 과정에서 agent에게 민감한 내부 테이블이나 제한된 컬럼이 보이지 않도록 wire protocol 쿼리를 가로채는 기능입니다.