Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(mcp): tell agents how to read the next page of a list (#126414)

Julian Bezab49a4e24489
diff --git a/services/mcp/src/lib/build-tool-result.ts b/services/mcp/src/lib/build-tool-result.ts
index 050160b9f07e..39f405dcd0d9 100644
--- a/services/mcp/src/lib/build-tool-result.ts
+++ b/services/mcp/src/lib/build-tool-result.ts
@@ -2,6 +2,7 @@ import { RESOURCE_URI_META_KEY } from '@modelcontextprotocol/ext-apps/server'
import { type DiscoveryHint, type DiscoveryHintKind, getDiscoveryHint, isEmptyToolResult } from '@/lib/discovery-hints'
import { estimateTokens } from '@/lib/estimate-tokens'
+import { getNextPageHint } from '@/lib/next-page-hint'
import { formatResponse } from '@/lib/response'
import { isPrepareConfirmedActionResult } from '@/tools/confirmed-action-runtime'
import { POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY, POSTHOG_META_KEY, POSTHOG_TEXT_PROJECTION_KEY } from '@/tools/types'
@@ -242,6 +243,10 @@ export function buildToolResultPayload(opts: BuildToolResultOptions): ToolResult
if (discoveryHint) {
footers.push(discoveryHint.text)
}
+ const nextPageHint = getNextPageHint(toolName, rawResult)
+ if (nextPageHint) {
+ footers.push(nextPageHint)
+ }
}
if (includeRenderNote && hasUiResource && !useJson) {
diff --git a/services/mcp/src/lib/next-page-hint.ts b/services/mcp/src/lib/next-page-hint.ts
new file mode 100644
index 000000000000..617ba0b0b84e
--- /dev/null
+++ b/services/mcp/src/lib/next-page-hint.ts
@@ -0,0 +1,55 @@
+interface PaginatedEnvelope {
+ results: unknown[]
+ next: string
+ count?: number
+}
+
+const ENVELOPE_KEYS = ['results', 'next', 'count', 'previous']
+
+// Other parameters in `next`, such as `search`, repeat arguments the agent already sent.
+const PAGING_PARAMS = ['cursor', 'offset', 'limit', 'page']
+
+function findPaginatedEnvelope(data: unknown): PaginatedEnvelope | null {
+ if (data === null || typeof data !== 'object' || Array.isArray(data)) {
+ return null
+ }
+ const record = data as Record<string, unknown>
+ if (!Array.isArray(record.results) || typeof record.next !== 'string' || !('previous' in record)) {
+ return null
+ }
+ // Wrappers such as `withPostHogUrl` and `withAgentNote` add `_`-prefixed keys next to the envelope.
+ const hasOtherKeys = Object.keys(record).some((key) => !ENVELOPE_KEYS.includes(key) && !key.startsWith('_'))
+ if (hasOtherKeys) {
+ return null
+ }
+ return record as unknown as PaginatedEnvelope
+}
+
+function pluralizeResults(count: number): string {
+ return count === 1 ? '1 result' : `${count} results`
+}
+
+export function getNextPageHint(toolName: string, handlerResult: unknown): string | null {
+ const envelope = findPaginatedEnvelope(handlerResult)
+ if (!envelope) {
+ return null
+ }
+
+ let params: URLSearchParams
+ try {
+ params = new URL(envelope.next).searchParams
+ } catch {
+ return null
+ }
+
+ const pagingValues = PAGING_PARAMS.filter((name) => params.has(name)).map((name) => `${name}=${params.get(name)}`)
+ if (pagingValues.length === 0) {
+ return null
+ }
+
+ const shown =
+ typeof envelope.count === 'number'
+ ? `Showing ${envelope.results.length} of ${pluralizeResults(envelope.count)}.`
+ : `Showing ${pluralizeResults(envelope.results.length)}.`
+ return `${shown} More results exist: call ${toolName} again with the same arguments and set ${pagingValues.join(' and ')} to get the next page.`
+}
diff --git a/services/mcp/tests/unit/build-tool-result.test.ts b/services/mcp/tests/unit/build-tool-result.test.ts
index df936d5375ab..e8ef32abce8b 100644
--- a/services/mcp/tests/unit/build-tool-result.test.ts
+++ b/services/mcp/tests/unit/build-tool-result.test.ts
@@ -357,7 +357,6 @@ describe('buildToolResultPayload — non-query use cases', () => {
it.each([
{ results: [{ id: 1 }], next: null, count: 1, previous: null },
{ results: [], next: null, count: 0, previous: null },
- { results: [{ id: 1 }], next: 'https://example.com/api/items/?cursor=next', previous: null },
])('unwraps optimized lists but preserves JSON and widget data: %j', (handlerResult) => {
for (const outputFormat of ['optimized', 'json'] as const) {
const payload = buildToolResultPayload({
@@ -374,6 +373,56 @@ describe('buildToolResultPayload — non-query use cases', () => {
}
})
+ it.each([
+ {
+ handlerResult: {
+ results: [{ id: 1 }],
+ next: 'https://example.com/api/items/?cursor=cD0yMDI2&search=foo',
+ previous: null,
+ },
+ expected:
+ 'Showing 1 result. More results exist: call mock-tool again with the same arguments and set cursor=cD0yMDI2 to get the next page.',
+ },
+ {
+ handlerResult: {
+ results: [{ id: 1 }, { id: 2 }],
+ next: 'https://example.com/api/items/?limit=2&offset=2',
+ count: 5,
+ previous: null,
+ _posthogUrl: 'https://example.com/items',
+ },
+ expected:
+ 'Showing 2 of 5 results. More results exist: call mock-tool again with the same arguments and set offset=2 and limit=2 to get the next page.',
+ },
+ ])('tells the agent how to read the next page: $handlerResult.next', ({ handlerResult, expected }) => {
+ const payload = buildToolResultPayload({ handlerResult, toolName: 'mock-tool', params: {} })
+
+ expect(payload.content[0]!.text).toBe(`${formatResponse(handlerResult)}\n\n${expected}`)
+ })
+
+ it.each(['optimized', 'json'] as const)(
+ 'keeps widget data and JSON text whole when another page exists: %s',
+ (outputFormat) => {
+ const handlerResult = {
+ results: [{ id: 1 }],
+ next: 'https://example.com/api/items/?cursor=next',
+ previous: null,
+ }
+
+ const payload = buildToolResultPayload({
+ handlerResult,
+ toolName: 'mock-tool',
+ params: { output_format: outputFormat },
+ includeAppData: true,
+ })
+
+ if (outputFormat === 'json') {
+ expect(payload.content[0]!.text).toBe(JSON.stringify(handlerResult))
+ }
+ expect(payload._meta?.[APP_DATA_META_KEY]).toEqual(handlerResult)
+ }
+ )
+
it.each([
{ results: [{ id: 1 }], query: { kind: 'HogQLQuery' } },
{ results: [{ id: 1 }], next: null, previous: null, status: 'ready' },