Skip to main content
Glama

DB-Guard MCP

License: MIT Python 3.10+ Java 17+ MCP Compatible

简体中文文档 (Chinese README) | Security Architecture

DB-Guard MCP is a zero-password, defense-in-depth Model Context Protocol (MCP) server that bridges AI coding assistants (GitHub Copilot in IntelliJ IDEA & VS Code, Cursor, Claude Code / Desktop) with the databases already configured in your local DBeaver — across MariaDB, MySQL, Oracle, PostgreSQL, GaussDB, and H2 on Windows, macOS, and Linux.

It is purpose-built to solve a painful daily engineering workflow: correlating application error logs + domain code + live database records to rapidly pinpoint bad/corrupted data, preview fixes in rolled-back transactions, and remediate safely with mandatory backups and audit logs.


Key Features

  • Zero-Password DBeaver Reuse (Including SSH Tunnels) Automatically discovers connections, cached JDBC drivers, and SSH tunnels from your local DBeaver workspace (workspace6). Credentials are decrypted strictly in JVM memory — never written to config files, logs, or exposed to the LLM.

  • Protocol & Engine-Level Read-Only Lock Diagnostic tools (diagnose_query, inspect_schema, explain_query) strip multi-statement flags (allowMultiQueries=false), enforce Connection.setReadOnly(true) + SET SESSION TRANSACTION READ ONLY (SET TRANSACTION READ ONLY on Oracle), apply query timeouts and row caps, and always ROLLBACK on close.

  • Anomaly-Preserving Dynamic PII Masking Automatically masks sensitive columns and values (IDs, names, phones, emails, secrets) before returning results to cloud LLMs — while preserving NULL vs empty string "", character length, and leading/trailing whitespace (J***h [MASKED:PII len=12 trail_ws=2]) so AI can still spot data corruption!

  • Rolled-Back Transactional Previews (preview_remediation) Tests UPDATE / DELETE / INSERT fixes inside a real database transaction (START TRANSACTION $\rightarrow$ pre-SELECT $\rightarrow$ DML $\rightarrow$ post-SELECT $\rightarrow$ ROLLBACK), verifying constraints and returning exact row diffs with zero persistence.

  • Fail-Closed "No Backup, No Modification" & Dual Audit Ledger Every modification — whether handed off to DBeaver (open_remediation_in_dbeaver) or committed locally (apply_remediation) — must first persist three backup artifacts (backup_record.json, before_rows_insert.sql, and primary-key-accurate rollback.sql) and append to modification_audit.md & modification_audit.jsonl.


Related MCP server: safe-sql-mcp

Architecture

flowchart LR
    IDE["IDE AI Agent<br/>(GitHub Copilot / Cursor / Claude)"] <-->|"MCP stdio (JSON-RPC)"| PY["db-guard-mcp (Python)<br/>SQL AST Guard + PII Masker + Auditor"]
    PY <-->|"Single-Statement Pipe"| JVM["JdbcBridge (JVM)<br/>In-Memory DBeaver Vault + SSHJ Tunnel"]
    DBV[("Local DBeaver Workspace<br/>data-sources.json + drivers")] -.->|"Auto-Discover"| JVM
    JVM <-->|"READ ONLY Lock / Atomic Tx"| DB[("MariaDB / MySQL / Oracle /<br/>PostgreSQL / GaussDB")]
    PY -->|"Fail-Closed Pre-Backup"| BKP["~/.db-guard-mcp/<br/>audit-backups/ & change-logs/"]
    PY -->|"1-Click Transaction Script"| GUI["DBeaver Desktop UI<br/>(Manual Review & COMMIT)"]

Prerequisites

  • Python 3.10+

  • JDK 17+ (java and javac on PATH)

  • DBeaver (Community or PRO) with at least one saved database connection (Save password checked) and downloaded driver


Quick Start

1. Install

git clone https://github.com/kasonye/copilot-dbeaver-mcp.git
cd copilot-dbeaver-mcp
pip install -e .

Verify your environment, JDBC drivers, and DBeaver connection discovery:

db-guard-mcp --doctor

2. Connect to GitHub Copilot (IntelliJ IDEA / VS Code)

Add db-guard-mcp to your global MCP configuration so it works across every project without adding files to business repositories:

  • IntelliJ IDEA / JetBrains IDEs:

    • Windows: %LOCALAPPDATA%\github-copilot\intellij\mcp.json

    • macOS / Linux: ~/.config/github-copilot/intellij/mcp.json

  • VS Code:User mcp.json (Command Palette $\rightarrow$ MCP: Open User Configuration)

{
  "servers": {
    "db-guard-dbeaver": {
      "type": "stdio",
      "command": "db-guard-mcp",
      "args": []
    }
  }
}

(Tip: If db-guard-mcp is not on your global PATH, set "command": "/path/to/python" and "args": ["-m", "db_guard"].)


Exposed MCP Tools (10 Tools)

Tool

Mode

Description

scan_recent_db_errors_in_logs

Read-Only

Scans project logs for SQL/JPA/Hibernate/constraint exceptions and highlights application stack frames.

list_connections

Read-Only

Lists all auto-discovered DBeaver connections, drivers, and SSH tunnel status (zero secrets exposed).

list_databases

Read-Only

Lists available databases / schemas on a specified DBeaver connection.

inspect_schema

Read-Only

Inspects tables, columns, data types, nullability, primary keys, foreign keys, and table DDL.

explain_query

Read-Only

Runs EXPLAIN to check index usage before querying large tables.

diagnose_query

Read-Only

Runs a single SELECT / SHOW / DESCRIBE inside a READ ONLY transaction with PII masking.

preview_remediation

Dry-Run (ROLLBACK)

Runs target DML inside a rolled-back transaction, returning before/after diffs and generating a DBeaver .sql script.

open_remediation_in_dbeaver

Backup + Handoff

Backs up original rows + logs the operation, then opens a manual-transaction .sql script (SET autocommit=0; ... ROLLBACK;) in DBeaver.

apply_remediation

Backup + Atomic Commit

Allowed only on allow_direct_apply_connections (default: localhost). Persists full backups + audit logs before row-count-locked commit.

list_modification_history

Read-Only

Queries chronological modification audit logs, field diffs, backup bundles, and rollback.sql paths.


Configuration (Optional)

Copy config.example.yaml to ~/.db-guard-mcp/config.yaml (or ./config.local.yaml). Changes are hot-reloaded on every tool call without restarting your IDE.


Running Tests

python -m unittest discover -s tests -v

License

Released under the MIT License.

Available Tools

10 tools
apply_remediationB
Destructive

MANDATORY BACKUP + AUDIT COMMIT: Persists full original row backups (JSON + INSERT SQL + rollback.sql) to audit-backups/, executes atomic row-count-locked DML on allowed connections, and logs field-level changes to change-logs/modification_audit.md & .jsonl.

Inputs: table (required), dml_sql (required), where_clause (required), expected_affected_rows (required), +3 more.

diagnose_queryA
Read-onlyIdempotent

Executes a single strictly READ-ONLY diagnostic query (SELECT / SHOW / DESCRIBE) using DBeaver's saved connection inside an engine-enforced READ ONLY transaction with timeout & row caps. Automatically masks PII columns while preserving length, NULL vs empty, and whitespace anomalies.

Inputs: sql (required), database, max_rows, connection.

explain_queryB
Read-onlyIdempotent

Runs EXPLAIN on a SELECT query using the specified DBeaver connection + database.

Inputs: sql (required), database, connection.

inspect_schemaA
Read-onlyIdempotent

Inspects tables, columns, types, nullability, PKs, FKs, and DDL on a DBeaver connection + database. Pass table='exact_table' for full column/FK/DDL details, or table_pattern='%order%' to search tables.

Inputs: table, database, connection, max_tables, +1 more.

list_connectionsA
Read-onlyIdempotent

Lists all ready-to-use database connections automatically discovered from local DBeaver (names, hosts, ports, drivers, SSH tunnel flags) without exposing any credentials.

Inputs: no named parameters.

list_databasesA
Read-onlyIdempotent

Lists all databases / schemas available on a specified DBeaver connection.

Inputs: connection.

list_modification_historyB
Read-onlyIdempotent

Lists chronological database modification audit logs, field diffs, original data backup paths, and ready-to-run rollback.sql paths.

Inputs: limit, table.

open_remediation_in_dbeaverB
Idempotent

MANDATORY BACKUP + AUDIT HANDOFF: First backs up original rows (JSON + INSERT SQL + rollback.sql) to audit-backups/ and appends an audit entry to change-logs/, then opens the transaction-wrapped .sql script directly in DBeaver bound to that connection for human review and COMMIT.

Inputs: table, dml_sql, database, connection, +3 more.

preview_remediationB
Read-onlyIdempotent

Runs a real transactional dry-run (START TRANSACTION -> pre-SELECT -> DML -> post-SELECT -> ROLLBACK) using DBeaver's connection WITHOUT committing any change. Returns before/after row diff and generates a transaction-safe .sql script.

Inputs: table (required), dml_sql (required), where_clause (required), database, +2 more.

scan_recent_db_errors_in_logsB
Read-onlyIdempotent

Scans application log files in the current workspace (pass project_dir or log_path) for recent SQL, JPA, Hibernate, constraint, and bad-data exceptions.

Inputs: log_path, tail_lines, max_matches, project_dir.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.7/5.0

    Scored across 10 tools

    Disambiguation4/5

    Most tools target distinct stages: connection discovery, schema inspection, read-only diagnostics, remediation dry-run/handoff/apply, and audit history. explain_query and diagnose_query both execute or analyze queries, and preview_remediation vs open_remediation_in_dbeaver both involve transaction-safe scripts, but the descriptions make their intended uses distinguishable.

    Naming Consistency5/5

    All tool names use snake_case and begin with action verbs, with no camelCase or mixed naming styles. Some names are long, such as scan_recent_db_errors_in_logs and open_remediation_in_dbeaver, but they still follow a predictable verb-led pattern.

    Tool Count5/5

    10 tools is well within the ideal 3–15 range and maps cleanly to the database diagnostics-to-remediation workflow. No tools appear redundant or trivial for the stated scope.

    Completeness4/5

    The surface covers connection discovery, schema inspection, read-only query diagnosis, remediation preview/handoff/apply, and audit history, which is a complete lifecycle for guarded database changes. The main gap is the lack of an explicit rollback/revert execution tool, relying instead on generated rollback.sql paths for manual use.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Provides AI assistants with read-only access to inspect database schemas, preview data, and run safe queries across PostgreSQL, MySQL, MongoDB, and SQL Server. It enables AI tools to understand database structures and relationships automatically to generate more accurate code.
      6 npm
      7
      MIT
    • F
      license
      Not graded
      quality
      D
      maintenance
      Enables read-only SQL database access for AI assistants, allowing schema exploration and safe query execution without risk of data modification.
      -
    • A
      license
      B
      quality
      D
      maintenance
      Enables AI assistants to interact with multiple SQL databases (PostgreSQL, MySQL, SQL Server, SQLite, Trino) through MCP, reusing existing DBeaver connections for queries, schema management, and transactions, with SSH tunneling and read-only mode support.
      22
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      Gives AI coding tools reviewed access to PostgreSQL, MySQL, SQL Server, and SQLite databases, letting read-only queries run instantly while every data or schema change pauses for human approval in a review dialog. It also exposes schema introspection for agents and a way to open the connection manager.
      MIT