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.

50.6 KB
Raw Blame
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'

const { mockToolCallsInc, mockToolDurationObserve, mockToolDurationStartTimer, mockToolErrorsInc } = vi.hoisted(() => {
    const mockStop = vi.fn()
    return {
        mockToolCallsInc: vi.fn(),
        mockToolDurationObserve: vi.fn(),
        mockToolDurationStartTimer: vi.fn(() => mockStop),
        mockToolErrorsInc: vi.fn(),
    }
})

vi.mock('@/hono/metrics', () => ({
    toolCallsTotal: { inc: mockToolCallsInc },
    toolCallDurationSeconds: {
        observe: mockToolDurationObserve,
        startTimer: mockToolDurationStartTimer,
    },
    toolErrorsTotal: { inc: mockToolErrorsInc },
}))

vi.mock('@/hono/analytics', () => ({
    trackToolCall: vi.fn(),
    trackExecuteSqlGeneration: vi.fn(),
    trackToolSpan: vi.fn(),
}))

vi.mock('@/resources/internals', () => ({
    fetchContextMillResources: vi.fn().mockRejectedValue(new Error('mocked')),
    filterValidEntries: vi.fn().mockReturnValue([]),
    loadManifestFromArchive: vi.fn().mockReturnValue({ resources: [] }),
}))

vi.mock('@/resources', () => ({
    getPromptsFromManifest: vi.fn().mockResolvedValue([]),
}))

import { z } from 'zod'

import { ApiClient } from '@/api/client'
import { trackExecuteSqlGeneration, trackToolCall, trackToolSpan } from '@/hono/analytics'
import { InstructionsBuilder } from '@/hono/instructions'
import type { ResolvedState } from '@/hono/request-state-resolver'
import { ToolCatalog } from '@/hono/tool-catalog'
import { ToolExecutor } from '@/hono/tool-executor'
import {
    MCPToolResultError,
    PostHogApiError,
    PostHogRateLimitError,
    PostHogTransportError,
    PostHogValidationError,
    ToolInputValidationError,
    wrapError,
} from '@/lib/errors'
import { getPostHogClient } from '@/lib/posthog'
import { URI_MAP } from '@/resources/ui-apps.generated'
import { normalizeParamAliases } from '@/tools/cast-helpers'

import { makeToolExecutorState, mockApi, toolFromPreBuilt } from '../shared/test-utils'

const mockTrackToolCall = vi.mocked(trackToolCall)

/** Extra-properties bag passed to the 5th arg of `trackToolCall` for a given tool. */
function trackToolCallExtras(tool: string): Record<string, unknown> | undefined {
    const call = mockTrackToolCall.mock.calls.find((c) => c[0] === tool)
    return call?.[4]
}

function makeState(tools: { name: string }[], overrides: Partial<ResolvedState> = {}): ResolvedState {
    return makeToolExecutorState(tools as any, overrides)
}

type FakeToolBase = { schema: z.ZodObject<Record<string, never>>; handler: ReturnType<typeof vi.fn>; _meta: undefined }

function makeFakeTool(
    name: string,
    handler: () => Promise<unknown> = async () => 'ok'
): { name: string; build: () => FakeToolBase; base: FakeToolBase } {
    return {
        name,
        build() {
            return this.base
        },
        base: {
            schema: z.object({}),
            handler: vi.fn().mockImplementation(handler),
            _meta: undefined,
        },
    }
}

function callsFor(mock: ReturnType<typeof vi.fn>, tool: string): any[] {
    return mock.mock.calls.filter((c: any[]) => c[0]?.tool === tool).map((c: any[]) => c[0])
}

describe('ToolExecutor metrics', () => {
    let catalog: ToolCatalog
    let executor: ToolExecutor

    beforeAll(async () => {
        catalog = new ToolCatalog()
        await catalog.warmup()
    })

    beforeEach(() => {
        mockToolCallsInc.mockClear()
        mockToolDurationObserve.mockClear()
        mockToolDurationStartTimer.mockClear()
        mockToolErrorsInc.mockClear()
        mockTrackToolCall.mockClear()
        vi.mocked(trackExecuteSqlGeneration).mockClear()
        vi.mocked(trackToolSpan).mockClear()

        executor = new ToolExecutor(catalog, new InstructionsBuilder(''))
    })

    afterEach(() => {
        vi.unstubAllGlobals()
        vi.restoreAllMocks()
    })

    it.each([
        { tool: 'execute-sql', useSingleExec: false, type: 'api_5xx' },
        { tool: 'execute-sql', useSingleExec: false, type: 'internal' },
        { tool: 'execute-sql', useSingleExec: true, type: 'internal' },
        { tool: 'execute-sql', useSingleExec: true, type: 'validation' },
        { tool: 'execute-sql', useSingleExec: false, type: 'validation' },
        { tool: 'execute-sql', useSingleExec: false, type: 'memory_limit' },
        { tool: 'execute-sql', useSingleExec: true, type: 'memory_limit' },
        { tool: 'read-data-schema', useSingleExec: false, type: 'permission' },
        { tool: 'read-data-schema', useSingleExec: true, type: 'api_5xx' },
    ])(
        'classifies backend result errors without capturing caller content: %j',
        async ({ tool, useSingleExec, type }) => {
            const captureException = vi.spyOn(getPostHogClient(), 'captureException').mockImplementation(() => {})
            const tools = catalog
                .getPreBuiltEntries()
                .map((entry) => toolFromPreBuilt(catalog.getToolByName(entry.name)!, entry))
            const state = makeToolExecutorState(tools, { useSingleExec, suppressAnalytics: false })
            state.context.api = new ApiClient({ apiToken: 'phx_test', baseUrl: 'https://us.posthog.com' })
            state.context.stateManager.getProjectId = vi.fn().mockResolvedValue(2)
            const content = 'Tool failed: private caller query. You may retry with adjusted inputs.'
            vi.stubGlobal(
                'fetch',
                vi.fn().mockResolvedValue(
                    new Response(
                        JSON.stringify({
                            success: false,
                            content,
                            error_type: type,
                            error_code: type === 'validation' ? 'unknown_identifier' : undefined,
                        })
                    )
                )
            )
            const args = { query: tool === 'execute-sql' ? 'SELECT 1' : { kind: 'events' } }
            const result = await executor.handleToolCall(
                useSingleExec
                    ? { name: 'exec', arguments: { command: `call ${tool} ${JSON.stringify(args)}` } }
                    : { name: tool, arguments: args },
                state
            )

            expect(result).toMatchObject({
                isError: true,
                content: [{ type: 'text', text: `Error: [${tool}]: ${content}` }],
            })
            expect(mockToolErrorsInc).toHaveBeenCalledWith({ tool, error_type: type })
            expect(captureException).toHaveBeenCalledTimes(['validation', 'permission'].includes(type) ? 0 : 1)
            const properties = trackToolCallExtras(tool)
            expect(properties).toMatchObject({ $mcp_error_type: type, $mcp_error_message: `Tool failed: ${type}` })
            if (type === 'validation') {
                expect(properties?.$mcp_error_code).toBe('unknown_identifier')
            } else {
                expect(properties).not.toHaveProperty('$mcp_error_code')
            }
            expect(JSON.stringify(properties)).not.toContain('private caller query')
            const errorMetadata = {
                isError: true,
                errorMessage: `Tool failed: ${type}`,
            }
            expect(trackToolSpan).toHaveBeenCalledWith(
                tool,
                expect.objectContaining({
                    distinctId: state.distinctId,
                    requestContext: state.requestContext,
                    suppressAnalytics: false,
                }),
                expect.objectContaining(errorMetadata)
            )
            if (tool === 'execute-sql') {
                expect(trackExecuteSqlGeneration).toHaveBeenCalledOnce()
                expect(vi.mocked(trackExecuteSqlGeneration).mock.calls[0]?.[3]).toMatchObject(errorMetadata)
            }
        }
    )

    describe('direct tool calls', () => {
        it('records success counter and duration timer', async () => {
            vi.spyOn(catalog, 'getToolByName').mockReturnValue(makeFakeTool('my-tool') as any)

            await executor.handleToolCall(
                { name: 'my-tool', arguments: {} },
                makeToolExecutorState([{ name: 'my-tool' }])
            )

            expect(mockToolDurationStartTimer).toHaveBeenCalledWith({ tool: 'my-tool' })
            expect(mockToolCallsInc).toHaveBeenCalledWith({ tool: 'my-tool', status: 'success' })
            expect(mockToolDurationStartTimer.mock.results[0]!.value).toHaveBeenCalledWith({ status: 'success' })
        })

        it('records error counter, duration timer, and error classification on failure', async () => {
            vi.spyOn(catalog, 'getToolByName').mockReturnValue(
                makeFakeTool('fail-tool', async () => {
                    throw new Error('boom')
                }) as any
            )

            await executor.handleToolCall(
                { name: 'fail-tool', arguments: {} },
                makeToolExecutorState([{ name: 'fail-tool' }])
            )

            expect(mockToolCallsInc).toHaveBeenCalledWith({ tool: 'fail-tool', status: 'error' })
            expect(mockToolErrorsInc).toHaveBeenCalledWith({ tool: 'fail-tool', error_type: 'internal' })
            expect(mockToolDurationStartTimer.mock.results[0]!.value).toHaveBeenCalledWith({ status: 'error' })
        })

        it('stamps $mcp_error_type on the analytics event so the dashboard can slice failures by reason', async () => {
            vi.spyOn(catalog, 'getToolByName').mockReturnValue(
                makeFakeTool('fail-tool', async () => {
                    throw new Error('boom')
                }) as any
            )

            await executor.handleToolCall(
                { name: 'fail-tool', arguments: { experimentId: 29 } },
                makeState([{ name: 'fail-tool' }])
            )

            // The errored event carries the call's shape too; this is the path the
            // property exists for.
            expect(trackToolCallExtras('fail-tool')).toMatchObject({
                $mcp_error_type: 'internal',
                $mcp_input_keys: ['experimentId'],
            })
        })

        // $mcp_error_message is readable by every analytics viewer in the project, not just
        // the caller that received the tool result — so only messages whose shape WE control
        // are captured. Arbitrary thrown values echo caller input (document previews, SQL
        // fragments, upstream response bodies) and must never reach analytics.
        it.each([
            ['a generic Error', new Error('preview of caller document: SECRET=abc123')],
            ['a thrown string', 'raw string echoing tool input'],
            ['a non-Error object', { secret_payload: 'do not capture' }],
        ])('omits $mcp_error_message when the tool throws %s', async (_label, thrown) => {
            vi.spyOn(catalog, 'getToolByName').mockReturnValue(
                makeFakeTool('fail-tool', async () => {
                    throw thrown
                }) as any
            )

            await executor.handleToolCall(
                { name: 'fail-tool', arguments: {} },
                makeToolExecutorState([{ name: 'fail-tool' }])
            )

            const extras = trackToolCallExtras('fail-tool')
            expect(extras).toMatchObject({ $mcp_error_type: 'internal' })
            expect(extras).not.toHaveProperty('$mcp_error_message')
            expect(extras).not.toHaveProperty('$mcp_error_code')
            expect(extras).not.toHaveProperty('$mcp_error_field')
        })

        // The code and normalized field path are what make leaf failure modes measurable:
        // $mcp_error_message is free text, so dashboards can't group on it, and the raw
        // attr fragments per array index ("actions__0__...", "actions__3__...").
        it('stamps $mcp_error_code and index-normalized $mcp_error_field for a PostHogValidationError', async () => {
            vi.spyOn(catalog, 'getToolByName').mockReturnValue(
                makeFakeTool('fail-tool', async () => {
                    throw new PostHogValidationError({
                        detail: "Email input must contain a 'from' property",
                        attr: 'actions__2__inputs__email',
                        code: 'invalid_input',
                        extra: undefined,
                        url: 'https://us.posthog.com/api/environments/2/hog_flows/',
                        method: 'POST',
                    })
                }) as any
            )

            await executor.handleToolCall(
                { name: 'fail-tool', arguments: {} },
                makeToolExecutorState([{ name: 'fail-tool' }])
            )

            const extras = trackToolCallExtras('fail-tool')
            expect(extras).toMatchObject({
                $mcp_error_type: 'validation',
                $mcp_error_code: 'invalid_input',
                $mcp_error_field: 'actions__N__inputs__email',
            })
            // The detail body echoes caller input, so it must never ride along.
            expect(JSON.stringify(extras)).not.toContain("'from' property")
        })

        // A tool that fails inside PostHog's backend answers with an error type and, when the
        // backend knows it, the leaf failure name. Without the name every such failure reads
        // as one `internal` or `validation` bucket.
        it.each([
            ['a code from the backend', 'unknown_identifier', 'unknown_identifier'],
            ['a code with control characters', 'bad\ncode ', 'badcode'],
        ])('stamps $mcp_error_code for an MCPToolResultError with %s', async (_label, errorCode, expected) => {
            vi.spyOn(catalog, 'getToolByName').mockReturnValue(
                makeFakeTool('fail-tool', async () => {
                    throw new MCPToolResultError('Tool failed', 'validation', errorCode)
                }) as any
            )

            await executor.handleToolCall(
                { name: 'fail-tool', arguments: {} },
                makeToolExecutorState([{ name: 'fail-tool' }])
            )

            expect(trackToolCallExtras('fail-tool')).toMatchObject({
                $mcp_error_type: 'validation',
                $mcp_error_code: expected,
            })
        })

        it('omits $mcp_error_code for an MCPToolResultError without a code', async () => {
            vi.spyOn(catalog, 'getToolByName').mockReturnValue(
                makeFakeTool('fail-tool', async () => {
                    throw new MCPToolResultError('Tool failed', 'internal')
                }) as any
            )

            await executor.handleToolCall(
                { name: 'fail-tool', arguments: {} },
                makeToolExecutorState([{ name: 'fail-tool' }])
            )

            const extras = trackToolCallExtras('fail-tool')
            expect(extras).toMatchObject({ $mcp_error_type: 'internal' })
            expect(extras).not.toHaveProperty('$mcp_error_code')
        })

        it.each([
            [
                'a ToolInputValidationError (value-free field descriptors)',
                new ToolInputValidationError('Invalid input for tool: date_from (invalid_type)', {
                    fields: ['date_from'],
                }),
                'Invalid input for tool: date_from (invalid_type)',
            ],
            [
                'a PostHogValidationError (controlled code + field only, never the detail body)',
                new PostHogValidationError({
                    // detail echoes the caller's offending expression; a query tool caller can
                    // hide a secret here, so it must never reach analytics.
                    detail: 'Unable to resolve field: SECRET=sk_live_abc123',
                    attr: 'query',
                    code: 'invalid_input',
                    extra: undefined,
                    url: 'https://us.posthog.com/api/environments/2/query/',
                    method: 'POST',
                }),
                'Validation error: invalid_input (field: query)',
            ],
            [
                'a TimeoutError',
                Object.assign(new Error('deadline of 30000ms exceeded while calling https://internal.example'), {
                    name: 'TimeoutError',
                }),
                'Tool call timed out',
            ],
        ])('stamps $mcp_error_message for %s', async (_label, thrown, expected) => {
            vi.spyOn(catalog, 'getToolByName').mockReturnValue(
                makeFakeTool('fail-tool', async () => {
                    throw thrown
                }) as any
            )

            await executor.handleToolCall(
                { name: 'fail-tool', arguments: {} },
                makeToolExecutorState([{ name: 'fail-tool' }])
            )

            expect(trackToolCallExtras('fail-tool')).toMatchObject({ $mcp_error_message: expected })
        })

        // An API-layer rejection used to carry no structured field, so it was only
        // reachable by string-parsing $mcp_error_message. It now populates the same
        // property a local schema rejection does — the API's free-text `detail` still
        // never reaches analytics.
        it('stamps $mcp_validation_fields for an API validation error, without the detail body', async () => {
            vi.spyOn(catalog, 'getToolByName').mockReturnValue(
                makeFakeTool('fail-tool', async () => {
                    throw new PostHogValidationError({
                        detail: 'Unable to resolve field: SECRET=sk_live_abc123',
                        attr: 'series.0.event',
                        code: 'invalid_input',
                        extra: undefined,
                        url: 'https://us.posthog.com/api/environments/2/query/',
                        method: 'POST',
                    })
                }) as any
            )

            await executor.handleToolCall(
                { name: 'fail-tool', arguments: {} },
                makeToolExecutorState([{ name: 'fail-tool' }])
            )

            const extras = trackToolCallExtras('fail-tool')
            expect(extras).toMatchObject({
                $mcp_error_type: 'validation',
                // Array indices collapse here too, matching the schema path.
                $mcp_validation_fields: ['series.N.event:invalid_input'],
            })
            expect(JSON.stringify(extras)).not.toContain('sk_live_abc123')
        })

        it('rebuilds PostHogApiError messages from status + path, never the response body or query string', async () => {
            vi.spyOn(catalog, 'getToolByName').mockReturnValue(
                makeFakeTool('fail-tool', async () => {
                    throw new PostHogApiError({
                        status: 502,
                        statusText: 'Bad Gateway',
                        body: '{"secret": "upstream response body must not leak"}',
                        url: 'https://us.posthog.com/api/environments/2/insights/?token=sk_live_secret',
                        method: 'GET',
                    })
                }) as any
            )

            await executor.handleToolCall(
                { name: 'fail-tool', arguments: {} },
                makeToolExecutorState([{ name: 'fail-tool' }])
            )

            expect(trackToolCallExtras('fail-tool')).toMatchObject({
                $mcp_error_message: 'HTTP 502 Bad Gateway on GET /api/environments/2/insights/',
            })
        })

        it('truncates $mcp_error_message and strips control characters, keeping newlines', async () => {
            vi.spyOn(catalog, 'getToolByName').mockReturnValue(
                makeFakeTool('fail-tool', async () => {
                    // ToolInputValidationError.message is passed through verbatim, so it exercises
                    // the sanitizer/truncation path in extractErrorMessage.
                    throw new ToolInputValidationError(`line2\x00\x08${'x'.repeat(3000)}`, { fields: ['date_from'] })
                }) as any
            )

            await executor.handleToolCall(
                { name: 'fail-tool', arguments: {} },
                makeToolExecutorState([{ name: 'fail-tool' }])
            )

            const message = trackToolCallExtras('fail-tool')?.$mcp_error_message as string
            expect(message.startsWith('line2xxx')).toBe(true)
            expect(message).toHaveLength(2048)
        })

        it('carries the upstream status alongside the error type for API failures', async () => {
            vi.spyOn(catalog, 'getToolByName').mockReturnValue(
                makeFakeTool('execute-sql', async () => {
                    throw new PostHogRateLimitError({
                        body: '{}',
                        url: 'https://us.posthog.com/api/environments/2/mcp_tools/execute_sql/',
                        method: 'POST',
                        retryAfterSeconds: 5,
                    })
                }) as any
            )

            await executor.handleToolCall(
                { name: 'execute-sql', arguments: {} },
                makeToolExecutorState([{ name: 'execute-sql' }])
            )

            expect(trackToolCallExtras('execute-sql')).toMatchObject({
                $mcp_error_type: 'rate_limited',
                $mcp_error_status: 429,
                // Subclasses of PostHogApiError get the same rebuilt-safe message shape.
                $mcp_error_message: 'HTTP 429 Too Many Requests on POST /api/environments/2/mcp_tools/execute_sql/',
            })
        })

        it('classifies a downstream 429 as rate_limited, keeping it out of the error rate', async () => {
            vi.spyOn(catalog, 'getToolByName').mockReturnValue(
                makeFakeTool('execute-sql', async () => {
                    throw new PostHogRateLimitError({
                        body: '{}',
                        url: 'https://us.posthog.com/api/environments/2/mcp_tools/execute_sql/',
                        method: 'POST',
                        retryAfterSeconds: 5,
                    })
                }) as any
            )

            await executor.handleToolCall(
                { name: 'execute-sql', arguments: {} },
                makeToolExecutorState([{ name: 'execute-sql' }])
            )

            expect(mockToolErrorsInc).toHaveBeenCalledWith({ tool: 'execute-sql', error_type: 'rate_limited' })
        })

        it('classifies a 429 wrapped in a cause chain as rate_limited', async () => {
            vi.spyOn(catalog, 'getToolByName').mockReturnValue(
                makeFakeTool('execute-sql', async () => {
                    throw wrapError(
                        'Failed to run query',
                        new PostHogRateLimitError({
                            body: '{}',
                            url: 'https://us.posthog.com/api/environments/2/mcp_tools/execute_sql/',
                            method: 'POST',
                            retryAfterSeconds: null,
                        })
                    )
                }) as any
            )

            await executor.handleToolCall(
                { name: 'execute-sql', arguments: {} },
                makeToolExecutorState([{ name: 'execute-sql' }])
            )

            expect(mockToolErrorsInc).toHaveBeenCalledWith({ tool: 'execute-sql', error_type: 'rate_limited' })
        })

        it.each([
            ['a transport error', (error: Error): Error => error],
            [
                'a transport error wrapped in a cause chain',
                (error: Error): Error => wrapError('Failed to get insight', error),
            ],
        ])('classifies a request deadline on %s as timeout', async (_label, wrap) => {
            vi.spyOn(catalog, 'getToolByName').mockReturnValue(
                makeFakeTool('insight-query', async () => {
                    throw wrap(
                        new PostHogTransportError({
                            url: 'https://us.posthog.com/api/environments/2/insights/1/',
                            method: 'GET',
                            attempts: 1,
                            retryable: true,
                            cause: new DOMException('No response within 120 seconds', 'TimeoutError'),
                        })
                    )
                }) as any
            )

            await executor.handleToolCall(
                { name: 'insight-query', arguments: {} },
                makeToolExecutorState([{ name: 'insight-query' }])
            )

            expect(mockToolErrorsInc).toHaveBeenCalledWith({ tool: 'insight-query', error_type: 'timeout' })
        })

        it('records validation_error without starting a timer', async () => {
            vi.spyOn(catalog, 'getToolByName').mockReturnValue({
                name: 'strict-tool',
                build() {
                    return this.base
                },
                base: { schema: z.object({ required_field: z.string() }), handler: vi.fn(), _meta: undefined },
            } as any)

            await executor.handleToolCall(
                { name: 'strict-tool', arguments: {} },
                makeToolExecutorState([{ name: 'strict-tool' }])
            )

            expect(mockToolCallsInc).toHaveBeenCalledWith({ tool: 'strict-tool', status: 'validation_error' })
            expect(mockToolDurationStartTimer).not.toHaveBeenCalled()
        })

        // The direct path used to return before tracking, so a schema rejection in
        // 'tools' mode produced no `$mcp_tool_call` at all — leaving every
        // exec-vs-direct error comparison silently flattering direct mode. Pin both
        // the event and the value-free diagnostics that make it actionable.
        it('emits an errored analytics event with the rejected fields on a schema rejection', async () => {
            vi.spyOn(catalog, 'getToolByName').mockReturnValue({
                name: 'strict-tool',
                build() {
                    return this.base
                },
                base: { schema: z.object({ required_field: z.string() }), handler: vi.fn(), _meta: undefined },
            } as any)

            await executor.handleToolCall(
                { name: 'strict-tool', arguments: { requiredField: 'sent under the wrong name' } },
                makeToolExecutorState([{ name: 'strict-tool' }])
            )

            // Exactly one event: the rejection returns before the handler runs, so
            // neither the success nor the catch tracker can also fire. A second emit
            // here would double-count the call in every error-rate metric.
            const calls = mockTrackToolCall.mock.calls.filter((c) => c[0] === 'strict-tool')
            expect(calls).toHaveLength(1)
            const call = calls[0]!
            expect(call[2]).toBe(true)
            // No handler ran, so the call carries no duration (mirrors the exec path).
            expect(call[1]).toBe(0)
            expect(trackToolCallExtras('strict-tool')).toMatchObject({
                $mcp_error_type: 'validation',
                $mcp_input_keys: ['requiredField'],
                // `:undefined` is the received type — the param was absent, not
                // mistyped, which is what separates an alias slip from a coercion bug.
                $mcp_validation_fields: ['required_field:invalid_type:undefined'],
            })
        })

        it('stamps the emptiness the response builder recorded', async () => {
            vi.spyOn(catalog, 'getToolByName').mockReturnValue(
                makeFakeTool('query-error-tracking-issues-list', async () => ({ results: [] })) as any
            )

            await executor.handleToolCall(
                { name: 'query-error-tracking-issues-list', arguments: {} },
                makeToolExecutorState([{ name: 'query-error-tracking-issues-list' }])
            )

            expect(trackToolCallExtras('query-error-tracking-issues-list')).toMatchObject({
                mcp_result_empty: true,
            })
        })

        // The shape is read from the raw input, before preprocess folds the alias away.
        it('stamps the input keys and the alias used on a successful direct call', async () => {
            vi.spyOn(catalog, 'getToolByName').mockReturnValue({
                name: 'alias-tool',
                build() {
                    return this.base
                },
                base: {
                    schema: z.preprocess(normalizeParamAliases({ id: ['experimentId'] }), z.object({ id: z.number() })),
                    handler: vi.fn().mockResolvedValue('ok'),
                    _meta: undefined,
                },
            } as any)

            await executor.handleToolCall(
                { name: 'alias-tool', arguments: { experimentId: 29, llm_model: 'claude', context: {} } },
                makeState([{ name: 'alias-tool' }])
            )

            const call = mockTrackToolCall.mock.calls.find((c) => c[0] === 'alias-tool')!
            expect(call[2]).toBe(false)
            expect(call[4]).toMatchObject({
                // SDK-injected arguments are not something the agent chose to send.
                $mcp_input_keys: ['experimentId'],
                $mcp_input_aliases_used: ['experimentId:id'],
            })
            expect(JSON.stringify(call[4])).not.toContain('29')
        })

        // `params.arguments` is whatever JSON arrived. A string or array is rejected by
        // the schema, and must not be walked as if it were an argument object first.
        it('records no input keys when arguments is not an object', async () => {
            vi.spyOn(catalog, 'getToolByName').mockReturnValue(makeFakeTool('ok-tool') as any)

            await executor.handleToolCall(
                { name: 'ok-tool', arguments: 'x'.repeat(10_000) as unknown as Record<string, unknown> },
                makeState([{ name: 'ok-tool' }])
            )

            const call = mockTrackToolCall.mock.calls.find((c) => c[0] === 'ok-tool')!
            expect(call[2]).toBe(true)
            expect(call[4]).not.toHaveProperty('$mcp_input_keys')
        })

        it('stamps the input keys on a rejected direct call, without an alias property', async () => {
            vi.spyOn(catalog, 'getToolByName').mockReturnValue({
                name: 'strict-tool',
                build() {
                    return this.base
                },
                base: { schema: z.object({ required_field: z.string() }), handler: vi.fn(), _meta: undefined },
            } as any)

            await executor.handleToolCall(
                { name: 'strict-tool', arguments: { requiredField: 'x' } },
                makeState([{ name: 'strict-tool' }])
            )

            const extras = trackToolCallExtras('strict-tool')
            expect(extras).toMatchObject({ $mcp_input_keys: ['requiredField'] })
            expect(extras).not.toHaveProperty('$mcp_input_aliases_used')
        })

        it('returns the structured tool error when the session lookup fails', async () => {
            vi.spyOn(catalog, 'getToolByName').mockReturnValue(
                makeFakeTool('failing-tool', async () => {
                    throw new Error('boom')
                }) as any
            )
            const state = makeState([{ name: 'failing-tool' }])
            vi.mocked(state.reqCtx.getEffectiveSessionUuid).mockRejectedValue(new Error('redis down'))

            const result = await executor.handleToolCall({ name: 'failing-tool', arguments: {} }, state)

            expect((result as any).isError).toBe(true)
        })

        it('records error for unknown tool', async () => {
            await executor.handleToolCall({ name: 'nonexistent', arguments: {} }, makeToolExecutorState([]))

            expect(mockToolCallsInc).toHaveBeenCalledWith({ tool: 'nonexistent', status: 'error' })
        })
    })

    describe('single-exec mode', () => {
        function execState(): ResolvedState {
            // Mirror getFilteredTools: full tool objects with real schemas and
            // handlers, so exec's inner dispatch (schema validation, handler
            // call) behaves as in production.
            const tools = catalog
                .getPreBuiltEntries()
                .map((entry) => toolFromPreBuilt(catalog.getToolByName(entry.name)!, entry))
            return makeToolExecutorState(tools as any, { useSingleExec: true })
        }

        it('emits no exec-labelled counter or timer on success', async () => {
            await executor.handleToolCall({ name: 'exec', arguments: { command: 'tools' } }, execState())

            expect(callsFor(mockToolCallsInc, 'exec')).toHaveLength(0)
            expect(callsFor(mockToolDurationStartTimer, 'exec')).toHaveLength(0)
        })

        // Without the verb, every non-`call` command lands in one undifferentiated
        // `exec` bucket — schema discovery, tool search and a mistyped verb become
        // indistinguishable, and `unknown_command` records nothing to diagnose.
        // `$mcp_exec_target_tool` is what links an `info <tool>` to the `call <tool>`
        // that follows it, and is the only trace of an attempted unknown tool.
        it.each([
            ['tools', { $mcp_exec_verb: 'tools' }],
            ['info docs-search', { $mcp_exec_verb: 'info', $mcp_exec_target_tool: 'docs-search' }],
            ['schema docs-search query', { $mcp_exec_verb: 'schema', $mcp_exec_target_tool: 'docs-search' }],
            // A verb or tool name we don't recognize is caller text, so the event
            // records that it was unrecognized rather than the token itself.
            ['frobnicate whatever', { $mcp_exec_verb: 'unrecognized' }],
            ['call not-a-real-tool {}', { $mcp_exec_verb: 'call', $mcp_exec_target_tool: 'unrecognized' }],
            [
                'learn -s "funnel conversion"',
                {
                    $mcp_exec_verb: 'learn',
                    exec_learn_kind: 'search',
                    exec_search_query: 'funnel conversion',
                    $mcp_error_code: 'unknown_command',
                },
            ],
        ])('stamps the exec verb and target for "%s"', async (command, expected) => {
            await executor.handleToolCall({ name: 'exec', arguments: { command } }, execState())

            const call = mockTrackToolCall.mock.calls.at(-1)
            expect(call?.[4]).toMatchObject(expected)
        })

        it.each([
            ['an empty results envelope', async () => ({ results: [] }), true],
            ['a populated result', async () => ({ results: [{ id: 1 }] }), false],
        ])('reports emptiness of %s on an exec-routed call', async (_label, handler, empty) => {
            const tool = { ...makeFakeTool('query-error-tracking-issues-list', handler).base }
            await executor.handleToolCall(
                { name: 'exec', arguments: { command: 'call query-error-tracking-issues-list {}' } },
                makeToolExecutorState([{ name: 'query-error-tracking-issues-list', ...tool }], { useSingleExec: true })
            )

            const extras = mockTrackToolCall.mock.calls.at(-1)?.[4]
            expect(extras?.mcp_result_empty).toBe(empty ? true : undefined)
        })

        // In exec mode the inner arguments are JSON inside `command`, so the direct
        // path's wiring alone would record nothing about the shape of nearly every call.
        it('stamps the inner input keys and alias on an exec call', async () => {
            await executor.handleToolCall(
                {
                    name: 'exec',
                    arguments: { command: 'call feature-flag-get-definition-by-key {"flagKey": "checkout-v2"}' },
                },
                execState()
            )

            const extras = mockTrackToolCall.mock.calls.at(-1)?.[4]
            expect(extras).toMatchObject({
                $mcp_exec_verb: 'call',
                $mcp_input_keys: ['flagKey'],
                $mcp_input_aliases_used: ['flagKey:key'],
            })
            expect(JSON.stringify(extras)).not.toContain('checkout-v2')
        })

        it.each([
            ['info docs-search'],
            ['schema docs-search query'],
            ['tools'],
            // An unparseable body carries no keys either.
            ['call docs-search {not json'],
        ])('stamps no input keys for "%s"', async (command) => {
            await executor.handleToolCall({ name: 'exec', arguments: { command } }, execState())

            expect(mockTrackToolCall.mock.calls.at(-1)?.[4]).not.toHaveProperty('$mcp_input_keys')
        })

        it.each(['gated_tool', 'tool_not_granted'] as const)('stamps the target tool on %s', async (reason) => {
            const state = execState()
            state.allTools = state.allTools.filter((tool) => tool.name !== 'notebooks-create')
            if (reason === 'gated_tool') {
                state.flagGatedTools = [{ name: 'notebooks-create', supersededBy: ['notebooks-create-markdown'] }]
            } else {
                state.scopeGatedTools = []
                state.flagGatedTools = []
                state.heldTools = new Set(['docs-search'])
            }

            await executor.handleToolCall({ name: 'exec', arguments: { command: 'call notebooks-create {}' } }, state)

            expect(mockTrackToolCall.mock.calls.at(-1)?.[4]).toMatchObject({
                $mcp_exec_verb: 'call',
                $mcp_exec_target_tool: 'notebooks-create',
                $mcp_error_code: reason,
            })
        })

        it('emits inner tool name for counter and duration on inner tool call', async () => {
            await executor.handleToolCall(
                { name: 'exec', arguments: { command: 'call docs-search {"query": "test"}' } },
                execState()
            )

            const innerCounts = callsFor(mockToolCallsInc, 'docs-search')
            expect(innerCounts.length).toBeGreaterThan(0)
            expect(innerCounts[0].status).toMatch(/^(success|error)$/)

            const innerDurations = mockToolDurationObserve.mock.calls.filter((c: any[]) => c[0]?.tool === 'docs-search')
            expect(innerDurations.length).toBeGreaterThan(0)

            expect(callsFor(mockToolCallsInc, 'exec')).toHaveLength(0)
        })

        it('classifies inner tool errors under the inner tool name, not exec', async () => {
            await executor.handleToolCall(
                { name: 'exec', arguments: { command: 'call docs-search {"query": "test"}' } },
                execState()
            )

            const innerClassifications = callsFor(mockToolErrorsInc, 'docs-search')
            const execClassifications = callsFor(mockToolErrorsInc, 'exec')

            expect(innerClassifications.length).toBeGreaterThan(0)
            expect(innerClassifications[0].error_type).toBeTruthy()
            expect(execClassifications).toHaveLength(0)
        })

        it('records inner validation_error without a duration observation', async () => {
            await executor.handleToolCall({ name: 'exec', arguments: { command: 'call docs-search {}' } }, execState())

            expect(callsFor(mockToolCallsInc, 'docs-search')).toEqual([
                { tool: 'docs-search', status: 'validation_error' },
            ])
            const innerDurations = mockToolDurationObserve.mock.calls.filter((c: any[]) => c[0]?.tool === 'docs-search')
            expect(innerDurations).toHaveLength(0)
            expect(callsFor(mockToolCallsInc, 'exec')).toHaveLength(0)
        })

        it('classifies inner validation failures as validation, not internal', async () => {
            await executor.handleToolCall({ name: 'exec', arguments: { command: 'call docs-search {}' } }, execState())

            expect(callsFor(mockToolErrorsInc, 'docs-search')).toEqual([
                { tool: 'docs-search', error_type: 'validation' },
            ])
            expect(callsFor(mockToolErrorsInc, 'exec')).toHaveLength(0)
        })

        // Dispatcher rejections are agent mistakes, not server faults: they must not
        // land in the `internal` bucket the error-rate alert watches, they stay
        // attributed to `exec` (no inner tool ran), and they must carry a value-free
        // message so the failure is debuggable from analytics.
        it.each([
            ['call nonexistent-tool-xyz {}', 'unknown_tool'],
            ['frobnicate', 'unknown_command'],
            ['docs-search {"query":"funnels"}', 'tool_as_command'],
            ['call docs-search {not json}', 'invalid_json'],
        ])('classifies %s as validation', async (command, reason) => {
            await executor.handleToolCall({ name: 'exec', arguments: { command } }, execState())

            expect(callsFor(mockToolCallsInc, 'exec')).toEqual([{ tool: 'exec', status: 'validation_error' }])
            expect(callsFor(mockToolErrorsInc, 'exec')).toEqual([{ tool: 'exec', error_type: 'validation' }])
            expect(trackToolCallExtras('exec')).toMatchObject({
                $mcp_error_type: 'validation',
                $mcp_error_code: reason,
                $mcp_error_message: `Exec command rejected: ${reason}`,
            })
        })

        it('classifies a scope-gated tool as permission, not validation', async () => {
            // The agent can't fix this by sending different input — the connection has
            // to be reauthorized, which is what the permission-rate alert watches for.
            const state = execState()
            state.scopeGatedTools = [{ name: 'gated-tool', missingScopes: ['insight:read'] }] as any

            await executor.handleToolCall({ name: 'exec', arguments: { command: 'info gated-tool' } }, state)

            expect(callsFor(mockToolErrorsInc, 'exec')).toEqual([{ tool: 'exec', error_type: 'permission' }])
            expect(trackToolCallExtras('exec')).toMatchObject({
                $mcp_error_message: 'Exec command rejected: missing_scope',
            })
        })

        it('emits an errored event when the exec wrapper schema rejects the arguments', async () => {
            const result = await executor.handleToolCall({ name: 'exec', arguments: { cmd: 'tools' } }, execState())

            expect((result as any).isError).toBe(true)
            expect(callsFor(mockToolCallsInc, 'exec')).toEqual([{ tool: 'exec', status: 'validation_error' }])
            const call = mockTrackToolCall.mock.calls.find((c) => c[0] === 'exec')
            expect(call?.[1]).toBe(0)
            expect(call?.[2]).toBe(true)
            expect(call?.[4]).toMatchObject({
                $mcp_input_keys: ['cmd'],
                $mcp_error_type: 'validation',
            })
            expect(call?.[4]).not.toHaveProperty('$mcp_exec_verb')
        })

        // Reading a stored skill is one of the most common tool calls, and nearly all of
        // them arrive here, as JSON inside a command string rather than as tool arguments.
        // Without this the event records that *a* skill was read but never which one.
        describe('skill reads', () => {
            function lastExtras(): Record<string, unknown> {
                return (mockTrackToolCall.mock.calls.at(-1)?.[4] ?? {}) as Record<string, unknown>
            }

            /** A context whose skill fetch resolves, so the success path runs. */
            function contextThatServes(): any {
                return {
                    api: mockApi({ request: vi.fn().mockResolvedValue({ name: 'conductor', body: 'skill body' }) }),
                    cache: {},
                    env: {},
                    stateManager: { getProjectId: vi.fn().mockResolvedValue('2') },
                    sessionManager: {},
                    getDistinctId: vi.fn(),
                    trackEvent: vi.fn(),
                }
            }

            /** A context whose skill fetch 404s — a deleted, renamed, or unreadable skill. */
            function contextThatRejects(): any {
                return {
                    ...contextThatServes(),
                    api: mockApi({
                        request: vi.fn().mockRejectedValue(
                            new PostHogApiError({
                                status: 404,
                                statusText: 'Not Found',
                                body: '{"detail":"Not found."}',
                                url: 'https://us.posthog.com/api/projects/2/llm_skills/name/conductor/',
                                method: 'GET',
                            })
                        ),
                    }),
                }
            }

            /** A context whose skill fetch 404s with the store's own lookup detail,
             *  which is the only 404 the dispatcher rewrites into a plain result. */
            function contextThatMisses(): any {
                return {
                    ...contextThatServes(),
                    api: mockApi({
                        request: vi.fn().mockRejectedValue(
                            new PostHogApiError({
                                status: 404,
                                statusText: 'Not Found',
                                body: '{"detail":"Skill with name \'conductor\' not found."}',
                                url: 'https://us.posthog.com/api/projects/2/llm_skills/name/conductor/',
                                method: 'GET',
                            })
                        ),
                    }),
                }
            }

            function execStateWith(context: any): ResolvedState {
                return { ...execState(), context }
            }

            it.each([
                ['a body read', 'call skill-get {"skill_name":"conductor"}', { $mcp_skill_name: 'conductor' }],
                [
                    'a paged continuation',
                    'call skill-get {"skill_name":"conductor","body_offset":5000}',
                    { $mcp_skill_name: 'conductor', $mcp_skill_body_offset: 5000 },
                ],
                [
                    'a bundled-file read',
                    'call skill-file-get {"skill_name":"conductor","file_path":"references/x.md"}',
                    { $mcp_skill_name: 'conductor' },
                ],
            ])('records the skill when %s succeeds', async (_label, command, expected) => {
                await executor.handleToolCall(
                    { name: 'exec', arguments: { command } },
                    execStateWith(contextThatServes())
                )

                expect(lastExtras()).toMatchObject(expected)
            })

            // A skill that was never delivered is not usage. Stamping it would let a
            // deleted skill that agents keep requesting read as popular.
            it.each([
                ['a body read', 'call skill-get {"skill_name":"conductor","body_offset":5000}'],
                ['a bundled-file read', 'call skill-file-get {"skill_name":"conductor","file_path":"x.md"}'],
            ])('records no skill when %s fails', async (_label, command) => {
                await executor.handleToolCall(
                    { name: 'exec', arguments: { command } },
                    execStateWith(contextThatRejects())
                )

                expect(lastExtras()).not.toHaveProperty('$mcp_skill_name')
                expect(lastExtras()).not.toHaveProperty('$mcp_skill_body_offset')
            })

            // The agent reads a lookup miss as a plain result, but the miss rate has to
            // stay measurable. Recording the rewritten result as a success would hide
            // every deleted or renamed skill agents keep asking for.
            it('records a rewritten lookup miss as a failed call', async () => {
                const response: any = await executor.handleToolCall(
                    { name: 'exec', arguments: { command: 'call skill-get {"skill_name":"conductor"}' } },
                    execStateWith(contextThatMisses())
                )

                expect(response.isError).toBeFalsy()
                expect(mockTrackToolCall.mock.calls.at(-1)?.[2]).toBe(true)
                expect(lastExtras()).not.toHaveProperty('$mcp_skill_name')
                expect(lastExtras()).toMatchObject({ $mcp_error_type: 'api_4xx', $mcp_error_status: 404 })
                expect(callsFor(mockToolErrorsInc, 'skill-get')).toEqual([{ tool: 'skill-get', error_type: 'api_4xx' }])
            })

            // Dropping the skill must not take the exec properties with it — those are
            // stamped on failures by design, and are the only record of what was tried.
            it('keeps the exec verb and target when a skill read fails', async () => {
                await executor.handleToolCall(
                    { name: 'exec', arguments: { command: 'call skill-get {"skill_name":"conductor"}' } },
                    execStateWith(contextThatRejects())
                )

                expect(lastExtras()).toMatchObject({
                    $mcp_exec_verb: 'call',
                    $mcp_exec_target_tool: 'skill-get',
                })
            })

            it.each([
                // The agent's text, not a skill that could exist — same rule the exec
                // verb and target follow.
                ['a skill name outside the store’s own shape', 'call skill-get {"skill_name":"../../etc/passwd"}'],
                ['a non-skill tool', 'call docs-search {"query":"skill_name"}'],
            ])('records no skill for %s', async (_label, command) => {
                await executor.handleToolCall(
                    { name: 'exec', arguments: { command } },
                    execStateWith(contextThatServes())
                )

                expect(lastExtras()).not.toHaveProperty('$mcp_skill_name')
            })

            it('records the skill in direct tools mode too', async () => {
                const tools = catalog
                    .getPreBuiltEntries()
                    .map((entry) => toolFromPreBuilt(catalog.getToolByName(entry.name)!, entry))

                await executor.handleToolCall(
                    { name: 'skill-get', arguments: { skill_name: 'conductor' } },
                    makeToolExecutorState(tools as any, { context: contextThatServes() })
                )

                expect(trackToolCallExtras('skill-get')).toMatchObject({ $mcp_skill_name: 'conductor' })
            })
        })
    })

    describe('render-ui', () => {
        const uiAppTool = {
            name: 'survey-get',
            annotations: { readOnlyHint: true },
            _meta: { ui: { resourceUri: URI_MAP['survey'] } },
        }

        it('emits an errored event when the wrapper schema rejects the arguments', async () => {
            const result = await executor.handleToolCall(
                { name: 'render-ui', arguments: { toolName: 'survey-get' } },
                makeState([uiAppTool], { useSingleExec: true, renderUiEnabled: true })
            )

            expect((result as any).isError).toBe(true)
            expect(callsFor(mockToolCallsInc, 'render-ui')).toEqual([{ tool: 'render-ui', status: 'validation_error' }])
            const call = mockTrackToolCall.mock.calls.find((c) => c[0] === 'render-ui')
            expect(call?.[1]).toBe(0)
            expect(call?.[2]).toBe(true)
            expect(call?.[4]).toMatchObject({
                $mcp_input_keys: ['toolName'],
                $mcp_error_type: 'validation',
            })
        })
    })
})