Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

list-pages.ts

45 lines1.3 KB

1// Same cap as MAX_TOOLS_LIST_PAGES in client.ts.
2const DEFAULT_MAX_LIST_PAGES = 100
3​
4/**
5 * This function reads each page of a cursor-paginated list.
6 * This function returns the items in page order.
7 *
8 * The first call to `fetchPage` gets `undefined`.
9 * Each later call gets the cursor from the previous page.
10 * `options.maxPages` is the page cap.
11 * The default cap is 100, the same limit as `MAX_TOOLS_LIST_PAGES`.
12 *
13 * If the next cursor is the same as the sent cursor,
14 * this function throws an Error.
15 * If the page count is more than the cap, this function throws an Error.
16 */
17export async function listPages<TItem>(
18 fetchPage: (cursor: string | undefined) => Promise<{
19 items: ReadonlyArray<TItem>
20 nextCursor?: string
21 }>,
22 options?: { maxPages?: number },
23) {
24 const maxPages = options?.maxPages ?? DEFAULT_MAX_LIST_PAGES
25 const items: Array<TItem> = []
26 let cursor: string | undefined
27 let pageCount = 0
28​
29 do {
30 pageCount++
31 if (pageCount > maxPages) {
32 throw new Error(`MCP list pagination exceeded ${maxPages} pages`)
33 }
34​
35 const page = await fetchPage(cursor)
36 items.push(...page.items)
37 const nextCursor = page.nextCursor
38 if (nextCursor !== undefined && nextCursor === cursor) {
39 throw new Error('MCP list pagination repeated a cursor')
40 }
41 cursor = nextCursor
42 } while (cursor)
43​
44 return items