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.

fix(mcp): unwrap django list response text (#104268)

Georgiy Tarasove43c1cfd1375
diff --git a/services/mcp/src/lib/response.ts b/services/mcp/src/lib/response.ts
index 57a7c21034a9..ffbf868d0d5b 100644
--- a/services/mcp/src/lib/response.ts
+++ b/services/mcp/src/lib/response.ts
@@ -28,13 +28,29 @@ function preprocessKeys(obj: any, placeholderMap: Map<string, string>, placehold
return obj
}
+function unwrapPaginatedResponse(data: unknown): unknown {
+ if (
+ data !== null &&
+ typeof data === 'object' &&
+ 'results' in data &&
+ Array.isArray(data.results) &&
+ 'next' in data &&
+ 'previous' in data &&
+ Object.keys(data).every((key) => ['results', 'next', 'count', 'previous'].includes(key))
+ ) {
+ return data.results
+ }
+
+ return data
+}
+
export function formatResponse(data: any): string {
if (typeof data === 'string') {
return data
}
const placeholderMap = new Map<string, string>()
- const processed = preprocessKeys(data, placeholderMap)
+ const processed = preprocessKeys(unwrapPaginatedResponse(data), placeholderMap)
let result = encode(processed)
for (const [placeholder, jsonValue] of placeholderMap.entries()) {
diff --git a/services/mcp/tests/unit/build-tool-result.test.ts b/services/mcp/tests/unit/build-tool-result.test.ts
index 9db75ef281a6..6ef9895607d1 100644
--- a/services/mcp/tests/unit/build-tool-result.test.ts
+++ b/services/mcp/tests/unit/build-tool-result.test.ts
@@ -10,6 +10,7 @@ import {
isToolCallPayload,
} from '@/lib/build-tool-result'
import { estimateTokens } from '@/lib/estimate-tokens'
+import { formatResponse } from '@/lib/response'
import { POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY, POSTHOG_META_KEY } from '@/tools/types'
import { APP_DATA_META_KEY } from '@/ui-apps/types'
@@ -353,6 +354,40 @@ describe('buildToolResultPayload — inline-exec UI host (forceUiDataToMeta)', (
})
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({
+ handlerResult,
+ toolName: 'mock-tool',
+ params: { output_format: outputFormat },
+ includeAppData: true,
+ })
+
+ expect(payload.content[0]!.text).toBe(
+ outputFormat === 'json' ? JSON.stringify(handlerResult) : formatResponse(handlerResult.results)
+ )
+ 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' },
+ { results: 'not a list', next: null, count: 1, previous: null },
+ ])('preserves non-pagination result objects: %j', (handlerResult) => {
+ const payload = buildToolResultPayload({
+ handlerResult,
+ toolName: 'mock-tool',
+ params: { output_format: 'json' },
+ })
+
+ expect(JSON.parse(payload.content[0]!.text)).toEqual(handlerResult)
+ })
+
it('preserves array handler results', () => {
const result = [{ id: 'template-1' }]
Object.defineProperty(result, POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY, {
diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.ts
index 8dd313583f37..3ac8b906ec6e 100644
--- a/services/mcp/tests/unit/exec.test.ts
+++ b/services/mcp/tests/unit/exec.test.ts
@@ -6,6 +6,7 @@ import { z } from 'zod'
import { STRUCTURED_CONTENT_ONLY_TEXT, type ToolResultPayload, UI_APP_RENDER_NOTE } from '@/lib/build-tool-result'
import { handleToolError, PostHogApiError, ToolInputValidationError } from '@/lib/errors'
import { estimateTokens } from '@/lib/estimate-tokens'
+import { formatResponse } from '@/lib/response'
import { buildQueryToolsBlock, buildToolDomainsCompact } from '@/lib/instructions'
import { InstructionsFormatter } from '@/lib/instructions-formatter'
import { SessionManager } from '@/lib/SessionManager'
@@ -393,6 +394,21 @@ describe('exec tool', () => {
expect(result).not.toBe(JSON.stringify({ id: 1, name: 'test', items: [{ a: 1 }, { a: 2 }] }))
})
+ it.each(['call mock-tool', 'call --json mock-tool'])(
+ 'uses the requested pagination format for %s',
+ async (command) => {
+ const results = [{ id: 1, name: 'example' }]
+ const handlerResult = { results, next: null, count: 1, previous: null }
+ const exec = createExec([makeMockTool({ handler: async () => handlerResult })])
+
+ const result = await exec.handler(mockContext, { command })
+
+ expect(result).toBe(
+ command.includes('--json') ? JSON.stringify(handlerResult) : formatResponse(results)
+ )
+ }
+ )
+
it('returns raw JSON when --json flag is passed in command', async () => {
const exec = createExec()
const result = await exec.handler(mockContext, { command: 'call --json mock-tool' })