Skip to main content

A Model Context Protocol (MCP) server that enables secure interaction with Redis DataBases.

Project description

Redis MCP Server

Python Version Redis Version FastMCP License: MIT Code Style: Black

A Model Context Protocol (MCP) server that enables secure, efficient interaction with Redis databases through AI assistants and applications.

๐Ÿš€ Features

  • ๐Ÿ”Œ MCP Protocol Support: Built on FastMCP framework with standard MCP tools and resources
  • ๐Ÿ—„๏ธ Redis Compatibility: Support for Redis single, master-slave, and cluster deployments
  • โšก Asynchronous Architecture: Built with redis.asyncio and hiredis for high-performance operations
  • ๐Ÿ”— Connection Pooling: Efficient connection management with configurable pool settings
  • ๐Ÿ”’ Security Features: Password protection, SSL support, and connection validation
  • ๐Ÿ› ๏ธ Comprehensive Tools: Redis command execution, monitoring, and data management
  • ๐Ÿ“Š Monitoring & Analytics: Server info, memory usage, client connections, and key statistics
  • ๐Ÿ”ง Flexible Configuration: JSON-based configuration with multiple instance support
  • ๐Ÿ“ Detailed Logging: Structured logging with configurable levels and file rotation
  • ๐Ÿณ Production Ready: Health checks, error handling, and graceful connection management

๐Ÿ“‹ Prerequisites

  • Python: >= 3.12
  • Redis: >= 5.0.0
  • Network Access: To Redis server instance(s)

๐Ÿ› ๏ธ Installation

1. Install from PyPI (Recommended)

pip install redis-mcp-server3

2. Configure database connection

Edit dbconfig.json with your database credentials:

{
  "redisEncoding": "utf-8",
  "redisPoolSize": 5,
  "redisMaxConnections": 10,
  "redisConnectionTimeout": 30,
  "socketTimeout": 30,
  "retryOnTimeout": true,
  "healthCheckInterval": 30,
  "redisType-Comment": "single ๅ•ๆœบๆจกๅผใ€masterslave ไธปไปŽๆจกๅผใ€cluster ้›†็พคๆจกๅผ",
  "redisList": [
    {
      "redisInstanceId": "redis-local-single",
      "redisType": "single",
      "redisHost": "localhost",
      "redisPort": 6379,
      "redisDatabase": 0,
      "redisPassword": 123456,
      "dbActive": true
    },
    {
      "redisInstanceId": "redis-ms-single",
      "redisType": "masterslave",
      "redisHost": "localhost",
      "redisPort": 6379,
      "redisDatabase": 0,
      "redisPassword": 123456,
      "dbActive": false
    },
    {
      "redisInstanceId": "redis-cluster-single",
      "redisType": "cluster",
      "redisHost": "localhost",
      "redisPort": 6379,
      "redisDatabase": 0,
      "redisPassword": 123456,
      "dbActive": false
    }
  ],
  "logPath": "/path/to/logs",
  "logLevel": "info"
}
# redisType
Redis Instance is in singleใ€masterslaveใ€cluster mode.
# dbActive
Only database instances with dbActive set to true in the dbList configuration list are available. 
# logPath
MCP server log is stored in /path/to/logs/mcp_server.log.
# logLevel
TRACE, DEBUG, INFO, SUCCESS, WARNING, ERROR, CRITICAL

3. Configure MCP Client

Add to your MCP client configuration file:

{
  "mcpServers": {
    "redis-mcp-client": {
      "command": "redis-mcp-server3",
      "env": {
        "config_file": "/path/to/your/dbconfig.json"
      },
      "disabled": false
    }
  }
}

Note: Replace /path/to/your/dbconfig.json with the actual path to your configuration file.

4. Clone the repository (Development Mode)

git clone https://github.com/j00131120/mcp_database_server.git
cd mcp_database_server/redis_mcp_server
# Import project into your IDE

5. Configure MCP Client for Development

{
  "mcpServers": {
    "redis-mcp-client": {
      "command": "/bin/uv",
      "args": ["run", "redis_mcp_server3/server.py"],
      "cwd": "/path/to/your/project",
      "env": {
        "config_file": "/path/to/your/dbconfig.json"
      },
      "disabled": false
    }
  }
}

# command
uv absolute path
# cwd
project absolute path
# config_file
dbconfig.json file path

๐Ÿš€ Quick Start

1. Start the MCP Server

# Using installed package
redis-mcp-server3

# Using FastMCP CLI
fastmcp run redis_mcp_server3/server.py

# Direct Python execution
python redis_mcp_server3/server.py

# Using fastmcp debug
fastmcp dev redis_mcp_server3/server.py

2. Basic Usage Examples

# Execute Redis commands
await redis_exec("SET", ["user:1001", "John Doe"])
await redis_exec("GET", ["user:1001"])

# Hash operations
await redis_exec("HSET", ["user:1001:profile", "name", "John", "age", "30"])
await redis_exec("HGETALL", ["user:1001:profile"])

# List operations
await redis_exec("LPUSH", ["tasks", "task1", "task2"])
await redis_exec("LRANGE", ["tasks", "0", "-1"])

# Get server information
server_info = await get_server_info()
memory_info = await get_memory_info()

๐Ÿ“š API Reference

MCP Tools

redis_exec(command: str, args: list = None)

Execute any Redis command with arguments.

Parameters:

  • command (str): Redis command name (e.g., 'GET', 'SET', 'HGET')
  • args (list, optional): Command arguments

Returns:

  • dict: Execution result with success status and data

Examples:

# String operations
await redis_exec("SET", ["key1", "value1"])
await redis_exec("GET", ["key1"])
await redis_exec("SETEX", ["key2", "60", "temp_value"])

# Hash operations  
await redis_exec("HSET", ["hash1", "field1", "value1"])
await redis_exec("HGETALL", ["hash1"])

# List operations
await redis_exec("LPUSH", ["list1", "item1", "item2"])
await redis_exec("LRANGE", ["list1", "0", "-1"])

# Set operations
await redis_exec("SADD", ["set1", "member1", "member2"])
await redis_exec("SMEMBERS", ["set1"])

gen_test_data(table: str, columns: list, num: int = 10)

Generate test data for Redis hash structures.

Parameters:

  • table (str): Table/prefix name for the keys
  • columns (list): Field names to populate
  • num (int): Number of test records to generate

get_server_info()

Get Redis server basic information.

Returns:

  • Server version, mode, OS, architecture, uptime

get_memory_info()

Get Redis memory usage statistics.

Returns:

  • Memory usage, peak usage, RSS memory, max memory settings

get_clients_info()

Get Redis client connection information.

Returns:

  • Connected clients count, input/output buffer sizes

get_stats_info()

Get Redis operation statistics.

Returns:

  • Total connections, commands processed, keyspace hits/misses

get_db_info()

Get Redis database information.

Returns:

  • Database size, keyspace information

get_keys_info()

Get sample key information (first 10 keys).

Returns:

  • Total key count, sample keys with types and TTL

get_key_types()

Get key type distribution statistics.

Returns:

  • Distribution of different key types (string, hash, list, set, zset)

get_redis_config()

Get Redis configuration information.

Returns:

  • Important Redis configuration parameters

get_redis_overview()

Get comprehensive Redis overview (all monitoring information).

Returns:

  • Complete system overview including all above information

MCP Resources

database://config

Database configuration information (sensitive data hidden).

Returns:

  • Safe configuration details without passwords

database://status

Database connection status and health check results.

Returns:

  • Connection status, ping results, basic operations test

๐Ÿ—๏ธ Architecture

Project Structure

redis_mcp_server/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ __init__.py              # Package metadata and API
โ”‚   โ”œโ”€โ”€ server.py                # Main MCP server entry point
โ”‚   โ”œโ”€โ”€ utils/                   # Utility modules
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py          # Utility exports
โ”‚   โ”‚   โ”œโ”€โ”€ db_config.py         # Configuration management
โ”‚   โ”‚   โ”œโ”€โ”€ db_pool.py           # Connection pool management
โ”‚   โ”‚   โ”œโ”€โ”€ db_operate.py        # Redis operations wrapper
โ”‚   โ”‚   โ””โ”€โ”€ logger_util.py       # Logging configuration
โ”‚   โ”œโ”€โ”€ resources/               # MCP resources
โ”‚   โ”‚   โ””โ”€โ”€ db_resources.py      # Database resources provider
โ”‚   โ””โ”€โ”€ tools/                   # MCP tools
โ”‚       โ””โ”€โ”€ db_tool.py           # Redis management tools
โ”œโ”€โ”€ dbconfig.json               # Database configuration
โ”œโ”€โ”€ pyproject.toml              # Project configuration
โ”œโ”€โ”€ requirements.txt            # Python dependencies
โ””โ”€โ”€ README.md                   # Project documentation

Key Components

Connection Pool Manager

  • Singleton Pattern: Single pool instance per application
  • Async Management: Non-blocking connection handling
  • Health Monitoring: Automatic connection validation
  • Resource Cleanup: Proper connection release

Configuration System

  • JSON-based: Human-readable configuration
  • Environment Override: Flexible deployment options
  • Multi-instance: Support for multiple Redis instances
  • Validation: Comprehensive error checking

Logging System

  • Structured Logging: JSON-formatted log entries
  • File Rotation: Automatic log file management
  • Configurable Levels: TRACE to CRITICAL
  • Performance Optimized: Asynchronous logging

๐Ÿ”ง Advanced Configuration

SSL/TLS Configuration

For secure connections, configure SSL in your dbconfig.json:

{
  "redisList": [
    {
      "redisInstanceId": "secure-redis",
      "redisHost": "secure.redis.example.com",
      "redisPort": 6380,
      "redisSsl": true,
      "redisPassword": "secure_password",
      "dbActive": true
    }
  ]
}

Cluster Configuration

For Redis cluster deployments:

{
  "redisList": [
    {
      "redisInstanceId": "redis-cluster",
      "redisType": "cluster",
      "redisHost": "cluster-node1.example.com",
      "redisPort": 7000,
      "redisPassword": "cluster_password",
      "dbActive": true
    }
  ]
}

Performance Tuning

Optimize for high-throughput scenarios:

{
  "redisPoolSize": 20,
  "redisMaxConnections": 50,
  "redisConnectionTimeout": 10,
  "socketTimeout": 5,
  "healthCheckInterval": 60
}

๐Ÿงช Testing

Basic Connection Test

# Test Redis connection
status = await get_connection_status()
print(status)  # {'ping': True, 'set_get': 'ok'}

Performance Testing

# Generate test data
await gen_test_data("users", ["name", "email", "age"], 1000)

# Check database size
db_info = await get_db_info()
print(f"Total keys: {db_info['dbsize']}")

๐Ÿ“Š Monitoring

Health Checks

The server provides built-in health monitoring:

# Get comprehensive overview
overview = await get_redis_overview()

# Check specific metrics
memory = await get_memory_info()
if memory['used_memory'] > threshold:
    # Handle high memory usage
    pass

Log Analysis

Monitor server logs for performance and errors:

# View real-time logs
tail -f /var/log/redis_mcp_server/logs/mcp_server.log

# Search for errors
grep "ERROR" /var/log/redis_mcp_server/logs/mcp_server.log

๐Ÿšจ Troubleshooting

Common Issues

Connection Errors

Problem: ConnectionError: Connection refused

Solution:

# Check Redis server status
redis-cli ping

# Verify Redis is running
systemctl status redis

# Check network connectivity
telnet localhost 6379

Authentication Errors

Problem: AuthenticationError: Auth failed

Solutions:

  • Verify password in dbconfig.json
  • Check Redis AUTH configuration
  • Ensure user has proper permissions

Memory Issues

Problem: High memory usage or OOM errors

Solutions:

  • Monitor with get_memory_info()
  • Adjust maxmemory policy
  • Implement key expiration
  • Use Redis memory optimization techniques

Performance Issues

Problem: Slow response times

Solutions:

  • Increase connection pool size
  • Reduce connection timeout
  • Monitor with get_stats_info()
  • Check network latency

Debug Mode

Enable debug logging:

{
  "logLevel": "debug"
}

Diagnostic Commands

# Check server health
server_info = await get_server_info()
clients_info = await get_clients_info()
stats_info = await get_stats_info()

# Analyze key distribution
key_types = await get_key_types()
keys_sample = await get_keys_info()

๐Ÿค Contributing

We welcome contributions! Please follow these guidelines:

Development Setup

# Clone the repository
git clone https://github.com/j00131120/mcp_database_server.git
cd mcp_database_server/redis_mcp_server

# Install development dependencies
pip install -e ".[dev,test,docs]"

# Install pre-commit hooks
pre-commit install

Code Quality

# Format code
black redis_mcp_server3/
isort redis_mcp_server3/

# Lint code
flake8 redis_mcp_server3/
mypy redis_mcp_server3/

# Run tests
pytest

# Run tests with coverage
pytest --cov=redis_mcp_server3 --cov-report=html

Submitting Changes

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass
  6. Commit your changes (git commit -m 'Add amazing feature')
  7. Push to the branch (git push origin feature/amazing-feature)
  8. Open a Pull Request

Code Style

  • Follow PEP 8 guidelines
  • Use type hints for all functions
  • Add docstrings for public methods
  • Write comprehensive tests
  • Update documentation

๐Ÿ“„ License

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

๐Ÿ‘ฅ Authors

๐Ÿ™ Acknowledgments

  • FastMCP - MCP framework foundation
  • redis-py - Python Redis client
  • Loguru - Structured logging library
  • Redis - In-memory data structure store

๐Ÿ“ž Support

๐Ÿ”„ Version History

v1.0.0

  • Initial release
  • Full MCP protocol support
  • Redis connection pooling
  • Comprehensive monitoring tools
  • Security features implementation
  • Production-ready deployment

Built with โค๏ธ for the Redis and MCP communities

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

redis_mcp_server3-1.1.0.tar.gz (26.1 kB view details)

Uploaded Source

Built Distribution

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

redis_mcp_server3-1.1.0-py3-none-any.whl (23.6 kB view details)

Uploaded Python 3

File details

Details for the file redis_mcp_server3-1.1.0.tar.gz.

File metadata

  • Download URL: redis_mcp_server3-1.1.0.tar.gz
  • Upload date:
  • Size: 26.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.5

File hashes

Hashes for redis_mcp_server3-1.1.0.tar.gz
Algorithm Hash digest
SHA256 29528a4c903e9962109e3333f5e8edfa264e83903178c0b148817ec942d14786
MD5 07ab0790e562c12f81da5037ed1e9009
BLAKE2b-256 03cfe07eed482c335b0d3d4de62d29ff49387c7ba43324c0a9b7557ca27b2372

See more details on using hashes here.

File details

Details for the file redis_mcp_server3-1.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for redis_mcp_server3-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f40f70f1e48f9e298f145048ad5f28a7b3f4374157b3243ec763785f330cc3e4
MD5 e4f7d5a77edebf10c120a57470b7cd62
BLAKE2b-256 b09dcaae97a1e25578a531840ae2d4ddcfddfee72475fdcfcd1ac7021d8f23eb

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