: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(billing): clarify mcp permission errors (#95953)
Pawel Cebulab6bce177e549
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.mdindex 5c6cb8b6d6e7..21e1a863ee76 100644--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md@@ -130,6 +130,11 @@ aggregates data that is not represented as a team-scoped PostHog table,or returns a curated API shape that would be awkward or unsafe to rebuild in SQL.For these tools, keep the surface narrow and document the source and shape in the YAML description.+For proxy endpoints that can fail because of either user permissions or request scope,+return distinct API-visible error details. Agents should stop on true authorization+failures, but they can often recover from a bad project/team filter if the response says+the requested scope is unavailable.+System tables are defined in [`posthog/hogql/database/schema/system.py`](https://github.com/PostHog/posthog/blob/master/posthog/hogql/database/schema/system.py) as `PostgresTable` instances.Each table must include a `team_id` column for data isolation.diff --git a/ee/api/billing.py b/ee/api/billing.pyindex 109c7cb6f749..87d7246e9900 100644--- a/ee/api/billing.py+++ b/ee/api/billing.py@@ -125,6 +125,18 @@ BILLING_GUIDANCE_ERRORS: dict[str, type[APIException]] = {BILLING_LIMIT_TODAYS_USAGE_KEYS = ("posthog_code_credits",)+BILLING_ACCESS_DENIED_MESSAGE = (+ "Your PostHog user does not have billing access for this organization. "+ "Ask someone with billing access to run this or update your role."+)+BILLING_USAGE_SPEND_ACCESS_DENIED_MESSAGE = (+ "Your PostHog user does not have access to billing usage and spend for this organization. "+ "Ask someone with billing access to run this or update your role."+)+BILLING_PROJECT_ACCESS_DENIED_MESSAGE = (+ "The requested projects are not available to this PostHog user or token. "+ "Adjust the project filter or ask someone with billing access to run this."+)def _owner_only_billing_enabled(user: User, organization: Organization) -> Optional[bool]:@@ -252,7 +264,7 @@ class HasBillingAccess(permissions.BasePermission):Permission to allow users with Billing access to access Billing endpoints."""- message = "You do not have access to Billing for this organization."+ message = BILLING_ACCESS_DENIED_MESSAGEdef has_permission(self, request: Request, view: Any) -> bool:try:@@ -271,7 +283,7 @@ class HasBillingUsageSpendReadAccess(permissions.BasePermission):Permission for read-only billing usage/spend endpoints."""- message = "You do not have access to billing usage and spend data for this organization."+ message = BILLING_USAGE_SPEND_ACCESS_DENIED_MESSAGEdef has_permission(self, request: Request, view: Any) -> bool:try:@@ -700,7 +712,7 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):org = self._get_org()if is_token_auth_request(request):if not org or not isinstance(request.user, User) or not user_has_billing_access(request.user, org):- raise PermissionDenied("You do not have access to Billing for this organization.")+ raise PermissionDenied(BILLING_ACCESS_DENIED_MESSAGE)# If on Cloud and we have the property billing - return 404 as we always use legacy billing it it existsif hasattr(org, "billing"):@@ -1382,7 +1394,7 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):accessible_team_ids = sorted(set(accessible_team_ids).intersection(token_scoped_team_ids))if not accessible_team_ids:- raise PermissionDenied(HasBillingUsageSpendReadAccess.message)+ raise PermissionDenied(BILLING_PROJECT_ACCESS_DENIED_MESSAGE)requested_team_ids = self._parse_team_ids(params_to_pass.get("team_ids"))if not requested_team_ids:@@ -1390,7 +1402,7 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):scoped_team_ids = sorted(set(requested_team_ids).intersection(accessible_team_ids))if not scoped_team_ids:- raise PermissionDenied(HasBillingUsageSpendReadAccess.message)+ raise PermissionDenied(BILLING_PROJECT_ACCESS_DENIED_MESSAGE)return scoped_team_idsdiff --git a/ee/api/test/test_billing.py b/ee/api/test/test_billing.pyindex ffec9c5eb97f..2ea0d3f98191 100644--- a/ee/api/test/test_billing.py+++ b/ee/api/test/test_billing.py@@ -33,7 +33,9 @@ from products.access_control.backend.models.access_control import AccessControlfrom ee.api.billing import (_EXPORT_STREAMS,+ BILLING_ACCESS_DENIED_MESSAGE,BILLING_LIMIT_TODAYS_USAGE_FLAG,+ BILLING_PROJECT_ACCESS_DENIED_MESSAGE,MEMBER_BILLING_USAGE_SPEND_READ_ACCESS_FLAG,OWNER_ONLY_BILLING_FLAG,BillingDateRangeTooLong,@@ -1364,6 +1366,10 @@ class TestBillingUsageAndSpendAPI(APILicensedTest):)self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ expected_detail = (+ BILLING_ACCESS_DENIED_MESSAGE if action_name == "list" else HasBillingUsageSpendReadAccess.message+ )+ self.assertEqual(response.json()["detail"], expected_detail)mock_manager_method.assert_not_called()@patch("ee.billing.billing_manager.BillingManager.get_usage_data")@@ -1646,6 +1652,7 @@ class TestBillingUsageAndSpendAPI(APILicensedTest):)self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ self.assertEqual(response.json()["detail"], BILLING_PROJECT_ACCESS_DENIED_MESSAGE)mock_get_usage_data.assert_not_called()@patch("ee.billing.billing_manager.BillingManager.get_billing")@@ -1807,12 +1814,14 @@ class TestBillingUsageAndSpendAPI(APILicensedTest):self.organization_membership.save()response = self.client.get("/api/billing/usage/")self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ self.assertEqual(response.json()["detail"], HasBillingUsageSpendReadAccess.message)def test_get_spend_permission_denied_for_member(self):self.organization_membership.level = OrganizationMembership.Level.MEMBERself.organization_membership.save()response = self.client.get("/api/billing/spend/")self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ self.assertEqual(response.json()["detail"], HasBillingUsageSpendReadAccess.message)@parameterized.expand([@@ -2043,6 +2052,7 @@ class TestBillingUsageAndSpendAPI(APILicensedTest):response = self.client.get(f"/api/billing/{endpoint}/?team_ids=[{private_team.pk}]")self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ self.assertEqual(response.json()["detail"], BILLING_PROJECT_ACCESS_DENIED_MESSAGE)# An empty team_ids list means "all teams" to the billing service, so it must never be called heremock_get_usage_data.assert_not_called()mock_get_spend_data.assert_not_called()@@ -2302,19 +2312,37 @@ class TestBillingPermissionDeniedForMembers(APILicensedTest):@parameterized.expand([- ("activate", "post", "/api/billing/activate", {"products": "all_products:"}),- ("deactivate", "post", "/api/billing/deactivate", {"products": "product_1"}),- ("patch", "patch", "/api/billing//", {"custom_limits_usd": {}}),- ("subscription_switch_plan", "post", "/api/billing/subscription/switch-plan", {"plan": "test"}),- ("portal", "get", "/api/billing/portal", None),- ("activate_trial", "post", "/api/billing/trials/activate", {"product": "test"}),- ("cancel_trial", "post", "/api/billing/trials/cancel", {"product": "test"}),- ("purchase_credits", "post", "/api/billing/credits/purchase", {"amount": 100}),- ("claim_coupon", "post", "/api/billing/coupons/claim", {"code": "TEST"}),- ("startup_apply", "post", "/api/billing/startups/apply", "USE_ORG_ID"),+ ("activate", "post", "/api/billing/activate", {"products": "all_products:"}, BILLING_ACCESS_DENIED_MESSAGE),+ ("deactivate", "post", "/api/billing/deactivate", {"products": "product_1"}, BILLING_ACCESS_DENIED_MESSAGE),+ ("patch", "patch", "/api/billing//", {"custom_limits_usd": {}}, BILLING_ACCESS_DENIED_MESSAGE),+ (+ "subscription_switch_plan",+ "post",+ "/api/billing/subscription/switch-plan",+ {"plan": "test"},+ BILLING_ACCESS_DENIED_MESSAGE,+ ),+ ("portal", "get", "/api/billing/portal", None, BILLING_ACCESS_DENIED_MESSAGE),+ (+ "activate_trial",+ "post",+ "/api/billing/trials/activate",+ {"product": "test"},+ BILLING_ACCESS_DENIED_MESSAGE,+ ),+ ("cancel_trial", "post", "/api/billing/trials/cancel", {"product": "test"}, BILLING_ACCESS_DENIED_MESSAGE),+ (+ "purchase_credits",+ "post",+ "/api/billing/credits/purchase",+ {"amount": 100},+ BILLING_ACCESS_DENIED_MESSAGE,+ ),+ ("claim_coupon", "post", "/api/billing/coupons/claim", {"code": "TEST"}, BILLING_ACCESS_DENIED_MESSAGE),+ ("startup_apply", "post", "/api/billing/startups/apply", "USE_ORG_ID", None),])- def test_permission_denied(self, _name, method, url, data):+ def test_permission_denied(self, _name, method, url, data, expected_detail):if data == "USE_ORG_ID":data = {"organization_id": str(self.organization.id)}client_method = getattr(self.client, method)@@ -2326,6 +2354,8 @@ class TestBillingPermissionDeniedForMembers(APILicensedTest):else:response = client_method(url)self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ if expected_detail:+ self.assertEqual(response.json()["detail"], expected_detail)@patch("ee.billing.billing_manager.http_session.get")def test_list_still_accessible(self, mock_request):diff --git a/products/billing/skills/test_understanding_billing_usage_skill.py b/products/billing/skills/test_understanding_billing_usage_skill.pyindex 07e160d9ba6a..af0e75279796 100644--- a/products/billing/skills/test_understanding_billing_usage_skill.py+++ b/products/billing/skills/test_understanding_billing_usage_skill.py@@ -17,3 +17,13 @@ def test_product_drilldown_treats_product_data_as_untrusted() -> None:skill_content = SKILL_PATH.read_text(encoding="utf-8")assert "untrusted evidence" in skill_content+++def test_permission_errors_point_to_access_recovery() -> None:+ skill_content = SKILL_PATH.read_text(encoding="utf-8")+ normalized_skill_content = " ".join(skill_content.split())++ assert "If a billing tool returns a permission error, read the error detail" in normalized_skill_content+ assert "Stop only when it says the user does not have billing access" in normalized_skill_content+ assert "does not have billing access for this organization" in normalized_skill_content+ assert "If the permission error points to requested projects or `team_ids`" in normalized_skill_contentdiff --git a/products/billing/skills/understanding-billing-usage/SKILL.md b/products/billing/skills/understanding-billing-usage/SKILL.mdindex 59912c547024..7ebcdf030023 100644--- a/products/billing/skills/understanding-billing-usage/SKILL.md+++ b/products/billing/skills/understanding-billing-usage/SKILL.md@@ -40,17 +40,25 @@ or contract questions. Keep it focused on usage and spend behavior.| `posthog:billing-spend-get` | Optional spend context when the user asks about dollars || Product-specific MCP tools | Follow-up investigation inside the affected product/project |-Only use this skill when the Billing read tools above are available. If the user asks-about Billing usage and those tools are not available, do not continue with this-workflow; briefly say that Billing usage investigation is not enabled for this-organization or MCP session. If a Billing tool is available but returns a permission-error, explain that the MCP session needs Billing access from an org admin or owner-rather than saying the feature is unavailable.+Only use this skill when the billing read tools above are available. If the user asks+about billing usage and those tools are not available, do not continue with this+workflow. Briefly say that billing usage investigation is not enabled for this+organization or MCP session.++If a billing tool returns a permission error, read the error detail before+deciding what to do. Stop only when it says the user does not have billing+access. Say the current PostHog user does not have billing access for this+organization and should ask someone with billing access to run it or update+their role.++If the permission error points to requested projects or `team_ids`, correct the+project filter once if the user provided the wrong project context. Do not+describe that as missing billing access unless the tool says it is.Some clients expose PostHog MCP tools through `mcp__posthog__exec` instead of direct-`posthog:*` tool names. If the direct Billing tools are not visible, search for-`billing`, inspect the relevant tool schema, and call the Billing tool through the-dispatcher before deciding Billing usage investigation is unavailable.+`posthog:*` tool names. If the direct billing tools are not visible, search for+`billing`, inspect the relevant tool schema, and call the billing tool through the+dispatcher before deciding billing usage investigation is unavailable.Read `references/spike-alert-mechanics.md` when the prompt comes from a usage alertemail or dashboard link and you need URL parameter or weekday/weekend baseline guidance.