: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 agent-experience eval benchmark spec and task set (#67947)
Daniel Viscade7a977f6aac
diff --git a/services/mcp/evals/README.md b/services/mcp/evals/README.mdnew file mode 100644index 000000000000..6dedce42debb--- /dev/null+++ b/services/mcp/evals/README.md@@ -0,0 +1,43 @@+# MCP agent-experience evals++The objective function for improving the MCP server: a fixed benchmark of agent tasks, sampled from real usage, that can be scored against a live MCP server. A change to a tool description, schema, or handler "improves the MCP" only if these scores say so.++Two consumers:++- **Regression protection** — run before/after any change to tool descriptions, schemas, or the catalog.+- **The improve-my-mcp campaign** — an autoresearch-style loop that proposes a change, re-runs the affected benchmark slice, and only keeps changes that measurably help. Every campaign PR carries before/after scores from this harness as evidence.++## Layout++- `benchmark/tasks.yaml` — the task set (v0). Each task is a realistic agent goal with the tools a competent agent should reach for.+- `benchmark/schema.ts` — zod schema, loader, and types. `tests/evals/benchmark.test.ts` validates the fixtures against the schema and the live tool catalog, so a tool rename or removal fails CI here instead of silently invalidating the benchmark.++## Task format++```yaml+- id: flags-list-active # kebab-case, unique+ category: feature-flags # see TASK_CATEGORIES in schema.ts+ intent: 'List all our active feature flags.' # what the agent is asked, phrased like a real request+ expected_tools: [feature-flag-get-all] # what a competent agent should call+ acceptable_tools: [execute-sql] # also fine; no tool-selection penalty+ success_criteria: "Returns the project's active flags by key." # pass condition for the agent-mode judge+ probe: # optional: deterministic call, no LLM needed+ tool: feature-flag-get-all+ args: {}+ max_ms: 15000+```++## Modes++**Probe mode** (deterministic, no LLM): executes each task's `probe` against a live server and validates schemas, latency, and error responses for every referenced tool. Probes must reference read-only tools — the fixture test enforces `readOnlyHint`, and the runner refuses anything else, so a bad fixture cannot mutate project data.++**Agent mode** (LLM): replays each `intent` through an agent loop against the live server, then scores task success against `success_criteria` (LLM judge) and tool selection against `expected_tools`/`acceptable_tools`.++Scores per run: task success rate, tool-selection accuracy, schema-validation failure count, tool error rate, retries per task, latency p50/p95, tokens per task.++## Authoring rules++- Sample intents from real usage (`$mcp_intent` clusters, `query-mcp-tool-sample-intents`) but **paraphrase — never paste customer text verbatim**, and never include PII.+- Keep the task set stable within a campaign: scores are only comparable across runs of the same benchmark version. Bump `version` on breaking changes to the set.+- Weight new tasks toward observed pain: high-error tools, discoverability misses (intents where agents picked the wrong tool), and multi-step chains (resolve id → act).+- A task must be achievable in a seeded demo project — don't write tasks that depend on one specific production dataset.diff --git a/services/mcp/evals/benchmark/schema.ts b/services/mcp/evals/benchmark/schema.tsnew file mode 100644index 000000000000..a9b36e525469--- /dev/null+++ b/services/mcp/evals/benchmark/schema.ts@@ -0,0 +1,73 @@+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { parse as parseYaml } from 'yaml'+import { z } from 'zod'++/**+ * Benchmark task file schema — the objective function for the MCP agent+ * experience. Tasks are sampled from real agent intents (paraphrased, never+ * verbatim) and describe what a competent agent should achieve against a+ * live MCP server, which tools it is expected to reach for, and optionally a+ * deterministic probe call the runner can execute without an LLM.+ */++export const TASK_CATEGORIES = [+ 'sql',+ 'data-schema',+ 'product-analytics',+ 'insights',+ 'error-tracking',+ 'feature-flags',+ 'session-replay',+ 'llm-analytics',+ 'logs',+ 'dashboards',+ 'docs',+ 'project',+ 'mcp-analytics',+ 'metrics',+] as const++export const BenchmarkProbeSchema = z.object({+ // Probes must reference read-only tools; the runner refuses to execute a+ // probe whose tool lacks readOnlyHint so a bad fixture can't mutate data.+ tool: z.string().min(1),+ args: z.record(z.string(), z.unknown()).default({}),+ max_ms: z.number().int().positive().default(15_000),+})++export const BenchmarkTaskSchema = z.object({+ id: z+ .string()+ .regex(/^[a-z0-9][a-z0-9-]+$/, 'task ids are kebab-case')+ .max(64),+ category: z.enum(TASK_CATEGORIES),+ // The user-visible goal the agent is given, written like a real request.+ intent: z.string().min(10),+ // Tools a competent agent is expected to call to complete the task.+ expected_tools: z.array(z.string().min(1)).min(1),+ // Tools that also count as a reasonable path (no tool-selection penalty).+ acceptable_tools: z.array(z.string().min(1)).default([]),+ // Plain-language pass condition consumed by the agent-mode judge.+ success_criteria: z.string().min(10),+ probe: BenchmarkProbeSchema.optional(),+})++export const BenchmarkFileSchema = z.object({+ version: z.literal(0),+ tasks: z.array(BenchmarkTaskSchema).min(1),+})++export type BenchmarkProbe = z.infer<typeof BenchmarkProbeSchema>+export type BenchmarkTask = z.infer<typeof BenchmarkTaskSchema>+export type BenchmarkFile = z.infer<typeof BenchmarkFileSchema>++export const DEFAULT_BENCHMARK_PATH = fileURLToPath(new URL('./tasks.yaml', import.meta.url))++export function loadBenchmark(path: string = DEFAULT_BENCHMARK_PATH): BenchmarkFile {+ return BenchmarkFileSchema.parse(parseYaml(readFileSync(path, 'utf-8')))+}++export function referencedTools(task: BenchmarkTask): string[] {+ return [...new Set([...task.expected_tools, ...task.acceptable_tools, ...(task.probe ? [task.probe.tool] : [])])]+}diff --git a/services/mcp/evals/benchmark/tasks.yaml b/services/mcp/evals/benchmark/tasks.yamlnew file mode 100644index 000000000000..668331bae13f--- /dev/null+++ b/services/mcp/evals/benchmark/tasks.yaml@@ -0,0 +1,229 @@+# MCP agent-experience benchmark v0.+#+# Task intents are paraphrased from real agent usage (top tool families by+# production volume) — never verbatim copies of customer text. Keep probes+# read-only; the runner refuses non-read-only probe tools.+version: 0+tasks:+ # --- sql ---------------------------------------------------------------+ - id: sql-daily-event-volume+ category: sql+ intent: 'How many events did we ingest per day over the last 7 days?'+ expected_tools: [execute-sql]+ acceptable_tools: [query-trends]+ success_criteria: 'Returns a per-day event count covering roughly the last seven days.'+ probe:+ tool: execute-sql+ args:+ query: 'SELECT toDate(timestamp) AS day, count() AS events FROM events WHERE timestamp > now() - INTERVAL 7 DAY GROUP BY day ORDER BY day'++ - id: sql-top-events+ category: sql+ intent: 'List the 10 most common event names this month with their counts.'+ expected_tools: [execute-sql]+ acceptable_tools: [read-data-schema, query-trends]+ success_criteria: 'Returns up to ten event names ranked by count for the last ~30 days.'+ probe:+ tool: execute-sql+ args:+ query: 'SELECT event, count() AS c FROM events WHERE timestamp > now() - INTERVAL 30 DAY GROUP BY event ORDER BY c DESC LIMIT 10'++ - id: sql-find-saved-insights+ category: sql+ intent: 'Do we already have any saved insights about signup conversion?'+ expected_tools: [execute-sql]+ acceptable_tools: [insight-get]+ success_criteria: 'Searches saved insights (system tables) for signup/conversion matches and reports what exists, checking the table schema before querying it.'++ # --- data-schema --------------------------------------------------------+ - id: schema-discover-onboarding-events+ category: data-schema+ intent: "What events does this project capture? I'm especially looking for anything related to onboarding."+ expected_tools: [read-data-schema]+ success_criteria: 'Lists project events and calls out onboarding-related ones, without inventing event names.'+ probe:+ tool: read-data-schema+ args:+ query:+ kind: events++ - id: schema-property-values+ category: data-schema+ intent: 'What browsers do our users use? Check the actual property values rather than guessing.'+ expected_tools: [read-data-schema]+ acceptable_tools: [execute-sql]+ success_criteria: 'Reads browser property values from the schema tool (or SQL) and reports observed values.'++ - id: warehouse-schema-tables+ category: data-schema+ intent: 'What tables are available in our data warehouse, and what columns do they have?'+ expected_tools: [read-data-warehouse-schema]+ acceptable_tools: [execute-sql]+ success_criteria: 'Enumerates warehouse tables with column details.'++ # --- product-analytics ---------------------------------------------------+ - id: trends-weekly-active-users+ category: product-analytics+ intent: 'Chart weekly active users for the past 8 weeks.'+ expected_tools: [query-trends]+ acceptable_tools: [execute-sql]+ success_criteria: 'Produces a weekly unique-user series covering roughly eight weeks, after confirming the event exists in the schema.'++ - id: funnel-signup-conversion+ category: product-analytics+ intent: "What's our conversion rate from viewing the site to signing up, this month?"+ expected_tools: [query-funnel]+ acceptable_tools: [execute-sql]+ success_criteria: 'Builds a two-step funnel from real events and reports a conversion percentage.'++ - id: retention-weekly-return+ category: product-analytics+ intent: 'Do users who signed up last month keep coming back week over week?'+ expected_tools: [query-retention]+ success_criteria: 'Returns a weekly retention breakdown for the signup cohort.'++ - id: paths-after-login+ category: product-analytics+ intent: 'What do users typically do right after logging in?'+ expected_tools: [query-paths]+ acceptable_tools: [execute-sql]+ success_criteria: 'Shows the most common event sequences starting from a login-like event.'++ - id: lifecycle-user-composition+ category: product-analytics+ intent: "Of this week's active users, how many are new versus returning versus resurrecting?"+ expected_tools: [query-lifecycle]+ success_criteria: 'Reports the lifecycle composition buckets for the current week.'++ - id: stickiness-engagement+ category: product-analytics+ intent: 'How many days per week do our most engaged users actually use the product?'+ expected_tools: [query-stickiness]+ success_criteria: 'Returns a stickiness distribution (users by number of active days).'++ - id: trends-actors-spike+ category: product-analytics+ intent: 'Something spiked yesterday in our exception events — which users are behind it?'+ expected_tools: [query-trends-actors]+ acceptable_tools: [execute-sql, query-error-tracking-issues-list]+ success_criteria: 'Identifies the people behind the spike data point rather than just re-plotting the trend.'++ # --- insights -------------------------------------------------------------+ - id: insight-create-daily-signups+ category: insights+ intent: 'Save a trends insight tracking daily signups so the team can find it later.'+ expected_tools: [insight-create]+ acceptable_tools: [query-trends, read-data-schema]+ success_criteria: 'Creates a saved insight with a sensible name and returns its link.'++ - id: insight-rename+ category: insights+ intent: "Rename my 'Daily signups' insight to 'Signups (daily)'."+ expected_tools: [insight-update]+ acceptable_tools: [execute-sql, insight-get]+ success_criteria: 'Finds the existing insight by name and updates only its name.'++ - id: insight-run-existing+ category: insights+ intent: 'Run our saved weekly revenue insight and tell me the latest value.'+ expected_tools: [insight-query]+ acceptable_tools: [insight-get, execute-sql]+ success_criteria: 'Locates the saved insight, executes it, and reports the most recent data point.'++ # --- error-tracking --------------------------------------------------------+ - id: errors-top-issues+ category: error-tracking+ intent: 'What are our top error issues by volume this week?'+ expected_tools: [query-error-tracking-issues-list]+ acceptable_tools: [execute-sql]+ success_criteria: 'Lists the highest-volume error issues for the last seven days.'++ - id: errors-stack-traces+ category: error-tracking+ intent: 'Show me recent stack traces for our most common error.'+ expected_tools: [query-error-tracking-issue-events]+ acceptable_tools: [query-error-tracking-issues-list]+ success_criteria: 'Finds the top issue first, then fetches sample events with stack traces for it.'++ # --- feature-flags ----------------------------------------------------------+ - id: flags-list-active+ category: feature-flags+ intent: 'List all our active feature flags.'+ expected_tools: [feature-flag-get-all]+ success_criteria: "Returns the project's active flags by key."+ probe:+ tool: feature-flag-get-all+ args: {}++ - id: flag-rollout-conditions+ category: feature-flags+ intent: 'What are the rollout conditions for our mcp-analytics feature flag?'+ expected_tools: [feature-flag-get-definition]+ acceptable_tools: [feature-flag-get-all]+ success_criteria: "Resolves the flag's numeric id first, then reports its release conditions — does not guess the id."++ # --- session-replay ----------------------------------------------------------+ - id: replay-rage-clicks+ category: session-replay+ intent: 'Find session recordings from this week where users rage-clicked.'+ expected_tools: [query-session-recordings-list]+ success_criteria: 'Returns recordings filtered to the last week with rage-click activity.'++ # --- llm-analytics -------------------------------------------------------------+ - id: llma-recent-traces+ category: llm-analytics+ intent: 'Show me our latest LLM traces and how many tokens they used.'+ expected_tools: [query-llm-traces-list]+ success_criteria: 'Lists recent LLM traces including token usage.'++ # --- logs -----------------------------------------------------------------------+ - id: logs-error-severity+ category: logs+ intent: 'Are there any error-severity logs from our API service in the last hour?'+ expected_tools: [query-logs]+ success_criteria: 'Queries logs filtered by severity and service for the last hour.'++ # --- dashboards --------------------------------------------------------------------+ - id: dashboard-team-health+ category: dashboards+ intent: "Create a dashboard called 'Team health' from our existing activation insights."+ expected_tools: [dashboard-create]+ acceptable_tools: [execute-sql, insight-get]+ success_criteria: 'Reuses existing insights where they exist and creates the dashboard, returning its link.'++ # --- docs -------------------------------------------------------------------------+ - id: docs-behavioral-cohort+ category: docs+ intent: 'How do I create a behavioral cohort in PostHog?'+ expected_tools: [docs-search]+ success_criteria: 'Answers from documentation with source links, not from memory.'++ # --- project ------------------------------------------------------------------------+ - id: project-switch-then-flags+ category: project+ intent: 'Switch to our other project and list its feature flags.'+ expected_tools: [switch-project, feature-flag-get-all]+ success_criteria: 'Switches the active project before listing flags, and says which project the flags came from.'++ # --- mcp-analytics (dogfood discoverability) -------------------------------------------+ - id: mcp-tool-reliability+ category: mcp-analytics+ intent: 'How reliable has our execute-sql MCP tool been this week? I want error rate and p95 latency.'+ expected_tools: [query-mcp-tool-stats]+ acceptable_tools: [execute-sql, query-mcp-tool-daily-stats]+ success_criteria: 'Uses the MCP analytics tooling (not raw SQL) to report calls, error rate, and p95 for the tool.'++ - id: mcp-session-intents+ category: mcp-analytics+ intent: 'What have agents been trying to do with our MCP server lately?'+ expected_tools: [query-mcp-tool-sample-intents]+ acceptable_tools: [execute-sql, mcp-analytics-sessions-list]+ success_criteria: 'Surfaces recent agent intents from MCP analytics rather than guessing.'++ # --- metrics ----------------------------------------------------------------------------+ - id: metrics-api-error-rate+ category: metrics+ intent: 'What does the error-rate metric for our API service look like over the last day?'+ expected_tools: [metric-names-list, query-metrics]+ acceptable_tools: [execute-sql]+ success_criteria: 'Resolves the exact metric name first (names match exactly), then queries a rate over the last 24h — does not guess the metric name.'diff --git a/services/mcp/evals/runner/probe.ts b/services/mcp/evals/runner/probe.tsnew file mode 100644index 000000000000..e06f32b5ce66--- /dev/null+++ b/services/mcp/evals/runner/probe.ts@@ -0,0 +1,132 @@+/**+ * Deterministic probe runner — no LLM. Connects to a LIVE MCP server,+ * verifies every tool the benchmark references is advertised, executes each+ * task's read-only probe call, and prints/writes a score summary.+ *+ * Usage:+ * LIVE_MCP_URL=http://localhost:9876 LIVE_MCP_TOKEN=phx_... \+ * pnpm exec tsx evals/runner/probe.ts [--out score.json]+ *+ * Exit code is non-zero when any referenced tool is missing or any probe+ * fails, so the campaign (or CI) can gate on it directly.+ */++import { Client } from '@modelcontextprotocol/sdk/client/index.js'+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'+import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js'+import { writeFileSync } from 'node:fs'+import process from 'node:process'++import { loadBenchmark, referencedTools, type BenchmarkTask } from '../benchmark/schema'+import { formatSummary, summarize, type ProbeResult, type ToolMiss } from './results'++interface AdvertisedTool {+ name: string+ annotations?: { readOnlyHint?: boolean }+}++async function runProbe(+ client: Client,+ task: BenchmarkTask,+ advertised: Map<string, AdvertisedTool>+): Promise<ProbeResult> {+ const probe = task.probe!+ const base = { task_id: task.id, tool: probe.tool }+ const tool = advertised.get(probe.tool)+ if (!tool) {+ return { ...base, status: 'skipped_not_advertised' }+ }+ // Enforce read-only from the LIVE advertisement, not just the fixture —+ // an annotation regression must fail the probe rather than mutate data.+ if (tool.annotations?.readOnlyHint !== true) {+ return { ...base, status: 'refused_not_read_only' }+ }++ const startedAt = Date.now()+ try {+ const result = await client.callTool({ name: probe.tool, arguments: probe.args }, undefined, {+ timeout: probe.max_ms,+ })+ const latency = Date.now() - startedAt+ if (result.isError) {+ const content = Array.isArray(result.content) ? result.content : []+ const text = content+ .map((item) => (item && typeof item === 'object' && 'text' in item ? String(item.text) : ''))+ .join(' ')+ return { ...base, status: 'tool_error', latency_ms: latency, error_snippet: text.slice(0, 200) }+ }+ return { ...base, status: 'ok', latency_ms: latency }+ } catch (error) {+ const latency = Date.now() - startedAt+ const message = error instanceof Error ? error.message : String(error)+ // The SDK raises a typed timeout when RequestOptions.timeout elapses —+ // classify on that, not on wall-clock heuristics.+ const isTimeout = error instanceof McpError && error.code === ErrorCode.RequestTimeout+ return {+ ...base,+ status: isTimeout ? 'timeout' : 'transport_error',+ latency_ms: latency,+ error_snippet: message.slice(0, 200),+ }+ }+}++async function main(): Promise<void> {+ const url = process.env.LIVE_MCP_URL ?? 'http://localhost:9876'+ const token = process.env.LIVE_MCP_TOKEN+ if (!token) {+ console.error('LIVE_MCP_TOKEN is required (a personal API key for the target instance)')+ process.exit(2)+ }+ const outFlagIndex = process.argv.indexOf('--out')+ const outPath = outFlagIndex === -1 ? null : (process.argv[outFlagIndex + 1] ?? null)+ if (outFlagIndex !== -1 && outPath === null) {+ console.error('--out requires a file path')+ process.exit(2)+ }++ const benchmark = loadBenchmark()+ const transport = new StreamableHTTPClientTransport(new URL('/mcp', url), {+ requestInit: { headers: { Authorization: `Bearer ${token}` } },+ })+ const client = new Client({ name: 'mcp-eval-probe', version: '0.0.0' }, { capabilities: {} })+ await client.connect(transport)++ try {+ const listed = await client.listTools()+ const advertised = new Map<string, AdvertisedTool>(+ listed.tools.map((tool) => [tool.name, tool as AdvertisedTool])+ )++ const toolMisses: ToolMiss[] = benchmark.tasks.flatMap((task) =>+ referencedTools(task)+ .filter((tool) => !advertised.has(tool))+ .map((tool) => ({ task_id: task.id, tool }))+ )++ const probes: ProbeResult[] = []+ for (const task of benchmark.tasks.filter((candidate) => candidate.probe)) {+ probes.push(await runProbe(client, task, advertised))+ }++ const summary = summarize({+ benchmarkVersion: benchmark.version,+ tasksTotal: benchmark.tasks.length,+ toolsReferenced: new Set(benchmark.tasks.flatMap(referencedTools)).size,+ toolMisses,+ probes,+ })++ // stdout directly: the summary IS the program output (oxlint strips console.log).+ process.stdout.write(formatSummary(summary) + '\n')+ if (outPath) {+ writeFileSync(outPath, JSON.stringify(summary, null, 2))+ process.stdout.write(`wrote ${outPath}\n`)+ }+ process.exit(summary.tool_misses.length > 0 || summary.probes_failed > 0 ? 1 : 0)+ } finally {+ await client.close().catch(() => undefined)+ }+}++void main()diff --git a/services/mcp/evals/runner/results.ts b/services/mcp/evals/runner/results.tsnew file mode 100644index 000000000000..7dd15da4cd61--- /dev/null+++ b/services/mcp/evals/runner/results.ts@@ -0,0 +1,94 @@+/**+ * Pure result types + aggregation for eval runs. Kept free of I/O so the+ * scoring math is unit-testable — campaign keep/discard decisions ride on+ * these numbers.+ */++export type ProbeStatus =+ | 'ok'+ | 'tool_error' // server answered with isError: true+ | 'transport_error' // request failed or threw+ | 'timeout'+ | 'refused_not_read_only' // advertised annotations don't mark the tool read-only+ | 'skipped_not_advertised'++export interface ToolMiss {+ task_id: string+ tool: string+}++export interface ProbeResult {+ task_id: string+ tool: string+ status: ProbeStatus+ latency_ms?: number+ error_snippet?: string+}++export interface ProbeRunSummary {+ benchmark_version: number+ tasks_total: number+ tools_referenced: number+ /** Referenced tools the server did not advertise — discoverability misses. */+ tool_misses: ToolMiss[]+ probes_total: number+ probes_ok: number+ probes_failed: number+ latency_p50_ms: number | null+ latency_p95_ms: number | null+ probes: ProbeResult[]+}++export function percentile(sortedValues: number[], p: number): number | null {+ if (sortedValues.length === 0) {+ return null+ }+ const rank = Math.min(sortedValues.length - 1, Math.max(0, Math.ceil((p / 100) * sortedValues.length) - 1))+ return sortedValues[rank] ?? null+}++export function summarize(input: {+ benchmarkVersion: number+ tasksTotal: number+ toolsReferenced: number+ toolMisses: ToolMiss[]+ probes: ProbeResult[]+}): ProbeRunSummary {+ const latencies = input.probes+ .map((probe) => probe.latency_ms)+ .filter((value): value is number => typeof value === 'number')+ .sort((a, b) => a - b)+ const ok = input.probes.filter((probe) => probe.status === 'ok').length++ return {+ benchmark_version: input.benchmarkVersion,+ tasks_total: input.tasksTotal,+ tools_referenced: input.toolsReferenced,+ tool_misses: input.toolMisses,+ probes_total: input.probes.length,+ probes_ok: ok,+ probes_failed: input.probes.length - ok,+ latency_p50_ms: percentile(latencies, 50),+ latency_p95_ms: percentile(latencies, 95),+ probes: input.probes,+ }+}++export function formatSummary(summary: ProbeRunSummary): string {+ const lines = [+ `benchmark v${summary.benchmark_version}: ${summary.tasks_total} tasks, ${summary.tools_referenced} referenced tools`,+ `tool presence: ${summary.tool_misses.length === 0 ? 'all advertised' : `${summary.tool_misses.length} MISSING`}`,+ ...summary.tool_misses.map((miss) => ` MISSING ${miss.tool} (task ${miss.task_id})`),+ `probes: ${summary.probes_ok}/${summary.probes_total} ok` ++ (summary.latency_p50_ms !== null+ ? ` (p50 ${summary.latency_p50_ms}ms, p95 ${summary.latency_p95_ms}ms)`+ : ''),+ ...summary.probes+ .filter((probe) => probe.status !== 'ok')+ .map(+ (probe) =>+ ` ${probe.status.toUpperCase()} ${probe.tool} (task ${probe.task_id})${probe.error_snippet ? `: ${probe.error_snippet}` : ''}`+ ),+ ]+ return lines.join('\n')+}diff --git a/services/mcp/tests/evals/benchmark.test.ts b/services/mcp/tests/evals/benchmark.test.tsnew file mode 100644index 000000000000..8e732f9ff3a6--- /dev/null+++ b/services/mcp/tests/evals/benchmark.test.ts@@ -0,0 +1,49 @@+import { describe, expect, it } from 'vitest'++import { getToolDefinitions } from '@/tools/toolDefinitions'++import { TASK_CATEGORIES, loadBenchmark, referencedTools } from '../../evals/benchmark/schema'++describe('MCP eval benchmark fixtures', () => {+ // Loaded inside each test (not at describe scope) so a broken fixture or+ // catalog fails the owning test with a real error instead of blowing up+ // vitest's collection phase.+ it('parses against the schema with unique task ids', () => {+ const benchmark = loadBenchmark()+ const ids = benchmark.tasks.map((task) => task.id)+ expect(new Set(ids).size).toBe(ids.length)+ })++ it('only references tools that exist in the catalog', () => {+ const known = new Set(Object.keys(getToolDefinitions()))+ const unknown = loadBenchmark().tasks.flatMap((task) =>+ referencedTools(task)+ .filter((tool) => !known.has(tool))+ .map((tool) => `${task.id} → ${tool}`)+ )+ expect(unknown).toEqual([])+ })++ it('uses every declared task category', () => {+ const used = new Set(loadBenchmark().tasks.map((task) => task.category))+ const unused = TASK_CATEGORIES.filter((category) => !used.has(category))+ expect(unused).toEqual([])+ })++ it('only probes read-only tools', () => {+ const catalog = getToolDefinitions()+ const unsafe = loadBenchmark()+ .tasks.filter((task) => task.probe)+ .filter((task) => catalog[task.probe!.tool]?.annotations?.readOnlyHint !== true)+ .map((task) => `${task.id} → ${task.probe!.tool}`)+ expect(unsafe).toEqual([])+ })++ it('probes exercise a tool the task expects', () => {+ const mismatched = loadBenchmark()+ .tasks.filter((task) => task.probe)+ .filter((task) => ![...task.expected_tools, ...task.acceptable_tools].includes(task.probe!.tool))+ .map((task) => task.id)+ expect(mismatched).toEqual([])+ })+})diff --git a/services/mcp/tests/evals/results.test.ts b/services/mcp/tests/evals/results.test.tsnew file mode 100644index 000000000000..23136d0aa0a2--- /dev/null+++ b/services/mcp/tests/evals/results.test.ts@@ -0,0 +1,40 @@+import { describe, expect, it } from 'vitest'++import { percentile, summarize, type ProbeResult } from '../../evals/runner/results'++describe('eval result aggregation', () => {+ it.each([+ { values: [], p: 95, expected: null },+ { values: [100], p: 50, expected: 100 },+ { values: [100], p: 95, expected: 100 },+ { values: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], p: 50, expected: 5 },+ { values: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], p: 95, expected: 10 },+ { values: [1, 2, 3, 4], p: 95, expected: 4 },+ ])('percentile(p$p) of $values is $expected', ({ values, p, expected }) => {+ expect(percentile(values, p)).toBe(expected)+ })++ it('counts every non-ok status as failed and keeps latency math to ok+errored calls only', () => {+ const probes: ProbeResult[] = [+ { task_id: 'a', tool: 't1', status: 'ok', latency_ms: 100 },+ { task_id: 'b', tool: 't2', status: 'tool_error', latency_ms: 300 },+ { task_id: 'c', tool: 't3', status: 'refused_not_read_only' },+ { task_id: 'd', tool: 't4', status: 'skipped_not_advertised' },+ ]++ const summary = summarize({+ benchmarkVersion: 0,+ tasksTotal: 4,+ toolsReferenced: 4,+ toolMisses: [{ task_id: 'd', tool: 't4' }],+ probes,+ })++ expect(summary.probes_total).toBe(4)+ expect(summary.probes_ok).toBe(1)+ expect(summary.probes_failed).toBe(3)+ expect(summary.latency_p50_ms).toBe(100)+ expect(summary.latency_p95_ms).toBe(300)+ expect(summary.tool_misses).toHaveLength(1)+ })+})