Neural Mastery
← Practice
Cursor-Based Pagination for an MCP Tool Listeasy

Cursor-Based Pagination for an MCP Tool List

easy Agents in Production 10–15 min

NumPy allowed · plain Python earns 10 bonus points

Implement cursor-based pagination for an MCP `tools/list` response -- real MCP servers with many tools paginate list results using an opaque cursor rather than returning everything (or a numeric offset) at once, and a client has to follow that cursor correctly to enumerate every tool.

Task

Implement paginate_tools(tools, page_size, cursor). Treat cursor as None for the first page, or the string form of a starting index for a later page. Return (tools[start:start+page_size], next_cursor), where next_cursor is the string form of the next start index, or None if the page reaches the end of tools.

Function Signature

paginate_tools(tools: list[str], page_size: int, cursor: str | None) -> tuple[list[str], str | None]

Examples

Example 1: First Page
Input: tools = ['alpha', 'beta', 'gamma', 'delta', 'epsilon'] page_size = 2 cursor = None
Output: [['alpha', 'beta'], '2']
Example 2: Middle Page
Input: tools = ['alpha', 'beta', 'gamma', 'delta', 'epsilon'] page_size = 2 cursor = '2'
Output: [['gamma', 'delta'], '4']
Example 3: Last Page -- No Next Cursor
Input: tools = ['alpha', 'beta', 'gamma', 'delta', 'epsilon'] page_size = 2 cursor = '4'
Output: [['epsilon'], None]

Constraints

  • Must raise ValueError if page_size <= 0.
  • Must raise ValueError if cursor does not parse to a valid position (negative, or past the end of tools).
  • cursor=None always means "start from the beginning."
  • next_cursor is None exactly when the returned page reaches the end of the list.
Python3Saved ✓
def paginate_tools(tools: list[str], page_size: int, cursor: str | None) -> tuple[list[str], str | None]:
"""cursor is None for the first page, else the opaque cursor string
returned by the previous call. Return (page_items, next_cursor),
where next_cursor is None once there are no more items. Raise
ValueError if page_size <= 0 or cursor does not correspond to a valid
position."""
# Your implementation here
pass

Case 1: First Page
Input: tools = ['alpha', 'beta', 'gamma', 'delta', 'epsilon'] page_size = 2 cursor = None
Expected: [['alpha', 'beta'], '2']
Case 2: Middle Page
Input: tools = ['alpha', 'beta', 'gamma', 'delta', 'epsilon'] page_size = 2 cursor = '2'
Expected: [['gamma', 'delta'], '4']
Case 3: Last Page -- No Next Cursor
Input: tools = ['alpha', 'beta', 'gamma', 'delta', 'epsilon'] page_size = 2 cursor = '4'
Expected: [['epsilon'], None]