Database MCP
Provides tools for connecting to and querying MySQL databases, with support for caching and bilingual prompts
Provides tools for connecting to and querying PostgreSQL databases, with support for caching and bilingual prompts
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
DB-MCP Gateway
A multi-database MCP gateway with table-level access control.
Manage MySQL and PostgreSQL connections through a web admin UI, create scoped MCP endpoints, and assign users via token-based ACL.
Architecture
┌─────────────────────────────────────────────────────────┐
│ DB-MCP Gateway │
│ │
│ Connection ─── credentials (admin, all tables) │
│ │ │
│ ├── Endpoint ─── MCP exposure + table scope │
│ │ e.g. /mysql/orders-api (tables: orders, │
│ │ order_items) │
│ │ │
│ └── Endpoint ─── MCP exposure (all tables) │
│ e.g. /mysql/full-access │
│ │
│ ACL: User ──► Endpoint │
│ (token-based, one user can access multiple endpoints) │
│ │
│ Admin UI: /admin │
│ User discovery: /api/endpoints?token=xxx │
└─────────────────────────────────────────────────────────┘Three-layer model:
Connection — database credentials. Admin-level, no restrictions.
Endpoint — MCP exposure layer. References one connection. Optionally restricts which tables are visible via
allowed_tableswhitelist. Empty whitelist = all tables.ACL — binds a user to an endpoint. Users authenticate by token.
One connection can back multiple endpoints with different table scopes.
Related MCP server: MCP Universal DB Client
Permission model (gateway-owned)
The gateway holds the admin DB credentials and executes every query itself. Permissions are enforced at two levels, both in the gateway:
L1 — endpoint access: every request to an MCP endpoint (
/{db_type}/{alias}/sse|/messages|/mcp) must carry a user token, either asAuthorization: Bearer <token>(preferred) or?token=. The gateway checks the token → endpoint ACL; no grant → 403.L2 — table scope: per tool call, referenced tables are extracted from the SQL AST (sqlglot) and checked against the endpoint's
allowed_tables;execute_sqladditionally rejects anything that is not a single pureSELECT(blocks data-modifying CTEs,SELECT INTO,INTO OUTFILE, stacked queries).
Features
Multi-database: unlimited MySQL and PostgreSQL connections.
Table-level scoping: each endpoint can whitelist specific tables.
get_all_schemas/get_tablesfilter results;get_table_schemablocks unauthorized tables;execute_sqlvalidates table references.Web admin UI: light/dark theme, pagination, search, batch import, bulk ACL assignment. Accessible at
/admin.Token-based user auth: each user gets a hex token. Users query
/api/endpoints?token=xxxto discover their available MCP servers.Dynamic mounting: endpoints are mounted/unmounted on config change without restart.
Standalone servers:
server_mysql.pyandserver_pgsql.pycan run independently with.envconfig (SDK 1.27+, v1 API).Optional TTL cache: per-call
use_cache/ttlparameters (gateway and standalone).Two transports: SSE (
/sse,/messages) and Streamable HTTP (/mcp) mounted per endpoint.Audit log: every MCP tool call appended as JSONL (
audit.log).Usage metering: per user / endpoint / tool counters (
GET /admin/api/metering, persisted tometering.json).Runtime guards: query timeout, server-side
max_rowscap, per-(user, endpoint) rate limiting (all env-configurable).AST read-only guard: sqlglot-based, blocks data-modifying CTEs,
SELECT INTO,INTO OUTFILE, stacked queries.
Project Structure
gateway.py # FastAPI gateway entrypoint
gateway_config.py # Models + pickle persistence
gateway_api.py # Admin + user API routes
gateway_mcp_factory.py # Dynamic per-endpoint MCP server creation
server_mysql.py # Standalone MySQL MCP server (SDK 1.27+)
server_pgsql.py # Standalone PostgreSQL MCP server (SDK 1.27+)
core/
base.py # Abstract driver interface
cache.py # In-process TTL cache
sqlguard.py # AST read-only guard + table extraction (sqlglot)
engines.py # Process-wide async engine cache
ctx.py # Per-request context (L1 identity for tools)
audit.py # JSONL query audit log
metering.py # Usage counters (persisted JSON)
ratelimit.py # Sliding-window rate limiter
tests/ # pytest: guard, scope, persistence, auth, metering
drivers/
mysql_driver.py # MySQL driver (SQLAlchemy + aiomysql)
pgsql_driver.py # PostgreSQL driver (SQLAlchemy + asyncpg)
prompts/
mysql_prompts.py # MySQL built-in prompts (bilingual)
pgsql_prompts.py # PostgreSQL built-in prompts (bilingual)
static/
admin.html # Admin management UI
gateway_data.json # Persisted config (JSON; legacy .pkl auto-migrated)
requirements.txt
Dockerfile
.env.sampleQuick Start
Gateway mode
pip install -r requirements.txt
uvicorn gateway:app --host 0.0.0.0 --port 8000Open http://localhost:8000/admin to configure connections, endpoints,
users, and ACL.
Standalone MySQL
uvicorn server_mysql:app --host 0.0.0.0 --port 8001Standalone PostgreSQL
uvicorn server_pgsql:app --host 0.0.0.0 --port 8002Standalone servers read connection info from .env (see .env.sample).
Docker
docker build -t db-mcp:latest .
# Gateway (default)
docker run --rm -p 8000:8000 db-mcp:latest
# MySQL only
docker run --rm -p 8001:8001 -e TARGET=mysql db-mcp:latest
# PostgreSQL only
docker run --rm -p 8002:8002 -e TARGET=pgsql db-mcp:latestAdmin UI
Visit /admin. The UI has four tabs:
Connections — add/edit/delete database connections. Batch import via JSON array. Search and filter by type.
Endpoints — create MCP endpoints backed by a connection. Set
allowed_tablesto restrict table access (one per line, supportstable,db.table,schema.table). Leave empty for all tables.Users — create users, view/regenerate tokens.
ACL — assign endpoints to users. Bulk assign supported.
First startup creates a default admin user automatically.
Check the Users tab for the token.
Securing the admin API
Set ADMIN_TOKEN before starting the gateway:
export ADMIN_TOKEN="a-long-random-string"
uvicorn gateway:app --host 0.0.0.0 --port 8000When set, every /admin/api/* call must carry
Authorization: Bearer <ADMIN_TOKEN> (the bundled admin UI has a token
box in the top bar and stores it in localStorage). Without it the
server logs a warning and leaves the admin API open (dev only).
Connection passwords are write-only: accepted on create/update, but
read APIs always return "password": "***". To change a password, edit
the connection and type the new one (blank = keep unchanged).
MCP Endpoints
Each endpoint exposes SSE and Streamable HTTP transports:
SSE: /{db_type}/{endpoint_alias}/sse
SSE messages: /{db_type}/{endpoint_alias}/messages
Streamable HTTP: /{db_type}/{endpoint_alias}/mcp
Also accessible by endpoint ID:
SSE: /{db_type}/{endpoint_id}/sseUser endpoint discovery
GET /api/endpoints?token=USER_TOKENReturns the list of endpoints the user can access, with MCP paths and
table scope info. Every MCP request to those paths must then carry the
token as Authorization: Bearer <token> (or ?token=).
Table scoping example
Connection prod-mysql points to a MySQL instance with full access.
You create three endpoints:
Endpoint Alias | Connection | allowed_tables | Use case |
| prod-mysql |
| Order service |
| prod-mysql |
| User service |
| prod-mysql | (empty = all) | Internal admin |
Assign orders-api to user A, users-api to user B, full-access
to user C. Each gets their own MCP server URL.
API Reference
Admin API (/admin/api)
Method | Path | Description |
GET |
| List connections |
POST |
| Create connection |
PATCH |
| Update connection |
DELETE |
| Delete connection (+ cascade) |
POST |
| Batch create |
GET |
| List endpoints |
POST |
| Create endpoint |
PATCH |
| Update endpoint |
DELETE |
| Delete endpoint (+ cascade) |
GET |
| List users |
POST |
| Create user |
DELETE |
| Delete user (+ cascade) |
POST |
| Regenerate token |
GET |
| List ACL rules |
POST |
| Create ACL rule |
POST |
| Batch create ACL |
DELETE |
| Delete ACL rule |
GET |
| Usage counters (users/endpoints/tools) |
POST |
| Resync MCP mounts |
User API (/api)
Method | Path | Description |
GET |
| Discover accessible endpoints |
MCP Tools
Each endpoint exposes these tools (names vary by db_type):
Tool | Description |
| List databases/schemas with tables/columns (filtered by scope) |
| List tables (filtered by scope) |
| Describe a table (blocked if outside scope) |
| Execute read-only SELECT (AST-validated, table references checked) |
| Get built-in analysis/sql_rules/react prompt |
Persistence
Config is stored in gateway_data.json (JSON, atomic writes). A legacy
gateway_data.pkl is auto-migrated on first load (backed up as
gateway_data.pkl.bak). To reset, delete the JSON file and restart.
Observability
Audit:
audit.log(JSONL) — one record per MCP tool call: timestamp, user, endpoint, tool, SQL hash + preview, tables, rows, duration, cache hit, error. SetDBMCP_AUDIT_PATHto relocate.Metering:
GET /admin/api/meteringreturns aggregated calls/rows/errors/latency per user, endpoint and tool (persisted tometering.json,DBMCP_METERING_PATHto relocate).
Runtime guards
Env var | Default | Meaning |
|
| tool-call timeout, seconds |
|
| hard server-side cap for |
|
| tool calls per (user, endpoint) per minute |
| (empty) | comma-separated |
Production note (Streamable HTTP): the MCP SDK enables DNS-rebinding protection by default and only allows
localhost/127.0.0.1/[::1](with port). If you serve the gateway on a public domain, extend the allow-list via env (mcp 2.x no longer readsFASTMCP_TRANSPORT_SECURITY__*env vars, so the gateway maps it for you):MCP_ALLOWED_HOSTS="db.example.com:*". SSE transport is unaffected.
Tests
pip install -r requirements.lock pytest
pytest tests/ -qCovers: read-only SQL guard + table extraction, L2 table scope, JSON persistence + pickle migration, admin auth + password masking, metering, rate limiter, engine fingerprint.
Requirements
Python 3.12+
mcp >= 2 (v2 API with
MCPServer; v1'sFastMCPwas renamed)fastapi, uvicorn, sqlalchemy, aiomysql, asyncpg, python-dotenv, pydantic, sqlglot
Pinned lock file:
requirements.lock(pip install -r requirements.lock)
This server cannot be deployed
Maintenance
Related MCP Connectors
Text-to-SQL MCP server: read-only queries on PostgreSQL, MySQL and SQL Server with your real schema
PostgreSQL, MySQL, and SQL Server in one session. 26 read-only MCP tools for AI agents.
PostgreSQL, MySQL, OpenAPI/Swagger, and shared Agent Memory with scoped access.
Hosted PostgreSQL MCP server for Claude, ChatGPT and Cursor, with each action switched per account.
Related MCP Servers
- AlicenseNot gradedqualityAmaintenanceThe Multi DB MCP Server is a high-performance implementation of the Database Model Context Protocol designed to revolutionize how AI agents interact with databases. Currently supporting MySQL and PostgreSQL databases.476MIT
- AlicenseAqualityCmaintenanceEnables connecting to and querying multiple database types (PostgreSQL, MySQL, SQLite) through a unified interface. Supports managing multiple concurrent database connections with connection pooling and SQL query execution through MCP tools.56 npmMIT
- AlicenseNot gradedqualityNot gradedmaintenanceA universal database gateway MCP server that enables AI assistants to connect to and query multiple databases (PostgreSQL, MySQL, MariaDB, SQL Server, SQLite) with support for schema exploration, SQL execution, and secure connections via SSH tunnels.7 npm-
- FlicenseNot gradedqualityAmaintenanceAn MCP server that exposes relational databases (PostgreSQL/MySQL) to AI agents with natural language to SQL query support.19-