Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(posthog-ai): move exec command parsing out of the eval harness (#106429)

Rafael Audibert747639aa7a78
diff --git a/products/posthog_ai/backend/exec_commands.py b/products/posthog_ai/backend/exec_commands.py
new file mode 100644
index 000000000000..32ef679a8ad9
--- /dev/null
+++ b/products/posthog_ai/backend/exec_commands.py
@@ -0,0 +1,85 @@
+"""Parsing for the single-exec PostHog MCP tool, shared by the backend and the eval harness.
+
+In single-exec mode the agent reaches every PostHog tool through one ``exec`` call, so the tool the
+agent meant is only in the command string.
+"""
+
+import json
+from typing import Any
+
+INFO_SYNTHETIC_PREFIX = "__info__:"
+"""Synthetic name assigned when ``exec {command: "info <tool>"}`` is unwrapped.
+
+Lets scorers treat the single-exec CLI's ``info <tool>`` and Claude Code's
+``ToolSearch(select:mcp__posthog__<tool>)`` as interchangeable
+"tool schema loaded" signals via a stable namespaced name.
+"""
+
+
+def normalize_tool_name(name: str | None) -> str:
+ """Strip the Claude-Code MCP namespace prefix from a tool name.
+
+ Claude Code surfaces MCP tools as ``mcp__<server>__<tool>``. Scorers
+ think in bare tool names like ``query-retention``; normalising here
+ keeps the public API simple.
+ """
+ if not name:
+ return ""
+ if name.startswith("mcp__"):
+ parts = name.split("__", 2)
+ if len(parts) == 3:
+ return parts[2]
+ return name
+
+
+_CALL_FLAGS = frozenset({"--json", "--confirm", "--no-skills"})
+
+
+def parse_exec_command(command: str) -> tuple[str, dict[str, Any]] | None:
+ """Split a CLI-style ``exec`` command string into ``(virtual_name, input)``.
+
+ Recognised shapes (produced by single-exec mode where the agent talks to
+ the PostHog MCP through one ``exec`` tool):
+ - ``"info <tool>"`` → ``("__info__:<tool>", {})``
+ - ``"call [--json] [--confirm] [--no-skills] <tool> <json>"`` → ``("<tool>", parsed_json)``
+
+ Returns ``None`` for anything else (``search``, ``tools``, ``schema``,
+ malformed) so callers can fall through to the raw ``exec`` representation.
+ """
+ stripped = command.strip()
+ if not stripped:
+ return None
+
+ head, _, rest = stripped.partition(" ")
+ head = head.lower()
+
+ if head == "info":
+ tool = rest.strip().split(None, 1)[0] if rest.strip() else ""
+ if tool:
+ return (f"{INFO_SYNTHETIC_PREFIX}{tool}", {})
+ return None
+
+ if head == "call":
+ rest = rest.strip()
+ flag, _, remainder = rest.partition(" ")
+ while flag in _CALL_FLAGS:
+ rest = remainder.lstrip()
+ flag, _, remainder = rest.partition(" ")
+ if not rest:
+ return None
+ tool, _, json_part = rest.partition(" ")
+ tool = tool.strip()
+ if not tool:
+ return None
+ json_part = json_part.strip()
+ parsed: dict[str, Any] = {}
+ if json_part:
+ try:
+ decoded = json.loads(json_part)
+ if isinstance(decoded, dict):
+ parsed = decoded
+ except json.JSONDecodeError:
+ parsed = {}
+ return (tool, parsed)
+
+ return None
diff --git a/products/posthog_ai/backend/tests/test_exec_commands.py b/products/posthog_ai/backend/tests/test_exec_commands.py
new file mode 100644
index 000000000000..90594a8d9ea3
--- /dev/null
+++ b/products/posthog_ai/backend/tests/test_exec_commands.py
@@ -0,0 +1,15 @@
+import unittest
+
+from products.posthog_ai.backend.exec_commands import normalize_tool_name
+
+
+class TestNormalizeToolName(unittest.TestCase):
+ def test_strips_mcp_prefix(self):
+ self.assertEqual(normalize_tool_name("mcp__posthog__query-trends"), "query-trends")
+
+ def test_passes_through_bare_names(self):
+ self.assertEqual(normalize_tool_name("query-trends"), "query-trends")
+
+ def test_handles_empty_and_none(self):
+ self.assertEqual(normalize_tool_name(None), "")
+ self.assertEqual(normalize_tool_name(""), "")
diff --git a/products/posthog_ai/eval_harness/log_parser.py b/products/posthog_ai/eval_harness/log_parser.py
index b97325e538fa..96ed7bec2a1a 100644
--- a/products/posthog_ai/eval_harness/log_parser.py
+++ b/products/posthog_ai/eval_harness/log_parser.py
@@ -18,34 +18,13 @@ from typing import Any
from pydantic import BaseModel, ConfigDict
+from products.posthog_ai.backend.exec_commands import normalize_tool_name, parse_exec_command
+
from .acp_log import parse_log
SKILL_TOOL_NAME = "Skill"
EXEC_TOOL_NAME = "exec"
EXECUTE_SQL_TOOL_NAME = "execute-sql"
-INFO_SYNTHETIC_PREFIX = "__info__:"
-"""Synthetic name assigned when ``exec {command: "info <tool>"}`` is unwrapped.
-
-Lets scorers treat the single-exec CLI's ``info <tool>`` and Claude Code's
-``ToolSearch(select:mcp__posthog__<tool>)`` as interchangeable
-"tool schema loaded" signals via a stable namespaced name.
-"""
-
-
-def normalize_tool_name(name: str | None) -> str:
- """Strip the Claude-Code MCP namespace prefix from a tool name.
-
- Claude Code surfaces MCP tools as ``mcp__<server>__<tool>``. Scorers
- think in bare tool names like ``query-retention``; normalising here
- keeps the public API simple.
- """
- if not name:
- return ""
- if name.startswith("mcp__"):
- parts = name.split("__", 2)
- if len(parts) == 3:
- return parts[2]
- return name
def describe_tool_use(name: str | None, tool_input: dict[str, Any]) -> tuple[str, dict[str, Any]]:
@@ -60,7 +39,7 @@ def describe_tool_use(name: str | None, tool_input: dict[str, Any]) -> tuple[str
if normalized == EXEC_TOOL_NAME:
command = tool_input.get("command", "")
if isinstance(command, str):
- unwrapped = _parse_exec_command(command)
+ unwrapped = parse_exec_command(command)
if unwrapped is not None:
return unwrapped
return (normalized, tool_input)
@@ -271,7 +250,7 @@ class LogParser:
if normalized == EXEC_TOOL_NAME:
command = tool_input.get("command", "")
if isinstance(command, str):
- unwrapped = _parse_exec_command(command)
+ unwrapped = parse_exec_command(command)
if unwrapped is not None:
inner_name, inner_input = unwrapped
output_format = tool_input.get("output_format")
@@ -345,56 +324,3 @@ def _index_tool_use_positions(messages: list[dict[str, Any]]) -> dict[str, int]:
if isinstance(call_id, str) and call_id and call_id not in positions:
positions[call_id] = idx
return positions
-
-
-_CALL_FLAGS = frozenset({"--json", "--confirm", "--no-skills"})
-
-
-def _parse_exec_command(command: str) -> tuple[str, dict[str, Any]] | None:
- """Split a CLI-style ``exec`` command string into ``(virtual_name, input)``.
-
- Recognised shapes (produced by single-exec mode where the agent talks to
- the PostHog MCP through one ``exec`` tool):
- - ``"info <tool>"`` → ``("__info__:<tool>", {})``
- - ``"call [--json] [--confirm] [--no-skills] <tool> <json>"`` → ``("<tool>", parsed_json)``
-
- Returns ``None`` for anything else (``search``, ``tools``, ``schema``,
- malformed) so callers can fall through to the raw ``exec`` representation.
- """
- stripped = command.strip()
- if not stripped:
- return None
-
- head, _, rest = stripped.partition(" ")
- head = head.lower()
-
- if head == "info":
- tool = rest.strip().split(None, 1)[0] if rest.strip() else ""
- if tool:
- return (f"{INFO_SYNTHETIC_PREFIX}{tool}", {})
- return None
-
- if head == "call":
- rest = rest.strip()
- flag, _, remainder = rest.partition(" ")
- while flag in _CALL_FLAGS:
- rest = remainder.lstrip()
- flag, _, remainder = rest.partition(" ")
- if not rest:
- return None
- tool, _, json_part = rest.partition(" ")
- tool = tool.strip()
- if not tool:
- return None
- json_part = json_part.strip()
- parsed: dict[str, Any] = {}
- if json_part:
- try:
- decoded = json.loads(json_part)
- if isinstance(decoded, dict):
- parsed = decoded
- except json.JSONDecodeError:
- parsed = {}
- return (tool, parsed)
-
- return None
diff --git a/products/posthog_ai/eval_harness/scorers/__init__.py b/products/posthog_ai/eval_harness/scorers/__init__.py
index c90cd7a653e6..06b898d91578 100644
--- a/products/posthog_ai/eval_harness/scorers/__init__.py
+++ b/products/posthog_ai/eval_harness/scorers/__init__.py
@@ -1,4 +1,5 @@
-from products.posthog_ai.eval_harness.log_parser import LogParser, normalize_tool_name
+from products.posthog_ai.backend.exec_commands import normalize_tool_name
+from products.posthog_ai.eval_harness.log_parser import LogParser
from .deterministic import AnswerToolCallNot, ExitCodeZero, NoToolCall, RequiredToolCall
from .judged import (
diff --git a/products/posthog_ai/eval_harness/test/test_log_parser.py b/products/posthog_ai/eval_harness/test/test_log_parser.py
index 1088d33d2bb2..159703e7c875 100644
--- a/products/posthog_ai/eval_harness/test/test_log_parser.py
+++ b/products/posthog_ai/eval_harness/test/test_log_parser.py
@@ -6,15 +6,8 @@ import json
import unittest
-from products.posthog_ai.eval_harness.log_parser import (
- EXEC_TOOL_NAME,
- INFO_SYNTHETIC_PREFIX,
- SKILL_TOOL_NAME,
- LogParser,
- SkillCall,
- ToolCall,
- normalize_tool_name,
-)
+from products.posthog_ai.backend.exec_commands import INFO_SYNTHETIC_PREFIX
+from products.posthog_ai.eval_harness.log_parser import EXEC_TOOL_NAME, SKILL_TOOL_NAME, LogParser, SkillCall, ToolCall
def _notification(**params) -> dict:
@@ -446,15 +439,3 @@ class TestLogParserModels(unittest.TestCase):
call = SkillCall(name="x", call_id="c", output="", is_error=False, position=0)
with self.assertRaises(Exception):
call.name = "y" # type: ignore[misc] # ty: ignore[invalid-assignment]
-
-
-class TestNormalizeToolName(unittest.TestCase):
- def test_strips_mcp_prefix(self):
- self.assertEqual(normalize_tool_name("mcp__posthog__query-trends"), "query-trends")
-
- def test_passes_through_bare_names(self):
- self.assertEqual(normalize_tool_name("query-trends"), "query-trends")
-
- def test_handles_empty_and_none(self):
- self.assertEqual(normalize_tool_name(None), "")
- self.assertEqual(normalize_tool_name(""), "")
diff --git a/products/posthog_ai/evals/cli_mcp/scorers.py b/products/posthog_ai/evals/cli_mcp/scorers.py
index 64d7811d8be5..30b6e2876e65 100644
--- a/products/posthog_ai/evals/cli_mcp/scorers.py
+++ b/products/posthog_ai/evals/cli_mcp/scorers.py
@@ -37,13 +37,8 @@ from __future__ import annotations
import re
-from products.posthog_ai.eval_harness.log_parser import (
- EXEC_TOOL_NAME,
- INFO_SYNTHETIC_PREFIX,
- LogParser,
- ToolCall,
- is_schema_discovery_call,
-)
+from products.posthog_ai.backend.exec_commands import INFO_SYNTHETIC_PREFIX
+from products.posthog_ai.eval_harness.log_parser import EXEC_TOOL_NAME, LogParser, ToolCall, is_schema_discovery_call
from products.posthog_ai.eval_harness.scorers.contract import Score, Scorer
__all__ = [
@@ -107,7 +102,7 @@ def _exec_command_head(call: ToolCall) -> tuple[str, str]:
Empty tuple for non-``exec`` or already-unwrapped calls. Lets scorers
inspect the ``search`` / ``schema`` / ``tools`` verbs that
- ``_parse_exec_command`` intentionally drops on the floor.
+ ``parse_exec_command`` intentionally drops on the floor.
"""
if call.is_exec_unwrapped or call.name != EXEC_TOOL_NAME:
return ("", "")
diff --git a/products/posthog_ai/evals/cli_mcp/skill_distribution_scorers.py b/products/posthog_ai/evals/cli_mcp/skill_distribution_scorers.py
index 4597bd6d4660..edcab296662e 100644
--- a/products/posthog_ai/evals/cli_mcp/skill_distribution_scorers.py
+++ b/products/posthog_ai/evals/cli_mcp/skill_distribution_scorers.py
@@ -10,8 +10,9 @@ from braintrust_core.score import Scorer
from posthog.dataclasses import frozen
+from products.posthog_ai.backend.exec_commands import normalize_tool_name
from products.posthog_ai.eval_harness.harness.cli import SkillDelivery
-from products.posthog_ai.eval_harness.log_parser import EXEC_TOOL_NAME, LogParser, ToolCall, normalize_tool_name
+from products.posthog_ai.eval_harness.log_parser import EXEC_TOOL_NAME, LogParser, ToolCall
_BUNDLED_SKILL_PATH_MARKERS = (
"/scripts/plugins/posthog/skills/",
diff --git a/products/posthog_ai/evals/cli_mcp/skill_usage_scorers.py b/products/posthog_ai/evals/cli_mcp/skill_usage_scorers.py
index 317e35538abc..39d0cb7f8200 100644
--- a/products/posthog_ai/evals/cli_mcp/skill_usage_scorers.py
+++ b/products/posthog_ai/evals/cli_mcp/skill_usage_scorers.py
@@ -18,8 +18,9 @@ from typing import Any, cast
from braintrust import Score
from braintrust_core.score import Scorer
+from products.posthog_ai.backend.exec_commands import normalize_tool_name
from products.posthog_ai.eval_harness.harness.cli import SkillDelivery
-from products.posthog_ai.eval_harness.log_parser import EXEC_TOOL_NAME, LogParser, ToolCall, normalize_tool_name
+from products.posthog_ai.eval_harness.log_parser import EXEC_TOOL_NAME, LogParser, ToolCall
from products.posthog_ai.eval_harness.scorers import BINARY_CHOICE_SCORES, JUDGE_MODEL, JudgedScorer
from products.posthog_ai.evals.cli_mcp.skill_distribution_scorers import (
_exec_command,
diff --git a/products/posthog_ai/evals/product_analytics/scorers.py b/products/posthog_ai/evals/product_analytics/scorers.py
index bb779597297d..97498fb03732 100644
--- a/products/posthog_ai/evals/product_analytics/scorers.py
+++ b/products/posthog_ai/evals/product_analytics/scorers.py
@@ -20,12 +20,8 @@ from pydantic import BaseModel
from posthog.schema import AssistantFunnelsQuery, AssistantRetentionQuery, AssistantTrendsQuery
-from products.posthog_ai.eval_harness.log_parser import (
- INFO_SYNTHETIC_PREFIX,
- LogParser,
- ToolCall,
- is_schema_discovery_call,
-)
+from products.posthog_ai.backend.exec_commands import INFO_SYNTHETIC_PREFIX
+from products.posthog_ai.eval_harness.log_parser import LogParser, ToolCall, is_schema_discovery_call
from products.posthog_ai.eval_harness.scorers import (
BINARY_CHOICE_SCORES,
GRADED_ALIGNMENT_CHOICE_SCORES,
diff --git a/products/posthog_ai/evals/retrieval/scorers.py b/products/posthog_ai/evals/retrieval/scorers.py
index 222dc2136fee..8144eacb6c57 100644
--- a/products/posthog_ai/evals/retrieval/scorers.py
+++ b/products/posthog_ai/evals/retrieval/scorers.py
@@ -39,7 +39,8 @@ import re
import json
from typing import Any
-from products.posthog_ai.eval_harness.log_parser import INFO_SYNTHETIC_PREFIX, LogParser
+from products.posthog_ai.backend.exec_commands import INFO_SYNTHETIC_PREFIX
+from products.posthog_ai.eval_harness.log_parser import LogParser
from products.posthog_ai.eval_harness.scorers.contract import Score, Scorer
__all__ = [