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.

fix(llma): accept OAuth tokens on @me/spend with personal_spend scope (#59490)

Paul D'Ambra8108cadca5f6
diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsx
index caaa53efb47a..8512ca7a1ee3 100644
--- a/frontend/src/lib/scopes.tsx
+++ b/frontend/src/lib/scopes.tsx
@@ -93,6 +93,15 @@ export const API_SCOPES: APIScope[] = [
},
},
{ key: 'person', objectName: 'Person', objectPlural: 'persons' },
+ {
+ key: 'personal_spend',
+ objectName: 'Personal LLM spend',
+ objectPlural: 'personal LLM spend',
+ disabledActions: ['write'],
+ warnings: {
+ read: <>This scope allows you to retrieve your own LLM spend across PostHog products.</>,
+ },
+ },
{ key: 'persisted_folder', objectName: 'Persisted folder', objectPlural: 'persisted folders' },
{ key: 'customer_profile_config', objectName: 'Customer profile config', objectPlural: 'customer profile configs' },
{ key: 'plugin', objectName: 'Plugin', objectPlural: 'plugins' },
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 3dbd051ffc3a..995da720fa4f 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5369,6 +5369,7 @@ export type APIScopeObject =
| 'organization_integration'
| 'organization_member'
| 'person'
+ | 'personal_spend'
| 'persisted_folder'
| 'plugin'
| 'product_tour'
diff --git a/posthog/api/documentation.py b/posthog/api/documentation.py
index 686c8d0a6960..50018e622338 100644
--- a/posthog/api/documentation.py
+++ b/posthog/api/documentation.py
@@ -673,6 +673,9 @@ _PROJECTS_PREFIX_RE = re.compile(r"^/api/projects/\{parent_lookup_\w+\}/")
_ENVIRONMENTS_PREFIX_RE = re.compile(r"^/api/environments/\{parent_lookup_\w+\}/")
_ORG_PREFIX_RE = re.compile(r"^/api/organizations/\{parent_lookup_\w+\}/")
+_OPERATION_ID_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
+_HTTP_METHODS = frozenset({"get", "put", "post", "delete", "options", "head", "patch", "trace"})
+
# Match finalized paths (after {parent_lookup_*} substitution) for postprocessing.
_ORG_PROJECTS_FINAL_RE = re.compile(r"^/api/organizations/[^/]+/projects/")
_PROJECT_ENVS_FINAL_RE = re.compile(r"^/api/projects/[^/]+/environments/")
@@ -1034,6 +1037,29 @@ def lint_spec_consistency_hook(result, generator, request, public):
walk(v, f"{path}[{i}]")
walk(result, "$")
+
+ # operationId must be a valid identifier — drf-spectacular auto-derives it from the
+ # URL path, so segments like `@me` produce `..._@me_..._list` which (a) breaks the
+ # MCP YAML scaffolder, whose keys can't contain `@`, and (b) is rejected by any
+ # OpenAPI-typed-client codegen that maps it to a function name. The fix is to set
+ # `operation_id="..."` explicitly on `@extend_schema` — surface it here so CI catches
+ # it the same day it lands instead of breaking the MCP build downstream.
+ paths = result.get("paths") or {}
+ for url_path, methods in paths.items():
+ if not isinstance(methods, dict):
+ continue
+ for method, op in methods.items():
+ if method not in _HTTP_METHODS or not isinstance(op, dict):
+ continue
+ op_id = op.get("operationId")
+ if isinstance(op_id, str) and not _OPERATION_ID_RE.match(op_id):
+ spectacular_warn(
+ f"spec consistency: operationId {op_id!r} contains non-identifier "
+ f"characters (must match {_OPERATION_ID_RE.pattern}) at "
+ f"{method.upper()} {url_path}. Set `operation_id=` explicitly on "
+ f"`@extend_schema(...)` to override the URL-derived default."
+ )
+
return result
diff --git a/posthog/api/test/test_documentation_lint_hook.py b/posthog/api/test/test_documentation_lint_hook.py
new file mode 100644
index 000000000000..ab2f4de06e00
--- /dev/null
+++ b/posthog/api/test/test_documentation_lint_hook.py
@@ -0,0 +1,56 @@
+"""Tests for posthog.api.documentation.lint_spec_consistency_hook."""
+
+import pytest
+from unittest.mock import patch
+
+from posthog.api.documentation import lint_spec_consistency_hook
+
+
+ "operation_id,should_warn",
+ [
+ ("llm_analytics_personal_spend_list", False),
+ ("clean_snake_case_id", False),
+ ("CamelCaseId", False),
+ ("_underscore_prefix", False),
+ ("llm_analytics_@me_spend_list", True),
+ ("path-with-dashes", True),
+ ("contains.dots", True),
+ ("trailing space ", True),
+ ("123_starts_with_digit", True),
+ ],
+)
+def test_lint_spec_consistency_hook_operation_id_validation(operation_id: str, should_warn: bool) -> None:
+ spec = {
+ "paths": {
+ "/api/test/": {
+ "get": {"operationId": operation_id},
+ },
+ },
+ }
+ with patch("posthog.api.documentation.spectacular_warn") as mock_warn:
+ lint_spec_consistency_hook(spec, generator=None, request=None, public=True)
+ warned_about_op_id = any(
+ "operationId" in str(call_args.args[0]) and operation_id in str(call_args.args[0])
+ for call_args in mock_warn.call_args_list
+ )
+ assert warned_about_op_id is should_warn, (
+ f"operationId {operation_id!r} expected should_warn={should_warn} but got {warned_about_op_id}. "
+ f"All warnings: {[c.args[0] for c in mock_warn.call_args_list]}"
+ )
+
+
+def test_lint_spec_consistency_hook_skips_non_method_keys() -> None:
+ """`parameters`, `summary`, etc. on a path object aren't HTTP methods — skip them."""
+ spec = {
+ "paths": {
+ "/api/test/": {
+ "parameters": [{"name": "weird-name"}],
+ "get": {"operationId": "valid_id"},
+ },
+ },
+ }
+ with patch("posthog.api.documentation.spectacular_warn") as mock_warn:
+ lint_spec_consistency_hook(spec, generator=None, request=None, public=True)
+ op_id_warnings = [c for c in mock_warn.call_args_list if "operationId" in str(c.args[0])]
+ assert op_id_warnings == []
diff --git a/posthog/scopes.py b/posthog/scopes.py
index 524a10b147ed..2a1e6f5e4220 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -73,6 +73,7 @@ APIScopeObject = Literal[
"organization_integration",
"organization_member",
"person",
+ "personal_spend",
"persisted_folder",
"plugin",
"product_tour",
diff --git a/products/endpoints/backend/api.py b/products/endpoints/backend/api.py
index a90b5b557ea1..137d249cc9be 100644
--- a/products/endpoints/backend/api.py
+++ b/products/endpoints/backend/api.py
@@ -2652,6 +2652,9 @@ class EndpointViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.Model
)
@extend_schema(
+ # url_path="openapi.json" would otherwise produce `..._openapi.json_retrieve` —
+ # the `.` is rejected by lint_spec_consistency_hook + the MCP YAML scaffolder.
+ operation_id="endpoints_openapi_spec_retrieve",
description="Get OpenAPI 3.0 specification for this endpoint. Use this to generate typed SDK clients.",
parameters=[
OpenApiParameter(
diff --git a/products/endpoints/frontend/generated/api.schemas.ts b/products/endpoints/frontend/generated/api.schemas.ts
index e8a5f2b1d6b7..495100c82bd4 100644
--- a/products/endpoints/frontend/generated/api.schemas.ts
+++ b/products/endpoints/frontend/generated/api.schemas.ts
@@ -854,7 +854,7 @@ export type EndpointsListParams = {
offset?: number
}
-export type EndpointsOpenapiJsonRetrieveParams = {
+export type EndpointsOpenapiSpecRetrieveParams = {
/**
* Specific endpoint version to generate the spec for. Defaults to latest.
*/
diff --git a/products/endpoints/frontend/generated/api.ts b/products/endpoints/frontend/generated/api.ts
index 367d19ce3d2b..8d422e6f58ce 100644
--- a/products/endpoints/frontend/generated/api.ts
+++ b/products/endpoints/frontend/generated/api.ts
@@ -17,7 +17,7 @@ import type {
EndpointRunResponseApi,
EndpointVersionResponseApi,
EndpointsListParams,
- EndpointsOpenapiJsonRetrieveParams,
+ EndpointsOpenapiSpecRetrieveParams,
EndpointsVersionsListParams,
MaterializationPreviewRequestApi,
PaginatedEndpointResponseListApi,
@@ -189,10 +189,10 @@ export const endpointsMaterializationStatusRetrieve = async (
})
}
-export const getEndpointsOpenapiJsonRetrieveUrl = (
+export const getEndpointsOpenapiSpecRetrieveUrl = (
projectId: string,
name: string,
- params?: EndpointsOpenapiJsonRetrieveParams
+ params?: EndpointsOpenapiSpecRetrieveParams
) => {
const normalizedParams = new URLSearchParams()
@@ -212,13 +212,13 @@ export const getEndpointsOpenapiJsonRetrieveUrl = (
/**
* Get OpenAPI 3.0 specification for this endpoint. Use this to generate typed SDK clients.
*/
-export const endpointsOpenapiJsonRetrieve = async (
+export const endpointsOpenapiSpecRetrieve = async (
projectId: string,
name: string,
- params?: EndpointsOpenapiJsonRetrieveParams,
+ params?: EndpointsOpenapiSpecRetrieveParams,
options?: RequestInit
): Promise<void> => {
- return apiMutator<void>(getEndpointsOpenapiJsonRetrieveUrl(projectId, name, params), {
+ return apiMutator<void>(getEndpointsOpenapiSpecRetrieveUrl(projectId, name, params), {
...options,
method: 'GET',
})
diff --git a/products/endpoints/mcp/tools.yaml b/products/endpoints/mcp/tools.yaml
index a81c4e231724..b019b5b48688 100644
--- a/products/endpoints/mcp/tools.yaml
+++ b/products/endpoints/mcp/tools.yaml
@@ -72,7 +72,7 @@ tools:
Get lightweight materialization status for an endpoint without fetching full endpoint data. Returns whether
materialization is possible, current status, last run time, and any errors. Supports ?version=N.
endpoint-openapi-spec:
- operation: endpoints_openapi.json_retrieve
+ operation: endpoints_openapi_spec_retrieve
enabled: true
scopes:
- endpoint:read
diff --git a/products/llm_analytics/backend/api/personal_spend.py b/products/llm_analytics/backend/api/personal_spend.py
index baacde962851..c510793a168d 100644
--- a/products/llm_analytics/backend/api/personal_spend.py
+++ b/products/llm_analytics/backend/api/personal_spend.py
@@ -591,14 +591,18 @@ class PersonalSpendViewSet(viewsets.ViewSet):
authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]
permission_classes = [permissions.IsAuthenticated, APIScopePermission]
- # Not project- or org-nested; the caller's identity is the only scope. INTERNAL
- # opts out of team/org scope enforcement in APIScopePermission. The required
- # scope on the wire is still `llm_analytics:read`, supplied below so the MCP
- # tool's scope declaration stays accurate.
+ # Identity-scoped: the caller reads their own spend, not data nested under
+ # a team or project. `scope_object = "INTERNAL"` + `dangerously_skip_scoped_team_enforcement`
+ # opt out of team/org enforcement in APIScopePermission — valid here because
+ # this viewset filters strictly by the authenticated user's email (see
+ # `_email_filter` in `list` below). The required scope is overridden to the
+ # purpose-built `personal_spend:read` — narrower than the broad `user:read`
+ # cluster — and the frontend (scopes.tsx) marks its `:write` as disabled.
scope_object = "INTERNAL"
+ dangerously_skip_scoped_team_enforcement = True
def dangerously_get_required_scopes(self, request: Request, view) -> list[str] | None:
- return ["llm_analytics:read"]
+ return ["personal_spend:read"]
def get_throttles(self):
return [
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 4c6bb40ca61d..04342a2e2443 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -38106,7 +38106,7 @@ export namespace Schemas {
offset?: number;
};
- export type EnvironmentsEndpointsOpenapiJsonRetrieveParams = {
+ export type EnvironmentsEndpointsOpenapiSpecRetrieveParams = {
/**
* Specific endpoint version to generate the spec for. Defaults to latest.
*/
@@ -43055,7 +43055,7 @@ export namespace Schemas {
offset?: number;
};
- export type EndpointsOpenapiJsonRetrieveParams = {
+ export type EndpointsOpenapiSpecRetrieveParams = {
/**
* Specific endpoint version to generate the spec for. Defaults to latest.
*/
diff --git a/services/mcp/src/generated/endpoints/api.ts b/services/mcp/src/generated/endpoints/api.ts
index 1adeb0577eba..c65e06113905 100644
--- a/services/mcp/src/generated/endpoints/api.ts
+++ b/services/mcp/src/generated/endpoints/api.ts
@@ -166,7 +166,7 @@ export const EndpointsMaterializationStatusRetrieveParams = /* @__PURE__ */ zod.
/**
* Get OpenAPI 3.0 specification for this endpoint. Use this to generate typed SDK clients.
*/
-export const EndpointsOpenapiJsonRetrieveParams = /* @__PURE__ */ zod.object({
+export const EndpointsOpenapiSpecRetrieveParams = /* @__PURE__ */ zod.object({
name: zod.string(),
project_id: zod
.string()
@@ -175,7 +175,7 @@ export const EndpointsOpenapiJsonRetrieveParams = /* @__PURE__ */ zod.object({
),
})
-export const EndpointsOpenapiJsonRetrieveQueryParams = /* @__PURE__ */ zod.object({
+export const EndpointsOpenapiSpecRetrieveQueryParams = /* @__PURE__ */ zod.object({
version: zod
.number()
.optional()
diff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.ts
index d4f38fde2034..bd61ce1e0a87 100644
--- a/services/mcp/src/lib/oauth-scopes.generated.ts
+++ b/services/mcp/src/lib/oauth-scopes.generated.ts
@@ -127,6 +127,8 @@ export const OAUTH_SCOPES_SUPPORTED = [
'organization_member:write',
'person:read',
'person:write',
+ 'personal_spend:read',
+ 'personal_spend:write',
'persisted_folder:read',
'persisted_folder:write',
'plugin:read',
diff --git a/services/mcp/src/tools/generated/endpoints.ts b/services/mcp/src/tools/generated/endpoints.ts
index 71785363a0a0..76b5ed07c28b 100644
--- a/services/mcp/src/tools/generated/endpoints.ts
+++ b/services/mcp/src/tools/generated/endpoints.ts
@@ -7,8 +7,8 @@ import {
EndpointsDestroyParams,
EndpointsListQueryParams,
EndpointsMaterializationStatusRetrieveParams,
- EndpointsOpenapiJsonRetrieveParams,
- EndpointsOpenapiJsonRetrieveQueryParams,
+ EndpointsOpenapiSpecRetrieveParams,
+ EndpointsOpenapiSpecRetrieveQueryParams,
EndpointsPartialUpdateBody,
EndpointsPartialUpdateParams,
EndpointsRetrieveParams,
@@ -107,8 +107,8 @@ const endpointMaterializationStatus = (): ToolBase<
},
})
-const EndpointOpenapiSpecSchema = EndpointsOpenapiJsonRetrieveParams.omit({ project_id: true }).extend(
- EndpointsOpenapiJsonRetrieveQueryParams.shape
+const EndpointOpenapiSpecSchema = EndpointsOpenapiSpecRetrieveParams.omit({ project_id: true }).extend(
+ EndpointsOpenapiSpecRetrieveQueryParams.shape
)
const endpointOpenapiSpec = (): ToolBase<typeof EndpointOpenapiSpecSchema, unknown> => ({