Skip to content

Commit 2390cce

Browse files
authored
Merge pull request #81 from redis/fix/json-anyof-schema
Fix: Simplify json_set schema to avoid anyOf operator
2 parents 0a69289 + abe017d commit 2390cce

File tree

1 file changed

+9
-30
lines changed

1 file changed

+9
-30
lines changed

src/tools/json.py

Lines changed: 9 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,59 +1,38 @@
11
import json
22
from typing import Optional
33
from redis.exceptions import RedisError
4-
from pydantic_core import core_schema
54

65
from src.common.connection import RedisConnectionManager
76
from src.common.server import mcp
87

98

10-
# Custom type that accepts any JSON value but generates a proper schema
11-
class JsonValue:
12-
"""Accepts any JSON-serializable value."""
13-
14-
@classmethod
15-
def __get_pydantic_core_schema__(cls, _source_type, _handler):
16-
"""Define how Pydantic should validate this type."""
17-
# Accept any value
18-
return core_schema.any_schema()
19-
20-
@classmethod
21-
def __get_pydantic_json_schema__(cls, _core_schema, _handler):
22-
"""Define the JSON schema for this type."""
23-
# Return a schema that accepts string, number, boolean, object, array, or null
24-
return {
25-
"anyOf": [
26-
{"type": "string"},
27-
{"type": "number"},
28-
{"type": "boolean"},
29-
{"type": "object"},
30-
{"type": "array", "items": {"type": "string"}},
31-
{"type": "null"},
32-
]
33-
}
34-
35-
369
@mcp.tool()
3710
async def json_set(
3811
name: str,
3912
path: str,
40-
value: JsonValue,
13+
value: str,
4114
expire_seconds: Optional[int] = None,
4215
) -> str:
4316
"""Set a JSON value in Redis at a given path with an optional expiration time.
4417
4518
Args:
4619
name: The Redis key where the JSON document is stored.
4720
path: The JSON path where the value should be set.
48-
value: The JSON value to store.
21+
value: The JSON value to store (as JSON string, or will be auto-converted).
4922
expire_seconds: Optional; time in seconds after which the key should expire.
5023
5124
Returns:
5225
A success message or an error message.
5326
"""
27+
# Try to parse the value as JSON, if it fails, treat it as a plain string
28+
try:
29+
parsed_value = json.loads(value)
30+
except (json.JSONDecodeError, TypeError):
31+
parsed_value = value
32+
5433
try:
5534
r = RedisConnectionManager.get_connection()
56-
r.json().set(name, path, value)
35+
r.json().set(name, path, parsed_value)
5736

5837
if expire_seconds is not None:
5938
r.expire(name, expire_seconds)

0 commit comments

Comments
 (0)