
DB Connect MCP
io.github.yugui923由 GitHub 帳號 yugui923 發布v0.3.1更新於 Oct 24, 2026
Multi-database MCP server for PostgreSQL, MySQL, and ClickHouse
概覽
唯讀 MCP 伺服器,讓助理探索並分析 PostgreSQL、MySQL/MariaDB 與 ClickHouse 資料庫。
- 可以做什麼
- 每個伺服器實例連接一個資料庫,提供列出結構描述與資料表、描述資料表結構、查看外鍵關聯,以及依樣式搜尋物件的工具。它也能對欄位做統計與值分布分析、取樣資料、執行帶自動列數限制的唯讀 SELECT 或 WITH 查詢,並回傳預估或 EXPLAIN ANALYZE 查詢計畫。資料庫脈絡也會以可快取的 MCP 資源形式提供。
- 適用情境
- 適合讓助理了解陌生的資料庫結構、回答資料表結構與關聯的問題,或在唯讀前提下做探索性查詢。偏向資料分析與理解資料,而不是應用程式開發或修改資料表結構。
- 執行需求
- 本機 Python 3.10 以上環境,以 pip 安裝 db-connect-mcp,並用 python -m db_connect_mcp 執行。需要 DATABASE_URL 連線字串,對應 PostgreSQL 9.6+、MySQL/MariaDB 5.7+/10.2+ 或 ClickHouse,且能連上該資料庫網路。資料庫位於防火牆後時可選用 SSH 通道設定(SSH_HOST、SSH_PORT、SSH_USERNAME,以及 SSH_PASSWORD、SSH_PRIVATE_KEY_PATH 或 SSH_PRIVATE_KEY)。
安裝
在 SourceWeft 中
- 開啟 儀表板中的 DB Connect MCP,將其新增到工作區。
- 為需要使用其工具的對話啟用該服務。
Desktop only,透過 STDIO。 STDIO 服務會啟動本機處理程序,因此需要 SourceWeft 桌面主機。
其他 MCP 客戶端
參照 儲存庫 中的啟動說明。
README
db-connect-mcp - Multi-Database MCP Server
[CI] [CodeQL] [codecov] [OpenSSF Scorecard] [License: MIT]
A read-only MCP (Model Context Protocol) server for exploratory data analysis across multiple database systems. This server provides safe, read-only access to PostgreSQL, MySQL, and ClickHouse databases with comprehensive analysis capabilities.
Demo
Quick Start
-
Install:
-
Add to Claude Desktop
claude_desktop_config.json: -
Restart Claude Desktop and start querying your database!
Note: Using
python -m db_connect_mcpensures the command works even if Python's Scripts directory isn't in your PATH. ExistingmcpServersconfigurations remain valid: stdio is still the default. The optional remote Streamable HTTP mode serves both older initialize-based clients and 2026-07-28 session-free MCP clients at/mcpwithout changing the database or SSH configuration. Existing HTTP deployments must review forwarded Host/Origin values: the upgrade enables transport validation and may requireMCP_ALLOWED_HOSTS/MCP_ALLOWED_ORIGINS.
Features
🗄️ Multi-Database Support
- PostgreSQL - Full support with advanced metadata and statistics
- MySQL - Complete support for MySQL and MariaDB databases
- ClickHouse - Support for analytical workloads and columnar storage
🔍 Database Exploration
- List schemas - View all schemas in the database
- List tables - See all tables with metadata (size, row counts, comments)
- Describe tables - Get detailed column information, indexes, and constraints
- View relationships - Understand foreign key relationships between tables
📊 Data Analysis
- Column profiling - Statistical analysis of column data
- Basic statistics (count, unique values, nulls)
- Numeric statistics (mean, median, std dev, quartiles)
- Value frequency distribution
- Cardinality analysis
- Data sampling - Preview table data with configurable limits
- Custom queries - Execute read-only SQL queries safely
- Object search - Find schemas, tables, views, columns, and indexes without loading the full catalog
- Query plans - Inspect estimated plans or opt into
EXPLAIN ANALYZEwhere supported - Hypothetical indexes (PostgreSQL, opt-in) - Compare HypoPG planner estimates without creating a real index. Requires an administrator-installed HypoPG extension,
DB_HYPOPG_ENABLED=trueon the server, andopt_in=trueon eachcompare_hypothetical_indexcall. Provide a single simple SELECT, schema, table, and 1–4 column names; comments, CTEs, functions, literals, parameters, and multiple statements are rejected. The tool uses one read-only connection andEXPLAINwithoutANALYZE, caps planning/lock waits at 5s/1s, and rolls back session-local changes. The response reportshypothetical_index_usedby matching the HypoPG index name in the resulting plan; an unused candidate may be irrelevant or simply not chosen by the planner. The candidate requires schemaUSAGEand tableSELECTprivileges. These estimates are not measured speedups.
🔒 Safety Features
- Read-only enforcement - All connections are read-only at multiple levels
- Query validation - Only SELECT and WITH queries are allowed
- Automatic limits - Queries are automatically limited to prevent large result sets
- Connection string safety - Automatically adds read-only parameters
- Database-specific safety - Each adapter implements appropriate safety measures
🔭 Observability
db-connect-mcp inherits the MCP SDK's built-in OpenTelemetry server instrumentation. The API is a no-op until the launching process configures an SDK and exporter. Review exporter sampling and redaction before production use, because database identifiers and error details may be sensitive.
💡 Best Practices
Tip: db-connect-mcp works best with databases that have proper comments on tables and columns. When your database includes descriptive comments, the MCP server can provide richer context to AI assistants, leading to better understanding of your data model and more accurate query suggestions.
Adding comments in PostgreSQL:
Adding comments in MySQL:
The server automatically retrieves and displays these comments when describing tables, helping AI assistants understand the purpose and semantics of your data.
🔐 SSH Tunnel Support
- Secure remote access - Connect to databases behind firewalls via SSH tunnels
- Automatic tunnel management - Tunnel lifecycle handled transparently (start, health check, restart, cleanup)
- Reliable native forwarding - Paramiko
SSHClienttransport with target preflight and stable-port recovery - Flexible authentication - Password or private key based SSH authentication
- Any database type - Works with PostgreSQL, MySQL, and ClickHouse through the same tunnel
See the SSH Tunnel Guide for configuration details.
Installation
Prerequisites
- Python 3.10 or higher
- A database: PostgreSQL (9.6+), MySQL/MariaDB (5.7+/10.2+), or ClickHouse
Install via pip
That's it! The package is now ready to use.
For developers: See Development Guide for setting up a development environment.
Configuration
Create a .env file with your database connection string:
The server automatically detects the database type and adds appropriate read-only parameters.
For PostgreSQL, set ENABLE_PG_STAT_STATEMENTS=true to advertise the optional
get_top_queries tool. It reads bounded cumulative statistics for the current
user/database if pg_stat_statements was installed and preloaded by the database
administrator. It does not install extensions. Query text is omitted unless
explicitly requested and can contain sensitive information. See the
top-query report contract for bounds and statuses.
Connection String Examples
The server now provides more flexible and secure URL handling:
- Automatic driver detection: Async drivers are automatically added if not specified
- JDBC URL support: JDBC prefixes are automatically handled
jdbc:postgresql://...→postgresql+asyncpg://...jdbc:mysql://...→mysql+aiomysql://...- Works with all dialect variations (e.g.,
jdbc:postgres://,jdbc:mariadb://)
- Database dialect variations: Common variations are automatically normalized
- PostgreSQL:
postgresql,postgres,pg,psql,pgsql - MySQL/MariaDB:
mysql,mariadb,maria - ClickHouse:
clickhouse,ch,click
- PostgreSQL:
- Allowlist-based parameter filtering: Only known-safe parameters are preserved
- Database-specific parameters: Each database type has its own set of supported parameters
- Robust parsing: Handles various URL formats gracefully
PostgreSQL:
Supported PostgreSQL Parameters:
application_name- Identifies your app in pg_stat_activity (useful for monitoring)connect_timeout- Connection timeout in secondscommand_timeout- Default timeout for operationsssl/sslmode- SSL connection requirements (automatically converted for asyncpg compatibility)server_settings- Server settings dictionaryoptions- Command-line options to send to server- Performance tuning:
prepared_statement_cache_size,max_cached_statement_lifetime, etc.
MySQL/MariaDB:
Supported MySQL Parameters:
charset- Character encoding (e.g., utf8mb4) - critical for data integrityuse_unicode- Enable Unicode supportconnect_timeout,read_timeout,write_timeout- Various timeoutsautocommit- Transaction autocommit modeinit_command- Initial SQL command to runsql_mode- SQL mode settingstime_zone- Time zone setting
ClickHouse:
Supported ClickHouse Parameters:
database- Default database selectiontimeout,connect_timeout,send_receive_timeout- Various timeoutscompress,compression- Enable compressionmax_block_size,max_threads- Performance tuning
Note:
- SSL parameters (
ssl,sslmode) are automatically converted to the correct format for asyncpg - Certificate file parameters (
sslcert,sslkey,sslrootcert) are filtered out as they can cause compatibility issues - Only parameters known to work with async drivers are preserved
Usage
Running the Server
Note: Using
python -m db_connect_mcpworks regardless of whether Python's Scripts directory is in your PATH.
Using with Claude Code
Add the MCP server to your project's .mcp.json:
Or manually create .mcp.json in your project root. Below are examples for each supported database:
PostgreSQL:
MySQL:
ClickHouse:
PostgreSQL via SSH tunnel (database behind a firewall, reachable only through a bastion host):
MySQL via SSH tunnel:
Multiple databases (each MCP server instance connects to one database):
After creating .mcp.json, restart Claude Code and verify with /mcp. You should see db-connect-mcp listed with all available tools.
Tip: Instead of
SSH_PRIVATE_KEY_PATH, you can useSSH_PRIVATE_KEYto pass the private key content directly as a string (raw PEM or base64-encoded PEM). This is useful in CI/CD or cloud environments where mounting key files is impractical.
See the SSH Tunnel Guide for full tunnel configuration reference.
Using with Claude Desktop
Add the server to your Claude Desktop configuration (claude_desktop_config.json):
The same database URL formats and SSH tunnel environment variables shown in the Claude Code examples above work identically with Claude Desktop.
For development: See Development Guide for running from source with uv.
Database Feature Support
MCP Resources
Modern MCP clients can discover database context as private, cache-aware JSON resources in addition to calling tools:
db-connect://database— database identity, dialect, and capabilitiesdb-connect://schema/{schema}— schema counts and metadatadb-connect://table/{schema}/{table}— columns, indexes, constraints, and comments
The schema and table forms are also advertised as resource templates for direct access when the identifier is already known.
Resource catalogs are URI-sorted and cursor-paginated in pages of 100. Cursors are tied to a catalog snapshot; if schemas or tables change between pages, the server asks the client to restart pagination instead of returning an inconsistent traversal.
Available Tools
All tools publish JSON Schema input and output contracts, read-only behavior
annotations, and machine-readable structured results. The same result remains
available as JSON text for clients that do not yet consume MCP structured
content. Structured list results use an items envelope while their legacy
text form remains a JSON array.
get_database_info
Get database metadata, including the dialect, version, connection details, read-only status, and capabilities.
list_schemas
List all schemas in the database.
list_tables
List all tables in a schema with metadata.
- Parameters:
schema(optional): Schema name (default: "public")
describe_table
Get detailed information about a table.
- Parameters:
table: Name of the tableschema(optional): Schema name (default: "public")
analyze_column
Analyze a column with statistics and distribution.
- Parameters:
table: Name of the tablecolumn: Name of the columnschema(optional): Schema name (default: "public")
sample_data
Get a sample of data from a table.
- Parameters:
table: Name of the tableschema(optional): Schema name (default: "public")limit(optional): Number of rows (default: 100, max: 1000)
execute_query
Execute a read-only SQL query.
- Parameters:
query: SQL query (must be SELECT or WITH)limit(optional): Maximum rows (default: 1000, max: 10000)
get_table_relationships
Get foreign key relationships for a table.
- Parameters:
table: Name of the tableschema(optional): Schema name (default: "public")
explain_query
Get a database-specific query execution plan.
- Parameters:
query: SQL query to explainanalyze(optional): Execute the query and include actual runtime statistics (default: false)
search_objects
Search schemas, tables, views, columns, and indexes with progressive detail.
- Parameters:
pattern: SQLLIKEpattern, such as%user%object_types(optional): Object types to includedetail_level(optional):names,summary, orfull(default:summary)schema(optional): Restrict the search to a schematable(optional): Restrict column and index searches to a tablelimit(optional): Maximum matches (default: 100, max: 1000)
Example Usage
Once configured, you can use the server with any compatible MCP client:
Database-Specific Examples
Working with PostgreSQL:
Working with MySQL:
Working with ClickHouse:
Safety and Security
- Read-only intent: Write statements are rejected, and PostgreSQL and MySQL connections use read-only transactions. This is not a SQL sandbox: SELECT may call functions with external or session-level effects. MySQL read-only sessions are not pooled across requests; direct named-lock calls and variable assignments are rejected in
execute_query. Use a least-privilege database role on every engine, especially ClickHouse, where SELECT may invoke external table functions. - Query limits:
execute_querybounds returned rows and serialized response size, not total database work or peak process memory. ClickHouse's synchronous driver may buffer a full result before the application checks it. Use database-side execution, memory, and access limits. See health and query safety notes.
Development
For detailed development setup, testing, and contribution guidelines, see the Development Guide.
Project Structure
Architecture
The server uses an adapter pattern to support multiple database systems:
- Adapters: Each database type has its own adapter that implements database-specific functionality
- Core: Shared functionality for connection management, query execution, and metadata inspection
- Models: Pydantic models for type safety and validation
- Server: MCP server implementation that routes requests to appropriate components
Running Tests
Local Test Database:
- PostgreSQL 17 with 50K+ rows of sample data across 7 tables
- Automatically initialized via Docker Compose
- No cloud database or .env configuration required
- See Docker Setup for details
See the Development Guide and Testing Guide for detailed testing instructions.
Troubleshooting
Connection Issues
- Verify your DATABASE_URL is correct and includes the appropriate driver
- Check network connectivity to the database
- Ensure the database user has appropriate read permissions
- For PostgreSQL: Check if SSL is required (
?ssl=require) - For MySQL: Verify charset settings (
?charset=utf8mb4) - For ClickHouse: Check port (default is 9000 for native, 8123 for HTTP)
Database-Specific Issues
PostgreSQL:
- Ensure
asyncpgdriver is specified for async operations - SSL certificates may be required for cloud databases
MySQL/MariaDB:
- Use
aiomysqldriver for async support - Check MySQL version compatibility (5.7+ or MariaDB 10.2+)
- Verify charset and collation settings
ClickHouse:
- Use
asynchdriver for async operations - Note that ClickHouse has limited support for foreign keys and constraints
- Some statistical functions may not be available
Permission Errors
- The database user needs at least SELECT permissions on the schemas/tables you want to analyze
- Some statistical functions may require additional permissions
- ClickHouse may require specific permissions for system tables
Large Result Sets
- Use the
limitparameter to control result size - The server automatically limits results to prevent memory issues
- For large analyses, consider using more specific queries
Author
Created by Yuri Gui.
Contributing
Contributions are welcome! The server is designed to be read-only and safe by default. Any new features should maintain these safety guarantees.
License
MIT License - See LICENSE file for details
來源:README.md,提交 3049fe7
工具
0版本歷史
1- v0.3.1最新Sep 16, 2026
評分
已滿足適用檢查項的 50%
該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。
- 近 30 天內可連通25 分
請保持端點能夠回應 MCP 握手;SourceWeft 每 30 天探測一次。
- 已宣告認證方式10 分
請在註冊中心條目中宣告憑證請求標頭,或保持端點能夠回應探測,以便判定其認證方式。
- 已列出工具15 分
請讓伺服器在無憑證時回應 tools/list,或發布可在沙箱中無憑證啟動的軟體包。
- 描述必需15 分
- 圖示10 分
- 文件15 分
- 授權條款10 分