Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

fix(server): reject a malformed pagination cursor offset (#5071)

Lukas Buckd869ad0eb6aa
diff --git a/fastmcp_slim/fastmcp/utilities/pagination.py b/fastmcp_slim/fastmcp/utilities/pagination.py
index 48e2e45bb..685d9d50a 100644
--- a/fastmcp_slim/fastmcp/utilities/pagination.py
+++ b/fastmcp_slim/fastmcp/utilities/pagination.py
@@ -36,7 +36,17 @@ class CursorState:
"""
try:
data = json.loads(base64.urlsafe_b64decode(cursor.encode()).decode())
- return cls(offset=data["o"])
+ offset = data["o"]
+ # The offset reaches a slice and an addition, so a string or a float
+ # surfaces as a TypeError the caller reports as an internal error, and
+ # a negative one slices from the end and returns a valid-looking page
+ # the client never asked for. A cursor is ours to produce, so anything
+ # but a whole non-negative count means it was tampered with.
+ if isinstance(offset, bool) or not isinstance(offset, int) or offset < 0:
+ raise ValueError(
+ f"cursor offset must be a non-negative integer: {offset!r}"
+ )
+ return cls(offset=offset)
except (
json.JSONDecodeError,
KeyError,
diff --git a/tests/server/test_pagination.py b/tests/server/test_pagination.py
index ac1124d02..f4645fc2c 100644
--- a/tests/server/test_pagination.py
+++ b/tests/server/test_pagination.py
@@ -8,6 +8,7 @@ import mcp_types
import pytest
from mcp.server.context import ServerRequestContext
from mcp.shared.exceptions import MCPError
+from mcp.types import INVALID_PARAMS
from fastmcp import Client, FastMCP
from fastmcp.utilities.pagination import CursorState, paginate_sequence
@@ -43,6 +44,21 @@ class TestCursorEncoding:
with pytest.raises(ValueError, match="Invalid cursor"):
CursorState.decode(invalid)
+ @pytest.mark.parametrize("offset", ["1", 1.5, -1, True, None, [0]])
+ def test_decode_rejects_a_malformed_offset(self, offset: object) -> None:
+ """An offset that is not a whole non-negative count is an invalid cursor.
+
+ A string or a float reached the slice and raised TypeError, which the
+ server reports as an internal error rather than invalid parameters, and a
+ negative one sliced from the end and returned a valid-looking page.
+ """
+ import base64
+ import json
+
+ invalid = base64.urlsafe_b64encode(json.dumps({"o": offset}).encode()).decode()
+ with pytest.raises(ValueError, match="Invalid cursor"):
+ CursorState.decode(invalid)
+
def test_decode_missing_offset_raises(self) -> None:
"""JSON missing the offset key should raise ValueError."""
import base64
@@ -106,6 +122,40 @@ class TestPaginateSequence:
paginate_sequence([1, 2, 3], "invalid!", 10)
+class TestMalformedCursorParams:
+ """A tampered cursor is invalid parameters, not an internal error."""
+
+ @staticmethod
+ def _cursor(offset: object) -> str:
+ import base64
+ import json
+
+ return base64.urlsafe_b64encode(json.dumps({"o": offset}).encode()).decode()
+
+ @pytest.mark.parametrize("offset", ["1", 1.5, -1])
+ def test_paginate_sequence_rejects_a_malformed_offset(self, offset: object) -> None:
+ with pytest.raises(ValueError, match="Invalid cursor"):
+ paginate_sequence([0, 1, 2], self._cursor(offset), page_size=2)
+
+ async def test_list_tools_reports_invalid_params(self) -> None:
+ """The caller maps the ValueError to INVALID_PARAMS, so the client sees that."""
+ server = FastMCP(list_page_size=1)
+
+ @server.tool(name="one")
+ def one() -> int:
+ return 1
+
+ @server.tool(name="two")
+ def two() -> int:
+ return 2
+
+ async with Client(server) as client:
+ with pytest.raises(MCPError) as excinfo:
+ await client.list_tools_mcp(cursor=self._cursor(-1))
+
+ assert excinfo.value.error.code == INVALID_PARAMS
+
+
class TestServerPagination:
"""Integration tests for server pagination."""