: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(engineering_analytics): MCP read tools + diagnosis skill (#61382)
Raúl Negrón-Oteroe486faa7064a
diff --git a/products/engineering_analytics/backend/tests/test_mcp.py b/products/engineering_analytics/backend/tests/test_mcp.pynew file mode 100644index 000000000000..63f4cc5b205e--- /dev/null+++ b/products/engineering_analytics/backend/tests/test_mcp.py@@ -0,0 +1,25 @@+import json+from pathlib import Path++import pytest++_DEFINITIONS = Path(__file__).parents[4] / "services/mcp/schema/generated-tool-definitions.json"+++class TestEngineeringAnalyticsMCPTools:+ @pytest.mark.parametrize("tool", ["pull-requests", "workflow-health", "pr-lifecycle"])+ def test_tool_is_generated_read_only_and_scoped(self, tool: str) -> None:+ definitions = json.loads(_DEFINITIONS.read_text())++ assert tool in definitions, f"{tool} missing from generated tool definitions; run hogli build:openapi"+ entry = definitions[tool]+ assert entry["feature"] == "engineering_analytics"+ assert entry["annotations"]["readOnlyHint"] is True+ assert entry["annotations"]["destructiveHint"] is False+ assert "engineering_analytics:read" in entry["required_scopes"]++ def test_removed_report_tools_are_not_generated(self) -> None:+ definitions = json.loads(_DEFINITIONS.read_text())++ assert "workflow-report" not in definitions+ assert "time-to-merge" not in definitionsdiff --git a/products/engineering_analytics/mcp/tools.yaml b/products/engineering_analytics/mcp/tools.yamlnew file mode 100644index 000000000000..d7d8032a6590--- /dev/null+++ b/products/engineering_analytics/mcp/tools.yaml@@ -0,0 +1,79 @@+# MCP tool definition — tool entries are scaffolded from the OpenAPI schema.+# The tool list and operation IDs are kept in sync automatically:+# pnpm --filter=@posthog/mcp run scaffold-yaml -- --sync-all+#+# To enable a tool, set enabled: true and add required scopes + annotations.+# All other fields (title, description, enrich_url, etc.) are yours to configure.+category: Engineering analytics+feature: engineering_analytics+url_prefix: /engineering_analytics+ui_apps: {}+tools:+ engineering-analytics-ci-cards:+ operation: engineering_analytics_ci_cards+ enabled: false+ pr-lifecycle:+ operation: engineering_analytics_pr_lifecycle+ enabled: true+ scopes:+ - engineering_analytics:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: PR lifecycle timeline+ description: >+ The timeline of a single pull request: a header (number, title, author, state, draft, timestamps) plus+ ordered events — opened, CI started, CI finished, and merged or closed. Use this to answer "where is this PR+ stuck and what happened to it". metric_quality is "partial" — it covers CI events only; review and comment+ events are not yet available. For aggregate questions use the pull-requests and workflow-health tools.+ param_overrides:+ pr_number:+ description: Pull request number to inspect.+ repo:+ description: Optional 'owner/name' repository to disambiguate when the PR number exists in more than one connected repo.+ pull-requests:+ operation: engineering_analytics_pull_requests+ enabled: true+ scopes:+ - engineering_analytics:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ list: true+ title: List pull requests with CI status+ description: >+ Open pull requests plus any merged or closed within the window, newest first, each with its head-SHA CI+ rollup (runs / passing / failing / pending). Use this for "which PRs are stuck", "which open PRs have+ failing or pending CI", and per-author or per-repo PR triage. open_to_merge_seconds is coarse — it is+ merged_at minus created_at and fuses draft and ready-for-review time, so report it as "open to merge", never+ "cycle time". CI counts come from the latest run per workflow on the head SHA and can lag until the+ workflow_run webhook settles a late completion. Bots and drafts are present; exclude them (is_bot, is_draft)+ for throughput questions.+ param_overrides:+ date_from:+ description: >+ Recency floor for merged/closed PRs — relative ('-30d', '-8w') or ISO8601. Open PRs are always+ included regardless of age. Defaults to -30d.+ workflow-health:+ operation: engineering_analytics_workflow_health+ enabled: true+ scopes:+ - engineering_analytics:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ list: true+ title: Per-workflow CI health+ description: >+ Per-workflow CI health over a window: run count, success rate, p50/p95 duration, and last failure time. Use+ this for "is CI getting faster or slower", "which GitHub Actions workflow is the slow or flaky long pole",+ and CI duration trends. Rates and percentiles are over completed runs only and are null for a window with no+ completed runs; to get a trend, call this over two adjacent windows and compare.+ param_overrides:+ date_from:+ description: Window start — relative ('-30d', '-8w') or ISO8601. Defaults to -30d.+ date_to:+ description: Window end — relative or ISO8601. Defaults to now.diff --git a/products/engineering_analytics/skills/diagnosing-ci-and-merge-bottlenecks/SKILL.md b/products/engineering_analytics/skills/diagnosing-ci-and-merge-bottlenecks/SKILL.mdnew file mode 100644index 000000000000..dcd941d429ea--- /dev/null+++ b/products/engineering_analytics/skills/diagnosing-ci-and-merge-bottlenecks/SKILL.md@@ -0,0 +1,99 @@+---+name: diagnosing-ci-and-merge-bottlenecks+description: >+ Diagnoses CI and pull-request pipeline health for a GitHub repo using the engineering analytics MCP tools —+ pull-requests (PR list with CI status), workflow-health (per-workflow CI trends), and pr-lifecycle (a single PR's+ timeline). Use when asked whether CI is getting faster or slower, which GitHub Actions workflow is the slow or+ flaky long-pole, how long PRs take from open to merge, how an author's merge time compares to the cohort, which+ open PRs have failing or pending CI, or where a specific pull request is stuck. Triggers on "engineering+ analytics", "is CI getting slower", "slow workflow", "flaky CI", "time to merge", "cycle time", "PR throughput",+ "failing checks", "where is PR <n> stuck", "CI long pole", "what's holding up this PR".+---++# Diagnosing CI and merge bottlenecks++Engineering analytics treats a pull request like product analytics treats a user: a PR moves through a pipeline+(`opened → CI → review → merged → deployed`) and the job is to find where it slows down. The surface is **three+named MCP tools** — you call them, you don't write SQL. Dogfooded on `PostHog/posthog`; the same tools serve+autonomous agents (e.g. PostHog Code) reasoning about their own PRs.++## The tools++- **`pull-requests`** — the PR workhorse. Open PRs plus anything merged or closed since `date_from` (default+ `-30d`), newest first. Each row carries `author` (nested object: `handle`, `display_name`, `is_bot`), `repo`+ (nested: `owner`, `name`), `state`, `is_draft`, `labels`, `open_to_merge_seconds`, and a `ci` rollup+ (`runs` / `passing` / `failing` / `pending`) from the head-SHA join. Answers most PR-level questions:+ which PRs have failing or pending CI, which are stuck open longest, per-author or per-repo triage, and+ time-to-merge stats (aggregate `open_to_merge_seconds` over the returned merged rows yourself — median and p95,+ never a mean).+- **`workflow-health`** — per-workflow CI health over a window (`date_from` / `date_to`, default last 30 days):+ `run_count`, `success_rate`, `p50_seconds`, `p95_seconds`, `last_failure_at`. Answers "is CI getting faster or+ slower" and "which workflow is the slow or flaky long pole". There is no built-in trend — call it over two+ adjacent windows and compare. `success_rate` / `p50_seconds` / `p95_seconds` cover completed runs only and are+ `null` when a window has no completed runs — guard for null before comparing two windows (a workflow can have+ runs in one and none in the other).+- **`pr-lifecycle`** — a single PR's timeline: a header plus ordered events — opened, then a CI started/finished+ pair **per workflow run** (many on a multi-workflow repo, interleaved by time), then merged/closed. Answers+ "where is PR N stuck". `metric_quality` is `partial`.++There is no aggregate time-to-merge tool and no "counts" tool — derive those from `pull-requests` (the stuck/failing+counts, the merge-time percentiles).++## Caveats you must carry into every answer++These are structural limits of today's snapshot data — state them, don't paper over them.++- **`open_to_merge_seconds` is coarse.** It fuses _draft_ time and _ready-for-review_ time into one figure. Report+ it as "open to merge", never "cycle time" or "review time". Flag it when long-lived drafts inflate a number.+- **CI status can be stale.** The CI source syncs on a watermark and does not refresh a run that completes after+ newer runs land (until the `workflow_run` webhook ships). Treat a `pending` count as unsettled, not as a settled+ failure; lead with status, not a verdict.+- **CI for a PR is the head-SHA join, nothing else.** The `ci` rollup reflects only the latest commit's runs. There+ is no other link between a PR and its checks.+- **No reviews, approvals, per-check/job, or deploys yet.** Don't infer review behaviour or DORA metrics from their+ absence; that data hasn't landed. `pr-lifecycle` is `partial` for the same reason.+- **Bots and drafts are present in `pull-requests` output, excluded by convention.** Filter out `author.is_bot`+ (nested under `author`, not a row-level field) and `is_draft` for throughput / merge-time questions; keep them in+ for bot-impact questions.+- **`pull-requests` returns a capped page.** At most `limit` rows (newest first); `truncated` is `true` when more+ match, and there is no repo or limit filter to narrow the call. When `truncated` is `true`, any percentile or+ count you derive covers only the newest page — not the whole window — so say so and shrink `date_from` until the+ real set fits under the cap.++## Choosing a tool++| The question | Tool | How |+| ------------------------------------------------------ | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Is CI getting slower? Which workflow is the long pole? | `workflow-health` | Call over two adjacent windows (e.g. `date_from=-14d`, then `date_from=-28d` `date_to=-14d`); compare `p50_seconds` and `p95_seconds` per workflow. Lead with the median but always check p95 separately — they move independently. |+| Which open PRs have failing or pending CI? | `pull-requests` | Keep rows where `ci.failing > 0` or `ci.pending > 0`. `pending` means unsettled (or stale) — not a settled failure. |+| Which PRs are stuck open longest? | `pull-requests` | Keep `state = open`, not `is_draft`, not `author.is_bot`; sort by `created_at` ascending (oldest first). |+| How long are PRs taking to merge? Per author? | `pull-requests` | Over merged rows (`merged_at` set, not bot, not draft), aggregate `open_to_merge_seconds` — median and p95. Group by `author.handle` for **cohort context, not a ranking** (per-developer surveillance is an explicit non-goal). Trend it by calling with two `date_from` windows. |+| Where is PR N stuck? | `pr-lifecycle` | Walk the sorted events: `opened → first CI started`, the CI span (first start → last finish; one pair per workflow), `last CI finished → merged`. The largest gap is the bottleneck. A long open→merge with quick CI points at review/idle time the `partial` data can't itemize yet — say so. |++## The high-value chain++Mirror how a human investigates: aggregate signal → confirm → concrete PR.++```text+workflow-health (find the slow/flaky long-pole workflow)+ → pull-requests (confirm it's dragging merge time; list the affected PRs)+ → pr-lifecycle (open a representative stuck PR and show the gap)+```++"CI median rose because `e2e-playwright` p95 doubled; that workflow is the long pole on PR #1234, which sat 47m in+CI before merging."++## Output expectations++- Lead with the verdict in one line, then the supporting numbers.+- Carry the coarse / partial / staleness caveat whenever the distinction matters.+- For multi-window or multi-workflow comparisons, a short table beats prose. Report median and p95 side by side —+ never collapse them into one "average".++## What NOT to do++- Don't call `open_to_merge_seconds` cycle time or review time — it's coarse open-to-merge.+- Don't report a CI count as a settled failure when `pending > 0` — it may be unsettled or stale.+- Don't infer reviews, approvals, per-check counts, or deploys — that data isn't ingested yet.+- Don't turn per-author buckets into a leaderboard — they're for finding stuck work, not ranking people.+- Don't reach for these tools to fetch raw PR contents or diffs — they surface pipeline signal, not the PR thread.diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex e57117a83785..7446e961231f 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -4370,6 +4370,20 @@"readOnlyHint": true}},+ "pr-lifecycle": {+ "description": "The timeline of a single pull request: a header (number, title, author, state, draft, timestamps) plus ordered events — opened, CI started, CI finished, and merged or closed. Use this to answer \"where is this PR stuck and what happened to it\". metric_quality is \"partial\" — it covers CI events only; review and comment events are not yet available. For aggregate questions use the pull-requests and workflow-health tools.",+ "category": "Engineering analytics",+ "feature": "engineering_analytics",+ "summary": "PR lifecycle timeline",+ "title": "PR lifecycle timeline",+ "required_scopes": ["engineering_analytics:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"project-get": {"description": "Retrieve a project and its settings. Pass `@current` as the ID to fetch the caller's active project.","category": "Core",@@ -4498,6 +4512,20 @@"readOnlyHint": false}},+ "pull-requests": {+ "description": "Open pull requests plus any merged or closed within the window, newest first, each with its head-SHA CI rollup (runs / passing / failing / pending). Use this for \"which PRs are stuck\", \"which open PRs have failing or pending CI\", and per-author or per-repo PR triage. open_to_merge_seconds is coarse — it is merged_at minus created_at and fuses draft and ready-for-review time, so report it as \"open to merge\", never \"cycle time\". CI counts come from the latest run per workflow on the head SHA and can lag until the workflow_run webhook settles a late completion. Bots and drafts are present; exclude them (is_bot, is_draft) for throughput questions.",+ "category": "Engineering analytics",+ "feature": "engineering_analytics",+ "summary": "List pull requests with CI status",+ "title": "List pull requests with CI status",+ "required_scopes": ["engineering_analytics:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"query-apm-spans": {"description": "Query trace spans with filtering by service name, status code, date range, and structured attribute filters. Supports cursor-based pagination. Returns spans with uuid, trace_id, span_id, parent_span_id, name, kind, service_name, status_code, timestamp, end_time, duration_nano, is_root_span, matched_filter, and attributes (the span-level OTel attribute map, e.g. db.statement, http.url).\n\nUse 'apm-attributes-list' and 'apm-attribute-values-list' to discover available attributes before building filters. Use 'apm-services-list' to discover available services.\n\n# Return shape\n\nResults are **grouped by trace**, not a flat list of matching spans. For each trace that contains at least one span matching your filters, the response includes spans from that trace (up to `prefetchSpans` per trace, root span first). Two fields tell you which spans actually matched:\n\n- `matched_filter` — `1` if **this span** satisfies your `filterGroup`/`serviceNames`/`statusCodes`, `0` if it's only included because it shares a trace with a match (e.g. a prefetched sibling or the trace's root). When you filter by a child span's name, the matching child has `matched_filter: 1` and its root/siblings have `matched_filter: 0`.\n- `is_root_span` — `true` for the trace's entry span.\n\nTo collapse each matching trace to a **single row — its root span**, set `rootSpans: true` — see below. (The row is the trace's entry span, which may itself carry `matched_filter: 0` when the match was on a child.) To inspect a single trace's full tree, take a `trace_id` from the results and call `apm-trace-get`.\n\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\nAll parameters must be nested inside a `query` object.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters via the `query.filterGroup` field to narrow results. Only include property filters when they are essential to directly answer the user's question.\n\nWhen using a property filter, you should:\n\n- **Choose the right type.** Span property types are:\n - `span` — filters built-in span fields (trace_id, span_id, duration, name, kind, status_code).\n - `span_attribute` — filters span-level attributes (e.g. \"http.method\", \"http.status_code\").\n - `span_resource_attribute` — filters resource-level attributes (e.g. k8s labels, deployment info).\n- **Use `apm-attributes-list` to discover available attribute keys** before building filters.\n- **Use `apm-attribute-values-list` to discover valid values** for a specific attribute key.\n- **Find the suitable operator for the value type** (see supported operators below).\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Existence (no value needed): `is_set`, `is_not_set`\n\nThe `value` field accepts a string, number, or array of strings depending on the operator. Omit `value` for `is_set`/`is_not_set`.\n\n## Time period\n\nUse the `query.dateRange` field to control the time window. If the question doesn't mention time, the default is the last hour (`-1h`). Examples of relative dates: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.serviceNames\n\nFilter by service names. Use `apm-services-list` to discover available services.\n\n## query.statusCodes\n\nFilter by HTTP status codes (list of integers).\n\n## query.orderBy\n\nSort by timestamp: `latest` (default) or `earliest`.\n\n## query.filterGroup\n\nA list of property filters to narrow results. Each filter specifies `key`, `operator`, `type` (span/span_attribute/span_resource_attribute), and optionally `value`. See the \"Property filters\" section above.\n\n## query.dateRange\n\nDate range to filter results. Defaults to the last hour (`-1h`).\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.traceId\n\nFilter to a specific trace ID (hex string). Use this when you already know the trace ID.\n\n## query.rootSpans\n\nSet `true` to return **only root spans** — one entry span per matching trace, which collapses each trace to a single row. Useful for \"list the traces matching X\" without sifting through `matched_filter`. Leave unset (or `false`) to get all spans of matching traces, where you read `matched_filter` to find the ones that matched. The frontend leaves this unset.\n\n## query.limit\n\nMaximum number of results (1-1000). Defaults to 100.\n\n## query.after\n\nCursor for pagination. Use the `nextCursor` value from the previous response.\n\n## query.prefetchSpans\n\nNumber of spans to return per matching trace (1-100), root span first. Useful to preview trace structure without a separate `apm-trace-get`. With the default (1) you get one span per trace (the root); raise it to also pull the matching children and their siblings (check `matched_filter` to tell them apart). Ignored when `rootSpans: true`, which always returns just the root.\n\n## query.excludeAttributes\n\nSet `true` to drop the per-span `attributes` map from results (the map stays present but empty). The attribute map holds multi-KB values like `db.statement`, so excluding it keeps large result sets compact — set it when you only need span structure/timing (`name`, `service_name`, `duration_nano`, `parent_span_id`) and not the OTel attributes. Defaults to false.\n\n# Examples\n\n## List recent error spans\n\n```json\n{\n \"query\": {\n \"statusCodes\": [500, 503]\n }\n}\n```\n\n## Search spans from a specific service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Filter by a span attribute\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"http.method\", \"operator\": \"exact\", \"type\": \"span_attribute\", \"value\": \"POST\" }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Find slow spans\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"duration\", \"operator\": \"gt\", \"type\": \"span\", \"value\": \"1000000000\" }],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Combine service and attribute filters\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"web-server\"],\n \"filterGroup\": [{ \"key\": \"http.status_code\", \"operator\": \"gt\", \"type\": \"span_attribute\", \"value\": \"399\" }],\n \"dateRange\": { \"date_from\": \"-12h\" }\n }\n}\n```\n\n## Check if a resource attribute exists\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"k8s.pod.name\", \"operator\": \"is_set\", \"type\": \"span_resource_attribute\" }]\n }\n}\n```\n\n# Reminders\n\n- Ensure that any property filters are directly relevant to the user's question. Avoid unnecessary filtering.\n- Use `apm-attributes-list` and `apm-attribute-values-list` to discover attributes before guessing filter keys/values.\n- Use `apm-services-list` to discover available services before filtering by service name.\n- Duration values are in nanoseconds (1 second = 1,000,000,000 nanoseconds).","category": "Tracing",@@ -6428,6 +6456,20 @@"readOnlyHint": true}},+ "workflow-health": {+ "description": "Per-workflow CI health over a window: run count, success rate, p50/p95 duration, and last failure time. Use this for \"is CI getting faster or slower\", \"which GitHub Actions workflow is the slow or flaky long pole\", and CI duration trends. Rates and percentiles are over completed runs only and are null for a window with no completed runs; to get a trend, call this over two adjacent windows and compare.",+ "category": "Engineering analytics",+ "feature": "engineering_analytics",+ "summary": "Per-workflow CI health",+ "title": "Per-workflow CI health",+ "required_scopes": ["engineering_analytics:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"workflows-create": {"description": "Create a workflow. Needs an actions array with exactly one type='trigger' (config.type: event|webhook|manual|batch|tracking_pixel) plus action nodes — function/function_email/function_sms/function_push, delay (e.g. '30m'), conditional_branch, wait_until_condition — connected by edges. Created as a draft; activate with workflows-enable. 'batch' = broadcast to an audience, one run per matching person (emails/messages). The audience is config.filters.properties: person-property conditions ({type:'person',key,value,operator}) and/or cohort references ({type:'cohort',key:'id',value:<id>,operator:'in'}). Prefer inline person-property conditions or a dynamic (filter-based) cohort via cohorts-create — these re-evaluate as people qualify; a static cohort is a frozen list, use only when given an explicit set. Behavioral (event-based) cohorts are rejected — for 'did event X', use an 'event' trigger instead. A batch workflow fires only once enabled and a recurring schedule is attached (workflows-schedule-create).","category": "Workflows",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 1fe126c5060d..14913085f5b5 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -4653,6 +4653,20 @@"readOnlyHint": true}},+ "pr-lifecycle": {+ "description": "The timeline of a single pull request: a header (number, title, author, state, draft, timestamps) plus ordered events — opened, CI started, CI finished, and merged or closed. Use this to answer \"where is this PR stuck and what happened to it\". metric_quality is \"partial\" — it covers CI events only; review and comment events are not yet available. For aggregate questions use the pull-requests and workflow-health tools.",+ "category": "Engineering analytics",+ "feature": "engineering_analytics",+ "summary": "PR lifecycle timeline",+ "title": "PR lifecycle timeline",+ "required_scopes": ["engineering_analytics:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"project-get": {"description": "Retrieve a project and its settings. Pass `@current` as the ID to fetch the caller's active project.","category": "Core",@@ -4795,6 +4809,20 @@"readOnlyHint": false}},+ "pull-requests": {+ "description": "Open pull requests plus any merged or closed within the window, newest first, each with its head-SHA CI rollup (runs / passing / failing / pending). Use this for \"which PRs are stuck\", \"which open PRs have failing or pending CI\", and per-author or per-repo PR triage. open_to_merge_seconds is coarse — it is merged_at minus created_at and fuses draft and ready-for-review time, so report it as \"open to merge\", never \"cycle time\". CI counts come from the latest run per workflow on the head SHA and can lag until the workflow_run webhook settles a late completion. Bots and drafts are present; exclude them (is_bot, is_draft) for throughput questions.",+ "category": "Engineering analytics",+ "feature": "engineering_analytics",+ "summary": "List pull requests with CI status",+ "title": "List pull requests with CI status",+ "required_scopes": ["engineering_analytics:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"query-apm-spans": {"description": "Query trace spans with filtering by service name, status code, date range, and structured attribute filters. Supports cursor-based pagination. Returns spans with uuid, trace_id, span_id, parent_span_id, name, kind, service_name, status_code, timestamp, end_time, duration_nano, is_root_span, matched_filter, and attributes (the span-level OTel attribute map, e.g. db.statement, http.url).\n\nUse 'apm-attributes-list' and 'apm-attribute-values-list' to discover available attributes before building filters. Use 'apm-services-list' to discover available services.\n\n# Return shape\n\nResults are **grouped by trace**, not a flat list of matching spans. For each trace that contains at least one span matching your filters, the response includes spans from that trace (up to `prefetchSpans` per trace, root span first). Two fields tell you which spans actually matched:\n\n- `matched_filter` — `1` if **this span** satisfies your `filterGroup`/`serviceNames`/`statusCodes`, `0` if it's only included because it shares a trace with a match (e.g. a prefetched sibling or the trace's root). When you filter by a child span's name, the matching child has `matched_filter: 1` and its root/siblings have `matched_filter: 0`.\n- `is_root_span` — `true` for the trace's entry span.\n\nTo collapse each matching trace to a **single row — its root span**, set `rootSpans: true` — see below. (The row is the trace's entry span, which may itself carry `matched_filter: 0` when the match was on a child.) To inspect a single trace's full tree, take a `trace_id` from the results and call `apm-trace-get`.\n\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\nAll parameters must be nested inside a `query` object.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters via the `query.filterGroup` field to narrow results. Only include property filters when they are essential to directly answer the user's question.\n\nWhen using a property filter, you should:\n\n- **Choose the right type.** Span property types are:\n - `span` — filters built-in span fields (trace_id, span_id, duration, name, kind, status_code).\n - `span_attribute` — filters span-level attributes (e.g. \"http.method\", \"http.status_code\").\n - `span_resource_attribute` — filters resource-level attributes (e.g. k8s labels, deployment info).\n- **Use `apm-attributes-list` to discover available attribute keys** before building filters.\n- **Use `apm-attribute-values-list` to discover valid values** for a specific attribute key.\n- **Find the suitable operator for the value type** (see supported operators below).\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Existence (no value needed): `is_set`, `is_not_set`\n\nThe `value` field accepts a string, number, or array of strings depending on the operator. Omit `value` for `is_set`/`is_not_set`.\n\n## Time period\n\nUse the `query.dateRange` field to control the time window. If the question doesn't mention time, the default is the last hour (`-1h`). Examples of relative dates: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.serviceNames\n\nFilter by service names. Use `apm-services-list` to discover available services.\n\n## query.statusCodes\n\nFilter by HTTP status codes (list of integers).\n\n## query.orderBy\n\nSort by timestamp: `latest` (default) or `earliest`.\n\n## query.filterGroup\n\nA list of property filters to narrow results. Each filter specifies `key`, `operator`, `type` (span/span_attribute/span_resource_attribute), and optionally `value`. See the \"Property filters\" section above.\n\n## query.dateRange\n\nDate range to filter results. Defaults to the last hour (`-1h`).\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.traceId\n\nFilter to a specific trace ID (hex string). Use this when you already know the trace ID.\n\n## query.rootSpans\n\nSet `true` to return **only root spans** — one entry span per matching trace, which collapses each trace to a single row. Useful for \"list the traces matching X\" without sifting through `matched_filter`. Leave unset (or `false`) to get all spans of matching traces, where you read `matched_filter` to find the ones that matched. The frontend leaves this unset.\n\n## query.limit\n\nMaximum number of results (1-1000). Defaults to 100.\n\n## query.after\n\nCursor for pagination. Use the `nextCursor` value from the previous response.\n\n## query.prefetchSpans\n\nNumber of spans to return per matching trace (1-100), root span first. Useful to preview trace structure without a separate `apm-trace-get`. With the default (1) you get one span per trace (the root); raise it to also pull the matching children and their siblings (check `matched_filter` to tell them apart). Ignored when `rootSpans: true`, which always returns just the root.\n\n## query.excludeAttributes\n\nSet `true` to drop the per-span `attributes` map from results (the map stays present but empty). The attribute map holds multi-KB values like `db.statement`, so excluding it keeps large result sets compact — set it when you only need span structure/timing (`name`, `service_name`, `duration_nano`, `parent_span_id`) and not the OTel attributes. Defaults to false.\n\n# Examples\n\n## List recent error spans\n\n```json\n{\n \"query\": {\n \"statusCodes\": [500, 503]\n }\n}\n```\n\n## Search spans from a specific service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Filter by a span attribute\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"http.method\", \"operator\": \"exact\", \"type\": \"span_attribute\", \"value\": \"POST\" }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Find slow spans\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"duration\", \"operator\": \"gt\", \"type\": \"span\", \"value\": \"1000000000\" }],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Combine service and attribute filters\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"web-server\"],\n \"filterGroup\": [{ \"key\": \"http.status_code\", \"operator\": \"gt\", \"type\": \"span_attribute\", \"value\": \"399\" }],\n \"dateRange\": { \"date_from\": \"-12h\" }\n }\n}\n```\n\n## Check if a resource attribute exists\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"k8s.pod.name\", \"operator\": \"is_set\", \"type\": \"span_resource_attribute\" }]\n }\n}\n```\n\n# Reminders\n\n- Ensure that any property filters are directly relevant to the user's question. Avoid unnecessary filtering.\n- Use `apm-attributes-list` and `apm-attribute-values-list` to discover attributes before guessing filter keys/values.\n- Use `apm-services-list` to discover available services before filtering by service name.\n- Duration values are in nanoseconds (1 second = 1,000,000,000 nanoseconds).","category": "Tracing",@@ -6797,6 +6825,20 @@"readOnlyHint": true}},+ "workflow-health": {+ "description": "Per-workflow CI health over a window: run count, success rate, p50/p95 duration, and last failure time. Use this for \"is CI getting faster or slower\", \"which GitHub Actions workflow is the slow or flaky long pole\", and CI duration trends. Rates and percentiles are over completed runs only and are null for a window with no completed runs; to get a trend, call this over two adjacent windows and compare.",+ "category": "Engineering analytics",+ "feature": "engineering_analytics",+ "summary": "Per-workflow CI health",+ "title": "Per-workflow CI health",+ "required_scopes": ["engineering_analytics:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"workflows-archive": {"description": "Archive a draft or disabled workflow.","category": "Workflows",diff --git a/services/mcp/src/generated/engineering_analytics/api.ts b/services/mcp/src/generated/engineering_analytics/api.tsnew file mode 100644index 000000000000..f86504d3256b--- /dev/null+++ b/services/mcp/src/generated/engineering_analytics/api.ts@@ -0,0 +1,61 @@+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * MCP service uses these Zod schemas for generated tool handlers.+ * To regenerate: hogli build:openapi+ *+ * PostHog API - MCP 3 enabled ops+ * OpenAPI spec version: 1.0.0+ */+import * as zod from 'zod'++/**+ * The timeline of a single pull request: header plus ordered events (opened, CI started/finished, merged or closed). Use this to answer 'where is this PR stuck and what happened to it'. This is a partial view: review and comment events are not yet available.+ */+export const EngineeringAnalyticsPrLifecycleParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+})++export const EngineeringAnalyticsPrLifecycleQueryParams = /* @__PURE__ */ zod.object({+ pr_number: zod.number().describe('Pull request number to inspect.'),+ repo: zod+ .string()+ .optional()+ .describe(+ "Optional 'owner/name' repository to disambiguate when the PR number exists in more than one connected repo."+ ),+})++/**+ * Open pull requests plus any merged or closed since date_from (default -30d), newest first, each with its head-SHA CI rollup. The list is capped; when more match, `truncated` is true and the ci_cards counts can exceed it. open_to_merge_seconds is coarse — it fuses draft and ready-for-review time; CI counts can lag until late completions settle.+ */+export const EngineeringAnalyticsPullRequestsParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+})++export const EngineeringAnalyticsPullRequestsQueryParams = /* @__PURE__ */ zod.object({+ date_from: zod.string().optional().describe("Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d."),+})++/**+ * Per-workflow CI health over a window (default last 30 days): run count, success rate, p50/p95 duration over completed runs, and last failure time. Use this for 'is CI getting slower' and 'which workflow is the long pole'; compare two windows to get a trend.+ */+export const EngineeringAnalyticsWorkflowHealthParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+})++export const EngineeringAnalyticsWorkflowHealthQueryParams = /* @__PURE__ */ zod.object({+ date_from: zod.string().optional().describe("Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d."),+ date_to: zod.string().optional().describe('Window end: relative or ISO8601. Defaults to now.'),+})diff --git a/services/mcp/src/tools/generated/engineering_analytics.ts b/services/mcp/src/tools/generated/engineering_analytics.tsnew file mode 100644index 000000000000..67a429504499--- /dev/null+++ b/services/mcp/src/tools/generated/engineering_analytics.ts@@ -0,0 +1,91 @@+// AUTO-GENERATED from products/engineering_analytics/mcp/tools.yaml + OpenAPI — do not edit+import { z } from 'zod'++import type { Schemas } from '@/api/generated'+import {+ EngineeringAnalyticsPrLifecycleQueryParams,+ EngineeringAnalyticsPullRequestsQueryParams,+ EngineeringAnalyticsWorkflowHealthQueryParams,+} from '@/generated/engineering_analytics/api'+import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'+import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'++const PrLifecycleSchema = EngineeringAnalyticsPrLifecycleQueryParams.extend({+ pr_number: EngineeringAnalyticsPrLifecycleQueryParams.shape['pr_number'].describe(+ 'Pull request number to inspect.'+ ),+ repo: EngineeringAnalyticsPrLifecycleQueryParams.shape['repo'].describe(+ "Optional 'owner/name' repository to disambiguate when the PR number exists in more than one connected repo."+ ),+})++const prLifecycle = (): ToolBase<typeof PrLifecycleSchema, Schemas.PRLifecycle> => ({+ name: 'pr-lifecycle',+ schema: PrLifecycleSchema,+ handler: async (context: Context, params: z.infer<typeof PrLifecycleSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.PRLifecycle>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/engineering_analytics/pr_lifecycle/`,+ query: {+ pr_number: params.pr_number,+ repo: params.repo,+ },+ })+ return result+ },+})++const PullRequestsSchema = EngineeringAnalyticsPullRequestsQueryParams.extend({+ date_from: EngineeringAnalyticsPullRequestsQueryParams.shape['date_from'].describe(+ "Recency floor for merged/closed PRs — relative ('-30d', '-8w') or ISO8601. Open PRs are always included regardless of age. Defaults to -30d."+ ),+})++const pullRequests = (): ToolBase<typeof PullRequestsSchema, WithPostHogUrl<Schemas.PullRequestList>> => ({+ name: 'pull-requests',+ schema: PullRequestsSchema,+ handler: async (context: Context, params: z.infer<typeof PullRequestsSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.PullRequestList>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/engineering_analytics/pull_requests/`,+ query: {+ date_from: params.date_from,+ },+ })+ return await withPostHogUrl(context, result, '/engineering_analytics')+ },+})++const WorkflowHealthSchema = EngineeringAnalyticsWorkflowHealthQueryParams.extend({+ date_from: EngineeringAnalyticsWorkflowHealthQueryParams.shape['date_from'].describe(+ "Window start — relative ('-30d', '-8w') or ISO8601. Defaults to -30d."+ ),+ date_to: EngineeringAnalyticsWorkflowHealthQueryParams.shape['date_to'].describe(+ 'Window end — relative or ISO8601. Defaults to now.'+ ),+})++const workflowHealth = (): ToolBase<typeof WorkflowHealthSchema, WithPostHogUrl<Schemas.WorkflowHealthItem[]>> => ({+ name: 'workflow-health',+ schema: WorkflowHealthSchema,+ handler: async (context: Context, params: z.infer<typeof WorkflowHealthSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.WorkflowHealthItem[]>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/engineering_analytics/workflow_health/`,+ query: {+ date_from: params.date_from,+ date_to: params.date_to,+ },+ })+ return await withPostHogUrl(context, result, '/engineering_analytics')+ },+})++export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {+ 'pr-lifecycle': prLifecycle,+ 'pull-requests': pullRequests,+ 'workflow-health': workflowHealth,+}diff --git a/services/mcp/src/tools/generated/index.ts b/services/mcp/src/tools/generated/index.tsindex f732bc25a042..56495a5ea332 100644--- a/services/mcp/src/tools/generated/index.ts+++ b/services/mcp/src/tools/generated/index.ts@@ -17,6 +17,7 @@ import { GENERATED_TOOLS as data_warehouse } from './data_warehouse'import { GENERATED_TOOLS as docs } from './docs'import { GENERATED_TOOLS as early_access_features } from './early_access_features'import { GENERATED_TOOLS as endpoints } from './endpoints'+import { GENERATED_TOOLS as engineering_analytics } from './engineering_analytics'import { GENERATED_TOOLS as error_tracking } from './error_tracking'import { GENERATED_TOOLS as experiments } from './experiments'import { GENERATED_TOOLS as feature_flags } from './feature_flags'@@ -59,6 +60,7 @@ export const GENERATED_TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> =...docs,...early_access_features,...endpoints,+ ...engineering_analytics,...error_tracking,...experiments,...feature_flags,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/pr-lifecycle.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/pr-lifecycle.jsonnew file mode 100644index 000000000000..1e87341f8e0a--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/pr-lifecycle.json@@ -0,0 +1,15 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "pr_number": {+ "description": "Pull request number to inspect.",+ "type": "number"+ },+ "repo": {+ "description": "Optional 'owner/name' repository to disambiguate when the PR number exists in more than one connected repo.",+ "type": "string"+ }+ },+ "required": ["pr_number"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/pull-requests.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/pull-requests.jsonnew file mode 100644index 000000000000..5e3bdc2305a9--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/pull-requests.json@@ -0,0 +1,10 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "date_from": {+ "description": "Recency floor for merged/closed PRs — relative ('-30d', '-8w') or ISO8601. Open PRs are always included regardless of age. Defaults to -30d.",+ "type": "string"+ }+ },+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflow-health.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflow-health.jsonnew file mode 100644index 000000000000..84375af3ceb2--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflow-health.json@@ -0,0 +1,14 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "date_from": {+ "description": "Window start — relative ('-30d', '-8w') or ISO8601. Defaults to -30d.",+ "type": "string"+ },+ "date_to": {+ "description": "Window end — relative or ISO8601. Defaults to now.",+ "type": "string"+ }+ },+ "type": "object"+}