Handle pagination in an AI-facing data tool
In this article (5 sections)
Returning every record can overflow context and service limits. Pagination needs stable cursors and a budget so an agent cannot fetch forever.
Execute three pages
The MCP contract lab pages seven synthetic metric IDs in groups of three.
from mcp_cases import pagination_case
result = pagination_case()
assert result["page_count"] == 3
assert result["complete"] is True
assert result["duplicates"] is False
assert result["records"] == [f"M-{i}" for i in range(1, 8)]The final cursor is null. This is local list slicing, not server pagination.
Design a stable page contract
Accept opaque cursor and bounded page size. Return items, next cursor and optionally snapshot/version identity. Do not expose database offsets or secrets in cursors. Define ordering and behaviour when underlying data changes.
Agents need a maximum pages/items/time rule and a reason to continue. Summarization should not hide truncated results; return completeness metadata.
Test boundaries
Cover empty, exact page, final partial page, invalid/expired cursor, changed snapshot and repeated request. Verify authorization on every page and no cross-tenant cursor reuse.
The Generative & Agentic AI course connects pagination to context budgets and bounded tool loops.
Exercise
Implement cursor pagination over 23 records. Add a five-page agent budget, snapshot identity and cross-tenant cursor rejection.
Continue learning
This article is part of the MCP and integration contracts sequence. Use the neighbouring tasks when you need the prerequisite or the next application.
- Review the prerequisite or neighbouring task in Version a tool contract without breaking callers.
- Continue with Rate-limit tools by user and tenant.
Reference: MCP specification.
Pankit Kumar has 10 years in Data Science & AI, building and shipping production systems in regulated pharma and clinical environments. He is a freelance trainer at Boston Institute of Analytics, AnalytixLabs and Scaler, and has taught this material to thousands of working professionals.
This article is part of our Generative & Agentic AI programme — 3 months. Add practical GenAI, retrieval and agent-building skills to your existing toolkit.
Explore Generative & Agentic AI