MySQL MCP implements security controls for database connections. It supports stdio and HTTP transports. It utilizes MCP v2 stateless architecture.
Identifier Sanitization (src/adapters/mysql/schemas/)
- β Zod schemas β Validates and quotes all table, column, schema, and index names across all tool groups.
- β MySQL identifier rules enforced β start with letter/underscore, contain only alphanumerics, underscores, or $ signs
- β 64-character limit enforced (MySQL maximum)
- β
Invalid identifiers throw
InvalidIdentifierError
Parameterized Queries
- β
All user-provided values use parameterized queries via
mysql2library - β Identifier sanitization complements parameterized values β defense in depth
Every tool returns structured error responses β never raw exceptions or internal details:
{
"success": false,
"error": "Descriptive message with context",
"code": "MODULE_ERROR_CODE",
"category": "VALIDATION_ERROR",
"suggestion": "Actionable remediation hint",
"recoverable": true
}Error logic leverages the MySQLMcpError hierarchy (multiple distinct categories). It returns enriched payloads via formatHandlerErrorResponse(). Error codes are module-prefixed. The server logs internal stack traces but never exposes them to clients.
- β Zod schemas β Validate all tool inputs at tool boundaries before database operations
- β Parameterized queries β Use parameterized queries throughout β never string interpolation
- β Audit filters required β Audit log queries must provide at least one filter to prevent mass data extraction
- β Data masking aliases β Validate aliases strictly at the MCP boundary to prevent evasion
- β Identifier sanitization β Validate table, column, schema, and index names against injection
A dedicated security sandbox strictly confines all file I/O operations exposed by the server. This includes MySQL Shell operations and Audit Subsystem snapshots.
- β
ALLOWED_IO_ROOTSEnforcement β operations must target absolute paths within administrator-configured directories. HTTP transports hard-fail on startup if omitted. - β
Path Traversal Prevention β blocks traversal sequences (
..), null bytes, and query parameters. - β
Symlink Awareness β resolves and asserts
realpathto prevent escaping the sandbox via symlink targets. - β Hidden Files Protection β rejects dotfiles and hidden directories unless explicitly authorized.
- β Drive Letter Validation β cross-platform compatible with strict Windows drive letter and UNC path checking.
Code Mode executes user-provided JavaScript in a hardened isolated-vm sandbox. This includes multiple layers of defense-in-depth and fleet-standard restrictions. These features are detailed prominently in the README.md.
- β Strict V8 Isolate Boundary β executes within a physically separate V8 isolate. It ensures native objects and prototypes cannot cross the boundary.
- β Memory & CPU Constraints β enforced at the C++ level. This includes synchronous timeouts and strict heap limits.
- β
API Bindings via Reference β Injects MySQL methods securely using
ivm.Referencewrappers.
- β
Comprehensive blocked patterns β regex rules block
require(),import(),eval(),Function,process, and__proto__. They also block filesystem/network access and system commands. - β Unicode & Comment Sanitization β Strips comments and performs NFKC normalization to prevent regex evasion.
- β Configurable code input limit β prevents payload-based resource exhaustion.
- β RPC Quotas β Caps RPC API calls per execution. This prevents unbounded loops.
- β
Execution timeout β Enforces timeouts to prevent resource exhaustion. Configurable via schema
timeout. - β
Egress boundary enforcement β streaming
JSON.stringifyserialization aborts mid-flight when exceeding size caps. - β Rate limiting β Enforces per-client rate limits. Configure via CODEMODE_RATE_LIMIT_MAX. Uses Redis with in-memory fallbacks.
- β
Readonly enforcement β when
readonly: true, write methods return structured errors instead of executing. - β Audit logging β Logs every execution with UUID, client ID, metrics, and redacted code preview.
- β
Admin scope β Code Mode requires
adminscope when OAuth is enabled. - β
Full API access β Exposes all tool groups via the
mysql.*namespace.
When running in HTTP mode (--transport http), the following security measures apply:
- β
DNS Rebinding Protection β
validateHostHeader()strictly validatesHostheaders - β X-Content-Type-Options: nosniff β prevents MIME sniffing
- β X-Frame-Options: DENY β prevents clickjacking
- β Content-Security-Policy: default-src 'none'; frame-ancestors 'none' β prevents XSS and framing
- β Cache-Control: no-store, no-cache, must-revalidate β prevents caching of sensitive data
- β Referrer-Policy: no-referrer β prevents referrer leakage
- β Permissions-Policy: camera=(), microphone=(), geolocation=() β restricts browser APIs
- β Strict-Transport-Security header for HTTPS deployments
- β
Enable via
--enable-hstsflag orMCP_ENABLE_HSTS=true
- β
Origin whitelist with
Vary: Originheader for caching - β
Optional credentials support (
corsAllowCredentials) - β
MCP-specific headers allowed (
X-Session-ID,mcp-session-id)
- β
Built-in Rate Limiting β Configurable rate limiting per IP. Configure limits via
MCP_RATE_LIMIT_MAX. Distribute limits across deployments via Redis using graceful in-memory fallbacks. - β
Health Endpoint Bypass β
/healthbypasses limits to ensure reliable load balancer checks - β
Returns 429 Too Many Requests with proper
Retry-Afterheaders when limits are exceeded - β Slowloris DoS Protection β strictly enforced timeouts at the transport layer prevent connection exhaustion (120s request, 65s headers, 66s keep-alive)
Reverse Proxy Note: The server uses
req.socket.remoteAddressfor rate limiting. All requests may share the same IP behind reverse proxies. You must ensure your proxy forwards distinct client IPs. Pass--trust-proxyor setTRUST_PROXY=true. This trusts theX-Forwarded-Forheader. Alternatively, you can apply rate limiting at the proxy layer instead.
- β Memory Exhaustion Protection β Strict request bounds prevent memory exhaustion DoS
The server supports full OAuth 2.1 for production multi-tenant deployments. These enterprise security features are detailed prominently in the README.md.
- β
RFC 9728 Protected Resource Metadata (
/.well-known/oauth-protected-resource) - β RFC 8414 Authorization Server Discovery with caching
- β RFC 7591 OAuth 2.1 Dynamic Client Registration
- β JWT validation with JWKS support (TTL: 1 hour)
- β
MySQL-specific scopes:
read,write,admin,full,db:{name},table:{db}:{table} - β
Per-tool scope enforcement via
AsyncLocalStoragecontext threading - β
Bearer Token Auth: Use
MCP_AUTH_TOKENfor straightforward token authentication to avoid OAuth overhead.
β οΈ HTTP without Authentication: Exposing HTTP transport without authentication grants unrestricted access to all clients.
- β
Dedicated user:
app(UID 1001) with minimal privileges - β
Restricted group:
app(GID 1001)
Note: Administrators must restrict
/app/datadirectory permissions on the host system.
- β Minimal base image: Node.js Alpine image
- β Multi-stage build: Build dependencies not in production image
- β Production pruning: Uses pnpm install --prod and pnpm store prune in the runtime stage
- β Process isolation from host system
The Dockerfile explicitly patches npm-bundled transitive dependencies for Docker Scout compliance.
# Secure volume mounting
docker run -i --rm -v ./data:/app/data writenotenow/mysql-mcp:latest --transport stdio --allowed-io-roots /app/data --mysql "mysql://mcp_user:secure_password@host.docker.internal:3306/testdb"# Apply resource limits
docker run -i --memory=1g --cpus=1 -v ./data:/app/data:rw -e ALLOWED_IO_ROOTS=/app/data writenotenow/mysql-mcp:latest --transport stdio --mysql "mysql://mcp_user:secure_password@host.docker.internal:3306/testdb"- β
Dual Audit Log Architecture β Primary MCP server writes to mcp-audit.jsonl. Grafana Alloy ingests mcp-audit.jsonl and routes to Loki. Exporter reads from mcp-audit.jsonl via AUDIT_LOG_PATH to compute metrics. Exporter isolates its own writes by setting
--audit-logto exporter-audit.jsonl. The metrics server and exporter share a single process. Both operate on port 3000. This prevents port contention. - β
Exporter Healthcheck:
wget --spider -q http://127.0.0.1:3000/metrics - β Full JSONL Audit Trails β comprehensive logging array capturing mutations, Code Mode executions, and system events
- β Session Token Estimates β robust burn-rate tracking appended to log entries
- β Pre-Mutation Snapshots (Backup) β interceptor captures table states before destructive administration operations
- β
Redact Sensitive Fields β The
--audit-redactflag redacts sensitive data in logs. - β Recursive sanitization for nested objects
- β Control character sanitization (ASCII 0x00-0x1F except tab/newline, 0x7F, C1 characters)
- β Prevents log forging and escape sequence attacks
- β CodeQL analysis β automated static analysis on push/PR
- β pnpm audit β dependency vulnerability checking (audit-level: moderate)
- β Dependabot β automated dependency update PRs (weekly for npm and GitHub Actions)
- β Secrets scanning β dedicated workflow for leaked credential detection
- β E2E transport parity β Playwright suite validates streamable and stateless HTTP behavior
- Never commit database credentials to version control β use environment variables
- Require OAuth 2.1 authentication for HTTP transport in production.
- Restrict database user permissions to minimum required
- Enable SSL for database connections in production (
ssl=truein connection string) - Enable HSTS when running over HTTPS (
--enable-hsts) - Configure CORS origins explicitly β avoid wildcards
- Use resource limits β apply Docker
--memoryand--cpuslimits - Apply rate limiting at the proxy layer when deploying behind a reverse proxy
- Consider SHA-pinning critical GitHub Actions in CI workflows for supply-chain defense-in-depth
- Parameterized queries only β never interpolate user input into SQL strings
- Zod validation β all tool inputs validated via schemas at tool boundaries
- No secrets in code β use environment variables (
.envfiles are gitignored) - Typed error classes β descriptive messages with context; don't expose internals
- Regular updates β keep Node.js and pnpm dependencies updated
- Security scanning β regularly scan Docker images for vulnerabilities
- Parameterized SQL queries throughout
- Identifier sanitization (table, column, schema, index names)
- Input validation via Zod schemas
- Filesystem boundary sandbox (
ALLOWED_IO_ROOTS) for all file I/O operations - Code Mode sandbox isolation (true separate V8 isolate via isolated-vm)
- Code Mode native prototype isolation (objects cannot cross isolate boundary)
- Code Mode blocked patterns (comprehensive static regex rules + Unicode/NFKC validation)
- Code Mode egress streaming boundary (abort serialization on oversized results)
- Code Mode RPC Quotas
- Code Mode execution timeout (dynamically configurable)
- Code Mode rate limiting (configurable via
CODEMODE_RATE_LIMIT_MAX, Redis-backed with in-memory fallback) - Code Mode audit logging
- HTTP bounds limits
- Configurable CORS with origin whitelist
- Rate limiting (configurable via
MCP_RATE_LIMIT_MAX, Redis-backed with in-memory fallback) - Slowloris DoS timeouts (strictly enforced at transport layer)
- DNS rebinding protection via Host header validation
- Security headers (CSP, X-Content-Type-Options, X-Frame-Options, Cache-Control, Referrer-Policy, Permissions-Policy)
- HSTS (opt-in)
- OAuth 2.1 with JWT/JWKS validation (RFC 9728, RFC 8414)
- MySQL-specific scope enforcement (
read,write,admin,full,db:{name},table:{db}:{table}) - Per-tool scope enforcement via
AsyncLocalStorage - Credential redaction in logs
- Log injection prevention
- Non-root Docker user
- Multi-stage Docker build with production pruning
- Transitive dependency CVE patching in Dockerfile
- CI/CD security pipeline (CodeQL, pnpm audit, secrets scanning)
- Structured error responses (no internal details leaked)
- Comprehensive security documentation
| Version | Supported |
|---|---|
| Current Major Version | β |
| Previous Major Version | β |
If you discover a security vulnerability:
- Do not open a public GitHub issue
- Email security concerns to: admin@adamic.tech
- Include detailed reproduction steps and potential impact
- Allow reasonable time for a fix before public disclosure
- Initial Response: Within 48 hours
- Status Update: Within 7 days
- Fix Timeline: Depends on severity
We appreciate responsible disclosure. We will acknowledge your contribution in our release notes.
- Container updates: Rebuild Docker images when base images are updated
- Dependency updates: Keep npm packages updated via
pnpm auditand Dependabot - Database maintenance: Run
OPTIMIZE TABLEandANALYZE TABLEregularly for optimal performance - Security patches: Apply host system security updates
Security-first principles drive the mysql-mcp server design. It protects your databases. It maintains excellent performance and full MySQL capability.