npm package: @hamaster/redis-mcp-server
Description: Redis MCP Server - A Model Context Protocol server for Redis operations
Author: andrewlu@hamaster.cn
Latest version: 1.0.1

# Redis MCP Server

A Model Context Protocol (MCP) server that provides comprehensive Redis operations as tools. This server allows AI assistants to interact with Redis databases through standardized MCP tools, supporting basic key-value operations, Hash data structures, and List (Array) operations.

## Features

This MCP server provides the following Redis operations organized by data type:

### Basic Key-Value Operations

- **redis_ping**: Test Redis connection
- **redis_set**: Set key-value pairs with optional TTL (Time To Live)
- **redis_get**: Retrieve values by key
- **redis_del**: Delete one or more keys
- **redis_exists**: Check if a key exists
- **redis_keys**: Find keys matching a pattern
- **redis_expire**: Set a timeout on a key
- **redis_ttl**: Get time-to-live for a key
- **redis_type**: Get the type of value stored at a key
- **redis_info**: Get Redis server information and statistics
- **redis_dbsize**: Get the number of keys in the database
- **redis_flushdb**: Delete all keys in the current database ⚠️

### Hash Operations

- **redis_hset**: Set the value of a hash field
- **redis_hget**: Get the value of a hash field
- **redis_hgetall**: Get all fields and values in a hash
- **redis_hdel**: Delete one or more hash fields
- **redis_hexists**: Check if a hash field exists
- **redis_hkeys**: Get all field names in a hash
- **redis_hvals**: Get all values in a hash
- **redis_hlen**: Get the number of fields in a hash

### List (Array) Operations

- **redis_lpush**: Insert values at the head of a list
- **redis_rpush**: Insert values at the tail of a list
- **redis_lpop**: Remove and return the first element (head)
- **redis_rpop**: Remove and return the last element (tail)
- **redis_lrange**: Get a range of elements from a list
- **redis_llen**: Get the length of a list
- **redis_lindex**: Get an element from a list by index

## Installation

### Local Installation

1. Clone or download this repository
2. Install dependencies:
```bash
cd redis-mcp-server
npm install
```

3. Configure environment variables (optional):
```bash
# Copy the example environment file
cp .env.example .env

# Edit .env with your Redis configuration
# Or use environment variables directly when running the server
```

## Configuration

### Environment Variables

The Redis MCP server accepts the following environment variables:

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `REDIS_HOST` | No | `localhost` | Redis server host |
| `REDIS_PORT` | No | `6379` | Redis server port |
| `REDIS_PASSWORD` | No | - | Redis password (if required) |
| `REDIS_DB` | No | `0` | Redis database number |

#### Using .env File

For local development, you can use a `.env` file to configure environment variables:

1. Copy the example file:
```bash
cp .env.example .env
```

2. Edit `.env` with your Redis configuration:
```bash
# Redis Server Configuration
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=
REDIS_DB=0
```

3. Install `dotenv` to load environment variables (optional):
```bash
npm install dotenv
```

4. Update `src/index.js` to load environment variables (if using dotenv):
```javascript
import 'dotenv/config';
```

#### Setting Environment Variables in MCP Hub

When configuring the MCP server in MCP Hub, you can set environment variables directly in the configuration file:

```json
{
  "mcpServers": {
    "redis": {
      "command": "node",
      "args": ["d:/workspace/nodejs/mcp-servers/redis-mcp-server/src/index.js"],
      "env": {
        "REDIS_HOST": "localhost",
        "REDIS_PORT": "6379",
        "REDIS_PASSWORD": "",
        "REDIS_DB": "0"
      }
    }
  }
}
```

### MCP Hub Configuration

To use this server with MCP Hub, add the following configuration to your MCP settings file (usually located at `~/.config/mcp/settings.json` or similar):

```json
{
  "mcpServers": {
    "redis": {
      "command": "node",
      "args": ["d:/workspace/nodejs/mcp-servers/redis-mcp-server/src/index.js"],
      "env": {
        "REDIS_HOST": "localhost",
        "REDIS_PORT": "6379",
        "REDIS_PASSWORD": "",
        "REDIS_DB": "0"
      }
    }
  }
}
```

### Using with npx

You can run the server directly using npx:

```bash
npx redis-mcp-server
```

Or with custom environment variables:

```bash
REDIS_HOST=localhost REDIS_PORT=6379 npx redis-mcp-server
```

## Usage Examples

### Basic Key-Value Operations

#### Test Connection
```json
{
  "name": "redis_ping",
  "arguments": {}
}
```

#### Set a key with TTL
```json
{
  "name": "redis_set",
  "arguments": {
    "key": "user:123",
    "value": "{\"name\":\"John\",\"age\":30}",
    "ttl": 3600
  }
}
```

#### Get a key
```json
{
  "name": "redis_get",
  "arguments": {
    "key": "user:123"
  }
}
```

#### Check if key exists
```json
{
  "name": "redis_exists",
  "arguments": {
    "key": "session:abc123"
  }
}
```

#### Find keys matching pattern
```json
{
  "name": "redis_keys",
  "arguments": {
    "pattern": "user:*"
  }
}
```

#### Get TTL of a key
```json
{
  "name": "redis_ttl",
  "arguments": {
    "key": "user:123"
  }
}
```

### Hash Operations

#### Set a hash field
```json
{
  "name": "redis_hset",
  "arguments": {
    "key": "user:123:profile",
    "field": "email",
    "value": "john@example.com"
  }
}
```

#### Get a hash field
```json
{
  "name": "redis_hget",
  "arguments": {
    "key": "user:123:profile",
    "field": "email"
  }
}
```

#### Get all hash fields and values
```json
{
  "name": "redis_hgetall",
  "arguments": {
    "key": "user:123:profile"
  }
}
```

#### Check if hash field exists
```json
{
  "name": "redis_hexists",
  "arguments": {
    "key": "user:123:profile",
    "field": "email"
  }
}
```

#### Get all hash field names
```json
{
  "name": "redis_hkeys",
  "arguments": {
    "key": "user:123:profile"
  }
}
```

#### Get all hash values
```json
{
  "name": "redis_hvals",
  "arguments": {
    "key": "user:123:profile"
  }
}
```

#### Get number of fields in hash
```json
{
  "name": "redis_hlen",
  "arguments": {
    "key": "user:123:profile"
  }
}
```

#### Delete hash fields
```json
{
  "name": "redis_hdel",
  "arguments": {
    "key": "user:123:profile",
    "fields": ["email", "phone"]
  }
}
```

### List (Array) Operations

#### Push values to the head of a list
```json
{
  "name": "redis_lpush",
  "arguments": {
    "key": "task:queue",
    "values": ["task1", "task2", "task3"]
  }
}
```

#### Push values to the tail of a list
```json
{
  "name": "redis_rpush",
  "arguments": {
    "key": "logs",
    "values": ["log1", "log2"]
  }
}
```

#### Pop from the head of a list
```json
{
  "name": "redis_lpop",
  "arguments": {
    "key": "task:queue"
  }
}
```

#### Pop from the tail of a list
```json
{
  "name": "redis_rpop",
  "arguments": {
    "key": "logs"
  }
}
```

#### Get a range of elements from a list
```json
{
  "name": "redis_lrange",
  "arguments": {
    "key": "logs",
    "start": 0,
    "stop": -1
  }
}
```

#### Get list length
```json
{
  "name": "redis_llen",
  "arguments": {
    "key": "task:queue"
  }
}
```

#### Get element by index
```json
{
  "name": "redis_lindex",
  "arguments": {
    "key": "logs",
    "index": 0
  }
}
```

### Advanced Examples

#### Working with Redis INFO
```json
{
  "name": "redis_info",
  "arguments": {
    "section": "memory"
  }
}
```

#### Delete multiple keys
```json
{
  "name": "redis_del",
  "arguments": {
    "keys": ["cache:1", "cache:2", "cache:3"]
  }
}
```

## Tool Reference

### Basic Operations

#### redis_ping
Tests Redis connection by sending a PING command.
- **Parameters**: None
- **Returns**: `{ result: "PONG", message: "Redis connection is working" }`

#### redis_set
Sets a key-value pair in Redis. Optionally sets a TTL.
- **Parameters**:
  - `key` (string, required): The key to set
  - `value` (string, required): The value to set
  - `ttl` (number, optional): Time to live in seconds
- **Returns**: `{ result: "OK", message: "Key 'X' set successfully" }`

#### redis_get
Retrieves the value of a key from Redis.
- **Parameters**:
  - `key` (string, required): The key to retrieve
- **Returns**: `{ key: string, value: string | null, exists: boolean }`

#### redis_del
Deletes one or more keys from Redis.
- **Parameters**:
  - `keys` (array of strings, required): Array of keys to delete
- **Returns**: `{ deleted: number, keys: string[] }`

#### redis_exists
Checks if a key exists in Redis.
- **Parameters**:
  - `key` (string, required): The key to check
- **Returns**: `{ key: string, exists: boolean }`

#### redis_keys
Finds all keys matching a pattern.
- **Parameters**:
  - `pattern` (string, required): Pattern to match (e.g., "*", "user:*", "session:*")
- **Returns**: `{ pattern: string, keys: string[], count: number }`

#### redis_expire
Sets a timeout on a key.
- **Parameters**:
  - `key` (string, required): The key to set timeout on
  - `seconds` (number, required): Time to live in seconds
- **Returns**: `{ key: string, ttl: number, success: boolean }`

#### redis_ttl
Gets the time to live for a key.
- **Parameters**:
  - `key` (string, required): The key to check TTL for
- **Returns**: `{ key: string, ttl: number, message: string }`
  - ttl = -1: Key has no expiry
  - ttl = -2: Key does not exist
  - ttl > 0: Time to live in seconds

#### redis_type
Gets the type of value stored at a key.
- **Parameters**:
  - `key` (string, required): The key to check type for
- **Returns**: `{ key: string, type: string }`
  - Possible types: "string", "hash", "list", "set", "zset", "none"

#### redis_info
Gets information and statistics about the Redis server.
- **Parameters**:
  - `section` (string, optional): Section to retrieve (server, clients, memory, persistence, stats, replication, cpu, cluster, keyspace)
- **Returns**: `{ section: string, info: string }`

#### redis_dbsize
Returns the number of keys in the selected database.
- **Parameters**: None
- **Returns**: `{ database_size: number }`

#### redis_flushdb
Deletes all keys in the current database. ⚠️ Warning: This operation cannot be undone.
- **Parameters**: None
- **Returns**: `{ result: string, message: "Database flushed successfully" }`

### Hash Operations

#### redis_hset
Sets the value of a hash field. Creates the hash if it does not exist.
- **Parameters**:
  - `key` (string, required): The hash key
  - `field` (string, required): The field name within the hash
  - `value` (string, required): The value to store in the field
- **Returns**: `{ key: string, field: string, value: string, new_field: boolean, message: string }`

#### redis_hget
Gets the value of a hash field.
- **Parameters**:
  - `key` (string, required): The hash key
  - `field` (string, required): The field name within the hash
- **Returns**: `{ key: string, field: string, value: string | null, exists: boolean }`

#### redis_hgetall
Gets all fields and values in a hash.
- **Parameters**:
  - `key` (string, required): The hash key
- **Returns**: `{ key: string, hash: object, field_count: number }`

#### redis_hdel
Deletes one or more hash fields.
- **Parameters**:
  - `key` (string, required): The hash key
  - `fields` (array of strings, required): Array of field names to delete
- **Returns**: `{ key: string, deleted_fields: string[], deleted_count: number }`

#### redis_hexists
Checks if a hash field exists.
- **Parameters**:
  - `key` (string, required): The hash key
  - `field` (string, required): The field name to check
- **Returns**: `{ key: string, field: string, exists: boolean }`

#### redis_hkeys
Gets all field names in a hash.
- **Parameters**:
  - `key` (string, required): The hash key
- **Returns**: `{ key: string, fields: string[], count: number }`

#### redis_hvals
Gets all values in a hash.
- **Parameters**:
  - `key` (string, required): The hash key
- **Returns**: `{ key: string, values: string[], count: number }`

#### redis_hlen
Gets the number of fields in a hash.
- **Parameters**:
  - `key` (string, required): The hash key
- **Returns**: `{ key: string, field_count: number }`

### List (Array) Operations

#### redis_lpush
Inserts all the specified values at the head of a list. Creates the list if it does not exist.
- **Parameters**:
  - `key` (string, required): The list key
  - `values` (array of strings, required): Array of values to insert at the head (in order from head to tail)
- **Returns**: `{ key: string, pushed_values: string[], new_length: number }`

#### redis_rpush
Inserts all the specified values at the tail of a list. Creates the list if it does not exist.
- **Parameters**:
  - `key` (string, required): The list key
  - `values` (array of strings, required): Array of values to insert at the tail (in order from head to tail)
- **Returns**: `{ key: string, pushed_values: string[], new_length: number }`

#### redis_lpop
Removes and returns the first element (head) of a list.
- **Parameters**:
  - `key` (string, required): The list key
- **Returns**: `{ key: string, popped_value: string | null, success: boolean }`

#### redis_rpop
Removes and returns the last element (tail) of a list.
- **Parameters**:
  - `key` (string, required): The list key
- **Returns**: `{ key: string, popped_value: string | null, success: boolean }`

#### redis_lrange
Gets a range of elements from a list.
- **Parameters**:
  - `key` (string, required): The list key
  - `start` (number, required): Starting index (0-based, supports negative indices)
  - `stop` (number, required): Stopping index (inclusive, 0-based, supports negative indices)
- **Returns**: `{ key: string, start: number, stop: number, elements: string[], count: number }`
- **Notes**: Use start=0 and stop=-1 to get all elements. Indexing is zero-based and supports negative indices (-1 is last element).

#### redis_llen
Gets the length of a list.
- **Parameters**:
  - `key` (string, required): The list key
- **Returns**: `{ key: string, length: number }`

#### redis_lindex
Gets an element from a list by its index.
- **Parameters**:
  - `key` (string, required): The list key
  - `index` (number, required): The index of the element (0-based, supports negative indices)
- **Returns**: `{ key: string, index: number, value: string | null, exists: boolean }`
- **Notes**: Indexing is zero-based and supports negative indices (-1 is last element, -2 is second to last, etc.)

## Development

### Project Structure

```
redis-mcp-server/
├── package.json
├── README.md
├── .gitignore
├── .npmignore
├── .env.example
├── EXAMPLE_CONFIG.json
└── src/
    └── index.js       # Main server implementation
```

### Running Locally

To run the server locally for testing:

```bash
cd redis-mcp-server
npm start
```

The server will start listening on stdio, ready to communicate with MCP clients.

## Requirements

- Node.js 18+ (for ES modules support)
- Redis server running and accessible

## Best Practices

1. **Use appropriate data types**: Choose between strings, hashes, or lists based on your use case
   - Strings: Simple key-value pairs
   - Hashes: Objects with multiple fields (e.g., user profiles)
   - Lists: Ordered collections (e.g., logs, queues)

2. **Set TTL for temporary data**: Use the `ttl` parameter with `redis_set` or `redis_expire` for keys that should expire

3. **Use patterns wisely**: When using `redis_keys`, be specific with patterns to avoid performance issues on large datasets

4. **Hash fields for structured data**: Use hashes instead of multiple string keys for related data (e.g., `user:123:profile` with fields like name, email, age)

5. **List for queues**: Use `lpush` and `rpop` for FIFO queues, or `rpush` and `lpop` for LIFO stacks

## Error Handling

All tools return consistent error responses:
```json
{
  "error": "Error message",
  "success": false
}
```

Common errors:
- Invalid parameters: Missing or incorrectly typed parameters
- Connection errors: Redis server not reachable
- Authentication errors: Invalid password
- Key errors: Key does not exist (for operations that require it)

## License

ISC

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.