: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
feat(phai): llma-parser-recipe-create with server-side validation (#69287)
Georgiy Tarasov0528aedb6c2c
diff --git a/.github/workflows/cd-mcp-image.yml b/.github/workflows/cd-mcp-image.ymlindex 3964327778a6..c24e08da57ff 100644--- a/.github/workflows/cd-mcp-image.yml+++ b/.github/workflows/cd-mcp-image.yml@@ -13,6 +13,12 @@ on:paths:- 'services/mcp/**'- '.github/workflows/cd-mcp-image.yml'+ # Bundled into the MCP image at build time (copy-instructions.ts `shared/` copy ++ # shared parser sources) — without these paths an edit there never rebuilds the+ # image and the bundle goes stale.+ - 'products/ai_observability/backend/prompts/parser_recipe_examples.yaml'+ - 'products/ai_observability/frontend/customParser/**'+ - 'products/ai_observability/frontend/normalizer/**'# paths mirror the push trigger; the build-mcp-image label only forces a# build on PRs touching these paths, use workflow_dispatch otherwise.pull_request:@@ -20,6 +26,9 @@ on:paths:- 'services/mcp/**'- '.github/workflows/cd-mcp-image.yml'+ - 'products/ai_observability/backend/prompts/parser_recipe_examples.yaml'+ - 'products/ai_observability/frontend/customParser/**'+ - 'products/ai_observability/frontend/normalizer/**'workflow_dispatch:jobs:diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex f40e7027f2da..001568a7850a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -507,7 +507,7 @@ importers:version: 5.3.0jest-image-snapshot:specifier: ^6.4.0- version: 6.4.0([email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])))+ version: 6.4.0([email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])))mockdate:specifier: ^3.0.5version: 3.0.5@@ -1931,7 +1931,7 @@ importers:version: 3.6.0jest-image-snapshot:specifier: ^6.4.0- version: 6.4.0([email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])))+ version: 6.4.0([email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])))storybook:specifier: 'catalog:'version: 10.4.6(@testing-library/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])@@ -2678,7 +2678,7 @@ importers:version: 8.57.0jest:specifier: '*'- version: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ version: 30.0.5([email protected]([email protected]))kea:specifier: 'catalog:'version: 4.0.0-pre.6([email protected])@@ -3506,7 +3506,7 @@ importers:version: 2.1.1jest:specifier: '*'- version: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ version: 30.0.5([email protected]([email protected]))kea:specifier: 'catalog:'version: 4.0.0-pre.6([email protected])@@ -4525,7 +4525,7 @@ importers:version: 1.2.1jest:specifier: '*'- version: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ version: 30.0.5([email protected]([email protected]))kea:specifier: 'catalog:'version: 4.0.0-pre.6([email protected])@@ -4788,6 +4788,9 @@ importers:'@posthog/mcp-analytics':specifier: npm:@posthog/[email protected]version: '@posthog/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])'+ '@posthog/products-ai-observability':+ specifier: workspace:*+ version: link:../../products/ai_observability'@posthog/quill':specifier: workspace:*version: link:../../packages/quill/packages/quill@@ -27107,7 +27110,7 @@ snapshots:- supports-color- ts-node- '@jest/[email protected]([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))':dependencies:'@jest/console': 30.0.5'@jest/pattern': 30.0.1@@ -27122,7 +27125,7 @@ snapshots:exit-x: 0.2.2graceful-fs: 4.2.11jest-changed-files: 30.0.5- jest-config: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))jest-haste-map: 30.0.5jest-message-util: 30.0.5jest-regex-util: 30.0.1@@ -27143,7 +27146,7 @@ snapshots:- supports-color- ts-node- '@jest/[email protected]([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))':+ '@jest/[email protected]([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))':dependencies:'@jest/console': 30.0.5'@jest/pattern': 30.0.1@@ -27158,7 +27161,7 @@ snapshots:exit-x: 0.2.2graceful-fs: 4.2.11jest-changed-files: 30.0.5- jest-config: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ jest-config: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))jest-haste-map: 30.0.5jest-message-util: 30.0.5jest-regex-util: 30.0.1@@ -38391,15 +38394,15 @@ snapshots:- supports-color- ts-node- [email protected](@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected])):+ [email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:- '@jest/core': 30.0.5([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ '@jest/core': 30.0.5([email protected](@swc/[email protected])(@types/[email protected])([email protected]))'@jest/test-result': 30.0.5'@jest/types': 30.0.5chalk: 4.1.2exit-x: 0.2.2import-local: 3.2.0- jest-config: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ jest-config: 30.0.5(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))jest-util: 30.0.5jest-validate: 30.0.5yargs: 17.7.2@@ -38410,15 +38413,15 @@ snapshots:- supports-color- ts-node- [email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:- '@jest/core': 30.0.5([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ '@jest/core': 30.0.5([email protected]([email protected]))'@jest/test-result': 30.0.5'@jest/types': 30.0.5chalk: 4.1.2exit-x: 0.2.2import-local: 3.2.0- jest-config: 30.0.5(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ jest-config: 30.0.5([email protected]([email protected]))jest-util: 30.0.5jest-validate: 30.0.5yargs: 17.7.2@@ -38556,7 +38559,7 @@ snapshots:- babel-plugin-macros- supports-color- [email protected](@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:'@babel/core': 7.29.0'@jest/get-type': 30.0.1@@ -38585,12 +38588,11 @@ snapshots:optionalDependencies:'@types/node': 22.18.8esbuild-register: 3.6.0([email protected])transitivePeerDependencies:- babel-plugin-macros- supports-color- [email protected](@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected])):+ [email protected](@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:'@babel/core': 7.29.0'@jest/get-type': 30.0.1@@ -38619,7 +38621,7 @@ snapshots:optionalDependencies:'@types/node': 22.18.8esbuild-register: 3.6.0([email protected])transitivePeerDependencies:- babel-plugin-macros- supports-color@@ -38657,7 +38659,7 @@ snapshots:- babel-plugin-macros- supports-color- [email protected](@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected])):+ [email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:'@babel/core': 7.29.0'@jest/get-type': 30.0.1@@ -38685,13 +38687,12 @@ snapshots:strip-json-comments: 3.1.1optionalDependencies:'@types/node': 25.8.0- esbuild-register: 3.6.0([email protected])transitivePeerDependencies:- babel-plugin-macros- supports-color- [email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:'@babel/core': 7.29.0'@jest/get-type': 30.0.1@@ -38718,8 +38719,7 @@ snapshots:slash: 3.0.0strip-json-comments: 3.1.1optionalDependencies:- '@types/node': 25.8.0+ esbuild-register: 3.6.0([email protected])transitivePeerDependencies:- babel-plugin-macros- supports-color@@ -39614,12 +39614,12 @@ snapshots:- supports-color- ts-node- [email protected](@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected])):+ [email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:- '@jest/core': 30.0.5([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ '@jest/core': 30.0.5([email protected](@swc/[email protected])(@types/[email protected])([email protected]))'@jest/types': 30.0.5import-local: 3.2.0- jest-cli: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ jest-cli: 30.0.5(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))transitivePeerDependencies:- '@types/node'- babel-plugin-macros@@ -39627,12 +39627,12 @@ snapshots:- supports-color- ts-node- [email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:- '@jest/core': 30.0.5([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ '@jest/core': 30.0.5([email protected]([email protected]))'@jest/types': 30.0.5import-local: 3.2.0- jest-cli: 30.0.5(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ jest-cli: 30.0.5([email protected]([email protected]))transitivePeerDependencies:- '@types/node'- babel-plugin-macrosdiff --git a/products/ai_observability/frontend/components/EventContentWithAsyncData.tsx b/products/ai_observability/frontend/components/EventContentWithAsyncData.tsxindex 7eea5a096600..6dd959cfb660 100644--- a/products/ai_observability/frontend/components/EventContentWithAsyncData.tsx+++ b/products/ai_observability/frontend/components/EventContentWithAsyncData.tsx@@ -105,6 +105,7 @@ export function EventContentConversation({const openCustomParserMax = useCustomParserMaxTool({eventId,+ traceId,input,output,tools: loadedTools,diff --git a/products/ai_observability/frontend/customParser/useCustomParserMaxTool.ts b/products/ai_observability/frontend/customParser/useCustomParserMaxTool.tsindex 9f4d649e0dff..ab27064637e3 100644--- a/products/ai_observability/frontend/customParser/useCustomParserMaxTool.ts+++ b/products/ai_observability/frontend/customParser/useCustomParserMaxTool.ts@@ -6,7 +6,8 @@ import { lemonToast } from '@posthog/lemon-ui'import { useMaxTool } from 'scenes/max/useMaxTool'import { teamLogic } from 'scenes/teamLogic'-import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { useAttachedContext, useMcpToolApplyBack } from 'products/posthog_ai/frontend/api/logics'+import type { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'import { llmAnalyticsParserRecipesCreate } from '../generated/api'import { parserRecipesLogic } from '../settings/parserRecipesLogic'@@ -15,8 +16,23 @@ import { handleCreateParserRecipeCall } from './validateRecipe'const MAX_EXISTING_RECIPES_CONTEXT_LENGTH = 4000+// Static, trusted instruction — never interpolate user or ingested trace data into it.+// Points the headless agent at the reference + create tools and the trace_id/event_uuid it+// finds in the untrusted trace-event sample block.+const AI_TRACE_PARSER_TOOL_CONTEXT_ITEM: AttachedContextItem = {+ type: 'instructions',+ hidden: true,+ value:+ 'The user has an LLM trace event open that fell back to raw JSON because no parser recognized it. ' ++ 'To fix it, first call llma-parser-recipe-reference for the recipe DSL syntax and examples, then call ' ++ 'llma-parser-recipe-create with the trace_id and event_uuid from the attached trace event sample. The ' ++ 'samples in context are truncated, but the server compiles and validates your recipe against the full ' ++ 'event and only saves it when it works. The open trace re-renders once the recipe is saved.',+}+export interface CustomParserMaxToolOptions {eventId: string+ traceId?: string | nullinput: unknownoutput: unknowntools?: unknown@@ -33,6 +49,7 @@ export interface CustomParserMaxToolOptions {*/export function useCustomParserMaxTool({eventId,+ traceId,input,output,tools,@@ -105,10 +122,13 @@ export function useCustomParserMaxTool({useAttachedContext(active? [+ AI_TRACE_PARSER_TOOL_CONTEXT_ITEM,{ type: 'llm_trace_event', key: eventId },{type: 'ai_trace_parser_context',value: JSON.stringify({+ trace_id: traceId ?? null,+ event_uuid: eventId,event_type: isGeneration ? 'generation' : 'span',unrecognized,sample_input: sampleForContext(input),@@ -120,6 +140,32 @@ export function useCustomParserMaxTool({: null)+ // Headless mirror: when the agent's llma-parser-recipe-create tool completes, reload the team's+ // recipes so the live normalizer re-renders the open trace. loadRecipes is idempotent, so we run+ // it on every completion regardless of whether the tool actually saved.+ useMcpToolApplyBack({+ tools: ['llma-parser-recipe-create'],+ targetKey: 'ai-trace-parser',+ active,+ onApply: (event, { innerInput }) => {+ loadRecipes()+ // A create for a different event must not claim this one was fixed; when the+ // args are unparseable we keep the toast, matching the pre-innerInput behavior.+ if (innerInput && typeof innerInput.event_uuid === 'string' && innerInput.event_uuid !== eventId) {+ return+ }+ try {+ const output = event.invocation.output+ const serialized = typeof output === 'string' ? output : JSON.stringify(output)+ if (serialized && serialized.includes('recipe_id')) {+ lemonToast.success('Custom parser saved')+ }+ } catch {+ // Output shape is client-profile-dependent — the agent narrates failures in chat.+ }+ },+ })+const { openMax } = useMaxTool({identifier: 'create_ai_trace_parser',active,diff --git a/products/ai_observability/frontend/messageNormalization.ts b/products/ai_observability/frontend/messageNormalization.tsindex 0a76d235a38f..fb47c8666e58 100644--- a/products/ai_observability/frontend/messageNormalization.ts+++ b/products/ai_observability/frontend/messageNormalization.ts@@ -1,10 +1,14 @@import posthog from 'posthog-js'-import { mergeRecipes, RecipeNormalizer, RunOutcome, StoredRecipe } from './normalizer'+import { mergeRecipes, RecipeNormalizer, RunOutcome, setNormalizerTelemetry, StoredRecipe } from './normalizer'import { CompatMessage } from './types'export type NormalizationResult = RunOutcome+// Route the portable normalizer's telemetry back through posthog-js in the browser.+// Headless callers (MCP server, tasks sandbox) leave the noop default in place.+setNormalizerTelemetry((event, properties) => posthog.capture(event, properties))+// Constructed once: the constructor compiles and sorts every recipe, so per-call// construction would be wasteful.const recipeNormalizer = new RecipeNormalizer()diff --git a/products/ai_observability/frontend/normalizer/index.ts b/products/ai_observability/frontend/normalizer/index.tsindex 212d1347797f..a8e62e01dca6 100644--- a/products/ai_observability/frontend/normalizer/index.ts+++ b/products/ai_observability/frontend/normalizer/index.ts@@ -6,3 +6,4 @@ export type { RunOutcome } from './recipe/runtime/pipeline'export { mergeRecipes } from './recipe/merge'export type { StoredRecipe } from './recipe/merge'export { compileRecipe } from './recipe/compile/compiler'+export { setNormalizerTelemetry } from './telemetry'diff --git a/products/ai_observability/frontend/normalizer/recipe/compile/compiler.ts b/products/ai_observability/frontend/normalizer/recipe/compile/compiler.tsindex 50ad88ac8207..38022524879a 100644--- a/products/ai_observability/frontend/normalizer/recipe/compile/compiler.ts+++ b/products/ai_observability/frontend/normalizer/recipe/compile/compiler.ts@@ -135,11 +135,12 @@ function compilePredicate(raw: unknown): Predicate {throw new Error(`predicate has multiple verbs (${verbs.join(', ')}); use one verb per field`)}if (verbs.length === 1) {+ const verb = verbs[0]!if (keys.length > 1) {const fields = keys.filter((k) => !PREDICATE_VERBS.has(k))- throw new Error(`predicate verb '${verbs[0]}' cannot be mixed with field keys (${fields.join(', ')})`)+ throw new Error(`predicate verb '${verb}' cannot be mixed with field keys (${fields.join(', ')})`)}- return buildPredicateFromVerb(verbs[0], raw[verbs[0]])+ return buildPredicateFromVerb(verb, raw[verb])}return new ShapePredicate(compilePattern(raw))}@@ -232,7 +233,7 @@ function compileValue(raw: unknown): Expr {if (isObject(raw)) {const keys = Object.keys(raw)if (keys.length === 1) {- const key = keys[0]+ const key = keys[0]!if (OPERATORS.has(key)) {return compileOperator(key, raw[key])}@@ -284,7 +285,7 @@ function compileInterp(s: string): Expr {if (m.index > cursor) {parts.push(s.slice(cursor, m.index))}- parts.push(new PathExpr(m[1].split('.')))+ parts.push(new PathExpr(m[1]!.split('.')))cursor = m.index + m[0].length}if (cursor < s.length) {diff --git a/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.test.ts b/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.test.tsindex 36ce37402286..ef0e4336bd1e 100644--- a/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.test.ts+++ b/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.test.ts@@ -1,4 +1,4 @@-import { AVAILABLE_TOOLS_ROLE } from '../../utils'+import { AVAILABLE_TOOLS_ROLE } from '../roles'import { RecipeNormalizer } from './recipeNormalizer'const mockRun = jest.fn()diff --git a/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.ts b/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.tsindex 4afc4fbc7b71..df8332cfe9e9 100644--- a/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.ts+++ b/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.ts@@ -1,5 +1,5 @@import { CompatMessage } from '../../types'-import { AVAILABLE_TOOLS_ROLE } from '../../utils'+import { AVAILABLE_TOOLS_ROLE } from '../roles'import { loadRecipes } from './registry'import { RecipePipeline, RunOutcome } from './runtime/pipeline'import { Recipe } from './spec/recipe'diff --git a/products/ai_observability/frontend/normalizer/recipe/runtime/coercion.test.ts b/products/ai_observability/frontend/normalizer/recipe/runtime/coercion.test.tsindex fe4e70b6c6de..4a92a08f80d7 100644--- a/products/ai_observability/frontend/normalizer/recipe/runtime/coercion.test.ts+++ b/products/ai_observability/frontend/normalizer/recipe/runtime/coercion.test.ts@@ -1,19 +1,19 @@-import posthog from 'posthog-js'-import { CompatMessage } from '../../../types'+import { setNormalizerTelemetry } from '../../telemetry'import { LiteralExpr } from '../ast/expr'import { Scope } from '../scope'import { EmitSpec } from '../spec/emitSpec'import { SlotCoercer } from './coercion'-jest.mock('posthog-js', () => ({ __esModule: true, default: { capture: jest.fn() } }))+const telemetrySpy = jest.fn()+setNormalizerTelemetry(telemetrySpy)const coercer = new SlotCoercer()const scope = (input: unknown = {}, role = 'user'): Scope => Scope.forNode(input, role)const lit = (value: unknown): LiteralExpr => new LiteralExpr(value)describe('SlotCoercer.buildMessage', () => {- beforeEach(() => jest.clearAllMocks())+ beforeEach(() => telemetrySpy.mockClear())it('builds a message with role and content', () => {const emit: EmitSpec = { content: lit('hello') }@@ -82,7 +82,7 @@ describe('SlotCoercer.buildMessage', () => {it('non-text content yields an empty string instead of leaking JSON', () => {const emit: EmitSpec = { content: lit({ unexpected: 'object' }) }expect(coercer.buildMessage(emit, scope())?.content).toBe('')- expect(posthog.capture).toHaveBeenCalled()+ expect(telemetrySpy).toHaveBeenCalled()})})diff --git a/products/ai_observability/frontend/normalizer/recipe/runtime/coercion.ts b/products/ai_observability/frontend/normalizer/recipe/runtime/coercion.tsindex ea5a753b4ef9..333d5719b63c 100644--- a/products/ai_observability/frontend/normalizer/recipe/runtime/coercion.ts+++ b/products/ai_observability/frontend/normalizer/recipe/runtime/coercion.ts@@ -1,7 +1,6 @@-import posthog from 'posthog-js'-import { CompatMessage, CompatToolCall, MultiModalContentItem } from '../../../types'-import { normalizeRole } from '../../../utils'+import { normalizeRole } from '../../roles'+import { emitNormalizerTelemetry } from '../../telemetry'import { Expr } from '../ast/expr'import { Scope } from '../scope'import { EmitSpec, RoleTag } from '../spec/emitSpec'@@ -118,7 +117,7 @@ export class SlotCoercer {// Reaching here is a recipe bug or coverage gap (recipes opt into rendering// arbitrary values with `stringify`); surface '' rather than plausible-looking// JSON, and log type only since the value may be sensitive.- posthog.capture('llma recipe produced non-text content', { content_type: typeof value })+ emitNormalizerTelemetry('llma recipe produced non-text content', { content_type: typeof value })return ''}diff --git a/products/ai_observability/frontend/normalizer/recipe/runtime/pipeline.test.ts b/products/ai_observability/frontend/normalizer/recipe/runtime/pipeline.test.tsindex 571cd22d7382..8f2aaee21a43 100644--- a/products/ai_observability/frontend/normalizer/recipe/runtime/pipeline.test.ts+++ b/products/ai_observability/frontend/normalizer/recipe/runtime/pipeline.test.ts@@ -4,8 +4,6 @@ import { Rule } from '../ast/rule'import { Recipe } from '../spec/recipe'import { NO_MATCH, RecipePipeline } from './pipeline'-jest.mock('posthog-js', () => ({ __esModule: true, default: { capture: jest.fn() } }))-const MATCH_ALL = new Pattern({})const MATCH_NONE = new Pattern({ __absent: new ExistsPredicate(true) })diff --git a/products/ai_observability/frontend/normalizer/recipe/scope.ts b/products/ai_observability/frontend/normalizer/recipe/scope.tsindex 23b3c01297f6..214aee9aedc3 100644--- a/products/ai_observability/frontend/normalizer/recipe/scope.ts+++ b/products/ai_observability/frontend/normalizer/recipe/scope.ts@@ -1,7 +1,7 @@// Per-dispatch context. The role is the only thing that flows parent → child;// everything else a rule needs comes from `input`.-import { normalizeRole, roleMap } from '../../utils'+import { normalizeRole, roleMap } from '../roles'export class Scope {private constructor(@@ -28,7 +28,7 @@ function resolveRole(input: unknown, inheritedRole: string): string {if (typeof obj.role === 'string') {return normalizeRole(obj.role, inheritedRole)}- if (typeof obj.type === 'string' && Object.hasOwn(roleMap, obj.type)) {+ if (typeof obj.type === 'string' && Object.prototype.hasOwnProperty.call(roleMap, obj.type)) {return normalizeRole(obj.type, inheritedRole)}return inheritedRolediff --git a/products/ai_observability/frontend/normalizer/roles.ts b/products/ai_observability/frontend/normalizer/roles.tsnew file mode 100644index 000000000000..ee444a991269--- /dev/null+++ b/products/ai_observability/frontend/normalizer/roles.ts@@ -0,0 +1,24 @@+export const roleMap: Record<string, string> = {+ user: 'user',+ human: 'user',++ assistant: 'assistant',+ model: 'assistant',+ ai: 'assistant',+ bot: 'assistant',++ system: 'system',+ instructions: 'system',+ context: 'system',+}++export function normalizeRole(rawRole: unknown, fallback: string): string {+ if (typeof rawRole !== 'string') {+ return fallback+ }+ const lowercased = rawRole.toLowerCase()+ return roleMap[lowercased] || lowercased+}++// Synthetic role used to surface the `$ai_tools` payload as a pseudo-message+export const AVAILABLE_TOOLS_ROLE = 'available tools'diff --git a/products/ai_observability/frontend/normalizer/telemetry.ts b/products/ai_observability/frontend/normalizer/telemetry.tsnew file mode 100644index 000000000000..2b1872626f42--- /dev/null+++ b/products/ai_observability/frontend/normalizer/telemetry.ts@@ -0,0 +1,15 @@+// Telemetry sink for the recipe normalizer. Kept injectable so the normalizer+// stays portable to Node (MCP server, tasks sandbox) — the browser wires a+// `posthog.capture` callback via `setNormalizerTelemetry`; elsewhere it's a noop.++type NormalizerTelemetryCallback = (event: string, properties: Record<string, unknown>) => void++let telemetryCallback: NormalizerTelemetryCallback = () => {}++export function setNormalizerTelemetry(callback: NormalizerTelemetryCallback): void {+ telemetryCallback = callback+}++export function emitNormalizerTelemetry(event: string, properties: Record<string, unknown>): void {+ telemetryCallback(event, properties)+}diff --git a/products/ai_observability/frontend/utils.ts b/products/ai_observability/frontend/utils.tsindex 5e6538f4ae7d..1b1e20fca0d5 100644--- a/products/ai_observability/frontend/utils.ts+++ b/products/ai_observability/frontend/utils.ts@@ -824,30 +824,9 @@ export function isOTelPartsMessage(input: unknown): input is OTelPartsMessage {)}-export const roleMap: Record<string, string> = {- user: 'user',- human: 'user',-- assistant: 'assistant',- model: 'assistant',- ai: 'assistant',- bot: 'assistant',-- system: 'system',- instructions: 'system',- context: 'system',-}--export function normalizeRole(rawRole: unknown, fallback: string): string {- if (typeof rawRole !== 'string') {- return fallback- }- const lowercased = rawRole.toLowerCase()- return roleMap[lowercased] || lowercased-}--// Synthetic role used to surface the `$ai_tools` payload as a pseudo-message-export const AVAILABLE_TOOLS_ROLE = 'available tools'+// Role helpers live in the portable normalizer module (leaf, no browser deps);+// re-exported here so the many frontend consumers keep their import paths.+export { roleMap, normalizeRole, AVAILABLE_TOOLS_ROLE } from './normalizer/roles'export const INTERNAL_THINKING_ROLE = 'assistant (thinking)'export const INTERNAL_TOOL_RESULT_ROLE = 'assistant (tool result)'diff --git a/products/posthog_ai/frontend/policy/toolPolicy.ts b/products/posthog_ai/frontend/policy/toolPolicy.tsindex c7f1f5c142f7..e598a687bc54 100644--- a/products/posthog_ai/frontend/policy/toolPolicy.ts+++ b/products/posthog_ai/frontend/policy/toolPolicy.ts@@ -137,6 +137,7 @@ const PERSIST_PROMPT_SUB_TOOLS = new Set(['cdp-functions-create','workflows-create','workflows-create-email-template',+ 'llma-parser-recipe-create',])/** Whether a permission request resolves to a create-family persist tool from `PERSIST_PROMPT_SUB_TOOLS`. */diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.pyindex 16a7e56d03c7..e72120b6026f 100644--- a/products/tasks/backend/constants.py+++ b/products/tasks/backend/constants.py@@ -119,6 +119,7 @@ POSTHOG_EXEC_PERSIST_SUB_TOOLS: tuple[str, ...] = ("cdp-functions-create","workflows-create","workflows-create-email-template",+ "llma-parser-recipe-create",)POSTHOG_EXEC_PERMISSION_REGEX = (diff --git a/services/mcp/package.json b/services/mcp/package.jsonindex 267accef4038..19b02090e46a 100644--- a/services/mcp/package.json+++ b/services/mcp/package.json@@ -50,6 +50,7 @@"@modelcontextprotocol/ext-apps": "^1.5.0","@modelcontextprotocol/sdk": "^1.29.0","@posthog/mcp-analytics": "npm:@posthog/[email protected]",+ "@posthog/products-ai-observability": "workspace:*","@posthog/quill": "workspace:*","@posthog/quill-charts": "workspace:*","@toon-format/toon": "^2.1.0",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex ba2b0e3dc366..18495936f22e 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -5657,6 +5657,34 @@"readOnlyHint": false}},+ "llma-parser-recipe-create": {+ "description": "Writes and saves a custom LLM analytics parser recipe so an unparsed trace event renders as a readable conversation. Call `llma-parser-recipe-reference` first to get the recipe DSL syntax and worked examples. The server loads the exact event (by trace_id + event_uuid), compiles your YAML, and validates it against that event, saving the recipe only when a previously-unrecognized input or output side becomes recognized. If the result is not valid, read the error, fix the YAML, and call again in the same turn; stop after about three failed attempts and explain what is blocking you. Do not force non-conversational data into a fake conversation shape — if the event genuinely is not a conversation, say so instead of inventing rules. Samples in your context are truncated, but the server always validates against the full event.",+ "category": "AI observability",+ "feature": "llm_analytics",+ "summary": "Compiles, validates, and saves a custom parser recipe for an LLM analytics trace event.",+ "title": "Create parser recipe",+ "required_scopes": ["llm_analytics:write", "query:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "llma-parser-recipe-reference": {+ "description": "Returns the LLM analytics parser recipe DSL reference: the syntax and a set of worked examples for writing parser recipes. Call this before `llma-parser-recipe-create` so you know the recipe grammar.",+ "category": "AI observability",+ "feature": "llm_analytics",+ "summary": "Returns the parser recipe DSL syntax and worked examples.",+ "title": "Parser recipe reference",+ "required_scopes": ["llm_analytics:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"llma-personal-spend": {"description": "Retrieve the current user's personal LLM spend analysis across PostHog products over the last N days (default 30, max 90). Returns a summary plus breakdowns by product, tool, model and UTC day. The `product` query param is required and scopes the tool / model / day breakdowns to a single product; currently only `posthog_code` is supported. `by_product` always returns the cross-product view, and `by_day` is a day-ascending series for spend-over-time questions. Pass `refresh=true` to bypass the 5-minute cache.","category": "AI observability",diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.jsonindex d546af7affe6..ecfc7de3ba38 100644--- a/services/mcp/schema/tool-definitions.json+++ b/services/mcp/schema/tool-definitions.json@@ -351,6 +351,34 @@"readOnlyHint": true}},+ "llma-parser-recipe-create": {+ "description": "Writes and saves a custom LLM analytics parser recipe so an unparsed trace event renders as a readable conversation. Call `llma-parser-recipe-reference` first to get the recipe DSL syntax and worked examples. The server loads the exact event (by trace_id + event_uuid), compiles your YAML, and validates it against that event, saving the recipe only when a previously-unrecognized input or output side becomes recognized. If the result is not valid, read the error, fix the YAML, and call again in the same turn; stop after about three failed attempts and explain what is blocking you. Do not force non-conversational data into a fake conversation shape — if the event genuinely is not a conversation, say so instead of inventing rules. Samples in your context are truncated, but the server always validates against the full event.",+ "category": "AI observability",+ "feature": "llm_analytics",+ "summary": "Compiles, validates, and saves a custom parser recipe for an LLM analytics trace event.",+ "title": "Create parser recipe",+ "required_scopes": ["llm_analytics:write", "query:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "llma-parser-recipe-reference": {+ "description": "Returns the LLM analytics parser recipe DSL reference: the syntax and a set of worked examples for writing parser recipes. Call this before `llma-parser-recipe-create` so you know the recipe grammar.",+ "category": "AI observability",+ "feature": "llm_analytics",+ "summary": "Returns the parser recipe DSL syntax and worked examples.",+ "title": "Parser recipe reference",+ "required_scopes": ["llm_analytics:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"organizations-get": {"description": "Fetches the organizations that the user has access to, with their id, name, and membership level. Use this to discover organizations — including ones other than the active organization — and to resolve an organization name to the id you pass to `switch-organization`.","category": "Organization & project management",diff --git a/services/mcp/scripts/copy-instructions.ts b/services/mcp/scripts/copy-instructions.tsindex a2bb9138619f..fb39a155a241 100644--- a/services/mcp/scripts/copy-instructions.ts+++ b/services/mcp/scripts/copy-instructions.ts@@ -29,6 +29,12 @@ const PROMPTS = [src: 'services/mcp/playbooks',dest: 'shared/playbooks',},+ {+ // Parser recipe DSL reference served by `llma-parser-recipe-reference`;+ // the Python MaxTool reads the same file, keeping one source of truth.+ src: 'products/ai_observability/backend/prompts/parser_recipe_examples.yaml',+ dest: 'shared/parser_recipe_examples.yaml',+ },]/** `auditing-the-fleet` → `auditingTheFleet` (valid JS identifier). */diff --git a/services/mcp/scripts/hono-esbuild-config.ts b/services/mcp/scripts/hono-esbuild-config.tsindex 2e7942660694..9905da89bf71 100644--- a/services/mcp/scripts/hono-esbuild-config.ts+++ b/services/mcp/scripts/hono-esbuild-config.ts@@ -42,7 +42,7 @@ export function honoEsbuildOptions(opts: HonoEsbuildOptions = {}): BuildOptionssourcemap: opts.sourcemap ?? true,external: [],plugins: [cfWorkersStub, ...(opts.extraPlugins ?? [])],- loader: { '.html': 'text', '.md': 'text', '.json': 'json' },+ loader: { '.html': 'text', '.md': 'text', '.yaml': 'text', '.json': 'json' },define: { 'process.env.NODE_ENV': opts.dev ? '"development"' : '"production"' },// Bundled CJS modules (e.g. ioredis using `require('util')`) call through// to a global `require`. ESM has no `require`; banner injects one. Thediff --git a/services/mcp/src/tools/aiObservability/parserRecipeCreate.ts b/services/mcp/src/tools/aiObservability/parserRecipeCreate.tsnew file mode 100644index 000000000000..8388ad24fef3--- /dev/null+++ b/services/mcp/src/tools/aiObservability/parserRecipeCreate.ts@@ -0,0 +1,181 @@+import { z } from 'zod'++import { getPostHogClient } from '@/lib/posthog'+import type { Context, ToolBase } from '@/tools/types'++import { validateRecipeAgainstSample } from 'products/ai_observability/frontend/customParser/validateRecipe'+import { mergeRecipes, RecipeNormalizer, type StoredRecipe } from 'products/ai_observability/frontend/normalizer'++// Mirrors MAX_SOURCE_LENGTH on the ParserRecipe model.+const MAX_SOURCE_LENGTH = 100_000++// The team's custom recipes are fetched with a fixed cap. A team with more custom+// recipes than this gets a slightly stale merge — acceptable, since the server still+// validates against the full event and the built-ins always run first.+const RECIPE_LIST_LIMIT = 300++const schema = z.object({+ name: z.string().min(1).max(255).describe('Short human-readable name for the recipe, shown in the parser editor.'),+ yaml_source: z+ .string()+ .min(1)+ .max(MAX_SOURCE_LENGTH)+ .describe(+ 'The recipe as raw YAML. Call `llma-parser-recipe-reference` first for the DSL syntax and worked examples. The server compiles and validates this against the exact event before saving.'+ ),+ trace_id: z.string().min(1).describe('The `$ai_trace_id` of the trace containing the event to parse.'),+ event_uuid: z.string().min(1).describe('The UUID (`id`) of the specific event within the trace to parse.'),+})++type Params = z.infer<typeof schema>++interface ParserRecipeCreateResult {+ valid: boolean+ error?: string+ recipe_id?: string+ saved?: boolean+ already_recognized?: boolean+}++interface TraceEvent {+ id: string+ event: string+ properties?: Record<string, unknown>+}++interface Trace {+ events?: TraceEvent[]+}++interface EventSample {+ input: unknown+ output: unknown+ // Embeddings have no message-shaped output; treat that side as recognized so the+ // recipe only has to explain the input.+ outputRecognizedByDefault: boolean+}++// Extract the input/output sides by event type, mirroring `ConversationDisplay`.+function extractSample(eventName: string, properties: Record<string, unknown>): EventSample {+ if (eventName === '$ai_generation') {+ return {+ input: properties.$ai_input,+ output: properties.$ai_output_choices ?? properties.$ai_output,+ outputRecognizedByDefault: false,+ }+ }+ if (eventName === '$ai_embedding') {+ return { input: properties.$ai_input, output: undefined, outputRecognizedByDefault: true }+ }+ // Spans and everything else carry their payload in the `_state` fields.+ return {+ input: properties.$ai_input_state,+ output: properties.$ai_output_state,+ outputRecognizedByDefault: false,+ }+}++export const parserRecipeCreateHandler: ToolBase<typeof schema, ParserRecipeCreateResult>['handler'] = async (+ context: Context,+ params: Params+) => {+ const projectId = await context.stateManager.getProjectId()++ // The 1-year window mirrors the frontend trace fetch (`aiObservabilityTraceDataLogic`);+ // without it, older traces silently return no rows.+ const dateFrom = new Date(Date.now() - 365 * 24 * 3600 * 1000).toISOString()+ const traceResult = await context.api+ .query({ projectId: String(projectId) })+ .execute({ queryBody: { kind: 'TraceQuery', traceId: params.trace_id, dateRange: { date_from: dateFrom } } })+ if (!traceResult.success) {+ // Infra failures are exceptions; validation failures are results.+ throw new Error(`Failed to load trace ${params.trace_id}: ${traceResult.error.message}`)+ }++ const traces = (traceResult.data.results ?? []) as Trace[]+ const event = traces.flatMap((trace) => trace.events ?? []).find((candidate) => candidate.id === params.event_uuid)+ if (!event) {+ return { valid: false, error: 'event not found in trace — re-check trace_id and event_uuid' }+ }++ const properties = event.properties ?? {}+ const { input, output, outputRecognizedByDefault } = extractSample(event.event, properties)+ if (input === undefined && output === undefined) {+ // TraceQuery falls back to the shared events table where the heavy AI columns are+ // stripped, and `ai_events` has a retention TTL — a payload-less event can't prove+ // anything about a recipe, and normalizeMessages(undefined) would count as recognized.+ return {+ valid: false,+ error: 'the event payload is not available server-side (it likely aged out of retention) — the recipe cannot be validated against it',+ }+ }+ const tools = properties.$ai_tools++ const listResponse = await context.api.request<{ results?: Array<{ id: string; source: string }> }>({+ method: 'GET',+ path: `/api/projects/${projectId}/llm_analytics/parser_recipes/`,+ query: { limit: RECIPE_LIST_LIMIT },+ })+ const teamRecipes: StoredRecipe[] = (listResponse.results ?? []).map((row) => ({ id: row.id, source: row.source }))++ // Recompute recognition the way the browser does, so validation only demands the+ // sides that are currently unrecognized. The whole (possibly multi-MB) trace is+ // deserialized once here and discarded — the same order of work the browser does.+ const normalizer = new RecipeNormalizer(mergeRecipes(teamRecipes))+ const inputRecognized = normalizer.normalizeMessages(input, 'user', tools).recognized+ const outputRecognized = outputRecognizedByDefault || normalizer.normalizeMessages(output, 'assistant').recognized++ const verdict = validateRecipeAgainstSample(params.yaml_source, teamRecipes, {+ input,+ output,+ tools,+ inputRecognized,+ outputRecognized,+ })+ if (!verdict.valid) {+ return { valid: false, error: verdict.error }+ }++ // An event both sides of which are already recognized doesn't need a recipe; the+ // candidate then only has to compile. Flag it so the caller knows.+ const alreadyRecognized = inputRecognized && outputRecognized++ // A byte-identical recipe already exists — return it instead of saving a duplicate.+ const existing = teamRecipes.find((recipe) => recipe.source === params.yaml_source)+ if (existing) {+ return { valid: true, recipe_id: existing.id, ...(alreadyRecognized ? { already_recognized: true } : {}) }+ }++ // With both sides pre-recognized, validation was vacuous — the candidate proved+ // nothing, so persisting it team-wide would save an unproven recipe.+ if (alreadyRecognized) {+ return { valid: true, already_recognized: true }+ }++ try {+ const created = await context.api.request<{ id: string }>({+ method: 'POST',+ path: `/api/projects/${projectId}/llm_analytics/parser_recipes/`,+ body: { name: params.name, source: params.yaml_source },+ })+ return { valid: true, recipe_id: created.id }+ } catch (error) {+ // Capture before the soft return: the graceful result bypasses `handleToolError`,+ // the path that normally surfaces 5xx-class failures to observability.+ try {+ getPostHogClient().captureException(error, undefined, { tag: 'mcp', tool: 'llma-parser-recipe-create' })+ } catch {+ // Observability must never break the request.+ }+ // Only persistence failed — never make the agent rewrite a correct recipe.+ return { valid: true, saved: false, error: error instanceof Error ? error.message : String(error) }+ }+}++const tool = (): ToolBase<typeof schema, ParserRecipeCreateResult> => ({+ name: 'llma-parser-recipe-create',+ schema,+ handler: parserRecipeCreateHandler,+})++export default tooldiff --git a/services/mcp/src/tools/aiObservability/parserRecipeReference.ts b/services/mcp/src/tools/aiObservability/parserRecipeReference.tsnew file mode 100644index 000000000000..4f23bc743f95--- /dev/null+++ b/services/mcp/src/tools/aiObservability/parserRecipeReference.ts@@ -0,0 +1,26 @@+// Copied into `shared/` by scripts/copy-instructions.ts before bundling so this stays+// the single source of truth with the Python MaxTool, which reads the same file.+// Too big (~14KB) to embed in a tool description.+import parserRecipeExamples from '@shared/parser_recipe_examples.yaml'+import { z } from 'zod'++import type { ToolBase } from '@/tools/types'++const schema = z.object({})++interface ParserRecipeReferenceResult {+ reference: string+}++export const parserRecipeReferenceHandler: ToolBase<+ typeof schema,+ ParserRecipeReferenceResult+>['handler'] = async () => ({ reference: parserRecipeExamples })++const tool = (): ToolBase<typeof schema, ParserRecipeReferenceResult> => ({+ name: 'llma-parser-recipe-reference',+ schema,+ handler: parserRecipeReferenceHandler,+})++export default tooldiff --git a/services/mcp/src/tools/index.ts b/services/mcp/src/tools/index.tsindex 688a38cabd93..0fb709c71ea5 100644--- a/services/mcp/src/tools/index.ts+++ b/services/mcp/src/tools/index.ts@@ -5,6 +5,8 @@ import { filterStaffOnlyTools } from '@/lib/staff-only-tools'import resolveResource from './agentPlatform/resolveResource'// AI observabilityimport getLLMCosts from './aiObservability/getLLMCosts'+import parserRecipeCreate from './aiObservability/parserRecipeCreate'+import parserRecipeReference from './aiObservability/parserRecipeReference'// Debugimport debugMcpUiApps from './debug/debugMcpUiApps'// Experiments (hand-written — CRUD + lifecycle are codegen in generated/experiments.ts)@@ -89,6 +91,8 @@ export const TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> = {// AI observability'get-llm-total-costs-for-project': getLLMCosts,+ 'llma-parser-recipe-create': parserRecipeCreate,+ 'llma-parser-recipe-reference': parserRecipeReference,// Notebooks'notebook-edit': notebookEdit,diff --git a/services/mcp/tests/hono/setup.ts b/services/mcp/tests/hono/setup.tsindex 1e27e7a4b90c..1b8124e8e053 100644--- a/services/mcp/tests/hono/setup.ts+++ b/services/mcp/tests/hono/setup.ts@@ -13,10 +13,13 @@ vi.mock('cloudflare:workers', () => ({},}))-// Mock shared guidelines (generated by scripts/copy-instructions.ts, not checked in)+// Mock shared prompt files (generated by scripts/copy-instructions.ts, not checked in)vi.mock('@shared/guidelines.md', () => ({default: '# Guidelines\nTest guidelines content.',}))+vi.mock('@shared/parser_recipe_examples.yaml', () => ({+ default: 'rules: []\n',+}))vi.mock('@/resources/ui-apps', async (importOriginal) => {const actual = await importOriginal<typeof import('@/resources/ui-apps')>()diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-parser-recipe-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-parser-recipe-create.jsonnew file mode 100644index 000000000000..a4b15c88486f--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-parser-recipe-create.json@@ -0,0 +1,29 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "event_uuid": {+ "description": "The UUID (`id`) of the specific event within the trace to parse.",+ "minLength": 1,+ "type": "string"+ },+ "name": {+ "description": "Short human-readable name for the recipe, shown in the parser editor.",+ "maxLength": 255,+ "minLength": 1,+ "type": "string"+ },+ "trace_id": {+ "description": "The `$ai_trace_id` of the trace containing the event to parse.",+ "minLength": 1,+ "type": "string"+ },+ "yaml_source": {+ "description": "The recipe as raw YAML. Call `llma-parser-recipe-reference` first for the DSL syntax and worked examples. The server compiles and validates this against the exact event before saving.",+ "maxLength": 100000,+ "minLength": 1,+ "type": "string"+ }+ },+ "required": ["name", "yaml_source", "trace_id", "event_uuid"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-parser-recipe-reference.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-parser-recipe-reference.jsonnew file mode 100644index 000000000000..7b7ea9186078--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-parser-recipe-reference.json@@ -0,0 +1,5 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {},+ "type": "object"+}diff --git a/services/mcp/tests/unit/parser-recipe-create.test.ts b/services/mcp/tests/unit/parser-recipe-create.test.tsnew file mode 100644index 000000000000..e79878899418--- /dev/null+++ b/services/mcp/tests/unit/parser-recipe-create.test.ts@@ -0,0 +1,192 @@+import { describe, expect, it, vi } from 'vitest'++import parserRecipeCreate from '@/tools/aiObservability/parserRecipeCreate'+import type { Context } from '@/tools/types'++// A recipe whose rule matches the `acme_*` sample shape below. The built-in recipes+// do not recognize that shape, so this recipe is what makes the sample recognized.+const MATCHING_RECIPE = `+rules:+ - on:+ acme_kind: q+ emit:+ role: user+ content: $.acme_text+`++// Compiles, but matches nothing in the sample — the event stays unrecognized.+const NON_MATCHING_RECIPE = `+rules:+ - on:+ some_other_key: { exists: true }+ emit:+ role: user+ content: $.acme_text+`++const TRACE_ID = 'trace-1'+const EVENT_UUID = 'event-1'++interface EventShape {+ id: string+ event: string+ properties: Record<string, unknown>+}++function generationEvent(overrides: Partial<EventShape> = {}): EventShape {+ return {+ id: EVENT_UUID,+ event: '$ai_generation',+ properties: {+ $ai_input: { acme_kind: 'q', acme_text: 'hi' },+ $ai_output: { acme_kind: 'q', acme_text: 'bye' },+ },+ ...overrides,+ }+}++function createContext(options: { events: EventShape[]; queryError?: string; request?: ReturnType<typeof vi.fn> }): {+ context: Context+ execute: ReturnType<typeof vi.fn>+ request: ReturnType<typeof vi.fn>+} {+ const execute = vi+ .fn()+ .mockResolvedValue(+ options.queryError+ ? { success: false, error: { message: options.queryError } }+ : { success: true, data: { results: [{ events: options.events }] } }+ )+ const request = options.request ?? vi.fn().mockResolvedValue({ results: [] })+ const context = {+ api: { request, query: vi.fn().mockReturnValue({ execute }) } as any,+ stateManager: { getProjectId: vi.fn().mockResolvedValue('42') } as any,+ env: {} as any,+ sessionManager: {} as any,+ cache: {} as any,+ getDistinctId: async () => 'distinct-id',+ trackEvent: async () => {},+ } as Context+ return { context, execute, request }+}++describe('llma-parser-recipe-create handler', () => {+ const baseParams = {+ name: 'Acme SDK',+ yaml_source: MATCHING_RECIPE,+ trace_id: TRACE_ID,+ event_uuid: EVENT_UUID,+ }++ it('validates against the event and persists the recipe, returning its id', async () => {+ const request = vi+ .fn()+ .mockResolvedValueOnce({ results: [] }) // GET recipes list+ .mockResolvedValueOnce({ id: 'recipe-123' }) // POST create+ const { context } = createContext({ events: [generationEvent()], request })++ const result = await parserRecipeCreate().handler(context, baseParams)++ expect(result).toEqual({ valid: true, recipe_id: 'recipe-123' })+ expect(request).toHaveBeenCalledTimes(2)+ expect(request.mock.calls[1]![0]).toMatchObject({+ method: 'POST',+ path: '/api/projects/42/llm_analytics/parser_recipes/',+ body: { name: 'Acme SDK', source: MATCHING_RECIPE },+ })+ })++ it('returns a validation error and does not persist when the source is not valid YAML', async () => {+ const { context, request } = createContext({ events: [generationEvent()] })++ const result = await parserRecipeCreate().handler(context, { ...baseParams, yaml_source: 'rules: [unclosed' })++ expect(result.valid).toBe(false)+ // Only the recipe list GET ran — nothing was POSTed.+ expect(request).toHaveBeenCalledTimes(1)+ })++ it('rejects a recipe that compiles but leaves the event unrecognized', async () => {+ const { context, request } = createContext({ events: [generationEvent()] })++ const result = await parserRecipeCreate().handler(context, { ...baseParams, yaml_source: NON_MATCHING_RECIPE })++ expect(result.valid).toBe(false)+ expect(result.error).toContain('no rule matched')+ expect(request).toHaveBeenCalledTimes(1)+ })++ it('reuses an identical existing recipe instead of POSTing a duplicate', async () => {+ const request = vi.fn().mockResolvedValueOnce({ results: [{ id: 'recipe-0', source: MATCHING_RECIPE }] })+ const { context } = createContext({ events: [generationEvent()], request })++ const result = await parserRecipeCreate().handler(context, baseParams)++ // The identical recipe is already installed, so the event is already recognized+ // by the time we recompute — hence the flag alongside the deduped id.+ expect(result).toEqual({ valid: true, recipe_id: 'recipe-0', already_recognized: true })+ expect(request).toHaveBeenCalledTimes(1)+ })++ it('does not persist an unproven recipe when both sides are already recognized', async () => {+ // MATCHING_RECIPE is already installed, so validation of the candidate is vacuous —+ // a non-matching candidate must be flagged, not saved team-wide.+ const request = vi.fn().mockResolvedValueOnce({ results: [{ id: 'recipe-0', source: MATCHING_RECIPE }] })+ const { context } = createContext({ events: [generationEvent()], request })++ const result = await parserRecipeCreate().handler(context, { ...baseParams, yaml_source: NON_MATCHING_RECIPE })++ expect(result).toEqual({ valid: true, already_recognized: true })+ // Only the recipe list GET ran — nothing was POSTed.+ expect(request).toHaveBeenCalledTimes(1)+ })++ it('rejects an event whose payload is unavailable server-side instead of saving blind', async () => {+ // Retention TTL / events-table fallback strips the heavy AI columns; with both sides+ // undefined the normalizer reports recognized and any compiling YAML would save.+ const strippedEvent = generationEvent({ properties: {} })+ const { context, request } = createContext({ events: [strippedEvent] })++ const result = await parserRecipeCreate().handler(context, baseParams)++ expect(result.valid).toBe(false)+ expect(result.error).toContain('not available')+ expect(request).not.toHaveBeenCalled()+ })++ it('returns a not-found error when the event is absent from the trace', async () => {+ const { context, request } = createContext({ events: [generationEvent({ id: 'someone-else' })] })++ const result = await parserRecipeCreate().handler(context, baseParams)++ expect(result).toEqual({ valid: false, error: 'event not found in trace — re-check trace_id and event_uuid' })+ expect(request).not.toHaveBeenCalled()+ })++ it('reads $ai_input_state / $ai_output_state for span events', async () => {+ // Only the `_state` fields carry the sample; if the handler read `$ai_input`+ // instead, the input would be undefined and the recipe would fail to match.+ const spanEvent = generationEvent({+ event: '$ai_span',+ properties: {+ $ai_input_state: { acme_kind: 'q', acme_text: 'in' },+ $ai_output_state: { acme_kind: 'q', acme_text: 'out' },+ },+ })+ const request = vi.fn().mockResolvedValueOnce({ results: [] }).mockResolvedValueOnce({ id: 'recipe-span' })+ const { context } = createContext({ events: [spanEvent], request })++ const result = await parserRecipeCreate().handler(context, baseParams)++ expect(result).toEqual({ valid: true, recipe_id: 'recipe-span' })+ })++ it('reports a persistence failure as valid-but-unsaved so the agent does not rewrite', async () => {+ const request = vi.fn().mockResolvedValueOnce({ results: [] }).mockRejectedValueOnce(new Error('500 from API'))+ const { context } = createContext({ events: [generationEvent()], request })++ const result = await parserRecipeCreate().handler(context, baseParams)++ expect(result).toEqual({ valid: true, saved: false, error: '500 from API' })+ })+})diff --git a/services/mcp/tests/vitest-text-loader.ts b/services/mcp/tests/vitest-text-loader.tsnew file mode 100644index 000000000000..81ac6423bd87--- /dev/null+++ b/services/mcp/tests/vitest-text-loader.ts@@ -0,0 +1,17 @@+// The Hono and worker entry points import `*.md`, `*.html`, and `*.yaml` files as raw+// text (esbuild inlines them via its `text` loader at build time; wrangler via a `Text`+// rule). Vitest's default loader rejects those as JS, so every Node-pool vitest config+// registers this transform that stringifies their contents. The workers-pool project+// has its own transform stack and doesn't need it.+export const textLoader = {+ name: 'text-loader',+ transform(code: string, id: string): { code: string; map: null } | undefined {+ if (id.endsWith('.md') || id.endsWith('.html') || id.endsWith('.yaml')) {+ return {+ code: `export default ${JSON.stringify(code)}`,+ map: null,+ }+ }+ return undefined+ },+}diff --git a/services/mcp/types.d.ts b/services/mcp/types.d.tsindex 2b06e4467367..f33c327d7536 100644--- a/services/mcp/types.d.ts+++ b/services/mcp/types.d.ts@@ -14,3 +14,10 @@ declare namespace Cloudflare {MCP_HONO_URL: string | undefined}}++// YAML imports resolve to the file's raw text (esbuild `.yaml` text loader,+// wrangler `Text` rule, vitest raw-text transform).+declare module '*.yaml' {+ const content: string+ export default content+}diff --git a/services/mcp/vitest.config.mts b/services/mcp/vitest.config.mtsindex f63025b0994f..091e27ea2664 100644--- a/services/mcp/vitest.config.mts+++ b/services/mcp/vitest.config.mts@@ -1,19 +1,7 @@import tsconfigPaths from 'vite-tsconfig-paths'import { defineConfig } from 'vitest/config'-// Shared markdown loader so *.md imports resolve as string exports in the-// Node-pool project. The workers-pool project has its own transform stack.-const markdownLoader = {- name: 'markdown-loader',- transform(code: string, id: string) {- if (id.endsWith('.md')) {- return {- code: `export default ${JSON.stringify(code)}`,- map: null,- }- }- },-}+import { textLoader } from './tests/vitest-text-loader'// Two projects run under a single `pnpm test` invocation:// - `unit` → fast Node-pool suite (default pool, ~2s)@@ -29,7 +17,7 @@ export default defineConfig({globalSetup: ['tests/global-setup.ts'],projects: [{- plugins: [tsconfigPaths({ root: '.' }), markdownLoader],+ plugins: [tsconfigPaths({ root: '.' }), textLoader],test: {name: 'unit',globals: true,diff --git a/services/mcp/vitest.hono.config.mts b/services/mcp/vitest.hono.config.mtsindex e2416dc74454..b4f04a5f27c4 100644--- a/services/mcp/vitest.hono.config.mts+++ b/services/mcp/vitest.hono.config.mts@@ -1,21 +1,10 @@import tsconfigPaths from 'vite-tsconfig-paths'import { defineConfig } from 'vitest/config'+import { textLoader } from './tests/vitest-text-loader'+export default defineConfig({- plugins: [- tsconfigPaths({ root: '.' }),- {- name: 'text-loader',- transform(code, id) {- if (id.endsWith('.md') || id.endsWith('.html')) {- return {- code: `export default ${JSON.stringify(code)}`,- map: null,- }- }- },- },- ],+ plugins: [tsconfigPaths({ root: '.' }), textLoader],test: {globals: true,environment: 'node',diff --git a/services/mcp/vitest.integration.config.mts b/services/mcp/vitest.integration.config.mtsindex c307e636fe75..adf4e9928f72 100644--- a/services/mcp/vitest.integration.config.mts+++ b/services/mcp/vitest.integration.config.mts@@ -1,21 +1,7 @@import tsconfigPaths from 'vite-tsconfig-paths'import { defineConfig } from 'vitest/config'-// The Hono and worker entry points import `*.md` and `*.html` template files-// directly. Vitest's default loader rejects those as JS, so we register a tiny-// transform that stringifies their contents. Mirrors the loader in the other-// vitest configs.-const textLoader = {- name: 'text-loader',- transform(code: string, id: string) {- if (id.endsWith('.md') || id.endsWith('.html')) {- return {- code: `export default ${JSON.stringify(code)}`,- map: null,- }- }- },-}+import { textLoader } from './tests/vitest-text-loader'export default defineConfig({plugins: [tsconfigPaths({ root: '.' }), textLoader],diff --git a/services/mcp/vitest.perf.config.mts b/services/mcp/vitest.perf.config.mtsindex 3e6aeabbddd4..1f5794e25765 100644--- a/services/mcp/vitest.perf.config.mts+++ b/services/mcp/vitest.perf.config.mts@@ -1,21 +1,10 @@import tsconfigPaths from 'vite-tsconfig-paths'import { defineConfig } from 'vitest/config'+import { textLoader } from './tests/vitest-text-loader'+export default defineConfig({- plugins: [- tsconfigPaths({ root: '.' }),- {- name: 'text-loader',- transform(code, id) {- if (id.endsWith('.md') || id.endsWith('.html')) {- return {- code: `export default ${JSON.stringify(code)}`,- map: null,- }- }- },- },- ],+ plugins: [tsconfigPaths({ root: '.' }), textLoader],test: {globals: true,environment: 'node',diff --git a/services/mcp/wrangler.jsonc b/services/mcp/wrangler.jsoncindex 3429be28d47c..b88447c56559 100644--- a/services/mcp/wrangler.jsonc+++ b/services/mcp/wrangler.jsonc@@ -53,7 +53,7 @@"rules": [{"type": "Text",- "globs": ["**/*.md"],+ "globs": ["**/*.md", "**/*.yaml"],"fallthrough": true,},],