CLAUDE.md · bytebase/dbhub
CLAUDE.md from bytebase/dbhub: 223 lines covering Commands, Architecture Overview, Configuration, Database Connectors and more.
Template by bytebase
Install
Works with Claude Code. Read the repository before you give any tool access to your data.
curl -fsSL https://raw.githubusercontent.com/bytebase/dbhub/main/CLAUDE.md -o CLAUDE.md
Read it and adapt it to your project before use.
Get the weekly diff
The weekly diff: one email a week with new agent tools, notable updates and grade changes, plus security alerts for tools you follow. Double opt-in, one-click unsubscribe.
About
Use cases: prompt-engineering
Reviews
Write a reviewNo reviews yet. Installed it? Reviews come from verified installers only. How reviews work
What's in it
A CLAUDE.md file: project memory Claude Code loads at the start of every session.
- For
- Claude Code
- Length
- 223 lines
- File
CLAUDE.md
Sections
- Commands
- Architecture Overview
- Configuration
- Database Connectors
- Testing Approach
- SSH Tunnel Support
- Code Style
First lines (shown under the repo's MIT license)
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
# DBHub Development Guidelines
DBHub is a zero-dependency, token efficient database MCP server implementing the Model Context Protocol (MCP) server interface. This lightweight server bridges MCP-compatible clients (Claude Desktop, Claude Code, Cursor) with various database systems.
## Commands
- Build: `pnpm run build` - Compiles TypeScript to JavaScript using tsup
- Start: `pnpm run start` - Runs the compiled server
- Dev: `pnpm run dev` - Runs server with tsx (no compilation needed)
- Test: `pnpm test` - Run all tests
- Test Watch: `pnpm test:watch` - Run tests in watch mode
- Integration Tests: `pnpm test:integration` - Run database integration tests (requires Docker)
- Claude Code Plugin: `plugin/` packages DBHub as a Claude Code plugin — `.mcp.json` launches `npx @bytebase/dbhub` (pinned to the plugin version) against the bundled read-only `plugin/dbhub.toml` (DSN prompted via `userConfig` in `plugin/.claude-plugin/plugin.json`, passed as `DBHUB_DSN`), plus `/dbhub:setup` and `/dbhub:explore` skills. Validate with `claude plugin validate ./plugin`; test with `claude --plugin-dir ./plugin`.
- Versioning: `package.json` is the single source of truth. `pnpm version <bump>` bumps it and auto-runs `scripts/sync-version.mjs`, which propagates the version into `plugin/.claude-plugin/plugin.json`, `plugin/.mcp.json`, and `server.json` (files that can't be stamped at build time — the plugin is read straight from git with no build step, and `server.json`'s own version is what the npm publish workflow (`.github/workflows/npm-publish.yml`) checks against the MCP Registry before republishing — the registry publish runs as a post-step of that same workflow, after the npm publish succeeds). `mcpb/manifest.json` needs no sync — `scripts/build-mcpb.mjs` stamps it from `package.json` at build time. `src/__tests__/plugin-consistency.test.ts` fails CI if any of these drift from `package.json`, or if `plugin/dbhub.toml` diverges from `mcpb/dbhub.toml`.
- MCP Bundle: `pnpm run build:mcpb` - Package DBHub as an `.mcpb` bundle for MCPB-compatible clients (Claude Desktop, Claude Code, MCP for Windows; see `mcpb/` and `scripts/build-mcpb.mjs`); `pnpm run test:mcpb` smoke-tests the packed bundle over stdio. Published to GitHub releases by `.github/workflows/mcpb-release.yml`. The bundle is read-only by design (`mcpb/dbhub.toml`), with the DSN supplied via the `DBHUB_DSN` env var declared in `mcpb/manifest.json` (TOML `${ENV_VAR}` interpolation).
## Architecture Overview
The codebase follows a modular architecture centered around the MCP protocol:
```
src/
├── connectors/ # Database-specific implementations
│ ├── postgres/ # PostgreSQL connector
│ ├── mysql/ # MySQL connector
│ ├── mariadb/ # MariaDB connector
│ ├── sqlserver/ # SQL Server connector
│ ├── oracle/ # Oracle connector (node-oracledb Thin mode, no Instant Client)
│ └── sqlite/ # SQLite connector
├── tools/ # MCP tool handlers
│ ├── execute-sql.ts # SQL execution handler
│ ├── search-objects.ts # Unified search/list with progressive disclosure
│ ├── explain-sql.ts # Opt-in EXPLAIN plan tool (never executes the target statement)
│ └── health-check.ts # Opt-in connection pool + buffer cache metrics tool (Postgres/MySQL/MariaDB/SQL Server/Oracle)
├── utils/ # Shared utilities
│ ├── dsn-obfuscator.ts# DSN security
│ ├── response-formatter.ts # Output formatting
│ ├── allowed-keywords.ts # Read-only SQL classification primitives
│ └── sql-access-policy.ts # Statement class → verdict pipeline (single source of readonly semantics)
└── index.ts # Entry point with transport handling
```
Key architectural patterns:
- **Connector Registry**: Dynamic registration system for database connectors
- **Connector Manager**: Manages database connections (single or multiple)
- Supports multi-database configuration via TOML
- Maintains `Map<id, Connector>` for named connections
- `getConnector(sourceId?)` returns connector by ID or default (first)
- `getCurrentConnector(sourceId?)` static method for tool handlers
- Backward compatible with single-connection mode
- Location: `src/connectors/manager.ts`
- **Transport Abstraction**: Support for both stdio (desktop tools) and HTTP (network clients)
- HTTP transport endpoint: `/mcp` (aligns with official MCP SDK standard)
- Implemented in `src/server.ts` using `createMcpHandler` (MCP SDK v2), which serves both protocol eras from one factory: the stateless 2026-07-28 revision natively, and 2025-era clients via the default `legacy: 'stateless'` fallback (fresh server per request, spec-standard SSE-framed responses; GET/DELETE on the legacy path return 405)
- stdio uses `serveStdio` from `@modelcontextprotocol/server/stdio` (era pinned per connection)
- 2026-07-28 clients get cache hints on `tools/list` (`cacheHints` in `ServerOptions`: 5-minute TTL, `private` scope) and send `Mcp-Method`/`Mcp-Name` headers usable for gateway routing/rate-limiting
- Tests in `src/__tests__/json-rpc-integration.test.ts`
- **Tool Handlers**: Clean separation of MCP protocol concerns
- Multi-database routing is by tool name, not by parameter: one tool instance is registered per source, named `execute_sql_{source_id}` / `search_objects_{source_id}` (single-source configs keep the bare `execute_sql` / `search_objects` names). See `src/tools/index.ts` and `src/utils/tool-metadata.ts`. `source_id` appears in tool *output* metadata only.
- **Token-Efficient Schema Exploration**: Unified search/list tool with progressive disclosure
- `search_objects`: Single tool for both pattern-based search and listing all objects
- Pattern parameter defaults to `%` (match all) - optional for listing use cases
- Detail levels: `names` (minimal), `summary` (with metadata), `full` (complete structure)
- Supports: schemas, tables, columns, procedures, indexes
- Inspired by Anthropic's MCP code execution patterns for reducing token usage
- **Integration Test Base**: Shared test utilities for consistent connector testing
## Configuration
DBHub supports three configuration methods:
### 1. TOML Configuration File (Multi-Database)
**Recommended for projects requiring multiple database connections**
- Load with `--config=path/to/config.toml` (see `resolveTomlConfigPath` in `src/config/toml-loader.ts`)
- Configuration structure:
- `[[sources]]` - Database connection definitions with unique `id` fields
- `[[tools]]` - Tool configuration (execution settings, custom tools)
- Example:
```toml
[[sources]]
id = "prod_pg"
dsn = "postgres://user:pass@localhost:5432/production"
connection_timeout = 60
query_timeout = 30
[[sources]]
id = "staging_mysql"
type = "mysql"
host = "localhost"
database = "staging"
user = "root"
password = "secret"
# Tool configuration (readonly, max_rows are tool-level settings)
[[tools]]
name = "execute_sql"
source = "prod_pg"
readonly = true
max_rows = 1000
```
- Key files:
- `src/types/config.ts`: TypeScript interfaces for TOML structure
- `src/config/toml-loader.ts`: TOML parsing and validation
- `src/config/__tests__/toml-loader.test.ts`: Comprehensive test suite
- Features:
- Per-source settings: SSH tunnels, timeouts, SSL configuration
- Per-tool settings: `readonly`, `max_rows` (configured in `[[tools]]` section, not `[[sources]]`)
- Custom tools: Define reusable, parameterized SQL operations
- Path expansion for `~/` in file paths
- Automatic password redaction in logs
- First source is the default database
- Usage in MCP tools: each source gets its own tool, suffixed with the normalized source id (e.g. `execute_sql_prod_pg(sql)`, `search_objects_staging_mysql(...)`)
- See `dbhub.toml.example` for complete configuration reference
- Documentation: https://dbhub.ai/config/toml
### 2. Environment Variables (Single Database)
- Copy `.env.example` to `.env` and configure for your database connection
- Two ways to configure:
- Set `DSN` to a full connection string (recommended)
- Set individual parameters: `DB_TYPE`, `DB_HOST`, `DB_PORT`, `DB_USER`, `DB_PASSWORD`, `DB_NAME`
- SSH tunnel via environment: `SSH_HOST`, `SSH_PORT`, `SSH_USER`, `SSH_PASSWORD`, `SSH_KEY`, `SSH_PASSPHRASE`
### 3. Command-Line Arguments
- `--dsn`: Database connection string (single database; cannot be combined with TOML config)
- `--transport`: `stdio` (default) or `http` for streamable HTTP transport (endpoint: `/mcp`)
- `--port`: HTTP server port (default: 8080)
- `--host`: HTTP bind host (default: `0.0.0.0`; env `DBHUB_HOST`)
- `--allowed-hosts`: Comma-separated extra hostnames accepted in the HTTP `Host`/`Origin` headers, for DNS-rebinding protection (env `DBHUB_ALLOWED_HOSTS`). Loopback is always allowed; on a wildcard bind (`0.0.0.0`/`::`) this machine's hostname and IPs are auto-allowed so local/by-IP access needs no config. Set the flag for other names (e.g. a reverse-proxy/public DNS name); use `*` to disable the check when fronted by your own auth/proxy. See `buildAllowedHosts`/`getSelfHosts` in `src/utils/cross-origin.ts`.
- `--auth-token`: Comma-separated bearer token(s) required on every HTTP request via `Authorization: Bearer <token>` (env `DBHUB_AUTH_TOKEN`). Unset by default (no auth); configuring a token is itself the opt-in — there is no separate enforcement flag. A comma-separated list supports zero-downtime rotation (add the new token, redeploy, drop the old one) and per-client tokens. `/healthz` is exempt. Not OAuth — a flat shared-secret allow-list, not full identity-based authorization; see `validateAuthToken` in `src/utils/auth-token.ts`.
- `--config`: Path to TOML configuration file
- `--demo`: Use bundled SQLite employee database
- `--readonly`: Restrict to read-only SQL operations (deprecated - use TOML configuration instead)
- `--max-rows`: Limit rows returned from SELECT queries (deprecated - use TOML configuration instead)
- SSH tunnel options: `--ssh-host`, `--ssh-port`, `--ssh-user`, `--ssh-password`, `--ssh-key`, `--ssh-passphrase`, `--ssh-agent`
- Documentation: https://dbhub.ai/config/command-line
### Configuration Priority Order
**Database sources** come from either a TOML file (`--config`) or a DSN. TOML defines
sources for one or more databases; a DSN configures exactly one, so `--config` and
`--dsn` together throw — see `resolveSourceConfigs` in `src/config/env.ts`.
The guard is deliberately limited to the `--dsn` flag. `DSN` and `DB_*` environment
variables (exported or from `.env`) are left alone because TOML `${VAR}` interpolation
reads them: `dsn = "${DSN}"` is a supported way to keep credentials out of the file.
Without `--config`, the DSN is resolved in this order:
1. `--dsn` command-line argument
2. `DSN` environment variable
3. Individual `DB_*` environment variables
4. `.env` files (`.env.local` in development, `.env` in production)
**All other settings** (`--transport`, `--port`, `--host`, `--allowed-hosts`, …) live
outside TOML and follow the same order:
1. Command-line argumentsSignals
- Stars
- 3,716
- Forks
- 323
- Open issues
- 2
- Contributors
- 41
- Last commit (this folder)
- Oct 9, 2026 (20 days ago)
- Last release
- Oct 9, 2026 (20 days ago)
From GitHub (fetched Oct 24, 2026).
Details
- License
- MIT
- Repository
- github.com/bytebase/dbhub
- First seen
- Oct 24, 2026
- Last checked
- Oct 24, 2026
- Source
- GitHubgithub-graphql
More from bytebase
Cite this page
CLAUDE.md · bytebase/dbhub. Agent Mart. https://agentmart.dev/templates/bytebase-dbhub-claude-md (last updated 2026-10-24)