: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-analytics): agent eval runner for any MCP server (#110382)
Lucas Faria2d0d7fce8e07
diff --git a/products/mcp_analytics/backend/agent_evals/__init__.py b/products/mcp_analytics/backend/agent_evals/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/mcp_analytics/backend/agent_evals/agent_loop.py b/products/mcp_analytics/backend/agent_evals/agent_loop.pynew file mode 100644index 000000000000..4f5c1d50cfc1--- /dev/null+++ b/products/mcp_analytics/backend/agent_evals/agent_loop.py@@ -0,0 +1,150 @@+import asyncio+from collections.abc import Awaitable, Callable+from typing import Literal++import httpx+import anthropic+from anthropic.types import Message, MessageParam, ToolResultBlockParam, ToolUseBlock, Usage++from posthog.dataclasses import frozen++from products.mcp_analytics.backend.agent_evals.scenarios import Scenario++TrialOutcome = Literal[+ "answered",+ "turn_limit", # still calling tools after max_turns model responses+ "truncated", # a response hit max_tokens+ "refused",+ "model_error", # the API call failed, or returned a stop reason the loop cannot continue from+ "mcp_error", # the MCP session could not be opened+]++_STOP_REASON_OUTCOMES: dict[str, TrialOutcome] = {+ "end_turn": "answered",+ "stop_sequence": "answered",+ "max_tokens": "truncated",+ "refusal": "refused",+}+++@frozen+class ToolCallRecord:+ name: str+ input: object+ is_error: bool+ # Kept whole, because a judge that reads a shortened result grades a different trial.+ result_text: str+ latency_ms: int+++@frozen+class TrialUsage:+ input_tokens: int = 0+ output_tokens: int = 0+ cache_read_input_tokens: int = 0+ cache_creation_input_tokens: int = 0++ def add(self, usage: Usage) -> "TrialUsage":+ return TrialUsage(+ input_tokens=self.input_tokens + usage.input_tokens,+ output_tokens=self.output_tokens + usage.output_tokens,+ cache_read_input_tokens=self.cache_read_input_tokens + (usage.cache_read_input_tokens or 0),+ cache_creation_input_tokens=self.cache_creation_input_tokens + (usage.cache_creation_input_tokens or 0),+ )+++@frozen+class AgentTrial:+ scenario_id: str+ trial: int+ outcome: TrialOutcome+ final_text: str+ tool_calls: tuple[ToolCallRecord, ...]+ turns: int+ usage: TrialUsage+ duration_ms: int+ error: str | None = None+++@frozen+class ToolOutcome:+ text: str+ is_error: bool+++@frozen+class TrialDeps:+ create_message: Callable[[list[MessageParam]], Awaitable[Message]]+ call_tool: Callable[[str, object], Awaitable[ToolOutcome]]+ now_ms: Callable[[], int]+++async def run_trial(scenario: Scenario, trial: int, max_turns: int, deps: TrialDeps) -> AgentTrial:+ started_at = deps.now_ms()+ messages: list[MessageParam] = [{"role": "user", "content": scenario.intent}]+ tool_calls: list[ToolCallRecord] = []+ usage = TrialUsage()+ turns = 0+ last_text = ""++ def finish(outcome: TrialOutcome, error: str | None = None) -> AgentTrial:+ return AgentTrial(+ scenario_id=scenario.id,+ trial=trial,+ outcome=outcome,+ final_text=last_text,+ tool_calls=tuple(tool_calls),+ turns=turns,+ usage=usage,+ duration_ms=deps.now_ms() - started_at,+ error=error,+ )++ while True:+ try:+ response = await deps.create_message(messages)+ # A dropped response stream surfaces as a raw httpx error, not an APIError.+ except (anthropic.APIError, httpx.HTTPError) as error:+ return finish("model_error", str(error))+ turns += 1+ usage = usage.add(response.usage)+ last_text = "\n".join(block.text for block in response.content if block.type == "text")+ # Append the content unchanged, so the cached prefix stays byte-identical.+ messages.append({"role": "assistant", "content": response.content})++ if response.stop_reason != "tool_use":+ outcome = _STOP_REASON_OUTCOMES.get(response.stop_reason or "")+ return (+ finish(outcome) if outcome else finish("model_error", f"unexpected stop_reason {response.stop_reason}")+ )++ if turns >= max_turns:+ # The model would never see these results, so running the tools only changes server state.+ return finish("turn_limit")++ tool_uses = [block for block in response.content if isinstance(block, ToolUseBlock)]+ records = await asyncio.gather(*(_call_recorded(deps, use) for use in tool_uses))+ tool_calls.extend(records)+ # Every result goes back in one user message. Split messages teach the model to stop calling tools in parallel.+ results: list[ToolResultBlockParam] = [+ {"type": "tool_result", "tool_use_id": use.id, "content": record.result_text, "is_error": record.is_error}+ for use, record in zip(tool_uses, records, strict=True)+ ]+ messages.append({"role": "user", "content": results})+++async def _call_recorded(deps: TrialDeps, use: ToolUseBlock) -> ToolCallRecord:+ started_at = deps.now_ms()+ try:+ outcome = await deps.call_tool(use.name, use.input)+ except Exception as error:+ # A transport failure is something the agent sees and can recover from, so it is+ # fed back as an error result rather than ending the trial.+ outcome = ToolOutcome(text=str(error), is_error=True)+ return ToolCallRecord(+ name=use.name,+ input=use.input,+ is_error=outcome.is_error,+ result_text=outcome.text,+ latency_ms=deps.now_ms() - started_at,+ )diff --git a/products/mcp_analytics/backend/agent_evals/runner.py b/products/mcp_analytics/backend/agent_evals/runner.pynew file mode 100644index 000000000000..bd65ac3c4f4a--- /dev/null+++ b/products/mcp_analytics/backend/agent_evals/runner.py@@ -0,0 +1,279 @@+import re+import json+import time+import asyncio+import logging+import dataclasses+from collections.abc import AsyncIterator, Iterator+from contextlib import asynccontextmanager, contextmanager+from datetime import UTC, datetime, timedelta+from typing import Literal+from urllib.parse import urlsplit++import anthropic+from anthropic.types import Message, MessageParam, TextBlockParam, ToolParam+from mcp import ClientSession+from mcp.client.streamable_http import streamablehttp_client+from mcp.types import AudioContent, CallToolResult, ImageContent, Implementation, TextContent, Tool++from posthog.dataclasses import frozen++from products.mcp_analytics.backend.agent_evals.agent_loop import (+ AgentTrial,+ ToolOutcome,+ TrialDeps,+ TrialUsage,+ run_trial,+)+from products.mcp_analytics.backend.agent_evals.scenarios import Scenario++# The levels the pinned anthropic SDK types. It predates `xhigh`.+Effort = Literal["low", "medium", "high", "max"]++SYSTEM_PROMPT = (+ "You are an AI agent connected to an MCP server. "+ "Use the server's tools to complete the user's request, then reply with the answer."+)+MAX_TOKENS = 16_000+TOOL_CALL_TIMEOUT = timedelta(seconds=60)+CLIENT_INFO = Implementation(name="mcp-eval-agent", version="0.0.0")+++@frozen+class RunConfig:+ url: str+ headers: dict[str, str] = dataclasses.field(repr=False)+ scenarios: tuple[Scenario, ...]+ trials: int+ concurrency: int+ model: str+ effort: Effort | None+ max_turns: int+++@frozen+class AgentRunReport:+ # The origin only: a path can carry a capability token, and the report is shared.+ server_origin: str+ # Names only, because any header can carry a credential on a server we don't know.+ header_names: tuple[str, ...]+ tool_names: tuple[str, ...]+ # The scenarios as they ran, so a later grader never reads criteria that were edited afterwards.+ scenarios: tuple[Scenario, ...]+ model: str+ effort: Effort | None+ system_prompt: str+ trials_per_scenario: int+ max_turns: int+ max_tokens: int+ started_at: str+ finished_at: str+ trials: tuple[AgentTrial, ...]++ def to_json(self) -> str:+ return json.dumps(dataclasses.asdict(self), indent=2, default=lambda scenario: scenario.model_dump())+++async def run_agent_evals(config: RunConfig, client: anthropic.AsyncAnthropic) -> AgentRunReport:+ started_at = _now_iso()+ async with _mcp_session(config) as (catalog, server_instructions):+ tools = await _list_all_tools(catalog)+ # MCP clients pass the server's instructions to the model, so the eval agent gets them too.+ system_prompt = f"{SYSTEM_PROMPT}\n\n{server_instructions}" if server_instructions else SYSTEM_PROMPT+ # A breakpoint on the system block caches the tools and system prompt, which every scenario+ # shares. The top-level breakpoint only covers one conversation, because it lands on the latest+ # message and each scenario starts from a different intent.+ system: list[TextBlockParam] = [{"type": "text", "text": system_prompt, "cache_control": {"type": "ephemeral"}}]+ tool_params: list[ToolParam] = [+ {"name": tool.name, "description": tool.description or "", "input_schema": tool.inputSchema} for tool in tools+ ]+ slots = asyncio.Semaphore(config.concurrency)++ async def bounded(scenario: Scenario, trial: int) -> AgentTrial:+ async with slots:+ return await _run_scenario(config, client, system, tool_params, scenario, trial)++ trials: list[AgentTrial] = []+ # Rounds run in sequence and scenarios run concurrently inside a round. Scenarios that+ # change server state share it, so they can race each other and leave state for the next round.+ for trial in range(1, config.trials + 1):+ trials.extend(await asyncio.gather(*(bounded(scenario, trial) for scenario in config.scenarios)))++ return AgentRunReport(+ server_origin=server_origin(config.url),+ header_names=tuple(config.headers),+ tool_names=tuple(tool.name for tool in tools),+ scenarios=config.scenarios,+ model=config.model,+ effort=config.effort,+ system_prompt=system_prompt,+ trials_per_scenario=config.trials,+ max_turns=config.max_turns,+ max_tokens=MAX_TOKENS,+ started_at=started_at,+ finished_at=_now_iso(),+ trials=tuple(trials),+ )+++async def _run_scenario(+ config: RunConfig,+ client: anthropic.AsyncAnthropic,+ system: list[TextBlockParam],+ tools: list[ToolParam],+ scenario: Scenario,+ trial: int,+) -> AgentTrial:+ async def create_message(messages: list[MessageParam]) -> Message:+ # Streaming, because the SDK refuses MAX_TOKENS without it for models with a lower non-streaming cap.+ async with client.messages.stream(+ model=config.model,+ max_tokens=MAX_TOKENS,+ system=system,+ tools=tools,+ messages=messages,+ # Omitted unless chosen, because models without effort support reject the field.+ output_config={"effort": config.effort} if config.effort else anthropic.omit,+ extra_body={"cache_control": {"type": "ephemeral"}},+ ) as stream:+ return await stream.get_final_message()++ finished: AgentTrial | None = None+ try:+ # A session per trial, so state a server keeps per session cannot leak between trials.+ async with _mcp_session(config) as (session, _):+ # MCP clients list tools in each session; the SDK validates tool results against that list.+ await _list_all_tools(session)++ async def call_tool(name: str, tool_input: object) -> ToolOutcome:+ if not isinstance(tool_input, dict):+ return ToolOutcome(text="Tool input must be a JSON object.", is_error=True)+ try:+ result = await session.call_tool(name, tool_input, read_timeout_seconds=TOOL_CALL_TIMEOUT)+ except Exception as error:+ return ToolOutcome(text=describe_failure(error, config), is_error=True)+ return ToolOutcome(text=tool_result_text(result), is_error=bool(result.isError))++ deps = TrialDeps(create_message=create_message, call_tool=call_tool, now_ms=_now_ms)+ finished = await run_trial(scenario, trial, config.max_turns, deps)+ except Exception as error:+ if finished is None:+ return AgentTrial(+ scenario_id=scenario.id,+ trial=trial,+ outcome="mcp_error",+ final_text="",+ tool_calls=(),+ turns=0,+ usage=TrialUsage(),+ duration_ms=0,+ error=describe_failure(error, config),+ )+ assert finished is not None+ return finished+++def describe_failure(error: Exception, config: RunConfig) -> str:+ # HTTP errors quote the request URL in their own normalized form, and a rejected header's value,+ # so every URL is cut to its origin rather than matched against the configured one.+ text = _URL.sub(lambda match: server_origin(match.group(0)), _describe(error))+ for value in config.headers.values():+ if value:+ text = text.replace(value, "[redacted]")+ return text+++def _describe(error: Exception) -> str:+ # anyio task groups wrap the transport's failure, and the group's own message names none of it.+ if isinstance(error, BaseExceptionGroup):+ return "; ".join(+ _describe(inner) if isinstance(inner, Exception) else repr(inner) for inner in error.exceptions+ )+ return str(error) or type(error).__name__+++@asynccontextmanager+async def _mcp_session(config: RunConfig) -> AsyncIterator[tuple[ClientSession, str | None]]:+ # Bounds every transport request, including the DELETE that ends the session on close.+ async with streamablehttp_client(+ config.url, headers=config.headers, timeout=TOOL_CALL_TIMEOUT, sse_read_timeout=TOOL_CALL_TIMEOUT+ ) as (read, write, _):+ # The timeout bounds a server that keeps the stream open but never answers initialize or list_tools.+ async with ClientSession(+ read, write, client_info=CLIENT_INFO, read_timeout_seconds=TOOL_CALL_TIMEOUT+ ) as session:+ initialized = await session.initialize()+ yield session, initialized.instructions+++async def _list_all_tools(session: ClientSession) -> list[Tool]:+ tools: list[Tool] = []+ cursor: str | None = None+ while True:+ page = await session.list_tools(cursor=cursor)+ tools.extend(page.tools)+ cursor = page.nextCursor+ if not cursor:+ return tools+++def tool_result_text(result: CallToolResult) -> str:+ parts: list[str] = []+ for item in result.content:+ match item:+ case TextContent():+ parts.append(item.text)+ case ImageContent() | AudioContent():+ parts.append(f"[{item.type} {item.mimeType}, {len(item.data)} base64 characters]")+ case _:+ parts.append(item.model_dump_json())+ if not parts and result.structuredContent:+ parts.append(json.dumps(result.structuredContent))+ return "\n".join(parts)+++def format_run_summary(report: AgentRunReport) -> str:+ by_scenario: dict[str, list[AgentTrial]] = {}+ for trial in report.trials:+ by_scenario.setdefault(trial.scenario_id, []).append(trial)+ answered = sum(1 for trial in report.trials if trial.outcome == "answered")+ lines = [+ f"agent run on {report.server_origin}: {report.model} ({report.effort or 'default effort'}), "+ f"{len(by_scenario)} scenarios x {report.trials_per_scenario} trials",+ f"answered {answered}/{len(report.trials)}",+ ]+ for scenario_id, trials in by_scenario.items():+ tool_errors = sum(1 for trial in trials for call in trial.tool_calls if call.is_error)+ suffix = f" ({tool_errors} tool errors)" if tool_errors else ""+ lines.append(f" {scenario_id}: {' '.join(trial.outcome for trial in trials)}{suffix}")+ return "\n".join(lines)+++@contextmanager+def quiet_transport_logs() -> Iterator[None]:+ """The MCP SDK and httpx log request URLs and tracebacks; the report already records every failure."""+ loggers = [logging.getLogger(name) for name in ("mcp", "httpx", "httpcore")]+ levels = [logger.level for logger in loggers]+ for logger in loggers:+ logger.setLevel(logging.CRITICAL + 1)+ try:+ yield+ finally:+ for logger, level in zip(loggers, levels, strict=True):+ logger.setLevel(level)+++_URL = re.compile(r"https?://[^\s'\"<>]+", re.IGNORECASE)+++def server_origin(url: str) -> str:+ parts = urlsplit(url)+ return f"{parts.scheme}://{parts.netloc.rpartition('@')[2]}"+++def _now_ms() -> int:+ return time.monotonic_ns() // 1_000_000+++def _now_iso() -> str:+ return datetime.now(UTC).isoformat()diff --git a/products/mcp_analytics/backend/agent_evals/scenarios.py b/products/mcp_analytics/backend/agent_evals/scenarios.pynew file mode 100644index 000000000000..32cb19eb040e--- /dev/null+++ b/products/mcp_analytics/backend/agent_evals/scenarios.py@@ -0,0 +1,35 @@+from pathlib import Path+from typing import Literal++import yaml+from pydantic import BaseModel, ConfigDict, Field, model_validator+++class Scenario(BaseModel):+ """A request an agent should be able to complete against an MCP server."""++ model_config = ConfigDict(frozen=True, extra="forbid")++ id: str = Field(pattern=r"^[a-z0-9][a-z0-9-]*$", max_length=64)+ intent: str = Field(min_length=10)+ success_criteria: str = Field(min_length=10)+ expected_tools: tuple[str, ...] = ()+++class ScenarioFile(BaseModel):+ model_config = ConfigDict(frozen=True, extra="forbid")++ version: Literal[1]+ scenarios: tuple[Scenario, ...] = Field(min_length=1)++ @model_validator(mode="after")+ def _unique_ids(self) -> "ScenarioFile":+ ids = [scenario.id for scenario in self.scenarios]+ duplicates = sorted({scenario_id for scenario_id in ids if ids.count(scenario_id) > 1})+ if duplicates:+ raise ValueError(f"duplicate scenario ids: {', '.join(duplicates)}")+ return self+++def load_scenarios(path: Path) -> ScenarioFile:+ return ScenarioFile.model_validate(yaml.safe_load(path.read_text()))diff --git a/products/mcp_analytics/backend/management/commands/run_mcp_evals.py b/products/mcp_analytics/backend/management/commands/run_mcp_evals.pynew file mode 100644index 000000000000..2b67a48784de--- /dev/null+++ b/products/mcp_analytics/backend/management/commands/run_mcp_evals.py@@ -0,0 +1,126 @@+"""Run agent eval scenarios against a live MCP server and write every trial to a JSON report.++Each scenario's intent goes through a Claude tool-use loop against the server, ``--trials``+times. The report keeps each trial's outcome, tool calls with full results, tokens and latency.+Nothing here grades the trials.++The server's bearer token comes from ``MCP_EVAL_SERVER_TOKEN`` so it never appears in the+process list. An ``Authorization`` header passed with ``--header`` takes precedence. Against+PostHog's own server, pin the project with ``--header 'x-posthog-project-id: <id>'``, because+PostHog keeps the active project per token, so one trial's project switch moves the others.+"""++import os+import re+import asyncio+from pathlib import Path+from typing import cast, get_args+from urllib.parse import urlsplit++from django.conf import settings+from django.core.management.base import BaseCommand, CommandError, CommandParser++import anthropic++from products.mcp_analytics.backend.agent_evals.runner import (+ Effort,+ RunConfig,+ describe_failure,+ format_run_summary,+ quiet_transport_logs,+ run_agent_evals,+)+from products.mcp_analytics.backend.agent_evals.scenarios import load_scenarios++TOKEN_ENV = "MCP_EVAL_SERVER_TOKEN"+++class Command(BaseCommand):+ help = "Run agent eval scenarios against a live MCP server and write a JSON report."++ def add_arguments(self, parser: CommandParser) -> None:+ parser.add_argument("--url", required=True, help="The MCP endpoint, for example http://localhost:8787/mcp.")+ parser.add_argument("--scenarios", type=Path, required=True, help="YAML file of scenarios to run.")+ parser.add_argument("--out", type=Path, required=True, help="Where to write the JSON report.")+ parser.add_argument(+ "--header", action="append", default=[], help="Extra request header as 'Name: value'. Repeatable."+ )+ parser.add_argument("--only", action="append", default=[], help="Run only this scenario id. Repeatable.")+ parser.add_argument("--trials", type=int, default=3)+ parser.add_argument("--concurrency", type=int, default=4)+ parser.add_argument("--model", default="claude-opus-5-5")+ parser.add_argument(+ "--effort", choices=get_args(Effort), help="Omitted unless set; the model's default applies."+ )+ parser.add_argument("--max-turns", type=int, default=20)++ def handle(self, *args: object, **options: object) -> None:+ if not settings.ANTHROPIC_API_KEY:+ raise CommandError("ANTHROPIC_API_KEY is not set")+ for name in ("trials", "concurrency", "max_turns"):+ if cast(int, options[name]) <= 0:+ raise CommandError(f"--{name.replace('_', '-')} must be a positive integer")++ scenario_file = load_scenarios(cast(Path, options["scenarios"]))+ only = cast(list[str], options["only"])+ unknown = sorted(set(only) - {scenario.id for scenario in scenario_file.scenarios})+ if unknown:+ raise CommandError(f"unknown scenario ids: {', '.join(unknown)}")+ scenarios = tuple(scenario for scenario in scenario_file.scenarios if not only or scenario.id in only)++ config = RunConfig(+ url=_url(cast(str, options["url"])),+ headers=_headers(cast(list[str], options["header"]), os.environ.get(TOKEN_ENV)),+ scenarios=scenarios,+ trials=cast(int, options["trials"]),+ concurrency=cast(int, options["concurrency"]),+ model=cast(str, options["model"]),+ effort=cast(Effort | None, options["effort"]),+ max_turns=cast(int, options["max_turns"]),+ )+ try:+ with quiet_transport_logs():+ report = asyncio.run(+ run_agent_evals(config, anthropic.AsyncAnthropic(api_key=settings.ANTHROPIC_API_KEY))+ )+ except Exception as unreachable:+ # Only the catalog session raises here; every trial failure stays inside its trial.+ raise CommandError(f"could not list the server's tools: {describe_failure(unreachable, config)}") from None++ out = cast(Path, options["out"])+ out.parent.mkdir(parents=True, exist_ok=True)+ out.write_text(report.to_json())+ self.stdout.write(f"{format_run_summary(report)}\nwrote {out}")+++def _url(raw: str) -> str:+ parts = urlsplit(raw)+ if parts.scheme not in ("http", "https") or not parts.hostname:+ raise CommandError("--url must be an http or https URL")+ if parts.username or parts.password or parts.query or parts.fragment:+ # Credentials travel in a header, which never reaches the report or the logs.+ raise CommandError(f"--url must have no credentials or query; use {TOKEN_ENV} or --header")+ return raw+++def _headers(raw_headers: list[str], token: str | None) -> dict[str, str]:+ headers: dict[str, str] = {}+ for raw in raw_headers:+ name, separator, value = raw.partition(":")+ if not separator or not name.strip():+ raise CommandError("--header must look like 'Name: value'")+ headers[name.strip()] = _header_value(name.strip(), value)+ if token and not any(name.lower() == "authorization" for name in headers):+ headers["Authorization"] = f"Bearer {_header_value(TOKEN_ENV, token)}"+ return headers+++def _header_value(source: str, value: str) -> str:+ # Checked here so the HTTP client never rejects it, because its error would quote the value.+ value = value.strip()+ if _CONTROL_CHARACTERS.search(value):+ raise CommandError(f"{source} contains a control character")+ return value+++_CONTROL_CHARACTERS = re.compile(r"[\x00-\x1f\x7f]")diff --git a/products/mcp_analytics/backend/tests/test_agent_evals_loop.py b/products/mcp_analytics/backend/tests/test_agent_evals_loop.pynew file mode 100644index 000000000000..8ec439a07d24--- /dev/null+++ b/products/mcp_analytics/backend/tests/test_agent_evals_loop.py@@ -0,0 +1,159 @@+import asyncio+from collections.abc import Awaitable, Callable++from django.test import SimpleTestCase++import httpx+import anthropic+from anthropic.types import ContentBlock, Message, MessageParam, StopReason, TextBlock, ToolUseBlock, Usage+from parameterized import parameterized++from products.mcp_analytics.backend.agent_evals.agent_loop import AgentTrial, ToolOutcome, TrialDeps, run_trial+from products.mcp_analytics.backend.agent_evals.scenarios import Scenario++SCENARIO = Scenario(+ id="flags-list-active",+ intent="List all our active feature flags.",+ success_criteria="Returns the active flags by key.",+)+++def _message(stop_reason: StopReason, content: list[ContentBlock]) -> Message:+ return Message.model_construct(+ id="msg",+ type="message",+ role="assistant",+ model="claude-opus-5-5",+ content=content,+ stop_reason=stop_reason,+ stop_sequence=None,+ usage=Usage(input_tokens=10, output_tokens=5, cache_read_input_tokens=3),+ )+++def _text(value: str) -> TextBlock:+ return TextBlock(type="text", text=value)+++def _tool_use(use_id: str, name: str) -> ToolUseBlock:+ return ToolUseBlock(type="tool_use", id=use_id, name=name, input={})+++def _api_error() -> anthropic.APIError:+ return anthropic.APIConnectionError(request=httpx.Request("POST", "https://api.anthropic.com/v1/messages"))+++class _Scripted:+ def __init__(self, responses: list[Message | Exception]) -> None:+ self.responses = responses+ self.sent: list[list[MessageParam]] = []++ async def create_message(self, messages: list[MessageParam]) -> Message:+ self.sent.append(list(messages))+ response = self.responses[min(len(self.sent), len(self.responses)) - 1]+ if isinstance(response, Exception):+ raise response+ return response+++def _run(script: _Scripted, call_tool: Callable[[str, object], Awaitable[ToolOutcome]], max_turns: int) -> AgentTrial:+ deps = TrialDeps(create_message=script.create_message, call_tool=call_tool, now_ms=lambda: 0)+ return asyncio.run(run_trial(SCENARIO, 1, max_turns, deps))+++async def _ok_tool(name: str, tool_input: object) -> ToolOutcome:+ return ToolOutcome(text="[]", is_error=False)+++class TestAgentTrialLoop(SimpleTestCase):+ @parameterized.expand(+ [+ (+ "a_final_reply_after_a_tool_call_is_answered",+ [+ _message("tool_use", [_tool_use("t1", "feature-flag-get-all")]),+ _message("end_turn", [_text("Two flags.")]),+ ],+ "answered",+ 2,+ "Two flags.",+ ),+ (+ "a_model_that_never_stops_calling_tools_hits_the_turn_limit",+ [_message("tool_use", [_text("Checking."), _tool_use("t1", "feature-flag-get-all")])],+ "turn_limit",+ 3,+ "Checking.",+ ),+ ("an_api_failure_is_a_model_error_not_an_answer", [_api_error()], "model_error", 0, ""),+ ("a_dropped_response_stream_is_a_model_error", [httpx.ReadError("stream closed")], "model_error", 0, ""),+ ("a_refusal_is_recorded_as_refused", [_message("refusal", [])], "refused", 1, ""),+ (+ "a_cut_off_response_is_truncated",+ [_message("max_tokens", [_text("Partial")])],+ "truncated",+ 1,+ "Partial",+ ),+ (+ "a_stop_reason_the_loop_cannot_continue_from_is_a_model_error",+ [_message("pause_turn", [_text("Paused")])],+ "model_error",+ 1,+ "Paused",+ ),+ ]+ )+ def test_trial_outcome(+ self,+ _name: str,+ responses: list[Message | Exception],+ outcome: str,+ turns: int,+ final_text: str,+ ) -> None:+ trial = _run(_Scripted(responses), _ok_tool, max_turns=3)++ assert (trial.outcome, trial.turns, trial.final_text) == (outcome, turns, final_text)+ assert (trial.usage.input_tokens, trial.usage.cache_read_input_tokens) == (10 * turns, 3 * turns)++ def test_parallel_tool_results_return_in_one_message_and_a_thrown_call_becomes_an_error(self) -> None:+ async def call_tool(name: str, tool_input: object) -> ToolOutcome:+ if name == "execute-sql":+ raise ConnectionError("socket hang up")+ return ToolOutcome(text='[{"key":"beta"}]', is_error=False)++ script = _Scripted(+ [+ _message("tool_use", [_tool_use("t1", "feature-flag-get-all"), _tool_use("t2", "execute-sql")]),+ _message("end_turn", [_text("Done.")]),+ ]+ )++ trial = _run(script, call_tool, max_turns=5)++ assert trial.outcome == "answered"+ assert [(call.name, call.is_error, call.result_text) for call in trial.tool_calls] == [+ ("feature-flag-get-all", False, '[{"key":"beta"}]'),+ ("execute-sql", True, "socket hang up"),+ ]+ assert script.sent[1][-1] == {+ "role": "user",+ "content": [+ {"type": "tool_result", "tool_use_id": "t1", "content": '[{"key":"beta"}]', "is_error": False},+ {"type": "tool_result", "tool_use_id": "t2", "content": "socket hang up", "is_error": True},+ ],+ }++ def test_the_turn_limit_stops_before_running_tools_the_model_would_never_see(self) -> None:+ called: list[str] = []++ async def call_tool(name: str, tool_input: object) -> ToolOutcome:+ called.append(name)+ return ToolOutcome(text="[]", is_error=False)++ trial = _run(+ _Scripted([_message("tool_use", [_tool_use("t1", "feature-flag-get-all")])]), call_tool, max_turns=3+ )++ assert (trial.outcome, trial.turns, len(called), len(trial.tool_calls)) == ("turn_limit", 3, 2, 2)diff --git a/products/mcp_analytics/backend/tests/test_agent_evals_runner.py b/products/mcp_analytics/backend/tests/test_agent_evals_runner.pynew file mode 100644index 000000000000..2bad77fbb370--- /dev/null+++ b/products/mcp_analytics/backend/tests/test_agent_evals_runner.py@@ -0,0 +1,199 @@+import io+import asyncio+import logging+import dataclasses+from collections.abc import AsyncIterator+from contextlib import asynccontextmanager++from unittest.mock import patch++from django.core.management.base import CommandError+from django.test import SimpleTestCase++from mcp.types import CallToolResult, ImageContent, ListToolsResult, TextContent+from parameterized import parameterized++from products.mcp_analytics.backend.agent_evals import runner+from products.mcp_analytics.backend.agent_evals.agent_loop import AgentTrial, TrialUsage+from products.mcp_analytics.backend.agent_evals.runner import RunConfig, tool_result_text+from products.mcp_analytics.backend.agent_evals.scenarios import Scenario+from products.mcp_analytics.backend.management.commands.run_mcp_evals import _headers, _url++SCENARIO = Scenario(+ id="flags-list-active", intent="List all our active feature flags.", success_criteria="Returns the flags."+)+CONFIG = RunConfig(+ url="http://localhost:8787/mcp/cap-secret",+ headers={},+ scenarios=(SCENARIO,),+ trials=1,+ concurrency=1,+ model="claude-opus-5-5",+ effort="medium",+ max_turns=3,+)+ANSWERED = AgentTrial(+ scenario_id=SCENARIO.id,+ trial=1,+ outcome="answered",+ final_text="Two flags.",+ tool_calls=(),+ turns=1,+ usage=TrialUsage(),+ duration_ms=5,+)+++class TestRunnerBoundaries(SimpleTestCase):+ @parameterized.expand(+ [+ ("as_configured", "401 for https://mcp.example.com/mcp/cap-secret", "401 for https://mcp.example.com"),+ (+ "quoted_differently",+ "401 for 'HTTPS://MCP.Example.com:443/mcp/cap%2Dsecret'",+ "401 for 'https://MCP.Example.com:443'",+ ),+ ("header_value", "rejected X-Api-Key k-123", "rejected X-Api-Key [redacted]"),+ ]+ )+ def test_recorded_failures_carry_neither_a_path_nor_a_header_value(+ self, _name: str, message: str, expected: str+ ) -> None:+ config = dataclasses.replace(+ CONFIG, url="https://mcp.example.com/mcp/cap-secret", headers={"X-Api-Key": "k-123"}+ )++ assert runner.describe_failure(ConnectionError(message), config) == expected++ def test_transport_logs_stay_quiet_during_a_run(self) -> None:+ stream = io.StringIO()+ handler = logging.StreamHandler(stream)+ logging.getLogger().addHandler(handler)+ self.addCleanup(logging.getLogger().removeHandler, handler)++ with runner.quiet_transport_logs():+ logging.getLogger("mcp.client.streamable_http").error("POST https://mcp.example.com/mcp/cap-secret failed")++ assert stream.getvalue() == ""+ assert logging.getLogger("mcp").level == logging.NOTSET++ @parameterized.expand(+ [+ (+ "userinfo_and_path_are_dropped",+ "https://user:[email protected]/mcp/cap-secret",+ "https://mcp.example.com",+ ),+ ("the_port_is_kept", "http://localhost:8787/mcp", "http://localhost:8787"),+ ("ipv6_keeps_its_brackets", "http://[::1]:8787/mcp", "http://[::1]:8787"),+ ]+ )+ def test_the_report_records_only_the_server_origin(self, _name: str, url: str, expected: str) -> None:+ assert runner.server_origin(url) == expected++ @parameterized.expand(+ [+ ("query", "https://mcp.example.com/mcp?token=abc"),+ ("userinfo", "https://u:[email protected]/mcp"),+ ("fragment", "https://mcp.example.com/mcp#k"),+ ("not_http", "ftp://mcp.example.com/mcp"),+ ]+ )+ def test_a_url_that_could_carry_credentials_is_rejected(self, _name: str, url: str) -> None:+ with self.assertRaises(CommandError):+ _url(url)++ @parameterized.expand(+ [+ ("the_token_becomes_a_bearer_header", [], "tok", {"Authorization": "Bearer tok"}),+ ("an_explicit_authorization_wins", ["authorization: Basic x"], "tok", {"authorization": "Basic x"}),+ ("values_are_trimmed", ["x-posthog-project-id: 2 "], None, {"x-posthog-project-id": "2"}),+ ]+ )+ def test_headers(self, _name: str, raw: list[str], token: str | None, expected: dict[str, str]) -> None:+ assert _headers(raw, token) == expected++ @parameterized.expand(+ [("no_separator", "x-posthog-project-id"), ("empty_name", ": 2"), ("control_character", "X-Api-Key: a\rb")]+ )+ def test_a_malformed_header_is_rejected(self, _name: str, raw: str) -> None:+ with self.assertRaises(CommandError):+ _headers([raw], None)++ @parameterized.expand(+ [+ (+ "text_parts_join_by_line",+ CallToolResult(content=[TextContent(type="text", text="a"), TextContent(type="text", text="b")]),+ "a\nb",+ ),+ (+ "media_is_described_not_inlined",+ CallToolResult(content=[ImageContent(type="image", data="aGk=", mimeType="image/png")]),+ "[image image/png, 4 base64 characters]",+ ),+ (+ "structured_content_fills_an_empty_result",+ CallToolResult(content=[], structuredContent={"count": 2}),+ '{"count": 2}',+ ),+ ]+ )+ def test_tool_result_text(self, _name: str, result: CallToolResult, expected: str) -> None:+ assert tool_result_text(result) == expected+++class _EmptyCatalog:+ async def list_tools(self, cursor: str | None = None) -> ListToolsResult:+ return ListToolsResult(tools=[])+++def _session(fail_on: str):+ @asynccontextmanager+ async def session(config: RunConfig) -> AsyncIterator[tuple[_EmptyCatalog, None]]:+ if fail_on == "open":+ raise ExceptionGroup(+ "unhandled errors in a TaskGroup", [ConnectionError(f"connection refused: {config.url}")]+ )+ yield _EmptyCatalog(), None+ if fail_on == "close":+ raise ConnectionError("stream closed")++ return session+++class TestTrialFailureBoundary(SimpleTestCase):+ @parameterized.expand(+ [+ ("a_teardown_failure_keeps_the_finished_trial", "close", ("answered", None)),+ (+ "an_open_failure_is_an_mcp_error_with_the_real_cause_and_no_token",+ "open",+ ("mcp_error", "connection refused: http://localhost:8787"),+ ),+ ]+ )+ def test_a_session_failure_stays_inside_its_trial(self, _name: str, fail_on: str, expected: tuple) -> None:+ async def fake_run_trial(*args: object) -> AgentTrial:+ return ANSWERED++ with patch.object(runner, "_mcp_session", _session(fail_on)), patch.object(runner, "run_trial", fake_run_trial):+ trial = asyncio.run(runner._run_scenario(CONFIG, None, [], [], SCENARIO, 1)) # type: ignore[arg-type]++ assert (trial.outcome, trial.error) == expected++ def test_session_setup_and_teardown_share_the_tool_call_timeout(self) -> None:+ seen: dict[str, object] = {}++ @asynccontextmanager+ async def transport(url: str, **kwargs: object) -> AsyncIterator[None]:+ seen.update(kwargs)+ if url:+ raise ConnectionError("refused")+ yield++ with patch.object(runner, "streamablehttp_client", transport):+ trial = asyncio.run(runner._run_scenario(CONFIG, None, [], [], SCENARIO, 1)) # type: ignore[arg-type]++ assert trial.outcome == "mcp_error"+ assert (seen["timeout"], seen["sse_read_timeout"]) == (runner.TOOL_CALL_TIMEOUT, runner.TOOL_CALL_TIMEOUT)