convez.ai
MCP ServerDados & AnalyticsIntermediário
hex1n

db-mcp

hex1n/db-mcp

Acesso seguro a múltiplos bancos de dados via MCP em Go

Ver no GitHub
InicialPluginScore · de 0 a 100

Servidor MCP multi-engine para acesso a bancos de dados locais via Claude e Codex. Suporta MySQL, OceanBase e Redis com operações leitura/escrita controladas e seguras através de um único binário Go compilado.

Instalação

$npx convez-ai hex1n/db-mcp

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
0
Forks
0
Acompanhando
0
Saúde
28%
Último commit
há 4 meses
Versão
v0.1.1
Issues abertas
0
Contribuidores
2

Casos de uso

  • Inspeção de ambientes de teste e desenvolvimento
  • Execução de queries SQL contra MySQL/OceanBase
  • Operações em cache Redis com controle de escrita
  • Integração de múltiplas datasources em projeto único

Veredito

Ferramenta sólida para conectar Claude a bancos de dados locais com segurança. Implementação em Go garante performance e compilação cross-platform; ideal para ambientes de desenvolvimento e testes com proteções contra operações destrutivas acidentais.

README

A tradução para o português deste README ainda está na fila.

db-mcp

简体中文

Multi-engine database MCP server for Codex and Claude Code. It targets local test-environment inspection and bounded data operations through a single fast Go binary. Supported engines:

  • OceanBase (MySQL protocol)
  • MySQL
  • Redis

One server can serve several datasources of different kinds at the same time.

Features

  • Standard MCP stdio server.
  • Lazy connections, so startup does not wait for any database.
  • Project-scoped TOML datasource config, multiple datasources per project.
  • Pluggable engine registry — adding a new database is one registration plus an engine implementation.
  • Tools are registered per configured kind: a config without SQL datasources will not expose SQL tools, and vice versa.
  • Direct credentials, environment-backed passwords, or (for SQL) Java properties-backed JDBC config.
  • Two operation modes: inspect for bounded agent reads and operate for explicit local raw/write work.
  • Bounded row/element counts via max_rows, single-value previews via max_value_bytes, and best-effort MCP response caps via max_result_bytes.

Tools

Shared (always available):

  • list_datasources
  • current_datasource
  • get_current_time (RFC3339 timestamp with timezone offset)

SQL engines (mysql, oceanbase) — registered when a SQL datasource exists:

  • list_tables
  • describe_table
  • sample_table
  • execute_sql

Redis (redis) — registered when a Redis datasource exists:

  • redis_scan (bounded SCAN; preferred over the blocking KEYS)
  • redis_get (auto-detects string/list/set/hash/zset, bounded)
  • redis_type
  • redis_ttl
  • redis_command (arbitrary command in argv form)

Calling a SQL tool against a Redis datasource (or vice versa) returns a clear capability error. Write/destructive statements (execute_sql writes, redis_command SET/DEL/FLUSHALL...) should only be used after explicit user confirmation.

Every tool carries MCP annotations: read tools set readOnlyHint, while execute_sql and redis_command set destructiveHint; all set openWorldHint=false (a closed datasource, not the open internet). MCP clients can use these hints to visually separate safe reads from writes and to prompt before destructive calls.

Install

The server is cross-platform. Build it on the OS where you will run the MCP client.

Windows:

go build -o "$env:USERPROFILE\bin\db-mcp.exe" ./cmd/db-mcp

macOS/Linux:

go build -o "$HOME/bin/db-mcp" ./cmd/db-mcp

Download prebuilt binaries from GitHub Releases after a tagged release exists. Release assets are published for:

  • linux-amd64
  • linux-arm64
  • darwin-amd64 (macOS Intel)
  • darwin-arm64 (macOS Apple Silicon)
  • windows-amd64

Each release also includes checksums.txt.

Or install from GitHub after the repository is published:

go install github.com/hex1n/db-mcp/cmd/db-mcp@latest

If the GitHub owner is not hex1n, update the module path in go.mod before publishing.

Distribution

Pushing a version tag creates a GitHub Release with cross-platform binaries:

git tag v0.1.0
git push origin v0.1.0

The release workflow builds with CGO_ENABLED=0, injects the tag into db-mcp --version, packages README files and examples/db-mcp.toml.example, and uploads checksums. Supported release targets are Linux/macOS on amd64 and arm64, plus Windows on amd64.

Datasource Config

Create .db-mcp.toml in the target project root. Do not commit this file when it contains passwords.

default = "project_test"
max_rows = 500
max_value_bytes = 65536
max_result_bytes = 1048576
query_timeout_seconds = 30
# inspect is the recommended default for agent use. Use mode = "operate" only
# for local test databases where raw/write commands are explicitly allowed.
mode = "inspect"

# OceanBase (MySQL protocol) with an env-backed password.
[datasources.project_test]
driver = "oceanbase"
host = "oceanbase.example.internal"
port = 3306
database = "your_database"
username = "your_user@tenant#cluster"
password_from = "env:DB_MCP_PASSWORD"

# Plain MySQL.
[datasources.mysql_local]
driver = "mysql"
host = "127.0.0.1"
port = 3306
database = "app"
username = "root"
password = "secret"

# Redis. Uses redis_db (logical DB index) instead of a SQL database name.
[datasources.cache_local]
driver = "redis"
host = "127.0.0.1"
port = 6379
redis_db = 0
# password_from = "env:REDIS_PASSWORD"

General notes:

  • default is required when more than one datasource is configured. With a single datasource, it may be omitted and resolves to that datasource.
  • max_rows limits rows or collection elements, not bytes. max_value_bytes caps each returned value preview, and max_result_bytes caps the returned MCP payload on a best-effort basis. A truncated response is a preview, not full data.
  • mode = "inspect" restricts execute_sql and redis_command to bounded reads. mode = "operate" keeps raw/write capabilities enabled. If mode is omitted, db-mcp uses operate for backward compatibility.
  • Legacy read_only = true is still accepted as mode = "inspect", but do not configure both mode and read_only.
  • execute_sql and redis_command require an explicit datasource when multiple datasources are configured.

Per-driver notes:

  • driver defaults to mysql when omitted. oceanbase is an alias of the MySQL driver.
  • SQL datasources require host, database, and username. Default port 3306.
  • Redis datasources require only host; username/password are optional and redis_db selects the logical DB (default 0). Default port 6379.
  • password_from = "env:NAME" reads the password from an environment variable.

A SQL datasource can also be backed by a Java properties file with keys like:

db.project.url=jdbc:mysql://oceanbase.example.internal:3306/your_database
db.project.username=your_user@tenant#cluster
db.project.password=your_password
[datasources.from_properties]
driver = "mysql"
properties_file = "app/bootstrap/src/main/resources/config/application-test.properties"
properties_prefix = "db.project"

properties_file is SQL-only.

Operation Modes

Set mode = "inspect" at the top level to refuse mutations server-side:

  • execute_sql accepts only reads: SELECT/SHOW/DESC/DESCRIBE/EXPLAIN and read-only WITH CTEs (a CTE wrapping INSERT/UPDATE/DELETE/REPLACE is rejected). EXPLAIN ANALYZE (which actually runs the statement) and SELECT ... INTO OUTFILE/DUMPFILE are also rejected.
  • For SQL engines, inspect mode additionally opens the connection with a read-only session (transaction_read_only), so the database itself rejects any write that slips past the statement classifier (e.g. a side-effecting function).
  • redis_command accepts only small-result metadata reads or argument-bounded reads (PING, TIME, TYPE, TTL, EXISTS, STRLEN, GETRANGE, HLEN, LLEN, SCARD, ZCARD, ...). Writes and raw commands whose result can be enlarged by data or arguments (SET/DEL/FLUSHALL, KEYS, SCAN, MGET, HGETALL, SMEMBERS, LRANGE, ZRANGE, HSCAN, ...) are refused; use redis_get/redis_scan for bounded data reads.
  • The read-only built-ins (list_tables, redis_get, ...) are unaffected.
  • The write tools keep their destructiveHint even in this mode, so clients still prompt before running them — inspect mode is a guard, not a guarantee.

The SQL statement classifier is a fast first line of defense and does not parse SQL fully. On SQL engines the read-only DB session backs it up, but it depends on the engine honoring transaction_read_only (guaranteed on MySQL; OceanBase MySQL mode accepts it). redis_command has no equivalent server-side backstop, so its allowlist is the guard. Result budgets also run after the database client has produced values, so very large SQL cells may still consume driver memory before they are truncated for MCP output. For a hard guarantee, also use a read-only database account or a Redis ACL/read-only replica.

Use mode = "operate" only for local test databases where raw/write statements and Redis commands are intentionally available. In operate mode, execute_sql and redis_command still require explicit datasource when more than one datasource is configured, and both retain destructiveHint.

Legacy read_only = true remains supported as an alias for mode = "inspect". New configs should use mode.

Config lookup order when --config is omitted:

  1. DB_MCP_CONFIG
  2. $CLAUDE_PROJECT_DIR/.db-mcp.toml
  3. .db-mcp.toml in the current working directory

Codex

Project .codex/config.toml:

Windows:

[mcp_servers.db_mcp_project_test]
command = "C:\\Users\\you\\bin\\db-mcp.exe"
args = ["--config", "C:\\path\\to\\your-project\\.db-mcp.toml"]

macOS/Linux:

[mcp_servers.db_mcp_project_test]
command = "/path/to/db-mcp"
args = ["--config", "/path/to/your-project/.db-mcp.toml"]

If db-mcp is on PATH, command = "db-mcp" is also fine.

Restart or reload the Codex session after changing MCP server config.

Claude Code

Project .mcp.json:

Windows:

{
  "mcpServers": {
    "db-mcp-project-test": {
      "command": "${USERPROFILE}/bin/db-mcp.exe",
      "args": [
        "--config",
        "${CLAUDE_PROJECT_DIR:-.}/.db-mcp.toml"
      ]
    }
  }
}

macOS/Linux:

{
  "mcpServers": {
    "db-mcp-project-test": {
      "command": "${HOME}/bin/db-mcp",
      "args": [
        "--config",
        "${CLAUDE_PROJECT_DIR:-.}/.db-mcp.toml"
      ]
    }
  }
}

Claude Code supports environment-variable expansion in .mcp.json, including ${VAR} and ${VAR:-default}.

Development Verification

Local checks:

go test ./...
go vet ./...
go build ./cmd/db-mcp

After installing or building the binary, verify the CLI:

db-mcp --version

For a SQL datasource, ask the MCP client to run:

select database() as db_name, now() as db_time

For a Redis datasource, ask it to run redis_command with ["PING"], or redis_scan with pattern *.

Optional live smoke tests are skipped unless their environment variables are set:

DB_MCP_TEST_MYSQL=127.0.0.1:3306/app \
DB_MCP_TEST_MYSQL_USER=root \
DB_MCP_TEST_MYSQL_PASSWORD=secret \
go test -run TestMySQLLiveSmoke ./internal/engine/mysqlengine

DB_MCP_TEST_OCEANBASE=oceanbase.example.internal:3306/app \
DB_MCP_TEST_OCEANBASE_USER='user@tenant#cluster' \
DB_MCP_TEST_OCEANBASE_PASSWORD=secret \
go test -run TestOceanBaseLiveSmoke ./internal/engine/mysqlengine

DB_MCP_TEST_REDIS=127.0.0.1:6379 \
go test -run TestRedisLiveSmoke ./internal/engine/redisengine

CI runs the local checks on Linux, macOS, and Windows, with the race detector and coverage on Linux/macOS, plus a staticcheck lint job. It also runs MySQL and Redis live smoke tests on Linux service containers. OceanBase remains an environment-triggered smoke test because it requires a compatible external test instance.

Before tagging a release, verify that main is green in CI. The release workflow runs go vet/go test first and only builds and publishes if they pass, and packages the same ./cmd/db-mcp binary path documented above.

Boundaries

db-mcp is not a production database security gateway. It does not provide full SQL parsing, RBAC, audit approval flows, Redis Cluster/Sentinel support, or PostgreSQL support. Use database-side read-only accounts, Redis ACLs, and network isolation for hard safety boundaries.

Docs

See docs/README.md for the current docs index and the status of historical plans.

Ver o original no GitHub

Bom para

Relacionados