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(mcp): fail codegen on scope drift, mark request-dependent scopes (#112336)

Julian Bezcdb60ad38df4
diff --git a/.agents/skills/implementing-mcp-tools/SKILL.md b/.agents/skills/implementing-mcp-tools/SKILL.md
index 86aef0a0c0b3..1364b0c69b75 100644
--- a/.agents/skills/implementing-mcp-tools/SKILL.md
+++ b/.agents/skills/implementing-mcp-tools/SKILL.md
@@ -182,7 +182,9 @@ tools:
When `scopes` is omitted, the generator uses the scopes the API requires, so the tool cannot drift from the endpoint.
Set `scopes` by hand only when the API computes them per request (the generator fails and says so) or to gate a tool more tightly.
-A `scopes` list that misses a scope the API requires prints a warning, and a GitHub annotation on CI.
+A `scopes` list that misses a scope the API requires fails codegen, with a GitHub annotation on CI.
+When the API picks the scopes per request, list the action in the viewset's `request_dependent_scope_actions`.
+The spec then marks the operation with `x-request-dependent-scopes`, codegen skips the check for it, and its tools must declare `scopes`.
`annotations` default to the HTTP method for GET (read-only) and DELETE (destructive).
PATCH, POST and PUT vary too much (a PATCH can be a soft delete or non-idempotent), so declare `annotations` for them.
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
index 62e57efb29e5..cba970cda41d 100644
--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
@@ -262,6 +262,8 @@ Product teams own their definitions and control which operations are exposed as
2. **Configure** the YAML – enable tools and add descriptions.
Scopes come from the API when you omit them. Annotations default for GET and DELETE, so declare them for PATCH, POST and PUT.
+ A `scopes` list that misses a scope the API requires fails codegen.
+ When an action's scopes depend on the request, list the action in the viewset's `request_dependent_scope_actions`, and declare `scopes` on its tools.
Each YAML file has a top-level structure validated by Zod ([`scripts/yaml-config-schema.ts`](https://github.com/PostHog/posthog/blob/master/services/mcp/scripts/yaml-config-schema.ts)):
**Tool names** follow a **`domain-action`** convention in lowercase kebab-case (`[a-z0-9-]`),
@@ -295,7 +297,7 @@ Product teams own their definitions and control which operations are exposed as
operation: your_product_endpoint_list # must match an OpenAPI operationId
enabled: true # false excludes from generation
# --- optional: ---
- scopes: # defaults to the scopes the API requires; a list that misses one warns
+ scopes: # defaults to the scopes the API requires; a list that misses one fails codegen
- your_product:read
annotations: # defaults for GET and DELETE; required for PATCH, POST and PUT
readOnly: true
diff --git a/posthog/api/documentation.py b/posthog/api/documentation.py
index 5d5860fdf698..38c804f579bc 100644
--- a/posthog/api/documentation.py
+++ b/posthog/api/documentation.py
@@ -8,7 +8,7 @@ from django.db import models
from drf_spectacular.drainage import warn as spectacular_warn
from drf_spectacular.extensions import OpenApiAuthenticationExtension
from drf_spectacular.openapi import AutoSchema
-from drf_spectacular.plumbing import build_basic_type, build_mock_request, build_parameter_type
+from drf_spectacular.plumbing import ComponentRegistry, build_basic_type, build_mock_request, build_parameter_type
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import (
OpenApiParameter,
@@ -96,6 +96,17 @@ class PostHogAutoSchema(AutoSchema):
# without a public REST contract.
return bool(self.get_extensions().get("x-internal")) and not _include_internal_operations()
+ def get_operation(
+ self, path: str, path_regex: str, path_prefix: str, method: str, registry: ComponentRegistry
+ ) -> dict[str, Any] | None:
+ operation = super().get_operation(path, path_regex, path_prefix, method, registry)
+ # The marker is set here and not in get_extensions(), because an @extend_schema(extensions=...)
+ # decorator on the action replaces the get_extensions() output.
+ dynamic_actions: frozenset[str] = getattr(self.view, "request_dependent_scope_actions", frozenset())
+ if operation is not None and getattr(self.view, "action", None) in dynamic_actions:
+ operation["x-request-dependent-scopes"] = True
+ return operation
+
def _resolve_path_parameters(self, variables):
from drf_spectacular.plumbing import get_view_model, resolve_django_path_parameter, resolve_regex_path_parameter
diff --git a/posthog/api/test/test_api_docs.py b/posthog/api/test/test_api_docs.py
index dfc21ee8d384..ef9a526d0f88 100644
--- a/posthog/api/test/test_api_docs.py
+++ b/posthog/api/test/test_api_docs.py
@@ -26,6 +26,19 @@ class _XInternalMarkerViewSet(viewsets.ViewSet):
return Response({"ok": True})
+class _RequestDependentScopesViewSet(viewsets.ViewSet):
+ scope_object = "project"
+ request_dependent_scope_actions = frozenset({"retrieve"})
+
+ @extend_schema(responses={200: _XInternalMarkerSerializer})
+ def list(self, request: Request) -> Response:
+ return Response({"ok": True})
+
+ @extend_schema(responses={200: _XInternalMarkerSerializer}, extensions={"x-product": "core"})
+ def retrieve(self, request: Request, id: str) -> Response:
+ return Response({"ok": True})
+
+
class TestAPIDocsSchema(APIBaseTest):
def test_retired_project_environments_route_is_not_in_schema(self) -> None:
self.client.logout()
@@ -53,6 +66,17 @@ class TestAPIDocsSchema(APIBaseTest):
codegen_schema = SchemaGenerator(patterns=patterns).get_schema(request=None, public=True)
assert "/api/x_internal_marker/" in codegen_schema["paths"]
+ def test_request_dependent_scope_marker_covers_only_listed_actions(self) -> None:
+ patterns = [
+ path("api/request_dependent/", _RequestDependentScopesViewSet.as_view({"get": "list"})),
+ path("api/request_dependent/<str:id>/", _RequestDependentScopesViewSet.as_view({"get": "retrieve"})),
+ ]
+
+ schema = SchemaGenerator(patterns=patterns).get_schema(request=None, public=True)
+
+ assert "x-request-dependent-scopes" not in schema["paths"]["/api/request_dependent/"]["get"]
+ assert schema["paths"]["/api/request_dependent/{id}/"]["get"]["x-request-dependent-scopes"] is True
+
def test_can_generate_api_docs_schema(self) -> None:
self.client.logout()
diff --git a/products/context_layer/backend/presentation/views.py b/products/context_layer/backend/presentation/views.py
index 07899f3b7362..bbdc44c5c3b7 100644
--- a/products/context_layer/backend/presentation/views.py
+++ b/products/context_layer/backend/presentation/views.py
@@ -629,6 +629,7 @@ class ContextLayerAgentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"update_page": "task:write",
"propose_page": "task:write",
}
+ request_dependent_scope_actions = frozenset(_RUN_TASK_SCOPES)
def dangerously_get_required_scopes(self, request: Request, view=None) -> list[str] | None: # noqa: ANN001
"""A run acts with task scopes; everyone else faces the organization ones.
diff --git a/services/mcp/scripts/generate-tools.ts b/services/mcp/scripts/generate-tools.ts
index 39bf072169b9..a99e7ff6ab95 100644
--- a/services/mcp/scripts/generate-tools.ts
+++ b/services/mcp/scripts/generate-tools.ts
@@ -91,6 +91,8 @@ interface OpenApiOperation {
operationId: string
/** Scopes the API requires, written by `posthog/api/documentation.py`. */
security?: Array<Record<string, string[]>>
+ /** The API picks the scopes per request, so `security` lists only the fallback for human callers. */
+ 'x-request-dependent-scopes'?: boolean
parameters?: OpenApiParam[]
requestBody?: {
content?: {
@@ -1739,6 +1741,12 @@ function resolveToolScopes(name: string, config: ToolConfig, resolved: ResolvedO
if (config.scopes?.length) {
return config.scopes
}
+ if (resolved.operation['x-request-dependent-scopes']) {
+ throw new Error(
+ `Enabled tool "${name}" has no "scopes", and the API picks the scopes for "${resolved.operation.operationId}" per request. ` +
+ `The spec lists only the fallback scopes for human callers. Add the scopes the tool's callers need to "scopes" in the tool's YAML.`
+ )
+ }
const specScopes = getSpecScopes(resolved.operation)
if (specScopes.length === 0) {
throw new Error(
@@ -1764,9 +1772,9 @@ function resolveToolAnnotations(name: string, config: ToolConfig, method: string
return { ...defaults }
}
-/** Scopes the API requires that the YAML list leaves out. A `:write` scope covers `:read`, as at runtime. Empty when the YAML has no list or the spec has none. */
+/** Scopes the API requires that the YAML list leaves out. A `:write` scope covers `:read`, as at runtime. Empty when the YAML has no list, the spec has none, or the API picks the scopes per request. */
function findMissingSpecScopes(config: ToolConfig, resolved: ResolvedOperation): string[] {
- if (!config.scopes?.length) {
+ if (!config.scopes?.length || resolved.operation['x-request-dependent-scopes']) {
return []
}
return getSpecScopes(resolved.operation).filter((scope) => !hasScope(config.scopes ?? [], scope))
@@ -1776,9 +1784,9 @@ function reportMissingSpecScopes(name: string, yamlLabel: string, missingScopes:
const message =
`Tool "${name}" does not list the scope(s) the API requires: ${missingScopes.join(', ')}. ` +
`A token without them sees the tool and then gets a 403. Add them to "scopes" or drop "scopes" to use the API's.`
- process.stdout.write(`WARNING ${yamlLabel}: ${message}\n`)
+ console.error(`ERROR ${yamlLabel}: ${message}`)
if (process.env.GITHUB_ACTIONS === 'true') {
- process.stdout.write(`::warning file=${yamlLabel}::${message}\n`)
+ process.stdout.write(`::error file=${yamlLabel}::${message}\n`)
}
}
@@ -1822,6 +1830,7 @@ function generateCategoryFile(
const missingScopes = findMissingSpecScopes(config, resolved)
if (missingScopes.length > 0) {
reportMissingSpecScopes(name, fileName, missingScopes)
+ process.exit(1)
}
try {
enabledTools.push([
diff --git a/services/mcp/tests/unit/generate-tools.test.ts b/services/mcp/tests/unit/generate-tools.test.ts
index 9ba86009cb99..a6ce0af9a3c2 100644
--- a/services/mcp/tests/unit/generate-tools.test.ts
+++ b/services/mcp/tests/unit/generate-tools.test.ts
@@ -2441,11 +2441,20 @@ describe('generateCategoryFile with a missing operation', () => {
describe('derived scopes and annotations', () => {
const readAndWrite = [{ PersonalAPIKeyAuth: ['thing:read', 'thing:write'] }]
- function specWith(method: string, security?: Array<Record<string, string[]>>): OpenApiSpec {
+ function specWith(
+ method: string,
+ security?: Array<Record<string, string[]>>,
+ requestDependentScopes?: boolean
+ ): OpenApiSpec {
return makeSpec({
paths: {
'/api/projects/{project_id}/things/': {
- [method.toLowerCase()]: { operationId: 'things_op', parameters: [], security },
+ [method.toLowerCase()]: {
+ operationId: 'things_op',
+ parameters: [],
+ security,
+ 'x-request-dependent-scopes': requestDependentScopes,
+ },
},
},
})
@@ -2494,8 +2503,8 @@ describe('derived scopes and annotations', () => {
{
name: 'prefers explicit YAML scopes over the spec',
security: readAndWrite,
- yamlScopes: ['thing:read'],
- expected: ['thing:read'],
+ yamlScopes: ['thing:write'],
+ expected: ['thing:write'],
},
])('scopes: $name', ({ security, yamlScopes, expected }) => {
const { enabledTools } = generate(specWith('GET', security), { scopes: yamlScopes })
@@ -2504,10 +2513,26 @@ describe('derived scopes and annotations', () => {
})
it.each([
- { name: 'no security block', security: undefined },
- { name: 'an empty security requirement', security: [{}] },
- ])('scopes: fails when the YAML has none and the spec has $name', ({ security }) => {
- expect(generateAndCaptureExit(specWith('GET', security), {})).toMatch(/Add "scopes" to the tool's YAML/)
+ {
+ name: 'no security block',
+ security: undefined,
+ requestDependent: false,
+ error: /Add "scopes" to the tool's YAML/,
+ },
+ {
+ name: 'an empty security requirement',
+ security: [{}],
+ requestDependent: false,
+ error: /Add "scopes" to the tool's YAML/,
+ },
+ {
+ name: 'request-dependent scopes',
+ security: readAndWrite,
+ requestDependent: true,
+ error: /picks the scopes for "things_op" per request/,
+ },
+ ])('scopes: fails when the YAML has none and the spec has $name', ({ security, requestDependent, error }) => {
+ expect(generateAndCaptureExit(specWith('GET', security, requestDependent), {})).toMatch(error)
})
it.each([
@@ -2533,51 +2558,70 @@ describe('derived scopes and annotations', () => {
expect(enabledTools[0]?.[1].annotations).toEqual(explicit)
})
- describe('scope coverage warning', () => {
- function captureStdout(): string[] {
+ describe('scope coverage check', () => {
+ function runCoverage(spec: OpenApiSpec, tool: Partial<ToolConfig>): { exited: boolean; output: string } {
const lines: string[] = []
+ vi.spyOn(console, 'error').mockImplementation((message: string) => {
+ lines.push(message)
+ })
vi.spyOn(process.stdout, 'write').mockImplementation((chunk) => {
lines.push(String(chunk))
return true
})
- return lines
+ vi.spyOn(process, 'exit').mockImplementation((() => {
+ throw new Error('exit')
+ }) as never)
+ let exited = false
+ try {
+ generate(spec, tool)
+ } catch {
+ exited = true
+ }
+ return { exited, output: lines.join('') }
}
it.each([
- { name: 'YAML misses a spec scope', yamlScopes: ['thing:read'], warns: true },
+ { name: 'YAML misses a spec scope', yamlScopes: ['thing:read'], requestDependent: false, fails: true },
{
name: 'YAML is broader than the spec',
yamlScopes: ['thing:read', 'thing:write', 'thing:admin'],
- warns: false,
+ requestDependent: false,
+ fails: false,
},
- { name: 'YAML has no scopes', yamlScopes: undefined, warns: false },
- ])('$name -> warns: $warns', ({ yamlScopes, warns }) => {
- const lines = captureStdout()
-
- generate(specWith('GET', readAndWrite), { scopes: yamlScopes })
+ { name: 'YAML has no scopes', yamlScopes: undefined, requestDependent: false, fails: false },
+ {
+ name: 'the API picks the scopes per request',
+ yamlScopes: ['task:read'],
+ requestDependent: true,
+ fails: false,
+ },
+ ])('$name -> fails: $fails', ({ yamlScopes, requestDependent, fails }) => {
+ const { exited, output } = runCoverage(specWith('GET', readAndWrite, requestDependent), {
+ scopes: yamlScopes,
+ })
- const output = lines.join('')
- expect(output.includes('thing:write')).toBe(warns)
- if (warns) {
+ expect(exited).toBe(fails)
+ expect(output.includes('thing:write')).toBe(fails)
+ if (fails) {
expect(output).toContain('Tool "thing-op"')
expect(output).toContain('products/things/mcp/tools.yaml')
}
})
it('treats a write scope as covering a spec read scope', () => {
- const lines = captureStdout()
-
- generate(specWith('GET', [{ PersonalAPIKeyAuth: ['thing:read'] }]), { scopes: ['thing:write'] })
+ const { exited, output } = runCoverage(specWith('GET', [{ PersonalAPIKeyAuth: ['thing:read'] }]), {
+ scopes: ['thing:write'],
+ })
- expect(lines.join('')).toBe('')
+ expect(exited).toBe(false)
+ expect(output).toBe('')
})
it('skips tools whose spec declares no scopes', () => {
- const lines = captureStdout()
-
- generate(specWith('GET', undefined), { scopes: ['thing:read'] })
+ const { exited, output } = runCoverage(specWith('GET', undefined), { scopes: ['thing:read'] })
- expect(lines.join('')).toBe('')
+ expect(exited).toBe(false)
+ expect(output).toBe('')
})
it.each([
@@ -2585,11 +2629,10 @@ describe('derived scopes and annotations', () => {
{ githubActions: 'false', annotated: false },
])('emits a GitHub annotation only on CI (GITHUB_ACTIONS=$githubActions)', ({ githubActions, annotated }) => {
vi.stubEnv('GITHUB_ACTIONS', githubActions)
- const lines = captureStdout()
- generate(specWith('GET', readAndWrite), { scopes: ['thing:read'] })
+ const { output } = runCoverage(specWith('GET', readAndWrite), { scopes: ['thing:read'] })
- expect(lines.join('').includes('::warning file=products/things/mcp/tools.yaml::')).toBe(annotated)
+ expect(output.includes('::error file=products/things/mcp/tools.yaml::')).toBe(annotated)
})
})
})