Skip to main content
Glama
redis

Redis MCP Server

Official
by redis

sadd

Add a value to a Redis set, optionally setting a TTL in seconds for automatic removal.

Instructions

Add a value to a Redis set with an optional expiration time.

Args: name: The Redis set key. value: The value to add to the set. expire_seconds: Optional; time in seconds after which the set should expire.

Returns: A success message or an error message.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
nameYes
valueYes
expire_secondsNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The 'sadd' tool handler function. Decorated with @mcp.tool(), it adds a value to a Redis set with optional expiration. Uses RedisConnectionManager.get_connection() to get the Redis client and calls r.sadd(name, value). Returns a success/error message string.
    @mcp.tool()
    async def sadd(name: str, value: str, expire_seconds: Optional[int] = None) -> str:
        """Add a value to a Redis set with an optional expiration time.
    
        Args:
            name: The Redis set key.
            value: The value to add to the set.
            expire_seconds: Optional; time in seconds after which the set should expire.
    
        Returns:
            A success message or an error message.
        """
        try:
            r = RedisConnectionManager.get_connection()
            r.sadd(name, value)
    
            if expire_seconds is not None:
                r.expire(name, expire_seconds)
    
            return f"Value '{value}' added successfully to set '{name}'." + (
                f" Expires in {expire_seconds} seconds." if expire_seconds else ""
            )
        except RedisError as e:
            return f"Error adding value '{value}' to set '{name}': {str(e)}"
  • Tool registration mechanism. The load_tools() function dynamically imports all modules in src/tools, including src/tools/set.py. The FastMCP instance 'mcp' is created and tools are loaded via @mcp.tool() decorator.
    def load_tools():
        import src.tools as tools_pkg
    
        for _, module_name, _ in pkgutil.iter_modules(tools_pkg.__path__):
            importlib.import_module(f"src.tools.{module_name}")
    
    
    # Initialize FastMCP server
    mcp = FastMCP(
        "Redis MCP Server", dependencies=["redis", "python-dotenv", "numpy", "aiohttp"]
    )
    
    # Load tools
    load_tools()
  • RedisConnectionManager.get_connection() is used by the sadd handler to obtain a Redis client instance.
    class RedisConnectionManager:
        _instance: Optional[Redis] = None
    
        @classmethod
        def get_connection(cls, decode_responses=True) -> Redis:
            if cls._instance is None:
                try:
                    # Create Entra ID credential provider if configured
                    credential_provider = None
                    if is_entraid_auth_enabled():
                        try:
                            credential_provider = create_credential_provider()
                        except EntraIDAuthenticationError as e:
                            _logger.error(
                                "Failed to create Entra ID credential provider: %s", e
                            )
                            raise
    
                    if REDIS_CFG["cluster_mode"]:
                        redis_class: Type[Union[Redis, RedisCluster]] = (
                            redis.cluster.RedisCluster
                        )
                        connection_params = {
                            "host": REDIS_CFG["host"],
                            "port": REDIS_CFG["port"],
                            "username": REDIS_CFG["username"],
                            "password": REDIS_CFG["password"],
                            "ssl": REDIS_CFG["ssl"],
                            "ssl_ca_path": REDIS_CFG["ssl_ca_path"],
                            "ssl_keyfile": REDIS_CFG["ssl_keyfile"],
                            "ssl_certfile": REDIS_CFG["ssl_certfile"],
                            "ssl_cert_reqs": REDIS_CFG["ssl_cert_reqs"],
                            "ssl_ca_certs": REDIS_CFG["ssl_ca_certs"],
                            "decode_responses": decode_responses,
                            "lib_name": f"redis-py(mcp-server_v{__version__})",
                            "max_connections_per_node": 10,
                        }
    
                        # Add credential provider if available
                        if credential_provider:
                            connection_params["credential_provider"] = credential_provider
                            # Note: Azure Redis Enterprise with EntraID uses plain text connections
                            # SSL setting is controlled by REDIS_SSL environment variable
                    else:
                        redis_class: Type[Union[Redis, RedisCluster]] = redis.Redis
                        connection_params = {
                            "host": REDIS_CFG["host"],
                            "port": REDIS_CFG["port"],
                            "db": REDIS_CFG["db"],
                            "username": REDIS_CFG["username"],
                            "password": REDIS_CFG["password"],
                            "ssl": REDIS_CFG["ssl"],
                            "ssl_ca_path": REDIS_CFG["ssl_ca_path"],
                            "ssl_keyfile": REDIS_CFG["ssl_keyfile"],
                            "ssl_certfile": REDIS_CFG["ssl_certfile"],
                            "ssl_cert_reqs": REDIS_CFG["ssl_cert_reqs"],
                            "ssl_ca_certs": REDIS_CFG["ssl_ca_certs"],
                            "decode_responses": decode_responses,
                            "lib_name": f"redis-py(mcp-server_v{__version__})",
                            "max_connections": 10,
                        }
    
                        # Add credential provider if available
                        if credential_provider:
                            connection_params["credential_provider"] = credential_provider
                            # Note: Azure Redis Enterprise with EntraID uses plain text connections
                            # SSL setting is controlled by REDIS_SSL environment variable
    
                    cls._instance = redis_class(**connection_params)
    
                except redis.exceptions.ConnectionError:
                    _logger.error("Failed to connect to Redis server")
                    raise
                except redis.exceptions.AuthenticationError:
                    _logger.error("Authentication failed")
                    raise
                except redis.exceptions.TimeoutError:
                    _logger.error("Connection timed out")
                    raise
                except redis.exceptions.ResponseError as e:
                    _logger.error("Response error: %s", e)
                    raise
                except redis.exceptions.RedisError as e:
                    _logger.error("Redis error: %s", e)
                    raise
                except redis.exceptions.ClusterError as e:
                    _logger.error("Redis Cluster error: %s", e)
                    raise
                except Exception as e:
                    _logger.error("Unexpected error: %s", e)
                    raise
    
            return cls._instance
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations exist, so the description must convey behavioral traits. It discloses that the tool adds a value (mutation) and optionally sets expiration. However, it does not mention how duplicates are handled (e.g., idempotent for existing members) or any side effects like creating the set if absent.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is very concise, using a clear docstring format with Args and Returns sections. Every sentence adds information without redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Although not exhaustive (e.g., no error conditions), the description covers the core operation, parameters, and return type. Given the tool's simplicity and the presence of siblings for context, it is mostly complete.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 0% description coverage, so the description compensates by explaining each parameter's meaning (name as key, value to add, expire_seconds as optional TTL). This adds essential value beyond the schema's type constraints.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action: 'Add a value to a Redis set with an optional expiration time.' It uses a specific verb (add) and resource (Redis set), and distinguishes from sibling set operations like srem (remove) or smembers (list).

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance is provided on when to use this tool versus alternatives, such as when to use srem or smembers. The description lacks explicit context for tool selection.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/redis/mcp-redis'

If you have feedback or need assistance with the MCP directory API, please join our Discord server