diff --git a/docs/concepts/mcp.md b/docs/concepts/mcp.md index bc82ea9c3..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 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, 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/docs/user_guide/how_to_guides/mcp.md b/docs/user_guide/how_to_guides/mcp.md index 6afd2282d..7148740c8 100644 --- a/docs/user_guide/how_to_guides/mcp.md +++ b/docs/user_guide/how_to_guides/mcp.md @@ -466,7 +466,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`. @@ -672,6 +672,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 aae49576b..68187a3cf 100644 --- a/redisvl/mcp/errors.py +++ b/redisvl/mcp/errors.py @@ -3,9 +3,11 @@ 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 +from redisvl.exceptions import RedisSearchError, RedisVLError, SchemaValidationError class MCPErrorCode(str, Enum): @@ -41,7 +43,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,8 +68,36 @@ def map_exception(exc: Exception) -> RedisVLMCPError: retryable=True, ) + # Index methods such as ``load`` wrap whatever went wrong in a plain + # ``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), + ): + return RedisVLMCPError( + str(exc), + code=MCPErrorCode.BACKEND_UNAVAILABLE, + retryable=True, + ) + return RedisVLMCPError( str(exc), 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..e5cf6be0d 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,17 @@ 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 warn_if_writing(error: RedisVLMCPError) -> RedisVLMCPError: + # 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: + return with_partial_write_warning( + error, "the tool may have written some records before it failed" + ) + 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 +237,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 warn_if_writing( + 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 warn_if_writing(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 f079e923c..cc56e87e4 100644 --- a/redisvl/mcp/tools/upsert.py +++ b/redisvl/mcp/tools/upsert.py @@ -3,8 +3,14 @@ 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.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 @@ -231,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 @@ -345,8 +361,19 @@ async def upsert_records( ) except Exception as exc: mapped = map_exception(exc) - mapped.metadata["partial_write_possible"] = True - raise mapped from 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. + if mapped.code is MCPErrorCode.INVALID_REQUEST or not isinstance( + exc, (RedisVLError, TimeoutError) + ): + 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 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..34ec92c09 100644 --- a/tests/unit/test_mcp/test_code_tools_unit.py +++ b/tests/unit/test_mcp/test_code_tools_unit.py @@ -12,11 +12,14 @@ 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])" ) +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 +457,46 @@ 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, 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"), True, id="invalid-request"), + pytest.param( + RedisVLMCPError( + "down", code=MCPErrorCode.BACKEND_UNAVAILABLE, retryable=True + ), + False, + id="tool-chose-message", + ), + ], +) +async def test_a_writing_tool_warns_that_a_failure_may_have_written_records( + monkeypatch, writes, raised, warned +): + _as_caller(monkeypatch) + + 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 ("may have written" in str(exc_info.value)) is (writes and warned) + + # -------------------------------------------------------------------------- # @code_tool and the module loader # -------------------------------------------------------------------------- diff --git a/tests/unit/test_mcp/test_errors.py b/tests/unit/test_mcp/test_errors.py index ddd286224..c5dfa9a65 100644 --- a/tests/unit/test_mcp/test_errors.py +++ b/tests/unit/test_mcp/test_errors.py @@ -1,7 +1,10 @@ +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 +from redisvl.exceptions import RedisSearchError, RedisVLError, SchemaValidationError from redisvl.mcp.errors import MCPErrorCode, RedisVLMCPError, map_exception @@ -59,6 +62,37 @@ 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_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)) + + 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..98ddfff94 100644 --- a/tests/unit/test_mcp/test_upsert_tool_unit.py +++ b/tests/unit/test_mcp/test_upsert_tool_unit.py @@ -2,8 +2,9 @@ from typing import Any import pytest -from redis.exceptions import RedisError +from redis.exceptions import ConnectionError as RedisConnectionError +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 @@ -454,16 +455,60 @@ 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("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( + 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" in str(exc_info.value)) is (id_field is None) + + +@pytest.mark.asyncio +@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 = error + + with pytest.raises(RedisVLMCPError) as exc_info: + await upsert_records(server, records=[{"content": "alpha doc"}]) + + assert exc_info.value.code == code + assert "partial_write_possible" not in exc_info.value.metadata + assert "written" not in str(exc_info.value) @pytest.mark.asyncio