: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(signals): record MCP scout metrics as structured output (#105830)
posthog[bot]e8496b0019c8
diff --git a/products/signals/backend/scout_harness/config_registry.py b/products/signals/backend/scout_harness/config_registry.pyindex f0218d88b8b8..cd82dc85fb20 100644--- a/products/signals/backend/scout_harness/config_registry.py+++ b/products/signals/backend/scout_harness/config_registry.py@@ -13,6 +13,7 @@ goes through the write-scoped config `create` endpoint.from __future__ import annotations+from collections.abc import Mappingfrom datetime import UTC, datetimefrom django.db import transaction@@ -33,6 +34,7 @@ from products.signals.backend.scout_harness.lazy_seed import (canonical_deprecation_for,canonical_display_name_for,canonical_skill_names,+ canonical_structured_output_schema_for,is_operational_scout,)from products.signals.backend.scout_harness.skill_loader import SIGNALS_SCOUT_SKILL_PREFIX@@ -311,6 +313,10 @@ def register_missing_configs(# before the scout declared a label has no way to acquire one otherwise.if name in canonical_names and (canonical_display_name := canonical_display_name_for(name)):defaults["display_name"] = canonical_display_name+ # The schema's presence is what switches the structured-output channel on, so a measurement+ # scout records from its first run. Backfilled onto existing rows below, like the label.+ if name in canonical_names and (canonical_schema := canonical_structured_output_schema_for(name)):+ defaults["structured_output_schema"] = canonical_schema# The launch cadence is stamped on every canonical (gated) scout — whether it seeds# enabled now or stays disabled for the user to switch on later — so a specialist a user# toggles on runs at the flag's launch cadence rather than the model default (daily).@@ -335,6 +341,7 @@ def register_missing_configs()reconcile_canonical_display_names(team_id, canonical_names & skill_names)+ reconcile_canonical_structured_output_schemas(team_id, canonical_names & skill_names)reconcile_operational_configs(team_id, operational_names & skill_names, withheld_skill_names, max_enabled_scouts=max_enabled_scouts@@ -350,27 +357,50 @@ def register_missing_configs(def reconcile_canonical_display_names(team_id: int, canonical_names: set[str]) -> None:"""Give every canonical scout on this team the label the fleet ships it under, if it has none.- The rest of the seed posture is forward-only, and for the same reason this pass is narrow: it- writes only where `display_name` is blank, so a scout a person renamed keeps the name they gave- it, on this tick and on every tick after. Blank is not a choice a person can lose — it is what- "no name of its own" is stored as, and the label the fleet ships is exactly the default that- stands for, so filling it in is the sync doing what blank already meant.-- Backfill, not posture: a canonical scout registered before the fleet declared its label would- otherwise read as "Apm" forever, since nothing else ever revisits the column. Costs one read- per tick once every row is named, and nothing after that.+ Blank is not a choice a person can lose — it is what "no name of its own" is stored as, and the+ label the fleet ships is exactly the default that stands for. Without this a canonical scout+ registered before the fleet declared its label would read as "Apm" forever, since nothing else+ revisits the column."""labelled = {name: label for name in canonical_names if (label := canonical_display_name_for(name))}- if not labelled:+ _backfill_unset_column(team_id, labelled, column="display_name", unset_filter={"display_name": ""})+++def reconcile_canonical_structured_output_schemas(team_id: int, canonical_names: set[str]) -> None:+ """Give every canonical scout on this team the record contract the fleet ships it with, if it+ has none.++ Null is what "this scout records nothing" is stored as, and the canonical schema is the default+ that stands for. Without this a config registered before the scout shipped a schema would never+ acquire one, so the scout would run without its record channel forever.+ """+ schemas = {name: schema for name in canonical_names if (schema := canonical_structured_output_schema_for(name))}+ _backfill_unset_column(+ team_id, schemas, column="structured_output_schema", unset_filter={"structured_output_schema__isnull": True}+ )+++def _backfill_unset_column(+ team_id: int, values: Mapping[str, object], *, column: str, unset_filter: Mapping[str, object]+) -> None:+ """Write a canonical default onto the rows of `values` whose `column` is still unset.++ The rest of the seed posture is forward-only — an existing row is the team's to tune — and this+ pass stays narrow for the same reason: it writes only where the column holds the value that+ means "unset", so a team that set the column keeps what they set, on this tick and every tick+ after. It is a backfill for rows created before the fleet declared the default, so it costs one+ read per tick and nothing more once every row carries one.+ """+ if not values:returnconfigs = SignalScoutConfig.objects.for_team(team_id)- unnamed = set(configs.filter(skill_name__in=labelled, display_name="").values_list("skill_name", flat=True))- for skill_name in sorted(unnamed):- # Re-checking `display_name=""` in the update makes the write lose to a rename that landed+ unset = set(configs.filter(skill_name__in=values, **unset_filter).values_list("skill_name", flat=True))+ for skill_name in sorted(unset):+ # Re-checking the unset value in the update makes the write lose to an edit that landed# since the read, rather than reverting it. QuerySet.update() skips both auto_now and the# activity log, which is what this should do: a seeded default is not an edit anyone made.- configs.filter(skill_name=skill_name, display_name="").update(- display_name=labelled[skill_name], updated_at=timezone.now()+ configs.filter(skill_name=skill_name, **unset_filter).update(+ **{column: values[skill_name]}, updated_at=timezone.now())diff --git a/products/signals/backend/scout_harness/lazy_seed.py b/products/signals/backend/scout_harness/lazy_seed.pyindex ec50400812e8..1093ebff16cc 100644--- a/products/signals/backend/scout_harness/lazy_seed.py+++ b/products/signals/backend/scout_harness/lazy_seed.py@@ -120,6 +120,8 @@ class CanonicalSkill:`display_name` is the optional `scout-display-name` frontmatter value, the label the fleetships the scout under. `deprecation` is the optional retirement marker from `scout-status` /`scout-deprecation`, set only on a scout PostHog is retiring.+ `structured_output_schema` is the record contract a measurement scout ships, read from the+ bundled file `scout-structured-output-schema` names."""name: str@@ -132,6 +134,7 @@ class CanonicalSkill:role: ScoutRole = SCOUT_ROLE_SPECIALISTdisplay_name: str = ""deprecation: ScoutDeprecation | None = None+ structured_output_schema: dict | None = None@dataclass(frozen=True)@@ -278,6 +281,73 @@ def _parse_display_name(frontmatter: dict, skill_file: Path, *, is_scout: bool)return display_name+def _parse_structured_output_schema(+ frontmatter: dict, files: list[CanonicalSkillFile], skill_file: Path, *, is_scout: bool+) -> dict | None:+ """Read the optional `scout-structured-output-schema` frontmatter value — the record contract+ a measurement scout ships, seeded onto its config so the structured-output channel is on from+ the first run.++ The value names a bundled file rather than carrying the schema itself: a JSON Schema is a+ document, not a frontmatter scalar. It is resolved against the already-read bundle, so the+ schema file is read once, is covered by the same size and path caps as every other bundled+ file, and cannot name anything outside `_ALLOWED_BUNDLE_SUBDIRS` — "not in the bundle" is the+ one error, and there is no second path to keep in step with the first.++ Being a bundled file also puts the schema in the content hash, so editing one bumps the skill+ version and reaches each team's skill row like a body edit. That is the file, not the contract+ the record endpoint enforces: that is the config column, seeded once and never overwritten (see+ `config_registry.reconcile_canonical_structured_output_schemas`). A team already running the+ scout keeps the schema it was seeded, so changing a shipped schema for existing teams needs a+ migration rather than a frontmatter edit.++ Validated here with the same `validate_structured_output_schema` the config API uses, so a+ broken canonical schema fails the harness sync once rather than failing every run of the+ scout on every team.++ Only scouts have a config for the schema to land on, so the key is rejected on a companion+ skill.+ """+ if "scout-structured-output-schema" not in frontmatter:+ return None+ if not is_scout:+ raise CanonicalSkillParseError(+ f"Only a signals-scout-* skill may declare 'scout-structured-output-schema': {skill_file}"+ )+ raw = frontmatter["scout-structured-output-schema"]+ if not isinstance(raw, str) or not (rel_path := raw.strip()):+ raise CanonicalSkillParseError(+ f"SKILL.md frontmatter 'scout-structured-output-schema' must be a non-empty string: {skill_file}"+ )+ bundled = next((f for f in files if f.path == rel_path), None)+ if bundled is None:+ raise CanonicalSkillParseError(+ f"SKILL.md frontmatter 'scout-structured-output-schema' must name a bundled file under "+ f"{', '.join(f'{subdir}/' for subdir in _ALLOWED_BUNDLE_SUBDIRS)} so the schema rides in "+ f"the skill bundle and its content hash: got {rel_path!r} in {skill_file}"+ )+ try:+ schema = json.loads(bundled.content)+ except json.JSONDecodeError as error:+ raise CanonicalSkillParseError(+ f"Structured-output schema '{rel_path}' is not valid JSON: {skill_file}: {error}"+ ) from error+ # Deferred: importing this reaches `tools/__init__`, whose report-check imports run through+ # billing and `posthog.tasks`, which imports this module back through the signals billing+ # helpers.+ from products.signals.backend.scout_harness.tools.structured_output import ( # noqa: PLC0415 — breaks a circular import+ StructuredOutputSchemaError,+ validate_structured_output_schema,+ )++ try:+ return validate_structured_output_schema(schema)+ except StructuredOutputSchemaError as error:+ raise CanonicalSkillParseError(+ f"Structured-output schema '{rel_path}' is invalid: {skill_file}: {error}"+ ) from error++def _parse_canonical_skill(skill_dir: Path, *, is_scout: bool = True) -> CanonicalSkill:skill_file = skill_dir / "SKILL.md"raw = skill_file.read_text(encoding="utf-8")@@ -384,6 +454,9 @@ def _parse_canonical_skill(skill_dir: Path, *, is_scout: bool = True) -> Canonicf"Canonical skill has {len(files)} bundled files, exceeding the {_MAX_SKILL_FILE_COUNT} limit: {skill_dir}")+ # After the bundle, because the schema is resolved out of it rather than read again.+ structured_output_schema = _parse_structured_output_schema(frontmatter, files, skill_file, is_scout=is_scout)+return CanonicalSkill(name=name,description=description.strip(),@@ -395,6 +468,7 @@ def _parse_canonical_skill(skill_dir: Path, *, is_scout: bool = True) -> Canonicrole=role,display_name=display_name,deprecation=deprecation,+ structured_output_schema=structured_output_schema,)@@ -517,6 +591,35 @@ def canonical_display_name_for(skill_name: str) -> str:return _canonical_display_names().get(skill_name, "")+@lru_cache(maxsize=1)+def _canonical_structured_output_schemas() -> dict[str, dict]:+ """The record contract per canonical scout name, for the scouts that ship one.++ Cached for the process like `canonical_skill_names` — the shipped fleet only changes on+ deploy — and degrades to empty on a malformed canonical rather than failing config+ registration, which leaves the channel off rather than half-configured.+ """+ try:+ return {+ skill.name: skill.structured_output_schema+ for skill in discover_canonical_skills()+ if skill.structured_output_schema+ }+ except CanonicalSkillParseError:+ logger.warning("canonical_structured_output_schemas: malformed canonical skill on disk; seeding no schemas")+ return {}+++def canonical_structured_output_schema_for(skill_name: str) -> dict | None:+ """The record contract the canonical scout of this name ships, to stamp on its config.++ None for a custom scout, and for a canonical scout that records nothing. Callers must confirm+ the name is canonical first — a team's own `signals-scout-*` skill can share a canonical name,+ and it inherits nothing from disk.+ """+ return _canonical_structured_output_schemas().get(skill_name)++@lru_cache(maxsize=1)def _canonical_deprecations() -> dict[str, ScoutDeprecation]:"""The retirement marker per canonical scout name, for the scouts PostHog is retiring.@@ -581,6 +684,7 @@ def reset_canonical_caches() -> None:_canonical_display_names,_canonical_operational_scouts,_canonical_deprecations,+ _canonical_structured_output_schemas,):cache.cache_clear()@@ -621,7 +725,9 @@ def _compute_canonical_hash(canonical: CanonicalSkill) -> str:Deliberately excludes `config_tags`, `role`, and `display_name`: the hash is compared against`_compute_row_hash` over the team's `LLMSkill` row, which stores none of them (all three shapethe config instead), so folding them in here would make every seeded row read as diverged- forever.+ forever. The structured-output schema is covered anyway, because it is a bundled file — which+ is what keeps each team's copy of the file current, though not the config column the record+ endpoint reads from (see `_parse_structured_output_schema`)."""payload = {"description": canonical.description,diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.pyindex 6bb64bdc4b12..d2462c8798ad 100644--- a/products/signals/backend/scout_harness/serializers.py+++ b/products/signals/backend/scout_harness/serializers.py@@ -47,6 +47,10 @@ from products.signals.backend.report_prompts import MAX_SUGGESTED_PROMPT_LENGTH,from products.signals.backend.scout_harness.config_registry import CRON_SCHEDULE_MAX_LENGTH, cron_schedule_errorfrom products.signals.backend.scout_harness.derived_metadata import DERIVED_FLAG_KEYS, DERIVED_METADATA_KEYfrom products.signals.backend.scout_harness.fleet_sync import SYNC_SURFACES+from products.signals.backend.scout_harness.lazy_seed import (+ canonical_skill_names,+ canonical_structured_output_schema_for,+)from products.signals.backend.scout_harness.limits import MAX_RUN_NOTE_CHARSfrom products.signals.backend.scout_harness.model_selection import scout_model_config_enabled, scout_model_pin_catalogfrom products.signals.backend.scout_harness.note_targets import PIPELINE_AUDIENCES@@ -2937,6 +2941,18 @@ _STRUCTURED_OUTPUT_SCHEMA_HELP = ()+def _refuse_clearing_shipped_schema(skill_name: str) -> None:+ """A null schema is what the canonical reconcile reads as "never seeded", so a clear on a+ canonical scout that ships one would be undone on the next coordinator tick and the channel+ would come back on. Send people to the two switches that stick instead."""+ if skill_name in canonical_skill_names() and canonical_structured_output_schema_for(skill_name):+ raise serializers.ValidationError(+ "This scout ships its structured output schema, so clearing it does not stick. To stop it "+ "recording, turn on the dry-run setting or disable the scout. To change what it records, "+ "set a schema of your own instead."+ )++def _validate_structured_output_schema(value: dict | None) -> dict | None:if value is None:return None@@ -3537,6 +3553,12 @@ class _ScoutConfigCapabilityFieldsMixin(serializers.Serializer):return _validate_scout_model(value, self.context, current=self.instance.model if self.instance else None)def validate_structured_output_schema(self, value: dict | None) -> dict | None:+ if (+ value is None+ and isinstance(self.instance, SignalScoutConfig)+ and self.instance.structured_output_schema is not None+ ):+ _refuse_clearing_shipped_schema(self.instance.skill_name)return _validate_structured_output_schema(value)def validate_mcp_gateway_server_ids(self, value: list[UUID]) -> list[str]:diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.pyindex 3ab8273cf7a3..fcb3ccbafc40 100644--- a/products/signals/backend/test/test_scout_harness_api.py+++ b/products/signals/backend/test/test_scout_harness_api.py@@ -1249,6 +1249,35 @@ class TestScoutHarnessConfigStructuredOutputSchemaAPI(APIBaseTest):config.refresh_from_db()assert config.structured_output_schema == _STRUCTURED_OUTPUT_SCHEMA+ @parameterized.expand(+ [+ ("custom_scout_clears", "signals-scout-judge", _STRUCTURED_OUTPUT_SCHEMA, status.HTTP_200_OK, None),+ (+ "canonical_shipped_schema_refused",+ "signals-scout-mcp-tool-calls",+ _STRUCTURED_OUTPUT_SCHEMA,+ status.HTTP_400_BAD_REQUEST,+ _STRUCTURED_OUTPUT_SCHEMA,+ ),+ ("canonical_null_to_null_is_a_no_op", "signals-scout-mcp-tool-calls", None, status.HTTP_200_OK, None),+ ]+ )+ def test_patch_null_clears_a_custom_schema_but_not_a_shipped_one(+ self, _name: str, skill_name: str, stored: dict | None, expected_status: int, expected_schema: dict | None+ ) -> None:+ # The per-tick reconcile refills a null schema on a canonical scout, so accepting the clear+ # would turn recording back on within the hour with nothing in the response saying so. A+ # patch that sends null over a null column is not a clear and must not be refused.+ config = SignalScoutConfig.objects.create(+ team=self.team, skill_name=skill_name, structured_output_schema=stored+ )+ response = self.client.patch(+ self._detail_url(str(config.id)), data={"structured_output_schema": None}, format="json"+ )+ assert response.status_code == expected_status, response.json()+ config.refresh_from_db()+ assert config.structured_output_schema == expected_schema+def test_patch_rejects_invalid_schema(self) -> None:config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-judge")response = self.client.patch(diff --git a/products/signals/backend/test/test_scout_harness_lazy_seed.py b/products/signals/backend/test/test_scout_harness_lazy_seed.pyindex 083cd3841892..32de7556692c 100644--- a/products/signals/backend/test/test_scout_harness_lazy_seed.py+++ b/products/signals/backend/test/test_scout_harness_lazy_seed.py@@ -22,14 +22,22 @@ from products.signals.backend.scout_harness.lazy_seed import (SyncResult,_compute_canonical_hash,_compute_row_hash,+ canonical_structured_output_schema_for,discover_canonical_skills,reset_canonical_caches,seed_canonical_skills,sync_canonical_skills,)from products.signals.backend.scout_harness.skill_loader import load_skill_for_run+from products.signals.backend.scout_harness.tools.structured_output import (+ InvalidStructuredOutputError,+ StructuredOutputRecord,+ _validate_records,+)from products.skills.backend.models.skills import LLMSkill, LLMSkillFile+_SCHEMA_JSON = '{"type": "object", "properties": {"verdict": {"type": "string"}}}'+@pytest.fixture(autouse=True)def _forget_the_canonical_fleet():@@ -611,6 +619,148 @@ class TestDiscoverCanonicalSkills:discover_canonical_skills(tmp_path)+class TestStructuredOutputSchemaFrontmatter:+ """`scout-structured-output-schema`: the record contract a measurement scout ships."""++ def test_parses_the_schema_from_the_named_bundled_file(self, tmp_path: Path) -> None:+ _write_canonical_skill(+ tmp_path,+ dir_name="signals-scout-bar",+ frontmatter="""+ ---+ name: signals-scout-bar+ description: bar skill+ scout-structured-output-schema: references/out.schema.json+ ---+ """,+ body="# Bar\n",+ bundled_files={"references/out.schema.json": _SCHEMA_JSON},+ )+ skill = discover_canonical_skills(tmp_path)[0]+ assert skill.structured_output_schema == {"type": "object", "properties": {"verdict": {"type": "string"}}}+ # The file also rides in the bundle, which is what folds the schema into the content+ # hash — without it a schema edit would never reach a team that already has the scout.+ assert "references/out.schema.json" in [f.path for f in skill.files]++ def test_defaults_to_no_schema(self, tmp_path: Path) -> None:+ _write_canonical_skill(+ tmp_path,+ dir_name="signals-scout-bar",+ frontmatter="---\nname: signals-scout-bar\ndescription: bar skill\n---\n",+ body="# Bar\n",+ )+ assert discover_canonical_skills(tmp_path)[0].structured_output_schema is None++ @pytest.mark.parametrize(+ "schema_yaml,schema_content,expected_error",+ [+ ("scout-structured-output-schema:", None, "must be a non-empty string"),+ ("scout-structured-output-schema: 17", None, "must be a non-empty string"),+ ("scout-structured-output-schema: out.schema.json", None, "must name a bundled file"),+ ("scout-structured-output-schema: ../out.schema.json", None, "must name a bundled file"),+ ("scout-structured-output-schema: references/../SKILL.md", None, "must name a bundled file"),+ ("scout-structured-output-schema: references/missing.json", None, "must name a bundled file"),+ ("scout-structured-output-schema: references/out.schema.json", "{not json", "not valid JSON"),+ ("scout-structured-output-schema: references/out.schema.json", '{"type": "array"}', "is invalid"),+ (+ "scout-structured-output-schema: references/out.schema.json",+ '{"type": "object", "properties": {"a": {"pattern": "^(a+)+$"}}}',+ "is invalid",+ ),+ ],+ )+ def test_rejects_a_malformed_declaration(+ self, tmp_path: Path, schema_yaml: str, schema_content: str | None, expected_error: str+ ) -> None:+ # A schema that does not survive validation must fail the harness sync once, rather than+ # seeding a contract that fails every record call of every run on every team. A path that+ # is not a bundled file fails the same way whether it is outside the bundle dirs, an+ # escape, or simply absent: the bundle is the only place the schema is looked for.+ _write_canonical_skill(+ tmp_path,+ dir_name="signals-scout-bar",+ frontmatter=f"---\nname: signals-scout-bar\ndescription: bar skill\n{schema_yaml}\n---\n",+ body="# Bar\n",+ bundled_files={"references/out.schema.json": schema_content} if schema_content else None,+ )+ with pytest.raises(CanonicalSkillParseError, match=expected_error):+ discover_canonical_skills(tmp_path)++ def test_rejects_the_key_on_a_companion_skill(self, tmp_path: Path) -> None:+ # A companion skill never gets a config, so there is nothing for the schema to land on.+ _write_canonical_skill(+ tmp_path,+ dir_name="authoring-scouts",+ frontmatter="""+ ---+ name: authoring-scouts+ description: companion authoring guide+ scout-structured-output-schema: references/out.schema.json+ ---+ """,+ body="# Authoring\n",+ bundled_files={"references/out.schema.json": _SCHEMA_JSON},+ )+ with pytest.raises(+ CanonicalSkillParseError,+ match="Only a signals-scout-\\* skill may declare 'scout-structured-output-schema'",+ ):+ discover_canonical_skills(tmp_path)+++class TestShippedStructuredOutputSchemas:+ """The schemas the canonical fleet ships, checked against the contract the record endpoint+ enforces. Discovery already rejects an invalid schema; these pin what the valid one accepts."""++ def test_mcp_tool_calls_schema_accepts_one_record_of_each_kind(self) -> None:+ # Validated through the endpoint's own `_validate_records`, not a fresh validator: the+ # endpoint resolves references through a no-retrieval registry and applies its own size+ # caps, so a schema that only passes a bare validator can still fail every real record+ # call — and validation is all-or-nothing, so one rejected record loses the whole batch.+ schema = canonical_structured_output_schema_for("signals-scout-mcp-tool-calls")+ assert schema is not None++ rollup = {+ "mcp_record_kind": "category_rollup",+ "mcp_metrics_version": "1",+ "mcp_regime": "hono",+ "mcp_window_days": 7,+ "mcp_category": "all",+ "mcp_calls": 4000,+ "mcp_errors": 240,+ "mcp_sessions": 900,+ "mcp_users": 30,+ "mcp_error_rate_pct": 6.0,+ "mcp_struggle_session_pct": None,+ "mcp_p95_duration_ms": 1830.0,+ "mcp_problem_tools": 2,+ "mcp_share_of_project_calls_pct": 100.0,+ "mcp_report_action": "authored",+ }+ share = {+ "mcp_record_kind": "tool_session_share",+ "mcp_metrics_version": "1",+ "mcp_tool": "execute-sql",+ "mcp_source": "self_driving",+ "mcp_category": "SQL",+ "mcp_sessions_with_call": 1200,+ "mcp_sessions_total": 4000,+ "mcp_session_share_pct": 30.0,+ "mcp_calls_per_session": 1.5,+ "mcp_share_pct_prior_window": 12.0,+ }+ _validate_records([StructuredOutputRecord(payload=rollup), StructuredOutputRecord(payload=share)], schema)+ # Closed on both branches: a stray field is a typo nobody would otherwise see, and a+ # payload that satisfies both branches would make the discriminator meaningless.+ for rejected in (+ {**rollup, "mcp_unexpected": 1},+ {**share, "mcp_report_action": "authored"},+ {**rollup, "mcp_report_action": "filed"},+ ):+ with pytest.raises(InvalidStructuredOutputError):+ _validate_records([StructuredOutputRecord(payload=rejected)], schema)++class TestDeprecationFrontmatter:"""`scout-status` / `scout-deprecation`: the marker a retirement PR adds to a SKILL.md."""@@ -1409,6 +1559,28 @@ class TestSeedCanonicalSkillsAlias(BaseTest):assert dict(named)["signals-scout-mcp-tool-calls"] == "MCP tool calls"assert all(display_name for _, display_name in named)+ def test_real_fleet_seeds_the_structured_output_schema_and_backfills_it_but_never_a_team_edit(self) -> None:+ # The schema's presence on the config is what switches the record channel on, so a dropped+ # frontmatter key means the scout records nothing and nobody notices. Every config of this+ # scout predates the key, so the backfill is the only way they acquire one — and it runs on+ # every tick, so it must lose to a team's own schema forever.+ seed_canonical_skills(self.team)+ register_missing_configs(self.team.id)+ configs = SignalScoutConfig.all_teams.filter(team=self.team)+ canonical_schema = canonical_structured_output_schema_for("signals-scout-mcp-tool-calls")++ assert configs.get(skill_name="signals-scout-mcp-tool-calls").structured_output_schema == canonical_schema+ assert configs.get(skill_name="signals-scout-general").structured_output_schema is None++ configs.filter(skill_name="signals-scout-mcp-tool-calls").update(structured_output_schema=None)+ register_missing_configs(self.team.id)+ assert configs.get(skill_name="signals-scout-mcp-tool-calls").structured_output_schema == canonical_schema++ team_schema = {"type": "object", "properties": {"ours": {"type": "string"}}}+ configs.filter(skill_name="signals-scout-mcp-tool-calls").update(structured_output_schema=team_schema)+ register_missing_configs(self.team.id)+ assert configs.get(skill_name="signals-scout-mcp-tool-calls").structured_output_schema == team_schema+def test_reconcile_names_a_row_seeded_before_the_label_existed_but_never_a_rename(self) -> None:# Every canonical config predates the frontmatter key, so the backfill is the only way they# acquire a label — and it runs on every tick, so it must lose to a person's rename forever.diff --git a/products/signals/skills/AGENTS.md b/products/signals/skills/AGENTS.mdindex 29465f763a69..b27e473064f3 100644--- a/products/signals/skills/AGENTS.md+++ b/products/signals/skills/AGENTS.md@@ -56,7 +56,7 @@ A scout is a skill that holds a `SignalScoutConfig`. The harness globs `signals-Its discriminator is a statically-verifiable rule violation in a skill that is fresh or load-bearing — the unchanged long tail, subjective style nits, and canonical seeded scout rows (`category: "scout"`) are noise. Treats skill bodies as untrusted data under test, never instructions.- `signals-scout-customer-analytics/` — account-health watcher for the Customer analytics (Accounts) product, where each `system.accounts` row is a customer organization keyed to its analytics by `external_id` (the group key). Curates a watchlist of commercially-staked accounts (assigned CSM / AE / owner, or a CRM link) and scores each account's product engagement — weekly volume / WAU / key-feature usage — against its own trailing baseline, watching for churn-risk shapes (an engagement cliff, dormancy onset, single-threaded champion departure) and the positive inverse (an expansion signal worth an upsell). Its discriminator is a per-account engagement regression while the fleet holds, weighted by commercial ownership: one staked account sliding is signal, the whole fleet moving together is a capture/aggregate problem for another scout. The linchpin is the account→group join — it verifies that `external_id` actually matches a live group key before trusting any per-account number (a seeded/CRM-sourced roster that doesn't join is a config gap, not a finding). Fills the seam neither commercial neighbor covers — `product-analytics` scores aggregate user-grain flows and `revenue-analytics` watches the lagging revenue/MRR signal; neither scores an individual account's engagement trajectory. Acquisition is the web-analytics scout's territory.- `signals-scout-customer-analytics-billing-and-usage/` — per-account product-mix watcher: one product's usage or forecasted MRR moving sharply in either direction against that account+product's own same-weekday trailing 4-week baseline **while the account total holds** — the masked shift account-level monitoring misses ("flags down 40%, total flat — replay growth is masking it"). Reads per-account per-product usage and MRR from the billing warehouse sources it discovers at Orient, weights severity by % change × the product's share of the account's MRR (an unexplained bill-inflating spike ranks with drops — surprise invoices churn accounts too), and sweeps account notes, channel summaries, and synced comms for a planned-change explanation before filing. Its discriminator is per-product divergence under a flat account total on a commercially staked account. Fills the seam its two commercial neighbors leave open — `customer-analytics` scores the account's aggregate engagement (a flat total looks healthy to it) and `revenue-analytics` watches aggregate revenue and upstream sync health; fleet-wide product moves are `product-analytics` / `health-checks` territory. On the **report channel** (`emit_report` / `edit_report`): one report per account+product shift, edited while the shift persists. **Withheld fleet-wide** via the `signals-scout` flag's `default_team_config.withheld_skills` and released only on team 2 (its `team_configs` override) — the billing views and the `postgres.posthog_user` reviewer mapping it depends on exist only there.-- `signals-scout-mcp-tool-calls/` — tool-quality watcher for PostHog MCP usage. Reads `$mcp_tool_call` telemetry for tools that need improvement: high, broad-reach failure rates, per-session retry/hammering that betrays a confusing schema, slow or context-bloating responses, and undiagnosable failures (an instrumentation gap). Its discriminator is rate/struggle weighted by volume and reach, concentrated in a consistent shape — not raw counts. Coverage-aware: it first probes which enrichment fields the project captures (they split by regime — PostHog's own hono server vs external SDK servers) and picks lenses to match, resting detection only on always-present fields (error flag, duration, tool name, session). On the **report channel** (`emit_report` / `edit_report`): files one report per problem category (`$mcp_tool_category`, the owning product team) listing that category's problem tools each with a fix hypothesis, editing the live category report while the category still has problem tools; falls back to one report per tool where category coverage is absent (external-SDK regime); bundles `references/queries.md`, a HogQL cookbook validated against real telemetry.+- `signals-scout-mcp-tool-calls/` — tool-quality watcher for PostHog MCP usage. Reads `$mcp_tool_call` telemetry for tools that need improvement: high, broad-reach failure rates, per-session retry/hammering that betrays a confusing schema, slow or context-bloating responses, and undiagnosable failures (an instrumentation gap). Its discriminator is rate/struggle weighted by volume and reach, concentrated in a consistent shape — not raw counts. Coverage-aware: it first probes which enrichment fields the project captures (they split by regime — PostHog's own hono server vs external SDK servers) and picks lenses to match, resting detection only on always-present fields (error flag, duration, tool name, session). On the **report channel** (`emit_report` / `edit_report`): files one report per problem category (`$mcp_tool_category`, the owning product team) listing that category's problem tools each with a fix hypothesis, editing the live category report while the category still has problem tools; falls back to one report per tool where category coverage is absent (external-SDK regime); bundles `references/queries.md`, a HogQL cookbook validated against real telemetry. The one scout on the **structured-output channel**: `scout-structured-output-schema` in its frontmatter ships `references/structured-output.schema.json`, so every run records a per-category roll-up and per-tool session-share rows as `$scout_structured_output` events — a chartable series for numbers that exist nowhere else (struggle share, problem-tool counts, the regime, and what the scout decided per category), with `references/metrics-dashboard.md` as the consumption recipe.- `signals-scout-tasks/` — delivery + demand watcher for the Tasks product (the agent work items a project runs), read from the `system.tasks` / `system.task_runs` system tables. Two lenses in one body: **delivery health** every run (runs failing, clustered by repository and by `error_message` prefix) and a ~weekly gated **demand** pass over human-authored tasks (recurring asks that point at a product gap). Its discriminator is failure concentration × spread — a cluster's failure rate over meaningful volume, with runs ÷ distinct tasks separating a _systemic_ defect in a shared path (ratio ≈ 1 across many tasks) from a _retry storm_ (ratio ≫ 1 over one or two stuck tasks), which is the single biggest false positive on this surface. Two exclusions are load-bearing: it always drops `origin_product = 'signals_scout'` (the fleet's own run containers, which the `internal` flag does _not_ filter and which can outnumber every real origin), and the demand lens reads human origins only, so the inbox's own throughput can never register as user demand. On the **report channel** (`emit_report` / `edit_report`): one report per cluster (a repository or a failure class), with the demand lens held to a higher bar — its default outcome is compounding scratchpad memory, and it files only once a theme crosses into something actionable. Bundles `references/queries.md`, a cookbook validated against real task data (it also tells the scout to probe `stage` before resting a lens on it). Task text is treated as untrusted prompt material, never instructions.- `signals-scout-conversations/` — support-delivery health watcher for the Conversations (support inbox) product. Reads the `$conversation_*` ticket-lifecycle events for operational regressions: SLA breach-rate steps on team replies (`sla_active` / `sla_breached`), first-response latency blowouts (ticket-created → first team reply), backlog inflow-vs-resolution imbalance, and channel / assignment / priority concentration. Its discriminator is a _rate against a volume-stable denominator, per operational dimension, stepping away from its own trailing baseline while ticket volume holds_ — a breach share / response latency / inflow-minus-resolution delta moving on steady volume is signal, a raw count that tracks inbound volume is baseline — always gated by a minimum-volume guard. On the **report channel** (`emit_report` / `edit_report`): files each dated, dimension-named regression as a 1:1 inbox report, editing the live report while the regression persists. It is the operational complement to the per-ticket emission path: the emission pipeline (`source_product="conversations"`) already reads each ticket thread and fires a per-ticket _product-feedback_ signal (bugs / feature requests / usability), so this scout never re-surfaces individual ticket content — it owns the aggregate throughput / SLA / backlog / routing shape the one-ticket-at-a-time emitter can't see, and (reading analytics events) it works whether or not that emission source is enabled.@@ -96,6 +96,17 @@ Give a new scout a label rather than adding a capitalization fix downstream.Unlike tags, it is reconciled onto rows seeded earlier, but only where the column is still blank, so a scout a team renamed keeps the name they gave it.It sits outside the canonical content hash for the same reason tags do.+Frontmatter also carries the optional **`scout-structured-output-schema`** — a path to a bundled JSON Schema file describing one record the scout writes through `scout-record-output`, seeded onto `SignalScoutConfig.structured_output_schema`.+The schema's presence is what switches the structured-output channel on, so a measurement scout records its series from its first run instead of waiting for someone to paste a schema into the config API.+It is a path rather than inline YAML because a JSON Schema is a document, and it must name a file in the skill bundle (`references/` or `scripts/`) so the schema is read once, under the same caps as every other bundled file, and rides the canonical content hash.+The harness validates it at discovery with the same `validate_structured_output_schema` the config API uses, so a broken schema fails the sync once instead of failing every run.+Like the display name, it is reconciled onto rows seeded earlier but only where the column is still null, so a team that edited its schema owns it from then on.+Because null is what the reconcile reads as "never seeded", the config API refuses to clear a shipped schema to null on a canonical scout and points at the two switches that do stick: the dry-run setting (`emit`) withholds the channel, and disabling the scout stops the runs.+The reconcile runs on the coordinator's per-tick path for explicitly enrolled teams; a wildcard-enrolled team picks the schema up when its configs are next created or synced, the same as the display name.+That cuts both ways: the config column is what the record endpoint enforces, and nothing overwrites it, so editing a shipped schema updates each team's copy of the _file_ but leaves every already-seeded config on the schema it was given.+Changing a schema teams already run needs a migration, not a frontmatter edit.+`signals-scout-mcp-tool-calls` is the one that ships with it.+Frontmatter also carries the optional **`scout-role`** value, which is `specialist` unless a scout says otherwise.A scout that watches the self-driving system rather than a product surface declares `scout-role: operational`, and the harness stops treating its quiet as waste: the config seeds enabled and exempt from the inactivity sweep, skips the launch allowlist and the per-team enabled-scout cap, and cannot be deleted through the config API.Unlike tags, the role is reconciled onto rows seeded earlier on every coordinator tick, because a silenced operational scout is the failure the role exists to prevent — though a pause a person made is still left standing, and `withheld_skills` still gates the scout.@@ -117,7 +128,7 @@ The entire canonical fleet is on the **report channel** (ported one scout per PRno canonical scout uses it, and the user-facing skills (`authoring-scouts`, `exploring-scouts`) no longer teach it — new scouts always list the report tools.The specialists each carry their own domain discriminator + investigation patterns.-Most are a single self-contained `SKILL.md`; a few bundle surface-specific references read on demand — `signals-scout-anomaly-detection` (`anomaly-methods.md`, `watchlist-and-memory.md`, `report-contract.md`), `signals-scout-ai-observability` (`lenses.md`), `signals-scout-surveys` (`response-querying.md`), `signals-scout-web-vitals` (`remediation.md`, `onset-correlation.md`), `signals-scout-mcp-tool-calls` (`queries.md`), `signals-scout-tasks` (`queries.md`), and `signals-scout-pr-follow-up` (`sources.md`, `deploy-ladder.md`, `probes.md`); `ls signals-scout-*/references/` is the current list. Treat the generalist as the reference shape. Note that a scout can only read its own bundled files at runtime (each team's `LLMSkill` row carries just that skill's files) — which is why a scout that needs the dedupe/memory conventions in depth bundles its own copy rather than pointing at the generalist's. The report-channel contract is the exception to that copy-it-locally rule: it rides in the harness prompt, not a file, so report scouts share one definition without each bundling a copy.+Most are a single self-contained `SKILL.md`; a few bundle surface-specific references read on demand — `signals-scout-anomaly-detection` (`anomaly-methods.md`, `watchlist-and-memory.md`, `report-contract.md`), `signals-scout-ai-observability` (`lenses.md`), `signals-scout-surveys` (`response-querying.md`), `signals-scout-web-vitals` (`remediation.md`, `onset-correlation.md`), `signals-scout-mcp-tool-calls` (`queries.md`, `metrics-dashboard.md`, `structured-output.schema.json`), `signals-scout-tasks` (`queries.md`), and `signals-scout-pr-follow-up` (`sources.md`, `deploy-ladder.md`, `probes.md`); `ls signals-scout-*/references/` is the current list. Treat the generalist as the reference shape. Note that a scout can only read its own bundled files at runtime (each team's `LLMSkill` row carries just that skill's files) — which is why a scout that needs the dedupe/memory conventions in depth bundles its own copy rather than pointing at the generalist's. The report-channel contract is the exception to that copy-it-locally rule: it rides in the harness prompt, not a file, so report scouts share one definition without each bundling a copy.## When editing skills in this directorydiff --git a/products/signals/skills/exploring-scouts/SKILL.md b/products/signals/skills/exploring-scouts/SKILL.mdindex f296ee6d2570..1d540f325a0c 100644--- a/products/signals/skills/exploring-scouts/SKILL.md+++ b/products/signals/skills/exploring-scouts/SKILL.md@@ -32,6 +32,11 @@ The run rows also carry `emitted_count` / `emitted_finding_ids` — **legacy fie**Never read `emitted_count: 0` as "did nothing"** — check the report columns and the run summary first.A scout whose config carries a `structured_output_schema` has a third output channel next to reports: schema-validated **measurement records**, recorded as `$scout_structured_output` events in the project (only _scalar_ top-level payload keys flatten to `output_<key>` properties — object and array fields live solely inside the full `output` property, so a missing `output_<key>` is not a missing value; `subject` names the judged entity) rather than as run-row columns.The events are the ground truth — `metadata.derived.has_structured_output` says the run had at least one batch **accepted**, which is a fast per-run screen but not delivery confirmation (a rare capture failure after acceptance leaves it true with fewer or no events behind it), so count the events when the number of records matters. See [`references/scout-data-model.md`](references/scout-data-model.md) for the event shape.+Of the scouts PostHog ships, `signals-scout-mcp-tool-calls` is the one that records a series: every run that finds MCP traffic writes a per-category roll-up of MCP tool health and per-tool session-share rows, whether or not it files a report, so a healthy category is distinguishable from an unmeasured one.+No records is not by itself a broken channel.+A run on a project with no recent `$mcp_tool_call` events stops early and records nothing, and a dry-run scout (`emit` off) has nowhere to record to.+Check the run summary, the `not-in-use:mcp_analytics` scratchpad entry, and the config's `emit` before you call the channel broken.+Find them with `event = '$scout_structured_output'` and `properties.skill_name = 'signals-scout-mcp-tool-calls'`; the scout's own `references/metrics-dashboard.md` carries the chart and alert recipes.Each run also carries a `metadata` map. Top-level: the provenance set `harness_prompt_version` / `report_channel` (`none`, `emit`, `edit`, or `both`) / `skill_origin` / `github_guidance`, saying which instructions the run was given; plus routing keys (`model` / `runtime_adapter` / `reasoning_effort` / `service_tier`) only when a gate or pin overrode the default. Nested under `metadata.derived`: booleans the harness computes at the end of the run (`has_emit_report`, `has_edit_report`, `has_self_improvement`, `has_chart`, `has_self_validation`, `has_structured_output`).When comparing runs (before/after a prompt change, one model against another), segment on all four provenance values first: runs differing on any of `harness_prompt_version`, `report_channel`, `skill_origin`, or `github_guidance` were given different instructions and aren't a like-for-like population. Runs predating this field have none of them, so treat missing provenance as unknown and exclude those runs from a comparison rather than pooling them.For "what kind of run was this?" questions — did it author a self-improvement report, did it validate its follow-up queue — read `derived` rather than parsing the prose summary. It's computed server-side from what the run actually did, so it can't disagree with the run's own output — with one exception: `has_structured_output` tracks batches the run had **accepted**, not events delivered, so it alone can be true with fewer or no records behind it (count the events, as above). No `derived` map at all means unknown, not "all false" — the run predates the field, failed before finishing, or its stamp failed. Most runs from before this shipped have no map, so don't read their absence as a finding.diff --git a/products/signals/skills/signals-scout-mcp-tool-calls/SKILL.md b/products/signals/skills/signals-scout-mcp-tool-calls/SKILL.mdindex 897df9f640d8..10e09ace36b2 100644--- a/products/signals/skills/signals-scout-mcp-tool-calls/SKILL.md+++ b/products/signals/skills/signals-scout-mcp-tool-calls/SKILL.md@@ -9,8 +9,10 @@ compatibility: >PostHog Signals agent (Claude sandbox). Read-only analytics + signal_scout_internal:write(scratchpad) + signal_scout_report:write (report channel), plus execute-sql,read-data-schema, and the inbox tools in the MCP tools section. The SQL cookbook lives in- references/queries.md (read it on demand); deep-dives into+ references/queries.md and the dashboard recipe for the recorded metrics in+ references/metrics-dashboard.md (read both on demand); deep-dives intoposthog:exploring-mcp-tool-quality and posthog:querying-posthog-data.+scout-structured-output-schema: references/structured-output.schema.jsonallowed_tools:- emit_report- edit_report@@ -32,6 +34,7 @@ You author reports directly via the report channel (`scout-emit-report` / `scout3. **Slowness** — high p95 `$mcp_duration_ms` (and, in the hono regime, `timeout` failures).4. **Context bloat** — oversized responses (hono regime only).5. **Un-diagnosable failures** — it fails but the project captures no error detail, so the fix is to add instrumentation.+6. **Over-calling** — agents call it in a much larger share of sessions than in the prior window, even when every call succeeds (lens 10).**Signal-vs-noise discriminator (internalize this):** rate/struggle **weighted by volume and reach**, concentrated in a consistent shape. Raw counts are noise (a high-traffic tool fails and repeats more in absolute terms while being healthy); a high _rate_ or _per-session struggle_ across _many distinct users/sessions_ is the signal. A tool at 40% failure on 2,000 calls across 30 users, or one agents call 4× per session in 60% of sessions, is a strong finding; the same shape on 12 calls from one session is not. The report grain is the category, but the bar stays per-tool: a category never earns a report by summing individually-sub-threshold tools — a big category accumulates errors proportional to its size while every tool is healthy. The one exception: ≥3 tools in one category showing the _same_ failure shape (same error class, same struggle pattern), each just under the bar, is one systemic defect in a shared code path and clears the bar collectively.@@ -58,7 +61,7 @@ MCP tool calls land on the `$mcp_tool_call` event, emitted by both PostHog's own| `$mcp_tool_category` | hono only (exec-dispatched calls carry the _inner_ tool's category) | the report grain: owning product team || `$mcp_mode` (`cli`/`tools`) | hono / CLI only | is it broken only via the exec wrapper? || `input_tokens` / `output_tokens` (bare keys, no `$`) | hono only | response bloat |-| `$mcp_intent` / `$mcp_intent_source` | sparse, opt-in (agent-supplied) | tie failures to what the agent wanted |+| `$mcp_intent` / `$mcp_intent_source` | agent-supplied; near-universal on hono, absent on most external SDKs | tie failures to what the agent wanted |Two consequences to remember, both verified against real data:@@ -94,20 +97,23 @@ Run **query 0** from the cookbook (unless a fresh `pattern:mcp_analytics:regime`Pick what the profile/probe flags as interesting and rotate across runs — don't run every lens every tick. Each maps to a cookbook query.-| Lens | Detects | Reliability | Query |-| ------------------- | ----------------------------------------------------------- | ------------------------------- | ----- |-| Failure leaderboard | high error-rate tools | Tier 1 (always) | 1 |-| Struggle / retry | schema/UX confusion (hammering, fail-then-retry) | Tier 1 (always) | 2 |-| Latency | slow tools | Tier 1 (always) | 4 |-| Error class | fix hypothesis from failure taxonomy | hono only | 3a |-| Error messages | fix hypothesis from raw text | external SDK only | 3b |-| Intent | what the agent wanted the tool to do | if `pct_with_intent` ≥ ~20 | 5 |-| Client / mode split | universal break vs one-harness break | Tier 1 (client); mode hono only | 6 |-| Observability gap | failures with no detail → add instrumentation | Tier 1 (always) | 7 |-| Output bloat | oversized responses | hono only | 8 |-| Category rollup | problem tools grouped by owning category (the report grain) | hono / per-category mode | 9 |--The workflow is **detect → localize → hypothesize → group**: query 1/2/4 detect per-tool candidates using only reliable fields (each now carries a `category` column); then use whichever Tier-2 lens the probe said is available (3a or 3b, plus 5/6) to localize each cause and form the per-tool fix hypothesis; query 9 rolls candidates up to their category with category-level denominators, and one report per category carries the per-tool hypotheses. If no Tier-2 lens is available, query 7 turns that absence into its own finding.+| Lens | Detects | Reliability | Query |+| ------------------- | --------------------------------------------------------------- | ------------------------------- | ----- |+| Failure leaderboard | high error-rate tools | Tier 1 (always) | 1 |+| Struggle / retry | schema/UX confusion (hammering, fail-then-retry) | Tier 1 (always) | 2 |+| Latency | slow tools | Tier 1 (always) | 4 |+| Error class | fix hypothesis from failure taxonomy | hono only | 3a |+| Error messages | fix hypothesis from raw text | external SDK only | 3b |+| Intent | what the agent wanted the tool to do | default on hono; check coverage | 5 |+| Client / mode split | universal break vs one-harness break | Tier 1 (client); mode hono only | 6 |+| Observability gap | failures with no detail → add instrumentation | Tier 1 (always) | 7 |+| Output bloat | oversized responses | hono only | 8 |+| Category rollup | problem tools grouped by owning category (the report grain) | hono / per-category mode | 9 |+| Session share | tools called in a growing share of sessions ("called too much") | Tier 1 (always) | 10 |++The workflow is **detect → localize → hypothesize → group**: query 1/2/4/10 detect per-tool candidates using only reliable fields (each now carries a `category` column); then use whichever Tier-2 lens the probe said is available (3a or 3b, plus 5/6) to localize each cause and form the per-tool fix hypothesis; query 9 rolls candidates up to their category with category-level denominators, and one report per category carries the per-tool hypotheses. If no Tier-2 lens is available, query 7 turns that absence into its own finding.++**Lens 10, session share, is the "called too much" lens** and the one the other four miss: a tool the agent reaches for in a growing share of sessions is a problem even when every call succeeds, because the cost is context and latency in every session rather than a failure anyone sees. Read it as a step change, not a level — a tool that went from a small share of a source's sessions to most of them between the current and prior window, with reach across many sessions, is a report candidate under the session-share bar in Decide. The fix hypothesis points at prompt or tool-description wording (the tool is being advertised too eagerly), not at the handler. It is deterministic: no judge, no sampling. A high but flat share is the tool doing its job.## Save memory as you go@@ -121,30 +127,40 @@ Encode the scope in the key prefix so future runs find it with one `text=mcp` se- key `report:mcp_analytics:category:<category>` — _"Report `019f0a96-…` covers the insights category's problem tools (query-run, list-insights). Edit it (`append_evidence` with fresh numbers / newly-problematic tools) while the category still has problem tools and the report is live; if it was resolved and the category later regresses, that's a fresh report."_- key `reviewer:mcp_analytics:<category>` — _"insights MCP tools routed to `alice` (owns the insights MCP surface per human correction on report `019f…`) — reuse while that evidence stands."_ Record the **evidence**, not just the login: a memory that says only "routed to alice" is indistinguishable from a guess, and blind reuse compounds a mis-route across every future run. Set the same evidence as the reviewer's `reason` when you author.+## Record metrics++Record what you measured on every run, quiet or not. The numbers above are derived — struggle share, problem-tool counts, the regime, what you did about each category — so they exist nowhere else, and a run that files nothing still tells you a category was healthy rather than unmeasured. Records go to `scout-record-output`, validated against the schema in [`references/structured-output.schema.json`](references/structured-output.schema.json), and land as `$scout_structured_output` events you can chart. The two kinds go in at different points, because only one of them depends on what you decide.++- **Before Decide, the `tool_session_share` records** from query 10 (`subject` = `tool:<tool>:<source>`) — the top 20 tools by session share per source. That bound keeps a run inside one or two batches and well under the per-run cap.+- **After Decide, once every report tool call has returned, one `category_rollup` per category with any traffic this window, healthy ones included** (`subject` = `category:<category>`), plus one for the project-wide baseline with `mcp_category` = `all`. The unremarkable records are the denominator: without them you cannot tell a healthy category from one nobody looked at. Take every measured field from query 11, which returns exactly these rows, and run it every tick even when the lenses rotate. Never build a category value from the per-tool queries: summed per-tool `users` or `sessions` count a user once per tool, and a per-tool p95 or struggle share does not average into a category value. Send `null` for `mcp_struggle_session_pct` or `mcp_p95_duration_ms` only where query 11 returns null. Set `mcp_problem_tools` to the number of distinct tools in the category that cleared any lens's bar this run, session share included. Set `mcp_report_action` to what you did with the category (`authored`, `edited`, `skipped_live_report`, `below_bar`, `none`), so the chart shows your decisions next to the numbers that drove them. Record `authored` or `edited` only when that report tool call succeeded; a write that failed is `none`.+- Send each kind as one batched call. Submit both kinds every run, quiet or not: a run that ends in skips and memory must still leave the series intact. The one exception: when query 10 returns no rows, skip the `tool_session_share` call, because the endpoint rejects an empty batch, and say in the close-out that no tool met the query floor. Never lower the floor or pad the batch to get rows. The `category_rollup` batch still goes in.+- Leave `mcp_metrics_version` at `1`. It is what a chart filters on, so it changes only when a field's definition does.+## DecideFor a category with candidates clearing the bar, the call is **edit an existing report, author a new one, remember, or skip** — use judgment, these are the rails:- **Search the inbox first.** The `report:mcp_analytics:category:<category>` scratchpad pointer is the reliable path (it holds the `report_id` — `inbox-reports-retrieve` it directly); with no pointer, `inbox-reports-list` by the category name _and_ by each problem tool's name (`ordering=-updated_at`) — the tool-name search is what catches legacy per-tool reports. A category with a live report and no material change is a **skip**.- **Edit** (`scout-edit-report`) when a still-live report already covers the category and it still has problem tools — the same ones, or new ones joining. Add the fresh numbers (per-tool rate trends, broadening reach) and any newly-problematic tools with `append_evidence`, each with its own hypothesis; or rewrite the title/summary on a report you authored. This is the default when a match exists. `edit-report` can't change status, so if the matched report is `resolved` / `suppressed` / `failed`, don't append (it won't resurface) — author a fresh report for the relapse and repoint the `report:` key.-- **Author** (`scout-emit-report`) only when nothing live covers the category — **one report per category** (tools aggregated over the window), never one per tool or per failed call. A **report-worthy finding** leaves nothing to take on trust: each listed tool's problem (failure / struggle / latency / bloat) high over the volume floor with reach across multiple users/sessions, and — when a Tier-2 lens is available — localized to a class/message/intent with counts in the `evidence`. Below that bar, write memory instead. The `title` names the category and the scale ("MCP data-warehouse tools need improvement: 4 tools failing/struggling"). The `summary` follows Hook (category + N problem tools + combined volume/reach + the category's share of project MCP traffic from query 9) → one short block per problem tool (the quantified problem, its shape from the Tier-2 lens, the fix hypothesis) → Recommendation. Write for an engineer on the owning team who's never seen these tools, and **state which regime the evidence came from**. Attach the category's shape via `charts` — a per-tool bar of the active lens's metric (failure rate, struggling-session share, p95 duration, or response bloat), plus a daily series of that same metric when a regression is dated — so the reader sees the problem tools at a glance. Set `priority` (P0–P4) + `priority_explanation` — what the _worst_ tool would earn alone (P2 if any tool is high-rate/high-struggle, broad-reach, clearly-localized; P3 otherwise); bundling never raises priority. Set `suggested_reviewers` via `scout-members-list` (objects — a `{github_login}` or `{user_uuid}`, not bare strings; cache under `reviewer:mcp_analytics:<category>`, and check prior category reports' artefacts via `inbox-report-artefacts-list` for precedent); left empty the report reaches no one. Then choose the actionability + repo together:+- **Author** (`scout-emit-report`) only when nothing live covers the category — **one report per category** (tools aggregated over the window), never one per tool or per failed call. A **report-worthy finding** leaves nothing to take on trust: each listed tool's problem (failure / struggle / latency / bloat) high over the volume floor with reach across multiple users/sessions, and — when a Tier-2 lens is available — localized to a class/message/intent with counts in the `evidence`. For session share the bar is a step, not a level: the tool went from a small share of a source's sessions in the prior window to most of them in the current one, across many sessions, with `share_pct_prior_window` over `prior_sessions_total`, `session_share_pct` and `sessions_with_call` / `sessions_total` in the `evidence`. A null `share_pct_prior_window` is no baseline, so it never clears this bar. Below that bar, write memory instead. The `title` names the category and the scale ("MCP data-warehouse tools need improvement: 4 tools failing/struggling"). The `summary` follows Hook (category + N problem tools + combined volume/reach + the category's share of project MCP traffic from query 9) → one short block per problem tool (the quantified problem, its shape from the Tier-2 lens, the fix hypothesis) → Recommendation. Write for an engineer on the owning team who's never seen these tools, and **state which regime the evidence came from**. Attach the category's shape via `charts` — a per-tool bar of the active lens's metric (failure rate, struggling-session share, p95 duration, response bloat, or session share next to its prior-window share), plus a daily series of that same metric when a regression is dated — so the reader sees the problem tools at a glance. Set `priority` (P0–P4) + `priority_explanation` — what the _worst_ tool would earn alone (P2 if any tool is high-rate/high-struggle, broad-reach, clearly-localized; P3 otherwise); bundling never raises priority. Set `suggested_reviewers` via `scout-members-list` (objects — a `{github_login}` or `{user_uuid}`, not bare strings; cache under `reviewer:mcp_analytics:<category>`, and check prior category reports' artefacts via `inbox-report-artefacts-list` for precedent); left empty the report reaches no one. Then choose the actionability + repo together:- In the **hono regime** the tools live in PostHog's own MCP server, so unless this project's team owns that code, the action is an investigation / upstream report → `actionability=requires_human_input` and `repository=NO_REPO` (NO_REPO is what stops `priority`+reviewers from spawning a pointless repo-selection sandbox).- When the team **owns the MCP server** (the external-SDK regime, or a team that owns the hono server's code) and the hypotheses are concrete code changes — a schema/description fix, a handler bug — → `actionability=immediately_actionable` with `repository="owner/repo"` (or omit `repository` to let the selector pick) to open a draft PR, and end the summary with the **Fix loop metric** section (next heading) so the implementation task iterates until the number moves. A category report bundling _heterogeneous_ fixes across several tools leans `requires_human_input` even on an owned server — there's no single-PR shape; a single-tool or same-shape-systemic report can stay `immediately_actionable`.- After authoring, write the `report:mcp_analytics:category:<category>` pointer with the `report_id` so the next run edits instead of duplicating, and update the `dedupe:` entry.- **Fold observability gaps in** (query 7): a tool that fails materially (≥50 errors) with ≥90% of failures unclassified (`$mcp_error_type IN ('', 'None')` and no message) enters its category's report as an entry whose suggestion is "add error-type/message instrumentation to its MCP handler". Only a _project-wide_ gap — failures undiagnosable across every category — is its own standalone P3 report; on a team-owned server the instrumentation change is concrete enough for `immediately_actionable` + the server repo, otherwise `requires_human_input` + `NO_REPO`.- **Migrating legacy per-tool state**: a live per-tool report (or a `report:mcp_analytics:<tool>` key) for a tool in problem category X — if that tool is X's _only_ problem tool, edit that report in place (it is the category report de facto) and write `report:mcp_analytics:category:<X>` pointing at its id; if X has other problem tools too, author the category report noting it supersedes the legacy one, `append_note` the legacy report pointing forward, and repoint the keys. Never end a run with two live reports independently claiming the same tool.- **Remember** if below the bar or to record what you ruled out; **skip** with a one-line note if a `noise:` / `addressed:` / `dedupe:` entry or a live inbox report already covers it.+- **Record** — when every category is settled and every report tool call has returned, submit the `category_rollup` batch from Record metrics.## Fix loop metric — the autoresearch handoffEvery report filed `immediately_actionable` with a repository must end its summary with a **`Fix loop metric`** section.Its presence is what turns the auto-started implementation task from a one-shot patch into a measure → fix → re-measure loop, so it must stand alone for an agent that has never seen this scout or its cookbook:-- **Metric** — one number matching the finding's primary lens, scoped to the category's problem tools over a trailing 7d window: failure rate for a failure finding, share of sessions with struggle (hammering / fail-then-retry) for a struggle/discoverability finding, p95 `$mcp_duration_ms` for latency.+- **Metric** — one number matching the finding's primary lens, scoped to the category's problem tools over a trailing 7d window: failure rate for a failure finding, share of sessions with struggle (hammering / fail-then-retry) for a struggle/discoverability finding, p95 `$mcp_duration_ms` for latency, and for a session-share finding the share of the source's sessions that called the tool (query 10), with the prior-window share as the reference point.- **Measurement** — the exact HogQL to re-run (the cookbook query you used, inlined with the category/tool filters baked in — never a reference to "query 1"), plus the fastest local proxy: reproducing the cited failing calls against a dev MCP server, or the affected handler's unit tests.- **Baseline** — the value measured this run, with volume and reach ("41% of 2,013 calls across 34 users, 7d").- **Goal** — the direction and a concrete bar, e.g. decrease to at or below the project-wide error rate from `pattern:mcp_analytics:baseline`.-- **Constraints** — the metric must move because the calls genuinely succeed: no masking errors, retry-hiding, swallowing exceptions, loosening schema validation to accept garbage, and no touching the `$mcp_tool_call` analytics stamping that feeds the measurement.+- **Constraints** — the metric must move because the calls genuinely succeed: no masking errors, retry-hiding, swallowing exceptions, loosening schema validation to accept garbage, and no touching the `$mcp_tool_call` analytics stamping that feeds the measurement. A session-share metric must fall because agents stop calling the tool when they do not need it, not because the tool was renamed, hidden, or removed.- **Evidence hygiene** — the PR's before/after evidence shows aggregate metric outputs and synthetic/local reproductions only: raw telemetry rows, error messages, intent strings, and user/customer identifiers never appear in a PR or its attached images (the target repo may be public, and PR image assets stay readable forever).- **Intent evidence** — when `pct_with_intent` clears the bar, one line on what agents were trying to do when the tool failed (top `$mcp_intent` values), so the fix validates against real usage rather than the schema alone.@@ -189,9 +205,10 @@ Harness-level:- `scout-scratchpad-search` / `-remember` / `-forget` — durable steering (regime, baselines, dedupe, report pointers).- `scout-runs-list` / `-runs-retrieve` — what prior runs found.- `scout-emit-report` / `scout-edit-report` — author a report / edit an existing one (the report-channel contract is in the harness prompt).+- `scout-record-output` — submit this run's `category_rollup` and `tool_session_share` records (the schema rides in the harness prompt).Deep-dive skills baked into the sandbox: `posthog:exploring-mcp-tool-quality`, `posthog:exploring-mcp-tool-usage`, `posthog:querying-posthog-data`.## Close out-One paragraph: the regime and report grain you found, which lenses you ran, which categories you filed or edited reports for — and which tools they carried, with why (failure / struggle / latency / bloat / gap) — what you remembered, what you ruled out. The harness saves this as the run summary; future runs read it via `scout-runs-list`. Don't write a separate "run metadata" scratchpad entry. "Looked but found nothing meaningful" is a real outcome.+One paragraph: the regime and report grain you found, which lenses you ran, how many records you submitted and of which kinds, which categories you filed or edited reports for — and which tools they carried, with why (failure / struggle / latency / bloat / session share / gap) — what you remembered, what you ruled out. The harness saves this as the run summary; future runs read it via `scout-runs-list`. Don't write a separate "run metadata" scratchpad entry. "Looked but found nothing meaningful" is a real outcome.diff --git a/products/signals/skills/signals-scout-mcp-tool-calls/references/metrics-dashboard.md b/products/signals/skills/signals-scout-mcp-tool-calls/references/metrics-dashboard.mdnew file mode 100644index 000000000000..edc1bcc58de5--- /dev/null+++ b/products/signals/skills/signals-scout-mcp-tool-calls/references/metrics-dashboard.md@@ -0,0 +1,127 @@+# Charting the metrics this scout records++Every run of this scout records its numbers as `$scout_structured_output` events (see the+**Record metrics** step in `SKILL.md`). This file is how you turn them into a dashboard. Nothing+here is part of a run — it is for whoever wants to watch the series.++Two filters belong on every query:++- `properties.skill_name = 'signals-scout-mcp-tool-calls'` — the event is shared with every other+ scout that records output.+- `properties.output_mcp_metrics_version = '1'` — definitions change; charts should not silently+ mix two of them. Raise this when the scout bumps the version.++Each record's scalar fields arrive flattened as `output_<field>` properties, so no JSON access is+needed. The two record kinds are told apart by `output_mcp_record_kind`.++**Every record is a rolling seven-day snapshot, and the scout runs more than once a day.** Summing+`calls` or `problem_tools` across a day adds the same window to itself once per run. Take the latest+snapshot of the day with `argMax(..., timestamp)`, or average, and label it.++**Plot the recorded rate, never a count of records.** A trend that counts `$scout_structured_output`+events broken down by category answers "how many times did the scout write about this category",+which is one per run and tells you nothing. The rate is a value in a property, so it needs an+aggregation over that property — `avg(output_mcp_error_rate_pct)`, not `count()`.++## 1. Error rate and struggle share per category over time++```sql+SELECT+ toStartOfDay(timestamp) AS day,+ toString(properties.output_mcp_category) AS category,+ avg(toFloat(properties.output_mcp_error_rate_pct)) AS error_rate_pct,+ avg(toFloat(properties.output_mcp_struggle_session_pct)) AS struggle_session_pct,+ argMax(toInt(properties.output_mcp_calls), timestamp) AS calls+FROM events+WHERE event = '$scout_structured_output'+ AND properties.skill_name = 'signals-scout-mcp-tool-calls'+ AND properties.output_mcp_metrics_version = '1'+ AND properties.output_mcp_record_kind = 'category_rollup'+ AND timestamp >= now() - INTERVAL 90 DAY+GROUP BY day, category+ORDER BY day DESC, calls DESC+```++`struggle_session_pct` is null for a category whose calls carry no session id, and `avg` skips+nulls, so those points are gaps rather than false zeroes. `calls` rides along as the weight: a category's+rate on a hundred calls is not comparable to one on fifty thousand. Filter `category = 'all'` for+the project-wide baseline on its own.++## 2. Session share per tool per source++```sql+SELECT+ toStartOfDay(timestamp) AS day,+ toString(properties.output_mcp_source) AS source,+ toString(properties.output_mcp_tool) AS tool,+ avg(toFloat(properties.output_mcp_session_share_pct)) AS session_share_pct,+ avg(toFloat(properties.output_mcp_share_pct_prior_window)) AS share_pct_prior_window,+ avg(toFloat(properties.output_mcp_calls_per_session)) AS calls_per_session+FROM events+WHERE event = '$scout_structured_output'+ AND properties.skill_name = 'signals-scout-mcp-tool-calls'+ AND properties.output_mcp_metrics_version = '1'+ AND properties.output_mcp_record_kind = 'tool_session_share'+ AND timestamp >= now() - INTERVAL 90 DAY+GROUP BY day, source, tool+ORDER BY day DESC, session_share_pct DESC+```++Add `AND properties.output_mcp_tool = '<tool>'` to watch one tool.++### Alerting on a step change for a named tool++The jump is the shape that matters, not the level, so alert on the difference between the current+share and the prior-window share the scout recorded next to it. Compute the delta in SQL and save+it as a single-series insight, then put a threshold alert on that series:++```sql+SELECT+ toStartOfDay(timestamp) AS day,+ avg(toFloat(properties.output_mcp_session_share_pct) - toFloat(properties.output_mcp_share_pct_prior_window)) AS share_delta_pct+FROM events+WHERE event = '$scout_structured_output'+ AND properties.skill_name = 'signals-scout-mcp-tool-calls'+ AND properties.output_mcp_metrics_version = '1'+ AND properties.output_mcp_record_kind = 'tool_session_share'+ AND properties.output_mcp_source = '<source>'+ AND properties.output_mcp_tool = '<tool>'+ AND isNotNull(properties.output_mcp_share_pct_prior_window)+ AND timestamp >= now() - INTERVAL 90 DAY+GROUP BY day+ORDER BY day DESC+```++The null filter drops runs where the prior window had too few sessions to be a baseline, so a+surface a team is only starting to use does not alert on every tool. Pick the threshold from the+tool's own history rather than a round number: a tool that has sat at 30% for a month should+alert on a jump of twenty points, not on crossing 90%. A trends insight with two series and the+formula `A - B` does the same job if you prefer the UI, with series A on the current share and+series B on the prior share.++## 3. Problem tools and what the scout decided++```sql+SELECT+ toStartOfDay(timestamp) AS day,+ toString(properties.output_mcp_category) AS category,+ toString(properties.output_mcp_report_action) AS report_action,+ argMax(toInt(properties.output_mcp_problem_tools), timestamp) AS problem_tools+FROM events+WHERE event = '$scout_structured_output'+ AND properties.skill_name = 'signals-scout-mcp-tool-calls'+ AND properties.output_mcp_metrics_version = '1'+ AND properties.output_mcp_record_kind = 'category_rollup'+ AND properties.output_mcp_category != 'all'+ AND timestamp >= now() - INTERVAL 90 DAY+GROUP BY day, category, report_action+ORDER BY day DESC, problem_tools DESC+```++This is the tile that makes the scout auditable: the problem-tool count next to what it did about+it. A category with problem tools and a long run of `below_bar` means the bar is set wrong, or the+tools are chronically noisy and the scout is right to hold. A run of `skipped_live_report` means a+report has been open a while and nobody has acted on it.++For the decision mix on its own, break `count()` down by `output_mcp_report_action` — here the+count is the measure, because each record is one decision.diff --git a/products/signals/skills/signals-scout-mcp-tool-calls/references/queries.md b/products/signals/skills/signals-scout-mcp-tool-calls/references/queries.mdindex 4d40e0911d7b..4befb1b44e00 100644--- a/products/signals/skills/signals-scout-mcp-tool-calls/references/queries.md+++ b/products/signals/skills/signals-scout-mcp-tool-calls/references/queries.md@@ -380,9 +380,10 @@ Read it:- `HAVING problem_tools > 0` keeps healthy categories out of the result — they get no report,so they don't belong in the report-grain rollup.-- This is aggregation, not detection — it catches the failure shape only. Struggle (query 2)- and latency (query 4) candidates join their category via the `category` column those queries- now carry; a category whose only problem tools are struggle/latency won't appear here (the+- This is aggregation, not detection — it catches the failure shape only. Struggle (query 2),+ latency (query 4) and session-share (query 10) candidates join their category via the+ `category` column those queries now carry, and they count toward the category's problem tools.+ A category whose only problem tools are struggle/latency/session-share won't appear here (the`HAVING` sees only the failure floor) — pull its `category_calls` denominators by re-runningwithout the `HAVING`, filtered to that category.- The `Uncategorized` bucket is dominated by bare `exec` rows (discovery verbs, wrapper@@ -390,3 +391,191 @@ Read it:sanity-check, not an owning team.- `category_error_rate_pct` alone is not a finding — a big category dilutes a broken tool; theper-tool entries in `problem_tool_details` are what clears the bar.++## 10. Session share — the "called too much" lens++The lens the other four miss: a tool the agent reaches for in a growing share of sessions costs+context and latency in every one of them, and every call succeeds, so failure rate, struggle,+latency, and bloat all read it as healthy. Ranks each tool by the share of its source's sessions+that called it at least once, against the same share over the preceding window. Deterministic —+no judge.++The surface is the bare `source` property (no `$` prefix) that the hono server stamps alongside+the `$mcp_*` fields: `self_driving`, `mcp`, `posthog_code`, `slack`, `posthog_ai`, `wizard`, `cli`.+It is the surface the call came from, not `$mcp_source`, which names the emitting SDK. External-SDK+projects do not stamp it, so those rows bucket as `unknown` and the lens degrades to one+project-wide denominator rather than breaking.++Both windows come out of one 14-day scan split by `is_current`, so the current and prior share are+measured the same way. The per-source denominator is a separate CTE joined back on `source_bucket` —+without it each tool would be scored against its own callers and every share would read 100%.++```sql+WITH per_session AS (+ SELECT+ coalesce(nullIf(nullIf(toString(properties.source), ''), 'None'), 'unknown') AS source_bucket,+ $session_id AS session,+ any(distinct_id) AS user,+ coalesce(nullIf(toString(properties.$mcp_exec_tool_call_name), ''), toString(properties.$mcp_tool_name)) AS tool,+ coalesce(nullIf(nullIf(toString(any(properties.$mcp_tool_category)), ''), 'None'), 'Uncategorized') AS category,+ timestamp >= now() - INTERVAL 7 DAY AS is_current,+ count() AS calls+ FROM events+ WHERE event = '$mcp_tool_call'+ AND properties.$mcp_source = 'posthog_mcp_analytics'+ AND $session_id != ''+ AND timestamp >= now() - INTERVAL 14 DAY+ GROUP BY source_bucket, session, tool, is_current+),+totals AS (+ SELECT+ source_bucket,+ uniqIf(session, is_current) AS sessions_total,+ uniqIf(session, NOT is_current) AS prior_sessions_total+ FROM per_session+ GROUP BY source_bucket+)+SELECT+ t.source_bucket AS source,+ t.tool AS tool,+ any(t.category) AS category,+ uniqIf(t.session, t.is_current) AS sessions_with_call,+ uniqIf(t.user, t.is_current) AS users_with_call,+ any(d.sessions_total) AS sessions_total,+ round(uniqIf(t.session, t.is_current) * 100.0 / nullIf(any(d.sessions_total), 0), 1) AS session_share_pct,+ round(avgIf(t.calls, t.is_current), 2) AS calls_per_session,+ any(d.prior_sessions_total) AS prior_sessions_total,+ if(any(d.prior_sessions_total) >= 20, round(uniqIf(t.session, NOT t.is_current) * 100.0 / any(d.prior_sessions_total), 1), NULL) AS share_pct_prior_window+FROM per_session AS t+JOIN totals AS d ON d.source_bucket = t.source_bucket+WHERE t.tool != 'exec'+GROUP BY source, tool+HAVING sessions_with_call >= 20+ORDER BY source, session_share_pct DESC+LIMIT 20 BY source+```++Read it:++- **The step change is the finding, not the level.** A tool that sits high and flat is doing its+ job. A tool whose share jumped between `share_pct_prior_window` and `session_share_pct`, across+ many sessions, is being advertised too eagerly — the fix hypothesis points at prompt or+ tool-description wording, not the handler.+- `share_pct_prior_window` is null when the source had fewer than 20 sessions in the prior window,+ the same floor as the current reach. A share over a few prior sessions reads as 0% or 100% by+ chance, so a surface a team is only starting to use would look like a jump on every tool. A null+ prior share is no baseline, so the row is not a step-change candidate. `prior_sessions_total` is+ the prior denominator to cite as evidence.+- `users_with_call` is the reach check. Twenty sessions from one `distinct_id` pass the session+ floor and are still one developer, so the single-user disqualifier applies here as everywhere.+ The category falls back to `Uncategorized` the same way query 9 does, because the record schema+ requires a string and one null category would reject the whole batch.+- Keep the source split. A tool called in most sessions of one surface and almost none of another+ localizes the cause to that surface's prompt.+- `calls_per_session` separates "reached for once, everywhere" from "hammered" — the latter is+ query 2's territory, and the two together say whether the tool is over-advertised or confusing.+- **Bare `exec` is filtered out.** The wrapper is present in nearly every session by construction,+ so it would top this query on every project and mean nothing. The `totals` CTE still counts its+ sessions, so the denominator stays every MCP session of the source. The same disqualifiers as+ everywhere else apply: a share over a handful of sessions is one developer.+- `LIMIT 20 BY source` returns the top 20 tools of each source, so one busy source cannot crowd+ another out. These rows are what the scout records as `tool_session_share` — the schema's fields+ only. `users_with_call` and `prior_sessions_total` are evidence for the report, not record fields,+ and the closed schema rejects a batch that carries them.+- For detection, rank by the change instead of the level. Run it again with+ `ORDER BY source, session_share_pct - share_pct_prior_window DESC NULLS LAST`, so a tool that+ rose from a low share is not cut behind tools that sit high and flat.++## 11. Category metrics — the `category_rollup` record++The source for every measured field of a `category_rollup` record: one row per category with any+traffic, healthy ones included, plus the project-wide `all` row. The per-tool queries cannot stand+in for it. Summing per-tool `users` or `sessions` counts a user once per tool they called, and a+per-tool p95 or struggle share does not average into a category value. Their volume floors also+drop tools, so they do not cover the whole category.++Every metric comes from raw rows at category grain. `tool_category` applies the header's+derivation rule, and joining it back to the raw rows keeps exec-routed calls that lack the property+in their tool's category. `arrayJoin` counts each row twice, once in its category and once in `all`,+so the baseline row is measured the same way in the same scan. Struggle uses query 2's session+definition: a session struggled in a category when any of its tools there was called three or more+times, or failed and was called again.++```sql+WITH calls AS (+ SELECT+ coalesce(nullIf(toString(properties.$mcp_exec_tool_call_name), ''), toString(properties.$mcp_tool_name)) AS tool,+ properties.$mcp_tool_category AS raw_category,+ $session_id AS session,+ distinct_id,+ toBool(properties.$mcp_is_error) AS is_error,+ toFloat(properties.$mcp_duration_ms) AS duration_ms+ FROM events+ WHERE event = '$mcp_tool_call'+ AND properties.$mcp_source = 'posthog_mcp_analytics'+ AND timestamp >= now() - INTERVAL 7 DAY+),+tool_category AS (+ SELECT+ tool,+ coalesce(nullIf(nullIf(toString(any(raw_category)), ''), 'None'), 'Uncategorized') AS category_bucket+ FROM calls+ GROUP BY tool+),+struggle AS (+ SELECT+ category,+ count() AS measured_sessions,+ countIf(session_struggled) AS struggle_sessions+ FROM (+ SELECT+ arrayJoin([c.category_bucket, 'all']) AS category,+ s.session AS session,+ max(s.session_calls >= 3 OR (s.session_errors > 0 AND s.session_calls > s.session_errors)) AS session_struggled+ FROM (+ SELECT session, tool, count() AS session_calls, countIf(is_error) AS session_errors+ FROM calls+ WHERE session != ''+ GROUP BY session, tool+ ) AS s+ JOIN tool_category AS c ON c.tool = s.tool+ GROUP BY category, session+ )+ GROUP BY category+),+volume AS (+ SELECT+ arrayJoin([c.category_bucket, 'all']) AS category,+ count() AS category_calls,+ countIf(k.is_error) AS category_errors,+ uniqIf(k.session, k.session != '') AS category_sessions,+ uniq(k.distinct_id) AS category_users,+ quantile(0.95)(k.duration_ms) AS category_p95_ms+ FROM calls AS k+ JOIN tool_category AS c ON c.tool = k.tool+ GROUP BY category+)+SELECT+ v.category AS category,+ v.category_calls AS calls,+ v.category_errors AS errors,+ v.category_sessions AS sessions,+ v.category_users AS users,+ round(v.category_errors * 100.0 / v.category_calls, 1) AS error_rate_pct,+ round(s.struggle_sessions * 100.0 / nullIf(s.measured_sessions, 0), 1) AS struggle_session_pct,+ round(v.category_p95_ms) AS p95_duration_ms,+ round(v.category_calls * 100.0 / max(v.category_calls) OVER (), 1) AS share_of_project_calls_pct+FROM volume AS v+LEFT JOIN struggle AS s ON s.category = v.category+ORDER BY calls DESC+```++Read it:++- Each column maps to the `mcp_`-prefixed record field of the same name. `mcp_problem_tools` and+ `mcp_report_action` are the scout's own judgment, so they do not come from here.+- `share_of_project_calls_pct` divides by the largest row, which is always `all`.+- `struggle_session_pct` is null for a category whose calls carry no `$session_id`, and+ `p95_duration_ms` is null when no call carries a duration. Record them as null, not zero.+- The numbers change only when the data does. Do not re-derive them from other queries on a run+ that skips this one, because a change of method shows on the chart as a step in the metric.diff --git a/products/signals/skills/signals-scout-mcp-tool-calls/references/structured-output.schema.json b/products/signals/skills/signals-scout-mcp-tool-calls/references/structured-output.schema.jsonnew file mode 100644index 000000000000..81d3d524fd02--- /dev/null+++ b/products/signals/skills/signals-scout-mcp-tool-calls/references/structured-output.schema.json@@ -0,0 +1,168 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "title": "MCP tool-calls scout record",+ "description": "One measurement the MCP tool-calls scout records per run. Two kinds: a per-category roll-up of the run's numbers, and a per-tool session-share row for the called-too-much lens.",+ "type": "object",+ "oneOf": [+ {+ "title": "category_rollup",+ "description": "One record per category with traffic in the window, healthy ones included, plus the project-wide baseline under category `all`. Subject is `category:<category>`.",+ "type": "object",+ "additionalProperties": false,+ "required": [+ "mcp_record_kind",+ "mcp_metrics_version",+ "mcp_regime",+ "mcp_window_days",+ "mcp_category",+ "mcp_calls",+ "mcp_errors",+ "mcp_sessions",+ "mcp_users",+ "mcp_error_rate_pct",+ "mcp_struggle_session_pct",+ "mcp_p95_duration_ms",+ "mcp_problem_tools",+ "mcp_share_of_project_calls_pct",+ "mcp_report_action"+ ],+ "properties": {+ "mcp_record_kind": { "const": "category_rollup", "description": "Discriminator." },+ "mcp_metrics_version": {+ "const": "1",+ "description": "Definition version. Charts filter on it, so bump it when a field's meaning changes."+ },+ "mcp_regime": {+ "enum": ["hono", "external_sdk"],+ "description": "Which telemetry regime the numbers came from (query 0)."+ },+ "mcp_window_days": {+ "type": "integer",+ "minimum": 1,+ "maximum": 90,+ "description": "Length of the measured window in days."+ },+ "mcp_category": {+ "type": "string",+ "maxLength": 100,+ "description": "Owning product category. `Uncategorized` for the no-category bucket, `all` for the project-wide baseline record."+ },+ "mcp_calls": {+ "type": "integer",+ "minimum": 0,+ "description": "Calls to the category's tools in the window."+ },+ "mcp_errors": { "type": "integer", "minimum": 0, "description": "Errored calls in the window." },+ "mcp_sessions": {+ "type": "integer",+ "minimum": 0,+ "description": "Distinct sessions that called the category's tools."+ },+ "mcp_users": {+ "type": "integer",+ "minimum": 0,+ "description": "Distinct users that called the category's tools."+ },+ "mcp_error_rate_pct": {+ "type": "number",+ "minimum": 0,+ "maximum": 100,+ "description": "Errors as a percentage of calls."+ },+ "mcp_struggle_session_pct": {+ "type": ["number", "null"],+ "minimum": 0,+ "maximum": 100,+ "description": "Percentage of the category's sessions with hammering or fail-then-retry (query 11). Null when none of the category's calls carry a session id."+ },+ "mcp_p95_duration_ms": {+ "type": ["number", "null"],+ "minimum": 0,+ "description": "p95 call duration in milliseconds (query 11). Null when none of the category's calls carry a duration."+ },+ "mcp_problem_tools": {+ "type": "integer",+ "minimum": 0,+ "description": "Distinct tools in the category that cleared any lens's per-tool bar this run, session share included."+ },+ "mcp_share_of_project_calls_pct": {+ "type": "number",+ "minimum": 0,+ "maximum": 100,+ "description": "The category's share of all $mcp_tool_call volume in the window."+ },+ "mcp_report_action": {+ "enum": ["authored", "edited", "skipped_live_report", "below_bar", "none"],+ "description": "What the scout did with this category this run."+ }+ }+ },+ {+ "title": "tool_session_share",+ "description": "One record per tool per source for the top tools by session share — the called-too-much lens (query 10). Subject is `tool:<tool>:<source>`.",+ "type": "object",+ "additionalProperties": false,+ "required": [+ "mcp_record_kind",+ "mcp_metrics_version",+ "mcp_tool",+ "mcp_source",+ "mcp_category",+ "mcp_sessions_with_call",+ "mcp_sessions_total",+ "mcp_session_share_pct",+ "mcp_calls_per_session",+ "mcp_share_pct_prior_window"+ ],+ "properties": {+ "mcp_record_kind": { "const": "tool_session_share", "description": "Discriminator." },+ "mcp_metrics_version": {+ "const": "1",+ "description": "Definition version. Charts filter on it, so bump it when a field's meaning changes."+ },+ "mcp_tool": {+ "type": "string",+ "maxLength": 100,+ "description": "Inner tool name, with the exec dispatcher unwrapped as the cookbook does."+ },+ "mcp_source": {+ "type": "string",+ "maxLength": 40,+ "description": "Calling surface, for example self_driving, mcp, posthog_code, slack, posthog_ai, wizard."+ },+ "mcp_category": {+ "type": "string",+ "maxLength": 100,+ "description": "The tool's owning product category, or `Uncategorized`."+ },+ "mcp_sessions_with_call": {+ "type": "integer",+ "minimum": 0,+ "description": "Sessions with at least one call to this tool."+ },+ "mcp_sessions_total": {+ "type": "integer",+ "minimum": 0,+ "description": "All MCP sessions for that source in the window."+ },+ "mcp_session_share_pct": {+ "type": "number",+ "minimum": 0,+ "maximum": 100,+ "description": "Sessions with a call as a percentage of all sessions for the source."+ },+ "mcp_calls_per_session": {+ "type": "number",+ "minimum": 0,+ "description": "Mean calls per session that used the tool."+ },+ "mcp_share_pct_prior_window": {+ "type": ["number", "null"],+ "minimum": 0,+ "maximum": 100,+ "description": "The same share over the preceding window, for a step-change read. Null when the source had fewer than 20 sessions in the prior window."+ }+ }+ }+ ]+}diff --git a/products/signals/skills/working-with-scouts/SKILL.md b/products/signals/skills/working-with-scouts/SKILL.mdindex 4ab452a526d5..bdf7b9cebb2a 100644--- a/products/signals/skills/working-with-scouts/SKILL.md+++ b/products/signals/skills/working-with-scouts/SKILL.md@@ -67,14 +67,14 @@ An untended inbox doesn't just decay; it switches the fleet off.When you want something watched, pick the cheapest path that gets it watched — most jobs don't need a new scout:-| Situation | Do this |-| ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| A canonical scout already covers the surface | Nothing to build: confirm it's enabled, and leave it a **note** if you want its attention pointed somewhere specific. |-| The surface is covered but you want a temporary or specific focus | Leave a **note** (optionally with `expires_at`): "watch the EU signup funnel this week", "we shipped a new checkout Tuesday, shifts after that are expected". |-| A covered scout keeps missing (or over-reporting) something structural | **Adapt** it: a disqualifier, threshold, or scope edit via `authoring-scouts`. Prefer a new differently-named scout for purely additive behavior, since editing a canonical scout's row marks it diverged and stops upstream improvements. |-| No scout covers it (a custom event, a niche funnel, an external system) | **Author a custom scout** via `authoring-scouts` (`posthog:scout-create`). In the inbox's scouts tab, the "Suggested for this project" strip proposes scouts from the project's own data, and "Suggest a scout" opens a chat that drafts one. A custom suggestion lands on the same create call; a canonical suggestion is an existing PostHog scout that is switched off, so accepting it enables that config rather than creating a new scout. |-| You want a recurring **metric**, not reports: a subjective quality/classification score no query can compute | **Author a measurement scout** on the structured-output channel: it judges a sample every run and records schema-validated `$scout_structured_output` events you chart in insights (and a workflow can act on), filing a report only on a material shift. See the recurring measurement / LLM-judge pattern in `authoring-scouts`. |-| You want an answer _now_, once | Don't use a scout at all: just query the data directly. Scouts are for standing watches, not one-off questions. |+| Situation | Do this |+| ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| A canonical scout already covers the surface | Nothing to build: confirm it's enabled, and leave it a **note** if you want its attention pointed somewhere specific. |+| The surface is covered but you want a temporary or specific focus | Leave a **note** (optionally with `expires_at`): "watch the EU signup funnel this week", "we shipped a new checkout Tuesday, shifts after that are expected". |+| A covered scout keeps missing (or over-reporting) something structural | **Adapt** it: a disqualifier, threshold, or scope edit via `authoring-scouts`. Prefer a new differently-named scout for purely additive behavior, since editing a canonical scout's row marks it diverged and stops upstream improvements. |+| No scout covers it (a custom event, a niche funnel, an external system) | **Author a custom scout** via `authoring-scouts` (`posthog:scout-create`). In the inbox's scouts tab, the "Suggested for this project" strip proposes scouts from the project's own data, and "Suggest a scout" opens a chat that drafts one. A custom suggestion lands on the same create call; a canonical suggestion is an existing PostHog scout that is switched off, so accepting it enables that config rather than creating a new scout. |+| You want a recurring **metric**, not reports: a subjective quality/classification score no query can compute | **Author a measurement scout** on the structured-output channel: it judges a sample every run and records schema-validated `$scout_structured_output` events you chart in insights (and a workflow can act on), filing a report only on a material shift. See the recurring measurement / LLM-judge pattern in `authoring-scouts`, and `signals-scout-mcp-tool-calls` for a shipped scout that already records one (its `references/metrics-dashboard.md` is the chart recipe). |+| You want an answer _now_, once | Don't use a scout at all: just query the data directly. Scouts are for standing watches, not one-off questions. |[`references/delegation-recipes.md`](references/delegation-recipes.md) has worked recipes for the common asks — watching a freshly shipped event, a time-boxed funnel watch, a daily digest, an external status page, quieting a noisy fleet, and more.