Skip to main content

FastMCP server for MySQL database operations

Project description

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

Variable Description Default
MYSQL_USER Database username -
MYSQL_PASSWORD Database password -
MYSQL_DB Database name -

Optional Variables

Variable Description Default
MYSQL_HOST Database host "127.0.0.1"
MYSQL_PORT Database port "3306"
MYSQL_ALLOW_INSERT Enable INSERT queries false
MYSQL_ALLOW_UPDATE Enable UPDATE queries false
MYSQL_ALLOW_DELETE Enable DELETE queries false
MYSQL_POOL_SIZE Connection pool size 10
MYSQL_QUERY_TIMEOUT Query timeout (ms) 30000
MYSQL_LOG_LEVEL Log level (DEBUG, INFO, WARNING, ERROR) INFO
MYSQL_CACHE_ENABLED Enable query result caching true
MYSQL_CACHE_MAX_SIZE Maximum cache entries 1000
MYSQL_CACHE_TTL Cache TTL (ms) 60000
MYSQL_CACHE_EVICTION_POLICY Cache eviction policy (lru/ttl/fifo) lru
MYSQL_CACHE_CLEANUP_INTERVAL Cache cleanup interval (seconds) 60.0
MYSQL_CACHE_INVALIDATION_MODE Cache invalidation strategy aggressive
MYSQL_STREAMING_CHUNK_SIZE Streaming query chunk size 1000
MYSQL_PAGINATION_DEFAULT_SIZE Default page size 10
MYSQL_PAGINATION_MAX_SIZE Maximum page size 1000

Usage

Claude Desktop Configuration

Add to your Claude Desktop configuration:

{
  "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"]
)

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:

Variable Description Default
MYSQL_ENABLE_SECURITY Enable all security features true
MYSQL_ENABLE_INJECTION_DETECTION Enable SQL injection detection true
MYSQL_ENABLE_RATE_LIMITING Enable rate limiting true
MYSQL_FILTER_MODE Filter mode (blacklist/whitelist/combined) blacklist
MYSQL_RATE_LIMIT_RPM Rate limit requests per minute 60
MYSQL_RATE_LIMIT_BURST Burst size for rate limiting 10
MYSQL_RATE_LIMIT_ALGORITHM Rate limiting algorithm (token_bucket/sliding_window/fixed_window) token_bucket
MYSQL_MAX_QUERY_LENGTH Maximum query length in characters 10000
MYSQL_MAX_PARAMETER_LENGTH Maximum parameter length 1000
MYSQL_LOG_SECURITY_EVENTS Log security violations true
MYSQL_LOG_REJECTED_QUERIES Log rejected queries true
MYSQL_AUDIT_ALL_QUERIES Audit 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 LICENSE file for details.

Acknowledgments

Support

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastmcp_mysql-0.1.0.tar.gz (134.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastmcp_mysql-0.1.0-py3-none-any.whl (66.5 kB view details)

Uploaded Python 3

File details

Details for the file fastmcp_mysql-0.1.0.tar.gz.

File metadata

  • Download URL: fastmcp_mysql-0.1.0.tar.gz
  • Upload date:
  • Size: 134.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.0

File hashes

Hashes for fastmcp_mysql-0.1.0.tar.gz
Algorithm Hash digest
SHA256 d8f87da97245b838df01721a0922fcc20a8a9908b73ce75c3284105c46016875
MD5 40acbc7208432b8fdb3aab95ffaee72b
BLAKE2b-256 f23488eda47fcb6a364a082cdfaceda775ecf1d692ab259e56c0e1baac58153b

See more details on using hashes here.

File details

Details for the file fastmcp_mysql-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: fastmcp_mysql-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 66.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.0

File hashes

Hashes for fastmcp_mysql-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5690f41825d9fc7c79ad8a85b8201c29dc670373c8cfa56b28d51229d65bb9f2
MD5 14b4ccfba87c986a3d13111bdf28206f
BLAKE2b-256 a2a422fe85eb5d7c6b4b5cb4a99c5c4bac28f6d6df8f959e1ec4d3f8d32294e1

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page