From a8d835a8b75ee553007092d6405ba9af632201da Mon Sep 17 00:00:00 2001 From: Vishal Bala Date: Fri, 30 Oct 2026 13:50:09 +0100 Subject: [PATCH 1/7] fix(mcp): map wrapped load failures by their cause AsyncSearchIndex.load wraps every non-validation failure, a lost connection included, in a plain RedisVLError, which map_exception sent to a non-retryable internal_error. map_exception now classifies a RedisVLError wrapper by its __cause__ and keeps the wrapper's message, and maps SchemaValidationError to invalid_request. FastMCP sends clients only the error message, not the code or metadata, so upsert-records now says in the message when a failed write may have landed partially, and that a retry without id_field duplicates records. --- redisvl/mcp/errors.py | 13 ++++++++-- redisvl/mcp/tools/upsert.py | 18 ++++++++++++-- tests/unit/test_mcp/test_errors.py | 25 +++++++++++++++++++- tests/unit/test_mcp/test_upsert_tool_unit.py | 15 ++++++++++++ 4 files changed, 66 insertions(+), 5 deletions(-) diff --git a/redisvl/mcp/errors.py b/redisvl/mcp/errors.py index aae49576b..6f22449a4 100644 --- a/redisvl/mcp/errors.py +++ b/redisvl/mcp/errors.py @@ -5,7 +5,7 @@ from pydantic import ValidationError from redis.exceptions import RedisError -from redisvl.exceptions import RedisSearchError +from redisvl.exceptions import RedisSearchError, RedisVLError, SchemaValidationError class MCPErrorCode(str, Enum): @@ -41,7 +41,9 @@ def map_exception(exc: Exception) -> RedisVLMCPError: if isinstance(exc, RedisVLMCPError): return exc - if isinstance(exc, (ValidationError, ValueError, FileNotFoundError)): + if isinstance( + exc, (ValidationError, SchemaValidationError, ValueError, FileNotFoundError) + ): return RedisVLMCPError( str(exc), code=MCPErrorCode.INVALID_REQUEST, @@ -64,6 +66,13 @@ def map_exception(exc: Exception) -> RedisVLMCPError: retryable=True, ) + # Index methods such as ``load`` wrap whatever went wrong in a plain + # ``RedisVLError``. Classify by the cause, so a lost connection stays retryable, + # but keep the wrapper's message, which says which operation failed. + if isinstance(exc, RedisVLError) and isinstance(exc.__cause__, Exception): + cause = map_exception(exc.__cause__) + return RedisVLMCPError(str(exc), code=cause.code, retryable=cause.retryable) + return RedisVLMCPError( str(exc), code=MCPErrorCode.INTERNAL_ERROR, diff --git a/redisvl/mcp/tools/upsert.py b/redisvl/mcp/tools/upsert.py index f079e923c..c746d3da1 100644 --- a/redisvl/mcp/tools/upsert.py +++ b/redisvl/mcp/tools/upsert.py @@ -345,8 +345,22 @@ async def upsert_records( ) except Exception as exc: mapped = map_exception(exc) - mapped.metadata["partial_write_possible"] = True - raise mapped from exc + # load validates every record before it writes any, so a rejected + # request wrote nothing. Anything else may have failed mid-write, and + # clients only see the message, so the warning goes there. + if mapped.code is MCPErrorCode.INVALID_REQUEST: + raise mapped from exc + warning = "some records may already have been written" + if id_field is None: + warning += ( + "; retrying without id_field writes them again under new keys" + ) + raise RedisVLMCPError( + f"{mapped}; {warning}", + code=mapped.code, + retryable=mapped.retryable, + metadata={**mapped.metadata, "partial_write_possible": True}, + ) from exc return { "index": rt.binding_id, diff --git a/tests/unit/test_mcp/test_errors.py b/tests/unit/test_mcp/test_errors.py index ddd286224..fa1795b94 100644 --- a/tests/unit/test_mcp/test_errors.py +++ b/tests/unit/test_mcp/test_errors.py @@ -1,7 +1,9 @@ +import pytest from pydantic import BaseModel, ValidationError from redis.exceptions import ConnectionError as RedisConnectionError +from redis.exceptions import TimeoutError as RedisTimeoutError -from redisvl.exceptions import RedisSearchError +from redisvl.exceptions import RedisSearchError, RedisVLError, SchemaValidationError from redisvl.mcp.errors import MCPErrorCode, RedisVLMCPError, map_exception @@ -59,6 +61,27 @@ def test_timeout_error_maps_to_backend_unavailable(): assert mapped.retryable is True +@pytest.mark.parametrize( + "cause", [RedisConnectionError("down"), RedisTimeoutError("slow")] +) +def test_wrapped_redis_errors_map_by_their_cause(cause): + try: + raise RedisVLError("Failed to load data") from cause + except RedisVLError as exc: + mapped = map_exception(exc) + + assert mapped.code == MCPErrorCode.BACKEND_UNAVAILABLE + assert mapped.retryable is True + assert str(mapped) == "Failed to load data" + + +def test_schema_validation_error_maps_to_invalid_request(): + mapped = map_exception(SchemaValidationError("bad record", index=0)) + + assert mapped.code == MCPErrorCode.INVALID_REQUEST + assert mapped.retryable is False + + def test_unknown_errors_map_to_internal_error(): mapped = map_exception(RuntimeError("unexpected")) diff --git a/tests/unit/test_mcp/test_upsert_tool_unit.py b/tests/unit/test_mcp/test_upsert_tool_unit.py index 2327af903..8848ae366 100644 --- a/tests/unit/test_mcp/test_upsert_tool_unit.py +++ b/tests/unit/test_mcp/test_upsert_tool_unit.py @@ -4,6 +4,7 @@ import pytest from redis.exceptions import RedisError +from redisvl.exceptions import SchemaValidationError from redisvl.mcp.config import MCPConfig from redisvl.mcp.errors import MCPErrorCode, RedisVLMCPError from redisvl.mcp.runtime import BindingRuntime @@ -464,6 +465,20 @@ async def test_upsert_records_surfaces_partial_write_possible_on_backend_failure assert exc_info.value.code == MCPErrorCode.BACKEND_UNAVAILABLE assert exc_info.value.metadata["partial_write_possible"] is True assert isinstance(exc_info.value.__cause__, RedisError) + assert "may already have been written" in str(exc_info.value) + assert "without id_field writes them again" in str(exc_info.value) + + +@pytest.mark.asyncio +async def test_upsert_records_rejected_load_does_not_warn_of_partial_write(): + server = FakeServer() + server.index.load_exception = SchemaValidationError("bad record", index=0) + + with pytest.raises(RedisVLMCPError) as exc_info: + await upsert_records(server, records=[{"content": "alpha doc"}]) + + assert exc_info.value.code == MCPErrorCode.INVALID_REQUEST + assert "written" not in str(exc_info.value) @pytest.mark.asyncio From 31c8039859ec1220f18ed892fac3bd2cb081071b Mon Sep 17 00:00:00 2001 From: Vishal Bala Date: Fri, 30 Oct 2026 13:57:07 +0100 Subject: [PATCH 2/7] fix(mcp): retry only transient wrapped errors; warn only after load ran A wrapped WRONGTYPE or OOM reply from load fails the same way on every retry, so only a wrapped connection or timeout error maps to a retryable backend_unavailable; other wrapped Redis errors stay non-retryable. upsert-records no longer warns of a partial write when run_guarded refused the call before load ran. Document in the how-to that a failed write may be partial and that id_field makes a retry overwrite. --- docs/user_guide/how_to_guides/mcp.md | 1 + redisvl/mcp/errors.py | 19 +++++++--- redisvl/mcp/tools/upsert.py | 12 ++++--- tests/unit/test_mcp/test_errors.py | 11 ++++++ tests/unit/test_mcp/test_upsert_tool_unit.py | 38 ++++++++++++++------ 5 files changed, 62 insertions(+), 19 deletions(-) diff --git a/docs/user_guide/how_to_guides/mcp.md b/docs/user_guide/how_to_guides/mcp.md index a64fc4743..8aaa6967b 100644 --- a/docs/user_guide/how_to_guides/mcp.md +++ b/docs/user_guide/how_to_guides/mcp.md @@ -670,6 +670,7 @@ Notes: - when server-side embedding is configured, records that need embedding must contain `runtime.default_embed_text_field` - when `skip_embedding_if_present` is `true`, records that already contain the configured vector field can skip re-embedding - when a vector field is configured but server-side embedding is disabled, callers must supply vectors explicitly +- a write that fails part-way, for example on a lost connection, may already have stored some records, and the error message says so. Pass `id_field` so a retry overwrites those records instead of storing them again under new keys ## Search Examples diff --git a/redisvl/mcp/errors.py b/redisvl/mcp/errors.py index 6f22449a4..17fc06320 100644 --- a/redisvl/mcp/errors.py +++ b/redisvl/mcp/errors.py @@ -3,7 +3,9 @@ from typing import Any from pydantic import ValidationError +from redis.exceptions import ConnectionError as RedisConnectionError from redis.exceptions import RedisError +from redis.exceptions import TimeoutError as RedisTimeoutError from redisvl.exceptions import RedisSearchError, RedisVLError, SchemaValidationError @@ -67,11 +69,18 @@ def map_exception(exc: Exception) -> RedisVLMCPError: ) # Index methods such as ``load`` wrap whatever went wrong in a plain - # ``RedisVLError``. Classify by the cause, so a lost connection stays retryable, - # but keep the wrapper's message, which says which operation failed. - if isinstance(exc, RedisVLError) and isinstance(exc.__cause__, Exception): - cause = map_exception(exc.__cause__) - return RedisVLMCPError(str(exc), code=cause.code, retryable=cause.retryable) + # ``RedisVLError``. A lost connection or a timeout under that wrapper is still + # worth retrying. Other wrapped Redis errors, such as WRONGTYPE or OOM, would + # fail the same way again, so they stay non-retryable. + if isinstance(exc, RedisVLError) and isinstance( + exc.__cause__, + (RedisConnectionError, RedisTimeoutError, TimeoutError, asyncio.TimeoutError), + ): + return RedisVLMCPError( + str(exc), + code=MCPErrorCode.BACKEND_UNAVAILABLE, + retryable=True, + ) return RedisVLMCPError( str(exc), diff --git a/redisvl/mcp/tools/upsert.py b/redisvl/mcp/tools/upsert.py index c746d3da1..36e4d0ae1 100644 --- a/redisvl/mcp/tools/upsert.py +++ b/redisvl/mcp/tools/upsert.py @@ -3,6 +3,7 @@ from copy import deepcopy from typing import Any +from redisvl.exceptions import RedisVLError from redisvl.mcp.auth import ensure_write_scope from redisvl.mcp.errors import MCPErrorCode, RedisVLMCPError, map_exception from redisvl.redis.utils import array_to_buffer @@ -345,10 +346,13 @@ async def upsert_records( ) except Exception as exc: mapped = map_exception(exc) - # load validates every record before it writes any, so a rejected - # request wrote nothing. Anything else may have failed mid-write, and - # clients only see the message, so the warning goes there. - if mapped.code is MCPErrorCode.INVALID_REQUEST: + # load raises its invalid_request errors before it writes anything, + # and run_guarded's own errors mean load never ran. Any other load + # failure, or a timeout, may have left records behind. Clients see + # only the message, so the warning goes there. + if mapped.code is MCPErrorCode.INVALID_REQUEST or not isinstance( + exc, (RedisVLError, TimeoutError, asyncio.TimeoutError) + ): raise mapped from exc warning = "some records may already have been written" if id_field is None: diff --git a/tests/unit/test_mcp/test_errors.py b/tests/unit/test_mcp/test_errors.py index fa1795b94..c5dfa9a65 100644 --- a/tests/unit/test_mcp/test_errors.py +++ b/tests/unit/test_mcp/test_errors.py @@ -1,6 +1,7 @@ import pytest from pydantic import BaseModel, ValidationError from redis.exceptions import ConnectionError as RedisConnectionError +from redis.exceptions import ResponseError from redis.exceptions import TimeoutError as RedisTimeoutError from redisvl.exceptions import RedisSearchError, RedisVLError, SchemaValidationError @@ -75,6 +76,16 @@ def test_wrapped_redis_errors_map_by_their_cause(cause): assert str(mapped) == "Failed to load data" +def test_wrapped_redis_reply_errors_stay_non_retryable(): + try: + raise RedisVLError("Failed to load data") from ResponseError("WRONGTYPE") + except RedisVLError as exc: + mapped = map_exception(exc) + + assert mapped.code == MCPErrorCode.INTERNAL_ERROR + assert mapped.retryable is False + + def test_schema_validation_error_maps_to_invalid_request(): mapped = map_exception(SchemaValidationError("bad record", index=0)) diff --git a/tests/unit/test_mcp/test_upsert_tool_unit.py b/tests/unit/test_mcp/test_upsert_tool_unit.py index 8848ae366..faff3dd7e 100644 --- a/tests/unit/test_mcp/test_upsert_tool_unit.py +++ b/tests/unit/test_mcp/test_upsert_tool_unit.py @@ -2,9 +2,9 @@ from typing import Any import pytest -from redis.exceptions import RedisError +from redis.exceptions import ConnectionError as RedisConnectionError -from redisvl.exceptions import SchemaValidationError +from redisvl.exceptions import RedisVLError, SchemaValidationError from redisvl.mcp.config import MCPConfig from redisvl.mcp.errors import MCPErrorCode, RedisVLMCPError from redisvl.mcp.runtime import BindingRuntime @@ -455,29 +455,47 @@ async def test_upsert_records_validates_non_vector_fields_before_embedding(): @pytest.mark.asyncio -async def test_upsert_records_surfaces_partial_write_possible_on_backend_failures(): +@pytest.mark.parametrize("id_field", [None, "id"]) +async def test_upsert_records_surfaces_partial_write_possible_on_backend_failures( + id_field, +): server = FakeServer() - server.index.load_exception = RedisError("boom") + try: + raise RedisVLError("Failed to load data") from RedisConnectionError("down") + except RedisVLError as exc: + server.index.load_exception = exc with pytest.raises(RedisVLMCPError) as exc_info: - await upsert_records(server, records=[{"content": "alpha doc"}]) + await upsert_records( + server, records=[{"id": "a", "content": "alpha doc"}], id_field=id_field + ) assert exc_info.value.code == MCPErrorCode.BACKEND_UNAVAILABLE + assert exc_info.value.retryable is True assert exc_info.value.metadata["partial_write_possible"] is True - assert isinstance(exc_info.value.__cause__, RedisError) assert "may already have been written" in str(exc_info.value) - assert "without id_field writes them again" in str(exc_info.value) + assert ("without id_field" in str(exc_info.value)) is (id_field is None) @pytest.mark.asyncio -async def test_upsert_records_rejected_load_does_not_warn_of_partial_write(): +@pytest.mark.parametrize( + "error, code", + [ + # load rejects bad records before it writes any. + (SchemaValidationError("bad record", index=0), MCPErrorCode.INVALID_REQUEST), + # run_guarded refuses before load runs. + (RuntimeError("MCP server is not running"), MCPErrorCode.INTERNAL_ERROR), + ], +) +async def test_upsert_records_does_not_warn_when_nothing_was_written(error, code): server = FakeServer() - server.index.load_exception = SchemaValidationError("bad record", index=0) + server.index.load_exception = error with pytest.raises(RedisVLMCPError) as exc_info: await upsert_records(server, records=[{"content": "alpha doc"}]) - assert exc_info.value.code == MCPErrorCode.INVALID_REQUEST + assert exc_info.value.code == code + assert "partial_write_possible" not in exc_info.value.metadata assert "written" not in str(exc_info.value) From f6db189b6f5c732378bd339a559f7790ff86724f Mon Sep 17 00:00:00 2001 From: Vishal Bala Date: Thu, 5 Nov 2026 13:50:19 +0100 Subject: [PATCH 3/7] fix(mcp): warn of partial writes from code tools too The code-tools stack now on main maps a tool's exceptions through map_exception, so a lost connection during ctx.index.load is a retryable backend_unavailable. A retry runs the whole tool again, so a tool declared with writes=True now warns in the message, on any retryable error the server maps, that it may already have written records. The warning moves into with_partial_write_warning, shared with upsert-records. docs/concepts/mcp.md no longer says a lost connection during ctx.index.load is a non-retryable internal_error. --- docs/concepts/mcp.md | 2 +- redisvl/mcp/errors.py | 14 ++++++++++ redisvl/mcp/tools/code.py | 31 +++++++++++++++++---- redisvl/mcp/tools/upsert.py | 17 ++++++----- tests/unit/test_mcp/test_code_tools_unit.py | 24 ++++++++++++++++ 5 files changed, 72 insertions(+), 16 deletions(-) diff --git a/docs/concepts/mcp.md b/docs/concepts/mcp.md index bc82ea9c3..0784c8295 100644 --- a/docs/concepts/mcp.md +++ b/docs/concepts/mcp.md @@ -321,7 +321,7 @@ The server applies the same rails as for a built-in, without the author asking f - Every `ctx.index` call takes a slot under the server-wide concurrency cap and is bounded by the binding's `runtime.request_timeout_seconds`. The cap is taken per call, so a tool that queries several times never blocks itself. - The whole tool call is bounded by the same timeout, so a tool cannot hold a request open indefinitely. A timeout returns a retryable `backend_unavailable` error. - A caller needs the server's read scope, and the write scope as well for a tool declared with `writes=True`, whose handle can both read and write. A tool can require an extra scope with `scope=`, which a caller must hold as well, so a code tool can be stricter than the built-ins but never looser. Like every scope, it is enforced only when the server has authentication configured. -- An exception the tool raises becomes a stable MCP error: `ValueError` becomes `invalid_request`, a Redis error from a search, aggregation or fetch a retryable `backend_unavailable`, and most other exceptions `internal_error`. That includes any failure of `ctx.index.load`, which reports even a lost connection as a non-retryable `internal_error`. Raise `RedisVLMCPError` to choose the code and message yourself. +- An exception the tool raises becomes a stable MCP error: `ValueError` becomes `invalid_request`, a Redis error from a search, aggregation or fetch a retryable `backend_unavailable`, and most other exceptions `internal_error`. A lost connection or timeout during `ctx.index.load` is a retryable `backend_unavailable`; any other `load` failure, such as a `WRONGTYPE` reply, is a non-retryable `internal_error`. When a tool declared with `writes=True` fails with a retryable error, the message warns that it may have written some records already, because a retry runs the whole tool again. Raise `RedisVLMCPError` to choose the code and message yourself; the server then adds no warning. The handle is a guardrail, not a sandbox. A code tool is your own code, running with the privileges of the process that started the server, and Python can still reach private attributes. What the handle does is make the bounded, policy-checked path the only obvious one. diff --git a/redisvl/mcp/errors.py b/redisvl/mcp/errors.py index 17fc06320..5999ab7b4 100644 --- a/redisvl/mcp/errors.py +++ b/redisvl/mcp/errors.py @@ -87,3 +87,17 @@ def map_exception(exc: Exception) -> RedisVLMCPError: code=MCPErrorCode.INTERNAL_ERROR, retryable=False, ) + + +def with_partial_write_warning(error: RedisVLMCPError, warning: str) -> RedisVLMCPError: + """Return ``error`` with a warning that a failed write may be partial. + + FastMCP sends a client the message alone, not ``code``, ``retryable`` or + ``metadata``, so the warning goes in the message. + """ + return RedisVLMCPError( + f"{error}; {warning}", + code=error.code, + retryable=error.retryable, + metadata={**error.metadata, "partial_write_possible": True}, + ) diff --git a/redisvl/mcp/tools/code.py b/redisvl/mcp/tools/code.py index 8641f4d33..792e5ab1c 100644 --- a/redisvl/mcp/tools/code.py +++ b/redisvl/mcp/tools/code.py @@ -26,7 +26,12 @@ from redisvl.mcp.auth import ensure_read_scope, ensure_tool_scope, ensure_write_scope from redisvl.mcp.config import validate_tool_name from redisvl.mcp.context import ToolContext -from redisvl.mcp.errors import MCPErrorCode, RedisVLMCPError, map_exception +from redisvl.mcp.errors import ( + MCPErrorCode, + RedisVLMCPError, + map_exception, + with_partial_write_warning, +) # Where `code_tool` leaves a function's spec for the loader to find. An attribute on # the function rather than a module-level registry, so importing a module @@ -193,6 +198,18 @@ def build_code_tool_spec( def register_code_tool(server: Any, spec: CodeToolSpec, binding_id: str) -> None: """Register one code tool against ``binding_id``.""" + def retryable_write_warned(error: RedisVLMCPError) -> RedisVLMCPError: + # A retry runs the whole tool again, including any writes it made + # before it failed. A tool that raises RedisVLMCPError itself has + # chosen its own message, so only errors mapped here get the warning. + if spec.writes and error.retryable: + return with_partial_write_warning( + error, + "the tool may have written some records before it failed, " + "and a retry runs it again", + ) + return error + async def code_tool(**kwargs: Any) -> Any: # Before anything else, so a caller without the scope never reaches the # binding or the function. The tool's own scope is required on top of @@ -221,15 +238,17 @@ async def code_tool(**kwargs: Any) -> Any: # code too, so a tool cannot hold a request open indefinitely. return await asyncio.wait_for(spec.fn(ctx, **kwargs), timeout) except asyncio.TimeoutError as exc: - raise RedisVLMCPError( - f"tool '{spec.name}' did not finish within {timeout:g}s", - code=MCPErrorCode.BACKEND_UNAVAILABLE, - retryable=True, + raise retryable_write_warned( + RedisVLMCPError( + f"tool '{spec.name}' did not finish within {timeout:g}s", + code=MCPErrorCode.BACKEND_UNAVAILABLE, + retryable=True, + ) ) from exc except RedisVLMCPError: raise except Exception as exc: - raise map_exception(exc) from exc + raise retryable_write_warned(map_exception(exc)) from exc code_tool.__name__ = spec.name.replace("-", "_") code_tool.__doc__ = spec.description diff --git a/redisvl/mcp/tools/upsert.py b/redisvl/mcp/tools/upsert.py index 36e4d0ae1..a307b4e47 100644 --- a/redisvl/mcp/tools/upsert.py +++ b/redisvl/mcp/tools/upsert.py @@ -5,7 +5,12 @@ from redisvl.exceptions import RedisVLError from redisvl.mcp.auth import ensure_write_scope -from redisvl.mcp.errors import MCPErrorCode, RedisVLMCPError, map_exception +from redisvl.mcp.errors import ( + MCPErrorCode, + RedisVLMCPError, + map_exception, + with_partial_write_warning, +) from redisvl.redis.utils import array_to_buffer from redisvl.schema.schema import StorageType from redisvl.schema.validation import validate_object @@ -348,8 +353,7 @@ async def upsert_records( mapped = map_exception(exc) # load raises its invalid_request errors before it writes anything, # and run_guarded's own errors mean load never ran. Any other load - # failure, or a timeout, may have left records behind. Clients see - # only the message, so the warning goes there. + # failure, or a timeout, may have left records behind. if mapped.code is MCPErrorCode.INVALID_REQUEST or not isinstance( exc, (RedisVLError, TimeoutError, asyncio.TimeoutError) ): @@ -359,12 +363,7 @@ async def upsert_records( warning += ( "; retrying without id_field writes them again under new keys" ) - raise RedisVLMCPError( - f"{mapped}; {warning}", - code=mapped.code, - retryable=mapped.retryable, - metadata={**mapped.metadata, "partial_write_possible": True}, - ) from exc + raise with_partial_write_warning(mapped, warning) from exc return { "index": rt.binding_id, diff --git a/tests/unit/test_mcp/test_code_tools_unit.py b/tests/unit/test_mcp/test_code_tools_unit.py index c645aeee5..e1fc14ff6 100644 --- a/tests/unit/test_mcp/test_code_tools_unit.py +++ b/tests/unit/test_mcp/test_code_tools_unit.py @@ -12,11 +12,13 @@ import pytest from conftest import _schema +from redis.exceptions import ConnectionError as RedisConnectionError fastmcp = pytest.importorskip( "fastmcp", reason="fastmcp not installed (install redisvl[mcp])" ) +from redisvl.exceptions import RedisVLError from redisvl.mcp.config import MCPConfig from redisvl.mcp.context import IndexHandle, ToolContext, WritableIndexHandle from redisvl.mcp.errors import MCPErrorCode, RedisVLMCPError @@ -454,6 +456,28 @@ async def failing(ctx: ToolContext, query: str) -> dict: assert exc_info.value is error +@pytest.mark.parametrize("writes", [True, False]) +@pytest.mark.parametrize( + "raised", [RedisVLError("Failed to load data"), asyncio.TimeoutError()] +) +async def test_only_a_writing_tool_warns_that_a_retryable_failure_may_be_partial( + monkeypatch, writes, raised +): + _as_caller(monkeypatch) + if isinstance(raised, RedisVLError): + raised.__cause__ = RedisConnectionError("down") + + async def failing(ctx: ToolContext, ticket_id: str) -> dict: + """Close a ticket.""" + raise raised + + with pytest.raises(RedisVLMCPError) as exc_info: + await _registered(failing, writes=writes)(ticket_id="t1") + + assert exc_info.value.retryable is True + assert ("may have written" in str(exc_info.value)) is writes + + # -------------------------------------------------------------------------- # @code_tool and the module loader # -------------------------------------------------------------------------- From 1188f05cf7a94f9e8a3517a063190bffcd9b958a Mon Sep 17 00:00:00 2001 From: Vishal Bala Date: Thu, 5 Nov 2026 13:53:23 +0100 Subject: [PATCH 4/7] fix(mcp): warn on every mapped failure of a writing code tool Clients see only the message, never the retry flag, so gating the code-tool warning on retryable hid a partial write behind a WRONGTYPE or OOM reply. A writes=True tool now warns on every error the server maps except invalid_request, matching upsert-records. The docs name the schema-validation, drop and expire cases, and the how-to tells authors who raise RedisVLMCPError that they get no warning. --- docs/concepts/mcp.md | 2 +- docs/user_guide/how_to_guides/mcp.md | 2 +- redisvl/mcp/tools/code.py | 20 ++++++------- tests/unit/test_mcp/test_code_tools_unit.py | 33 ++++++++++++++++----- 4 files changed, 38 insertions(+), 19 deletions(-) diff --git a/docs/concepts/mcp.md b/docs/concepts/mcp.md index 0784c8295..f0c614f1f 100644 --- a/docs/concepts/mcp.md +++ b/docs/concepts/mcp.md @@ -321,7 +321,7 @@ The server applies the same rails as for a built-in, without the author asking f - Every `ctx.index` call takes a slot under the server-wide concurrency cap and is bounded by the binding's `runtime.request_timeout_seconds`. The cap is taken per call, so a tool that queries several times never blocks itself. - The whole tool call is bounded by the same timeout, so a tool cannot hold a request open indefinitely. A timeout returns a retryable `backend_unavailable` error. - A caller needs the server's read scope, and the write scope as well for a tool declared with `writes=True`, whose handle can both read and write. A tool can require an extra scope with `scope=`, which a caller must hold as well, so a code tool can be stricter than the built-ins but never looser. Like every scope, it is enforced only when the server has authentication configured. -- An exception the tool raises becomes a stable MCP error: `ValueError` becomes `invalid_request`, a Redis error from a search, aggregation or fetch a retryable `backend_unavailable`, and most other exceptions `internal_error`. A lost connection or timeout during `ctx.index.load` is a retryable `backend_unavailable`; any other `load` failure, such as a `WRONGTYPE` reply, is a non-retryable `internal_error`. When a tool declared with `writes=True` fails with a retryable error, the message warns that it may have written some records already, because a retry runs the whole tool again. Raise `RedisVLMCPError` to choose the code and message yourself; the server then adds no warning. +- An exception the tool raises becomes a stable MCP error: `ValueError` becomes `invalid_request`, a Redis error from a search, aggregation, fetch, `drop_documents` or `expire_documents` a retryable `backend_unavailable`, and most other exceptions `internal_error`. From `ctx.index.load`, a record that fails schema validation is `invalid_request`, a lost connection or timeout a retryable `backend_unavailable`, and any other failure, such as a `WRONGTYPE` reply, a non-retryable `internal_error`. For a tool declared with `writes=True`, every one of these except `invalid_request` also warns, in the message, that the tool may have written some records before it failed. Raise `RedisVLMCPError` to choose the code and message yourself; the server then adds no warning. The handle is a guardrail, not a sandbox. A code tool is your own code, running with the privileges of the process that started the server, and Python can still reach private attributes. What the handle does is make the bounded, policy-checked path the only obvious one. diff --git a/docs/user_guide/how_to_guides/mcp.md b/docs/user_guide/how_to_guides/mcp.md index 8aaa6967b..094f725be 100644 --- a/docs/user_guide/how_to_guides/mcp.md +++ b/docs/user_guide/how_to_guides/mcp.md @@ -464,7 +464,7 @@ Rules worth knowing: - **A code tool reaches Redis only through `ctx.index`.** It has the read methods, plus a handful of bounded writes for a tool registered with `writes=True`. Records are addressed by document id, never by full Redis key, so a tool stays under its index's key prefix. That does not separate indexes whose prefixes overlap, and a prefix that is empty or made only of separator characters covers every key. On an index with several prefixes, ids address the first prefix only. `load` returns document ids, and `ctx.index.document_id(hit["id"])` turns a search result's key into one. On JSON storage, give a `FilterQuery` `return_fields`, or a document's own `id` field replaces the key in its results. There is no Redis client and no way to create, drop or clear the index. - **Writing tools need a cast for type checkers.** `ctx.index` is typed as `IndexHandle`. In a tool registered with `writes=True`, `cast(WritableIndexHandle, ctx.index)` gives a type checker the write methods, as `delete-spam-ticket` shows. Both types are exported from `redisvl.mcp`. - **Every call is bounded.** Each `ctx.index` call takes a slot under the concurrency cap and the binding's `request_timeout_seconds`, and the whole tool call is bounded by the same timeout. -- **Raise to report a problem.** A `ValueError` reaches the client as `invalid_request`; raise `RedisVLMCPError` to choose the error code yourself. +- **Raise to report a problem.** A `ValueError` reaches the client as `invalid_request`; raise `RedisVLMCPError` to choose the error code yourself. The server adds no partial-write warning to an error you raise this way, so if the tool may already have written records, say so in your message. - **Register before starting.** Tools register once, at the first startup, so a tool registered afterwards is refused. A code tool bound to an index that a profile scopes with `lock.inject` refuses to start, because nothing shows that it applies the tenant scope. For the full contract, read the code tools section in {doc}`/concepts/mcp`. diff --git a/redisvl/mcp/tools/code.py b/redisvl/mcp/tools/code.py index 792e5ab1c..1c3b5261a 100644 --- a/redisvl/mcp/tools/code.py +++ b/redisvl/mcp/tools/code.py @@ -198,15 +198,15 @@ def build_code_tool_spec( def register_code_tool(server: Any, spec: CodeToolSpec, binding_id: str) -> None: """Register one code tool against ``binding_id``.""" - def retryable_write_warned(error: RedisVLMCPError) -> RedisVLMCPError: - # A retry runs the whole tool again, including any writes it made - # before it failed. A tool that raises RedisVLMCPError itself has - # chosen its own message, so only errors mapped here get the warning. - if spec.writes and error.retryable: + def warn_if_writing(error: RedisVLMCPError) -> RedisVLMCPError: + # A writing tool may have stored records before it failed, and clients + # see only the message, not whether the error is retryable, so the + # warning goes on every failure the server maps except invalid_request, + # which a tool usually raises before it writes. A tool that raises + # RedisVLMCPError itself has chosen its own message and gets none. + if spec.writes and error.code is not MCPErrorCode.INVALID_REQUEST: return with_partial_write_warning( - error, - "the tool may have written some records before it failed, " - "and a retry runs it again", + error, "the tool may have written some records before it failed" ) return error @@ -238,7 +238,7 @@ async def code_tool(**kwargs: Any) -> Any: # code too, so a tool cannot hold a request open indefinitely. return await asyncio.wait_for(spec.fn(ctx, **kwargs), timeout) except asyncio.TimeoutError as exc: - raise retryable_write_warned( + raise warn_if_writing( RedisVLMCPError( f"tool '{spec.name}' did not finish within {timeout:g}s", code=MCPErrorCode.BACKEND_UNAVAILABLE, @@ -248,7 +248,7 @@ async def code_tool(**kwargs: Any) -> Any: except RedisVLMCPError: raise except Exception as exc: - raise retryable_write_warned(map_exception(exc)) from exc + raise warn_if_writing(map_exception(exc)) from exc code_tool.__name__ = spec.name.replace("-", "_") code_tool.__doc__ = spec.description diff --git a/tests/unit/test_mcp/test_code_tools_unit.py b/tests/unit/test_mcp/test_code_tools_unit.py index e1fc14ff6..8fb1115ac 100644 --- a/tests/unit/test_mcp/test_code_tools_unit.py +++ b/tests/unit/test_mcp/test_code_tools_unit.py @@ -13,6 +13,7 @@ import pytest from conftest import _schema from redis.exceptions import ConnectionError as RedisConnectionError +from redis.exceptions import ResponseError fastmcp = pytest.importorskip( "fastmcp", reason="fastmcp not installed (install redisvl[mcp])" @@ -456,16 +457,35 @@ async def failing(ctx: ToolContext, query: str) -> dict: assert exc_info.value is error +def _wrapped(cause: Exception) -> RedisVLError: + error = RedisVLError("Failed to load data") + error.__cause__ = cause + return error + + @pytest.mark.parametrize("writes", [True, False]) @pytest.mark.parametrize( - "raised", [RedisVLError("Failed to load data"), asyncio.TimeoutError()] + "raised, warned", + [ + pytest.param( + _wrapped(RedisConnectionError("down")), True, id="lost-connection" + ), + pytest.param(asyncio.TimeoutError(), True, id="timeout"), + pytest.param(_wrapped(ResponseError("WRONGTYPE")), True, id="reply-error"), + pytest.param(ValueError("bad sku"), False, id="invalid-request"), + pytest.param( + RedisVLMCPError( + "down", code=MCPErrorCode.BACKEND_UNAVAILABLE, retryable=True + ), + False, + id="tool-chose-message", + ), + ], ) -async def test_only_a_writing_tool_warns_that_a_retryable_failure_may_be_partial( - monkeypatch, writes, raised +async def test_a_writing_tool_warns_that_a_failure_may_have_written_records( + monkeypatch, writes, raised, warned ): _as_caller(monkeypatch) - if isinstance(raised, RedisVLError): - raised.__cause__ = RedisConnectionError("down") async def failing(ctx: ToolContext, ticket_id: str) -> dict: """Close a ticket.""" @@ -474,8 +494,7 @@ async def failing(ctx: ToolContext, ticket_id: str) -> dict: with pytest.raises(RedisVLMCPError) as exc_info: await _registered(failing, writes=writes)(ticket_id="t1") - assert exc_info.value.retryable is True - assert ("may have written" in str(exc_info.value)) is writes + assert ("may have written" in str(exc_info.value)) is (writes and warned) # -------------------------------------------------------------------------- From 155f01cb460336753d23eaf60335a0d94cb28724 Mon Sep 17 00:00:00 2001 From: Vishal Bala Date: Thu, 5 Nov 2026 13:55:11 +0100 Subject: [PATCH 5/7] fix(mcp): warn on invalid_request from a writing code tool too A code tool can store one batch and then reject its next input, so an invalid_request from a writing tool may follow a partial write. Every failure the server maps for a writes=True tool now carries the warning. --- docs/concepts/mcp.md | 2 +- redisvl/mcp/tools/code.py | 9 ++++----- tests/unit/test_mcp/test_code_tools_unit.py | 2 +- 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/docs/concepts/mcp.md b/docs/concepts/mcp.md index f0c614f1f..f0eeca0de 100644 --- a/docs/concepts/mcp.md +++ b/docs/concepts/mcp.md @@ -321,7 +321,7 @@ The server applies the same rails as for a built-in, without the author asking f - Every `ctx.index` call takes a slot under the server-wide concurrency cap and is bounded by the binding's `runtime.request_timeout_seconds`. The cap is taken per call, so a tool that queries several times never blocks itself. - The whole tool call is bounded by the same timeout, so a tool cannot hold a request open indefinitely. A timeout returns a retryable `backend_unavailable` error. - A caller needs the server's read scope, and the write scope as well for a tool declared with `writes=True`, whose handle can both read and write. A tool can require an extra scope with `scope=`, which a caller must hold as well, so a code tool can be stricter than the built-ins but never looser. Like every scope, it is enforced only when the server has authentication configured. -- An exception the tool raises becomes a stable MCP error: `ValueError` becomes `invalid_request`, a Redis error from a search, aggregation, fetch, `drop_documents` or `expire_documents` a retryable `backend_unavailable`, and most other exceptions `internal_error`. From `ctx.index.load`, a record that fails schema validation is `invalid_request`, a lost connection or timeout a retryable `backend_unavailable`, and any other failure, such as a `WRONGTYPE` reply, a non-retryable `internal_error`. For a tool declared with `writes=True`, every one of these except `invalid_request` also warns, in the message, that the tool may have written some records before it failed. Raise `RedisVLMCPError` to choose the code and message yourself; the server then adds no warning. +- An exception the tool raises becomes a stable MCP error: `ValueError` becomes `invalid_request`, a Redis error from a search, aggregation, fetch, `drop_documents` or `expire_documents` a retryable `backend_unavailable`, and most other exceptions `internal_error`. From `ctx.index.load`, a record that fails schema validation is `invalid_request`, a lost connection or timeout a retryable `backend_unavailable`, and any other failure, such as a `WRONGTYPE` reply, a non-retryable `internal_error`. For a tool declared with `writes=True`, every one of these also warns, in the message, that the tool may have written some records before it failed. Raise `RedisVLMCPError` to choose the code and message yourself; the server then adds no warning. The handle is a guardrail, not a sandbox. A code tool is your own code, running with the privileges of the process that started the server, and Python can still reach private attributes. What the handle does is make the bounded, policy-checked path the only obvious one. diff --git a/redisvl/mcp/tools/code.py b/redisvl/mcp/tools/code.py index 1c3b5261a..e5cf6be0d 100644 --- a/redisvl/mcp/tools/code.py +++ b/redisvl/mcp/tools/code.py @@ -199,12 +199,11 @@ def register_code_tool(server: Any, spec: CodeToolSpec, binding_id: str) -> None """Register one code tool against ``binding_id``.""" def warn_if_writing(error: RedisVLMCPError) -> RedisVLMCPError: - # A writing tool may have stored records before it failed, and clients - # see only the message, not whether the error is retryable, so the - # warning goes on every failure the server maps except invalid_request, - # which a tool usually raises before it writes. A tool that raises + # A writing tool may have stored records before it failed, even one + # that then rejects its input, and clients see only the message, so + # every failure the server maps gets the warning. A tool that raises # RedisVLMCPError itself has chosen its own message and gets none. - if spec.writes and error.code is not MCPErrorCode.INVALID_REQUEST: + if spec.writes: return with_partial_write_warning( error, "the tool may have written some records before it failed" ) diff --git a/tests/unit/test_mcp/test_code_tools_unit.py b/tests/unit/test_mcp/test_code_tools_unit.py index 8fb1115ac..34ec92c09 100644 --- a/tests/unit/test_mcp/test_code_tools_unit.py +++ b/tests/unit/test_mcp/test_code_tools_unit.py @@ -472,7 +472,7 @@ def _wrapped(cause: Exception) -> RedisVLError: ), pytest.param(asyncio.TimeoutError(), True, id="timeout"), pytest.param(_wrapped(ResponseError("WRONGTYPE")), True, id="reply-error"), - pytest.param(ValueError("bad sku"), False, id="invalid-request"), + pytest.param(ValueError("bad sku"), True, id="invalid-request"), pytest.param( RedisVLMCPError( "down", code=MCPErrorCode.BACKEND_UNAVAILABLE, retryable=True From e6787eb12efea080f0700d9289af0b7e23f55608 Mon Sep 17 00:00:00 2001 From: Vishal Bala Date: Wed, 11 Nov 2026 15:39:09 +0100 Subject: [PATCH 6/7] refactor(mcp): drop asyncio.TimeoutError from the new timeout checks Python 3.10 support is gone, and from 3.11 asyncio.TimeoutError is the builtin TimeoutError. --- redisvl/mcp/errors.py | 2 +- redisvl/mcp/tools/upsert.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/redisvl/mcp/errors.py b/redisvl/mcp/errors.py index 5999ab7b4..68187a3cf 100644 --- a/redisvl/mcp/errors.py +++ b/redisvl/mcp/errors.py @@ -74,7 +74,7 @@ def map_exception(exc: Exception) -> RedisVLMCPError: # fail the same way again, so they stay non-retryable. if isinstance(exc, RedisVLError) and isinstance( exc.__cause__, - (RedisConnectionError, RedisTimeoutError, TimeoutError, asyncio.TimeoutError), + (RedisConnectionError, RedisTimeoutError, TimeoutError), ): return RedisVLMCPError( str(exc), diff --git a/redisvl/mcp/tools/upsert.py b/redisvl/mcp/tools/upsert.py index a307b4e47..0c683f4ef 100644 --- a/redisvl/mcp/tools/upsert.py +++ b/redisvl/mcp/tools/upsert.py @@ -355,7 +355,7 @@ async def upsert_records( # and run_guarded's own errors mean load never ran. Any other load # failure, or a timeout, may have left records behind. if mapped.code is MCPErrorCode.INVALID_REQUEST or not isinstance( - exc, (RedisVLError, TimeoutError, asyncio.TimeoutError) + exc, (RedisVLError, TimeoutError) ): raise mapped from exc warning = "some records may already have been written" From 2e21a992a822160d434bbb79ab43a4576b4e7f60 Mon Sep 17 00:00:00 2001 From: Vishal Bala Date: Tue, 24 Nov 2026 11:05:25 +0100 Subject: [PATCH 7/7] fix(mcp): reject non-scalar hash values before upsert-records loads A None or nested value on a hash index passed schema validation, then made load raise TypeError while it built the write pipeline. That reached clients as internal_error with a partial-write warning, although nothing had been written and the input was at fault. upsert-records now rejects it as invalid_request before calling load. --- redisvl/mcp/tools/upsert.py | 26 ++++++++++++++------ tests/unit/test_mcp/test_upsert_tool_unit.py | 12 +++++++++ 2 files changed, 30 insertions(+), 8 deletions(-) diff --git a/redisvl/mcp/tools/upsert.py b/redisvl/mcp/tools/upsert.py index 0c683f4ef..cc56e87e4 100644 --- a/redisvl/mcp/tools/upsert.py +++ b/redisvl/mcp/tools/upsert.py @@ -237,16 +237,26 @@ def _prepare_record_for_storage( vector_field_name = rt.binding.runtime.vector_field_name _validate_record(prepared, index=index, vector_field_name=vector_field_name) - if vector_field_name is None: + if index.schema.index.storage_type != StorageType.HASH: return prepared - vector_value = prepared.get(vector_field_name) - - if index.schema.index.storage_type == StorageType.HASH: - if isinstance(vector_value, list): - prepared[vector_field_name] = array_to_buffer( - vector_value, - _vector_dtype(rt), + if vector_field_name is not None and isinstance( + prepared.get(vector_field_name), list + ): + prepared[vector_field_name] = array_to_buffer( + prepared[vector_field_name], + _vector_dtype(rt), + ) + # A hash stores only scalars. Rejecting anything else here, before load, + # makes it the caller's invalid_request rather than a TypeError that load + # raises while it builds the write pipeline. + for field_name, value in prepared.items(): + if not isinstance(value, (bytes, str, int, float)): + raise RedisVLMCPError( + f"field '{field_name}' must be a string or a number on a hash " + f"index, not {type(value).__name__}", + code=MCPErrorCode.INVALID_REQUEST, + retryable=False, ) return prepared diff --git a/tests/unit/test_mcp/test_upsert_tool_unit.py b/tests/unit/test_mcp/test_upsert_tool_unit.py index faff3dd7e..98ddfff94 100644 --- a/tests/unit/test_mcp/test_upsert_tool_unit.py +++ b/tests/unit/test_mcp/test_upsert_tool_unit.py @@ -454,6 +454,18 @@ async def test_upsert_records_validates_non_vector_fields_before_embedding(): assert server.index.load_calls == [] +@pytest.mark.asyncio +@pytest.mark.parametrize("value", [None, {"nested": 1}]) +async def test_upsert_records_rejects_non_scalar_hash_values_before_load(value): + server = FakeServer(storage_type="hash") + + with pytest.raises(RedisVLMCPError, match="note") as exc_info: + await upsert_records(server, records=[{"content": "alpha doc", "note": value}]) + + assert exc_info.value.code == MCPErrorCode.INVALID_REQUEST + assert server.index.load_calls == [] + + @pytest.mark.asyncio @pytest.mark.parametrize("id_field", [None, "id"]) async def test_upsert_records_surfaces_partial_write_possible_on_backend_failures(