: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(mcp): exec returns only formatted table in optimized mode (#57998)
Georgiy Tarasovd05eaa6f950c
diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex 40f6f772d956..9c54f6a7048f 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -6,7 +6,13 @@ import { isPostHogCodeConsumer } from '@/lib/client-detection'import { formatResponse } from '@/lib/response'import { TOKEN_CHAR_LIMIT, listAvailablePaths, resolveSchemaPath, summarizeSchema } from './schema-utils'-import { POSTHOG_META_KEY, type Context, type Tool, type ZodObjectAny } from './types'+import {+ POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY,+ POSTHOG_META_KEY,+ type Context,+ type Tool,+ type ZodObjectAny,+} from './types'type ExecSchema = ReturnType<typeof makeExecSchema>@@ -270,7 +276,23 @@ export function createExecTool(success: true,output_format: useJson ? 'json' : 'text',})- return useJson ? JSON.stringify(result) : formatResponse(result)+ if (useJson) {+ return JSON.stringify(result)+ }+ // Optimized mode: when the handler attached a backend-formatted table+ // via `__formatted_results_override`, return ONLY that string. The raw+ // `results`/`_posthogUrl` payload would otherwise duplicate the table+ // and crowd it out — buildToolResultPayload makes the same choice for+ // the non-exec path, this keeps exec consistent.+ if (result !== null && typeof result === 'object') {+ const formattedOverride = (result as Record<string, unknown>)[+ POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY+ ]+ if (typeof formattedOverride === 'string') {+ return formattedOverride+ }+ }+ return formatResponse(result)}default:diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex fa513b35bc8e..2fcb12566448 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -11,7 +11,13 @@ import { SessionManager } from '@/lib/SessionManager'import { getToolsFromContext } from '@/tools'import { createExecTool, type ExecInnerCallProperties } from '@/tools/exec'import { getToolDefinition } from '@/tools/toolDefinitions'-import { POSTHOG_META_KEY, type Context, type Tool, type ZodObjectAny } from '@/tools/types'+import {+ POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY,+ POSTHOG_META_KEY,+ type Context,+ type Tool,+ type ZodObjectAny,+} from '@/tools/types'function makeMockTool(overrides: Partial<Tool<ZodObjectAny>> = {}): Tool<ZodObjectAny> {return {@@ -73,6 +79,50 @@ describe('exec tool', () => {expect(parsed).toEqual({ id: 1, name: 'test', items: [{ a: 1 }, { a: 2 }] })})+ it('returns ONLY the formatted table when result has __formatted_results_override and mode is optimized', async () => {+ const tool = makeMockTool({+ handler: async () => ({+ results: [{ data: [1, 2, 3], count: 6 }],+ _posthogUrl: 'http://localhost:8010/insights/new#q=...',+ [POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]: 'Date|count\n2026-05-07|6',+ }),+ })+ const exec = createExec([tool])+ const result = await exec.handler(mockContext, { command: 'call mock-tool' })+ expect(result).toBe('Date|count\n2026-05-07|6')+ // Raw fields and the override key itself must not leak into optimized output+ expect(result).not.toContain('_posthogUrl')+ expect(result).not.toContain('results')+ expect(result).not.toContain('__formatted_results_override')+ })++ it('still TOON-encodes when __formatted_results_override is absent', async () => {+ const tool = makeMockTool({+ handler: async () => ({+ results: [{ data: [1, 2, 3], count: 6 }],+ _posthogUrl: 'http://localhost:8010/insights/new#q=...',+ }),+ })+ const exec = createExec([tool])+ const result = (await exec.handler(mockContext, { command: 'call mock-tool' })) as string+ expect(result).toContain('_posthogUrl')+ expect(result).toContain('results')+ })++ it('returns raw JSON (with override key) when --json flag is passed even if override is present', async () => {+ const tool = makeMockTool({+ handler: async () => ({+ results: [{ data: [1, 2, 3] }],+ [POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]: 'Date|count\n2026-05-07|6',+ }),+ })+ const exec = createExec([tool])+ const result = await exec.handler(mockContext, { command: 'call --json mock-tool' })+ const parsed = JSON.parse(result as string)+ expect(parsed.results).toEqual([{ data: [1, 2, 3] }])+ expect(parsed[POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]).toBe('Date|count\n2026-05-07|6')+ })+it('throws usage error for bare call', async () => {const exec = createExec()await expect(exec.handler(mockContext, { command: 'call' })).rejects.toThrow(