:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(mcp): page large github repository lists with compact rows (#108947)
posthog[bot]091d2df37186
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex 3dbff2496194..96a78cf591c2 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -5286,6 +5286,11 @@ export interface GitHubReposResponseApi {repositories: GitHubRepoApi[]/** Whether more repositories are available beyond this page. */has_more: boolean+ /**+ * The offset to pass to get the next page, or null when this page is the last one.+ * @nullable+ */+ next_offset: number | null/** Total number of repositories matching the search query, across all pages. */total: number}@@ -6035,6 +6040,10 @@ export type UsersIntegrationsGithubBranchesRetrieveParams = {}export type UsersIntegrationsGithubReposRetrieveParams = {+ /**+ * When true, return only id, name, and full_name for each repository. Use it to list large rosters in fewer, smaller pages.+ */+ compact?: boolean/*** Maximum number of repositories to return per request (max 500).* @minimum 1diff --git a/posthog/api/integration.py b/posthog/api/integration.pyindex 128662963890..baa702417cad 100644--- a/posthog/api/integration.py+++ b/posthog/api/integration.py@@ -55,6 +55,7 @@ from posthog.event_usage import report_user_actionfrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.fuzzy_search import fuzzy_filterfrom posthog.models import OrganizationMembership, User+from posthog.models.github_integration_base import GitHubIntegrationBasefrom posthog.models.integration import (ANTHROPIC_DEFAULT_INTEGRATION_ID_PREFIX,ANTHROPIC_MANAGED_AGENT_LIST_PAGE_LIMIT,@@ -334,16 +335,45 @@ class GitHubReposQuerySerializer(serializers.Serializer):min_value=0,help_text="Number of repositories to skip before returning results.",)+ compact = serializers.BooleanField(+ required=False,+ default=False,+ help_text=(+ "When true, return only id, name, and full_name for each repository. "+ "Use it to list large rosters in fewer, smaller pages."+ ),+ )class GitHubReposResponseSerializer(serializers.Serializer):repositories = GitHubRepoSerializer(many=True)has_more = serializers.BooleanField(help_text="Whether more repositories are available beyond this page.")+ next_offset = serializers.IntegerField(+ allow_null=True,+ help_text="The offset to pass to get the next page, or null when this page is the last one.",+ )total = serializers.IntegerField(help_text="Total number of repositories matching the search query, across all pages.")+def github_repos_page(github: GitHubIntegrationBase, query: dict[str, Any]) -> dict[str, Any]:+ """Build one `GitHubReposResponseSerializer` page from validated `GitHubReposQuerySerializer` data."""+ search, limit, offset = query["search"], query["limit"], query["offset"]+ repositories, has_more = github.list_cached_repositories(search=search, limit=limit, offset=offset)+ total = github.count_cached_repositories(search=search)+ if query["compact"]:+ repositories = [+ {"id": repo["id"], "name": repo["name"], "full_name": repo["full_name"]} for repo in repositories+ ]+ return {+ "repositories": repositories,+ "has_more": has_more,+ "next_offset": offset + len(repositories) if has_more else None,+ "total": total,+ }++GITHUB_INSTALLATION_STATUS_CHOICES = ["connected", "unavailable"]@@ -2126,18 +2156,11 @@ class IntegrationViewSet(def github_repos(self, request: Request, *args: Any, **kwargs: Any) -> Response:query_serializer = GitHubReposQuerySerializer(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"]instance = self.get_object()if instance.kind != "github":raise ValidationError("github_repos endpoint is only supported for GitHub integrations")- github = GitHubIntegration(instance)- repositories, has_more = github.list_cached_repositories(search=search, limit=limit, offset=offset)- total = github.count_cached_repositories(search=search)-- return Response({"repositories": repositories, "has_more": has_more, "total": total})+ return Response(github_repos_page(GitHubIntegration(instance), query_serializer.validated_data))@extend_schema(request=GitHubPrepareCallbackRequestSerializer, responses={204: None})@action(methods=["POST"], detail=False, url_path="github/prepare_callback")diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex 8c65377241d8..72da7a9c2daf 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -1869,6 +1869,60 @@ class TestIntegrationAPIKeyAccess:assert data["has_more"] is Falsemock_list_repos.assert_called_once_with(search="posthog", limit=1, offset=1)+ @pytest.mark.parametrize(+ "compact,expected_keys",+ [+ (True, {"id", "name", "full_name"}),+ (False, {"id", "name", "full_name", "private", "default_branch", "archived", "can_push"}),+ ],+ )+ def test_github_repos_next_offset_walks_roster_larger_than_one_page(+ self, client: HttpClient, compact: bool, expected_keys: set[str]+ ):+ self.github_integration.repository_cache = [+ {+ "id": i,+ "name": f"repo{i}",+ "full_name": f"org/repo{i}",+ "private": True,+ "default_branch": "main",+ "archived": False,+ "can_push": True,+ }+ for i in range(250)+ ]+ self.github_integration.repository_cache_updated_at = timezone.now()+ self.github_integration.save()++ key_value = "test_key_123"+ PersonalAPIKey.objects.create(+ label="Test Key",+ user=self.user,+ secure_value=hash_key_value(key_value),+ scopes=["integration:read"],+ )++ seen: list[str] = []+ offset: int | None = 0+ pages = 0+ while offset is not None:+ response = client.get(+ f"/api/environments/{self.team.pk}/integrations/{self.github_integration.id}/github_repos/"+ f"?limit=100&offset={offset}&compact={str(compact).lower()}",+ HTTP_AUTHORIZATION=f"Bearer {key_value}",+ )+ assert response.status_code == status.HTTP_200_OK+ data = response.json()+ assert data["total"] == 250+ assert data["has_more"] is (data["next_offset"] is not None)+ assert all(set(repo) == expected_keys for repo in data["repositories"])+ seen.extend(repo["full_name"] for repo in data["repositories"])+ offset = data["next_offset"]+ pages += 1++ assert pages == 3+ assert seen == [f"org/repo{i}" for i in range(250)]+@pytest.mark.parametrize("query_string,mock_return,expected_call",[diff --git a/posthog/api/user_integration.py b/posthog/api/user_integration.pyindex f92087f82af2..997ff630038a 100644--- a/posthog/api/user_integration.py+++ b/posthog/api/user_integration.py@@ -44,6 +44,7 @@ from posthog.api.integration import (GitHubReposRefreshResponseSerializer,GitHubReposResponseSerializer,github_rate_limited_response,+ github_repos_page,validate_github_repository_name,)from posthog.api.mixins import ValidatedRequest, validated_request@@ -479,9 +480,6 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):"""List repositories accessible to a specific GitHub installation (paginated, cached)."""query_serializer = GitHubReposQuerySerializer(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"]integration = UserIntegration.objects.filter(user=self._get_user(), kind="github", integration_id=installation_id@@ -489,10 +487,7 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):if integration is None:raise exceptions.NotFound("No GitHub integration found for this installation.")- github = UserGitHubIntegration(integration)- repositories, has_more = github.list_cached_repositories(search=search, limit=limit, offset=offset)- total = github.count_cached_repositories(search=search)- return Response({"repositories": repositories, "has_more": has_more, "total": total})+ return Response(github_repos_page(UserGitHubIntegration(integration), query_serializer.validated_data))@extend_schema(summary="Refresh repositories for a personal GitHub installation",diff --git a/products/integrations/frontend/generated/api.schemas.ts b/products/integrations/frontend/generated/api.schemas.tsindex 5ef8f7e13fd9..8067ed112605 100644--- a/products/integrations/frontend/generated/api.schemas.ts+++ b/products/integrations/frontend/generated/api.schemas.ts@@ -381,6 +381,11 @@ export interface GitHubReposResponseApi {repositories: GitHubRepoApi[]/** Whether more repositories are available beyond this page. */has_more: boolean+ /**+ * The offset to pass to get the next page, or null when this page is the last one.+ * @nullable+ */+ next_offset: number | null/** Total number of repositories matching the search query, across all pages. */total: number}@@ -891,6 +896,10 @@ export type IntegrationsGithubBranchesRetrieveParams = {}export type IntegrationsGithubReposRetrieveParams = {+ /**+ * When true, return only id, name, and full_name for each repository. Use it to list large rosters in fewer, smaller pages.+ */+ compact?: boolean/*** Maximum number of repositories to return per request (max 500).* @minimum 1diff --git a/products/integrations/mcp/tools.yaml b/products/integrations/mcp/tools.yamlindex 1704942ff0ae..5f188fd2e907 100644--- a/products/integrations/mcp/tools.yaml+++ b/products/integrations/mcp/tools.yaml@@ -131,9 +131,14 @@ tools:description: >List the repositories accessible to a GitHub integration (by integration ID). Serves the cached repositorylist from the GitHub App installation. Supports `search` (case-insensitive name match), `limit` (default- 100, max 500), and `offset` query parameters. Returns repository id, name, and full_name (owner/repo) plus a- has_more flag. Use this to validate that a repository is accessible to the integration before referencing it- (e.g. when creating a GitHub data warehouse source).+ 100, max 500), and `offset` query parameters. Returns repository id, name, and full_name (owner/repo), a+ has_more flag, a total count, and next_offset. When has_more is true, call again with `offset` set to+ next_offset to get the next page. Set `compact` to false only when you need the extra repository details.+ Use this to validate that a repository is accessible to the integration before referencing it (e.g. when+ creating a GitHub data warehouse source).+ param_overrides:+ compact:+ default: trueintegrations-github-teams-retrieve:operation: integrations_github_teams_retrieveenabled: falsediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 295f10e21e78..f12093b40eaa 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -7034,7 +7034,7 @@}},"integrations-github-repos-retrieve": {- "description": "List the repositories accessible to a GitHub integration (by integration ID). Serves the cached repository list from the GitHub App installation. Supports `search` (case-insensitive name match), `limit` (default 100, max 500), and `offset` query parameters. Returns repository id, name, and full_name (owner/repo) plus a has_more flag. Use this to validate that a repository is accessible to the integration before referencing it (e.g. when creating a GitHub data warehouse source).",+ "description": "List the repositories accessible to a GitHub integration (by integration ID). Serves the cached repository list from the GitHub App installation. Supports `search` (case-insensitive name match), `limit` (default 100, max 500), and `offset` query parameters. Returns repository id, name, and full_name (owner/repo), a has_more flag, a total count, and next_offset. When has_more is true, call again with `offset` set to next_offset to get the next page. Set `compact` to false only when you need the extra repository details. Use this to validate that a repository is accessible to the integration before referencing it (e.g. when creating a GitHub data warehouse source).","category": "Integrations","feature": "integrations","summary": "List GitHub integration repositories",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex bd05fa13bc6a..0b7ef0efcc39 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -7245,7 +7245,7 @@}},"integrations-github-repos-retrieve": {- "description": "List the repositories accessible to a GitHub integration (by integration ID). Serves the cached repository list from the GitHub App installation. Supports `search` (case-insensitive name match), `limit` (default 100, max 500), and `offset` query parameters. Returns repository id, name, and full_name (owner/repo) plus a has_more flag. Use this to validate that a repository is accessible to the integration before referencing it (e.g. when creating a GitHub data warehouse source).",+ "description": "List the repositories accessible to a GitHub integration (by integration ID). Serves the cached repository list from the GitHub App installation. Supports `search` (case-insensitive name match), `limit` (default 100, max 500), and `offset` query parameters. Returns repository id, name, and full_name (owner/repo), a has_more flag, a total count, and next_offset. When has_more is true, call again with `offset` set to next_offset to get the next page. Set `compact` to false only when you need the extra repository details. Use this to validate that a repository is accessible to the integration before referencing it (e.g. when creating a GitHub data warehouse source).","category": "Integrations","feature": "integrations","summary": "List GitHub integration repositories",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a4cd82620c0c..48605e6a9eb8 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -50751,6 +50751,11 @@ export namespace Schemas {repositories: GitHubRepo[];/** Whether more repositories are available beyond this page. */has_more: boolean;+ /**+ * The offset to pass to get the next page, or null when this page is the last one.+ * @nullable+ */+ next_offset: number | null;/** Total number of repositories matching the search query, across all pages. */total: number;}@@ -118082,6 +118087,10 @@ export namespace Schemas {};export type IntegrationsGithubReposRetrieveParams = {+ /**+ * When true, return only id, name, and full_name for each repository. Use it to list large rosters in fewer, smaller pages.+ */+ compact?: boolean;/*** Maximum number of repositories to return per request (max 500).* @minimum 1@@ -123434,6 +123443,10 @@ export namespace Schemas {};export type UsersIntegrationsGithubReposRetrieveParams = {+ /**+ * When true, return only id, name, and full_name for each repository. Use it to list large rosters in fewer, smaller pages.+ */+ compact?: boolean;/*** Maximum number of repositories to return per request (max 500).* @minimum 1diff --git a/services/mcp/src/generated/integrations/api.ts b/services/mcp/src/generated/integrations/api.tsindex 58e89ecd4200..7610426b126d 100644--- a/services/mcp/src/generated/integrations/api.ts+++ b/services/mcp/src/generated/integrations/api.ts@@ -138,6 +138,7 @@ export const IntegrationsGithubReposRetrieveParams = () => zod.object({),})+export const integrationsGithubReposRetrieveQueryCompactDefault = falseexport const integrationsGithubReposRetrieveQueryLimitDefault = 100export const integrationsGithubReposRetrieveQueryLimitMax = 500@@ -147,6 +148,12 @@ export const integrationsGithubReposRetrieveQueryOffsetMin = 0export const integrationsGithubReposRetrieveQuerySearchDefault = ``export const IntegrationsGithubReposRetrieveQueryParams = () => zod.object({+ compact: zod+ .boolean()+ .default(integrationsGithubReposRetrieveQueryCompactDefault)+ .describe(+ 'When true, return only id, name, and full_name for each repository. Use it to list large rosters in fewer, smaller pages.'+ ),limit: zod.number().min(1)diff --git a/services/mcp/src/tools/generated/integrations.ts b/services/mcp/src/tools/generated/integrations.tsindex bff2b1cd8634..c118062699ae 100644--- a/services/mcp/src/tools/generated/integrations.ts+++ b/services/mcp/src/tools/generated/integrations.ts@@ -82,9 +82,9 @@ const integrationsChannelsRetrieve = (): ToolBase<const IntegrationsGithubReposRetrieveSchema = () => {const IntegrationsGithubReposRetrieveParams = orvalSchemas.IntegrationsGithubReposRetrieveParams()const IntegrationsGithubReposRetrieveQueryParams = orvalSchemas.IntegrationsGithubReposRetrieveQueryParams()- return IntegrationsGithubReposRetrieveParams.omit({ project_id: true }).extend(- IntegrationsGithubReposRetrieveQueryParams.shape- )+ return IntegrationsGithubReposRetrieveParams.omit({ project_id: true })+ .extend(IntegrationsGithubReposRetrieveQueryParams.shape)+ .extend({ compact: IntegrationsGithubReposRetrieveQueryParams.shape['compact'].default(true).optional() })}const integrationsGithubReposRetrieve = (): ToolBase<@@ -99,6 +99,7 @@ const integrationsGithubReposRetrieve = (): ToolBase<method: 'GET',path: `/api/projects/${encodeURIComponent(String(projectId))}/integrations/${encodeURIComponent(String(params.id))}/github_repos/`,query: {+ compact: params.compact,limit: params.limit,offset: params.offset,search: params.search,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-github-repos-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-github-repos-retrieve.jsonindex b4d2857e3765..a92ed71f4948 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-github-repos-retrieve.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-github-repos-retrieve.json@@ -1,6 +1,11 @@{"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {+ "compact": {+ "default": true,+ "description": "When true, return only id, name, and full_name for each repository. Use it to list large rosters in fewer, smaller pages.",+ "type": "boolean"+ },"id": {"description": "A unique integer value identifying this integration.","type": "number"