Skip to content

Security: neverinfamous/mysql-mcp

SECURITY.md

πŸ”’ Security Policy

MySQL MCP implements security controls for database connections. It supports stdio and HTTP transports. It utilizes MCP v2 stateless architecture.

πŸ›‘οΈ Defend Your Database Infrastructure

Prevent SQL Injection Vulnerabilities

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 mysql2 library
  • βœ… Identifier sanitization complements parameterized values β€” defense in depth

Prevent Data Leaks with Structured Errors

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.

πŸ” Ensure Integrity with Input Validation

  • βœ… 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

πŸ“ Sandbox Operations with Filesystem Boundaries

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_ROOTS Enforcement β€” 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 realpath to 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.

πŸ§ͺ Isolate Threats in Code Mode Sandbox

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.

Enforce Engine-Level Restrictions

  • βœ… 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.Reference wrappers.

Validate Code Statically

  • βœ… 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.

Protect the Runtime

  • βœ… 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.stringify serialization 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 admin scope when OAuth is enabled.
  • βœ… Full API access β€” Exposes all tool groups via the mysql.* namespace.

🌐 Fortify Remote HTTP Transports

When running in HTTP mode (--transport http), the following security measures apply:

Add Security Headers

  • βœ… DNS Rebinding Protection β€” validateHostHeader() strictly validates Host headers
  • βœ… 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

Support HSTS

  • βœ… Strict-Transport-Security header for HTTPS deployments
  • βœ… Enable via --enable-hsts flag or MCP_ENABLE_HSTS=true

Configure CORS

  • βœ… Origin whitelist with Vary: Origin header for caching
  • βœ… Optional credentials support (corsAllowCredentials)
  • βœ… MCP-specific headers allowed (X-Session-ID, mcp-session-id)

Apply Rate Limiting

  • βœ… 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 β€” /health bypasses limits to ensure reliable load balancer checks
  • βœ… Returns 429 Too Many Requests with proper Retry-After headers 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.remoteAddress for rate limiting. All requests may share the same IP behind reverse proxies. You must ensure your proxy forwards distinct client IPs. Pass --trust-proxy or set TRUST_PROXY=true. This trusts the X-Forwarded-For header. Alternatively, you can apply rate limiting at the proxy layer instead.

Restrict Request Limits

  • βœ… Memory Exhaustion Protection β€” Strict request bounds prevent memory exhaustion DoS

πŸ”‘ Control Access via OAuth 2.1 & Bearer Tokens

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 AsyncLocalStorage context threading
  • βœ… Bearer Token Auth: Use MCP_AUTH_TOKEN for straightforward token authentication to avoid OAuth overhead.

⚠️ HTTP without Authentication: Exposing HTTP transport without authentication grants unrestricted access to all clients.

🐳 Deploy Secure Docker Containers

Run as Non-Root User

  • βœ… Dedicated user: app (UID 1001) with minimal privileges
  • βœ… Restricted group: app (GID 1001)

Note: Administrators must restrict /app/data directory permissions on the host system.

Harden the Container

  • βœ… 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

Patch Dependencies

The Dockerfile explicitly patches npm-bundled transitive dependencies for Docker Scout compliance.

Mount Volumes Securely

# 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

# 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"

πŸ” Maintain Compliance with Secure Logs

Enable Audit Subsystem

  • βœ… 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-log to 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 Credentials

  • βœ… Redact Sensitive Fields β€” The --audit-redact flag redacts sensitive data in logs.
  • βœ… Recursive sanitization for nested objects

Prevent Log Injection

  • βœ… Control character sanitization (ASCII 0x00-0x1F except tab/newline, 0x7F, C1 characters)
  • βœ… Prevents log forging and escape sequence attacks

πŸ”„ Automate Security in CI/CD Pipelines

  • βœ… 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

🚨 Implement Operational Security Best Practices

Follow Best Practices for Users

  1. Never commit database credentials to version control β€” use environment variables
  2. Require OAuth 2.1 authentication for HTTP transport in production.
  3. Restrict database user permissions to minimum required
  4. Enable SSL for database connections in production (ssl=true in connection string)
  5. Enable HSTS when running over HTTPS (--enable-hsts)
  6. Configure CORS origins explicitly β€” avoid wildcards
  7. Use resource limits β€” apply Docker --memory and --cpus limits
  8. Apply rate limiting at the proxy layer when deploying behind a reverse proxy
  9. Consider SHA-pinning critical GitHub Actions in CI workflows for supply-chain defense-in-depth

Follow Best Practices for Developers

  1. Parameterized queries only β€” never interpolate user input into SQL strings
  2. Zod validation β€” all tool inputs validated via schemas at tool boundaries
  3. No secrets in code β€” use environment variables (.env files are gitignored)
  4. Typed error classes β€” descriptive messages with context; don't expose internals
  5. Regular updates β€” keep Node.js and pnpm dependencies updated
  6. Security scanning β€” regularly scan Docker images for vulnerabilities

πŸ“‹ Verify with the Security Checklist

  • 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

🚨 Disclose Vulnerabilities Responsibly

Version Supported
Current Major Version βœ…
Previous Major Version βœ…

If you discover a security vulnerability:

  1. Do not open a public GitHub issue
  2. Email security concerns to: admin@adamic.tech
  3. Include detailed reproduction steps and potential impact
  4. Allow reasonable time for a fix before public disclosure

Review Response Timeline

  • 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.

πŸ”„ Maintain Protection with Security Updates

  • Container updates: Rebuild Docker images when base images are updated
  • Dependency updates: Keep npm packages updated via pnpm audit and Dependabot
  • Database maintenance: Run OPTIMIZE TABLE and ANALYZE TABLE regularly 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.

There aren't any published security advisories