Overview
DBHub follows a modular architecture centered around the Model Context Protocol (MCP). The design emphasizes:- Modular Connectors: Database-specific implementations behind a common interface
- Transport Abstraction: Support for both stdio (desktop tools) and HTTP (network clients)
- Token Efficiency: Progressive disclosure patterns to minimize context window usage
- Multi-Source Support: Connect to multiple databases simultaneously
- Type Safety: TypeScript strict mode throughout
Architecture Diagram
Core Components
Connector Registry Pattern
The Connector Registry provides dynamic registration and discovery of database connectors. Location:src/connectors/interface.ts:210-266
- Automatic connector discovery based on DSN format
- Type-safe connector lookup
- Sample DSN generation for documentation
- Singleton pattern for global access
Connector Manager
The Connector Manager orchestrates multi-database connections and lifecycle management. Location:src/connectors/manager.ts
Core Responsibilities:
- Multi-Source Support: Maintains a
Map<sourceId, Connector>for named connections - Connection Lifecycle: Handles connect/disconnect for all sources
- SSH Tunnel Management: Establishes and manages SSH tunnels per source
- Lazy Connections: Defers connection until first use (optional)
- Default Source: First configured source is the default when no
source_idspecified
Tool Handlers
Tool handlers implement MCP protocol tools with clean separation of concerns. Location:src/tools/
execute_sql (src/tools/execute-sql.ts):
- Execute SQL queries with parameterized inputs
- Apply row limits and read-only restrictions
- Transaction support (multi-statement execution)
- Request tracking and logging
src/tools/search-objects.ts):
- Unified search/list tool with progressive disclosure
- Pattern-based search (SQL LIKE syntax:
%,_) - Detail levels:
names(minimal),summary(metadata),full(complete) - Object types: schemas, tables, columns, procedures, functions, indexes
- Token-efficient design inspired by Anthropic’s MCP patterns
source_id parameter for multi-database routing:
Transport Abstraction
DBHub supports two transport modes for different use cases. Location:src/server.ts:240-253
Stdio Transport (Desktop Tools)
- Default transport for MCP desktop clients
- JSON-RPC over stdin/stdout
- Single persistent connection
- Used by: Claude Desktop, Claude Code, Cursor
HTTP Transport (Network Clients)
POST /mcp
- Stateless mode: New server instance per request
- JSON request/response (no Server-Sent Events)
- Prevents request ID collisions in concurrent scenarios
- Includes workbench UI and REST API
Token-Efficient Schema Exploration
DBHub uses progressive disclosure to minimize token usage when exploring database schemas. Location:src/tools/search-objects.ts
Design Pattern:
- Reduces initial token usage by 10-20x
- Progressive exploration as needed
- Default to minimal information
- Inspired by Anthropic’s MCP code execution patterns
DSN Parsing and Validation
Each connector implements a DSN parser for connection string handling. Location:src/connectors/interface.ts:82-104
Interface:
- PostgreSQL:
postgres://user:password@localhost:5432/dbname?sslmode=require - MySQL:
mysql://user:password@localhost:3306/dbname - SQL Server:
sqlserver://user:password@localhost:1433/dbname?instanceName=ENV1 - SQLite:
sqlite:///path/to/database.dborsqlite:///:memory:
- Password obfuscation in logs (
src/utils/dsn-obfuscate.ts) - SSL/TLS support via query parameters
- Validation before connection attempts
SQL Statement Parsing
DBHub includes a dialect-aware SQL parser for handling comments, strings, and statement splitting. Location:src/utils/sql-parser.ts
Key Functions:
- PostgreSQL: Nested multi-line comments (
/* /* nested */ */), dollar quotes ($$,$tag$) - MySQL/MariaDB: Backtick identifiers (`column`)
- SQLite: Backtick and bracket identifiers (`col`,
[col]) - SQL Server: Bracket identifiers (
[column]) - ANSI SQL: Single/double quotes,
--and/* */comments
Request Tracking and Logging
DBHub tracks all tool requests for debugging and monitoring. Location:src/utils/tool-handler-helpers.ts
Tracked Information:
- Source ID
- Tool name
- SQL statement (or search parameters)
- Execution time
- Success/failure status
- Error messages
Configuration System
DBHub supports multiple configuration methods with a clear priority order. Priority (highest to lowest):- Command-line arguments (
--dsn,--config, etc.) - TOML configuration file (
dbhub.toml) - Environment variables (
DSN,DB_HOST, etc.) .envfiles (.env.localin dev,.envin prod)
src/config/toml-loader.ts):
- Multi-source definitions with unique IDs
- Per-source settings (SSH tunnels, timeouts, SSL)
- Per-tool settings (readonly, max_rows)
- Custom tool definitions
- Path expansion (
~/→ home directory) - Automatic password redaction in logs
Design Patterns
Connector Cloning
Each connector supports cloning for multi-source isolation:Resource Management
Always usetry/finally for database clients:
Error Context
Provide actionable error messages:Performance Considerations
- Connection Pooling: Each connector uses connection pools (pg.Pool, mysql2.Pool, etc.)
- Lazy Connections: Optional deferred connection for unused sources
- Query Timeouts: Prevent runaway queries with configurable timeouts
- Row Limiting: Database-native LIMIT clauses (not application-level filtering)
- Progressive Schema Loading: Fetch metadata only when needed
Security Architecture
- Read-Only Mode: SDK-level enforcement via database session settings
- Keyword Validation: Application-level SQL validation before execution
- SSH Tunneling: Secure connections through bastion hosts
- SSL/TLS: Encryption for database connections
- DSN Obfuscation: Passwords redacted in all logs and error messages
- Parameterized Queries: SQL injection prevention
Testing Architecture
See Testing Guide for complete details. Key Principles:- Unit tests for utilities and parsers
- Integration tests with Testcontainers for real databases
- Shared test base for consistent connector testing
- Pre-commit hooks for fast feedback
Next Steps
- Building Connectors - Add new database support
- Testing Guide - Write and run tests
- Development Overview - Contributing guidelines