Cursor Patterns
A cursor is an opaque continuation token. The handler encodes it; Repl passes it back on the next call. This page is a dense reference — for the conceptual background, see Result-Flow Paging.
Pattern table
Section titled “Pattern table”| Pattern | When to use | Cursor encoding | Repl helper |
|---|---|---|---|
| Offset / index | Small or static datasets, admin tables, bounded lists | "42" — decimal row offset | FromOffset |
| Keyset / seek | Large, mutable databases with a stable sort column | base64 of (lastSortKey, tieBreakerId) | paging.CreateSource(...) |
| External page token | Wrapping a paginated API (Azure SDK, etc.) | Opaque token from the API response | paging.CreateSource(...) |
| nextLink / URL | OData, Microsoft Graph, REST APIs with @nextLink | Full URL string — validate origin | paging.CreateSource(...) |
| Snapshot | Consistent views over changing data | (snapshotId, offset) as base64-JSON | paging.CreateSource(...) |
| Range / window | Time-series and log scans: one time window, paged by count | base64 of (lastTimestamp, lastId, windowEnd) | paging.CreateSource(...) |
Offset cursor
Section titled “Offset cursor”Simplest pattern. Reliable on static or append-only data. Degrades on mutable rows (inserts shift subsequent pages).
public ReplPage<Row> Query(IReplPagingContext paging){ var offset = paging.AllRequested ? 0 : ParseOffset(paging.Cursor); var items = _store.Skip(offset).Take(paging.SuggestedPageSize).ToList(); var next = offset + items.Count < _store.Count ? (offset + items.Count).ToString(CultureInfo.InvariantCulture) : null; return paging.Page(items, nextCursor: next, totalCount: _store.Count);}
private static int ParseOffset(string? cursor) => cursor is null ? 0 : int.TryParse(cursor, NumberStyles.None, CultureInfo.InvariantCulture, out var v) ? v : throw new ArgumentException("Invalid continuation cursor.");Or use the built-in helper:
ReplPageSource.FromOffset<Row>( (offset, take, ct) => store.QueryAsync(offset, take, ct), totalCount: store.Count)Keyset / seek cursor
Section titled “Keyset / seek cursor”Best for large tables with frequent inserts or deletes. Encodes the sort key + tie-breaker of the last row seen. Pages are stable even as the underlying data changes.
app.Map("orders", async (IReplPagingContext paging, OrderStore store, CancellationToken ct) => paging.CreateSource<Order>(async (req, innerCt) => { var (afterDate, afterId) = ParseKeysetCursor(req.Cursor); var items = await store.SeekAsync(afterDate, afterId, req.PageSize, innerCt);
return new ReplPage<Order>( items, nextCursor: items.Count == req.PageSize ? EncodeKeysetCursor(items[^1].CreatedAt, items[^1].Id) : null); }));
private static (DateTimeOffset? after, int? id) ParseKeysetCursor(string? cursor){ if (cursor is null) return (null, null); try { var json = JsonSerializer.Deserialize<KeysetCursor>(Convert.FromBase64String(cursor)) ?? throw new ArgumentException("Invalid continuation cursor."); return (json.LastCreatedAt, json.LastId); } catch (Exception ex) when (ex is FormatException or JsonException) { // A cursor that does not decode is refused, never read as "start over". throw new ArgumentException("Invalid continuation cursor.", ex); }}
private static string EncodeKeysetCursor(DateTimeOffset at, int id) => Convert.ToBase64String(JsonSerializer.SerializeToUtf8Bytes(new KeysetCursor(at, id)));
private sealed record KeysetCursor(DateTimeOffset LastCreatedAt, int LastId);External page token
Section titled “External page token”Forward the API’s opaque token as-is. A caller can send any string back as the cursor, so the API must treat the token as untrusted; if it does not, keep the token server-side and hand out an opaque key instead.
app.Map("messages", async (IReplPagingContext paging, MessageApiClient client, CancellationToken ct) => paging.CreateSource<Message>(async (req, innerCt) => { var response = await client.GetMessagesAsync(req.Cursor, req.PageSize, innerCt); return new ReplPage<Message>( response.Messages, nextCursor: response.NextPageToken); }));nextLink / URL cursor
Section titled “nextLink / URL cursor”Used by OData and Microsoft Graph. The next-page URL is the cursor, and your client sends it with its own credentials, so a caller who edits it can reach any URL those credentials allow. Check the scheme, the host, the port and the collection path, not only a prefix. When the client holds a service identity rather than the caller’s, keep the nextLink server-side behind an opaque key, or sign it.
app.Map("items", async (IReplPagingContext paging, GraphClient client, CancellationToken ct) => paging.CreateSource<Item>(async (req, innerCt) => { // Accept only a nextLink for this collection on this API, not any URL on the host. if (req.Cursor is not null && !(Uri.TryCreate(req.Cursor, UriKind.Absolute, out var next) && next.Scheme == Uri.UriSchemeHttps && next.IdnHost == "graph.example.com" && next.IsDefaultPort && next.AbsolutePath == "/v1.0/items")) { throw new ArgumentException("Invalid continuation cursor."); }
var response = req.Cursor is null ? await client.GetItemsAsync(req.PageSize, innerCt) : await client.GetItemsFromUrlAsync(req.Cursor, innerCt);
return new ReplPage<Item>( response.Value, nextCursor: response.OdataNextLink); }));Snapshot cursor
Section titled “Snapshot cursor”Creates an immutable snapshot on the first page request and pages through it. The view is consistent even if the underlying table changes between pages.
app.Map("audit", async (IReplPagingContext paging, AuditStore store, ICurrentUser user, CancellationToken ct) => paging.CreateSource<AuditRow>(async (req, innerCt) => { var (snapshotId, offset) = ParseSnapshotCursor(req.Cursor);
// First page: create a snapshot owned by the caller; later pages: reuse it. // Snapshot ids must be unguessable, and reads are scoped to their owner. snapshotId ??= await store.CreateSnapshotAsync(user.Id, innerCt);
var items = await store.ReadSnapshotAsync(user.Id, snapshotId, offset, req.PageSize, innerCt); var nextOffset = offset + items.Count; var hasMore = items.Count == req.PageSize;
return new ReplPage<AuditRow>( items, nextCursor: hasMore ? EncodeSnapshotCursor(snapshotId, nextOffset) : null); }));
private static (string? id, int offset) ParseSnapshotCursor(string? cursor){ if (cursor is null) return (null, 0); try { var snap = JsonSerializer.Deserialize<SnapshotCursor>(Convert.FromBase64String(cursor)); return snap is { Id: not null, Offset: >= 0 } ? (snap.Id, snap.Offset) : throw new ArgumentException("Invalid continuation cursor."); } catch (Exception ex) when (ex is FormatException or JsonException) { throw new ArgumentException("Invalid continuation cursor.", ex); }}
private static string EncodeSnapshotCursor(string id, int offset) => Convert.ToBase64String(JsonSerializer.SerializeToUtf8Bytes(new SnapshotCursor(id, offset)));
private sealed record SnapshotCursor(string Id, int Offset);Range / window cursor
Section titled “Range / window cursor”For time-series or log data: the caller picks one time window, and pages hold a fixed number of events inside it. The cursor names the last event returned, by timestamp and id, so the next page starts strictly after it even when several events share a timestamp.
app.Map("metrics", async (IReplPagingContext paging, MetricStore store, string? from, string? to, CancellationToken ct) => paging.CreateSource<MetricRow>(async (req, innerCt) => { var (afterTime, afterId, windowEnd) = ParseWindowCursor(req.Cursor, from, to);
// Events strictly after (afterTime, afterId) and before windowEnd, ordered by (Timestamp, Id). var items = await store.QueryWindowAsync(afterTime, afterId, windowEnd, req.PageSize, innerCt);
var next = items.Count == req.PageSize ? EncodeWindowCursor(items[^1].Timestamp, items[^1].Id, windowEnd) : null;
return new ReplPage<MetricRow>(items, nextCursor: next); }));Cursor security checklist
Section titled “Cursor security checklist”- Length — Repl enforces ≤ 512 characters. Keep your encoded cursors well under this.
- Encoding — Prefer base64 for structured data. Avoid raw JSON or strings with spaces (Repl rejects whitespace in cursors). The interactive pager passes your
nextCursorback without Repl’s checks, so a cursor that fails them still works there, then fails when a script or an agent passes it back. - Refusal — A cursor your handler cannot decode is an error, not a request for the first page: falling back silently hands a script or an agent rows it already has. Inside
CreateSource, throwing is the way to refuse; the run ends as a handler error, and an MCP agent sees a failed call. - Ownership — Scope every query by the authenticated caller, never by an id read from the cursor. A cursor that must carry tenant, filter or internal ids needs authenticated protection, an HMAC or authenticated encryption such as ASP.NET Core Data Protection, with the owner inside the protected payload to compare with the caller. Data Protection’s string output is base64url and can start with
-, which Repl refuses; protect bytes and use standard base64 instead. - Expiry — Consider adding a timestamp to snapshot or session-bound cursors and rejecting expired ones.
- Leakage — Cursors that contain database internals (table names, raw SQL fragments, internal IDs) expose schema. Use opaque tokens or encrypt the payload.