接入你的智能体
從發布者安裝。不是 PlugMCP 端點。
遠端 URL 還是本機指令? 兩種安裝方式的差異
The DB MCP Server provides a standardized way for AI models to interact with multiple databases simultaneously. Built on the 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.
Unlike traditional database connectors, DB MCP Server can connect to and interact with multiple databases concurrently:
{
"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"
}
]
}
For each connected database, the server automatically generates specialized tools:
// 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
The server follows Clean Architecture principles with these layers:
--lazy-loading flag)read_only enforcement (blocks writes through both query_* and execute_* tools), max_rows result truncation with explicit notices, and per-query timeoutsProtect agent sessions against runaway queries and accidental writes:
| DB_MCP_AUDIT_LOG=/path/audit.jsonl | process | Appends one JSONL record per executed statement — timestamp, op (query/execute/tx_*), database, statement (capped at 10k chars), duration, error. Includes rejected attempts against read-only databases. Best-effort writes never fail a query; file is created with 0600. |
Defense in depth: read-only is enforced in three layers — application classifier, engine session defaults, and (recommended) least-privilege database users. Oracle currently relies on the classifier plus user privileges.
The safest local integration is STDIO. HTTP transports are still under hardening; do not expose the current server directly to a shared network.
# 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:
{
"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.
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:
./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 DB_MCP_API_KEY; terminate TLS, authentication, and network policy at the
proxy. A future release will replace it with a maintained Streamable HTTP
implementation.
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
DB_MCP_API_KEY; keep it behind a private TLS gateway until the identity and
conformance rollout is complete.
For browser-origin requests, set an explicit comma-separated allowlist:
MCP_ALLOWED_ORIGINS=https://agent.example.com
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.
The published image is a development/demo artifact, not an enterprise
hardening recommendation. The current Dockerfile runs as an unprivileged
user, omits an embedded config, and includes the legacy
-allow-insecure-sse behavior for local Compose compatibility. It exposes a
separate health port (9093) and is not suitable for public publication.
# Build a local image from this source revision
docker build -t db-mcp-server:local .
# Keep it private; the image's default SSE mode is compatibility-only
docker run --rm -p 127.0.0.1:9092:9092 \
-p 127.0.0.1:9093:9093 \
-v "$(pwd)/config.local.json:/app/config.json:ro" \
db-mcp-server:local
For a team deployment, wait for the authenticated Streamable transport and use a non-root, read-only-filesystem image with a private network, external secret store, and a TLS/OIDC gateway.
# Clone the repository
git clone https://github.com/FreePeak/db-mcp-server.git
cd db-mcp-server
# Build the server
make build
# Run the server
./bin/server -t stdio -c config.json
Create a config.json file with your database connections. schema_version: 1
enables strict unknown-field validation:
{
"schema_version": 1,
"connections": [
{
"id": "mysql1",
"type": "mysql",
"host": "mysql1",
"port": 3306,
"name": "db1",
"user": "user1",
"password_env": "DB_MCP_MYSQL_PASSWORD",
"query_timeout": 60,
"max_open_conns": 20,
"max_idle_conns": 5,
"conn_max_lifetime_seconds": 300,
"conn_max_idle_time_seconds": 60,
"read_only": false,
"max_rows": 1000,
"masking_rules": [
{ "pattern": "(?i)email", "strategy": "fixed_string", "value": "***MASKED***" },
{ "pattern": "(?i)(ssn|tax_id)", "strategy": "null" }
]
},
{
"id": "postgres1",
"type": "postgres",
"host": "postgres1",
"port": 5432,
"name": "db1",
"user": "user1",
"password_env": "DB_MCP_POSTGRES_PASSWORD"
},
{
"id": "sqlite_app",
"type": "sqlite",
"database_path": "./data/app.db",
"journal_mode": "WAL",
"cache_size": 2000,
"read_only": false,
"use_modernc_driver": true,
"query_timeout": 30,
"max_open_conns": 1,
"max_idle_conns": 1
},
{
"id": "sqlite_encrypted",
"type": "sqlite",
"database_path": "./data/secure.db",
"encryption_key": "your-secret-key-here",
"journal_mode": "WAL",
"use_modernc_driver": false
},
{
"id": "sqlite_memory",
"type": "sqlite",
"database_path": ":memory:",
"cache_size": 1000,
"use_modernc_driver": true
}
]
}
Do not put production credentials directly in JSON. Use either an environment variable name or a mounted secret file per connection:
{
"id": "prod",
"type": "postgres",
"host": "db.internal",
"port": 5432,
"name": "app",
"user": "mcp_reader",
"password_env": "DB_MCP_PROD_PASSWORD"
}
password_file and encryption_key_env/encryption_key_file are also
supported. Relative file paths resolve from the config file directory; an
inline value cannot be combined with a reference. The resolved value stays in
process memory and is not printed by the config loader.
# Basic syntax
./bin/server -t <transport> -c <config-file>
# HTTP transport options (legacy SSE requires an explicit opt-in)
./bin/server -t sse -h <hostname> -p <port> -allow-insecure-sse -c <config-file>
# Lazy loading mode (recommended for 10+ databases)
./bin/server -t stdio -c <config-file> --lazy-loading
# Customize log directory (useful for multi-project setups)
./bin/server -t stdio -c <config-file> -log-dir /tmp/db-mcp-logs
# Inline database configuration
./bin/server -t stdio -db-config '{"connections":[...]}'
# Environment variable configuration
export DB_CONFIG='{"connections":[...]}'
./bin/server -t stdio
# Print the build version
./bin/server --version
# Upgrade to the latest published release (verifies SHA-256, swaps the binary)
./bin/server update
./bin/server update -check # only report whether a newer release exists
./bin/server update -version 1.13.0 # install a specific release
Available Flags:
-t, -transport: Transport mode (stdio, legacy sse, or experimental streamable)-c, -config: Path to database configuration file-p, -port: HTTP port (default: 9092)-h, -host: HTTP bind host (default: 127.0.0.1)--version: Print the build version and exit-allow-insecure-sse: Explicitly allow legacy SSE for a private development proxy-api-key: Bearer key for the experimental Streamable HTTP entrypoint (or use DB_MCP_API_KEY)-log-level: Log level (debug, info, warn, error)-log-dir: Directory for log files (default: ./logs in current directory)-db-config: Inline JSON database configuration-lazy-loading: Establish connections on first use-unified-tools: Register one tool set with a database parameterUpdating: db-mcp-server update resolves the latest GitHub release, checks
the download against the release's SHA256SUMS manifest, and replaces the
running binary in place (the previous binary is left untouched if verification
fails). It installs the asset matching your OS and architecture — restart the
server afterwards. On Windows a running executable cannot be replaced, so update
through the npm installer there. -check reports without downloading; -force
reinstalls the current version.
Values in a .env file are loaded first; real environment variables take precedence. A JSON config file (CONFIG_PATH/DB_CONFIG_FILE) takes precedence over inline and legacy database variables.
When using SQLite databases, you can leverage these additional configuration options:
{
"id": "my_sqlite_db",
"type": "sqlite",
"database_path": "./data/myapp.db",
"journal_mode": "WAL",
"cache_size": 2000
}
{
"id": "encrypted_db",
"type": "sqlite",
"database_path": "./data/secure.db",
"encryption_key": "your-secret-encryption-key",
"use_modernc_driver": false
}
{
"id": "memory_db",
"type": "sqlite",
"database_path": ":memory:",
"cache_size": 1000
}
{
"id": "reference_data",
"type": "sqlite",
"database_path": "./data/reference.db",
"read_only": true,
"journal_mode": "DELETE"
}
When using Oracle databases, you can leverage these additional configuration options:
{
"id": "oracle_dev",
"type": "oracle",
"host": "localhost",
"port": 1521,
"service_name": "XEPDB1",
"user": "testuser",
"password": "testpass",
"max_open_conns": 50,
"max_idle_conns": 10,
"conn_max_lifetime_seconds": 1800
}
{
"id": "oracle_legacy",
"type": "oracle",
"host": "oracledb.company.com",
"port": 1521,
"sid": "ORCL",
"user": "app_user",
"password": "app_password"
}
{
"id": "oracle_cloud",
"type": "oracle",
"user": "ADMIN",
"password": "your-cloud-password",
"wallet_location": "/path/to/wallet_DBNAME",
"service_name": "dbname_high"
}
{
"id": "oracle_rac",
"type": "oracle",
"host": "scan.company.com",
"port": 1521,
"service_name": "production",
"user": "app_user",
"password": "app_password",
"max_open_conns": 100,
"max_idle_conns": 20
}
{
"id": "oracle_tns",
"type": "oracle",
"tns_admin": "/opt/oracle/network/admin",
"tns_entry": "PROD_DB",
"user": "app_user",
"password": "app_password"
}
{
"id": "oracle_ebr",
"type": "oracle",
"host": "oracledb.company.com",
"port": 1521,
"service_name": "production",
"user": "app_user",
"password": "app_password",
"edition": "v2_0"
}
When multiple connection methods are configured, the following priority is used:
tns_entry and tns_admin are configured)wallet_location is configured) - for Oracle CloudFor each connected database, DB MCP Server automatically generates these specialized tools:
For PostgreSQL databases with the timescaledb extension installed, these additional
specialized tools are registered automatically at startup (registration is config-driven,
so it also works under --lazy-loading; each handler verifies the extension at call time
and returns an actionable error when it is absent):
In unified mode the same seven tools appear once as timescaledb_timeseries_query,
timescaledb_analyze_timeseries, timescaledb_list_hypertables,
timescaledb_compression_settings, timescaledb_retention_policy,
timescaledb_list_continuous_aggregates, and timescaledb_continuous_aggregate_info,
each taking a required database parameter.
Scope note: read-only discovery above goes through the query pipeline and therefore stays usable on
read_onlydatabases; each handler checks for thetimescaledbextension first. Write-policy operations (hypertable creation, compression toggles, add/remove retention or refresh policies) remain unexposed — use plain SQL through the query/execute tools in the meantime. For detailed documentation, see TIMESCALEDB_TOOLS.md.
If you connect many databases (5+), the per-database tool naming generates a large number of tools (5 × N). Some MCP clients — Claude in particular — apply strict limits on the total number of tools and tool description size that can cause the agent to fail to load the server, ignore tools, or refuse to call them. Issue #18 documents this exact symptom: "the db-mcp-server does not function properly with Claude, even though it works fine with OpenAI".
For these clients, launch the server with the --unified-tools flag to register six consolidated tools (query, execute, transaction, performance, explain, describe, schema, filter_tables) instead of per-database tools:
./bin/server -t stdio -c config.json --unified-tools
Context-window cost (measured, TestToolTokenBenchmark, re-verified 2026-08 via scripts/token-benchmark.sh): unified mode costs ~1.25–1.6k tokens regardless of how many databases are connected, while per-database mode costs ~800 tokens per database (7 tools each) — 10 connected databases ≈ 8k tokens, an 80% wire-payload saving with unified. With one database only, per-database naming is slightly cheaper; unified wins from two databases onward and scales flat thereafter. Re-measure the real wire payload yourself with scripts/token-benchmark.sh; methodology and results in docs/benchmark-token-efficiency.md.
In unified mode, each tool accepts a required `database` parameter that names
which database the call should target. See the [Configuration](#configuration)
section for the full list of available databases. This dramatically reduces the
tool count and the cumulative description size, which resolves the Claude
compatibility issues.
For very large configurations, also enable `--lazy-loading` so that startup
doesn't open connections to databases that may never be queried during the
session.
## Examples
### Querying Multiple Databases
```sql
-- Query the MySQL database
query_mysql1("SELECT * FROM users LIMIT 10")
-- Query the PostgreSQL database in the same context
query_postgres1("SELECT * FROM products WHERE price > 100")
-- Query the SQLite database
query_sqlite_app("SELECT * FROM local_data WHERE created_at > datetime('now', '-1 day')")
-- Query the Oracle database
query_oracle_dev("SELECT * FROM employees WHERE hire_date > SYSDATE - 30")
The transaction_<db_id> tool supports begin, execute, commit, and rollback actions. Each begin returns a transactionId; pass it back to stage statements and to commit or roll back:
// 1. Start a transaction
{ "action": "begin" }
// → { "transactionId": "tx_mysql1_1730000000000000000" }
// 2. Execute statements within the transaction
{
"action": "execute",
"transactionId": "tx_mysql1_1730000000000000000",
"statement": "INSERT INTO orders (customer_id, product_id) VALUES (1, 2)"
}
// 3a. Commit — persists all staged statements
{ "action": "commit", "transactionId": "tx_mysql1_1730000000000000000" }
// 3b. OR rollback — discards all staged statements
{ "action": "rollback", "transactionId": "tx_mysql1_1730000000000000000" }
Unknown or already-retired transaction IDs return a clear error instead of a silent success, so agents can detect and recover from lost-transaction situations.
-- Get all tables in the database
schema_mysql1("tables")
-- Get columns for a specific table
schema_mysql1("columns", "users")
-- Get constraints
schema_mysql1("constraints", "orders")
-- Create a table in SQLite
execute_sqlite_app("CREATE TABLE IF NOT EXISTS local_cache (key TEXT PRIMARY KEY, value TEXT, timestamp DATETIME)")
-- Use SQLite-specific date functions
query_sqlite_app("SELECT * FROM events WHERE date(created_at) = date('now')")
-- Query SQLite master table for schema information
query_sqlite_app("SELECT name, sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")
-- Performance optimization with WAL mode
execute_sqlite_app("PRAGMA journal_mode = WAL")
execute_sqlite_app("PRAGMA synchronous = NORMAL")
-- Query user tables (excludes system schemas)
query_oracle_dev("SELECT table_name FROM user_tables ORDER BY table_name")
-- Use Oracle-specific date functions
query_oracle_dev("SELECT employee_id, hire_date FROM employees WHERE hire_date >= TRUNC(SYSDATE, 'YEAR')")
-- Oracle sequence operations
execute_oracle_dev("CREATE SEQUENCE emp_seq START WITH 1000 INCREMENT BY 1")
query_oracle_dev("SELECT emp_seq.NEXTVAL FROM DUAL")
-- Oracle-specific data types
query_oracle_dev("SELECT order_id, TO_CHAR(order_date, 'YYYY-MM-DD HH24:MI:SS') FROM orders")
-- Get schema metadata from Oracle data dictionary
query_oracle_dev("SELECT column_name, data_type, nullable FROM user_tab_columns WHERE table_name = 'EMPLOYEES'")
-- Use Oracle analytic functions
query_oracle_dev("SELECT employee_id, salary, RANK() OVER (ORDER BY salary DESC) as salary_rank FROM employees")
query_timeout setting in your configurationEnable verbose logging for troubleshooting:
./bin/server -t sse -c config.json -v
The project includes comprehensive unit and integration tests for all supported databases.
Run unit tests (no database required):
make test
# or
go test -short ./...
Integration tests require running database instances. We provide Docker Compose configurations for easy setup.
Test All Databases:
# Start test databases
docker-compose -f docker-compose.test.yml up -d
# Run all integration tests
go test ./... -v
# Stop test databases
docker-compose -f docker-compose.test.yml down -v
Test Oracle Database:
# Start Oracle test environment
./oracle-test.sh start
# Run Oracle tests
./oracle-test.sh test
# or manually
ORACLE_TEST_HOST=localhost go test -v ./pkg/db -run TestOracle
ORACLE_TEST_HOST=localhost go test -v ./pkg/dbtools -run TestOracle
# Stop Oracle test environment
./oracle-test.sh stop
# Full cleanup (removes volumes)
./oracle-test.sh cleanup
Test TimescaleDB:
# Start TimescaleDB test environment
./timescaledb-test.sh start
# Run TimescaleDB tests
TIMESCALEDB_TEST_HOST=localhost go test -v ./pkg/db/timescale ./internal/delivery/mcp
# Stop TimescaleDB test environment
./timescaledb-test.sh stop
Run comprehensive regression tests across all database types:
# Ensure all test databases are running
docker-compose -f docker-compose.test.yml up -d
./oracle-test.sh start
# Run regression tests
MYSQL_TEST_HOST=localhost \
POSTGRES_TEST_HOST=localhost \
ORACLE_TEST_HOST=localhost \
go test -v ./pkg/db -run TestRegression
# Run connection pooling tests
go test -v ./pkg/db -run TestConnectionPooling
All tests run automatically on every pull request via GitHub Actions. The CI pipeline includes:
We welcome contributions to the DB MCP Server project! To contribute:
git checkout -b feature/amazing-feature)git commit -m 'feat: add amazing feature')git push origin feature/amazing-feature)Please see our CONTRIBUTING.md file for detailed guidelines.
Before submitting a pull request, please ensure:
go test -short ./...golangci-lint run ./...This project is licensed under the MIT License - see the LICENSE file for details.
A powerful multi-database server implementing the Model Context Protocol (MCP) to provide AI assistants with structured access to databases.
工具
尚無工具清單。遠端伺服器會在首次健康檢查後取得工具清單。
常見問題
在本頁複製適用於 Cursor、Claude Desktop、Claude Code 或 VS Code 的 stdio 設定。它使用發布者的安裝方式,而不是 PlugMCP 代理伺服器。
這筆記錄未列出必要的環境變數。
Db 透過 stdio 在本機執行。
上次檢查時間:2026-10-26。 A powerful multi-database server implementing the Model Context Protocol (MCP) to provide AI assistants with structured access to databases.