: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(cli): grant agent login the MCP scope set (#64411)
Chris Volzer801e9a763c52
diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex ae9d478800cc..c442c5a73798 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -258,6 +258,7 @@ jobs:openapi_types:# Generated OpenAPI types - validate they match schema- 'frontend/src/generated/**/*'+ - 'frontend/src/lib/agentScopes.generated.ts'- 'products/*/frontend/generated/**/*'- 'services/mcp/src/generated/**/*'- 'services/mcp/src/api/generated.ts'@@ -1831,7 +1832,7 @@ jobs:commit_message: 'chore: update OpenAPI generated types'repo: ${{ github.repository }}branch: ${{ github.event.pull_request.head.ref }}- file_pattern: 'frontend/src/generated/** products/*/frontend/generated/** products/*/mcp/*.yaml services/mcp/definitions/*.yaml services/mcp/src/api/generated.ts services/mcp/src/generated/** services/mcp/schema/generated-tool-definitions.json services/mcp/schema/tool-definitions-all.json services/mcp/src/tools/generated/**'+ file_pattern: 'frontend/src/generated/** frontend/src/lib/agentScopes.generated.ts products/*/frontend/generated/** products/*/mcp/*.yaml services/mcp/definitions/*.yaml services/mcp/src/api/generated.ts services/mcp/src/generated/** services/mcp/schema/generated-tool-definitions.json services/mcp/schema/tool-definitions-all.json services/mcp/src/tools/generated/**'env:GITHUB_TOKEN: ${{ steps.openapi-app-token.outputs.token }}diff --git a/cli/.sampo/changesets/agent-cli-auth-scopes.md b/cli/.sampo/changesets/agent-cli-auth-scopes.mdnew file mode 100644index 000000000000..b1323c9c2909--- /dev/null+++ b/cli/.sampo/changesets/agent-cli-auth-scopes.md@@ -0,0 +1,5 @@+---+cargo/posthog-cli: patch+---++Fix CLI login for agent workflows by adding the Agent CLI preset, using the supported agent scope set, and showing clearer messages about what the generated key can do.diff --git a/cli/src/commands.rs b/cli/src/commands.rsindex 919e80089d89..a0e0116943ba 100644--- a/cli/src/commands.rs+++ b/cli/src/commands.rs@@ -139,7 +139,11 @@ pub enum Commands {Run `posthog-cli api --agent-help` for the full agent-facing usage guide.\n\n\This command group is experimental: pass `--experimental` after `api`, or set \POSTHOG_CLI_EXPERIMENTAL_API=1.\n\- Destructive tools require --confirm. Use --dry-run before mutations.",+ Destructive tools require --confirm. Use --dry-run before mutations.\n\n\+ Limitation: `login` grants the MCP scope set minus the writes PostHog \+ withholds from long-lived API keys, so a few tools (desktop file-system \+ writes, integration deletes, reminder and user-settings writes) are not \+ available through this command.",trailing_var_arg = true)]Api {diff --git a/cli/src/login.rs b/cli/src/login.rsindex 4b7ce5c022c2..b5ca65b5046d 100644--- a/cli/src/login.rs+++ b/cli/src/login.rs@@ -35,11 +35,16 @@ struct PollResponse {project_id: Option<String>,}+// The `agent-cli` use case grants the full MCP / `posthog-cli api` scope set+// (a superset of schema + error_tracking + endpoints), so a freshly logged-in+// CLI can run the agent interface without re-authorizing.+const DEFAULT_LOGIN_USE_CASES: &[&str] = &["agent-cli"];+pub fn login(host_override: Option<String>) -> Result<()> {if !io::stdout().is_terminal() {bail!("Failed to login. If you are running on a CI, skip this step and use POSTHOG_CLI_HOST, POSTHOG_CLI_PROJECT_ID, POSTHOG_CLI_API_KEY env variables when running commands")}- login_with_use_cases(host_override, vec!["schema", "error_tracking", "endpoints"])+ login_with_use_cases(host_override, DEFAULT_LOGIN_USE_CASES.to_vec())}pub fn login_with_use_cases(host_override: Option<String>, use_cases: Vec<&str>) -> Result<()> {@@ -275,12 +280,10 @@ fn manual_login() -> Result<(), Error> {.with_validator(env_id_validator).prompt()?;- let token = Text::new(- "Enter your personal API token",- )- .with_validator(token_validator)- .with_help_message("See posthog.com/docs/api#private-endpoint-authentication. It will need to have the 'error tracking write' scope.")- .prompt()?;+ let token = Text::new("Enter your personal API token")+ .with_validator(token_validator)+ .with_help_message("See posthog.com/docs/api#private-endpoint-authentication. It will need to have the 'error tracking write' scope. To enable tooling, select the 'Agent CLI' preset.")+ .prompt()?;let token = Token {host: Some(host.trim_end_matches('/').to_string()),@@ -294,3 +297,15 @@ fn manual_login() -> Result<(), Error> {complete_login(&provider, "manual_login")}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn default_login_requests_the_agent_cli_use_case() {+ // The agent-cli use case is what grants the CLI the full `posthog-cli api`+ // scope set; narrowing it here would silently break agent commands.+ assert_eq!(DEFAULT_LOGIN_USE_CASES, &["agent-cli"]);+ }+}diff --git a/frontend/src/lib/agentScopes.generated.ts b/frontend/src/lib/agentScopes.generated.tsnew file mode 100644index 000000000000..ffc338bca5ae--- /dev/null+++ b/frontend/src/lib/agentScopes.generated.ts@@ -0,0 +1,121 @@+// AUTO-GENERATED by services/mcp/scripts/build-cli-agent-scopes.ts.+// Regenerate with `hogli build:openapi`. Do not edit.+//+// The scopes the CLI `agent-cli` login use case grants — the same set the MCP+// requests (getAdvertisedOAuthScopes, the union of every tool’s+// required_scopes), minus the OIDC identity scopes that only apply to OAuth+// access tokens rather than Personal API Keys.++export const AGENT_USE_CASE_SCOPES = [+ 'action:read',+ 'action:write',+ 'account:read',+ 'account:write',+ 'activity_log:read',+ 'agents:read',+ 'agents:write',+ 'alert:read',+ 'alert:write',+ 'annotation:read',+ 'annotation:write',+ 'approvals:read',+ 'batch_export:read',+ 'batch_export:write',+ 'business_knowledge:read',+ 'business_knowledge:write',+ 'cohort:read',+ 'cohort:write',+ 'comment:read',+ 'dashboard:read',+ 'dashboard:write',+ 'early_access_feature:read',+ 'early_access_feature:write',+ 'endpoint:read',+ 'endpoint:write',+ 'engineering_analytics:read',+ 'error_tracking:read',+ 'error_tracking:write',+ 'evaluation:read',+ 'evaluation:write',+ 'event_definition:read',+ 'event_definition:write',+ 'experiment:read',+ 'experiment:write',+ 'experiment_saved_metric:read',+ 'experiment_saved_metric:write',+ 'external_data_source:read',+ 'external_data_source:write',+ 'feature_flag:read',+ 'feature_flag:write',+ 'file_system:read',+ 'file_system:write',+ 'group:read',+ 'health_issue:read',+ 'heatmap:read',+ 'heatmap:write',+ 'hog_flow:read',+ 'hog_flow:write',+ 'hog_function:read',+ 'hog_function:write',+ 'insight:read',+ 'insight:write',+ 'insight_variable:write',+ 'integration:read',+ 'integration:write',+ 'llm_analytics:read',+ 'llm_analytics:write',+ 'llm_prompt:read',+ 'llm_prompt:write',+ 'llm_skill:read',+ 'llm_skill:write',+ 'logs:read',+ 'logs:write',+ 'marketing_analytics:read',+ 'mcp_analytics:read',+ 'mcp_analytics:write',+ 'metrics:read',+ 'notebook:read',+ 'notebook:write',+ 'organization:read',+ 'organization:write',+ 'organization_member:read',+ 'person:read',+ 'person:write',+ 'project:read',+ 'project:write',+ 'property_definition:read',+ 'query:read',+ 'replay_scanner:read',+ 'replay_scanner:write',+ 'session_recording:read',+ 'session_recording:write',+ 'session_recording_playlist:read',+ 'session_recording_playlist:write',+ 'signal_scout:read',+ 'signal_scout:write',+ 'subscription:read',+ 'subscription:write',+ 'survey:read',+ 'survey:write',+ 'tagger:read',+ 'tagger:write',+ 'ticket:read',+ 'ticket:write',+ 'task:read',+ 'task:write',+ 'tracing:read',+ 'field_note:read',+ 'field_note:write',+ 'usage_metric:read',+ 'usage_metric:write',+ 'user:read',+ 'user:write',+ 'user_interview:read',+ 'user_interview:write',+ 'visual_review:read',+ 'visual_review:write',+ 'warehouse_table:read',+ 'warehouse_view:read',+ 'warehouse_view:write',+ 'web_analytics:read',+] as constdiff --git a/frontend/src/lib/scopes.test.ts b/frontend/src/lib/scopes.test.tsindex f527899fbef4..5f3c1e87a020 100644--- a/frontend/src/lib/scopes.test.ts+++ b/frontend/src/lib/scopes.test.ts@@ -1,4 +1,14 @@-import { API_KEY_SCOPE_PRESETS, API_SCOPES } from 'lib/scopes'+import { AGENT_USE_CASE_SCOPES } from 'lib/agentScopes.generated'+import { AGENT_CLI_API_KEY_SCOPES, API_KEY_SCOPE_PRESETS, API_SCOPES } from 'lib/scopes'++const getRenderableKeyCreationScopes = (): Set<string> =>+ new Set(+ API_SCOPES.flatMap(({ key, disabledActions }) =>+ (['read', 'write'] as const)+ .filter((action) => !disabledActions?.includes(action))+ .map((action) => `${key}:${action}`)+ )+ )describe('API_KEY_SCOPE_PRESETS', () => {const findPreset = (value: string): (typeof API_KEY_SCOPE_PRESETS)[number] => {@@ -28,4 +38,34 @@ describe('API_KEY_SCOPE_PRESETS', () => {expect(preset.scopes).toEqual(['*'])})})++ describe('agent_cli', () => {+ it('exists separately from the MCP server preset', () => {+ expect(findPreset('mcp_server').label).toBe('MCP Server')++ const preset = findPreset('agent_cli')+ expect(preset.label).toBe('Agent CLI')+ expect(preset.access_type).toBe('all')+ })++ it('uses the generated Agent CLI scopes with key-disabled writes removed', () => {+ const preset = findPreset('agent_cli')+ expect(preset.scopes).toEqual(AGENT_CLI_API_KEY_SCOPES)+ expect(preset.scopes).toEqual(+ expect.arrayContaining(['user:read', 'project:read', 'query:read', 'insight:write'])+ )+ expect(preset.scopes).not.toContain('file_system:write')+ expect(preset.scopes).not.toContain('integration:write')+ expect(preset.scopes).not.toContain('user:write')+ })++ it('only includes scopes the key creation UI can render', () => {+ const renderableScopes = getRenderableKeyCreationScopes()++ expect(AGENT_CLI_API_KEY_SCOPES).toEqual(+ (AGENT_USE_CASE_SCOPES as readonly string[]).filter((scope) => renderableScopes.has(scope))+ )+ expect(AGENT_CLI_API_KEY_SCOPES.every((scope) => renderableScopes.has(scope))).toBe(true)+ })+ })})diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsxindex 207362daae22..5a9bd1a81d8e 100644--- a/frontend/src/lib/scopes.tsx+++ b/frontend/src/lib/scopes.tsx@@ -1,3 +1,5 @@+import { AGENT_USE_CASE_SCOPES } from 'lib/agentScopes.generated'+import type { APIScopeAction, APIScopeObject } from '~/types'export const MAX_API_KEYS_PER_USER = 10 // Same as in posthog/api/personal_api_key.py@@ -30,6 +32,7 @@ export const API_SCOPES: APIScope[] = [{ key: 'annotation', objectName: 'Annotation', objectPlural: 'annotations' },{ key: 'approvals', objectName: 'Approvals', objectPlural: 'approvals' },{ key: 'batch_export', objectName: 'Batch export', objectPlural: 'batch exports' },+ { key: 'business_knowledge', objectName: 'Business knowledge', objectPlural: 'business knowledge' },// `clickhouse_test_cluster_perf` is omitted — see `INTERNAL_API_SCOPE_OBJECTS` in posthog/scopes.py.{ key: 'cohort', objectName: 'Cohort', objectPlural: 'cohorts' },{ key: 'comment', objectName: 'Comment', objectPlural: 'comments' },@@ -42,6 +45,7 @@ export const API_SCOPES: APIScope[] = [{ key: 'early_access_feature', objectName: 'Early access feature', objectPlural: 'early access features' },{ key: 'element', objectName: 'Element', objectPlural: 'elements' },{ key: 'endpoint', objectName: 'Endpoint', objectPlural: 'endpoints' },+ { key: 'engineering_analytics', objectName: 'Engineering analytics', objectPlural: 'engineering analytics' },{ key: 'event_definition', objectName: 'Event definition', objectPlural: 'event definitions' },{ key: 'error_tracking', objectName: 'Error tracking', objectPlural: 'error tracking' },{ key: 'evaluation', objectName: 'Evaluation', objectPlural: 'evaluations' },@@ -129,6 +133,7 @@ export const API_SCOPES: APIScope[] = [{ key: 'sharing_configuration', objectName: 'Sharing configuration', objectPlural: 'sharing configurations' },{ key: 'subscription', objectName: 'Subscription', objectPlural: 'subscriptions' },{ key: 'survey', objectName: 'Survey', objectPlural: 'surveys' },+ { key: 'tagger', objectName: 'Tagger', objectPlural: 'taggers' },{ key: 'ticket', objectName: 'Ticket', objectPlural: 'tickets' },{ key: 'tracing', objectName: 'Tracing', objectPlural: 'tracing' },{ key: 'field_note', objectName: 'Field note', objectPlural: 'field notes' },@@ -151,6 +156,7 @@ export const API_SCOPES: APIScope[] = [},{ key: 'signal_scout', objectName: 'Signals agent', objectPlural: 'signals agents' },{ key: 'task', objectName: 'Task', objectPlural: 'tasks' },+ { key: 'user_interview', objectName: 'User interview', objectPlural: 'user interviews' },{ key: 'visual_review', objectName: 'Visual review', objectPlural: 'visual reviews' },{key: 'webhook',@@ -168,6 +174,29 @@ export const PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION = ['endpoint:read']export type ProjectSecretAPIKeyAllowedScope = (typeof PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION)[number]+const API_KEY_CREATION_ACTIONS = ['read', 'write'] as const++// Scopes the manual key-creation UI can render and submit. This excludes actions+// disabled for Personal API Keys and any generated scope whose object has no UI row.+const API_KEY_CREATION_RENDERABLE_SCOPES = new Set(+ API_SCOPES.flatMap(({ key, disabledActions }) =>+ API_KEY_CREATION_ACTIONS.filter((action) => !disabledActions?.includes(action)).map(+ (action) => `${key}:${action}`+ )+ )+)++// Actions the manual key-creation UI withholds from Personal API Keys+// (e.g. file_system:write, integration:write, user:write) — see `disabledActions`+// above.+export const API_KEY_CREATION_DISABLED_SCOPES = new Set(+ API_SCOPES.flatMap(({ key, disabledActions }) => (disabledActions ?? []).map((action) => `${key}:${action}`))+)++export const AGENT_CLI_API_KEY_SCOPES = AGENT_USE_CASE_SCOPES.filter((scope) =>+ API_KEY_CREATION_RENDERABLE_SCOPES.has(scope)+)+export const API_KEY_SCOPE_PRESETS: {value: stringlabel: string@@ -206,6 +235,12 @@ export const API_KEY_SCOPE_PRESETS: {),access_type: 'all',},+ {+ value: 'agent_cli',+ label: 'Agent CLI',+ scopes: AGENT_CLI_API_KEY_SCOPES,+ access_type: 'all',+ },{value: 'read_only_access',label: 'Read-only access',diff --git a/frontend/src/scenes/authentication/cli/CLIAuthorize.tsx b/frontend/src/scenes/authentication/cli/CLIAuthorize.tsxindex fd479e4b7a2a..c156388b5492 100644--- a/frontend/src/scenes/authentication/cli/CLIAuthorize.tsx+++ b/frontend/src/scenes/authentication/cli/CLIAuthorize.tsx@@ -1,108 +1,24 @@import { useActions, useValues } from 'kea'import { Form } from 'kea-forms'-import { Fragment, useState } from 'react'-import { IconCode, IconGear, IconWarning } from '@posthog/icons'-import { IconInfo } from '@posthog/icons'-import { LemonButton, LemonInput, LemonSegmentedButton, LemonSelect, Link, Tooltip } from '@posthog/lemon-ui'+import { IconCode } from '@posthog/icons'+import { LemonButton, LemonInput, LemonSelect, Link } from '@posthog/lemon-ui'import { BridgePage } from 'lib/components/BridgePage/BridgePage'import { IconErrorOutline } from 'lib/lemon-ui/icons'import { LemonBanner } from 'lib/lemon-ui/LemonBanner'import { LemonField } from 'lib/lemon-ui/LemonField'-import { LemonModal } from 'lib/lemon-ui/LemonModal'-import { API_SCOPES } from 'lib/scopes'-import { isKeyOf } from 'lib/utils/guards'-import { capitalizeFirstLetter } from 'lib/utils/strings'import { SceneExport } from 'scenes/sceneTypes'+import { ScopeAccessRow } from 'scenes/settings/shared/ScopeAccessRow'import { urls } from 'scenes/urls'-import { cliAuthorizeLogic } from './cliAuthorizeLogic'+import { CLI_SCOPE_PRESETS, cliAuthorizeLogic } from './cliAuthorizeLogic'export const scene: SceneExport = {component: CLIAuthorize,logic: cliAuthorizeLogic,}-function ScopesList({- scopes,- formScopeRadioValues,- displayScopeValues,- setScopeRadioValue,- showAll = false,-}: {- scopes: typeof API_SCOPES- formScopeRadioValues: Record<string, string>- displayScopeValues?: Record<string, string>- setScopeRadioValue: (key: string, action: string) => void- showAll?: boolean-}): JSX.Element {- // Use displayScopeValues for filtering if provided, otherwise use formScopeRadioValues- const filterValues = displayScopeValues ?? formScopeRadioValues- const visibleScopes = showAll- ? scopes- : scopes.filter((scope) => filterValues[scope.key] && filterValues[scope.key] !== 'none')-- if (!showAll && visibleScopes.length === 0) {- return (- <div className="text-muted text-sm italic py-2">- No scopes selected. Click "Manage scopes" to select permissions.- </div>- )- }-- return (- <div>- {visibleScopes.map(({ key, disabledActions, warnings, info }) => {- const radioValue = formScopeRadioValues[key]- return (- <Fragment key={key}>- <div className="flex items-center justify-between gap-2 min-h-8">- <div className="flex items-center gap-1">- <b>{capitalizeFirstLetter(key.replace(/_/g, ' '))}</b>-- {info ? (- <Tooltip title={info}>- <IconInfo className="text-secondary text-base" />- </Tooltip>- ) : null}- </div>- <LemonSegmentedButton- onChange={(value) => setScopeRadioValue(key, value)}- value={radioValue ?? 'none'}- options={[- { label: 'No access', value: 'none' },- {- label: 'Read',- value: 'read',- disabledReason: disabledActions?.includes('read')- ? 'Does not apply to this resource'- : undefined,- },- {- label: 'Write',- value: 'write',- disabledReason: disabledActions?.includes('write')- ? 'Does not apply to this resource'- : undefined,- },- ]}- size="xsmall"- />- </div>- {warnings && isKeyOf(radioValue, warnings) && (- <div className="flex items-start gap-2 text-xs italic pb-2">- <IconWarning className="text-base text-secondary mt-0.5" />- <span>{warnings[radioValue]}</span>- </div>- )}- </Fragment>- )- })}- </div>- )-}-export function CLIAuthorize(): JSX.Element {const {authorize,@@ -112,39 +28,20 @@ export function CLIAuthorize(): JSX.Element {projectsLoading,isAuthorizeSubmitting,formScopeRadioValues,- displayedScopeValues,+ filteredScopes,+ searchTerm,+ scopePreset,+ allAccessSelected,missingSchemaScopes,missingErrorTrackingScopes,missingEndpointsScopes,+ missingAgentScopes,} = useValues(cliAuthorizeLogic)- const { setAuthorizeValue, setScopeRadioValue, updateDisplayedScopeSnapshot } = useActions(cliAuthorizeLogic)- const [isScopesModalOpen, setIsScopesModalOpen] = useState(false)-- const handleOpenModal = (): void => {- setIsScopesModalOpen(true)- }-- const handleCloseModal = (): void => {- updateDisplayedScopeSnapshot()- setIsScopesModalOpen(false)- }+ const { setAuthorizeValue, setScopeRadioValue, setSearchTerm, setScopePreset, resetScopes } =+ useActions(cliAuthorizeLogic)return (- <BridgePage- view="login"- {...(!isSuccess- ? {- hedgehog: true as const,- message: (- <>- Authorize- <br />- PostHog CLI- </>- ),- }- : { hedgehog: false as const })}- >+ <BridgePage view="login" hedgehog={false}>{isSuccess ? (<div className="text-center space-y-4"><h2>CLI Authorization Complete</h2>@@ -213,22 +110,26 @@ export function CLIAuthorize(): JSX.Element {/></LemonField>- <div className="mt-4 mb-2">- <div className="flex items-center justify-between mb-2">- <h3>Scopes</h3>- <LemonButton- type="secondary"- size="small"- icon={<IconGear />}- onClick={handleOpenModal}- >- Manage scopes- </LemonButton>- </div>- <p className="text-muted text-sm mb-2">- Selected permissions for the CLI. Only grant the scopes you need.- </p>+ <div className="flex items-center justify-between mt-4 mb-2">+ <h3 className="mb-0">Scopes</h3>+ <LemonSelect+ data-attr="cli-scope-preset"+ size="small"+ placeholder="Custom selection"+ value={scopePreset}+ onChange={(value) => setScopePreset(value)}+ options={CLI_SCOPE_PRESETS.map((preset) => ({+ label: preset.label,+ value: preset.value,+ }))}+ dropdownMatchSelectWidth={false}+ dropdownPlacement="bottom-end"+ /></div>+ <p className="text-muted text-sm mb-2">+ Permissions granted to the CLI. Pick a preset or fine-tune individual scopes — only grant+ what you need.+ </p><LemonField name="scopes">{({ error }) => (@@ -239,39 +140,73 @@ export function CLIAuthorize(): JSX.Element {</div>)}- <ScopesList- scopes={API_SCOPES}- formScopeRadioValues={formScopeRadioValues}- displayScopeValues={displayedScopeValues}- setScopeRadioValue={setScopeRadioValue}- showAll={false}- />+ {allAccessSelected ? (+ <LemonBanner+ type="warning"+ action={{ children: 'Reset', onClick: () => resetScopes() }}+ >+ <b>This key will have full access to all supported endpoints.</b> We+ recommend scoping it to only what the CLI needs.+ </LemonBanner>+ ) : (+ <>+ <LemonInput+ type="search"+ placeholder="Search scopes..."+ value={searchTerm}+ onChange={setSearchTerm}+ className="mb-2"+ size="small"+ />+ <div className="max-h-64 overflow-y-auto pr-1">+ {filteredScopes.length === 0 ? (+ <div className="text-muted text-sm py-2">+ No scopes match "{searchTerm}"+ </div>+ ) : (+ filteredScopes.map(+ ({ key, objectName, disabledActions, warnings, info }) => {+ const selected = formScopeRadioValues[key]+ const warningAction =+ selected === 'read' || selected === 'write'+ ? selected+ : null+ return (+ <ScopeAccessRow+ key={key}+ label={objectName}+ info={info}+ value={selected ?? 'none'}+ onChange={(value) => setScopeRadioValue(key, value)}+ readDisabledReason={+ disabledActions?.includes('read')+ ? 'Does not apply to this resource'+ : undefined+ }+ writeDisabledReason={+ disabledActions?.includes('write')+ ? 'Does not apply to this resource'+ : undefined+ }+ warning={+ warningAction ? warnings?.[warningAction] : null+ }+ />+ )+ }+ )+ )}+ </div>+ </>+ )}</>)}</LemonField>- <LemonModal- title="Manage CLI Scopes"- description="Select which permissions to grant to the CLI. Only select the scopes you need."- isOpen={isScopesModalOpen}- onClose={handleCloseModal}- footer={- <LemonButton type="primary" onClick={handleCloseModal}>- Done- </LemonButton>- }- >- <div className="max-h-96 overflow-y-auto">- <ScopesList- scopes={API_SCOPES}- formScopeRadioValues={formScopeRadioValues}- setScopeRadioValue={setScopeRadioValue}- showAll={true}- />- </div>- </LemonModal>-- {(missingSchemaScopes || missingErrorTrackingScopes || missingEndpointsScopes) && (+ {(missingSchemaScopes ||+ missingErrorTrackingScopes ||+ missingEndpointsScopes ||+ missingAgentScopes) && (<div className="space-y-2 mt-2">{missingSchemaScopes && (<LemonBanner type="warning">@@ -292,6 +227,13 @@ export function CLIAuthorize(): JSX.Element {(read or write) to execute endpoints.</LemonBanner>)}+ {missingAgentScopes && (+ <LemonBanner type="warning">+ <b>Agent commands limited:</b> The CLI's <code>api</code> commands need{' '}+ <code>user</code>, <code>project</code>, and <code>query</code> permissions+ (read or write) to discover data and run queries.+ </LemonBanner>+ )}</div>)}diff --git a/frontend/src/scenes/authentication/cli/cliAuthorizeLogic.test.ts b/frontend/src/scenes/authentication/cli/cliAuthorizeLogic.test.tsnew file mode 100644index 000000000000..30b3c78d2c4b--- /dev/null+++ b/frontend/src/scenes/authentication/cli/cliAuthorizeLogic.test.ts@@ -0,0 +1,124 @@+import { router } from 'kea-router'+import { expectLogic } from 'kea-test-utils'++import { AGENT_USE_CASE_SCOPES } from 'lib/agentScopes.generated'+import { API_SCOPES } from 'lib/scopes'++import { initKeaTests } from '~/test/init'++import { CLI_SCOPE_PRESETS, cliAuthorizeLogic } from './cliAuthorizeLogic'++const getRenderableKeyCreationScopes = (): Set<string> =>+ new Set(+ API_SCOPES.flatMap(({ key, disabledActions }) =>+ (['read', 'write'] as const)+ .filter((action) => !disabledActions?.includes(action))+ .map((action) => `${key}:${action}`)+ )+ )++describe('cliAuthorizeLogic', () => {+ let logic: ReturnType<typeof cliAuthorizeLogic.build>++ beforeEach(() => {+ initKeaTests()+ logic = cliAuthorizeLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ })++ it('grants the MCP scope set for the agent-cli use case, minus key-disabled writes', async () => {+ router.actions.push('/cli/authorize', {+ code: 'ABCD-1234',+ use_cases: 'agent-cli',+ })++ await expectLogic(logic).toMatchValues({+ requestedUseCases: ['agent-cli'],+ })+ const scopes = logic.values.authorize.scopes+ // Covers the agent surface (reads + the writes that are allowed on a key)+ expect(scopes).toEqual(expect.arrayContaining(['user:read', 'project:read', 'query:read', 'insight:write']))+ // But drops writes the product withholds from manually-created keys+ expect(scopes).not.toContain('file_system:write')+ expect(scopes).not.toContain('integration:write')+ expect(scopes).not.toContain('user:write')+ // Faithful subset of the generated MCP mirror+ expect(scopes.every((scope) => (AGENT_USE_CASE_SCOPES as readonly string[]).includes(scope))).toBe(true)+ // No hidden grants: every submitted Agent CLI scope must have a visible UI row+ const renderableScopes = getRenderableKeyCreationScopes()+ expect(scopes.every((scope) => renderableScopes.has(scope))).toBe(true)+ })++ it('filters out unknown use cases from the URL', async () => {+ router.actions.push('/cli/authorize', {+ code: 'ABCD-1234',+ use_cases: 'agent-cli,bogus,schema',+ })++ await expectLogic(logic).toMatchValues({+ requestedUseCases: ['agent-cli', 'schema'],+ })+ })++ it('normalizes the legacy agent use case from older CLI links', async () => {+ router.actions.push('/cli/authorize', {+ code: 'ABCD-1234',+ use_cases: 'agent,schema',+ })++ await expectLogic(logic).toMatchValues({+ requestedUseCases: ['agent-cli', 'schema'],+ })+ })++ it('defaults to the agent-cli use case when none are specified', async () => {+ router.actions.push('/cli/authorize', { code: 'ABCD-1234' })++ await expectLogic(logic).toMatchValues({+ requestedUseCases: ['agent-cli'],+ })+ expect(logic.values.authorize.scopes).toEqual(+ expect.arrayContaining(['user:read', 'project:read', 'query:read'])+ )+ expect(logic.values.authorize.scopes).not.toContain('file_system:write')+ })++ it('reflects the matching preset for the current scope selection', async () => {+ router.actions.push('/cli/authorize', { code: 'ABCD-1234' })++ // Default agent scopes map onto the agent-cli preset+ await expectLogic(logic).toMatchValues({ scopePreset: 'agent-cli' })+ expect(CLI_SCOPE_PRESETS.find((preset) => preset.value === 'agent-cli')?.label).toBe('Agent CLI')++ // Selecting a preset replaces the scope set and updates the dropdown+ logic.actions.setScopePreset('error_tracking')+ await expectLogic(logic).toMatchValues({+ scopePreset: 'error_tracking',+ })+ expect(logic.values.authorize.scopes).toEqual(['error_tracking:write'])++ expect(CLI_SCOPE_PRESETS.find((preset) => preset.value === 'all_access')).toBeUndefined()+ expect(CLI_SCOPE_PRESETS.find((preset) => preset.scopes.includes('*'))).toBeUndefined()+ })++ it('drops to a custom selection once a scope is fine-tuned', async () => {+ router.actions.push('/cli/authorize', { code: 'ABCD-1234' })+ await expectLogic(logic).toMatchValues({ scopePreset: 'agent-cli' })++ logic.actions.setScopeRadioValue('survey', 'none')+ await expectLogic(logic).toMatchValues({ scopePreset: null })+ })++ it('filters scopes by search term', async () => {+ router.actions.push('/cli/authorize', { code: 'ABCD-1234' })++ logic.actions.setSearchTerm('feature flag')+ await expectLogic(logic).toMatchValues({ searchTerm: 'feature flag' })+ expect(logic.values.filteredScopes.map((scope) => scope.key)).toContain('feature_flag')+ expect(logic.values.filteredScopes.every((scope) => scope.key === 'feature_flag')).toBe(true)+ })+})diff --git a/frontend/src/scenes/authentication/cli/cliAuthorizeLogic.ts b/frontend/src/scenes/authentication/cli/cliAuthorizeLogic.tsindex 7184cfb0e498..643328604e81 100644--- a/frontend/src/scenes/authentication/cli/cliAuthorizeLogic.ts+++ b/frontend/src/scenes/authentication/cli/cliAuthorizeLogic.ts@@ -4,14 +4,14 @@ import { loaders } from 'kea-loaders'import { urlToAction } from 'kea-router'import api from 'lib/api'-import { scopesArrayToObject } from 'lib/scopes'+import { AGENT_CLI_API_KEY_SCOPES, API_SCOPES, APIScope, scopesArrayToObject } from 'lib/scopes'import { userLogic } from 'scenes/userLogic'import { OrganizationBasicType } from '~/types'import type { cliAuthorizeLogicType } from './cliAuthorizeLogicType'-export type CLIUseCase = 'schema' | 'error_tracking' | 'endpoints'+export type CLIUseCase = 'schema' | 'error_tracking' | 'endpoints' | 'agent-cli'export interface CLIAuthorizeForm {userCode: string@@ -20,15 +20,25 @@ export interface CLIAuthorizeForm {scopes: string[]}-// Map use cases to their required scopes+// The agent set mirrors what the MCP requests, minus the actions disabled for+// manually-created keys. KNOWN LIMITATION: the few MCP tools needing those+// writes (desktop file-system writes, integration deletes, reminder + user-settings+// writes) therefore don't work through `posthog-cli api`.+const AGENT_SCOPES = AGENT_CLI_API_KEY_SCOPES++// Map use cases to their required scopes. The `agent-cli` set is generated from the+// MCP tool definitions (see agentScopes.generated.ts) so it stays in sync with+// what `posthog-cli api` / the MCP actually requires.const USE_CASE_SCOPES: Record<CLIUseCase, string[]> = {schema: ['event_definition:read', 'property_definition:read'],error_tracking: ['error_tracking:write'],endpoints: ['endpoint:write', 'insight_variable:write'],+ 'agent-cli': AGENT_SCOPES,}-// Default use cases when none are specified-const DEFAULT_USE_CASES: CLIUseCase[] = ['schema', 'error_tracking']+// Default use cases when none are specified. The CLI's agent interface drives+// this page, so a bare visit grants the full agent scope set.+const DEFAULT_USE_CASES: CLIUseCase[] = ['agent-cli']function getDefaultScopesForUseCases(useCases: CLIUseCase[]): string[] {const scopesSet = new Set<string>()@@ -42,6 +52,46 @@ function getDefaultScopesForUseCases(useCases: CLIUseCase[]): string[] {// Pre-compute default scopesconst DEFAULT_SCOPES = getDefaultScopesForUseCases(DEFAULT_USE_CASES)+// `read` for every scope that supports it (write-disabled scopes like file_system+// still allow read; only skip scopes whose read action is disabled).+const READ_ONLY_SCOPES = API_SCOPES.filter(({ disabledActions }) => !disabledActions?.includes('read')).map(+ ({ key }) => `${key}:read`+)++// Presets offered in the consent screen dropdown. Values match the URL `use_cases`+// so a requested use case maps onto the matching preset.+export const CLI_SCOPE_PRESETS: { value: string; label: string; scopes: string[] }[] = [+ { value: 'agent-cli', label: 'Agent CLI', scopes: USE_CASE_SCOPES['agent-cli'] },+ { value: 'schema', label: 'Schema management', scopes: USE_CASE_SCOPES.schema },+ { value: 'error_tracking', label: 'Error tracking', scopes: USE_CASE_SCOPES.error_tracking },+ { value: 'endpoints', label: 'Endpoint execution', scopes: USE_CASE_SCOPES.endpoints },+ { value: 'read_only', label: 'Read-only access', scopes: READ_ONLY_SCOPES },+]++function sameScopeSet(a: string[], b: string[]): boolean {+ if (a.length !== b.length) {+ return false+ }+ const setB = new Set(b)+ return a.every((scope) => setB.has(scope))+}++// The dropdown shows the preset whose scope set exactly matches the current+// selection, or null ("Custom selection") once the user fine-tunes a row.+function presetForScopes(scopes: string[]): string | null {+ return CLI_SCOPE_PRESETS.find((preset) => sameScopeSet(preset.scopes, scopes))?.value ?? null+}++function parseCLIUseCase(useCase: string): CLIUseCase | null {+ if (useCase === 'agent') {+ return 'agent-cli'+ }+ if (useCase === 'schema' || useCase === 'error_tracking' || useCase === 'endpoints' || useCase === 'agent-cli') {+ return useCase+ }+ return null+}+export const cliAuthorizeLogic = kea<cliAuthorizeLogicType>([path(['scenes', 'authentication', 'cli', 'cliAuthorizeLogic']),connect(() => ({@@ -52,8 +102,9 @@ export const cliAuthorizeLogic = kea<cliAuthorizeLogicType>([setSuccess: (success: boolean) => ({ success }),setScopeRadioValue: (key: string, action: string) => ({ key, action }),setRequestedUseCases: (useCases: CLIUseCase[]) => ({ useCases }),- updateDisplayedScopeSnapshot: true,- setDisplayedScopeValues: (values: Record<string, string>) => ({ values }),+ setSearchTerm: (searchTerm: string) => ({ searchTerm }),+ setScopePreset: (preset: string | null) => ({ preset }),+ resetScopes: true,}),reducers({isSuccess: [@@ -68,10 +119,10 @@ export const cliAuthorizeLogic = kea<cliAuthorizeLogicType>([setRequestedUseCases: (_, { useCases }) => useCases,},],- displayedScopeValues: [- {} as Record<string, string>,+ searchTerm: [+ '',{- setDisplayedScopeValues: (_, { values }) => values,+ setSearchTerm: (_, { searchTerm }) => searchTerm,},],}),@@ -140,6 +191,21 @@ export const cliAuthorizeLogic = kea<cliAuthorizeLogicType>([return scopesArrayToObject(authorize.scopes)},],+ filteredScopes: [+ (s) => [s.searchTerm],+ (searchTerm): APIScope[] => {+ const search = searchTerm.trim().toLowerCase()+ if (!search) {+ return API_SCOPES+ }+ return API_SCOPES.filter(+ (scope) =>+ scope.key.toLowerCase().includes(search) || scope.objectPlural.toLowerCase().includes(search)+ )+ },+ ],+ allAccessSelected: [(s) => [s.authorize], (authorize): boolean => !!authorize?.scopes?.includes('*')],+ scopePreset: [(s) => [s.authorize], (authorize): string | null => presetForScopes(authorize?.scopes ?? [])],missingSchemaScopes: [(s) => [s.authorize, s.requestedUseCases],(authorize, requestedUseCases): boolean => {@@ -194,6 +260,25 @@ export const cliAuthorizeLogic = kea<cliAuthorizeLogicType>([return !authorize.scopes.includes('endpoint:read') && !authorize.scopes.includes('endpoint:write')},],+ missingAgentScopes: [+ (s) => [s.authorize, s.requestedUseCases],+ (authorize, requestedUseCases): boolean => {+ // Only show warning if the agent-cli use case was requested+ if (!requestedUseCases.includes('agent-cli')) {+ return false+ }+ if (!authorize || !authorize.scopes) {+ return false+ }+ // The agent CLI can't even bootstrap (--agent-help, project context,+ // data discovery) without these. Write includes read, so either suffices.+ const hasUser = authorize.scopes.includes('user:read') || authorize.scopes.includes('user:write')+ const hasProject =+ authorize.scopes.includes('project:read') || authorize.scopes.includes('project:write')+ const hasQuery = authorize.scopes.includes('query:read') || authorize.scopes.includes('query:write')+ return !hasUser || !hasProject || !hasQuery+ },+ ],})),listeners(({ actions, values }) => ({loadProjectsSuccess: () => {@@ -214,18 +299,13 @@ export const cliAuthorizeLogic = kea<cliAuthorizeLogicType>([}actions.loadProjects(payload.value)}-- // Initialize displayed scope values when scopes are first set- if (payload.name === 'scopes' && Object.keys(values.displayedScopeValues).length === 0) {- // Directly compute scope values from the scopes array being set- const scopesArray = payload.value as string[]- const scopeValues = scopesArrayToObject(scopesArray)- actions.setDisplayedScopeValues(scopeValues)- }},- updateDisplayedScopeSnapshot: () => {- // Update displayed scope values with current form values- actions.setDisplayedScopeValues(values.formScopeRadioValues)+ setScopePreset: ({ preset }) => {+ const found = CLI_SCOPE_PRESETS.find((p) => p.value === preset)+ actions.setAuthorizeValue('scopes', found ? [...found.scopes] : [])+ },+ resetScopes: () => {+ actions.setAuthorizeValue('scopes', [])},submitAuthorizeSuccess: () => {actions.setSuccess(true)@@ -245,11 +325,7 @@ export const cliAuthorizeLogic = kea<cliAuthorizeLogicType>([},setRequestedUseCases: ({ useCases }) => {// Update scopes when requested use cases change- const newScopes = getDefaultScopesForUseCases(useCases)- actions.setAuthorizeValue('scopes', newScopes)- // Directly compute and update displayed scope values- const scopeValues = scopesArrayToObject(newScopes)- actions.setDisplayedScopeValues(scopeValues)+ actions.setAuthorizeValue('scopes', getDefaultScopesForUseCases(useCases))},setScopeRadioValue: ({ key, action }) => {if (!values.authorize || !values.authorize.scopes) {@@ -276,8 +352,9 @@ export const cliAuthorizeLogic = kea<cliAuthorizeLogicType>([// Parse use_cases from URL (comma-separated)const useCasesParam = searchParams.use_casesif (useCasesParam) {- const useCases = useCasesParam.split(',').filter((uc: string): uc is CLIUseCase => {- return uc === 'schema' || uc === 'error_tracking' || uc === 'endpoints'+ const useCases = useCasesParam.split(',').flatMap((uc: string) => {+ const parsedUseCase = parseCLIUseCase(uc)+ return parsedUseCase ? [parsedUseCase] : []})if (useCases.length > 0) {actions.setRequestedUseCases(useCases)diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 26c84dcccf44..32380962e2ba 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -5516,6 +5516,7 @@ export type APIScopeObject =| 'annotation'| 'approvals'| 'batch_export'+ | 'business_knowledge'| 'clickhouse_test_cluster_perf'| 'cohort'| 'comment'@@ -5529,6 +5530,7 @@ export type APIScopeObject =| 'early_access_feature'| 'element'| 'endpoint'+ | 'engineering_analytics'| 'error_tracking'| 'evaluation'| 'event_definition'@@ -5578,11 +5580,13 @@ export type APIScopeObject =| 'signal_scout'| 'subscription'| 'survey'+ | 'tagger'| 'task'| 'ticket'| 'uploaded_media'| 'usage_metric'| 'user'+ | 'user_interview'| 'visual_review'| 'warehouse_objects'| 'warehouse_table'diff --git a/hogli.yaml b/hogli.yamlindex 6c0edf7f6727..f4cedc7142dc 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -518,6 +518,10 @@ build:bin_script: build-mcp-oauth-scopes.pydescription: Generate OAUTH_SCOPES_SUPPORTED for the MCP protected-resourcemetadata from posthog/scopes.py+ build:openapi-cli-agent-scopes:+ cmd: pnpm --filter=@posthog/mcp run generate-cli-agent-scopes+ description: Generate the CLI `agent` login use-case scope list from the MCP+ tool definitions (must run after build:openapi-mcp-tools)build:openapi:steps:- build:openapi-schema@@ -527,6 +531,7 @@ build:- build:openapi-mcp- build:openapi-mcp-tools- build:openapi-mcp-scopes+ - build:openapi-cli-agent-scopesdescription: Generate OpenAPI schema and TypeScript types from the backendbuild:grammar:cmd: pnpm grammar:builddiff --git a/posthog/api/cli_auth.py b/posthog/api/cli_auth.pyindex af9558f60228..f1c0a309d4ee 100644--- a/posthog/api/cli_auth.py+++ b/posthog/api/cli_auth.py@@ -22,9 +22,11 @@ from rest_framework.decorators import actionfrom rest_framework.permissions import AllowAny, IsAuthenticatedfrom rest_framework.response import Response+from posthog.api.personal_api_key import validate_personal_api_key_scopesfrom posthog.auth import SessionAuthenticationfrom posthog.models import PersonalAPIKey, Team, Userfrom posthog.models.utils import generate_random_token_personal, hash_key_value, mask_key_value+from posthog.scopes import UNPRIVILEGED_SCOPES# Device code lives for 10 minutesDEVICE_CODE_EXPIRY_SECONDS = 600@@ -62,6 +64,13 @@ def get_user_code_cache_key(user_code: str) -> str:return f"cli_user_code:{user_code}"+def get_validation_error_description(error: serializers.ValidationError) -> str:+ detail = error.detail+ if isinstance(detail, list) and detail:+ return str(detail[0])+ return str(detail)++class DeviceCodeResponseSerializer(serializers.Serializer):"""Response containing device and user codes"""@@ -182,6 +191,7 @@ class CLIAuthViewSet(viewsets.ViewSet):user_code = serializer.validated_data["user_code"]project_id = serializer.validated_data["project_id"]scopes = serializer.validated_data.get("scopes", CLI_SCOPES)+ user: User = request.user# Validate that at least one scope is providedif not scopes:@@ -190,6 +200,14 @@ class CLIAuthViewSet(viewsets.ViewSet):status=status.HTTP_400_BAD_REQUEST,)+ try:+ validate_personal_api_key_scopes(scopes, user, allowed_scopes=UNPRIVILEGED_SCOPES)+ except serializers.ValidationError as error:+ return Response(+ {"error": "invalid_scope", "error_description": get_validation_error_description(error)},+ status=status.HTTP_400_BAD_REQUEST,+ )+# Look up device code from user codeuser_code_cache_key = get_user_code_cache_key(user_code)device_code = cache.get(user_code_cache_key)@@ -215,8 +233,6 @@ class CLIAuthViewSet(viewsets.ViewSet):)# Verify user has access to the project- user: User = request.user-try:team = Team.objects.get(id=project_id)# Check if user has access to this team's organization@@ -250,6 +266,8 @@ class CLIAuthViewSet(viewsets.ViewSet):secure_value=secure_value,mask_value=mask_value,scopes=scopes,+ scoped_teams=[team.id],+ scoped_organizations=[],)# User explicitly authorized this CLI via SessionAuthentication (seediff --git a/posthog/api/personal_api_key.py b/posthog/api/personal_api_key.pyindex ee2dfbdeeec0..f66336645b96 100644--- a/posthog/api/personal_api_key.py+++ b/posthog/api/personal_api_key.py@@ -21,6 +21,53 @@ from posthog.user_permissions import UserPermissionsMAX_API_KEYS_PER_USER = 10 # Same as in scopes.tsx+def validate_personal_api_key_scopes(+ scopes: list[str],+ requesting_user: User,+ *,+ existing_scopes: list[str] | None = None,+ allowed_scopes: frozenset[str] | None = None,+) -> None:+ for scope in scopes:+ if scope == "*":+ if allowed_scopes is None:+ continue+ raise serializers.ValidationError(f"Invalid scope: {scope}")++ scope_parts = scope.split(":")+ if (+ len(scope_parts) != 2+ or scope_parts[0] not in API_SCOPE_OBJECTS+ or scope_parts[0] in INTERNAL_API_SCOPE_OBJECTS+ or scope_parts[1] not in API_SCOPE_ACTIONS+ ):+ raise serializers.ValidationError(f"Invalid scope: {scope}")++ if allowed_scopes is not None and scope not in allowed_scopes:+ raise serializers.ValidationError(f"Invalid scope: {scope}")++ # Check feature flag for llm_gateway scope - block if newly adding this scope+ if scope_parts[0] == "llm_gateway":+ existing_has_llm_gateway = existing_scopes is not None and any(+ s.startswith("llm_gateway:") for s in existing_scopes+ )+ if not existing_has_llm_gateway:+ organization_id = requesting_user.current_organization_id+ if organization_id is None:+ raise serializers.ValidationError("Unable to verify feature access.")+ if not posthoganalytics.feature_enabled(+ "gateway-personal-api-key",+ str(requesting_user.distinct_id),+ groups={"organization": str(organization_id)},+ group_properties={"organization": {"id": str(organization_id)}},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ ):+ raise serializers.ValidationError(+ "LLM gateway scope is not available. Contact support to enable this feature."+ )++class PersonalAPIKeySerializer(serializers.ModelSerializer):# Specifying method name because the serializer class already has a get_value methodvalue = serializers.SerializerMethodField(method_name="get_key_value", read_only=True)@@ -67,40 +114,8 @@ class PersonalAPIKeySerializer(serializers.ModelSerializer):def validate_scopes(self, scopes):requesting_user = self.context["request"].user-- for scope in scopes:- if scope == "*":- continue-- scope_parts = scope.split(":")- if (- len(scope_parts) != 2- or scope_parts[0] not in API_SCOPE_OBJECTS- or scope_parts[0] in INTERNAL_API_SCOPE_OBJECTS- or scope_parts[1] not in API_SCOPE_ACTIONS- ):- raise serializers.ValidationError(f"Invalid scope: {scope}")-- # Check feature flag for llm_gateway scope - block if newly adding this scope- if scope_parts[0] == "llm_gateway":- existing_has_llm_gateway = self.instance is not None and any(- s.startswith("llm_gateway:") for s in self.instance.scopes- )- if not existing_has_llm_gateway:- organization_id = requesting_user.current_organization_id- if organization_id is None:- raise serializers.ValidationError("Unable to verify feature access.")- if not posthoganalytics.feature_enabled(- "gateway-personal-api-key",- str(requesting_user.distinct_id),- groups={"organization": str(organization_id)},- group_properties={"organization": {"id": str(organization_id)}},- only_evaluate_locally=False,- send_feature_flag_events=False,- ):- raise serializers.ValidationError(- "LLM gateway scope is not available. Contact support to enable this feature."- )+ existing_scopes = list(self.instance.scopes or []) if self.instance is not None else None+ validate_personal_api_key_scopes(scopes, requesting_user, existing_scopes=existing_scopes)return scopesdiff --git a/posthog/api/test/test_cli_auth.py b/posthog/api/test/test_cli_auth.pyindex e72f7b845f00..41cd5fcadb4b 100644--- a/posthog/api/test/test_cli_auth.py+++ b/posthog/api/test/test_cli_auth.py@@ -2,10 +2,12 @@ from datetime import timedeltafrom freezegun import freeze_timefrom posthog.test.base import APIBaseTest+from unittest.mock import patchfrom django.core.cache import cachefrom django.utils import timezone+from parameterized import parameterizedfrom rest_framework import statusfrom posthog.api.cli_auth import CLI_SCOPES, DEVICE_CODE_EXPIRY_SECONDS, get_device_cache_key, get_user_code_cache_key@@ -115,8 +117,64 @@ class TestCLIAuthAuthorizeEndpoint(APIBaseTest):api_key = PersonalAPIKey.objects.filter(user=self.user).order_by("-created_at").first()assert api_key is not Noneself.assertEqual(api_key.scopes, CLI_SCOPES)+ self.assertEqual(api_key.scoped_teams, [self.team.id])+ self.assertEqual(api_key.scoped_organizations, [])self.assertIn("CLI -", api_key.label)+ def test_authorization_honors_submitted_scopes(self):+ # The browser consent screen derives scopes from the requested use cases+ # (e.g. the `agent` use case grants the MCP scope set) and submits them.+ # The endpoint must mint a key with exactly those scopes, not CLI_SCOPES.+ submitted_scopes = ["user:read", "project:read", "query:read", "insight:write"]++ response = self.client.post(+ "/api/cli-auth/authorize/",+ {"user_code": self.user_code, "project_id": self.team.id, "scopes": submitted_scopes},+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ api_key = PersonalAPIKey.objects.filter(user=self.user).order_by("-created_at").first()+ assert api_key is not None+ self.assertEqual(api_key.scopes, submitted_scopes)+ self.assertEqual(api_key.scoped_teams, [self.team.id])++ @parameterized.expand(+ [+ ("wildcard", "*"),+ ("malformed", "query"),+ ("unknown_object", "not_a_scope:read"),+ ("unknown_action", "query:admin"),+ ("internal_object", "signal_scout_internal:write"),+ ]+ )+ def test_authorization_rejects_invalid_or_disallowed_scopes(self, _name: str, scope: str):+ response = self.client.post(+ "/api/cli-auth/authorize/",+ {"user_code": self.user_code, "project_id": self.team.id, "scopes": [scope]},+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["error"], "invalid_scope")+ self.assertIn(scope, response.json()["error_description"])+ self.assertEqual(PersonalAPIKey.objects.filter(user=self.user).count(), 0)++ device_cache_key = get_device_cache_key(self.device_code)+ device_data = cache.get(device_cache_key)+ self.assertEqual(device_data["status"], "pending")++ @patch("posthog.api.personal_api_key.posthoganalytics.feature_enabled", return_value=True)+ def test_authorization_rejects_llm_gateway_scope(self, feature_enabled):+ response = self.client.post(+ "/api/cli-auth/authorize/",+ {"user_code": self.user_code, "project_id": self.team.id, "scopes": ["llm_gateway:read"]},+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["error"], "invalid_scope")+ self.assertIn("llm_gateway:read", response.json()["error_description"])+ feature_enabled.assert_not_called()+ self.assertEqual(PersonalAPIKey.objects.filter(user=self.user).count(), 0)+def test_authorization_requires_authentication(self):"""Test that authorization endpoint requires user to be logged in"""self.client.logout()@@ -439,6 +497,36 @@ class TestCLIAuthEndToEnd(APIBaseTest):self.assertIn("property_definition:read", api_key.scopes)self.assertIn("error_tracking:write", api_key.scopes)+ def test_api_key_is_scoped_to_authorized_project(self):+ other_team = Team.objects.create(organization=self.organization, name="Other Team")++ response = self.client.post("/api/cli-auth/device-code/")+ device_code = response.json()["device_code"]+ user_code = response.json()["user_code"]++ self.client.post(+ "/api/cli-auth/authorize/",+ {"user_code": user_code, "project_id": self.team.id},+ )++ response = self.client.post("/api/cli-auth/poll/", {"device_code": device_code})+ api_key_value = response.json()["personal_api_key"]++ api_key = PersonalAPIKey.objects.get(secure_value=hash_key_value(api_key_value))+ self.assertEqual(api_key.scoped_teams, [self.team.id])+ self.assertEqual(api_key.scoped_organizations, [])++ self.client.logout()+ authorized_response = self.client.get(+ f"/api/projects/{self.team.pk}/event_definitions/", headers={"authorization": f"Bearer {api_key_value}"}+ )+ self.assertEqual(authorized_response.status_code, status.HTTP_200_OK)++ other_project_response = self.client.get(+ f"/api/projects/{other_team.pk}/event_definitions/", headers={"authorization": f"Bearer {api_key_value}"}+ )+ self.assertEqual(other_project_response.status_code, status.HTTP_403_FORBIDDEN)+def test_cross_team_access_is_prevented(self):"""Test that user cannot authorize CLI for a team in a different organization"""# Create a new organization that the user is NOT a member ofdiff --git a/services/mcp/package.json b/services/mcp/package.jsonindex be64355a8f8d..187471441984 100644--- a/services/mcp/package.json+++ b/services/mcp/package.json@@ -36,6 +36,7 @@"generate-mcp-types": "node scripts/generate-mcp-types.mjs","generate-orval-schemas": "node scripts/generate-orval-schemas.mjs","generate-tools": "tsx scripts/generate-tools.ts",+ "generate-cli-agent-scopes": "tsx scripts/build-cli-agent-scopes.ts","scaffold-yaml": "tsx scripts/scaffold-yaml.ts","lint-tool-names": "tsx scripts/lint-tool-names.ts","format": "oxlint --fix --fix-suggestions --fix-dangerously --quiet && oxfmt \"./**/*.{js,mjs,ts,tsx,json,yaml,yml,css,scss}\""diff --git a/services/mcp/scripts/build-cli-agent-scopes.ts b/services/mcp/scripts/build-cli-agent-scopes.tsnew file mode 100644index 000000000000..17732b903f24--- /dev/null+++ b/services/mcp/scripts/build-cli-agent-scopes.ts@@ -0,0 +1,72 @@+#!/usr/bin/env tsx+/**+ * Generates the scope list for the CLI `agent-cli` login use case.+ *+ * `posthog-cli login` mints a Personal API Key whose scopes come from the+ * `use_cases` it requests in the browser authorize flow. The `agent-cli` use case+ * must grant exactly what the MCP / `posthog-cli api` tool surface needs,+ * otherwise agent commands fail with `API key missing required scope`.+ *+ * The authoritative set is `getAdvertisedOAuthScopes()` — the union of every+ * tool's `required_scopes`. We strip the OIDC identity scopes (`openid`,+ * `profile`, `email`): those ride an OAuth access token, not a Personal API Key.+ *+ * Reads:+ * - src/tools/toolDefinitions.ts (getAdvertisedOAuthScopes, via tool-definitions.json)+ *+ * Produces:+ * - frontend/src/lib/agentScopes.generated.ts+ *+ * Run via hogli: `hogli build:openapi-cli-agent-scopes` (also runs as part of+ * `build:openapi`, after `build:openapi-mcp-tools` which produces the tool+ * definitions this reads). See `hogli.yaml`.+ */+import * as fs from 'node:fs'+import * as path from 'node:path'++import { getAdvertisedOAuthScopes } from '../src/tools/toolDefinitions'++const MCP_ROOT = path.resolve(__dirname, '..')+const REPO_ROOT = path.resolve(MCP_ROOT, '../..')+const OUTPUT_TS = path.resolve(REPO_ROOT, 'frontend/src/lib/agentScopes.generated.ts')++function main(): void {+ // Identity scopes (openid/profile/email) have no `:` and don't apply to+ // Personal API Keys — keep only the resource scopes the tools require.+ const scopes = getAdvertisedOAuthScopes().filter((scope) => scope.includes(':'))++ // Scope names are snake_case identifiers + colons and never need escaping,+ // but assert it so the build fails loudly if that ever changes.+ for (const scope of scopes) {+ if (scope.includes("'") || scope.includes('\\')) {+ throw new Error(`unexpected character in scope name: ${scope}`)+ }+ }++ const body = scopes.map((scope) => ` '${scope}',`).join('\n')+ const output =+ '// AUTO-GENERATED by services/mcp/scripts/build-cli-agent-scopes.ts.\n' ++ '// Regenerate with `hogli build:openapi`. Do not edit.\n' ++ '//\n' ++ '// The scopes the CLI `agent-cli` login use case grants — the same set the MCP\n' ++ '// requests (getAdvertisedOAuthScopes, the union of every tool’s\n' ++ '// required_scopes), minus the OIDC identity scopes that only apply to OAuth\n' ++ '// access tokens rather than Personal API Keys.\n' ++ '\n' ++ 'export const AGENT_USE_CASE_SCOPES = [\n' ++ `${body}\n` ++ '] as const\n'++ fs.mkdirSync(path.dirname(OUTPUT_TS), { recursive: true })+ const existing = fs.existsSync(OUTPUT_TS) ? fs.readFileSync(OUTPUT_TS, 'utf8') : null+ if (existing !== output) {+ fs.writeFileSync(OUTPUT_TS, output)+ // eslint-disable-next-line no-console+ console.log(`wrote ${OUTPUT_TS} (${scopes.length} scopes)`)+ } else {+ // eslint-disable-next-line no-console+ console.log(`${OUTPUT_TS} already up to date (${scopes.length} scopes)`)+ }+}++main()