
# Multi Database MCP Server
[](https://opensource.org/licenses/MIT)
[](https://goreportcard.com/report/github.com/FreePeak/db-mcp-server)
[](https://pkg.go.dev/github.com/FreePeak/db-mcp-server)
[](https://github.com/FreePeak/db-mcp-server/graphs/contributors)
A powerful multi-database server implementing the Model Context Protocol (MCP) to provide AI assistants with structured access to databases.
## Overview
The DB MCP Server provides a standardized way for AI models to interact with multiple databases simultaneously. Built on the [FreePeak/cortex](https://github.com/FreePeak/cortex) framework, it enables AI assistants to execute SQL queries, manage transactions, explore schemas, and analyze performance across different database systems through a unified interface.
## Core Concepts
### Multi-Database Support
Unlike traditional database connectors, DB MCP Server can connect to and interact with multiple databases concurrently:
```json
{
"connections": [
{
"id": "mysql1",
"type": "mysql",
"host": "localhost",
"port": 3306,
"name": "db1",
"user": "user1",
"password": "password1"
},
{
"id": "postgres1",
"type": "postgres",
"host": "localhost",
"port": 5432,
"name": "db2",
"user": "user2",
"password": "password2"
},
{
"id": "oracle1",
"type": "oracle",
"host": "localhost",
"port": 1521,
"service_name": "XEPDB1",
"user": "user3",
"password": "password3"
}
]
}
```
### Dynamic Tool Generation
For each connected database, the server automatically generates specialized tools:
```go
// For a database with ID "mysql1", these tools are generated:
query_mysql1 // Execute SQL queries
execute_mysql1 // Run data modification statements
transaction_mysql1 // Manage transactions
schema_mysql1 // Explore database schema
performance_mysql1 // Analyze query performance
```
### Clean Architecture
The server follows Clean Architecture principles with these layers:
1. **Domain Layer**: Core business entities and interfaces
2. **Repository Layer**: Data access implementations
3. **Use Case Layer**: Application business logic
4. **Delivery Layer**: External interfaces (MCP tools)
## Features
- **Simultaneous Multi-Database Support**: Connect to multiple MySQL, PostgreSQL, SQLite, and Oracle databases concurrently
- **Lazy Loading Mode**: Defer connection establishment until first use - perfect for setups with 10+ databases (enable with `--lazy-loading` flag)
- **Database-Specific Tool Generation**: Auto-creates specialized tools for each connected database
- **Clean Architecture**: Modular design with clear separation of concerns
- **OpenAI Agents SDK Compatibility**: Full compatibility for seamless AI assistant integration
- **Dynamic Database Tools**: Execute queries, run statements, manage transactions, explore schemas, analyze performance
- **Unified Interface**: Consistent interaction patterns across different database types
- **Connection Management**: Simple configuration for multiple database connections
- **Health Check**: Automatic validation of database connectivity on startup
- **Production Guardrails**: Per-database `read_only` checks (best-effort, applied to both `query_*` and `execute_*` tools; use least-privilege database users for a hard guarantee), `max_rows` result truncation with explicit notices, and per-query timeouts
### Production Guardrails
Protect agent sessions against runaway queries and accidental writes:
| Setting | Scope | Effect |
|---------|-------|--------|
| `"read_only": true` | per database | Best-effort defense in depth, not a security boundary. A textual check runs for both query and execute tools and rejects statements it does not recognize. Functions called from a `SELECT` may not be recognized, so the check can miss a write. Engine session defaults are a second layer, not a security boundary on their own: PostgreSQL/TimescaleDB sessions start with `default_transaction_read_only=on`, MySQL with `transaction_read_only=1`, and SQLite opens `mode=ro`. Oracle has no session-level read-only switch; the connector refuses to connect with credentials that hold write privileges. For strong guarantees, connect with a database account that only has SELECT privileges. On MySQL, the account must also lack the `FILE` privilege, which grants server-side file access. |
| `"max_rows": 1000` | per database | Truncates result sets at N rows and appends an explicit `Truncated: showing first N rows (max_rows=N)` notice so the model knows to refine its query instead of losing context. `0` (default) means unlimited. `LIMIT max_rows+1` is added where the statement can be rewritten (PostgreSQL/TimescaleDB, MySQL, SQLite), so the database stops at the cap; otherwise the result is truncated after N rows. Select-list functions with side effects (for example `nextval()`) run for at most max_rows+1 rows. |
| `"masking_rules": [...]` | per database | Masks values of result columns whose **name** matches a rule's regex before they leave the server — applies to every query shape including `SELECT *`. Strategies: `"fixed_string"` (replace with `value`), `"null"`, and `"partial"` (`keep_last` trailing characters visible; shorter values fully masked). First matching rule wins; invalid patterns or unknown strategies abort config load (fail closed); masked-cell counts are reported in the result footer. `masking_rules` match the result column name returned by the database; `mask_pii` also detects common PII formats in values. See [docs/design/column-masking-scoping.md](docs/design/column-masking-scoping.md). |
| `"mask_pii": true` | per database | Redacts PII in query results by **content shape**, not just column name: emails, phone numbers, Luhn-valid card numbers, SSNs, IPv4 addresses and 19+ digit identifiers are replaced with `[EMAIL]`/`[PHONE]`/`[CREDIT_CARD]`/`[SSN]`/`[IP_ADDRESS]`/`[LONG_NUMBER]` when they appear as a whole pattern inside a single cell, including free-text columns. Best-effort: values split across columns, non-standard formats, and names or addresses are not detected, and masking runs after the database has returned the data. Columns named like `email`/`card_number`/`iban` are redacted whole. Operator-controlled: once set, an agent **cannot** turn it off (the per-query `mask_pii` parameter is additive only). Composes with `masking_rules`. |
| `"query_timeout": 30` | per database | Cancels statements that exceed the timeout in seconds; enforced at the repository layer for every tool (queries, statements, transactions, explain, schema inspection). Unset defaults to 30s; `-1` disables. Env-only deployments can set `QUERY_TIMEOUT_SECONDS` to fill connections without an explicit value (JSON keeps precedence). |
| `"max_query_cost": 50000` | per database | Denies a `SELECT` or `WITH` through the query tool when its `EXPLAIN` planner-cost estimate is above the limit. Explain with `analyze=true` is estimated first and refused above the limit. PostgreSQL, TimescaleDB and MySQL only; startup fails on other engines and on a negative value. An estimate that cannot be obtained or read denies the query. `0` (default) means off. A caller limit from an agent key or OIDC role can lower it further. See [docs/governance.md](docs/governance.md#cost-limit-max_query_cost). |
| `DB_MCP_API_KEY` or `DB_MCP_API_KEY_FILE` | process | Shared Bearer key for Streamable HTTP. Set exactly one source (flag, env or file); Streamable HTTP refuses to start without authentication. Calls with this key use the principal `api-key`. The key file is read once at startup. |
| `DB_MCP_OIDC_ISSUER` + `DB_MCP_OIDC_AUDIENCE` | process | OIDC bearer tokens on Streamable HTTP: discovery at startup, signature, issuer and audience checks, and the `sub` claim as the principal. When set, OIDC replaces the shared key. |
| `DB_MCP_API_SCOPES` | process | Scopes granted to the shared key (default `db:read`) and required on every request under OIDC, except that a roles file supplies each token's scopes instead. Each tool call also needs its own scope: `db:read`, `db:write` or `db:admin`. See [Tool scopes](#tool-scopes). |
| `DB_MCP_AGENT_KEYS_FILE` | process | Per-agent keys: each agent gets a digest, an `id` (its audit principal), scopes and a database allowlist. Streamable HTTP only; cannot be combined with OIDC. Every agent key, `"*"` included, uses the unified tools only, so the server needs `-unified-tools`. |
| `DB_MCP_OIDC_ROLES_FILE` | process | Maps one token claim to a grant (scopes, databases, optional `max_query_cost`). The first matching role in file order applies; a token that matches no role is denied everything. Requires `DB_MCP_OIDC_ISSUER` and `-unified-tools`. |
| `DB_MCP_RESOURCE_URL` | process | Serves RFC 9728 protected resource metadata at `/.well-known/oauth-protected-resource` and adds a `WWW-Authenticate` challenge to `/mcp` 401 and 403 responses. Requires `DB_MCP_OIDC_ISSUER`. |
| `DB_MCP_AUDIT_LOG=/path/audit.jsonl` | process | Appends one JSONL record per executed statement — timestamp, op (`query`/`execute`/`tx_*`), database, statement (capped at 10,000 bytes), duration, error. Includes rejected attempts against read-only databases. Best-effort writes never fail a query; file is created with `0600`. Also records calls refused by a tool scope or by an agent key's database allowlist (`op: "denied"`, Streamable HTTP only) and the `tool` field; `DB_MCP_AUDIT_REQUIRED=true` makes startup fail unless the log opens, and `DB_MCP_AUDIT_PRINCIPAL` labels records that have no principal (stdio). |
Each record also says **who** ran the statement and **how much** it touched. These fields are additive and omitted when unknown, so existing consumers keep working:
- `principal`: the authenticated caller. For OIDC it is the token subject (`sub`); for the static API key it is `api-key`; for a per-agent key it is the key's `id`. Omitted for stdio and other unauthenticated transports, unless `DB_MCP_AUDIT_PRINCIPAL` labels them.
- `session`: the MCP session ID, when the transport has one (Streamable HTTP). It is written to the owner-only (`0600`) audit file. Omitted otherwise.
- `rows`: the number of rows shown for a query, capped at `max_rows` when the result is truncated (a query matching 100 rows with `max_rows=3` records `rows: 3`); rows affected for an execute; rows affected for a transaction execute, counted before commit, so a later rollback does not change the recorded count. Omitted when the statement failed or the engine did not report a count.
- `tool`: the MCP tool name of the call, such as `query` or `execute`. Written for calls that come through Streamable HTTP; stdio and SSE calls do not carry it.
- `op: "denied"`: a call refused by a tool scope, or by an agent key's database allowlist, before it reached the database. `error` holds the reason and `rows` is omitted. Written only for Streamable HTTP.
Example line (placeholder values):
```json
{"ts":"2026-11-18T10:15:30.123456789Z","op":"query","database":"app","statement":"SELECT id FROM orders LIMIT 5","duration_ms":1.234,"principal":"user@example.com","session":"mcp-session-example","rows":5}
```
> **Defense in depth**: read-only is best-effort and is not a guarantee. The layers are the application check, engine session defaults (not a security boundary on their own), and the database user's privileges. For strong guarantees, connect with a database account that only has SELECT privileges.
The production controls guide, with the agent keys file format, the authorization rules and a
worked pilot example, is in [docs/governance.md](docs/governance.md).
## Supported Databases
| Database | Status | Features |
| ---------- | ------------------------- | ------------------------------------------------------------ |
| MySQL | ✅ Full Support | Queries, Transactions, Schema Analysis, Performance Insights |
| PostgreSQL | ✅ Full Support (v9.6-17) | Queries, Transactions, Schema Analysis, Performance Insights |
| SQLite | ✅ Full Support | File-based & In-memory databases, SQLCipher encryption support |
| Oracle | ✅ Full Support (10g-23c) | Queries, Transactions, Schema Analysis, RAC, Cloud Wallet, TNS |
| TimescaleDB| ✅ Full Support | Time-Series Queries, Hypertable Discovery (write policies via SQL) |
## Deployment and transport status
The safest local integration is **STDIO**. HTTP transports are still under hardening; do not expose the current server directly to a shared network.
### Personal/local STDIO (recommended)
```bash
# Build from the audited source revision
make build
# Use a private, single-connection config
./bin/server -t stdio -c /absolute/path/to/config.local.json
```
For Cursor, point the client at the actual build output and use absolute paths:
```json
{
"mcpServers": {
"local-db": {
"command": "/absolute/path/to/db-mcp-server/bin/server",
"args": ["-t", "stdio", "-c", "/absolute/path/to/config.local.json"]
}
}
}
```
Use a read-only database account and a bounded `query_timeout` for a personal
PostgreSQL/MySQL connection. For SQLite, use an absolute `database_path` and
`"read_only": true` when the agent only needs to inspect data.
### Legacy SSE (compatibility only)
The historical Cortex SSE transport has no built-in authentication. It is
**disabled by default** and must only be enabled explicitly behind a trusted
private reverse proxy:
```bash
./bin/server -t sse -h 127.0.0.1 -p 9092 \
-allow-insecure-sse -c /absolute/path/to/config.local.json
```
Do not use this mode for a shared deployment. The legacy endpoint does not
apply the API key (`DB_MCP_API_KEY`, `DB_MCP_API_KEY_FILE`, or `-api-key`);
terminate TLS, authentication, and network policy at the proxy. A future release will replace it with a maintained Streamable HTTP
implementation.
### Streamable HTTP (experimental)
The `streamable` endpoint is backed by the maintained Go MCP SDK and supports
stateful sessions, JSON or SSE responses, notifications, GET/DELETE session
lifecycle, and JSON-RPC dispatch. The process refuses to start it without
an API key; keep it behind a private TLS gateway until the identity and
conformance rollout is complete.
Provide the key through exactly one source: `DB_MCP_API_KEY`, `DB_MCP_API_KEY_FILE`,
or the `-api-key` flag. Setting more than one is a startup error. The flag is
visible in the process list, so it logs a warning; prefer the file or env var.
Use the file form with Docker or Kubernetes secrets:
```bash
# Docker secret mounted at /run/secrets/db_mcp_api_key
docker run --rm -p 127.0.0.1:9092:9092 \
-e TRANSPORT_MODE=streamable \
-e DB_MCP_API_KEY_FILE=/run/secrets/db_mcp_api_key \
-v "$(pwd)/config.local.json:/app/config.json:ro" \
-v "$(pwd)/db_mcp_api_key:/run/secrets/db_mcp_api_key:ro" \
db-mcp-server:local
```
The key file is read once at startup. A rotated Kubernetes or Docker secret takes
effect only after the server restarts. The key is not read for the stdio or SSE
transports, so a blank key or a missing key file does not stop them.
For browser-origin requests, set an explicit comma-separated allowlist:
```bash
MCP_ALLOWED_ORIGINS=https://agent.example.com
```
The SDK applies these request rules to the `streamable` endpoint:
- When the server listens on a loopback address (the default `-h 127.0.0.1`),
a request whose `Host` header is not a loopback name is rejected with `403`.
- Each `MCP_ALLOWED_ORIGINS` entry must be `scheme://host[:port]`, with no
path, query, fragment, or trailing slash. Invalid entries are logged and
ignored, so browser requests from that origin still get `403`.
- A JSON `Content-Type` may carry parameters, such as
`application/json; charset=utf-8`.
The built-in static bearer key is a bounded pilot mechanism. It grants
`db:read` by default; set `DB_MCP_API_SCOPES=db:read,db:write` only for a
trusted write client. `db:admin` is reserved for controlled administration.
Set `DB_MCP_OIDC_ISSUER` and `DB_MCP_OIDC_AUDIENCE` to use OIDC discovery,
JWKS signature validation, issuer/audience checks, and subject identity for
shared deployments; database-specific scopes are still intentionally not
enabled until that policy is defined.
#### Tool scopes
The scope a call needs is decided by the statement or operation it runs, not
by the tool name alone:
| Tool | `db:read` | `db:write` |
|------|-----------|------------|
| `query`, `query_