: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(mcp): add empty-result triggers and conditions to guidance rules (#128500)
Adam Bowkeref708040e9f4
diff --git a/services/mcp/src/hono/guidance/engine.ts b/services/mcp/src/hono/guidance/engine.tsindex 6e65e17d5901..f712f65dea95 100644--- a/services/mcp/src/hono/guidance/engine.ts+++ b/services/mcp/src/hono/guidance/engine.ts@@ -6,6 +6,7 @@ import type { RedisLike } from '../cache/RedisCache'import { resolveSessionKey } from '../mcp-context'import { guidanceEvaluationErrorsTotal, guidanceNoticesTotal } from '../metrics'import type { ResolvedState } from '../request-state-resolver'+import { GuidanceProductState } from './product-state'import { GUIDANCE_RULES, type GuidanceRule } from './rules'// A conversation handle outlives any single request, so its counters keep the session store's@@ -26,6 +27,7 @@ export interface GuidanceCall {execVerb?: string | undefinedargs: Record<string, unknown> | undefinedisError: boolean+ resultEmpty?: boolean | undefined}export type GuidanceOutcome = 'shown' | 'flag_off' | 'suppressed' | 'no_consent'@@ -68,6 +70,9 @@ export function triggerMatches(rule: GuidanceRule, call: GuidanceCall): booleanif (trigger.outcome === 'error' && !call.isError) {return false}+ if (trigger.resultEmpty !== undefined && trigger.resultEmpty !== (call.resultEmpty === true)) {+ return false+ }if (trigger.excludeArgs?.some((path) => isSet(readArgPath(call.args, path)))) {return false}@@ -106,6 +111,12 @@ function ruleApplies(rule: GuidanceRule, state: ResolvedState, preset: string):// Mirror mode only records a call that another scope decided, so it never reports a notice itself.const RULE_STATE_SCRIPT = `local ttl = tonumber(ARGV[1])+if ARGV[4] == 'touch' then+ redis.call('EXPIRE', KEYS[1], ttl)+ redis.call('EXPIRE', KEYS[2], ttl)+ redis.call('EXPIRE', KEYS[3], ttl)+ return tonumber(redis.call('GET', KEYS[3]) or 0)+endif ARGV[4] == 'suppress' thenredis.call('SET', KEYS[2], '1', 'EX', ttl)redis.call('EXPIRE', KEYS[1], ttl)@@ -143,6 +154,8 @@ enum RuleResult {Suppressed = 2,}+type RuleMode = 'match' | 'suppress' | 'mirror' | 'touch'+export class GuidanceEngine {constructor(private readonly redis: RedisLike,@@ -161,15 +174,18 @@ export class GuidanceEngine {}try {const scopes = countingScopes(state)+ const productState = new GuidanceProductState(this.redis, state)let winner: GuidanceNotice | undefinedfor (const rule of rules) {- const result = await this.touchRule(rule, scopes, call, winner === undefined)+ const result = await this.touchRule(rule, scopes, call, winner === undefined, productState)if (result === RuleResult.Fired) {const outcome = firedOutcome(rule, state)winner = {ruleId: rule.id,outcome,- ...(outcome === 'shown' ? { text: rule.text } : {}),+ ...(outcome === 'shown'+ ? { text: typeof rule.text === 'string' ? rule.text : rule.text(call) }+ : {}),}} else if (result === RuleResult.Suppressed && !winner) {winner = { ruleId: rule.id, outcome: 'suppressed' }@@ -190,38 +206,56 @@ export class GuidanceEngine {rule: GuidanceRule,scopes: CountingScopes,call: GuidanceCall,- canFire: boolean+ canFire: boolean,+ productState: GuidanceProductState): Promise<RuleResult> {const suppressing = rule.suppressIfCalled.some((pattern) => matchesToolPattern(pattern, call.toolName))if (!suppressing && !triggerMatches(rule, call)) {return RuleResult.None}- const result = await this.runRuleScript(- rule,- scopes.primary,- scopes.ttl,- suppressing ? 'suppress' : 'match',- canFire+ const { condition } = rule+ if (suppressing || !condition) {+ const mode = suppressing ? 'suppress' : 'match'+ const result = await this.runRuleScript(rule, scopes.primary, scopes.ttl, mode, canFire)+ await this.mirrorRule(rule, scopes, suppressing ? 'suppress' : 'mirror', result !== RuleResult.None)+ return result as RuleResult+ }+ // `touch` keeps a capped rule's counters alive without the `match` count, so a rejected call+ // spends no `maxPerSession`. `match` is a separate step so that a gate that outlives the budget+ // cannot reserve a notice that nobody receives.+ const admitted = await productState.withinBudget('rule_gate', async () => {+ const shown = await this.runRuleScript(rule, scopes.primary, scopes.ttl, 'touch', canFire)+ return shown < rule.maxPerSession && (await condition({ call, productState }))+ })+ const result =+ admitted === true && productState.hasBudgetLeft()+ ? await productState.withinBudget('rule_match', () =>+ this.runRuleScript(rule, scopes.primary, scopes.ttl, 'match', canFire)+ )+ : undefined+ if (result === undefined) {+ await productState.withinBudget('rule_mirror', () => this.mirrorRule(rule, scopes, 'touch', false))+ return RuleResult.None+ }+ await productState.withinBudget('rule_mirror', () =>+ this.mirrorRule(rule, scopes, 'mirror', result !== RuleResult.None))+ return result as RuleResult+ }++ private async mirrorRule(rule: GuidanceRule, scopes: CountingScopes, mode: RuleMode, flag: boolean): Promise<void> {if (scopes.mirror) {- await this.runRuleScript(- rule,- scopes.mirror,- SESSION_TTL_SECONDS,- suppressing ? 'suppress' : 'mirror',- result !== RuleResult.None- )+ await this.runRuleScript(rule, scopes.mirror, SESSION_TTL_SECONDS, mode, flag)}- return result}private async runRuleScript(rule: GuidanceRule,scope: string,ttl: number,- mode: 'match' | 'suppress' | 'mirror',+ mode: RuleMode,flag: boolean- ): Promise<RuleResult> {+ ): Promise<number> {const key = (suffix: string): string => `${scope}:${rule.id}:${suffix}`const fired = await this.redis.eval(RULE_STATE_SCRIPT,@@ -235,7 +269,7 @@ export class GuidanceEngine {mode,flag ? '1' : '0')- return Number(fired) as RuleResult+ return Number(fired)}}diff --git a/services/mcp/src/hono/guidance/product-state.ts b/services/mcp/src/hono/guidance/product-state.tsnew file mode 100644index 000000000000..c89ac32df47c--- /dev/null+++ b/services/mcp/src/hono/guidance/product-state.ts@@ -0,0 +1,93 @@+import { createHash } from 'node:crypto'+import { z } from 'zod'++import type { RedisLike } from '../cache/RedisCache'+import { guidanceProductStateLookupsTotal } from '../metrics'+import type { ResolvedState } from '../request-state-resolver'++// The tool result waits for guidance, so all lookups of one evaluation share this budget.+const LOOKUP_BUDGET_MS = 300+// A lookup that misses the budget keeps running so that it can fill the cache for the next call.+const BACKGROUND_TIMEOUT_MS = 5_000+const HAS_ISSUES_TTL_SECONDS = 24 * 60 * 60+// Short, because the answer changes when a project sends its first exception.+const NO_ISSUES_TTL_SECONDS = 10 * 60++const issuesExistSchema = z.object({ exists: z.boolean() })++// Every read returns `undefined` when the answer is unknown, so a failure never fails the tool call.+export class GuidanceProductState {+ private deadlineAt: number | undefined+ private ingestedData: Promise<boolean | undefined> | undefined+ private errorTrackingIssues: Promise<boolean | undefined> | undefined++ constructor(+ private readonly redis: RedisLike,+ private readonly state: ResolvedState+ ) {}++ hasIngestedData(): Promise<boolean | undefined> {+ this.ingestedData ??= this.withinBudget('ingested_data', () => this.readIngestedData())+ return this.ingestedData+ }++ hasErrorTrackingIssues(): Promise<boolean | undefined> {+ this.errorTrackingIssues ??= this.withinBudget('error_tracking_issues', () => this.readErrorTrackingIssues())+ return this.errorTrackingIssues+ }++ private async readIngestedData(): Promise<boolean | undefined> {+ const project = await this.state.context.stateManager.getCachedOrFetchProject()+ return project?.ingested_event+ }++ private async readErrorTrackingIssues(): Promise<boolean> {+ const projectId = await this.state.context.stateManager.getProjectId()+ // A hit skips the API's permission check, so only a caller with the same user and scopes reuses it.+ const caller = createHash('sha256')+ .update(`${this.state.distinctId}|${[...this.state.apiKeyScopes].sort().join(',')}`)+ .digest('base64url')+ .slice(0, 22)+ const key = `mcp:guidance:state:error-tracking-issues:${projectId}:${caller}`+ const cached = await this.redis.get(key)+ if (cached !== null) {+ return cached === '1'+ }+ const { exists } = issuesExistSchema.parse(+ await this.state.context.api.request<unknown>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(projectId)}/error_tracking/issues/exists/`,+ timeoutMs: BACKGROUND_TIMEOUT_MS,+ signal: AbortSignal.timeout(BACKGROUND_TIMEOUT_MS),+ })+ )+ const ttl = exists ? HAS_ISSUES_TTL_SECONDS : NO_ISSUES_TTL_SECONDS+ await this.redis.set(key, exists ? '1' : '0', 'EX', ttl).catch(() => undefined)+ return exists+ }++ hasBudgetLeft(): boolean {+ return this.deadlineAt === undefined || Date.now() < this.deadlineAt+ }++ async withinBudget<T>(check: string, read: () => Promise<T>): Promise<T | undefined> {+ this.deadlineAt ??= Date.now() + LOOKUP_BUDGET_MS+ const work = read()+ // After a timeout nothing awaits this promise, so its rejection needs its own handler.+ work.catch(() => undefined)+ let timer: ReturnType<typeof setTimeout> | undefined+ const timedOut = new Promise<'timeout'>((resolve) => {+ timer = setTimeout(() => resolve('timeout'), Math.max(0, this.deadlineAt! - Date.now()))+ })+ try {+ const outcome = await Promise.race([work.then((value) => ({ value })), timedOut])+ guidanceProductStateLookupsTotal.inc({ check, result: outcome === 'timeout' ? 'timeout' : 'answered' })+ return outcome === 'timeout' ? undefined : outcome.value+ } catch {+ guidanceProductStateLookupsTotal.inc({ check, result: 'error' })+ return undefined+ } finally {+ clearTimeout(timer)+ }+ }+}diff --git a/services/mcp/src/hono/guidance/rules.ts b/services/mcp/src/hono/guidance/rules.tsindex 0f36c5e4dd6e..98e3cbe50332 100644--- a/services/mcp/src/hono/guidance/rules.ts+++ b/services/mcp/src/hono/guidance/rules.ts@@ -2,8 +2,17 @@ import { z } from 'zod'import { MCP_SCOPE_PRESET, type McpScopePreset } from '@/lib/scope-preset'+import type { GuidanceCall } from './engine'+import type { GuidanceProductState } from './product-state'+const scopePresets = Object.values(MCP_SCOPE_PRESET) as [McpScopePreset, ...McpScopePreset[]]+type GuidanceCondition = (input: {+ call: GuidanceCall+ productState: GuidanceProductState+}) => boolean | Promise<boolean>+type GuidanceText = (call: GuidanceCall) => string+const guidanceRuleSchema = z.object({id: z.string().regex(/^[a-z0-9-]+$/),/** The feature flag that turns the rule on for a caller. Every rule ships off. */@@ -20,6 +29,7 @@ const guidanceRuleSchema = z.object({argMaxLength: z.number().int().min(1).optional(),/** Call arguments that rule the call out when they are set, such as a target outside the project. */excludeArgs: z.array(z.string().min(1)).optional(),+ resultEmpty: z.boolean().optional(),outcome: z.enum(['any', 'success', 'error']),presets: z.array(z.enum(scopePresets)).min(1),}),@@ -32,7 +42,9 @@ const guidanceRuleSchema = z.object({requiresTool: z.array(z.string().min(1)).min(1),/** The notice sends the agent to an AI feature, so it is withheld (and stamped) without org consent. */requiresAiConsent: z.boolean().optional(),- text: z.string().min(1).max(2000),+ /** Runs for every outcome, so `shown` and `flag_off` callers stay comparable. A rejected call is not counted. */+ condition: z.custom<GuidanceCondition>((value) => typeof value === 'function').optional(),+ text: z.union([z.string().min(1).max(2000), z.custom<GuidanceText>((value) => typeof value === 'function')]),})export type GuidanceRule = z.infer<typeof guidanceRuleSchema>diff --git a/services/mcp/src/hono/metrics.ts b/services/mcp/src/hono/metrics.tsindex 07cd8c9ae823..75dbf04db09d 100644--- a/services/mcp/src/hono/metrics.ts+++ b/services/mcp/src/hono/metrics.ts@@ -230,4 +230,10 @@ export const guidanceEvaluationErrorsTotal = new Counter({help: 'Guidance evaluations that failed (Redis errors or timeouts) and yielded no notice.',})+export const guidanceProductStateLookupsTotal = new Counter({+ name: 'mcp_guidance_product_state_lookups_total',+ help: 'Budgeted reads for guidance conditions, by check and result (answered, timeout, error).',+ labelNames: ['check', 'result'] as const,+})+export { register }diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex 8e868ecf7202..72162a27bbc0 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -9,6 +9,7 @@ import {toolResultAnalyticsProperties,type ToolResultPayload,} from '@/lib/build-tool-result'+import { isEmptyToolResult } from '@/lib/empty-tool-result'import {ExecCommandError,handleToolError,@@ -509,6 +510,7 @@ export class ToolExecutor {toolName: tool.name,args: validation.data,isError: false,+ resultEmpty: isEmptyToolResult(handlerResult, tool.name),})let response: ToolResultPayload@@ -750,6 +752,7 @@ export class ToolExecutor {execVerb: typeof execShape.$mcp_exec_verb === 'string' ? execShape.$mcp_exec_verb : undefined,args: execMetrics.innerToolName ? parseExecCallInnerArgs(validation.data.command) : validation.data,isError: innerFailure !== undefined,+ resultEmpty: execMetrics.resultEmpty,})void trackToolCall(diff --git a/services/mcp/tests/hono/guidance-engine.test.ts b/services/mcp/tests/hono/guidance-engine.test.tsindex 49507fe9e7f5..28429aaed8dd 100644--- a/services/mcp/tests/hono/guidance-engine.test.ts+++ b/services/mcp/tests/hono/guidance-engine.test.ts@@ -263,6 +263,132 @@ describe('GuidanceEngine', () => {])})+ it.each([+ ['an empty result', true, true],+ ['a populated result', false, false],+ ['a result of unknown size', undefined, false],+ ])('a resultEmpty rule handles %s', (_label, resultEmpty, expected) => {+ const emptyRule: GuidanceRule = {+ ...rule,+ trigger: { tool: 'execute-sql', resultEmpty: true, outcome: 'any', presets: ['user'] },+ }+ expect(triggerMatches(emptyRule, { ...otherQuery, resultEmpty })).toBe(expected)+ })++ describe('a rule with a condition', () => {+ const conditionalRule = (condition: GuidanceRule['condition']): GuidanceRule => ({+ ...rule,+ threshold: 1,+ condition,+ })++ it('does not spend the session cap on a call the condition rejects', async () => {+ const condition = vi.fn().mockResolvedValueOnce(false).mockResolvedValue(true)+ const engine = new GuidanceEngine(makeGuidanceRedis(), [conditionalRule(condition)])+ await expect(run(engine, makeState(), [replayQuery, replayQuery])).resolves.toEqual([+ undefined,+ 'test-rule:shown',+ ])+ })++ it('skips the condition once the rule reaches its cap and keeps its counters alive', async () => {+ const condition = vi.fn().mockResolvedValue(true)+ const redis = makeGuidanceRedis()+ const engine = new GuidanceEngine(redis, [conditionalRule(condition)])+ await run(engine, makeState(), [replayQuery, replayQuery])+ expect(condition).toHaveBeenCalledTimes(1)+ expect(redis.evalCalls.at(-1)?.[6]).toBe('touch')+ })++ it('counts an admitted match when an earlier rule wins the call', async () => {+ const first: GuidanceRule = { ...conditionalRule(vi.fn().mockResolvedValue(true)), id: 'first-rule' }+ const second: GuidanceRule = {+ ...conditionalRule(vi.fn().mockResolvedValue(true)),+ id: 'second-rule',+ threshold: 2,+ }+ const engine = new GuidanceEngine(makeGuidanceRedis(), [first, second])+ await expect(run(engine, makeState(), [replayQuery, replayQuery])).resolves.toEqual([+ 'first-rule:shown',+ 'second-rule:shown',+ ])+ })++ it('reserves no notice when the gate finishes after the budget', async () => {+ vi.useFakeTimers()+ try {+ const redis = makeGuidanceRedis()+ const evaluateScript = redis.eval.bind(redis)+ const lateEval = vi.spyOn(redis, 'eval').mockImplementation(async (script, keys, ...args) => {+ await new Promise((resolve) => setTimeout(resolve, 400))+ return evaluateScript(script, keys, ...args)+ })+ const engine = new GuidanceEngine(redis, [conditionalRule(vi.fn().mockResolvedValue(true))])+ const pending = engine.evaluate(makeState(), replayQuery)+ await vi.advanceTimersByTimeAsync(1000)+ await expect(pending).resolves.toBeUndefined()+ expect(lateEval.mock.calls.map((call) => call[8])).toEqual(['touch'])+ } finally {+ vi.useRealTimers()+ }+ })++ it.each(['touch', 'match'])('holds the tool result to the budget when Redis stalls on %s', async (stalled) => {+ vi.useFakeTimers()+ try {+ const redis = makeGuidanceRedis()+ vi.spyOn(redis, 'eval').mockImplementation((_script, _keys, ...args) =>+ args[6] === 'touch' && stalled === 'match' ? Promise.resolve(0) : new Promise(() => {})+ )+ const admitted = (id: string): GuidanceRule => ({+ ...conditionalRule(vi.fn().mockResolvedValue(true)),+ id,+ })+ const engine = new GuidanceEngine(redis, [admitted('a'), admitted('b'), admitted('c')])+ const pending = engine.evaluate(makeState(), replayQuery)+ await vi.advanceTimersByTimeAsync(310)+ await expect(pending).resolves.toBeUndefined()+ } finally {+ vi.useRealTimers()+ }+ })++ it('applies the condition to a caller with the flag off', async () => {+ const condition = vi.fn().mockResolvedValueOnce(false).mockResolvedValue(true)+ const engine = new GuidanceEngine(makeGuidanceRedis(), [conditionalRule(condition)])+ const state = makeState({ toolFeatureFlags: {} })+ await expect(run(engine, state, [replayQuery, replayQuery])).resolves.toEqual([+ undefined,+ 'test-rule:flag_off',+ ])+ })++ it('records suppression without reading the condition', async () => {+ const condition = vi.fn().mockResolvedValue(true)+ const engine = new GuidanceEngine(makeGuidanceRedis(), [conditionalRule(condition)])+ await expect(run(engine, makeState(), [visionCall, replayQuery])).resolves.toEqual([+ undefined,+ 'test-rule:suppressed',+ ])+ expect(condition).toHaveBeenCalledTimes(1)+ })+ })++ it('builds function text from the call, only when the notice is shown', async () => {+ const text = vi.fn((call: GuidanceCall) => `Used ${call.toolName}.`)+ const engine = new GuidanceEngine(makeGuidanceRedis(), [{ ...rule, threshold: 1, text }])+ await expect(engine.evaluate(makeState({ toolFeatureFlags: {} }), replayQuery)).resolves.toEqual({+ ruleId: 'test-rule',+ outcome: 'flag_off',+ })+ expect(text).not.toHaveBeenCalled()+ const shown = await new GuidanceEngine(makeGuidanceRedis(), [{ ...rule, threshold: 1, text }]).evaluate(+ makeState(),+ replayQuery+ )+ expect(shown?.text).toBe('Used execute-sql.')+ })+it('shows nothing and logs when Redis fails', async () => {const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})const engine = new GuidanceEngine(makeGuidanceRedis(true), [{ ...rule, threshold: 1 }])diff --git a/services/mcp/tests/hono/guidance-product-state.test.ts b/services/mcp/tests/hono/guidance-product-state.test.tsnew file mode 100644index 000000000000..e618cb510422--- /dev/null+++ b/services/mcp/tests/hono/guidance-product-state.test.ts@@ -0,0 +1,111 @@+import { afterEach, describe, expect, it, vi } from 'vitest'++import { GuidanceProductState } from '@/hono/guidance/product-state'+import type { ResolvedState } from '@/hono/request-state-resolver'++import { makeToolExecutorState } from '../shared/test-utils'+import { makeGuidanceRedis } from './helpers/guidance-redis-stubs'++function makeState(+ options: {+ project?: () => Promise<unknown>+ request?: () => Promise<unknown>+ } = {}+): { state: ResolvedState; request: ReturnType<typeof vi.fn> } {+ const state = makeToolExecutorState([], { suppressAnalytics: false })+ const request = vi.fn(options.request ?? (async () => ({ exists: true })))+ state.context.stateManager = {+ getCachedOrFetchProject: vi.fn(options.project ?? (async () => ({ ingested_event: true }))),+ getProjectId: vi.fn().mockResolvedValue('42'),+ } as any+ state.context.api = { request } as any+ return { state, request }+}++describe('GuidanceProductState', () => {+ afterEach(() => {+ vi.useRealTimers()+ })++ it.each([+ [true, '1', 86_400],+ [false, '0', 600],+ ])('caches exists=%s across evaluations with its own TTL', async (exists, stored, ttl) => {+ const redis = makeGuidanceRedis()+ const set = vi.spyOn(redis, 'set')+ const { state, request } = makeState({ request: async () => ({ exists }) })++ await expect(new GuidanceProductState(redis, state).hasErrorTrackingIssues()).resolves.toBe(exists)+ await expect(new GuidanceProductState(redis, state).hasErrorTrackingIssues()).resolves.toBe(exists)++ expect(request).toHaveBeenCalledTimes(1)+ expect(set).toHaveBeenCalledWith(expect.stringContaining(':42'), stored, 'EX', ttl)+ })++ it.each([+ ['user', { distinctId: 'another-user' }],+ ['scope set', { apiKeyScopes: ['project:read'] }],+ ])('does not reuse a cached answer for another %s', async (_label, caller) => {+ const redis = makeGuidanceRedis()+ const { state, request } = makeState()+ await new GuidanceProductState(redis, state).hasErrorTrackingIssues()+ await new GuidanceProductState(redis, { ...state, ...caller }).hasErrorTrackingIssues()+ expect(request).toHaveBeenCalledTimes(2)+ })++ it.each([+ ['a rejected request', async () => Promise.reject(new Error('boom'))],+ ['an unexpected response', async () => ({ unexpected: true })],+ ])('treats %s as unknown and does not cache it', async (_label, requestImpl) => {+ const redis = makeGuidanceRedis()+ const { state, request } = makeState({ request: requestImpl })++ await expect(new GuidanceProductState(redis, state).hasErrorTrackingIssues()).resolves.toBeUndefined()+ await expect(new GuidanceProductState(redis, state).hasErrorTrackingIssues()).resolves.toBeUndefined()++ expect(request).toHaveBeenCalledTimes(2)+ })++ it('returns on the budget and lets the slow lookup fill the cache', async () => {+ vi.useFakeTimers()+ const redis = makeGuidanceRedis()+ let finish: (value: unknown) => void = () => {}+ const { state, request } = makeState({+ request: () => new Promise((resolve) => (finish = resolve)),+ })++ const pending = new GuidanceProductState(redis, state).hasErrorTrackingIssues()+ await vi.advanceTimersByTimeAsync(300)+ await expect(pending).resolves.toBeUndefined()++ finish({ exists: true })+ await vi.advanceTimersByTimeAsync(0)++ await expect(new GuidanceProductState(redis, state).hasErrorTrackingIssues()).resolves.toBe(true)+ expect(request).toHaveBeenCalledTimes(1)+ })++ it('shares one budget across the lookups of an evaluation', async () => {+ vi.useFakeTimers()+ const after = (ms: number, value: unknown) => (): Promise<unknown> =>+ new Promise((resolve) => setTimeout(() => resolve(value), ms))+ const { state } = makeState({+ project: after(200, { ingested_event: true }),+ request: after(200, { exists: true }),+ })+ const productState = new GuidanceProductState(makeGuidanceRedis(), state)++ const ingested = productState.hasIngestedData()+ await vi.advanceTimersByTimeAsync(200)+ await expect(ingested).resolves.toBe(true)++ const issues = productState.hasErrorTrackingIssues()+ await vi.advanceTimersByTimeAsync(100)+ await expect(issues).resolves.toBeUndefined()+ })++ it('treats a failing project read as unknown', async () => {+ const { state } = makeState({ project: async () => Promise.reject(new Error('boom')) })+ await expect(new GuidanceProductState(makeGuidanceRedis(), state).hasIngestedData()).resolves.toBeUndefined()+ })+})diff --git a/services/mcp/tests/hono/helpers/guidance-redis-stubs.ts b/services/mcp/tests/hono/helpers/guidance-redis-stubs.tsindex 18424b512e6d..7e20de25845e 100644--- a/services/mcp/tests/hono/helpers/guidance-redis-stubs.ts+++ b/services/mcp/tests/hono/helpers/guidance-redis-stubs.ts@@ -60,6 +60,10 @@ export function makeGuidanceRedis(failing = false): GuidanceRedisStub {args.map(String)const ttl = Number(ttlArg)const keys = [matchedKey, suppressedKey, shownKey]+ if (mode === 'touch') {+ refresh(keys, ttl)+ return guard(Number(store.get(shownKey!) ?? 0))+ }if (mode === 'suppress') {store.set(suppressedKey!, '1')refresh(keys, ttl)diff --git a/services/mcp/tests/hono/tool-executor-guidance.test.ts b/services/mcp/tests/hono/tool-executor-guidance.test.tsindex 5e1ac4601efc..8ae3aa138167 100644--- a/services/mcp/tests/hono/tool-executor-guidance.test.ts+++ b/services/mcp/tests/hono/tool-executor-guidance.test.ts@@ -18,7 +18,7 @@ vi.mock('@/lib/posthog', async () => {})import { GuidanceEngine } from '@/hono/guidance/engine'-import { MCP_GUIDANCE_REPLAY_VISION_FLAG, MCP_GUIDANCE_SQL_SCHEMA_FLAG } from '@/hono/guidance/rules'+import { MCP_GUIDANCE_REPLAY_VISION_FLAG, MCP_GUIDANCE_SQL_SCHEMA_FLAG, type GuidanceRule } from '@/hono/guidance/rules'import { InstructionsBuilder } from '@/hono/instructions'import { ToolCatalog } from '@/hono/tool-catalog'import { ToolExecutor } from '@/hono/tool-executor'@@ -161,4 +161,43 @@ describe('ToolExecutor guidance notices', () => {'sql-failures-to-schema',])})++ it.each(['direct', 'exec'])('passes an empty list result to guidance in %s mode', async (mode) => {+ const issuesList = makeTool('query-error-tracking-issues-list', () => ({ results: [] }))+ vi.spyOn(catalog, 'getToolByName').mockImplementation((name) =>+ name === issuesList.name+ ? { build: () => issuesList, meta: undefined, rawInputSchema: undefined, definition: undefined }+ : undefined+ )+ const emptyRule: GuidanceRule = {+ id: 'empty-result-rule',+ flag: 'mcp-guidance-empty-result',+ trigger: { tool: issuesList.name, resultEmpty: true, outcome: 'success', presets: ['user'] },+ threshold: 1,+ maxPerSession: 1,+ suppressIfCalled: [],+ requiresTool: [issuesList.name],+ text: 'The result is empty.',+ }+ const executor = new ToolExecutor(+ catalog,+ new InstructionsBuilder(''),+ undefined,+ new GuidanceEngine(makeGuidanceRedis(), [emptyRule])+ )+ const state = makeToolExecutorState([issuesList], {+ useSingleExec: mode === 'exec',+ suppressAnalytics: false,+ toolFeatureFlags: { [emptyRule.flag]: true },+ })++ const result = (await executor.handleToolCall(+ mode === 'exec'+ ? { name: 'exec', arguments: { command: `call ${issuesList.name} {}` } }+ : { name: issuesList.name, arguments: {} },+ state+ )) as SqlResult++ expect(result.content[0]?.text).toContain('The result is empty.')+ })})