MCPcopy Create free account
hub / github.com/modelcontextprotocol/go-sdk / paginateList

Function paginateList

mcp/server.go:1575–1611  ·  view source on GitHub ↗

paginateList is a generic helper that returns a paginated slice of items from a featureSet. It populates the provided result res with the items and sets its next cursor for subsequent pages. If there are no more pages, the next cursor within the result will be an empty string.

(fs *featureSet[T], pageSize int, params P, res R, setFunc func(R, []T))

Source from the content-addressed store, hash-verified

1573// and sets its next cursor for subsequent pages.
1574// If there are no more pages, the next cursor within the result will be an empty string.
1575func paginateList[P listParams, R listResult[T], T any](fs *featureSet[T], pageSize int, params P, res R, setFunc func(R, []T)) (R, error) {
1576 var seq iter.Seq[T]
1577 if params.cursorPtr() == nil || *params.cursorPtr() == "" {
1578 seq = fs.all()
1579 } else {
1580 pageToken, err := decodeCursor(*params.cursorPtr())
1581 // According to the spec, invalid cursors should return Invalid params.
1582 if err != nil {
1583 var zero R
1584 return zero, jsonrpc2.ErrInvalidParams
1585 }
1586 seq = fs.above(pageToken.LastUID)
1587 }
1588 var count int
1589 var features []T
1590 for f := range seq {
1591 count++
1592 // If we've seen pageSize + 1 elements, we've gathered enough info to determine
1593 // if there's a next page. Stop processing the sequence.
1594 if count == pageSize+1 {
1595 break
1596 }
1597 features = append(features, f)
1598 }
1599 setFunc(res, features)
1600 // No remaining pages.
1601 if count < pageSize+1 {
1602 return res, nil
1603 }
1604 nextCursor, err := encodeCursor(fs.uniqueID(features[len(features)-1]))
1605 if err != nil {
1606 var zero R
1607 return zero, err
1608 }
1609 *res.nextCursorPtr() = nextCursor
1610 return res, nil
1611}

Callers 6

listPromptsMethod · 0.85
listToolsMethod · 0.85
listResourcesMethod · 0.85
listResourceTemplatesMethod · 0.85
TestServerPaginateBasicFunction · 0.85

Calls 6

decodeCursorFunction · 0.85
encodeCursorFunction · 0.85
allMethod · 0.80
aboveMethod · 0.80
cursorPtrMethod · 0.65
nextCursorPtrMethod · 0.65

Tested by 2

TestServerPaginateBasicFunction · 0.68

Used in the wild real call sites across dependent graphs

searching dependent graphs…