: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
fix(mcp): point agents at built-in skills instead of the skills store (#99476)
Marcel Poelker0a6154cbbc48
diff --git a/products/replay_vision/mcp/tools.yaml b/products/replay_vision/mcp/tools.yamlindex 53158be0374c..9b9581372f31 100644--- a/products/replay_vision/mcp/tools.yaml+++ b/products/replay_vision/mcp/tools.yaml@@ -269,9 +269,17 @@ tools:`credit_limit` to cap what this one scanner can spend per billing period, so it cannot starve the org'sother scanners. The scanner stops scanning once the credits left cannot cover another observation, andresumes when the period resets. To get notified about what the scanner finds, add a scout digest or an alert- from the scanner's Scouts and Alerts tabs. For a scanner scoped to one experiment's exposed sessions, load- the `scanning-experiments-with-replay-vision` skill first — it derives the query from the experiment's- exposure criteria.+ from the scanner's Scouts and Alerts tabs. For a scanner scoped to one experiment's exposed sessions, set+ `experiment_targeting` to `{"experiment_id": <id>, "variant": null}` (or one variant key) and leave exposure+ out of `query`: the API derives the person-scoped exposure filter server-side, and rejects an+ `experiment_exposure` filter set directly in `query`. Pass the same `experiment_targeting` to+ `vision-scanners-estimate-create`, so the estimate counts only exposed sessions. Create with `enabled:+ false`, so you can preview the prompt on real sessions first. The `scanning-experiments-with-replay-vision`+ skill carries the full flow (status guards, prompt templates, sizing). It is a built-in PostHog skill, not a+ team skill in the skills store, so do not fetch it with `skill-get`. Load it with `learn+ posthog:scanning-experiments-with-replay-vision` when the `learn` command is available, or read it from your+ installed PostHog skills (`.agents/skills/`). If you have neither, the facts above are sufficient to+ continue.agent_note: >A new scanner runs the prompt as written, and the first sweep is where its weaknesses show. Tell the personthat rating its results thumbs up or down turns into a config recommendation they can review, and that@@ -324,7 +332,8 @@ tools:Preview how many observations a proposed scanner would generate, and what they would cost, before saving it.Send a `query` (`RecordingsQuery` shape; `date_from`/`date_to` are ignored — the estimate uses a fixed30-day lookback) plus the proposed `sampling_rate`, `sampling_mode` and `model`, and `scanner_id` when- re-estimating an existing scanner so its own projection isn't double-counted. Returns+ re-estimating an existing scanner so its own projection isn't double-counted. For an experiment scanner,+ pass the same `experiment_targeting` you will save, so the estimate counts only exposed sessions. Returns`matched_sessions_in_window`, the `window_days` it was measured over, `estimated_observations_per_month`,`credits_per_observation`, `estimated_credits_per_month`, and `other_enabled_scanners_monthly_credits` (theorg's other enabled scanners' projected spend). Enabled scanners sweep every 5 minutes, so a broad query candiff --git a/products/skills/mcp/tools.yaml b/products/skills/mcp/tools.yamlindex 01d56deae801..8abd11ca7537 100644--- a/products/skills/mcp/tools.yaml+++ b/products/skills/mcp/tools.yaml@@ -165,12 +165,14 @@ tools:title: Get skilldescription: >Get a specific agent skill by name, including its full body content, metadata, and file manifest. Follows- the Agent Skills specification (agentskills.io). The response always includes body_total_length (the full- body length in characters) — if the body you received is shorter than that, it was truncated in transit, so- page through it with body_offset and body_length and continue from body_next_offset until it is null. To- link a user to this skill in the PostHog app, build the URL from the skill `name`, not its `id`:- `/llm-analytics/skills/<name>` (e.g. `/llm-analytics/skills/pr-shepherd`). The `id` (UUID) is not a valid- route segment and will 404.+ the Agent Skills specification (agentskills.io). This store holds only the skills your team published.+ Built-in PostHog skills (for example `querying-posthog-data`) are not in it. Load a built-in skill with+ `learn posthog:<skill>` when the `learn` command is available, or read it from your installed PostHog skills+ (`.agents/skills/`). The response always includes body_total_length (the full body length in characters) —+ if the body you received is shorter than that, it was truncated in transit, so page through it with+ body_offset and body_length and continue from body_next_offset until it is null. To link a user to this+ skill in the PostHog app, build the URL from the skill `name`, not its `id`: `/llm-analytics/skills/<name>`+ (e.g. `/llm-analytics/skills/pr-shepherd`). The `id` (UUID) is not a valid route segment and will 404.skill-list:operation: llm_skills_listenabled: true@@ -184,9 +186,12 @@ tools:description: >List all agent skills stored for the current team. Returns skill names and descriptions for discovery — usedescriptions to determine which skill to fetch for a given task. Does not return skill body content (use- skill-get to fetch full content). To link a user to a skill in the PostHog app, build the URL from the skill- `name`, not its `id`: `/llm-analytics/skills/<name>` (e.g. `/llm-analytics/skills/pr-shepherd`). The `id`- (UUID) is not a valid route segment and will 404.+ skill-get to fetch full content). This store holds only the skills your team published. Built-in PostHog+ skills (for example `querying-posthog-data`) are not in it. Load a built-in skill with `learn+ posthog:<skill>` when the `learn` command is available, or read it from your installed PostHog skills+ (`.agents/skills/`). To link a user to a skill in the PostHog app, build the URL from the skill `name`, not+ its `id`: `/llm-analytics/skills/<name>` (e.g. `/llm-analytics/skills/pr-shepherd`). The `id` (UUID) is not+ a valid route segment and will 404.skill-rename:operation: llm_skills_name_rename_createenabled: truediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex a52424b5985d..cc6571edce51 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -10567,7 +10567,7 @@}},"skill-get": {- "description": "Get a specific agent skill by name, including its full body content, metadata, and file manifest. Follows the Agent Skills specification (agentskills.io). The response always includes body_total_length (the full body length in characters) — if the body you received is shorter than that, it was truncated in transit, so page through it with body_offset and body_length and continue from body_next_offset until it is null. To link a user to this skill in the PostHog app, build the URL from the skill `name`, not its `id`: `/llm-analytics/skills/<name>` (e.g. `/llm-analytics/skills/pr-shepherd`). The `id` (UUID) is not a valid route segment and will 404.",+ "description": "Get a specific agent skill by name, including its full body content, metadata, and file manifest. Follows the Agent Skills specification (agentskills.io). This store holds only the skills your team published. Built-in PostHog skills (for example `querying-posthog-data`) are not in it. Load a built-in skill with `learn posthog:<skill>` when the `learn` command is available, or read it from your installed PostHog skills (`.agents/skills/`). The response always includes body_total_length (the full body length in characters) — if the body you received is shorter than that, it was truncated in transit, so page through it with body_offset and body_length and continue from body_next_offset until it is null. To link a user to this skill in the PostHog app, build the URL from the skill `name`, not its `id`: `/llm-analytics/skills/<name>` (e.g. `/llm-analytics/skills/pr-shepherd`). The `id` (UUID) is not a valid route segment and will 404.","category": "Skills","feature": "skills","summary": "Get skill",@@ -10581,7 +10581,7 @@}},"skill-list": {- "description": "List all agent skills stored for the current team. Returns skill names and descriptions for discovery — use descriptions to determine which skill to fetch for a given task. Does not return skill body content (use skill-get to fetch full content). To link a user to a skill in the PostHog app, build the URL from the skill `name`, not its `id`: `/llm-analytics/skills/<name>` (e.g. `/llm-analytics/skills/pr-shepherd`). The `id` (UUID) is not a valid route segment and will 404.",+ "description": "List all agent skills stored for the current team. Returns skill names and descriptions for discovery — use descriptions to determine which skill to fetch for a given task. Does not return skill body content (use skill-get to fetch full content). This store holds only the skills your team published. Built-in PostHog skills (for example `querying-posthog-data`) are not in it. Load a built-in skill with `learn posthog:<skill>` when the `learn` command is available, or read it from your installed PostHog skills (`.agents/skills/`). To link a user to a skill in the PostHog app, build the URL from the skill `name`, not its `id`: `/llm-analytics/skills/<name>` (e.g. `/llm-analytics/skills/pr-shepherd`). The `id` (UUID) is not a valid route segment and will 404.","category": "Skills","feature": "skills","summary": "List skills",@@ -12090,7 +12090,7 @@}},"vision-scanners-create": {- "description": "Create a replay vision scanner. Pick a `scanner_type` — `monitor` (open-ended observations), `classifier` (assign a tag from a fixed label set), `scorer` (numeric rubric), or `summarizer` (free-text summary, embedded for search) — and fill `scanner_config` to match: all types need a `prompt`; monitors optionally set `allow_inconclusive`; classifiers also need `tags` (and optionally `multi_label`, `allow_freeform_tags`); scorers also need `scale`; summarizers optionally set `length`. Unknown `scanner_config` keys are rejected. `query` is a `RecordingsQuery` shape that defines which sessions the scanner watches — `date_from` and `date_to` are ignored (the schedule controls time). `sampling_mode` is a quality pre-filter over matched sessions (`focused` / `balanced` / `comprehensive`, default `comprehensive`) and `sampling_rate` is a 0..1 random downsample applied after it (default 1.0). `model` chooses the LLM and sets the credit price of every observation. Names must be unique within the team. Before creating a broad scanner (a permissive `query`, loose `sampling_mode`, and/or high `sampling_rate`), first call `vision-scanners-estimate-create` to project its monthly credit spend and `vision-quota-retrieve` to check the org's remaining budget — an enabled scanner sweeps matching recordings every 5 minutes, and creation itself does not check quota, so a too-broad scanner can exhaust the budget on its first sweeps. Set `credit_limit` to cap what this one scanner can spend per billing period, so it cannot starve the org's other scanners. The scanner stops scanning once the credits left cannot cover another observation, and resumes when the period resets. To get notified about what the scanner finds, add a scout digest or an alert from the scanner's Scouts and Alerts tabs. For a scanner scoped to one experiment's exposed sessions, load the `scanning-experiments-with-replay-vision` skill first — it derives the query from the experiment's exposure criteria.",+ "description": "Create a replay vision scanner. Pick a `scanner_type` — `monitor` (open-ended observations), `classifier` (assign a tag from a fixed label set), `scorer` (numeric rubric), or `summarizer` (free-text summary, embedded for search) — and fill `scanner_config` to match: all types need a `prompt`; monitors optionally set `allow_inconclusive`; classifiers also need `tags` (and optionally `multi_label`, `allow_freeform_tags`); scorers also need `scale`; summarizers optionally set `length`. Unknown `scanner_config` keys are rejected. `query` is a `RecordingsQuery` shape that defines which sessions the scanner watches — `date_from` and `date_to` are ignored (the schedule controls time). `sampling_mode` is a quality pre-filter over matched sessions (`focused` / `balanced` / `comprehensive`, default `comprehensive`) and `sampling_rate` is a 0..1 random downsample applied after it (default 1.0). `model` chooses the LLM and sets the credit price of every observation. Names must be unique within the team. Before creating a broad scanner (a permissive `query`, loose `sampling_mode`, and/or high `sampling_rate`), first call `vision-scanners-estimate-create` to project its monthly credit spend and `vision-quota-retrieve` to check the org's remaining budget — an enabled scanner sweeps matching recordings every 5 minutes, and creation itself does not check quota, so a too-broad scanner can exhaust the budget on its first sweeps. Set `credit_limit` to cap what this one scanner can spend per billing period, so it cannot starve the org's other scanners. The scanner stops scanning once the credits left cannot cover another observation, and resumes when the period resets. To get notified about what the scanner finds, add a scout digest or an alert from the scanner's Scouts and Alerts tabs. For a scanner scoped to one experiment's exposed sessions, set `experiment_targeting` to `{\"experiment_id\": <id>, \"variant\": null}` (or one variant key) and leave exposure out of `query`: the API derives the person-scoped exposure filter server-side, and rejects an `experiment_exposure` filter set directly in `query`. Pass the same `experiment_targeting` to `vision-scanners-estimate-create`, so the estimate counts only exposed sessions. Create with `enabled: false`, so you can preview the prompt on real sessions first. The `scanning-experiments-with-replay-vision` skill carries the full flow (status guards, prompt templates, sizing). It is a built-in PostHog skill, not a team skill in the skills store, so do not fetch it with `skill-get`. Load it with `learn posthog:scanning-experiments-with-replay-vision` when the `learn` command is available, or read it from your installed PostHog skills (`.agents/skills/`). If you have neither, the facts above are sufficient to continue.","category": "Replay vision","feature": "replay_vision","summary": "Create replay vision scanner",@@ -12119,7 +12119,7 @@}},"vision-scanners-estimate-create": {- "description": "Preview how many observations a proposed scanner would generate, and what they would cost, before saving it. Send a `query` (`RecordingsQuery` shape; `date_from`/`date_to` are ignored — the estimate uses a fixed 30-day lookback) plus the proposed `sampling_rate`, `sampling_mode` and `model`, and `scanner_id` when re-estimating an existing scanner so its own projection isn't double-counted. Returns `matched_sessions_in_window`, the `window_days` it was measured over, `estimated_observations_per_month`, `credits_per_observation`, `estimated_credits_per_month`, and `other_enabled_scanners_monthly_credits` (the org's other enabled scanners' projected spend). Enabled scanners sweep every 5 minutes, so a broad query can exhaust the budget quickly — run this before `vision-scanners-create` and compare the *credit* figures (never raw observation counts) against `remaining` from `vision-quota-retrieve`. These projections are per month while `remaining` covers only the rest of the current period, so prorate them by the days left between `period_start` and `period_end` before comparing.",+ "description": "Preview how many observations a proposed scanner would generate, and what they would cost, before saving it. Send a `query` (`RecordingsQuery` shape; `date_from`/`date_to` are ignored — the estimate uses a fixed 30-day lookback) plus the proposed `sampling_rate`, `sampling_mode` and `model`, and `scanner_id` when re-estimating an existing scanner so its own projection isn't double-counted. For an experiment scanner, pass the same `experiment_targeting` you will save, so the estimate counts only exposed sessions. Returns `matched_sessions_in_window`, the `window_days` it was measured over, `estimated_observations_per_month`, `credits_per_observation`, `estimated_credits_per_month`, and `other_enabled_scanners_monthly_credits` (the org's other enabled scanners' projected spend). Enabled scanners sweep every 5 minutes, so a broad query can exhaust the budget quickly — run this before `vision-scanners-create` and compare the *credit* figures (never raw observation counts) against `remaining` from `vision-quota-retrieve`. These projections are per month while `remaining` covers only the rest of the current period, so prorate them by the days left between `period_start` and `period_end` before comparing.","category": "Replay vision","feature": "replay_vision","summary": "Estimate replay vision scanner volume",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex fcf30572e944..0b5814d78837 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -11139,7 +11139,7 @@}},"skill-get": {- "description": "Get a specific agent skill by name, including its full body content, metadata, and file manifest. Follows the Agent Skills specification (agentskills.io). The response always includes body_total_length (the full body length in characters) — if the body you received is shorter than that, it was truncated in transit, so page through it with body_offset and body_length and continue from body_next_offset until it is null. To link a user to this skill in the PostHog app, build the URL from the skill `name`, not its `id`: `/llm-analytics/skills/<name>` (e.g. `/llm-analytics/skills/pr-shepherd`). The `id` (UUID) is not a valid route segment and will 404.",+ "description": "Get a specific agent skill by name, including its full body content, metadata, and file manifest. Follows the Agent Skills specification (agentskills.io). This store holds only the skills your team published. Built-in PostHog skills (for example `querying-posthog-data`) are not in it. Load a built-in skill with `learn posthog:<skill>` when the `learn` command is available, or read it from your installed PostHog skills (`.agents/skills/`). The response always includes body_total_length (the full body length in characters) — if the body you received is shorter than that, it was truncated in transit, so page through it with body_offset and body_length and continue from body_next_offset until it is null. To link a user to this skill in the PostHog app, build the URL from the skill `name`, not its `id`: `/llm-analytics/skills/<name>` (e.g. `/llm-analytics/skills/pr-shepherd`). The `id` (UUID) is not a valid route segment and will 404.","category": "Skills","feature": "skills","summary": "Get skill",@@ -11153,7 +11153,7 @@}},"skill-list": {- "description": "List all agent skills stored for the current team. Returns skill names and descriptions for discovery — use descriptions to determine which skill to fetch for a given task. Does not return skill body content (use skill-get to fetch full content). To link a user to a skill in the PostHog app, build the URL from the skill `name`, not its `id`: `/llm-analytics/skills/<name>` (e.g. `/llm-analytics/skills/pr-shepherd`). The `id` (UUID) is not a valid route segment and will 404.",+ "description": "List all agent skills stored for the current team. Returns skill names and descriptions for discovery — use descriptions to determine which skill to fetch for a given task. Does not return skill body content (use skill-get to fetch full content). This store holds only the skills your team published. Built-in PostHog skills (for example `querying-posthog-data`) are not in it. Load a built-in skill with `learn posthog:<skill>` when the `learn` command is available, or read it from your installed PostHog skills (`.agents/skills/`). To link a user to a skill in the PostHog app, build the URL from the skill `name`, not its `id`: `/llm-analytics/skills/<name>` (e.g. `/llm-analytics/skills/pr-shepherd`). The `id` (UUID) is not a valid route segment and will 404.","category": "Skills","feature": "skills","summary": "List skills",@@ -12735,7 +12735,7 @@}},"vision-scanners-create": {- "description": "Create a replay vision scanner. Pick a `scanner_type` — `monitor` (open-ended observations), `classifier` (assign a tag from a fixed label set), `scorer` (numeric rubric), or `summarizer` (free-text summary, embedded for search) — and fill `scanner_config` to match: all types need a `prompt`; monitors optionally set `allow_inconclusive`; classifiers also need `tags` (and optionally `multi_label`, `allow_freeform_tags`); scorers also need `scale`; summarizers optionally set `length`. Unknown `scanner_config` keys are rejected. `query` is a `RecordingsQuery` shape that defines which sessions the scanner watches — `date_from` and `date_to` are ignored (the schedule controls time). `sampling_mode` is a quality pre-filter over matched sessions (`focused` / `balanced` / `comprehensive`, default `comprehensive`) and `sampling_rate` is a 0..1 random downsample applied after it (default 1.0). `model` chooses the LLM and sets the credit price of every observation. Names must be unique within the team. Before creating a broad scanner (a permissive `query`, loose `sampling_mode`, and/or high `sampling_rate`), first call `vision-scanners-estimate-create` to project its monthly credit spend and `vision-quota-retrieve` to check the org's remaining budget — an enabled scanner sweeps matching recordings every 5 minutes, and creation itself does not check quota, so a too-broad scanner can exhaust the budget on its first sweeps. Set `credit_limit` to cap what this one scanner can spend per billing period, so it cannot starve the org's other scanners. The scanner stops scanning once the credits left cannot cover another observation, and resumes when the period resets. To get notified about what the scanner finds, add a scout digest or an alert from the scanner's Scouts and Alerts tabs. For a scanner scoped to one experiment's exposed sessions, load the `scanning-experiments-with-replay-vision` skill first — it derives the query from the experiment's exposure criteria.",+ "description": "Create a replay vision scanner. Pick a `scanner_type` — `monitor` (open-ended observations), `classifier` (assign a tag from a fixed label set), `scorer` (numeric rubric), or `summarizer` (free-text summary, embedded for search) — and fill `scanner_config` to match: all types need a `prompt`; monitors optionally set `allow_inconclusive`; classifiers also need `tags` (and optionally `multi_label`, `allow_freeform_tags`); scorers also need `scale`; summarizers optionally set `length`. Unknown `scanner_config` keys are rejected. `query` is a `RecordingsQuery` shape that defines which sessions the scanner watches — `date_from` and `date_to` are ignored (the schedule controls time). `sampling_mode` is a quality pre-filter over matched sessions (`focused` / `balanced` / `comprehensive`, default `comprehensive`) and `sampling_rate` is a 0..1 random downsample applied after it (default 1.0). `model` chooses the LLM and sets the credit price of every observation. Names must be unique within the team. Before creating a broad scanner (a permissive `query`, loose `sampling_mode`, and/or high `sampling_rate`), first call `vision-scanners-estimate-create` to project its monthly credit spend and `vision-quota-retrieve` to check the org's remaining budget — an enabled scanner sweeps matching recordings every 5 minutes, and creation itself does not check quota, so a too-broad scanner can exhaust the budget on its first sweeps. Set `credit_limit` to cap what this one scanner can spend per billing period, so it cannot starve the org's other scanners. The scanner stops scanning once the credits left cannot cover another observation, and resumes when the period resets. To get notified about what the scanner finds, add a scout digest or an alert from the scanner's Scouts and Alerts tabs. For a scanner scoped to one experiment's exposed sessions, set `experiment_targeting` to `{\"experiment_id\": <id>, \"variant\": null}` (or one variant key) and leave exposure out of `query`: the API derives the person-scoped exposure filter server-side, and rejects an `experiment_exposure` filter set directly in `query`. Pass the same `experiment_targeting` to `vision-scanners-estimate-create`, so the estimate counts only exposed sessions. Create with `enabled: false`, so you can preview the prompt on real sessions first. The `scanning-experiments-with-replay-vision` skill carries the full flow (status guards, prompt templates, sizing). It is a built-in PostHog skill, not a team skill in the skills store, so do not fetch it with `skill-get`. Load it with `learn posthog:scanning-experiments-with-replay-vision` when the `learn` command is available, or read it from your installed PostHog skills (`.agents/skills/`). If you have neither, the facts above are sufficient to continue.","category": "Replay vision","feature": "replay_vision","summary": "Create replay vision scanner",@@ -12764,7 +12764,7 @@}},"vision-scanners-estimate-create": {- "description": "Preview how many observations a proposed scanner would generate, and what they would cost, before saving it. Send a `query` (`RecordingsQuery` shape; `date_from`/`date_to` are ignored — the estimate uses a fixed 30-day lookback) plus the proposed `sampling_rate`, `sampling_mode` and `model`, and `scanner_id` when re-estimating an existing scanner so its own projection isn't double-counted. Returns `matched_sessions_in_window`, the `window_days` it was measured over, `estimated_observations_per_month`, `credits_per_observation`, `estimated_credits_per_month`, and `other_enabled_scanners_monthly_credits` (the org's other enabled scanners' projected spend). Enabled scanners sweep every 5 minutes, so a broad query can exhaust the budget quickly — run this before `vision-scanners-create` and compare the *credit* figures (never raw observation counts) against `remaining` from `vision-quota-retrieve`. These projections are per month while `remaining` covers only the rest of the current period, so prorate them by the days left between `period_start` and `period_end` before comparing.",+ "description": "Preview how many observations a proposed scanner would generate, and what they would cost, before saving it. Send a `query` (`RecordingsQuery` shape; `date_from`/`date_to` are ignored — the estimate uses a fixed 30-day lookback) plus the proposed `sampling_rate`, `sampling_mode` and `model`, and `scanner_id` when re-estimating an existing scanner so its own projection isn't double-counted. For an experiment scanner, pass the same `experiment_targeting` you will save, so the estimate counts only exposed sessions. Returns `matched_sessions_in_window`, the `window_days` it was measured over, `estimated_observations_per_month`, `credits_per_observation`, `estimated_credits_per_month`, and `other_enabled_scanners_monthly_credits` (the org's other enabled scanners' projected spend). Enabled scanners sweep every 5 minutes, so a broad query can exhaust the budget quickly — run this before `vision-scanners-create` and compare the *credit* figures (never raw observation counts) against `remaining` from `vision-quota-retrieve`. These projections are per month while `remaining` covers only the rest of the current period, so prorate them by the days left between `period_start` and `period_end` before comparing.","category": "Replay vision","feature": "replay_vision","summary": "Estimate replay vision scanner volume",diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex b8a915f525c1..aa4e5b52a6ec 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -34,8 +34,8 @@ import {} from '@/tools/exec'import { EXECUTE_SQL_TOOL_NAME } from '@/tools/posthogAiTools/executeSql'import { createRenderUiTool } from '@/tools/render-ui'-import { skillAnalyticsProperties } from '@/tools/skills/analytics'-import { formatSkillLookupMiss } from '@/tools/skills/notFound'+import { skillAnalyticsProperties, skillLookupMissProperties } from '@/tools/skills/analytics'+import { type BuiltInSkillHint, formatSkillLookupMiss, type SkillLookupMissKind } from '@/tools/skills/notFound'import type { Context, Tool, ZodObjectAny } from '@/tools/types'import {@@ -70,6 +70,8 @@ interface ExecMetricState {* a normal result, so the canonical event still records the failure.*/innerFailure: { error: unknown } | undefined+ /** Which kind of skill lookup missed, when the dispatcher rewrote a 404. */+ skillLookupMissKind: SkillLookupMissKind | undefined}/**@@ -388,12 +390,29 @@ export class ToolExecutor {stop({ status: 'error' })const classification = classifyToolError(error, tool.name)+ // A skill lookup that misses is not a failure the agent should read as+ // one. The exec dispatcher rewrites the same miss, and a tools-mode+ // client reaching this path must get the same answer — otherwise the+ // behavior changes with the client. Resolved here so the events below+ // record which kind of miss it was, and `handleToolError` adds nothing+ // to a 4xx that is lost by returning early: no recovery hint, no+ // exception capture.+ const lookupMiss = formatSkillLookupMiss(+ tool.name,+ error,+ validation.data as Record<string, unknown>,+ this.builtInSkillHint(state)+ )+void trackToolCall(tool.name,Date.now() - startMs,true,state,- errorAnalyticsProperties(classification, error),+ {+ ...errorAnalyticsProperties(classification, error),+ ...(lookupMiss ? skillLookupMissProperties(lookupMiss.kind) : {}),+ },analyticsMeta,this.servedToolDescription(tool.name))@@ -419,15 +438,8 @@ export class ToolExecutor {input: validation.data,})- // A skill lookup that misses is not a failure the agent should read as- // one. The exec dispatcher rewrites the same miss, and a tools-mode- // client reaching this path must get the same answer — otherwise the- // behavior changes with the client. Telemetry above already recorded- // the 404, and `handleToolError` adds nothing to a 4xx that is lost- // here: no recovery hint, no exception capture.- const lookupMiss = formatSkillLookupMiss(tool.name, error, validation.data as Record<string, unknown>)if (lookupMiss) {- return { content: [{ type: 'text', text: lookupMiss }] }+ return { content: [{ type: 'text', text: lookupMiss.message }] }}const sessionUuid = await state.reqCtx.getEffectiveSessionUuid(state.requestContext)@@ -444,6 +456,7 @@ export class ToolExecutor {innerToolName: undefined,commandMeta: undefined,innerFailure: undefined,+ skillLookupMissKind: undefined,}const resolved = this.resolveExecTool(state, execMetrics, analyticsMeta)@@ -510,6 +523,9 @@ export class ToolExecutor {{...execShape,...(failureShape ?? execSkillShape),+ ...(execMetrics.skillLookupMissKind+ ? skillLookupMissProperties(execMetrics.skillLookupMissKind)+ : {}),input_tokens: estimateTokens(validation.data),output_tokens: estimateResponseTokens(response),...execMetrics.commandMeta,@@ -565,6 +581,23 @@ export class ToolExecutor {}}+ /**+ * What this connection knows about the built-in PostHog skill catalog.+ *+ * Read from the catalog the server loads at startup, not from the `learn`+ * catalog: that one is undefined exactly when the `learn` command is off, which+ * is the case where an agent told to load a built-in skill has nowhere else to+ * go. A catalog that never loaded reports every name as absent, so the message+ * falls back to the store's own.+ */+ private builtInSkillHint(state: ResolvedState): BuiltInSkillHint {+ const catalog = this.skillCatalogService?.getCatalog()+ return {+ isBuiltIn: (name) => catalog?.has(name) === true,+ learnAvailable: this.instructionsBuilder.execSkillsEnabled(state),+ }+ }+private resolveExecTool(state: ResolvedState,execMetrics: ExecMetricState,@@ -582,6 +615,7 @@ export class ToolExecutor {if (!properties.success) {execMetrics.innerFailure = { error: properties.error }}+ execMetrics.skillLookupMissKind = properties.skill_lookup_miss_kindconst status = properties.success ? 'success' : properties.validation_error ? 'validation_error' : 'error'toolCallsTotal.inc({ tool: toolName, status })// Mirror the native path: schema rejections never start a handler, so@@ -640,6 +674,7 @@ export class ToolExecutor {this.skillCatalogService?.getCatalog()),flagGatedTools: state.flagGatedTools,+ builtInSkillHint: this.builtInSkillHint(state),skillsSession: this.instructionsBuilder.execSkillsEnabled(state)? buildSkillsSessionState(state.reqCtx, state.requestContext.mcpSessionId): undefined,diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex 00065d15858e..916019cb0eef 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -17,7 +17,7 @@ import { APP_DATA_META_KEY } from '@/ui-apps/types'import { type ExecLearnCatalog, QUALIFIED_IDENTIFIER, tokenizeLearnInput } from './exec-learn'import { TOKEN_CHAR_LIMIT, listAvailablePaths, resolveSchemaPath, summarizeSchema } from './schema-utils'-import { formatSkillLookupMiss } from './skills/notFound'+import { type BuiltInSkillHint, formatSkillLookupMiss, type SkillLookupMissKind } from './skills/notFound'import { isRegexPattern, searchToolsRanked, searchToolsRegex } from './tool-search'import { getToolDefinitions, type FlagGatedTool, type ScopeGatedTool } from './toolDefinitions'import {@@ -106,6 +106,8 @@ export interface ExecInnerCallProperties {* result (e.g. which metrics a catalog lookup returned), not just its size.*/output?: unknown+ /** Which kind of skill lookup missed, when the dispatcher rewrote a 404. */+ skill_lookup_miss_kind?: SkillLookupMissKind}export type ExecInnerCallTracker = (toolName: string, properties: ExecInnerCallProperties) => void@@ -172,6 +174,13 @@ export interface ExecToolOptions {* a retired name name its successor instead of reading as an unknown tool.*/flagGatedTools?: FlagGatedTool[]+ /**+ * Lets a 404 from the project skills store say that the name belongs to the+ * built-in PostHog catalog instead. Built from the server's own catalog, not+ * from `learnCatalog`: that one is absent exactly when `learn` is off, which+ * is the case where an agent has no way to reach a built-in skill at all.+ */+ builtInSkillHint?: BuiltInSkillHint}const CALL_USAGE = 'Usage: call [--json] [--confirm] [--no-skills] <tool_name> <json_input>'@@ -1687,6 +1696,10 @@ export function createExecTool(} catch (err) {// PostHogValidationError is the API's 400 validation_error body.const apiError = findRecoverableApiError(err)+ // A skill lookup that misses is not a failure the agent should+ // read as one. Resolved before the report below, so telemetry+ // records which kind of miss it was alongside the 404.+ const lookupMiss = formatSkillLookupMiss(tool.name, err, input, options.builtInSkillHint)trackInnerCall?.(tool.name, {duration_ms: Date.now() - startedAt,success: false,@@ -1695,18 +1708,16 @@ export function createExecTool(...(apiError? { error_status: apiError instanceof PostHogApiError ? apiError.status : 400 }: {}),+ ...(lookupMiss ? { skill_lookup_miss_kind: lookupMiss.kind } : {}),input,error: err,})- // A skill lookup that misses is not a failure the agent should- // read as one. Telemetry above still records the 404.- const lookupMiss = formatSkillLookupMiss(tool.name, err, input)if (lookupMiss) {// The success path below serializes a string result under// `--json`, so encode this the same way. A `--json` caller// reaches for `JSON.parse`, and raw prose is the one reply// that would break in its hands.- return useJson ? JSON.stringify(lookupMiss) : lookupMiss+ return useJson ? JSON.stringify(lookupMiss.message) : lookupMiss.message}throw err}diff --git a/services/mcp/src/tools/skills/analytics.ts b/services/mcp/src/tools/skills/analytics.tsindex aadc370d0fb8..fc01994cd8cc 100644--- a/services/mcp/src/tools/skills/analytics.ts+++ b/services/mcp/src/tools/skills/analytics.ts@@ -20,6 +20,8 @@* than echoed into analytics.*/+import type { SkillLookupMissKind } from './notFound'+/** The store's own constraint: lowercase alphanumerics and hyphens, max 64 chars.* Enforced at skill creation, so a value outside it never named a real skill. */const RECORDABLE_SKILL_NAME = /^[a-z0-9][a-z0-9-]{0,63}$/@@ -59,6 +61,18 @@ function recordableBodyOffset(value: unknown): number | undefined {* output of `parseExecCallInnerArgs` in single-exec mode. Malformed input yields* no properties rather than throwing — analytics must never break a tool call.*/+/**+ * Why a skill read returned 404, stamped on the errored `$mcp_tool_call`.+ *+ * Every miss looks the same in the data today, so an agent sent to the store for+ * a built-in PostHog skill is indistinguishable from an agent that mistyped a+ * name. A breakdown by this property separates the two, which is how the next+ * catalog the store does not hold gets noticed.+ */+export function skillLookupMissProperties(kind: SkillLookupMissKind): Record<string, unknown> {+ return { $mcp_skill_lookup_miss_kind: kind }+}+export function skillAnalyticsProperties(toolName: string | undefined, args: unknown): Record<string, unknown> {if (!toolName || !SKILL_READ_TOOLS.has(toolName)) {return {}diff --git a/services/mcp/src/tools/skills/notFound.ts b/services/mcp/src/tools/skills/notFound.tsindex 54c2cb38f757..22d6685e19c6 100644--- a/services/mcp/src/tools/skills/notFound.ts+++ b/services/mcp/src/tools/skills/notFound.ts@@ -11,6 +11,26 @@ const FILE_MISSING_DETAIL = 'not found in skill'* that emits it, so a 404 without it came from somewhere else. */const SKILL_MISSING_DETAIL = 'Skill with name'+/** Which kind of miss the message answers. Stamped on the errored `$mcp_tool_call`+ * so "agents asking the store for a built-in skill" is its own line in the data,+ * rather than hiding among the typos in one undifferentiated 404 count. */+export type SkillLookupMissKind = 'builtin' | 'unknown' | 'file' | 'version'++export interface SkillLookupMiss {+ message: string+ kind: SkillLookupMissKind+}++/** What the caller knows about the built-in PostHog skill catalog, which the+ * store knows nothing about. Optional at every call site, because a connection+ * that never loaded the catalog cannot claim a name is absent from it. */+export interface BuiltInSkillHint {+ /** True when the name is in the built-in PostHog skill catalog loaded by the server. */+ isBuiltIn: (name: string) => boolean+ /** True when this connection can run `learn posthog:<skill>`. */+ learnAvailable: boolean+}+/*** Returns the plain not-found message for a skill lookup 404, or undefined for* anything else — a different tool, a different status, or a genuine failure@@ -20,12 +40,19 @@ const SKILL_MISSING_DETAIL = 'Skill with name'* which reads as a service outage rather than a lookup miss. A model that draws* that conclusion stops calling the skill tools at all, so the miss has to name* itself and point at the tool that lists what exists.+ *+ * Built-in PostHog skills are a separate catalog the store never held, so a tool+ * description that says "load the `<name>` skill" sends an agent to `skill-get`+ * and the store answers 404. Pointing that agent at `skill-list` confirms the+ * wrong conclusion — that the skill does not exist — so a name the built-in+ * catalog knows says where the skill really lives instead.*/export function formatSkillLookupMiss(toolName: string,error: unknown,- input: Record<string, unknown>-): string | undefined {+ input: Record<string, unknown>,+ hint?: BuiltInSkillHint+): SkillLookupMiss | undefined {if (!SKILL_READ_TOOLS.has(toolName)) {return undefined}@@ -47,10 +74,13 @@ export function formatSkillLookupMiss(// returns the latest version's files, and a publish replaces the whole// set, so those paths can be absent at the pinned version.const pinnedVersion = typeof version === 'number' ? `, "version": ${version}` : ''- return [- `No file "${filePath}" in the skill "${skillName}".`,- `Run \`call skill-get {"skill_name": "${skillName}"${pinnedVersion}}\` to see the skill's file manifest.`,- ].join('\n')+ return {+ kind: 'file',+ message: [+ `No file "${filePath}" in the skill "${skillName}".`,+ `Run \`call skill-get {"skill_name": "${skillName}"${pinnedVersion}}\` to see the skill's file manifest.`,+ ].join('\n'),+ }}// A 404 the name lookup did not produce says nothing about what the store@@ -66,14 +96,39 @@ export function formatSkillLookupMiss(// exist. So a pinned read cannot be told the skill is absent: `skill-list`// would then list the skill the message just denied.if (typeof version === 'number') {- return [- `No version ${version} of the skill "${skillName}" in this project's skills store. The store answers the same way when the skill itself is missing.`,- `Run \`call skill-get {"skill_name": "${skillName}"}\` to read the latest version, or \`call skill-list\` to see the skills that are available.`,- ].join('\n')+ return {+ kind: 'version',+ message: [+ `No version ${version} of the skill "${skillName}" in this project's skills store. The store answers the same way when the skill itself is missing.`,+ `Run \`call skill-get {"skill_name": "${skillName}"}\` to read the latest version, or \`call skill-list\` to see the skills that are available.`,+ ].join('\n'),+ }+ }++ // A pinned `version` proves the caller already holds a store skill, so the+ // version message above stands. A `file_path` proves nothing: the store+ // answers a file read on an unknown name with the same skill-level 404, so+ // that read lands here too.+ if (hint?.isBuiltIn(skillName)) {+ return {+ kind: 'builtin',+ message: hint.learnAvailable+ ? [+ `"${skillName}" is a built-in PostHog skill, not a skill in this project's skills store.`,+ `Run \`learn posthog:${skillName}\` to load it.`,+ ].join('\n')+ : [+ `"${skillName}" is a built-in PostHog skill, not a skill in this project's skills store, and this connection cannot load built-in skills.`,+ `Read it from your installed PostHog skills (\`.agents/skills/${skillName}/SKILL.md\`) if you have them. Otherwise continue with the tool description.`,+ ].join('\n'),+ }}- return [- `No skill named "${skillName}" in this project's skills store.`,- 'Run `call skill-list` to see the skills that are available.',- ].join('\n')+ return {+ kind: 'unknown',+ message: [+ `No skill named "${skillName}" in this project's skills store.`,+ 'Run `call skill-list` to see the skills that are available.',+ ].join('\n'),+ }}diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.tsindex 32ee9395b6f8..57d12cd861a4 100644--- a/services/mcp/tests/hono/tool-executor.test.ts+++ b/services/mcp/tests/hono/tool-executor.test.ts@@ -165,6 +165,28 @@ describe('ToolExecutor', () => {expect(text).not.toContain('feature-flag-get-all')})+ function skillMissContext(skillName: string, body: string): ResolvedState['context'] {+ return {+ api: {+ request: vi.fn().mockRejectedValue(+ new PostHogApiError({+ status: 404,+ statusText: 'Not Found',+ body,+ url: `https://internal.example.com/api/projects/1/llm_skills/name/${skillName}/`,+ method: 'GET',+ })+ ),+ },+ cache: {},+ env: {},+ stateManager: { getProjectId: vi.fn().mockResolvedValue('1') },+ sessionManager: {},+ getDistinctId: vi.fn(),+ trackEvent: vi.fn(),+ } as any+ }+// Cursor and ChatGPT get the per-tool roster, so they call the skill read// tools here rather than through exec. Left on the generic error shape, the// same miss reads as a service outage for them and as a plain answer for@@ -183,27 +205,7 @@ describe('ToolExecutor', () => {'No file "refs/guide.md" in the skill "real-skill".',],])('answers a %s miss with the plain message in tools mode', async (name, args, body, expected) => {- const state = makeState([{ name }], {- context: {- api: {- request: vi.fn().mockRejectedValue(- new PostHogApiError({- status: 404,- statusText: 'Not Found',- body,- url: `https://internal.example.com/api/projects/1/llm_skills/name/${args.skill_name}/`,- method: 'GET',- })- ),- },- cache: {},- env: {},- stateManager: { getProjectId: vi.fn().mockResolvedValue('1') },- sessionManager: {},- getDistinctId: vi.fn(),- trackEvent: vi.fn(),- } as any,- })+ const state = makeState([{ name }], { context: skillMissContext(args.skill_name, body) })const result = (await executor.handleToolCall({ name, arguments: args }, state)) as any@@ -211,6 +213,54 @@ describe('ToolExecutor', () => {expect(result.content[0].text).toContain(expected)expect(result.content[0].text).not.toContain('Request failed')})++ // The `learn` command is feature-flagged, so most connections cannot load a+ // built-in skill at all. Sending them back to a store that never held one+ // is what makes an agent drop the task, so the message says where the skill+ // lives and whether this connection can reach it.+ // Both modes are covered: single-exec dispatch is where nearly every skill+ // read arrives, and the per-tool roster is the path Cursor and ChatGPT take.+ it.each([+ ['tools', false, 'this connection cannot load built-in skills.'],+ ['tools', true, 'Run `learn posthog:scanning-experiments-with-replay-vision` to load it.'],+ ['exec', false, 'this connection cannot load built-in skills.'],+ ['exec', true, 'Run `learn posthog:scanning-experiments-with-replay-vision` to load it.'],+ ])(+ 'names the built-in catalog on a store miss in %s mode, with learn enabled=%s',+ async (mode, skillsEnabled, expected) => {+ const skillName = 'scanning-experiments-with-replay-vision'+ const skills = new SkillCatalog([+ {+ name: skillName,+ description: 'A built-in skill.',+ files: [makeSkillFile('SKILL.md', '# Built-in skill')],+ },+ ])+ const skillExecutor = new ToolExecutor(catalog, new InstructionsBuilder(''), {+ getCatalog: () => skills,+ } as any)+ const useExec = mode === 'exec'+ // Exec dispatches through the real tool objects, so the roster has to+ // carry the handler rather than only the name.+ const tools = useExec+ ? catalog.getFilteredTools({ scopes: ['*'] }).filter((tool) => tool.name === 'skill-get')+ : [{ name: 'skill-get' }]+ const state = makeState(tools as any, {+ useSingleExec: useExec,+ toolFeatureFlags: { [MCP_EXEC_SKILLS_FEATURE_FLAG]: skillsEnabled },+ context: skillMissContext(skillName, `{"detail":"Skill with name '${skillName}' not found."}`),+ })+ const call = useExec+ ? { name: 'exec', arguments: { command: `call skill-get {"skill_name":"${skillName}"}` } }+ : { name: 'skill-get', arguments: { skill_name: skillName } }++ const result = (await skillExecutor.handleToolCall(call, state)) as any++ expect(result.isError).toBeFalsy()+ expect(result.content[0].text).toContain(expected)+ expect(result.content[0].text).not.toContain('call skill-list')+ }+ )})describe('handleToolsList', () => {diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex c90b64e47ec6..1d69c966b443 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -902,6 +902,63 @@ describe('exec tool', () => {)})+ // Built-in PostHog skills are a catalog the store never held, so a tool+ // description that says "load the `<name>` skill" sends an agent here and+ // the store answers 404. The message above points at `skill-list`, which+ // confirms the wrong conclusion — that the skill does not exist.+ const BUILT_IN_SKILL = 'scanning-experiments-with-replay-vision'++ it.each([+ [+ 'points a connection that can run `learn` at the built-in catalog',+ BUILT_IN_SKILL,+ '',+ true,+ `Run \`learn posthog:${BUILT_IN_SKILL}\` to load it.`,+ ],+ [+ 'tells a connection without `learn` that it cannot load the skill',+ BUILT_IN_SKILL,+ '',+ false,+ 'this connection cannot load built-in skills.',+ ],+ [+ 'keeps the store message for a name the built-in catalog does not know',+ 'missing-skill',+ '',+ false,+ 'No skill named "missing-skill"',+ ],+ [+ 'keeps the version message when a built-in name pins a version',+ BUILT_IN_SKILL,+ ',"version":7',+ false,+ `No version 7 of the skill "${BUILT_IN_SKILL}"`,+ ],+ ])('%s', async (_label, skillName, pinnedVersion, learnAvailable, expected) => {+ const exec = createExec(+ [makeSkillTool('skill-get', `{"detail":"Skill with name '${skillName}' not found."}`)],+ undefined,+ {+ builtInSkillHint: {+ isBuiltIn: (name) => name === BUILT_IN_SKILL,+ learnAvailable,+ },+ }+ )++ const result = (await exec.handler(mockContext, {+ command: `call skill-get {"skill_name":"${skillName}"${pinnedVersion}}`,+ })) as string++ expect(result).toContain(expected)+ // A pinned version proves the caller already holds a store skill, so+ // only the bare name lookup may be answered with the built-in catalog.+ expect(result.includes('built-in PostHog skill')).toBe(skillName === BUILT_IN_SKILL && !pinnedVersion)+ })+// A file belongs to one version row, and a publish replaces the whole set,// so an unpinned recovery command sends an agent working from an older// version to a manifest whose paths it cannot fetch.