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(eng-analytics): add github source selector (#63825)

Raúl Negrón-Otero62c159f594ff
diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.py
index c584dccd3ec9..851e0a9693ca 100644
--- a/products/engineering_analytics/backend/facade/api.py
+++ b/products/engineering_analytics/backend/facade/api.py
@@ -22,6 +22,7 @@ from posthog.models.team import Team
from products.engineering_analytics.backend import logic
from products.engineering_analytics.backend.facade.contracts import (
CICardSummary,
+ GitHubSource,
PRLifecycle,
PullRequestList,
WorkflowHealthItem,
@@ -86,3 +87,7 @@ def list_workflow_health(
return logic.build_workflow_health(
curated=_authorized_source(team, source_id, user_access_control), date_from=date_from, date_to=date_to
)
+
+
+def list_github_sources(*, team: Team, user_access_control: "UserAccessControl | None" = None) -> list[GitHubSource]:
+ return logic.build_github_sources(team=team, user_access_control=user_access_control)
diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.py
index e1f716709bca..38d098132005 100644
--- a/products/engineering_analytics/backend/facade/contracts.py
+++ b/products/engineering_analytics/backend/facade/contracts.py
@@ -81,6 +81,20 @@ class PRLifecycleEventKind(StrEnum):
CLOSED = "closed"
+@dataclass(frozen=True)
+class GitHubSource:
+ """A connected GitHub warehouse source the team can analyze. ``id`` is what a
+ caller passes back as ``source_id`` to select this source; ``repo`` and
+ ``prefix`` are display labels so a picker can tell two sources apart.
+ """
+
+ id: str
+ # Connected repository as 'owner/name' (from the source's job inputs), or '' if unknown.
+ repo: str
+ # User-chosen warehouse table-name prefix for this source, or '' when none was set.
+ prefix: str
+
+
@dataclass(frozen=True)
class RepoRef:
provider: str
diff --git a/products/engineering_analytics/backend/logic/__init__.py b/products/engineering_analytics/backend/logic/__init__.py
index ff6f65ddf74f..880918157f03 100644
--- a/products/engineering_analytics/backend/logic/__init__.py
+++ b/products/engineering_analytics/backend/logic/__init__.py
@@ -8,12 +8,14 @@ only in canonical types.
"""
from datetime import datetime
+from typing import TYPE_CHECKING
from posthog.models.team import Team
from posthog.utils import relative_date_parse
from products.engineering_analytics.backend.facade.contracts import (
CICardSummary,
+ GitHubSource,
PRLifecycle,
PullRequestList,
WorkflowHealthItem,
@@ -23,6 +25,10 @@ from products.engineering_analytics.backend.logic.queries.ci_cards import query_
from products.engineering_analytics.backend.logic.queries.pr_lifecycle import query_pr_lifecycle
from products.engineering_analytics.backend.logic.queries.pull_request_list import query_pull_request_list
from products.engineering_analytics.backend.logic.queries.workflow_health import query_workflow_health
+from products.engineering_analytics.backend.logic.sources import list_github_sources
+
+if TYPE_CHECKING:
+ from posthog.rbac.user_access_control import UserAccessControl
# Default recency window when a caller omits date_from. Relative strings (-30d) and
# ISO8601 are both accepted and resolved against the team's timezone.
@@ -45,6 +51,12 @@ def build_ci_cards(*, curated: CuratedGitHubSource) -> CICardSummary:
return query_ci_cards(curated=curated)
+# Listing the team's connected sources is its own concern (no curated read handle): it threads the
+# requesting user's access control so the picker can't enumerate sources the user can't access.
+def build_github_sources(*, team: Team, user_access_control: "UserAccessControl | None" = None) -> list[GitHubSource]:
+ return list_github_sources(team=team, user_access_control=user_access_control)
+
+
def build_pull_request_list(*, curated: CuratedGitHubSource, date_from: str | None = None) -> PullRequestList:
parsed_from = _parse_date(curated.team, date_from or _DEFAULT_WINDOW)
return query_pull_request_list(curated=curated, date_from=parsed_from)
diff --git a/products/engineering_analytics/backend/logic/sources.py b/products/engineering_analytics/backend/logic/sources.py
index 4d5136f5b095..bd62e727008e 100644
--- a/products/engineering_analytics/backend/logic/sources.py
+++ b/products/engineering_analytics/backend/logic/sources.py
@@ -20,10 +20,12 @@ from dataclasses import dataclass
from typing import TYPE_CHECKING
from uuid import UUID
+from django.db.models import QuerySet
+
from posthog.models.team import Team
from products.data_warehouse.backend.types import ExternalDataSourceType
-from products.engineering_analytics.backend.facade.contracts import GitHubSourceNotConnectedError
+from products.engineering_analytics.backend.facade.contracts import GitHubSource, GitHubSourceNotConnectedError
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
@@ -63,21 +65,15 @@ def resolve_github_tables(
presentation layer maps it to a 400, so the UI prompts to connect a source and an agent gets
an actionable error), or ``ValueError`` when ``source_id`` is not a UUID.
- ``user_access_control`` enforces the requesting user's per-source warehouse RBAC: a source the
- user can't access is filtered out before resolution, so a denied ``source_id`` raises (400) and
- the default-oldest path skips it. The curated HogQL runs team-scoped with no user and HogQL does
- not enforce per-user ACL on warehouse tables, so this is the only place that can honor it. None
- (system/Temporal/CLI contexts with no request user) skips filtering — team scoping still holds.
+ ``user_access_control`` enforces the requesting user's per-source warehouse RBAC (applied in
+ ``_github_sources``): a denied ``source_id`` raises (400) and the default-oldest path skips it.
+ The curated HogQL runs team-scoped with no user and HogQL does not enforce per-user ACL on
+ warehouse tables, so honoring it here is the only way the read path can. ``None`` (system/
+ Temporal/CLI contexts with no request user) skips filtering — team scoping still holds.
"""
- sources = (
- ExternalDataSource.objects.filter(team_id=team.pk, source_type=ExternalDataSourceType.GITHUB)
- .exclude(deleted=True)
- .order_by("created_at", "id")
- )
+ sources = _github_sources(team, user_access_control)
if source_id is not None:
sources = sources.filter(id=_as_source_uuid(source_id))
- if user_access_control is not None:
- sources = user_access_control.filter_queryset_by_access_level(sources)
for source in sources:
tables = _synced_table_names(team=team, source=source)
pull_requests = tables.get(PULL_REQUESTS_SCHEMA)
@@ -89,6 +85,43 @@ def resolve_github_tables(
raise GitHubSourceNotConnectedError()
+def list_github_sources(*, team: Team, user_access_control: "UserAccessControl | None" = None) -> list[GitHubSource]:
+ """The team's connected GitHub sources the caller may access, as selectable refs, oldest first.
+
+ Lists every non-deleted GitHub source the user can access — including ones whose endpoints aren't
+ fully synced yet — so a source picker shows everything they connected; selecting an unusable one
+ surfaces the same connect prompt ``resolve_github_tables`` drives. Sources the user can't access
+ (``user_access_control``) are filtered out, so the picker can't enumerate them. Each ``id`` is
+ what the caller passes back as ``source_id`` to read that source.
+ """
+ return [
+ GitHubSource(
+ id=str(source.id),
+ repo=str((source.job_inputs or {}).get("repository") or ""),
+ prefix=source.prefix or "",
+ )
+ for source in _github_sources(team, user_access_control)
+ ]
+
+
+def _github_sources(team: Team, user_access_control: "UserAccessControl | None" = None) -> QuerySet[ExternalDataSource]:
+ """The team's non-deleted GitHub sources the caller may access, oldest first — the order
+ ``resolve_github_tables`` defaults from, so a picker's first entry matches the default source.
+
+ ``user_access_control`` applies the requesting user's per-source warehouse RBAC, so neither the
+ resolver nor the picker can reach a source the user can't access; ``None`` (system/Temporal/CLI
+ contexts) skips it, leaving team scoping. This is the single place that access scope is decided.
+ """
+ sources = (
+ ExternalDataSource.objects.filter(team_id=team.pk, source_type=ExternalDataSourceType.GITHUB)
+ .exclude(deleted=True)
+ .order_by("created_at", "id")
+ )
+ if user_access_control is not None:
+ sources = user_access_control.filter_queryset_by_access_level(sources)
+ return sources
+
+
# Distinct from the no-source message: the caller picked a source that isn't a usable GitHub
# source for this team (wrong id, another team's source, or its endpoints aren't synced).
_NO_SELECTED_SOURCE = "The selected GitHub source isn't connected or has no synced pull_requests/workflow_runs tables."
diff --git a/products/engineering_analytics/backend/presentation/serializers.py b/products/engineering_analytics/backend/presentation/serializers.py
index 385a8407bed1..f4383d9cf69b 100644
--- a/products/engineering_analytics/backend/presentation/serializers.py
+++ b/products/engineering_analytics/backend/presentation/serializers.py
@@ -13,6 +13,7 @@ from products.engineering_analytics.backend.facade.contracts import (
Author,
CICardSummary,
CIStatusRollup,
+ GitHubSource,
PRLifecycle,
PRLifecycleEvent,
PullRequest,
@@ -24,6 +25,16 @@ from products.engineering_analytics.backend.facade.contracts import (
)
+class GitHubSourceSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = GitHubSource
+ extra_kwargs = {
+ "id": {"help_text": "Source id — pass as `source_id` to the other endpoints to read this source."},
+ "repo": {"help_text": "Connected repository as 'owner/name', or '' if unknown."},
+ "prefix": {"help_text": "User-chosen warehouse table-name prefix for this source, or '' when none."},
+ }
+
+
class RepoRefSerializer(DataclassSerializer):
class Meta:
dataclass = RepoRef
diff --git a/products/engineering_analytics/backend/presentation/views.py b/products/engineering_analytics/backend/presentation/views.py
index 996faa0d9d90..1a972a393f98 100644
--- a/products/engineering_analytics/backend/presentation/views.py
+++ b/products/engineering_analytics/backend/presentation/views.py
@@ -23,6 +23,7 @@ from products.engineering_analytics.backend.facade import api
from products.engineering_analytics.backend.facade.contracts import GitHubSourceNotConnectedError
from products.engineering_analytics.backend.presentation.serializers import (
CICardSummarySerializer,
+ GitHubSourceSerializer,
PRLifecycleSerializer,
PullRequestListSerializer,
WorkflowHealthItemSerializer,
@@ -74,7 +75,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
"""PR and CI lifecycle analytics over the GitHub warehouse data."""
scope_object = "engineering_analytics"
- scope_object_read_actions = ["ci_cards", "pull_requests", "workflow_health", "pr_lifecycle"]
+ scope_object_read_actions = ["sources", "ci_cards", "pull_requests", "workflow_health", "pr_lifecycle"]
scope_object_write_actions: list[str] = []
def handle_exception(self, exc: Exception) -> Response:
@@ -83,6 +84,21 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)
return super().handle_exception(exc)
+ @extend_schema(
+ operation_id="engineering_analytics_sources",
+ responses={200: GitHubSourceSerializer(many=True)},
+ description=(
+ "The team's connected GitHub data warehouse sources, oldest first. Populate a source picker "
+ "from this and pass a chosen `id` back as `source_id` to the other endpoints. A team can connect "
+ "GitHub more than once (e.g. one source per repository); this lists them all, including any whose "
+ "tables aren't fully synced yet."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def sources(self, request: Request, **kwargs) -> Response:
+ result = api.list_github_sources(team=self.team, user_access_control=self.user_access_control)
+ return Response(GitHubSourceSerializer(instance=result, many=True).data)
+
@extend_schema(
operation_id="engineering_analytics_ci_cards",
parameters=[_SOURCE_ID],
diff --git a/products/engineering_analytics/backend/tests/test_access_control.py b/products/engineering_analytics/backend/tests/test_access_control.py
index b61ffee03ec8..26c23160d006 100644
--- a/products/engineering_analytics/backend/tests/test_access_control.py
+++ b/products/engineering_analytics/backend/tests/test_access_control.py
@@ -78,3 +78,21 @@ class TestEngineeringAnalyticsAccessControl(WarehouseAccessControlTestMixin):
assert response.status_code == status.HTTP_200_OK
assert response.json()["truncated"] is False
+
+ def test_denied_user_cannot_enumerate_source_b_via_sources(self) -> None:
+ # The picker lists only sources the user can access; B is denied, so it must not appear --
+ # no id/repo/prefix enumeration of a restricted source, and no source_id to feed the reads.
+ self.client.force_login(self.no_access_user)
+ response = self.client.get(self._url("sources"))
+
+ assert response.status_code == status.HTTP_200_OK
+ ids = {source["id"] for source in response.json()}
+ assert str(self.source_a.id) in ids
+ assert str(self.source_b.id) not in ids
+
+ def test_allowed_user_can_enumerate_source_b_via_sources(self) -> None:
+ self.client.force_login(self.editor_user)
+ response = self.client.get(self._url("sources"))
+
+ assert response.status_code == status.HTTP_200_OK
+ assert str(self.source_b.id) in {source["id"] for source in response.json()}
diff --git a/products/engineering_analytics/backend/tests/test_facade.py b/products/engineering_analytics/backend/tests/test_facade.py
index 6b001b1fbb28..1e8ed3ef1189 100644
--- a/products/engineering_analytics/backend/tests/test_facade.py
+++ b/products/engineering_analytics/backend/tests/test_facade.py
@@ -73,3 +73,10 @@ class TestEngineeringAnalyticsFacade(BaseTest):
assert result is mock.sentinel.result
for_team.assert_called_once_with(self.team, **expected_for_team)
build.assert_called_once_with(curated=mock.sentinel.curated, **expected_build)
+
+ def test_list_github_sources_delegates_with_access(self) -> None:
+ with mock.patch(f"{_LOGIC}.build_github_sources", return_value=mock.sentinel.result) as build:
+ result = api.list_github_sources(team=self.team, user_access_control=mock.sentinel.uac)
+
+ assert result is mock.sentinel.result
+ build.assert_called_once_with(team=self.team, user_access_control=mock.sentinel.uac)
diff --git a/products/engineering_analytics/backend/tests/test_logic.py b/products/engineering_analytics/backend/tests/test_logic.py
index ba68f35b973e..78fe51f4d788 100644
--- a/products/engineering_analytics/backend/tests/test_logic.py
+++ b/products/engineering_analytics/backend/tests/test_logic.py
@@ -20,6 +20,7 @@ from products.data_warehouse.backend.test.utils import create_data_warehouse_tab
from products.data_warehouse.backend.types import ExternalDataSourceType
from products.engineering_analytics.backend.facade import api
from products.engineering_analytics.backend.facade.contracts import (
+ GitHubSource,
GitHubSourceNotConnectedError,
MetricQuality,
PRLifecycleEventKind,
@@ -31,6 +32,7 @@ from products.engineering_analytics.backend.logic.sources import (
PULL_REQUESTS_SCHEMA,
WORKFLOW_RUNS_SCHEMA,
GitHubTables,
+ list_github_sources,
resolve_github_tables,
)
from products.engineering_analytics.backend.tests.test_views import (
@@ -410,6 +412,63 @@ class TestResolveGitHubTables(BaseTest):
resolve_github_tables(team=self.team, source_id=str(other_source.id))
+class TestListGitHubSources(BaseTest):
+ """list_github_sources lists every connected GitHub source for a picker (ORM only).
+ Unlike resolve_github_tables it does not require synced tables — a half-synced source the
+ user connected should still be selectable; the empty state handles an unusable pick."""
+
+ def _source(
+ self,
+ *,
+ prefix: str,
+ repository: str | None = None,
+ source_type: ExternalDataSourceType = ExternalDataSourceType.GITHUB,
+ team: Team | None = None,
+ ) -> ExternalDataSource:
+ team = team or self.team
+ return ExternalDataSource.objects.create(
+ team=team,
+ source_id=f"src-{prefix}",
+ connection_id=f"src-{prefix}",
+ status=ExternalDataSource.Status.COMPLETED,
+ source_type=source_type,
+ prefix=prefix,
+ job_inputs={"repository": repository} if repository else {},
+ )
+
+ def test_lists_sources_oldest_first_with_repo_and_prefix(self) -> None:
+ older = self._source(prefix="older", repository="PostHog/posthog")
+ newer = self._source(prefix="newer", repository="PostHog/posthog.com")
+ assert list_github_sources(team=self.team) == [
+ GitHubSource(id=str(older.id), repo="PostHog/posthog", prefix="older"),
+ GitHubSource(id=str(newer.id), repo="PostHog/posthog.com", prefix="newer"),
+ ]
+
+ def test_includes_sources_without_synced_tables(self) -> None:
+ # No schemas/tables linked: resolve_github_tables would reject this, the picker keeps it.
+ source = self._source(prefix="pronly", repository="PostHog/posthog")
+ assert [s.id for s in list_github_sources(team=self.team)] == [str(source.id)]
+
+ def test_repo_is_blank_without_a_repository_input(self) -> None:
+ source = self._source(prefix="noinputs")
+ assert list_github_sources(team=self.team) == [GitHubSource(id=str(source.id), repo="", prefix="noinputs")]
+
+ def test_excludes_non_github_and_soft_deleted_sources(self) -> None:
+ self._source(prefix="stripe", source_type=ExternalDataSourceType.STRIPE)
+ deleted = self._source(prefix="gone", repository="PostHog/posthog")
+ ExternalDataSource.objects.filter(pk=deleted.pk).update(deleted=True)
+ kept = self._source(prefix="kept", repository="PostHog/posthog")
+ assert [s.id for s in list_github_sources(team=self.team)] == [str(kept.id)]
+
+ def test_empty_without_a_github_source(self) -> None:
+ assert list_github_sources(team=self.team) == []
+
+ def test_scoped_to_the_team(self) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ self._source(prefix="theirs", repository="PostHog/posthog", team=other_team)
+ assert list_github_sources(team=self.team) == []
+
+
class TestPRLifecycleWarehouse(_WarehouseMixin, BaseTest):
"""End-to-end through the curated builders over real warehouse tables.
Skips when object storage is unreachable."""
diff --git a/products/engineering_analytics/backend/tests/test_presentation.py b/products/engineering_analytics/backend/tests/test_presentation.py
index 9cc11ec16d1e..f380bd97fa0a 100644
--- a/products/engineering_analytics/backend/tests/test_presentation.py
+++ b/products/engineering_analytics/backend/tests/test_presentation.py
@@ -76,6 +76,21 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):
def _url(self, action: str) -> str:
return f"/api/projects/{self.team.id}/engineering_analytics/{action}/"
+ def test_sources_serializes(self) -> None:
+ sources = [
+ contracts.GitHubSource(id="0192f000-0000-7000-8000-000000000000", repo="PostHog/posthog", prefix="older"),
+ contracts.GitHubSource(
+ id="0192f000-0000-7000-8000-000000000001", repo="PostHog/posthog.com", prefix="website"
+ ),
+ ]
+ with mock.patch(f"{_VIEWS}.list_github_sources", return_value=sources):
+ response = self.client.get(self._url("sources"))
+
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ assert [s["id"] for s in body] == [sources[0].id, sources[1].id]
+ assert body[0] == {"id": sources[0].id, "repo": "PostHog/posthog", "prefix": "older"}
+
def test_ci_cards_serializes(self) -> None:
with mock.patch(f"{_VIEWS}.get_ci_cards", return_value=_cards()):
response = self.client.get(self._url("ci_cards"))
@@ -165,7 +180,7 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "the maximum is 366" in response.json()["detail"]
- @parameterized.expand(["ci_cards", "pull_requests", "workflow_health", "pr_lifecycle"])
+ @parameterized.expand(["sources", "ci_cards", "pull_requests", "workflow_health", "pr_lifecycle"])
def test_requires_authentication(self, action: str) -> None:
self.client.logout()
response = self.client.get(self._url(action))
diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.ts
index 20595785f39a..2bf464695d3b 100644
--- a/products/engineering_analytics/frontend/generated/api.schemas.ts
+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts
@@ -206,6 +206,15 @@ export interface PullRequestListApi {
limit: number
}
+export interface GitHubSourceApi {
+ /** Source id — pass as `source_id` to the other endpoints to read this source. */
+ id: string
+ /** Connected repository as 'owner/name', or '' if unknown. */
+ repo: string
+ /** User-chosen warehouse table-name prefix for this source, or '' when none. */
+ prefix: string
+}
+
export interface WorkflowHealthDayApi {
/** UTC calendar day. */
day: string
diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.ts
index 262ff2549550..991483a5e2bd 100644
--- a/products/engineering_analytics/frontend/generated/api.ts
+++ b/products/engineering_analytics/frontend/generated/api.ts
@@ -14,6 +14,7 @@ import type {
EngineeringAnalyticsPrLifecycleParams,
EngineeringAnalyticsPullRequestsParams,
EngineeringAnalyticsWorkflowHealthParams,
+ GitHubSourceApi,
PRLifecycleApi,
PullRequestListApi,
WorkflowHealthItemApi,
@@ -115,6 +116,23 @@ export const engineeringAnalyticsPullRequests = async (
})
}
+export const getEngineeringAnalyticsSourcesUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/engineering_analytics/sources/`
+}
+
+/**
+ * The team's connected GitHub data warehouse sources, oldest first. Populate a source picker from this and pass a chosen `id` back as `source_id` to the other endpoints. A team can connect GitHub more than once (e.g. one source per repository); this lists them all, including any whose tables aren't fully synced yet.
+ */
+export const engineeringAnalyticsSources = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<GitHubSourceApi[]> => {
+ return apiMutator<GitHubSourceApi[]>(getEngineeringAnalyticsSourcesUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getEngineeringAnalyticsWorkflowHealthUrl = (
projectId: string,
params?: EngineeringAnalyticsWorkflowHealthParams
diff --git a/products/engineering_analytics/frontend/generated/api.zod.schemas.ts b/products/engineering_analytics/frontend/generated/api.zod.schemas.ts
index 54b48956f788..14e87a2df452 100644
--- a/products/engineering_analytics/frontend/generated/api.zod.schemas.ts
+++ b/products/engineering_analytics/frontend/generated/api.zod.schemas.ts
@@ -318,6 +318,15 @@ export const PullRequestListApi = zod.object({
export type PullRequestListApi = zod.input<typeof PullRequestListApi>
export type PullRequestListApiOutput = zod.output<typeof PullRequestListApi>
+export const GitHubSourceApi = zod.object({
+ id: zod.string().describe('Source id — pass as `source_id` to the other endpoints to read this source.'),
+ repo: zod.string().describe("Connected repository as 'owner\/name', or '' if unknown."),
+ prefix: zod.string().describe("User-chosen warehouse table-name prefix for this source, or '' when none."),
+})
+
+export type GitHubSourceApi = zod.input<typeof GitHubSourceApi>
+export type GitHubSourceApiOutput = zod.output<typeof GitHubSourceApi>
+
export const WorkflowHealthDayApi = zod.object({
day: zod.iso.date().describe('UTC calendar day.'),
run_count: zod.number().describe('Runs started that day.'),
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsPullRequests.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsPullRequests.tsx
index 7c8abc661b44..5fd126b1a16f 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsPullRequests.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsPullRequests.tsx
@@ -1,5 +1,5 @@
import { useActions, useValues } from 'kea'
-import { router } from 'kea-router'
+import { combineUrl, router } from 'kea-router'
import {
LemonButton,
@@ -49,6 +49,7 @@ export function EngineeringAnalyticsPullRequests(): JSX.Element {
repoOptions,
hasActiveFilters,
activeCard,
+ sourceId,
} = useValues(engineeringAnalyticsLogic)
const { setStateFilter, setAuthor, setRepo, setCiStatusFilter, setSearch, resetFilters, applyCardFilter } =
useActions(engineeringAnalyticsLogic)
@@ -226,7 +227,11 @@ export function EngineeringAnalyticsPullRequests(): JSX.Element {
rowKey={prKeyOf}
loading={pullRequestsLoading}
onRow={(row) => {
- const detailUrl = urls.engineeringAnalyticsPullRequest(row.repoOwner, row.repoName, row.number)
+ // Carry the selected source so the PR's detail page reads the same one.
+ const detailUrl = combineUrl(
+ urls.engineeringAnalyticsPullRequest(row.repoOwner, row.repoName, row.number),
+ sourceId ? { source: sourceId } : {}
+ ).url
return {
// Inner links (PR title → GitHub) keep their own behavior.
onClick: (e: React.MouseEvent) => {
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsScene.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsScene.tsx
index 5159c8887d3a..459919a492c2 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsScene.tsx
@@ -1,7 +1,7 @@
import { BindLogic, useActions, useValues } from 'kea'
import { combineUrl, router } from 'kea-router'
-import { LemonBanner, LemonButton, LemonTab, LemonTabs } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonSelect, LemonTab, LemonTabs } from '@posthog/lemon-ui'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
import { SceneExport } from 'scenes/sceneTypes'
@@ -30,8 +30,8 @@ export function EngineeringAnalyticsScene({ tabId }: { tabId?: string }): JSX.El
const logic = engineeringAnalyticsLogic({ tabId })
// Keep this tab's filters and data alive across tab switches (React unmounts inactive tabs).
useAttachedLogic(logic, tabId ? engineeringAnalyticsSceneLogic({ tabId }) : undefined)
- const { anyLoading } = useValues(logic)
- const { refresh } = useActions(logic)
+ const { anyLoading, hasMultipleSources, sourceOptions, sourceId } = useValues(logic)
+ const { refresh, setSourceId } = useActions(logic)
const tabs: LemonTab<EngineeringAnalyticsTab>[] = [
{
@@ -58,15 +58,29 @@ export function EngineeringAnalyticsScene({ tabId }: { tabId?: string }): JSX.El
description={TAB_DESCRIPTIONS[activeTab]}
resourceType={{ type: 'health' }}
actions={
- <LemonButton
- type="secondary"
- size="small"
- onClick={refresh}
- loading={anyLoading}
- disabledReason={anyLoading ? 'Loading…' : undefined}
- >
- Refresh
- </LemonButton>
+ <div className="flex items-center gap-2">
+ {hasMultipleSources && (
+ <LemonSelect
+ size="small"
+ value={sourceId}
+ onChange={setSourceId}
+ options={sourceOptions}
+ placeholder="Source: default"
+ allowClear
+ dropdownMatchSelectWidth={false}
+ data-attr="engineering-analytics-source-select"
+ />
+ )}
+ <LemonButton
+ type="secondary"
+ size="small"
+ onClick={refresh}
+ loading={anyLoading}
+ disabledReason={anyLoading ? 'Loading…' : undefined}
+ >
+ Refresh
+ </LemonButton>
+ </div>
}
/>
<LemonBanner type="info" dismissKey="engineering-analytics-alpha">
diff --git a/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx b/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx
index f9f6656e3283..866ef13414ba 100644
--- a/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx
@@ -30,10 +30,11 @@ import { PullRequestDetailLogicProps, pullRequestDetailLogic } from './pullReque
export const scene: SceneExport<PullRequestDetailLogicProps> = {
component: PullRequestDetailScene,
logic: pullRequestDetailLogic,
- paramsToProps: ({ params: { repoOwner, repoName, number } }) => ({
+ paramsToProps: ({ params: { repoOwner, repoName, number }, searchParams: { source } }) => ({
repoOwner: decodeURIComponent(repoOwner),
repoName: decodeURIComponent(repoName),
number: parseInt(number, 10),
+ sourceId: source ?? null,
}),
}
diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
index 707e456fccf2..b7040007764b 100644
--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
@@ -8,9 +8,15 @@ import { initKeaTests } from '~/test/init'
import {
engineeringAnalyticsCiCards,
engineeringAnalyticsPullRequests,
+ engineeringAnalyticsSources,
engineeringAnalyticsWorkflowHealth,
} from '../generated/api'
-import type { CICardSummaryApi, PullRequestListItemApi, WorkflowHealthItemApi } from '../generated/api.schemas'
+import type {
+ CICardSummaryApi,
+ GitHubSourceApi,
+ PullRequestListItemApi,
+ WorkflowHealthItemApi,
+} from '../generated/api.schemas'
import { ciStatusOf } from '../lib/ci'
import { summarizeLifecycle, workflowRuns } from '../lib/lifecycle'
import {
@@ -26,6 +32,7 @@ jest.mock('../generated/api', () => ({
engineeringAnalyticsCiCards: jest.fn(),
engineeringAnalyticsPrLifecycle: jest.fn(),
engineeringAnalyticsPullRequests: jest.fn(),
+ engineeringAnalyticsSources: jest.fn(),
engineeringAnalyticsWorkflowHealth: jest.fn(),
}))
@@ -36,6 +43,7 @@ const mockPullRequests = engineeringAnalyticsPullRequests as jest.MockedFunction
const mockWorkflowHealth = engineeringAnalyticsWorkflowHealth as jest.MockedFunction<
typeof engineeringAnalyticsWorkflowHealth
>
+const mockSources = engineeringAnalyticsSources as jest.MockedFunction<typeof engineeringAnalyticsSources>
function makePr(overrides: Partial<PullRequestRow> = {}): PullRequestRow {
return {
@@ -104,6 +112,10 @@ const WORKFLOWS: WorkflowHealthItemApi[] = [
last_failure_at: '2026-05-30T00:00:00Z',
},
]
+const SOURCES: GitHubSourceApi[] = [
+ { id: 'src-older', repo: 'posthog/posthog', prefix: 'older' },
+ { id: 'src-newer', repo: 'posthog/posthog.com', prefix: 'website' },
+]
describe('engineeringAnalyticsLogic', () => {
let logic: ReturnType<typeof engineeringAnalyticsLogic.build>
@@ -116,6 +128,8 @@ describe('engineeringAnalyticsLogic', () => {
mockCiCards.mockResolvedValue(CARDS)
mockPullRequests.mockResolvedValue({ items: PRS, truncated: false, limit: PRS.length })
mockWorkflowHealth.mockResolvedValue(WORKFLOWS)
+ // Most tests are single- or no-source; the picker tests override with SOURCES.
+ mockSources.mockResolvedValue([])
})
afterEach(() => {
@@ -245,6 +259,54 @@ describe('engineeringAnalyticsLogic', () => {
expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '2026-01-01', date_to: '2026-03-01' })
})
+ it('exposes source options and the multi-source flag only when more than one source exists', async () => {
+ mockSources.mockResolvedValue(SOURCES)
+ logic = engineeringAnalyticsLogic()
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadGithubSourcesSuccess'])
+
+ expect(logic.values.hasMultipleSources).toBe(true)
+ expect(logic.values.sourceOptions).toEqual([
+ { value: 'src-older', label: 'posthog/posthog' },
+ { value: 'src-newer', label: 'posthog/posthog.com' },
+ ])
+ })
+
+ it('hides the picker when the team has a single source', async () => {
+ mockSources.mockResolvedValue([SOURCES[0]])
+ logic = engineeringAnalyticsLogic()
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadGithubSourcesSuccess'])
+
+ expect(logic.values.hasMultipleSources).toBe(false)
+ })
+
+ it('defaults to no source, then scopes every endpoint to the picked one and reloads', async () => {
+ logic = engineeringAnalyticsLogic()
+ logic.mount()
+ await expectLogic(logic).toDispatchActions([
+ 'loadCardsSuccess',
+ 'loadPullRequestsSuccess',
+ 'loadWorkflowHealthSuccess',
+ ])
+ // No source picked → omit source_id so the backend resolves its default.
+ expect(mockCiCards).toHaveBeenLastCalledWith('1', { source_id: undefined })
+
+ logic.actions.setSourceId('src-newer')
+ await expectLogic(logic).toDispatchActions([
+ 'setSourceId',
+ 'loadCards',
+ 'loadPullRequests',
+ 'loadWorkflowHealth',
+ 'loadCardsSuccess',
+ ])
+
+ expect(logic.values.sourceId).toBe('src-newer')
+ expect(mockCiCards).toHaveBeenLastCalledWith('1', { source_id: 'src-newer' })
+ expect(mockPullRequests).toHaveBeenLastCalledWith('1', { source_id: 'src-newer' })
+ expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-30d', source_id: 'src-newer' })
+ })
+
it('resetFilters returns every filter to defaults and clears hasActiveFilters', async () => {
logic = engineeringAnalyticsLogic()
logic.mount()
diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
index 7b3ddd995d04..ad87c9dce7c5 100644
--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
@@ -1,15 +1,19 @@
import { LogicWrapper, actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
+import { actionToUrl, router, urlToAction } from 'kea-router'
import { ApiConfig } from 'lib/api'
import { dayjs } from 'lib/dayjs'
import { objectsEqual } from 'lib/utils/objects'
+import { urls } from 'scenes/urls'
import {
engineeringAnalyticsCiCards,
engineeringAnalyticsPullRequests,
+ engineeringAnalyticsSources,
engineeringAnalyticsWorkflowHealth,
} from '../generated/api'
+import type { GitHubSourceApi } from '../generated/api.schemas'
import { CIStatus, ciStatusOf } from '../lib/ci'
import type { engineeringAnalyticsLogicType } from './engineeringAnalyticsLogicType'
@@ -190,6 +194,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
setStuckOnly: (stuckOnly: boolean) => ({ stuckOnly }),
setWorkflowDateRange: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
applyCardFilter: (card: CardFilter) => ({ card }),
+ setSourceId: (sourceId: string | null) => ({ sourceId }),
resetFilters: true,
refresh: true,
}),
@@ -199,7 +204,9 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
null as CardsData | null,
{
loadCards: async (): Promise<CardsData> => {
- const data = await engineeringAnalyticsCiCards(projectId())
+ const data = await engineeringAnalyticsCiCards(projectId(), {
+ source_id: values.sourceId ?? undefined,
+ })
return {
openPrs: data.open_prs,
repos: data.repos,
@@ -213,7 +220,9 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
[] as PullRequestRow[],
{
loadPullRequests: async (): Promise<PullRequestRow[]> => {
- const response = await engineeringAnalyticsPullRequests(projectId())
+ const response = await engineeringAnalyticsPullRequests(projectId(), {
+ source_id: values.sourceId ?? undefined,
+ })
return response.items.map(
(it): PullRequestRow => ({
number: it.number,
@@ -245,6 +254,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
const items = await engineeringAnalyticsWorkflowHealth(projectId(), {
date_from: values.workflowDateFrom ?? undefined,
date_to: values.workflowDateTo ?? undefined,
+ source_id: values.sourceId ?? undefined,
})
return items.map(
(it): WorkflowHealthRow => ({
@@ -267,6 +277,13 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
},
},
],
+ githubSources: [
+ [] as GitHubSourceApi[],
+ {
+ loadGithubSources: async (): Promise<GitHubSourceApi[]> =>
+ await engineeringAnalyticsSources(projectId()),
+ },
+ ],
})),
reducers({
@@ -301,6 +318,9 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
resetFilters: () => DEFAULT_FILTERS.stuckOnly,
},
],
+ // Which connected GitHub source to read; null = the backend default (oldest connected).
+ // URL-synced via `source` so it survives tab switches and deep-links into a PR's detail.
+ sourceId: [null as string | null, { setSourceId: (_, { sourceId }) => sourceId }],
// The endpoints 400 when the team has no GitHub warehouse source connected.
// A failed cards load is the canary for "no source connected".
loadFailed: [
@@ -364,6 +384,16 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
cardsLoading || pullRequestsLoading || workflowHealthLoading,
],
tableTruncated: [(s) => [s.pullRequests], (pullRequests): boolean => pullRequests.length >= PR_TABLE_LIMIT],
+ // Only worth a picker when the team has more than one GitHub source connected.
+ hasMultipleSources: [(s) => [s.githubSources], (githubSources): boolean => githubSources.length > 1],
+ sourceOptions: [
+ (s) => [s.githubSources],
+ (githubSources): { value: string; label: string }[] =>
+ githubSources.map((source) => ({
+ value: source.id,
+ label: source.repo || source.prefix || `source ${source.id.slice(0, 8)}`,
+ })),
+ ],
}),
listeners(({ actions, values }) => ({
@@ -372,6 +402,8 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
actions.loadPullRequests()
actions.loadWorkflowHealth()
},
+ // Cards, the PR list, and workflow health are all per-source — reload them all.
+ setSourceId: () => actions.refresh(),
setWorkflowDateRange: () => {
actions.loadWorkflowHealth()
},
@@ -384,9 +416,34 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
},
})),
+ actionToUrl(() => ({
+ setSourceId: ({ sourceId }) => {
+ const searchParams = { ...router.values.searchParams }
+ if (sourceId) {
+ searchParams.source = sourceId
+ } else {
+ delete searchParams.source
+ }
+ return [router.values.location.pathname, searchParams, router.values.hashParams, { replace: true }]
+ },
+ })),
+
+ urlToAction(({ actions, values }) => {
+ // The chosen source rides in `?source=` so it survives tab switches and deep-links into a PR's detail.
+ const applySource = (source: string | undefined): void => {
+ const next = source ?? null
+ if (next !== values.sourceId) {
+ actions.setSourceId(next)
+ }
+ }
+ return {
+ [urls.engineeringAnalytics()]: (_, searchParams) => applySource(searchParams.source),
+ [urls.engineeringAnalyticsWorkflows()]: (_, searchParams) => applySource(searchParams.source),
+ }
+ }),
+
afterMount(({ actions }) => {
- actions.loadCards()
- actions.loadPullRequests()
- actions.loadWorkflowHealth()
+ actions.loadGithubSources()
+ actions.refresh()
}),
])
diff --git a/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.ts b/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.ts
index 565a3dd33103..f05957a87804 100644
--- a/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.ts
@@ -17,6 +17,8 @@ export interface PullRequestDetailLogicProps {
repoOwner: string
repoName: string
number: number
+ // Which GitHub source the list was scoped to, threaded from `?source=` via paramsToProps.
+ sourceId: string | null
tabId?: string
}
@@ -30,7 +32,11 @@ export function sortRunsForTriage(runs: WorkflowRun[]): WorkflowRun[] {
export const pullRequestDetailLogic = kea<pullRequestDetailLogicType>([
path(['products', 'engineering_analytics', 'frontend', 'scenes', 'pullRequestDetailLogic']),
props({} as PullRequestDetailLogicProps),
- key((props) => `${props.tabId ?? 'default'}/${props.repoOwner}/${props.repoName}#${props.number}`),
+ // sourceId is part of the identity: the same PR number can resolve to a different source.
+ key(
+ (props) =>
+ `${props.tabId ?? 'default'}/${props.repoOwner}/${props.repoName}#${props.number}@${props.sourceId ?? ''}`
+ ),
loaders(({ props }) => ({
lifecycle: [
@@ -40,6 +46,7 @@ export const pullRequestDetailLogic = kea<pullRequestDetailLogicType>([
await engineeringAnalyticsPrLifecycle(projectId(), {
pr_number: props.number,
repo: `${props.repoOwner}/${props.repoName}`,
+ source_id: props.sourceId ?? undefined,
}),
},
],
diff --git a/products/engineering_analytics/mcp/tools.yaml b/products/engineering_analytics/mcp/tools.yaml
index fa36210c1889..f227c8885ec1 100644
--- a/products/engineering_analytics/mcp/tools.yaml
+++ b/products/engineering_analytics/mcp/tools.yaml
@@ -12,6 +12,22 @@ tools:
engineering-analytics-ci-cards:
operation: engineering_analytics_ci_cards
enabled: false
+ engineering-analytics-sources:
+ operation: engineering_analytics_sources
+ enabled: true
+ scopes:
+ - engineering_analytics:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ list: true
+ title: List connected GitHub 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.
pr-lifecycle:
operation: engineering_analytics_pr_lifecycle
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 8cbbf948f81d..b93206f6308e 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -2274,6 +2274,20 @@
"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",
+ "feature": "engineering_analytics",
+ "summary": "List connected GitHub sources",
+ "title": "List connected GitHub sources",
+ "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 653c2926ad2c..220a01b71fdc 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -2304,6 +2304,20 @@
"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",
+ "feature": "engineering_analytics",
+ "summary": "List connected GitHub sources",
+ "title": "List connected GitHub sources",
+ "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 666ad9fa8270..e6050a162b71 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -22499,6 +22499,15 @@ export namespace Schemas {
has_more: boolean;
}
+ export interface GitHubSource {
+ /** Source id — pass as `source_id` to the other endpoints to read this source. */
+ id: string;
+ /** Connected repository as 'owner/name', or '' if unknown. */
+ repo: string;
+ /** User-chosen warehouse table-name prefix for this source, or '' when none. */
+ prefix: string;
+ }
+
export interface GitHubTeam {
/** GitHub team numeric identifier. */
id: number;
diff --git a/services/mcp/src/generated/engineering_analytics/api.ts b/services/mcp/src/generated/engineering_analytics/api.ts
index 405e097d9c99..4013a8faab4d 100644
--- a/services/mcp/src/generated/engineering_analytics/api.ts
+++ b/services/mcp/src/generated/engineering_analytics/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 3 enabled ops
+ * PostHog API - MCP 4 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -56,6 +56,17 @@ export const EngineeringAnalyticsPullRequestsQueryParams = /* @__PURE__ */ zod.o
),
})
+/**
+ * The team's connected GitHub data warehouse sources, oldest first. Populate a source picker from this and pass a chosen `id` back as `source_id` to the other endpoints. A team can connect GitHub more than once (e.g. one source per repository); this lists them all, including any whose tables aren't fully synced yet.
+ */
+export const EngineeringAnalyticsSourcesParams = /* @__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/."
+ ),
+})
+
/**
* Per-workflow CI health over a window (default last 30 days, maximum 366 days): run count, success rate, p50/p95 duration over completed runs, last failure time, and a zero-filled daily run history. Use this for 'is CI getting slower' and 'which workflow is the long pole'; compare two windows to get a trend.
*/
diff --git a/services/mcp/src/tools/generated/engineering_analytics.ts b/services/mcp/src/tools/generated/engineering_analytics.ts
index 79c0adb8cdee..c41eb19baccd 100644
--- a/services/mcp/src/tools/generated/engineering_analytics.ts
+++ b/services/mcp/src/tools/generated/engineering_analytics.ts
@@ -10,6 +10,25 @@ import {
import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
+const EngineeringAnalyticsSourcesSchema = z.object({})
+
+const engineeringAnalyticsSources = (): ToolBase<
+ typeof EngineeringAnalyticsSourcesSchema,
+ WithPostHogUrl<Schemas.GitHubSource[]>
+> => ({
+ name: 'engineering-analytics-sources',
+ schema: EngineeringAnalyticsSourcesSchema,
+ // eslint-disable-next-line no-unused-vars
+ handler: async (context: Context, params: z.infer<typeof EngineeringAnalyticsSourcesSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.GitHubSource[]>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/engineering_analytics/sources/`,
+ })
+ return await withPostHogUrl(context, result, '/engineering-analytics')
+ },
+})
+
const PrLifecycleSchema = EngineeringAnalyticsPrLifecycleQueryParams.extend({
pr_number: EngineeringAnalyticsPrLifecycleQueryParams.shape['pr_number'].describe(
'Pull request number to inspect.'
@@ -88,6 +107,7 @@ const workflowHealth = (): ToolBase<typeof WorkflowHealthSchema, WithPostHogUrl<
})
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
+ 'engineering-analytics-sources': engineeringAnalyticsSources,
'pr-lifecycle': prLifecycle,
'pull-requests': pullRequests,
'workflow-health': workflowHealth,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/engineering-analytics-sources.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/engineering-analytics-sources.json
new file mode 100644
index 000000000000..7b7ea9186078
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/engineering-analytics-sources.json
@@ -0,0 +1,5 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {},
+ "type": "object"
+}