|
1 | 1 | from common.connection import RedisConnectionManager |
2 | 2 | from redis.exceptions import RedisError |
3 | 3 | from common.server import mcp |
| 4 | +import numpy as np |
4 | 5 |
|
5 | 6 |
|
6 | 7 | @mcp.tool() |
@@ -97,3 +98,55 @@ async def hexists(name: str, key: str) -> bool: |
97 | 98 | return r.hexists(name, key) |
98 | 99 | except RedisError as e: |
99 | 100 | return f"Error checking existence of field '{key}' in hash '{name}': {str(e)}" |
| 101 | + |
| 102 | +@mcp.tool() |
| 103 | +async def set_vector_in_hash(name: str, key: str, vector: list) -> bool: |
| 104 | + """Store a vector as a field in a Redis hash. |
| 105 | +
|
| 106 | + Args: |
| 107 | + name: The Redis hash key. |
| 108 | + key: The field name inside the hash. |
| 109 | + vector: The vector (list of numbers) to store in the hash. |
| 110 | +
|
| 111 | + Returns: |
| 112 | + True if the vector was successfully stored, False otherwise. |
| 113 | + """ |
| 114 | + try: |
| 115 | + r = RedisConnectionManager.get_connection() |
| 116 | + |
| 117 | + # Convert the vector to a NumPy array, then to a binary blob using np.float32 |
| 118 | + vector_array = np.array(vector, dtype=np.float32) |
| 119 | + binary_blob = vector_array.tobytes() |
| 120 | + |
| 121 | + r.hset(name, key, binary_blob) |
| 122 | + return True |
| 123 | + except RedisError as e: |
| 124 | + return f"Error storing vector in hash '{name}' with key '{key}': {str(e)}" |
| 125 | + |
| 126 | + |
| 127 | +@mcp.tool() |
| 128 | +async def get_vector_from_hash(name: str, key: str): |
| 129 | + """Retrieve a vector from a Redis hash and convert it back from binary blob. |
| 130 | +
|
| 131 | + Args: |
| 132 | + name: The Redis hash key. |
| 133 | + key: The field name inside the hash. |
| 134 | +
|
| 135 | + Returns: |
| 136 | + The vector as a list of floats, or an error message if retrieval fails. |
| 137 | + """ |
| 138 | + try: |
| 139 | + r = RedisConnectionManager.get_connection(decode_responses=False) |
| 140 | + |
| 141 | + # Retrieve the binary blob stored in the hash |
| 142 | + binary_blob = r.hget(name, key) |
| 143 | + |
| 144 | + if binary_blob: |
| 145 | + # Convert the binary blob back to a NumPy array (assuming it's stored as float32) |
| 146 | + vector_array = np.frombuffer(binary_blob, dtype=np.float32) |
| 147 | + return vector_array.tolist() |
| 148 | + else: |
| 149 | + return f"Field '{key}' not found in hash '{name}'." |
| 150 | + |
| 151 | + except RedisError as e: |
| 152 | + return f"Error retrieving vector from hash '{name}' with key '{key}': {str(e)}" |
0 commit comments