π The fast, Pythonic way to build MCP servers and clients.
Address review feedback: validation and edge cases
Jeremiah Lowin17d43d799189
diff --git a/docs/servers/pagination.mdx b/docs/servers/pagination.mdxindex ecdf64739..8c1002c7c 100644--- a/docs/servers/pagination.mdx+++ b/docs/servers/pagination.mdx@@ -21,11 +21,16 @@ from fastmcp import FastMCP# Enable pagination with 50 items per pageserver = FastMCP("ComponentRegistry", list_page_size=50)-# Register many tools, resources, prompts...-for i in range(200):- @server.tool(name=f"tool_{i}")- def make_tool(x: int) -> int:- return x * i+# Register tools (in practice, these might come from a database or config)+def search(query: str) -> str:+ return f"Results for: {query}"++def analyze(data: str) -> dict:+ return {"status": "analyzed", "data": data}++# ... many more tools, resources, prompts```When `list_page_size` is configured, the `tools/list`, `resources/list`, `resources/templates/list`, and `prompts/list` endpoints all paginate their responses. Each response includes a `nextCursor` field when more results exist, which clients use to fetch subsequent pages.diff --git a/src/fastmcp/server/context.py b/src/fastmcp/server/context.pyindex aa5cfe658..7b1f2f116 100644--- a/src/fastmcp/server/context.py+++ b/src/fastmcp/server/context.py@@ -346,10 +346,20 @@ class Context:Returns:List of Resource objects available on the server"""- result = await self.fastmcp._list_resources_mcp(- mcp.types.ListResourcesRequest()- )- return result.resources+ all_resources: list[SDKResource] = []+ cursor: str | None = None+ while True:+ request = mcp.types.ListResourcesRequest(+ params=mcp.types.ListResourcesRequestParams(cursor=cursor)+ if cursor+ else None+ )+ result = await self.fastmcp._list_resources_mcp(request)+ all_resources.extend(result.resources)+ if result.nextCursor is None:+ break+ cursor = result.nextCursor+ return all_resourcesasync def list_prompts(self) -> list[SDKPrompt]:"""List all available prompts from the server.@@ -357,8 +367,20 @@ class Context:Returns:List of Prompt objects available on the server"""- result = await self.fastmcp._list_prompts_mcp(mcp.types.ListPromptsRequest())- return result.prompts+ all_prompts: list[SDKPrompt] = []+ cursor: str | None = None+ while True:+ request = mcp.types.ListPromptsRequest(+ params=mcp.types.ListPromptsRequestParams(cursor=cursor)+ if cursor+ else None+ )+ result = await self.fastmcp._list_prompts_mcp(request)+ all_prompts.extend(result.prompts)+ if result.nextCursor is None:+ break+ cursor = result.nextCursor+ return all_promptsasync def get_prompt(self, name: str, arguments: dict[str, Any] | None = Nonediff --git a/src/fastmcp/server/server.py b/src/fastmcp/server/server.pyindex 114dddece..c2f7ce297 100644--- a/src/fastmcp/server/server.py+++ b/src/fastmcp/server/server.py@@ -387,6 +387,8 @@ class FastMCP(Provider, Generic[LifespanResultT]):)# Store list_page_size for pagination of list operations+ if list_page_size is not None and list_page_size <= 0:+ raise ValueError("list_page_size must be a positive integer")self._list_page_size: int | None = list_page_sizeif tool_serializer is not None and fastmcp.settings.deprecation_warnings:diff --git a/src/fastmcp/utilities/pagination.py b/src/fastmcp/utilities/pagination.pyindex b1df8d55f..48e2e45bb 100644--- a/src/fastmcp/utilities/pagination.py+++ b/src/fastmcp/utilities/pagination.py@@ -3,6 +3,7 @@from __future__ import annotationsimport base64+import binasciiimport jsonfrom collections.abc import Sequencefrom dataclasses import dataclass@@ -36,7 +37,13 @@ class CursorState:try:data = json.loads(base64.urlsafe_b64decode(cursor.encode()).decode())return cls(offset=data["o"])- except (json.JSONDecodeError, KeyError, ValueError, TypeError) as e:+ except (+ json.JSONDecodeError,+ KeyError,+ ValueError,+ TypeError,+ binascii.Error,+ ) as e:raise ValueError(f"Invalid cursor: {cursor}") from ediff --git a/tests/server/test_pagination.py b/tests/server/test_pagination.pyindex fde5cccf3..c1387fb46 100644--- a/tests/server/test_pagination.py+++ b/tests/server/test_pagination.py@@ -223,3 +223,21 @@ class TestServerPagination:result2 = await client.list_tools_mcp(cursor=result.nextCursor)assert len(result2.tools) == 10assert result2.nextCursor is None+++class TestPageSizeValidation:+ """Tests for list_page_size validation."""++ def test_zero_page_size_raises(self) -> None:+ """Zero page size should raise ValueError."""+ with pytest.raises(+ ValueError, match="list_page_size must be a positive integer"+ ):+ FastMCP(list_page_size=0)++ def test_negative_page_size_raises(self) -> None:+ """Negative page size should raise ValueError."""+ with pytest.raises(+ ValueError, match="list_page_size must be a positive integer"+ ):+ FastMCP(list_page_size=-1)