Skip to main content
Glama
lm203688

redis-mcp-server

by lm203688

get_key_value

Automatically detect the type of a Redis key and retrieve its value, supporting string, list, set, hash, and sorted set.

Instructions

自动识别键类型并获取值(支持string/list/set/hash/zset)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
keyYesRedis键名

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Core handler: RedisConnection.get_key_value() - auto-detects key type and delegates to the appropriate type-specific getter (string/list/set/hash/zset). This is the actual business logic implementation.
    def get_key_value(self, key: str) -> dict[str, Any]:
        """自动识别键类型并获取值"""
        key_info = self.get_key_type(key)
        key_type = key_info["type"]
    
        if key_type == "string":
            return self.get_string(key)
        elif key_type == "list":
            return self.get_list(key)
        elif key_type == "set":
            return self.get_set(key)
        elif key_type == "hash":
            return self.get_hash(key)
        elif key_type == "zset":
            return self.get_zset(key)
        else:
            return {"key": key, "type": key_type, "note": f"暂不支持 {key_type} 类型的自动读取"}
  • MCP tool registration via @mcp.tool() decorator wrapping get_key_value, with docstring describing it auto-detects key type and fetches value.
    @mcp.tool()
    def get_key_value(key: str) -> str:
        """自动识别键类型并获取值(支持string/list/set/hash/zset)
    
        Args:
            key: Redis键名
        """
        try:
            result = db.get_key_value(key)
            return json.dumps(result, ensure_ascii=False, indent=2, default=str)
        except PermissionError as e:
            return json.dumps({"error": str(e)}, ensure_ascii=False)
        except Exception as e:
            return json.dumps({"error": str(e)}, ensure_ascii=False)
  • Input schema: accepts 'key: str' parameter. Output schema: returns JSON string with key, type, value (or fields/members for complex types), and metadata.
    @mcp.tool()
    def get_key_value(key: str) -> str:
        """自动识别键类型并获取值(支持string/list/set/hash/zset)
    
        Args:
            key: Redis键名
        """
        try:
            result = db.get_key_value(key)
            return json.dumps(result, ensure_ascii=False, indent=2, default=str)
        except PermissionError as e:
            return json.dumps({"error": str(e)}, ensure_ascii=False)
        except Exception as e:
            return json.dumps({"error": str(e)}, ensure_ascii=False)
    
    
    @mcp.tool()
    def get_hash(key: str) -> str:
        """获取哈希类型的所有字段和值
    
        Args:
            key: Redis键名
        """
        try:
            result = db.get_hash(key)
            return json.dumps(result, ensure_ascii=False, indent=2, default=str)
        except PermissionError as e:
            return json.dumps({"error": str(e)}, ensure_ascii=False)
        except Exception as e:
            return json.dumps({"error": str(e)}, ensure_ascii=False)
    
    
    @mcp.tool()
    def get_memory_usage(key: str) -> str:
        """获取键的内存使用量
    
        Args:
            key: Redis键名
        """
        try:
            result = db.get_memory_usage(key)
            return json.dumps(result, ensure_ascii=False, indent=2)
        except PermissionError as e:
            return json.dumps({"error": str(e)}, ensure_ascii=False)
        except Exception as e:
            return json.dumps({"error": str(e)}, ensure_ascii=False)
    
    
    @mcp.tool()
    def set_string(key: str, value: str, ex: Optional[int] = None) -> str:
        """设置字符串值(需要关闭只读模式)
    
        Args:
            key: Redis键名
            value: 要设置的值
            ex: 过期时间(秒),不填则永不过期
        """
        try:
            result = db.set_string(key, value, ex)
            return json.dumps(result, ensure_ascii=False, indent=2)
        except PermissionError as e:
            return json.dumps({"error": str(e)}, ensure_ascii=False)
        except Exception as e:
            return json.dumps({"error": str(e)}, ensure_ascii=False)
    
    
    @mcp.tool()
    def delete_keys(keys: list[str]) -> str:
        """删除键(需要关闭只读模式)
    
        Args:
            keys: 要删除的键名列表
        """
        try:
            result = db.delete_keys(keys)
            return json.dumps(result, ensure_ascii=False, indent=2)
        except PermissionError as e:
            return json.dumps({"error": str(e)}, ensure_ascii=False)
        except Exception as e:
            return json.dumps({"error": str(e)}, ensure_ascii=False)
    
    
    @mcp.tool()
    def set_expire(key: str, seconds: int) -> str:
        """设置键的过期时间(需要关闭只读模式)
    
        Args:
            key: Redis键名
            seconds: 过期时间(秒)
        """
        try:
            result = db.set_expire(key, seconds)
            return json.dumps(result, ensure_ascii=False, indent=2)
        except PermissionError as e:
            return json.dumps({"error": str(e)}, ensure_ascii=False)
        except Exception as e:
            return json.dumps({"error": str(e)}, ensure_ascii=False)
    
    
    # ============================================================
    # 提示词(Prompts)
    # ============================================================
    
    
    @mcp.prompt()
    def analyze_redis() -> str:
        """生成Redis分析提示词"""
        return """请分析Redis实例的状态:
    
    1. 使用 server_info 获取服务器信息
    2. 使用 db_size 查看键数量
    3. 使用 scan_keys 查看键的分布模式
    4. 对重要键使用 get_key_type 和 get_key_value 查看内容
    5. 使用 get_memory_usage 分析内存占用
    6. 总结Redis的使用情况、内存分布、键模式
    7. 提出优化建议(如有)
    
    请用中文回答。"""
    
    
    @mcp.prompt()
    def find_keys_by_pattern(pattern: str) -> str:
        """生成键搜索提示词"""
        return f"""请搜索Redis中匹配 '{pattern}' 的键:
    
    1. 使用 scan_keys 搜索匹配的键
    2. 对每个键使用 get_key_type 查看类型
    3. 对重要键使用 get_key_value 查看值
    4. 使用 get_memory_usage 查看内存占用
    5. 总结搜索结果
    
    请用中文回答。"""
  • Helper: get_key_type() - called by get_key_value to determine the Redis type before dispatching.
    def get_key_type(self, key: str) -> dict[str, Any]:
        """获取键的类型"""
        if not self._is_key_allowed(key):
            raise PermissionError(f"键 '{key}' 不允许访问")
        key_type = self._client.type(key)
        ttl = self._client.ttl(key)
        return {
            "key": key,
            "type": key_type,
            "ttl": ttl if ttl >= 0 else ("永不过期" if ttl == -1 else "键不存在"),
        }
Behavior2/5

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

No annotations are provided, so the description carries the burden. It describes a read operation ('get value') but does not explicitly state safety, idempotency, side effects, or required permissions. With an agent needing this info, the description is insufficient.

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

Conciseness4/5

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

The description is a single concise sentence that conveys the core functionality and supported types. Every word adds value, though it could be slightly expanded for completeness.

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

Completeness3/5

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

The description covers the main purpose and supported types, but lacks details on error scenarios (e.g., non-existent key) and whether the tool is read-only. An output schema exists, which may mitigate some gaps, but overall completeness is average.

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

Parameters3/5

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

Schema coverage is 100% with a brief parameter description. The tool description adds context about type handling but does not enhance the parameter's meaning beyond the schema. Baseline 3 is appropriate.

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 that the tool automatically identifies the key type and retrieves the value, listing supported types (string/list/set/hash/zset). This distinguishes it from sibling tools like get_hash (specific to hash) and get_key_type (only returns type).

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

Usage Guidelines3/5

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

The description implies usage for any Redis key when the type is unknown, but it does not explicitly state when to use this tool versus alternatives like get_hash or set_string. No exclusions or context are provided.

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/lm203688/redis-mcp-server'

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