fastmcp-mysql

jinto/fastmcp-mysql

3.3

If you are the rightful owner of fastmcp-mysql and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.

FastMCP MySQL Server is a high-performance server implementation designed for secure and efficient access to MySQL databases, specifically tailored for LLM applications.

Tools
  1. mysql_query

    Execute SQL queries against the configured MySQL database.

FastMCP MySQL Server

A FastMCP server implementation for MySQL database operations, providing secure and efficient access to MySQL databases for LLM applications.

Features

  • šŸ”’ Secure by Default: Read-only access with optional write permissions
  • ⚔ High Performance: Connection pooling and async operations
  • šŸ›”ļø SQL Injection Protection: Built-in query validation and prepared statements
  • šŸ“Š Comprehensive Monitoring: Structured JSON logging
  • šŸ”§ Flexible Configuration: Environment variable based configuration
  • šŸš€ Easy Deployment: Install and run with uvx

Installation

Using uvx (Recommended)

# Run directly with uvx
uvx fastmcp-mysql

# With environment variables
MYSQL_HOST=localhost MYSQL_USER=myuser MYSQL_PASSWORD=mypass MYSQL_DB=mydb uvx fastmcp-mysql

Using pip

pip install fastmcp-mysql

From source

git clone https://github.com/jinto/fastmcp-mysql
cd fastmcp-mysql
uv sync --all-extras

Configuration

Configure the server using environment variables:

Required Variables

VariableDescriptionDefault
MYSQL_USERDatabase username-
MYSQL_PASSWORDDatabase password-

Optional Variables

VariableDescriptionDefault
MYSQL_HOSTDatabase host"127.0.0.1"
MYSQL_PORTDatabase port"3306"
MYSQL_DBDatabase name (optional)None
MYSQL_ALLOW_INSERTEnable INSERT queriesfalse
MYSQL_ALLOW_UPDATEEnable UPDATE queriesfalse
MYSQL_ALLOW_DELETEEnable DELETE queriesfalse
MYSQL_POOL_SIZEConnection pool size10
MYSQL_QUERY_TIMEOUTQuery timeout (ms)30000
MYSQL_LOG_LEVELLog level (DEBUG, INFO, WARNING, ERROR)INFO
MYSQL_CACHE_ENABLEDEnable query result cachingtrue
MYSQL_CACHE_MAX_SIZEMaximum cache entries1000
MYSQL_CACHE_TTLCache TTL (ms)60000
MYSQL_CACHE_EVICTION_POLICYCache eviction policy (lru/ttl/fifo)lru
MYSQL_CACHE_CLEANUP_INTERVALCache cleanup interval (seconds)60.0
MYSQL_CACHE_INVALIDATION_MODECache invalidation strategyaggressive
MYSQL_STREAMING_CHUNK_SIZEStreaming query chunk size1000
MYSQL_PAGINATION_DEFAULT_SIZEDefault page size10
MYSQL_PAGINATION_MAX_SIZEMaximum page size1000

Usage

Claude Desktop Configuration

Using Claude MCP CLI (Recommended)
# Install from PyPI (when published)
claude mcp add fastmcp-mysql \
  -e MYSQL_HOST="127.0.0.1" \
  -e MYSQL_PORT="3306" \
  -e MYSQL_USER="your_username" \
  -e MYSQL_PASSWORD="your_password" \
  -e MYSQL_DB="your_database" \
  -- uvx fastmcp-mysql

# Without specifying a database (use USE command)
claude mcp add fastmcp-mysql \
  -e MYSQL_HOST="127.0.0.1" \
  -e MYSQL_USER="your_username" \
  -e MYSQL_PASSWORD="your_password" \
  -- uvx fastmcp-mysql

# For local development
claude mcp add fastmcp-mysql \
  -e MYSQL_HOST="127.0.0.1" \
  -e MYSQL_PORT="3306" \
  -e MYSQL_USER="your_username" \
  -e MYSQL_PASSWORD="your_password" \
  -e MYSQL_DB="your_database" \
  -- uv run --project /path/to/fastmcp-mysql fastmcp-mysql
Manual Configuration

Add to your Claude Desktop configuration file:

{
  "mcpServers": {
    "mysql": {
      "command": "uvx",
      "args": ["fastmcp-mysql"],
      "env": {
        "MYSQL_HOST": "localhost",
        "MYSQL_PORT": "3306",
        "MYSQL_USER": "your_username",
        "MYSQL_PASSWORD": "your_password",
        "MYSQL_DB": "your_database",
        "MYSQL_ENABLE_SECURITY": "true",
        "MYSQL_RATE_LIMIT_RPM": "60",
        "MYSQL_RATE_LIMIT_BURST": "10"
      }
    }
  }
}

Available Tools

mysql_query

Execute SQL queries against the configured MySQL database.

Parameters:

  • query (string, required): The SQL query to execute
  • params (array, optional): Query parameters for prepared statements
  • database (string, optional): Target database (for multi-db mode)

Example:

# Simple query
result = await mysql_query("SELECT * FROM users WHERE active = 1")

# With parameters (SQL injection safe)
result = await mysql_query(
    "SELECT * FROM users WHERE age > %s AND city = %s",
    params=[18, "New York"]
)

# When no database is specified initially
result = await mysql_query("USE mydb")
result = await mysql_query("SHOW TABLES")
result = await mysql_query("SHOW DATABASES")

Security

Default Security Features

FastMCP MySQL includes comprehensive security features:

  • Read-only by default: Write operations must be explicitly enabled
  • SQL injection prevention:
    • Advanced pattern detection for SQL injection attempts
    • Parameter validation for all queries
    • Detection of encoded injection attempts (URL, Unicode, Hex)
  • Query filtering:
    • Blacklist mode: Blocks dangerous operations (DDL, system tables, file operations)
    • Whitelist mode: Only allows explicitly approved query patterns
    • Customizable filtering rules
  • Rate limiting:
    • Per-user request throttling
    • Configurable algorithms (Token Bucket, Sliding Window, Fixed Window)
    • Burst protection

Security Configuration

Configure security features via environment variables:

VariableDescriptionDefault
MYSQL_ENABLE_SECURITYEnable all security featurestrue
MYSQL_ENABLE_INJECTION_DETECTIONEnable SQL injection detectiontrue
MYSQL_ENABLE_RATE_LIMITINGEnable rate limitingtrue
MYSQL_FILTER_MODEFilter mode (blacklist/whitelist/combined)blacklist
MYSQL_RATE_LIMIT_RPMRate limit requests per minute60
MYSQL_RATE_LIMIT_BURSTBurst size for rate limiting10
MYSQL_RATE_LIMIT_ALGORITHMRate limiting algorithm (token_bucket/sliding_window/fixed_window)token_bucket
MYSQL_MAX_QUERY_LENGTHMaximum query length in characters10000
MYSQL_MAX_PARAMETER_LENGTHMaximum parameter length1000
MYSQL_LOG_SECURITY_EVENTSLog security violationstrue
MYSQL_LOG_REJECTED_QUERIESLog rejected queriestrue
MYSQL_AUDIT_ALL_QUERIESAudit all queries (performance impact)false

Enabling Write Operations

Write operations are disabled by default. Enable them with caution:

# Enable specific write operations
MYSQL_ALLOW_INSERT=true \
MYSQL_ALLOW_UPDATE=true \
MYSQL_ALLOW_DELETE=true \
uvx fastmcp-mysql

Security Best Practices

  1. Use Prepared Statements: Always use parameters instead of string concatenation
  2. Principle of Least Privilege: Only enable write operations when necessary
  3. Monitor Security Events: Check logs for security violations
  4. Rate Limiting: Adjust limits based on your application needs
  5. Whitelist Mode: Use whitelist mode for production environments when possible

Development

Setup Development Environment

# Clone the repository
git clone https://github.com/jinto/fastmcp-mysql
cd fastmcp-mysql

# Create virtual environment with uv
uv venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate

# Install dependencies
uv sync --all-extras

# Install pre-commit hooks
pre-commit install

Running Tests

# Run all tests
uv run pytest tests/

# Run with coverage
uv run pytest tests/ --cov=fastmcp_mysql

# Run specific test file
uv run pytest tests/unit/test_query.py

# Run integration tests only
uv run pytest tests/integration/

Code Quality

# Format code
uv run black src tests

# Lint code
uv run ruff check src tests

# Type checking
uv run mypy src

Architecture

The server follows Clean Architecture principles:

src/fastmcp_mysql/
ā”œā”€ā”€ __init__.py                 # Package initialization
ā”œā”€ā”€ __main__.py                 # Entry point for uvx
ā”œā”€ā”€ config.py                   # Configuration management
ā”œā”€ā”€ server.py                   # FastMCP server setup
ā”œā”€ā”€ connection.py               # Database connection management
ā”œā”€ā”€ security/                   # Security module (Clean Architecture)
│   ā”œā”€ā”€ __init__.py
│   ā”œā”€ā”€ manager.py              # Security orchestration
│   ā”œā”€ā”€ config.py               # Security configuration
│   ā”œā”€ā”€ exceptions.py           # Security exceptions
│   ā”œā”€ā”€ interfaces/             # Abstract interfaces
│   │   ā”œā”€ā”€ injection_detector.py
│   │   ā”œā”€ā”€ query_filter.py
│   │   └── rate_limiter.py
│   ā”œā”€ā”€ injection/              # SQL injection detection
│   │   ā”œā”€ā”€ detector.py
│   │   └── patterns.py
│   ā”œā”€ā”€ filtering/              # Query filtering
│   │   ā”œā”€ā”€ blacklist.py
│   │   ā”œā”€ā”€ whitelist.py
│   │   └── combined.py
│   └── rate_limiting/          # Rate limiting
│       ā”œā”€ā”€ token_bucket.py
│       ā”œā”€ā”€ sliding_window.py
│       ā”œā”€ā”€ fixed_window.py
│       └── factory.py
└── tools/                      # MCP tools
    ā”œā”€ā”€ __init__.py
    └── query.py                # Query execution tool

Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Please ensure:

  • All tests pass
  • Code is formatted with black
  • Type hints are added
  • Documentation is updated

License

This project is licensed under the MIT License - see the file for details.

Acknowledgments

Support