:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(integrations): add github teams listing endpoint (#56169)
Hugues Pouillot17f801a5b920
diff --git a/posthog/api/integration.py b/posthog/api/integration.pyindex 632d4716dbc4..66b30443da1e 100644--- a/posthog/api/integration.py+++ b/posthog/api/integration.py@@ -50,6 +50,7 @@ from posthog.models.integration import (FirebaseIntegration,GitHubInstallationAccess,GitHubIntegration,+ GitHubIntegrationError,GitLabIntegration,GoogleAdsIntegration,GoogleCloudIntegration,@@ -207,6 +208,41 @@ class GitHubReposRefreshResponseSerializer(serializers.Serializer):repositories = GitHubRepoSerializer(many=True, help_text="The refreshed repository cache.")+class GitHubTeamSerializer(serializers.Serializer):+ id = serializers.IntegerField(help_text="GitHub team numeric identifier.")+ slug = serializers.CharField(help_text="GitHub team slug.")+ name = serializers.CharField(help_text="GitHub team display name.")+++class GitHubTeamsQuerySerializer(serializers.Serializer):+ search = serializers.CharField(+ required=False,+ allow_blank=True,+ default="",+ help_text="Optional case-insensitive team name or slug search query.",+ )+ limit = serializers.IntegerField(+ required=False,+ default=100,+ min_value=1,+ max_value=500,+ help_text="Maximum number of teams to return per request (max 500).",+ )+ offset = serializers.IntegerField(+ required=False,+ default=0,+ min_value=0,+ help_text="Number of teams to skip before returning results.",+ )+++class GitHubTeamsResponseSerializer(serializers.Serializer):+ teams = GitHubTeamSerializer(+ many=True, help_text="List of GitHub teams available to the installation organization."+ )+ has_more = serializers.BooleanField(help_text="Whether more teams are available beyond this page.")++class GitHubBranchesQuerySerializer(serializers.Serializer):repo = serializers.CharField(help_text="Repository in owner/repo format")search = serializers.CharField(@@ -611,6 +647,7 @@ class IntegrationViewSet("channels","github_repos","github_branches",+ "github_teams","anthropic_managed_agents","anthropic_managed_agent_environments","anthropic_managed_agent_vaults",@@ -1217,6 +1254,29 @@ class IntegrationViewSet(return Response({"repositories": repositories})+ @extend_schema(+ parameters=[GitHubTeamsQuerySerializer],+ responses={200: GitHubTeamsResponseSerializer},+ )+ @action(methods=["GET"], detail=True, url_path="github_teams")+ def github_teams(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ query_serializer = GitHubTeamsQuerySerializer(data=request.query_params)+ query_serializer.is_valid(raise_exception=True)+ search = query_serializer.validated_data["search"]+ limit = query_serializer.validated_data["limit"]+ offset = query_serializer.validated_data["offset"]++ github = GitHubIntegration(self.get_object())+ try:+ teams, has_more = github.list_teams(search=search, limit=limit, offset=offset)+ except GitHubIntegrationError as err:+ capture_exception(err)+ raise ValidationError(+ "Unable to fetch GitHub teams. Please check integration settings and try again."+ ) from err++ return Response({"teams": teams, "has_more": has_more})+@extend_schema(parameters=[GitHubBranchesQuerySerializer],responses={200: GitHubBranchesResponseSerializer},diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex 55a9d0babedf..dcf8f6c4760e 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -25,6 +25,7 @@ from posthog.models.integration import (SLACK_INTEGRATION_KINDS,EmailIntegration,GitHubIntegration,+ GitHubIntegrationError,Integration,SlackIntegration,StripeIntegration,@@ -799,6 +800,78 @@ class TestIntegrationAPIKeyAccess:assert data["has_more"] is Falsemock_list_repos.assert_called_once_with(search="posthog", limit=1, offset=1)+ @pytest.mark.parametrize(+ "query_string,mock_return,expected_call",+ [+ (+ "",+ (+ [+ {"id": 1, "slug": "frontend-team", "name": "Frontend Team"},+ {"id": 2, "slug": "platform", "name": "Platform"},+ ],+ False,+ ),+ {"search": "", "limit": 100, "offset": 0},+ ),+ (+ "?search=front&limit=10&offset=20",+ (+ [+ {"id": 1, "slug": "frontend-team", "name": "Frontend Team"},+ ],+ True,+ ),+ {"search": "front", "limit": 10, "offset": 20},+ ),+ ],+ )+ @patch("posthog.models.integration.GitHubIntegration.list_teams")+ def test_github_teams(self, mock_list_teams, query_string, mock_return, expected_call, client: HttpClient):+ mock_list_teams.return_value = mock_return++ key_value = "test_key_123"+ PersonalAPIKey.objects.create(+ label="Test Key",+ user=self.user,+ secure_value=hash_key_value(key_value),+ scopes=["integration:read"],+ )++ response = client.get(+ f"/api/environments/{self.team.pk}/integrations/{self.github_integration.id}/github_teams/{query_string}",+ HTTP_AUTHORIZATION=f"Bearer {key_value}",+ )++ assert response.status_code == status.HTTP_200_OK+ data = response.json()+ assert data["teams"] == mock_return[0]+ assert data["has_more"] is mock_return[1]+ mock_list_teams.assert_called_once_with(**expected_call)++ @patch("posthog.models.integration.GitHubIntegration.list_teams")+ def test_github_teams_errors_return_400(self, mock_list_teams, client: HttpClient):+ mock_list_teams.side_effect = GitHubIntegrationError("GitHubIntegration: list_teams failed")++ key_value = "test_key_123"+ PersonalAPIKey.objects.create(+ label="Test Key",+ user=self.user,+ secure_value=hash_key_value(key_value),+ scopes=["integration:read"],+ )++ response = client.get(+ f"/api/environments/{self.team.pk}/integrations/{self.github_integration.id}/github_teams/",+ HTTP_AUTHORIZATION=f"Bearer {key_value}",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert (+ response.json()["detail"]+ == "Unable to fetch GitHub teams. Please check integration settings and try again."+ )+@patch("posthog.models.integration.GitHubIntegration.sync_repository_cache")def test_refresh_github_repos_with_write_scope_succeeds(self, mock_sync_repository_cache, client: HttpClient):mock_sync_repository_cache.return_value = [diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.pyindex b1ea83fe0669..637d29221b94 100644--- a/posthog/models/github_integration_base.py+++ b/posthog/models/github_integration_base.py@@ -402,6 +402,78 @@ class GitHubIntegrationBase:raise ValueError(f"GitHub integration account name is not a string: {name}")return name+ def list_teams(self, *, search: str = "", limit: int = 100, offset: int = 0) -> tuple[list[dict[str, Any]], bool]:+ """List GitHub teams for the integration account organization with bounded API calls."""+ account = self.integration.config.get("account", {})+ organization = account.get("name", "") if isinstance(account, dict) else ""+ if not organization:+ return [], False++ per_page = 100+ search_lower = search.lower().strip()++ if search_lower:+ # GitHub's org teams endpoint does not support server-side search.+ # Keep calls bounded and shift the fetch window by offset.+ max_pages = 10+ first_page = offset // per_page + 1+ last_page = first_page + max_pages - 1+ start = 0+ end = limit + 1+ else:+ requested = limit + 1+ first_page = offset // per_page + 1+ last_page = (offset + requested) // per_page + 1+ start = offset % per_page+ end = start + requested++ teams: list[dict[str, Any]] = []++ for page in range(first_page, last_page + 1):+ response = self._installation_authenticated_get(+ f"https://api.github.com/orgs/{organization}/teams?page={page}&per_page={per_page}",+ endpoint="/orgs/{org}/teams",+ )+ if response is None or response.status_code != 200:+ logger.warning(+ "GitHubIntegration: list_teams failed",+ integration_id=self.integration.id,+ organization=organization,+ status_code=response.status_code if response is not None else None,+ )+ raise GitHubIntegrationError("GitHubIntegration: list_teams failed")++ body = response.json()+ if not isinstance(body, list):+ logger.warning(+ "GitHubIntegration: list_teams invalid payload",+ integration_id=self.integration.id,+ organization=organization,+ )+ raise GitHubIntegrationError("GitHubIntegration: list_teams invalid payload")++ for team in body:+ if not isinstance(team, dict):+ continue+ team_id = team.get("id")+ slug = team.get("slug")+ name = team.get("name")+ if not isinstance(team_id, int) or not isinstance(slug, str) or not isinstance(name, str):+ continue+ teams.append({"id": team_id, "slug": slug, "name": name})++ if len(body) < per_page:+ break++ if search_lower:+ teams = [+ team for team in teams if search_lower in team["slug"].lower() or search_lower in team["name"].lower()+ ]++ window = teams[start:end]+ has_more = len(window) > limit+ return window[:limit], has_more+# --- Repository operations ---def get_commit_author_info(self, repository: str, sha: str) -> GitHubCommitAuthor | None:diff --git a/products/integrations/frontend/generated/api.schemas.ts b/products/integrations/frontend/generated/api.schemas.tsindex 924c37e6249f..f0c4eecf8e61 100644--- a/products/integrations/frontend/generated/api.schemas.ts+++ b/products/integrations/frontend/generated/api.schemas.ts@@ -314,6 +314,22 @@ export interface GitHubReposRefreshResponseApi {repositories: GitHubRepoApi[]}+export interface GitHubTeamApi {+ /** GitHub team numeric identifier. */+ id: number+ /** GitHub team slug. */+ slug: string+ /** GitHub team display name. */+ name: string+}++export interface GitHubTeamsResponseApi {+ /** List of GitHub teams available to the installation organization. */+ teams: GitHubTeamApi[]+ /** Whether more teams are available beyond this page. */+ has_more: boolean+}+export interface UserGitHubAccountApi {/*** GitHub account type for the installation (e.g. User or Organization).@@ -542,6 +558,24 @@ export type IntegrationsGithubReposRetrieveParams = {search?: string}+export type IntegrationsGithubTeamsRetrieveParams = {+ /**+ * Maximum number of teams to return per request (max 500).+ * @minimum 1+ * @maximum 500+ */+ limit?: number+ /**+ * Number of teams to skip before returning results.+ * @minimum 0+ */+ offset?: number+ /**+ * Optional case-insensitive team name or slug search query.+ */+ search?: string+}+export type UsersIntegrationsListParams = {/*** Number of results to return per page.diff --git a/products/integrations/frontend/generated/api.ts b/products/integrations/frontend/generated/api.tsindex 5e8d11d75511..735295adf94c 100644--- a/products/integrations/frontend/generated/api.ts+++ b/products/integrations/frontend/generated/api.ts@@ -12,9 +12,11 @@ import type {GitHubBranchesResponseApi,GitHubReposRefreshResponseApi,GitHubReposResponseApi,+ GitHubTeamsResponseApi,IntegrationConfigApi,IntegrationsGithubBranchesRetrieveParams,IntegrationsGithubReposRetrieveParams,+ IntegrationsGithubTeamsRetrieveParams,IntegrationsListParams,OrganizationIntegrationApi,PaginatedIntegrationConfigListApi,@@ -461,6 +463,38 @@ export const integrationsGithubReposRefreshCreate = async (})}+export const getIntegrationsGithubTeamsRetrieveUrl = (+ projectId: string,+ id: number,+ params?: IntegrationsGithubTeamsRetrieveParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : value.toString())+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/integrations/${id}/github_teams/?${stringifiedParams}`+ : `/api/projects/${projectId}/integrations/${id}/github_teams/`+}++export const integrationsGithubTeamsRetrieve = async (+ projectId: string,+ id: number,+ params?: IntegrationsGithubTeamsRetrieveParams,+ options?: RequestInit+): Promise<GitHubTeamsResponseApi> => {+ return apiMutator<GitHubTeamsResponseApi>(getIntegrationsGithubTeamsRetrieveUrl(projectId, id, params), {+ ...options,+ method: 'GET',+ })+}+export const getIntegrationsGoogleAccessibleAccountsRetrieveUrl = (projectId: string, id: number) => {return `/api/projects/${projectId}/integrations/${id}/google_accessible_accounts/`}diff --git a/products/integrations/mcp/tools.yaml b/products/integrations/mcp/tools.yamlindex 2f681c7f7228..a61c0001a1b8 100644--- a/products/integrations/mcp/tools.yaml+++ b/products/integrations/mcp/tools.yaml@@ -115,6 +115,9 @@ tools:integrations-github-repos-retrieve:operation: integrations_github_repos_retrieveenabled: false+ integrations-github-teams-retrieve:+ operation: integrations_github_teams_retrieve+ enabled: falseintegrations-google-accessible-accounts-retrieve:operation: integrations_google_accessible_accounts_retrieveenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 7323192e3d29..dfc2525e5e17 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -16978,6 +16978,22 @@ export namespace Schemas {has_more: boolean;}+ export interface GitHubTeam {+ /** GitHub team numeric identifier. */+ id: number;+ /** GitHub team slug. */+ slug: string;+ /** GitHub team display name. */+ name: string;+ }++ export interface GitHubTeamsResponse {+ /** List of GitHub teams available to the installation organization. */+ teams: GitHubTeam[];+ /** Whether more teams are available beyond this page. */+ has_more: boolean;+ }+export interface GitProviderFileLinkResolveResponse {/** Whether a matching file URL was found. */found: boolean;@@ -38582,6 +38598,24 @@ export namespace Schemas {search?: string;};+ export type EnvironmentsIntegrationsGithubTeamsRetrieveParams = {+ /**+ * Maximum number of teams to return per request (max 500).+ * @minimum 1+ * @maximum 500+ */+ limit?: number;+ /**+ * Number of teams to skip before returning results.+ * @minimum 0+ */+ offset?: number;+ /**+ * Optional case-insensitive team name or slug search query.+ */+ search?: string;+ };+export type EnvironmentsLogsAlertsListParams = {/*** Number of results to return per page.@@ -43704,6 +43738,24 @@ export namespace Schemas {search?: string;};+ export type IntegrationsGithubTeamsRetrieveParams = {+ /**+ * Maximum number of teams to return per request (max 500).+ * @minimum 1+ * @maximum 500+ */+ limit?: number;+ /**+ * Number of teams to skip before returning results.+ * @minimum 0+ */+ offset?: number;+ /**+ * Optional case-insensitive team name or slug search query.+ */+ search?: string;+ };+export type JsSnippetResolveRetrieve200 = { [key: string]: unknown };export type JsSnippetVersionRetrieve200 = { [key: string]: unknown };