Skip to content

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

feat(engineering-analytics): enable cost MCP tools + repo consistency (#66624)

Julian Bez58eaf3b59be7
diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.py
index 1e13871963ca..34cf1a900856 100644
--- a/products/engineering_analytics/backend/facade/api.py
+++ b/products/engineering_analytics/backend/facade/api.py
@@ -55,7 +55,7 @@ def get_pr_lifecycle(
*,
team: Team,
pr_number: int,
- repo: str | None = None,
+ repo: str,
source_id: str | None = None,
user_access_control: "UserAccessControl | None" = None,
) -> PRLifecycle | None:
diff --git a/products/engineering_analytics/backend/logic/__init__.py b/products/engineering_analytics/backend/logic/__init__.py
index 5d90605a46d5..f0f2975729c3 100644
--- a/products/engineering_analytics/backend/logic/__init__.py
+++ b/products/engineering_analytics/backend/logic/__init__.py
@@ -58,6 +58,8 @@ _MAX_WINDOW_DAYS = 366
# handle. They validate their own inputs (dates, repo) and read PR/CI data through the handle.
def build_pr_lifecycle(*, curated: CuratedGitHubSource, pr_number: int, repo: str | None) -> PRLifecycle | None:
owner, name = _split_repo(repo)
+ if not (owner and name):
+ raise ValueError("repo must be in 'owner/name' format")
return query_pr_lifecycle(curated=curated, pr_number=pr_number, repo_owner=owner, repo_name=name)
diff --git a/products/engineering_analytics/backend/logic/queries/pr_lifecycle.py b/products/engineering_analytics/backend/logic/queries/pr_lifecycle.py
index 83a728b9246c..1ea4711f62db 100644
--- a/products/engineering_analytics/backend/logic/queries/pr_lifecycle.py
+++ b/products/engineering_analytics/backend/logic/queries/pr_lifecycle.py
@@ -32,7 +32,7 @@ _HEADER = """
author_handle, author_avatar_url, is_bot,
repo_owner, repo_name, head_sha
FROM __PR_SOURCE__ AS pr
- WHERE number = {pr_number} __REPO_FILTER__
+ WHERE number = {pr_number} AND repo_owner = {repo_owner} AND repo_name = {repo_name}
ORDER BY created_at DESC
LIMIT 1
"""
@@ -49,17 +49,15 @@ def query_pr_lifecycle(
*,
curated: CuratedGitHubSource,
pr_number: int,
- repo_owner: str | None,
- repo_name: str | None,
+ repo_owner: str,
+ repo_name: str,
) -> PRLifecycle | None:
- placeholders: dict[str, ast.Expr] = {"pr_number": ast.Constant(value=pr_number)}
- repo_filter = ""
- if repo_owner and repo_name:
- repo_filter = "AND repo_owner = {repo_owner} AND repo_name = {repo_name}"
- placeholders["repo_owner"] = ast.Constant(value=repo_owner)
- placeholders["repo_name"] = ast.Constant(value=repo_name)
-
- header_sql = _HEADER.replace("__PR_SOURCE__", curated.pr_source()).replace("__REPO_FILTER__", repo_filter)
+ placeholders: dict[str, ast.Expr] = {
+ "pr_number": ast.Constant(value=pr_number),
+ "repo_owner": ast.Constant(value=repo_owner),
+ "repo_name": ast.Constant(value=repo_name),
+ }
+ header_sql = _HEADER.replace("__PR_SOURCE__", curated.pr_source())
header = curated.run(
header_sql,
query_type="engineering_analytics.pr_lifecycle.header",
diff --git a/products/engineering_analytics/backend/presentation/views.py b/products/engineering_analytics/backend/presentation/views.py
index d82a5f6f8640..92a9fa41a697 100644
--- a/products/engineering_analytics/backend/presentation/views.py
+++ b/products/engineering_analytics/backend/presentation/views.py
@@ -37,15 +37,6 @@ from products.engineering_analytics.backend.presentation.serializers import (
ENGINEERING_ANALYTICS_TAG = "engineering_analytics"
-_REPO = OpenApiParameter(
- name="repo",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=False,
- description="Optional 'owner/name' repository to disambiguate when the PR number exists in more than one "
- "connected repo.",
-)
-
_DATE_FROM = OpenApiParameter(
name="date_from",
type=OpenApiTypes.STR,
@@ -264,12 +255,18 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
required=True,
description="Pull request number to inspect.",
),
- _REPO,
+ OpenApiParameter(
+ name="repo",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="'owner/name' repository the pull request belongs to.",
+ ),
_SOURCE_ID,
],
responses={
200: PRLifecycleSerializer,
- 400: OpenApiResponse(description="Missing or non-integer pr_number, or invalid repo or source_id."),
+ 400: OpenApiResponse(description="Missing pr_number/repo, or invalid repo or source_id."),
404: OpenApiResponse(description="No pull request with that number in the warehouse."),
},
description=(
@@ -280,11 +277,15 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
)
@action(detail=False, methods=["get"], pagination_class=None)
def pr_lifecycle(self, request: Request, **kwargs) -> Response:
+ repo = request.query_params.get("repo")
try:
+ pr_number = _require_int_param(request, "pr_number")
+ if not repo:
+ raise ValueError("repo is required")
result = api.get_pr_lifecycle(
team=self.team,
- pr_number=_require_int_param(request, "pr_number"),
- repo=request.query_params.get("repo") or None,
+ pr_number=pr_number,
+ repo=repo,
source_id=request.query_params.get("source_id") or None,
user_access_control=self.user_access_control,
)
diff --git a/products/engineering_analytics/backend/tests/test_logic.py b/products/engineering_analytics/backend/tests/test_logic.py
index d32bcdf61c64..7ca714f6b636 100644
--- a/products/engineering_analytics/backend/tests/test_logic.py
+++ b/products/engineering_analytics/backend/tests/test_logic.py
@@ -218,7 +218,7 @@ class TestPRLifecycleMapping(BaseTest):
def test_returns_none_when_not_found(self) -> None:
with mock.patch(_RUN_QUERY, return_value=_resp([])):
- assert api.get_pr_lifecycle(team=self.team, pr_number=999, repo=None) is None
+ assert api.get_pr_lifecycle(team=self.team, pr_number=999, repo="PostHog/posthog") is None
@parameterized.expand(["PostHog", "PostHog/", "/posthog", "/"])
def test_malformed_repo_raises_before_querying(self, repo: str) -> None:
@@ -231,7 +231,7 @@ class TestPRLifecycleMapping(BaseTest):
# is_bot and state come from the curated query as columns; the logic layer does not re-derive them.
header = _header("closed", merged_at=None, closed_at=_dt("2026-01-12T15:00:00"), is_bot=True, head_sha="")
with mock.patch(_RUN_QUERY, return_value=_resp([header])):
- lifecycle = api.get_pr_lifecycle(team=self.team, pr_number=10, repo=None)
+ lifecycle = api.get_pr_lifecycle(team=self.team, pr_number=10, repo="PostHog/posthog")
assert lifecycle is not None
assert lifecycle.pull_request.state == PRState.CLOSED
diff --git a/products/engineering_analytics/backend/tests/test_presentation.py b/products/engineering_analytics/backend/tests/test_presentation.py
index 4e8e9746c4c1..574333bdf161 100644
--- a/products/engineering_analytics/backend/tests/test_presentation.py
+++ b/products/engineering_analytics/backend/tests/test_presentation.py
@@ -212,7 +212,7 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):
def test_pr_lifecycle_404_when_not_found(self) -> None:
with mock.patch(f"{_VIEWS}.get_pr_lifecycle", return_value=None):
- response = self.client.get(self._url("pr_lifecycle"), {"pr_number": "999"})
+ response = self.client.get(self._url("pr_lifecycle"), {"pr_number": "999", "repo": "PostHog/posthog"})
assert response.status_code == status.HTTP_404_NOT_FOUND
@@ -221,6 +221,12 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
+ def test_pr_lifecycle_400_when_repo_missing(self) -> None:
+ # repo is required (a PR number is repo-scoped), consistent with pr_runs/pr_cost.
+ response = self.client.get(self._url("pr_lifecycle"), {"pr_number": "10"})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
def test_workflow_run_serializes(self) -> None:
with mock.patch(f"{_VIEWS}.get_workflow_run", return_value=_workflow_run()) as get:
response = self.client.get(self._url("workflow_run"), {"run_id": "7777"})
diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.ts
index 4ddd46af53e6..bcb82a8d4b3d 100644
--- a/products/engineering_analytics/frontend/generated/api.schemas.ts
+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts
@@ -568,9 +568,9 @@ export type EngineeringAnalyticsPrLifecycleParams = {
*/
pr_number: number
/**
- * Optional 'owner/name' repository to disambiguate when the PR number exists in more than one connected repo.
+ * 'owner/name' repository the pull request belongs to.
*/
- repo?: string
+ repo: string
/**
* Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
*/
diff --git a/products/engineering_analytics/mcp/tools.yaml b/products/engineering_analytics/mcp/tools.yaml
index 197ffa0e7cc0..6e659bcbdd76 100644
--- a/products/engineering_analytics/mcp/tools.yaml
+++ b/products/engineering_analytics/mcp/tools.yaml
@@ -14,7 +14,22 @@ tools:
enabled: false
engineering-analytics-pr-cost:
operation: engineering_analytics_pr_cost
- enabled: false
+ enabled: true
+ scopes:
+ - engineering_analytics:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Estimated CI cost of a PR
+ description: >
+ Estimated CI dollar cost of one pull request, summed over the jobs of all its workflow runs, with breakdowns
+ per workflow (by_workflow) and per run (by_run). Reach for this instead of summing runner minutes by hand:
+ the estimate already classifies runners (billable self-hosted Linux vs free GitHub-hosted), applies the
+ per-vCPU price ladder, and excludes non-Linux and provider-hosted jobs. jobs_available is false when the
+ job-level source isn't synced yet — every figure is then zero/null, so check it before trusting a $0.00.
+ estimated_cost_usd is null (not zero) when nothing was costable, and unsettled_jobs counts billable jobs
+ still running that are left out of the estimate.
engineering-analytics-pr-runs:
operation: engineering_analytics_pr_runs
enabled: false
@@ -39,13 +54,42 @@ tools:
source. With a single source you can skip it — the other tools default to the oldest connected source.
engineering-analytics-workflow-jobs:
operation: engineering_analytics_workflow_jobs
- enabled: false
+ enabled: true
+ scopes:
+ - engineering_analytics:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ list: true
+ title: Jobs of a workflow run
+ description: >
+ The jobs of a single workflow run attempt, each with its status, conclusion, wall-clock duration_seconds,
+ runner tier (runner_provider / runner_label), and estimated_cost_usd. Use this to see where a run spent its
+ time and money job-by-job, or to find the slow or expensive job in a run. Scoped to one run_attempt (the
+ latest unless you pass run_attempt) so a re-run's attempts don't merge. estimated_cost_usd is null for free
+ GitHub-hosted, non-Linux, or unfinished jobs. Returns an empty list when the job-level source isn't synced
+ yet.
engineering-analytics-workflow-run:
operation: engineering_analytics_workflow_run
enabled: false
engineering-analytics-workflow-runner-costs:
operation: engineering_analytics_workflow_runner_costs
- enabled: false
+ enabled: true
+ scopes:
+ - engineering_analytics:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ list: true
+ title: Workflow cost by runner tier
+ description: >
+ One workflow's estimated CI cost broken down by runner tier over a window (date_from default -30d), highest
+ spend first. Each row is a tier (provider + runner_label) with its job_count, billable_minutes, and
+ estimated_cost_usd. Use this for "which runner tier drives this workflow's CI bill" and to spot oversized
+ runners. Billable self-hosted Linux tiers carry a cost; github-hosted and non-Linux rows are null. Returns
+ an empty list when the job-level source isn't synced yet.
engineering-analytics-workflow-runs:
operation: engineering_analytics_workflow_runs
enabled: false
@@ -64,11 +108,6 @@ tools:
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
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index ea46ea3f4186..bb65325fe673 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -2319,6 +2319,20 @@
"readOnlyHint": true
}
},
+ "engineering-analytics-pr-cost": {
+ "description": "Estimated CI dollar cost of one pull request, summed over the jobs of all its workflow runs, with breakdowns per workflow (by_workflow) and per run (by_run). Reach for this instead of summing runner minutes by hand: the estimate already classifies runners (billable self-hosted Linux vs free GitHub-hosted), applies the per-vCPU price ladder, and excludes non-Linux and provider-hosted jobs. jobs_available is false when the job-level source isn't synced yet — every figure is then zero/null, so check it before trusting a $0.00. estimated_cost_usd is null (not zero) when nothing was costable, and unsettled_jobs counts billable jobs still running that are left out of the estimate.",
+ "category": "Engineering analytics",
+ "feature": "engineering_analytics",
+ "summary": "Estimated CI cost of a PR",
+ "title": "Estimated CI cost of a PR",
+ "required_scopes": ["engineering_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"engineering-analytics-sources": {
"description": "The team's connected GitHub data warehouse sources, oldest first, each with its id, repo (owner/name), and table prefix. Call this first when a team may have more than one GitHub source, then pass a chosen id as source_id to the pull-requests, workflow-health, ci-cards, or pr-lifecycle tools to read that specific source. With a single source you can skip it — the other tools default to the oldest connected source.",
"category": "Engineering analytics",
@@ -2333,6 +2347,34 @@
"readOnlyHint": true
}
},
+ "engineering-analytics-workflow-jobs": {
+ "description": "The jobs of a single workflow run attempt, each with its status, conclusion, wall-clock duration_seconds, runner tier (runner_provider / runner_label), and estimated_cost_usd. Use this to see where a run spent its time and money job-by-job, or to find the slow or expensive job in a run. Scoped to one run_attempt (the latest unless you pass run_attempt) so a re-run's attempts don't merge. estimated_cost_usd is null for free GitHub-hosted, non-Linux, or unfinished jobs. Returns an empty list when the job-level source isn't synced yet.",
+ "category": "Engineering analytics",
+ "feature": "engineering_analytics",
+ "summary": "Jobs of a workflow run",
+ "title": "Jobs of a workflow run",
+ "required_scopes": ["engineering_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
+ "engineering-analytics-workflow-runner-costs": {
+ "description": "One workflow's estimated CI cost broken down by runner tier over a window (date_from default -30d), highest spend first. Each row is a tier (provider + runner_label) with its job_count, billable_minutes, and estimated_cost_usd. Use this for \"which runner tier drives this workflow's CI bill\" and to spot oversized runners. Billable self-hosted Linux tiers carry a cost; github-hosted and non-Linux rows are null. Returns an empty list when the job-level source isn't synced yet.",
+ "category": "Engineering analytics",
+ "feature": "engineering_analytics",
+ "summary": "Workflow cost by runner tier",
+ "title": "Workflow cost by runner tier",
+ "required_scopes": ["engineering_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"error-tracking-alerts-create": {
"description": "Create an error tracking alert that fires when an issue is created, reopened, or starts spiking. An alert is a HogFunction with `type=internal_destination` whose `filters.events` references one of the three error-tracking lifecycle events. The events themselves are the trigger — there is no threshold or evaluation window to configure.\n\nTrigger events:\n- `$error_tracking_issue_created` — fires once when a new issue first appears.\n- `$error_tracking_issue_reopened` — fires when a previously resolved issue starts emitting again.\n- `$error_tracking_issue_spiking` — fires when the spike detector flags abnormal volume on an\n issue. The spike threshold is configured separately via the spike detection config endpoint\n and applies to all issues in the project.\n\n\nRecipe — deliver an error tracking alert to Slack or a webhook:\n\n1. Confirm the trigger and channel with the user. Picking `created` for a noisy project will\n flood the channel; `spiking` is usually the safer default. Do not assume.\n\n\n2. Pick the integration. For Slack, call `integrations-list` with `kind=slack` to find the\n integration id, then `integrations-channels-retrieve` for that integration to list channels.\n For a webhook, the user provides the destination URL directly. Confirm the channel name or\n webhook URL with the user before creating the alert — never wire a new alert to a production\n channel without explicit confirmation.\n\n\n3. Dedupe. Call `error-tracking-alerts-list` and check whether an alert for the same trigger\n event already exists. Skip creation if one is present and enabled — call\n `error-tracking-alerts-partial-update` to adjust an existing alert instead of creating a\n duplicate. Several alerts on the same event for the same channel produce duplicate\n notifications.\n\n\n4. Create. Use `type=internal_destination`, the integration's `template_id`\n (`template-slack`, `template-webhook`, `template-discord`, `template-microsoft-teams`,\n `template-linear`, `template-github`, or `template-gitlab`), and:\n\n filters = {\n \"events\": [{\"id\": \"$error_tracking_issue_created\", \"type\": \"events\"}]\n }\n\n Optional per-issue scoping (`created`/`reopened` only): add a `filters.properties` clause\n on `$exception_issue_id` — for example\n `[{\"key\": \"$exception_issue_id\", \"value\": \"<issue_uuid>\", \"operator\": \"exact\", \"type\": \"event\"}]`\n to alert only on a specific known-flaky issue. `$error_tracking_issue_spiking` events carry\n no exception properties, so spiking alerts cannot be scoped per issue. PostHog's \"alerts\n configured\" recommendation only checks `filters.events`, so adding property filters does\n not affect it.\n\n\n5. Slack message body. Mirror the shape the in-product alert wizard produces so agent-created\n and UI-created alerts look identical. The canonical payloads for every integration are in\n the `authoring-error-tracking-alerts` skill references.\n\n For `$error_tracking_issue_created` (Slack):\n\n inputs = {\n \"slack_workspace\": {\"value\": <slack_integration_id_int>},\n \"channel\": {\"value\": \"<channel_id>\"},\n \"text\": {\"value\": \"New issue created: {event.properties.name}\"},\n \"blocks\": {\"value\": [\n {\"type\": \"header\", \"text\": {\"type\": \"plain_text\",\n \"text\": \"🔴 {event.properties.name}\"}},\n {\"type\": \"section\", \"text\": {\"type\": \"plain_text\", \"text\": \"New issue created\"}},\n {\"type\": \"section\", \"text\": {\"type\": \"mrkdwn\",\n \"text\": \"```{substring(event.properties.description, 1, 150)}```\"}},\n {\"type\": \"context\", \"elements\": [\n {\"type\": \"plain_text\", \"text\": \"Status: {event.properties.status}\"},\n {\"type\": \"mrkdwn\", \"text\": \"Project: <{project.url}|{project.name}>\"},\n {\"type\": \"mrkdwn\", \"text\": \"Alert: <{source.url}|{source.name}>\"}\n ]},\n {\"type\": \"divider\"},\n {\"type\": \"actions\", \"elements\": [\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Issue\"},\n \"url\": \"{project.url}/error_tracking/{event.distinct_id}?fingerprint={event.properties.fingerprint}&timestamp={event.properties.exception_timestamp}&utm_source=alert&utm_campaign=error_tracking_alert&utm_medium=slack\"}\n ]}\n ]}\n }\n\n For `$error_tracking_issue_reopened`, use the same blocks with the header swapped to\n `🔄 {event.properties.name}`, the section text to `Issue reopened`, and `text` to\n `Issue reopened: {event.properties.name}`.\n\n For `$error_tracking_issue_spiking` (Slack), use the same shape but swap the header to\n `📈 Issue spiking`, drop the `fingerprint`/`timestamp` params from the button URL (spiking\n events do not carry them), and add a context line referencing\n `{event.properties.current_bucket_value}` and `{event.properties.computed_baseline}`. The\n exact block layout is in the `authoring-error-tracking-alerts` skill references.\n\n\n6. Webhook body. The webhook template only requires `url`:\n\n inputs = {\"url\": {\"value\": \"<destination_url>\"}}\n\n Webhooks must be `https://` URLs.\n\n\nEvent property reference — common across all three events: `event.properties.name` (issue title), `event.properties.description` (truncated body), `event.distinct_id` (issue id used in the deep link). `created`/`reopened` additionally expose `event.properties.status`, `event.properties.fingerprint`, `event.properties.exception_timestamp`, and the originating exception's properties (e.g. `$exception_types`, `$exception_issue_id`). Spiking events instead expose `event.properties.current_bucket_value` and `event.properties.computed_baseline` — no status, fingerprint, or exception properties. Project context is available as `{project.url}` (already includes `/project/<team_id>`), `{project.name}`, and the alert's own metadata as `{source.url}` and `{source.name}`.",
"category": "Error tracking alerts",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index a7f7bef696b2..45841bd61f72 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -2363,6 +2363,20 @@
"readOnlyHint": true
}
},
+ "engineering-analytics-pr-cost": {
+ "description": "Estimated CI dollar cost of one pull request, summed over the jobs of all its workflow runs, with breakdowns per workflow (by_workflow) and per run (by_run). Reach for this instead of summing runner minutes by hand: the estimate already classifies runners (billable self-hosted Linux vs free GitHub-hosted), applies the per-vCPU price ladder, and excludes non-Linux and provider-hosted jobs. jobs_available is false when the job-level source isn't synced yet — every figure is then zero/null, so check it before trusting a $0.00. estimated_cost_usd is null (not zero) when nothing was costable, and unsettled_jobs counts billable jobs still running that are left out of the estimate.",
+ "category": "Engineering analytics",
+ "feature": "engineering_analytics",
+ "summary": "Estimated CI cost of a PR",
+ "title": "Estimated CI cost of a PR",
+ "required_scopes": ["engineering_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"engineering-analytics-sources": {
"description": "The team's connected GitHub data warehouse sources, oldest first, each with its id, repo (owner/name), and table prefix. Call this first when a team may have more than one GitHub source, then pass a chosen id as source_id to the pull-requests, workflow-health, ci-cards, or pr-lifecycle tools to read that specific source. With a single source you can skip it — the other tools default to the oldest connected source.",
"category": "Engineering analytics",
@@ -2377,6 +2391,34 @@
"readOnlyHint": true
}
},
+ "engineering-analytics-workflow-jobs": {
+ "description": "The jobs of a single workflow run attempt, each with its status, conclusion, wall-clock duration_seconds, runner tier (runner_provider / runner_label), and estimated_cost_usd. Use this to see where a run spent its time and money job-by-job, or to find the slow or expensive job in a run. Scoped to one run_attempt (the latest unless you pass run_attempt) so a re-run's attempts don't merge. estimated_cost_usd is null for free GitHub-hosted, non-Linux, or unfinished jobs. Returns an empty list when the job-level source isn't synced yet.",
+ "category": "Engineering analytics",
+ "feature": "engineering_analytics",
+ "summary": "Jobs of a workflow run",
+ "title": "Jobs of a workflow run",
+ "required_scopes": ["engineering_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
+ "engineering-analytics-workflow-runner-costs": {
+ "description": "One workflow's estimated CI cost broken down by runner tier over a window (date_from default -30d), highest spend first. Each row is a tier (provider + runner_label) with its job_count, billable_minutes, and estimated_cost_usd. Use this for \"which runner tier drives this workflow's CI bill\" and to spot oversized runners. Billable self-hosted Linux tiers carry a cost; github-hosted and non-Linux rows are null. Returns an empty list when the job-level source isn't synced yet.",
+ "category": "Engineering analytics",
+ "feature": "engineering_analytics",
+ "summary": "Workflow cost by runner tier",
+ "title": "Workflow cost by runner tier",
+ "required_scopes": ["engineering_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"error-tracking-alerts-create": {
"description": "Create an error tracking alert that fires when an issue is created, reopened, or starts spiking. An alert is a HogFunction with `type=internal_destination` whose `filters.events` references one of the three error-tracking lifecycle events. The events themselves are the trigger — there is no threshold or evaluation window to configure.\n\nTrigger events:\n- `$error_tracking_issue_created` — fires once when a new issue first appears.\n- `$error_tracking_issue_reopened` — fires when a previously resolved issue starts emitting again.\n- `$error_tracking_issue_spiking` — fires when the spike detector flags abnormal volume on an\n issue. The spike threshold is configured separately via the spike detection config endpoint\n and applies to all issues in the project.\n\n\nRecipe — deliver an error tracking alert to Slack or a webhook:\n\n1. Confirm the trigger and channel with the user. Picking `created` for a noisy project will\n flood the channel; `spiking` is usually the safer default. Do not assume.\n\n\n2. Pick the integration. For Slack, call `integrations-list` with `kind=slack` to find the\n integration id, then `integrations-channels-retrieve` for that integration to list channels.\n For a webhook, the user provides the destination URL directly. Confirm the channel name or\n webhook URL with the user before creating the alert — never wire a new alert to a production\n channel without explicit confirmation.\n\n\n3. Dedupe. Call `error-tracking-alerts-list` and check whether an alert for the same trigger\n event already exists. Skip creation if one is present and enabled — call\n `error-tracking-alerts-partial-update` to adjust an existing alert instead of creating a\n duplicate. Several alerts on the same event for the same channel produce duplicate\n notifications.\n\n\n4. Create. Use `type=internal_destination`, the integration's `template_id`\n (`template-slack`, `template-webhook`, `template-discord`, `template-microsoft-teams`,\n `template-linear`, `template-github`, or `template-gitlab`), and:\n\n filters = {\n \"events\": [{\"id\": \"$error_tracking_issue_created\", \"type\": \"events\"}]\n }\n\n Optional per-issue scoping (`created`/`reopened` only): add a `filters.properties` clause\n on `$exception_issue_id` — for example\n `[{\"key\": \"$exception_issue_id\", \"value\": \"<issue_uuid>\", \"operator\": \"exact\", \"type\": \"event\"}]`\n to alert only on a specific known-flaky issue. `$error_tracking_issue_spiking` events carry\n no exception properties, so spiking alerts cannot be scoped per issue. PostHog's \"alerts\n configured\" recommendation only checks `filters.events`, so adding property filters does\n not affect it.\n\n\n5. Slack message body. Mirror the shape the in-product alert wizard produces so agent-created\n and UI-created alerts look identical. The canonical payloads for every integration are in\n the `authoring-error-tracking-alerts` skill references.\n\n For `$error_tracking_issue_created` (Slack):\n\n inputs = {\n \"slack_workspace\": {\"value\": <slack_integration_id_int>},\n \"channel\": {\"value\": \"<channel_id>\"},\n \"text\": {\"value\": \"New issue created: {event.properties.name}\"},\n \"blocks\": {\"value\": [\n {\"type\": \"header\", \"text\": {\"type\": \"plain_text\",\n \"text\": \"🔴 {event.properties.name}\"}},\n {\"type\": \"section\", \"text\": {\"type\": \"plain_text\", \"text\": \"New issue created\"}},\n {\"type\": \"section\", \"text\": {\"type\": \"mrkdwn\",\n \"text\": \"```{substring(event.properties.description, 1, 150)}```\"}},\n {\"type\": \"context\", \"elements\": [\n {\"type\": \"plain_text\", \"text\": \"Status: {event.properties.status}\"},\n {\"type\": \"mrkdwn\", \"text\": \"Project: <{project.url}|{project.name}>\"},\n {\"type\": \"mrkdwn\", \"text\": \"Alert: <{source.url}|{source.name}>\"}\n ]},\n {\"type\": \"divider\"},\n {\"type\": \"actions\", \"elements\": [\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Issue\"},\n \"url\": \"{project.url}/error_tracking/{event.distinct_id}?fingerprint={event.properties.fingerprint}&timestamp={event.properties.exception_timestamp}&utm_source=alert&utm_campaign=error_tracking_alert&utm_medium=slack\"}\n ]}\n ]}\n }\n\n For `$error_tracking_issue_reopened`, use the same blocks with the header swapped to\n `🔄 {event.properties.name}`, the section text to `Issue reopened`, and `text` to\n `Issue reopened: {event.properties.name}`.\n\n For `$error_tracking_issue_spiking` (Slack), use the same shape but swap the header to\n `📈 Issue spiking`, drop the `fingerprint`/`timestamp` params from the button URL (spiking\n events do not carry them), and add a context line referencing\n `{event.properties.current_bucket_value}` and `{event.properties.computed_baseline}`. The\n exact block layout is in the `authoring-error-tracking-alerts` skill references.\n\n\n6. Webhook body. The webhook template only requires `url`:\n\n inputs = {\"url\": {\"value\": \"<destination_url>\"}}\n\n Webhooks must be `https://` URLs.\n\n\nEvent property reference — common across all three events: `event.properties.name` (issue title), `event.properties.description` (truncated body), `event.distinct_id` (issue id used in the deep link). `created`/`reopened` additionally expose `event.properties.status`, `event.properties.fingerprint`, `event.properties.exception_timestamp`, and the originating exception's properties (e.g. `$exception_types`, `$exception_issue_id`). Spiking events instead expose `event.properties.current_bucket_value` and `event.properties.computed_baseline` — no status, fingerprint, or exception properties. Project context is available as `{project.url}` (already includes `/project/<team_id>`), `{project.name}`, and the alert's own metadata as `{source.url}` and `{source.name}`.",
"category": "Error tracking alerts",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 72850411d28a..edafea545ae7 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -60918,9 +60918,9 @@ export namespace Schemas {
*/
pr_number: number;
/**
- * Optional 'owner/name' repository to disambiguate when the PR number exists in more than one connected repo.
+ * 'owner/name' repository the pull request belongs to.
*/
- repo?: string;
+ repo: string;
/**
* Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
*/
diff --git a/services/mcp/src/generated/engineering_analytics/api.ts b/services/mcp/src/generated/engineering_analytics/api.ts
index 64f858e3f504..e56d7410fde2 100644
--- a/services/mcp/src/generated/engineering_analytics/api.ts
+++ b/services/mcp/src/generated/engineering_analytics/api.ts
@@ -3,15 +3,15 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 4 enabled ops
+ * PostHog API - MCP 7 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.
+ * Estimated CI cost for a pull request, summed over the jobs of all its workflow runs. Billable self-hosted Linux runners only — provider-hosted (free GitHub-hosted) and non-Linux jobs are excluded. Every figure is zero/null with `jobs_available` false when the job-level source isn't synced yet.
*/
-export const EngineeringAnalyticsPrLifecycleParams = /* @__PURE__ */ zod.object({
+export const EngineeringAnalyticsPrCostParams = /* @__PURE__ */ zod.object({
project_id: zod
.string()
.describe(
@@ -19,14 +19,31 @@ export const EngineeringAnalyticsPrLifecycleParams = /* @__PURE__ */ zod.object(
),
})
-export const EngineeringAnalyticsPrLifecycleQueryParams = /* @__PURE__ */ zod.object({
- pr_number: zod.number().describe('Pull request number to inspect.'),
- repo: zod
+export const EngineeringAnalyticsPrCostQueryParams = /* @__PURE__ */ zod.object({
+ pr_number: zod.number().describe('Pull request number to estimate cost for.'),
+ repo: zod.string().describe("'owner/name' repository the pull request belongs to."),
+ source_id: zod
.string()
.optional()
.describe(
- "Optional 'owner/name' repository to disambiguate when the PR number exists in more than one connected repo."
+ 'Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.'
+ ),
+})
+
+/**
+ * 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().describe("'owner/name' repository the pull request belongs to."),
source_id: zod
.string()
.optional()
@@ -95,3 +112,54 @@ export const EngineeringAnalyticsWorkflowHealthQueryParams = /* @__PURE__ */ zod
'Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.'
),
})
+
+/**
+ * Jobs of a single workflow run attempt, with per-job duration, runner tier, and estimated cost. Scoped to one run_attempt (the latest unless specified) so a re-run's attempts don't merge. Returns an empty list when the job-level source isn't synced yet.
+ */
+export const EngineeringAnalyticsWorkflowJobsParams = /* @__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 EngineeringAnalyticsWorkflowJobsQueryParams = /* @__PURE__ */ zod.object({
+ run_attempt: zod
+ .number()
+ .optional()
+ .describe(
+ "Which re-run attempt to scope jobs to. Omit to use the run's latest attempt; pass an explicit attempt to avoid mixing jobs across a re-run's attempts."
+ ),
+ run_id: zod.number().describe('Workflow run id to list jobs for.'),
+ source_id: zod
+ .string()
+ .optional()
+ .describe(
+ 'Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.'
+ ),
+})
+
+/**
+ * A workflow's estimated CI cost broken down by runner tier over a window (date_from default -30d), highest spend first. Returns an empty list when the job-level source isn't synced.
+ */
+export const EngineeringAnalyticsWorkflowRunnerCostsParams = /* @__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 EngineeringAnalyticsWorkflowRunnerCostsQueryParams = /* @__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.'),
+ repo: zod.string().describe("'owner/name' repository the workflow belongs to."),
+ source_id: zod
+ .string()
+ .optional()
+ .describe(
+ 'Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.'
+ ),
+ workflow_name: zod.string().describe('Workflow name to break down cost for.'),
+})
diff --git a/services/mcp/src/tools/generated/engineering_analytics.ts b/services/mcp/src/tools/generated/engineering_analytics.ts
index 888d17194cde..0c4dbc78804d 100644
--- a/services/mcp/src/tools/generated/engineering_analytics.ts
+++ b/services/mcp/src/tools/generated/engineering_analytics.ts
@@ -3,13 +3,36 @@ import { z } from 'zod'
import type { Schemas } from '@/api/generated'
import {
+ EngineeringAnalyticsPrCostQueryParams,
EngineeringAnalyticsPrLifecycleQueryParams,
EngineeringAnalyticsPullRequestsQueryParams,
EngineeringAnalyticsWorkflowHealthQueryParams,
+ EngineeringAnalyticsWorkflowJobsQueryParams,
+ EngineeringAnalyticsWorkflowRunnerCostsQueryParams,
} from '@/generated/engineering_analytics/api'
import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
+const EngineeringAnalyticsPrCostSchema = EngineeringAnalyticsPrCostQueryParams
+
+const engineeringAnalyticsPrCost = (): ToolBase<typeof EngineeringAnalyticsPrCostSchema, Schemas.PRCostSummary> => ({
+ name: 'engineering-analytics-pr-cost',
+ schema: EngineeringAnalyticsPrCostSchema,
+ handler: async (context: Context, params: z.infer<typeof EngineeringAnalyticsPrCostSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.PRCostSummary>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/engineering_analytics/pr_cost/`,
+ query: {
+ pr_number: params.pr_number,
+ repo: params.repo,
+ source_id: params.source_id,
+ },
+ })
+ return result
+ },
+})
+
const EngineeringAnalyticsSourcesSchema = z.object({})
const engineeringAnalyticsSources = (): ToolBase<
@@ -29,15 +52,56 @@ const engineeringAnalyticsSources = (): ToolBase<
},
})
-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 EngineeringAnalyticsWorkflowJobsSchema = EngineeringAnalyticsWorkflowJobsQueryParams
+
+const engineeringAnalyticsWorkflowJobs = (): ToolBase<
+ typeof EngineeringAnalyticsWorkflowJobsSchema,
+ WithPostHogUrl<Schemas.WorkflowJob[]>
+> => ({
+ name: 'engineering-analytics-workflow-jobs',
+ schema: EngineeringAnalyticsWorkflowJobsSchema,
+ handler: async (context: Context, params: z.infer<typeof EngineeringAnalyticsWorkflowJobsSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.WorkflowJob[]>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/engineering_analytics/workflow_jobs/`,
+ query: {
+ run_attempt: params.run_attempt,
+ run_id: params.run_id,
+ source_id: params.source_id,
+ },
+ })
+ return await withPostHogUrl(context, result, '/engineering-analytics')
+ },
+})
+
+const EngineeringAnalyticsWorkflowRunnerCostsSchema = EngineeringAnalyticsWorkflowRunnerCostsQueryParams
+
+const engineeringAnalyticsWorkflowRunnerCosts = (): ToolBase<
+ typeof EngineeringAnalyticsWorkflowRunnerCostsSchema,
+ WithPostHogUrl<Schemas.WorkflowRunnerCost[]>
+> => ({
+ name: 'engineering-analytics-workflow-runner-costs',
+ schema: EngineeringAnalyticsWorkflowRunnerCostsSchema,
+ handler: async (context: Context, params: z.infer<typeof EngineeringAnalyticsWorkflowRunnerCostsSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.WorkflowRunnerCost[]>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/engineering_analytics/workflow_runner_costs/`,
+ query: {
+ date_from: params.date_from,
+ date_to: params.date_to,
+ repo: params.repo,
+ source_id: params.source_id,
+ workflow_name: params.workflow_name,
+ },
+ })
+ return await withPostHogUrl(context, result, '/engineering-analytics')
+ },
})
+const PrLifecycleSchema = EngineeringAnalyticsPrLifecycleQueryParams
+
const prLifecycle = (): ToolBase<typeof PrLifecycleSchema, Schemas.PRLifecycle> => ({
name: 'pr-lifecycle',
schema: PrLifecycleSchema,
@@ -109,7 +173,10 @@ const workflowHealth = (): ToolBase<typeof WorkflowHealthSchema, WithPostHogUrl<
})
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
+ 'engineering-analytics-pr-cost': engineeringAnalyticsPrCost,
'engineering-analytics-sources': engineeringAnalyticsSources,
+ 'engineering-analytics-workflow-jobs': engineeringAnalyticsWorkflowJobs,
+ 'engineering-analytics-workflow-runner-costs': engineeringAnalyticsWorkflowRunnerCosts,
'pr-lifecycle': prLifecycle,
'pull-requests': pullRequests,
'workflow-health': workflowHealth,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/engineering-analytics-pr-cost.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/engineering-analytics-pr-cost.json
new file mode 100644
index 000000000000..be6895e52414
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/engineering-analytics-pr-cost.json
@@ -0,0 +1,19 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "pr_number": {
+ "description": "Pull request number to estimate cost for.",
+ "type": "number"
+ },
+ "repo": {
+ "description": "'owner/name' repository the pull request belongs to.",
+ "type": "string"
+ },
+ "source_id": {
+ "description": "Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.",
+ "type": "string"
+ }
+ },
+ "required": ["pr_number", "repo"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/engineering-analytics-workflow-jobs.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/engineering-analytics-workflow-jobs.json
new file mode 100644
index 000000000000..cb09c5ad0e8a
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/engineering-analytics-workflow-jobs.json
@@ -0,0 +1,19 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "run_attempt": {
+ "description": "Which re-run attempt to scope jobs to. Omit to use the run's latest attempt; pass an explicit attempt to avoid mixing jobs across a re-run's attempts.",
+ "type": "number"
+ },
+ "run_id": {
+ "description": "Workflow run id to list jobs for.",
+ "type": "number"
+ },
+ "source_id": {
+ "description": "Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.",
+ "type": "string"
+ }
+ },
+ "required": ["run_id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/engineering-analytics-workflow-runner-costs.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/engineering-analytics-workflow-runner-costs.json
new file mode 100644
index 000000000000..44a3882b908d
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/engineering-analytics-workflow-runner-costs.json
@@ -0,0 +1,27 @@
+{
+ "$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"
+ },
+ "repo": {
+ "description": "'owner/name' repository the workflow belongs to.",
+ "type": "string"
+ },
+ "source_id": {
+ "description": "Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.",
+ "type": "string"
+ },
+ "workflow_name": {
+ "description": "Workflow name to break down cost for.",
+ "type": "string"
+ }
+ },
+ "required": ["repo", "workflow_name"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/pr-lifecycle.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/pr-lifecycle.json
index 2b50921c66a5..a1098de706fb 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/pr-lifecycle.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/pr-lifecycle.json
@@ -6,7 +6,7 @@
"type": "number"
},
"repo": {
- "description": "Optional 'owner/name' repository to disambiguate when the PR number exists in more than one connected repo.",
+ "description": "'owner/name' repository the pull request belongs to.",
"type": "string"
},
"source_id": {
@@ -14,6 +14,6 @@
"type": "string"
}
},
- "required": ["pr_number"],
+ "required": ["pr_number", "repo"],
"type": "object"
}