: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(tasks): trust PostHog MCP operations (#95344)
Dylan Martin4aeb887d98eb
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.tsindex f6623b549891..fb1bd2a333ac 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts@@ -16,7 +16,6 @@ import type { PermissionRequestFrame, StoredLogEntry } from '../types/wireTypes'import { contextItemLine, wrapWithPosthogContext } from '../utils/posthogContextBlock'import { computeTurnTrailers } from '../utils/turnTrailers'import { attachedContextLogic } from './attachedContextLogic'-import { foregroundStreamLogic } from './foregroundStreamLogic'import {extractRunArtifacts,mapHttpStatusToStreamError,@@ -3191,18 +3190,17 @@ describe('runStreamLogic', () => {})describe('permission_request ingest', () => {- // A destructive exec (`insight-update`) so the default policy prompts (shows a card) rather- // than auto-approving — the lifecycle tests below all assume a card appears.+ // An external MCP request prompts, so the lifecycle tests below can exercise the card.const permissionFrame: PermissionRequestFrame = {type: 'permission_request',requestId: 'req-1',toolCall: {toolCallId: 't1',- serverName: 'posthog',- toolName: 'exec',- _meta: { claudeCode: { toolName: 'mcp__posthog__exec' } },- rawInput: { command: 'call insight-update {"id":"abc"}' },- title: 'Update insight',+ serverName: 'other',+ toolName: 'write',+ _meta: { claudeCode: { toolName: 'mcp__other__write' } },+ rawInput: { value: 'new' },+ title: 'Write data',status: 'pending',},options: [@@ -3216,12 +3214,12 @@ describe('runStreamLogic', () => {expect(record).not.toBeNull()expect(record?.requestId).toEqual('req-1')expect(record?.toolCallId).toEqual('t1')- expect(record?.toolName).toEqual('mcp__posthog__exec')+ expect(record?.toolName).toEqual('mcp__other__write')expect(record?.options.map((o) => o.kind)).toEqual(['allow_once', 'reject'])- expect(record?.rawToolCall.rawServerName).toEqual('posthog')- expect(record?.rawToolCall.rawToolName).toEqual('exec')- expect(record?.rawToolCall.input).toEqual({ command: 'call insight-update {"id":"abc"}' })- expect(record?.rawToolCall.meta).toEqual({ claudeCode: { toolName: 'mcp__posthog__exec' } })+ expect(record?.rawToolCall.rawServerName).toEqual('other')+ expect(record?.rawToolCall.rawToolName).toEqual('write')+ expect(record?.rawToolCall.input).toEqual({ value: 'new' })+ expect(record?.rawToolCall.meta).toEqual({ claudeCode: { toolName: 'mcp__other__write' } })})it('returns null for a frame with no usable options', () => {@@ -3285,7 +3283,7 @@ describe('runStreamLogic', () => {)})- it('auto-approves a non-destructive PostHog exec without showing a card', async () => {+ it('auto-approves a PostHog MCP operation without showing a card', async () => {const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })// Resolving the proxy stream target mints a token before `openStream`, so the connection@@ -3298,7 +3296,10 @@ describe('runStreamLogic', () => {requestId: 'req-auto',toolCall: {...permissionFrame.toolCall,- rawInput: { command: 'call insight-create {"name":"x"}' },+ serverName: 'posthog',+ toolName: 'exec',+ _meta: { claudeCode: { toolName: 'mcp__posthog__exec' } },+ rawInput: { command: 'call insight-update {"id":"abc"}' },},})@@ -3339,47 +3340,23 @@ describe('runStreamLogic', () => {})})- describe('foreground gate for persist tools', () => {- // `defaultPermissionDecision` alone auto-approves `dashboard-create` everywhere (it isn't- // destructive). The product requirement is that this run must still prompt when it's a- // foreground stream (rendered in a surface the user is watching). Proving this needs the- // call site (`routePermissionRequest` consulting `foregroundStreamKeys`), not just the- // pure `isPersistPromptTool` helper.- it('prompts for a persist tool when this run is a foreground stream', async () => {- foregroundStreamLogic.actions.setForegroundStream('test-conversation', 'p1')- // A second surface watching a different run must not evict ours from the gate — the- // old single-slot model regressed exactly this (last write won, ours auto-approved).- foregroundStreamLogic.actions.setForegroundStream('other-stream', 'p2')- logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })- await flushPromises()- const source = MockStream.latest()-- await source.emitMessage({- ...permissionFrame,- requestId: 'req-dashboard-fg',- toolCall: {- ...permissionFrame.toolCall,- rawInput: { command: 'call dashboard-create {"name":"New dashboard"}' },- },- })-- expect(logic.values.pendingPermissionRequest?.requestId).toEqual('req-dashboard-fg')- expect(tasksRunsCommandCreate).not.toHaveBeenCalled()- })-- it('still auto-approves a persist tool when this run is not a foreground stream', async () => {- // No surface has registered this run; the auto-approve path yields one macrotask- // (the race re-check) before POSTing, so drain a timer tick too.+ describe('full-auto mode', () => {+ // A `bypassPermissions` run opts out of tool approvals. The mode arrives only on the+ // session/new meta, so this also guards that seed parsing.+ it('auto-approves an external MCP tool once session/new seeds bypassPermissions', async () => {logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })await flushPromises()const source = MockStream.latest()+ await source.emitMessage(+ notification('session/new', { _meta: { permissionMode: 'bypassPermissions' } })+ )await source.emitMessage({...permissionFrame,- requestId: 'req-dashboard-bg',+ requestId: 'req-destructive-fa',toolCall: {...permissionFrame.toolCall,- rawInput: { command: 'call dashboard-create {"name":"New dashboard"}' },+ rawInput: { value: 'changed' },},})await new Promise((resolve) => setTimeout(resolve, 0))@@ -3388,40 +3365,11 @@ describe('runStreamLogic', () => {expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', 'task-1', 'run-1', {jsonrpc: '2.0',method: 'permission_response',- params: { requestId: 'req-dashboard-bg', optionId: 'allow_once' },- })- })-- it('prompts when the foreground registration lands just after the frame (mount race)', async () => {- // A live SSE frame can be processed before a mounting surface's registration effect- // flushes. After `emitMessage` the auto-approve listener is parked on its one-macrotask- // yield; registering now must flip the decision to the card instead of the POST.- logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })- await flushPromises()- const source = MockStream.latest()-- await source.emitMessage({- ...permissionFrame,- requestId: 'req-dashboard-race',- toolCall: {- ...permissionFrame.toolCall,- rawInput: { command: 'call dashboard-create {"name":"New dashboard"}' },- },+ params: { requestId: 'req-destructive-fa', optionId: 'allow_once' },})- foregroundStreamLogic.actions.setForegroundStream('test-conversation', 'p-race')- await new Promise((resolve) => setTimeout(resolve, 0))-- expect(logic.values.pendingPermissionRequest?.requestId).toEqual('req-dashboard-race')- expect(tasksRunsCommandCreate).not.toHaveBeenCalled()})- })- describe('full-auto mode', () => {- // A `bypassPermissions` run opted out of tool approvals: a destructive exec sub-tool (which- // otherwise always prompts) must auto-approve even on a foreground stream. The mode arrives- // only on the session/new meta, so this also guards that seed parsing.- it('auto-approves a destructive exec sub-tool once session/new seeds bypassPermissions', async () => {- foregroundStreamLogic.actions.setForegroundStream('test-conversation', 'p-full-auto')+ it('still surfaces a connected-project operation', async () => {logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })await flushPromises()const source = MockStream.latest()@@ -3431,20 +3379,20 @@ describe('runStreamLogic', () => {)await source.emitMessage({...permissionFrame,- requestId: 'req-destructive-fa',+ requestId: 'req-connected-project',toolCall: {...permissionFrame.toolCall,- rawInput: { command: 'call cdp-functions-partial-update {"id":"abc"}' },+ serverName: 'posthog',+ toolName: 'exec',+ _meta: { claudeCode: { toolName: 'mcp__posthog__exec' } },+ rawInput: {+ command: 'call posthog-connection-call {"connection_id":"1","tool":"feature-flag-delete"}',+ },},})- await new Promise((resolve) => setTimeout(resolve, 0))- expect(logic.values.pendingPermissionRequest).toBeNull()- expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', 'task-1', 'run-1', {- jsonrpc: '2.0',- method: 'permission_response',- params: { requestId: 'req-destructive-fa', optionId: 'allow_once' },- })+ expect(logic.values.pendingPermissionRequest?.requestId).toEqual('req-connected-project')+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()})it('still surfaces a question in full-auto instead of picking an answer', async () => {@@ -3484,6 +3432,9 @@ describe('runStreamLogic', () => {requestId: 'req-fail',toolCall: {...permissionFrame.toolCall,+ serverName: 'posthog',+ toolName: 'exec',+ _meta: { claudeCode: { toolName: 'mcp__posthog__exec' } },rawInput: { command: 'call insight-create {"name":"x"}' },},})diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.tsindex 5672ee750530..d1170b4d42ea 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts@@ -18,7 +18,6 @@ import api from 'lib/api'import { FEATURE_FLAGS } from 'lib/constants'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'-import { delay } from 'lib/utils/async'import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'import { projectLogic } from 'scenes/projectLogic'import { userLogic } from 'scenes/userLogic'@@ -30,7 +29,12 @@ import type { FeatureFlagsSet } from '../../../../frontend/src/lib/logic/featureimport type { UserType } from '../../../../frontend/src/types'import { isPlanPermissionRequest } from '../policy/permissionUtils'import { parseSandboxQuestions } from '../policy/questionUtils'-import { defaultPermissionDecision, findAllowOptionId, isFullAutoMode, isPersistPromptTool } from '../policy/toolPolicy'+import {+ defaultPermissionDecision,+ findAllowOptionId,+ isConnectedProjectTool,+ isFullAutoMode,+} from '../policy/toolPolicy'import type {ContextUsage,PermissionRequestRecord,@@ -1771,9 +1775,9 @@ export const runStreamLogic = kea<runStreamLogicType>([}),/*** Entry point for every parsed permission request. Applies the default tool policy- * (`toolPolicy`): auto-approve built-in tools + non-destructive PostHog exec, prompt- * for update/delete exec (and other MCP). Replayed-from-history requests are never- * auto-approved — they're a read-only restore and the run may already be terminal.+ * (`toolPolicy`): auto-approve built-in tools and PostHog exec in the task's project, but+ * prompt for connected-project calls and other MCP. Replayed-from-history requests are+ * never auto-approved because the run may already be terminal.*/routePermissionRequest: (record: PermissionRequestRecord, replayedFromHistory: boolean = false) => ({record,@@ -2865,19 +2869,15 @@ export const runStreamLogic = kea<runStreamLogicType>([},routePermissionRequest: ({ record, replayedFromHistory }) => {// Replayed history is a read-only restore — never auto-approve (the run may be terminal).- // In full-auto (`bypassPermissions`) the user opted out of tool approvals entirely, so any- // relayed tool request is answered with its allow option — but questions and plan approvals- // still surface, since auto-answering those would pick an option on the user's behalf.- // Otherwise: persist/publish tools (dashboards, feature flags, surveys, hog functions,- // workflows) must still prompt when this run is a foreground stream (rendered in a surface- // the user is watching and can respond in), even though `defaultPermissionDecision` would- // auto-approve them as non-destructive. Background and headless runs keep auto-approving.+ // Full-auto covers the task's selected project. Questions, plan approvals, and calls into+ // connected projects still surface because the task did not authorize them.const fullAuto =- isFullAutoMode(values.currentMode) && !record.questions?.length && !isPlanPermissionRequest(record)- const isForegroundStream = values.foregroundStreamKeys.has(props.streamKey)- const forcePromptForForeground = !fullAuto && isForegroundStream && isPersistPromptTool(record)+ isFullAutoMode(values.currentMode) &&+ !record.questions?.length &&+ !isPlanPermissionRequest(record) &&+ !isConnectedProjectTool(record)const decision = fullAuto ? 'auto_allow' : defaultPermissionDecision(record)- if (!replayedFromHistory && !forcePromptForForeground && decision === 'auto_allow') {+ if (!replayedFromHistory && decision === 'auto_allow') {const optionId = findAllowOptionId(record)if (optionId) {actions.autoApprovePermissionRequest(record, optionId)@@ -2889,19 +2889,6 @@ export const runStreamLogic = kea<runStreamLogicType>([autoApprovePermissionRequest: async ({ record, optionId }) => {// Pin it seen up front so a reconnect replay can't re-process the same request mid-POST.actions.markPermissionRequestSeen(record.requestId)- // A persist tool routed here because no foreground surface was registered yet may have- // raced a mounting surface's registration (the SSE frame can land before the layout- // effect flushes). Yield one macrotask and re-check; if the stream became foreground,- // surface the card instead of silently persisting. Plain `delay`, not a kea breakpoint —- // a breakpoint would let a second rapid frame cancel this listener pre-POST and stall- // the agent. Full-auto runs skip the re-check — they never prompt for persist tools.- if (!isFullAutoMode(values.currentMode) && isPersistPromptTool(record)) {- await delay(0)- if (values.foregroundStreamKeys.has(props.streamKey)) {- actions.ingestPermissionRequest(record)- return- }- }const activeRun = cache.activeRun as { taskId: string; runId: string } | undefinedconst resolvedToolCall = resolveToolCall(record.rawToolCall)posthog.capture('permission_auto_approved', {diff --git a/products/posthog_ai/frontend/policy/toolPolicy.test.ts b/products/posthog_ai/frontend/policy/toolPolicy.test.tsindex 0d2a30d8a4e6..d7ee8797db3e 100644--- a/products/posthog_ai/frontend/policy/toolPolicy.test.ts+++ b/products/posthog_ai/frontend/policy/toolPolicy.test.ts@@ -1,14 +1,7 @@import type { PermissionRequestRecord, ToolInvocation } from '../types/streamTypes'import type { PermissionOption } from '../types/wireTypes'import type { AgentQuestion } from './questionUtils'-import {- defaultPermissionDecision,- findAllowOptionId,- isPersistPromptTool,- isPostHogDestructiveSubTool,- isPostHogExecTool,- type PermissionDecision,-} from './toolPolicy'+import { defaultPermissionDecision, findAllowOptionId, isPostHogExecTool, type PermissionDecision } from './toolPolicy'function makeRecord(overrides: {@@ -52,50 +45,6 @@ describe('toolPolicy', () => {})})- describe('isPostHogDestructiveSubTool', () => {- // Cases ported from Twig posthog-exec-gate.test.ts.- it.each([- 'experiment-update',- 'feature-flag-delete',- 'notebooks-destroy',- 'experiment-partial-update',- 'update-something',- 'delete',- 'workflows-patch-graph',- 'workflows-patch-email-template',- // Destructive-annotated names with no verb segment come from the exact-name set.- 'workflows-publish',- 'experiment-ship-variant',- 'feature-requests-remove-evidence-create',- 'inbox-reports-claim',- 'skill-archive',- 'error-tracking-issues-merge-create',- ])('%s is destructive', (sub) => expect(isPostHogDestructiveSubTool(sub)).toBe(true))- it.each([- 'experiment-get',- 'feature-flag-list',- 'experiment-create',- 'insights-pause',- 'get-updated-events',- // `patch` must match as a whole `-`-bounded segment, not as a substring.- 'dispatch-events-list',- ])('%s is not destructive', (sub) => expect(isPostHogDestructiveSubTool(sub)).toBe(false))-- // posthog-connection-call runs another tool in a connected project, so its verdict comes- // from the `tool` argument. Reading the wrapper's own name would either prompt on every- // cross-account read or wave a cross-account delete straight through.- it.each<[string, Record<string, unknown> | undefined, boolean]>([- ['read in the connected project', { tool: 'execute-sql' }, false],- ['write in the connected project', { tool: 'feature-flag-delete' }, true],- ['destructive-annotated name with no verb', { tool: 'workflows-publish' }, true],- ['no arguments at all', undefined, true],- ['tool argument missing', { connection_id: '1' }, true],- ['tool argument not a string', { tool: { name: 'execute-sql' } }, true],- ])('posthog-connection-call with %s → destructive: %s', (_case, input, expected) =>- expect(isPostHogDestructiveSubTool('posthog-connection-call', input)).toBe(expected)- )- })-describe('defaultPermissionDecision', () => {it.each<[string, PermissionRequestRecord, PermissionDecision]>([[@@ -110,41 +59,22 @@ describe('toolPolicy', () => {],['exec discovery verb', makeRecord({ input: { command: 'tools' } }), 'auto_allow'],['exec create', makeRecord({ input: { command: 'call insight-create {"name":"Signups"}' } }), 'auto_allow'],- ['exec update', makeRecord({ input: { command: 'call insight-update {"id":"abc"}' } }), 'prompt'],- // A destructive-annotated name without a verb segment must resolve through the- // exact-name set, not just the verb regex.- ['exec publish', makeRecord({ input: { command: 'call workflows-publish {"id":"w1"}' } }), 'prompt'],- ['exec delete', makeRecord({ input: { command: 'call feature-flag-delete {"key":"new-nav"}' } }), 'prompt'],- // A destructive sub-tool hidden behind --confirm/--json (in any order) must still prompt —- // the inner tool name is resolved after the flags, not as the flag token.+ ['exec update', makeRecord({ input: { command: 'call insight-update {"id":"abc"}' } }), 'auto_allow'],+ ['exec publish', makeRecord({ input: { command: 'call workflows-publish {"id":"w1"}' } }), 'auto_allow'],[- 'exec delete behind --confirm',- makeRecord({ input: { command: 'call --confirm feature-flag-delete {"key":"x"}' } }),- 'prompt',- ],- [- 'exec delete behind --confirm --json',- makeRecord({ input: { command: 'call --confirm --json feature-flag-delete {"key":"x"}' } }),- 'prompt',- ],- [- 'exec delete behind --json --confirm',- makeRecord({ input: { command: 'call --json --confirm feature-flag-delete {"key":"x"}' } }),- 'prompt',+ 'exec delete',+ makeRecord({ input: { command: 'call feature-flag-delete {"key":"new-nav"}' } }),+ 'auto_allow',],- // An exec call we can't resolve to a concrete sub-tool fails closed.- ['exec call with no sub-tool', makeRecord({ input: { command: 'call --json' } }), 'prompt'],- // The connected-project wrapper is judged by the tool it forwards, end to end through- // the exec command parser — a read there is as free as a read here.+ ['exec call with no sub-tool', makeRecord({ input: { command: 'call --json' } }), 'auto_allow'],['connection call running a read',makeRecord({input: {- command:- 'call posthog-connection-call {"connection_id":"1","tool":"execute-sql","arguments":{"query":"select 1"}}',+ command: 'call posthog-connection-call {"connection_id":"1","tool":"execute-sql"}',},}),- 'auto_allow',+ 'prompt',],['connection call running a delete',@@ -155,6 +85,16 @@ describe('toolPolicy', () => {}),'prompt',],+ [+ 'connection forward',+ makeRecord({+ input: {+ command:+ 'call posthog-connection-forward {"connection_id":"1","method":"GET","path":"api/projects/2/insights/"}',+ },+ }),+ 'prompt',+ ],// A permission frame carrying no canonical tool name isn't a positively-identified built-in.['unidentified frame',@@ -184,98 +124,6 @@ describe('toolPolicy', () => {})})- describe('isPersistPromptTool', () => {- // Proves the set resolves through `resolveToolCall` and matches a real generated create-family- // sub-tool name; a regression here (e.g. a typo'd set entry, or `resolveToolCall` changing its- // resolution shape) would silently drop the foreground prompt gate for that product family.- it.each<[string, PermissionRequestRecord, boolean]>([- [- 'dashboard-create',- makeRecord({ input: { command: 'call dashboard-create {"name":"My dashboard"}' } }),- true,- ],- [- 'dashboard-create-tile',- makeRecord({ input: { command: 'call dashboard-create-tile {"dashboard_id":1}' } }),- true,- ],- ['dashboard-tile-copy', makeRecord({ input: { command: 'call dashboard-tile-copy {"id":1}' } }), true],- [- 'dashboard-widgets-batch-add',- makeRecord({ input: { command: 'call dashboard-widgets-batch-add {"dashboard_id":1}' } }),- true,- ],- [- 'feature-flags-copy-flags-create',- makeRecord({ input: { command: 'call feature-flags-copy-flags-create {"key":"x"}' } }),- true,- ],- [- 'scheduled-changes-create',- makeRecord({ input: { command: 'call scheduled-changes-create {"model_name":"FeatureFlag"}' } }),- true,- ],- ['survey-launch', makeRecord({ input: { command: 'call survey-launch {"id":"s1"}' } }), true],- ['survey-stop', makeRecord({ input: { command: 'call survey-stop {"id":"s1"}' } }), true],- ['workflows-create', makeRecord({ input: { command: 'call workflows-create {"name":"Flow"}' } }), true],- // A read-only query wrapper must never be swept in by an over-broad set/match.- ['query-trends (read-only)', makeRecord({ input: { command: 'call query-trends {}' } }), false],- // An exec call that can't resolve to a concrete sub-tool has no `innerToolName` to match on.- ['unresolvable exec call', makeRecord({ input: { command: 'call --json' } }), false],- // posthog-connection-call persists whatever the tool it forwards persists — in *another*- // account. Matching the wrapper name alone would auto-approve a cross-account launch in- // exactly the watched run this gate exists for.- [- 'posthog-connection-call running survey-launch',- makeRecord({- input: {- command:- 'call posthog-connection-call {"connection_id":"1","tool":"survey-launch","arguments":{}}',- },- }),- true,- ],- [- 'posthog-connection-call running dashboard-create',- makeRecord({- input: {- command:- 'call posthog-connection-call {"connection_id":"1","tool":"dashboard-create","arguments":{"name":"x"}}',- },- }),- true,- ],- [- 'posthog-connection-call running a read-only tool',- makeRecord({- input: {- command:- 'call posthog-connection-call {"connection_id":"1","tool":"execute-sql","arguments":{}}',- },- }),- false,- ],- // The three ways the forwarded name can be unreadable all fail closed to a prompt.- [- 'posthog-connection-call with no tool argument',- makeRecord({ input: { command: 'call posthog-connection-call {"connection_id":"1"}' } }),- true,- ],- [- 'posthog-connection-call with a non-string tool argument',- makeRecord({ input: { command: 'call posthog-connection-call {"connection_id":"1","tool":42}' } }),- true,- ],- [- 'posthog-connection-call with unparseable arguments',- makeRecord({ input: { command: 'call posthog-connection-call {not json' } }),- true,- ],- ])('%s → %s', (_case, record, expected) => {- expect(isPersistPromptTool(record)).toEqual(expected)- })- })-describe('findAllowOptionId', () => {it('prefers allow_once over allow_always', () => {const id = findAllowOptionId(diff --git a/products/posthog_ai/frontend/policy/toolPolicy.ts b/products/posthog_ai/frontend/policy/toolPolicy.tsindex 9236fd4aedce..83584f9dea90 100644--- a/products/posthog_ai/frontend/policy/toolPolicy.ts+++ b/products/posthog_ai/frontend/policy/toolPolicy.ts@@ -8,104 +8,36 @@ export { isPostHogExecTool } from '../components/tool/posthogExecDisplay'/*** Client-side sandbox tool-permission policy.*- * The agent-server relays a permission request here in two cases: the exec sub-tool matched the- * server's `--posthogExecPermissionRegex` (relayed in every non-background run regardless of- * permission mode — see `POSTHOG_EXEC_PERMISSION_REGEX` in `products/tasks/backend/constants.py`,- * which must stay in sync with the destructive verbs and persist tools below), or the run's- * permission mode relays manual approvals and a client is connected. This policy decides which- * relayed requests auto-approve and which surface the approval card: built-ins and read-only- * PostHog `exec` auto-approve; destructive sub-tools prompt; persist/publish sub-tools prompt only- * on foreground streams; full-auto (`bypassPermissions`) runs answer everything.+ * The run's permission mode can relay manual approvals when a client is connected. This policy+ * auto-approves built-in tools and PostHog MCP calls in the task's project. It keeps approval cards+ * for connected-project calls, external MCP servers, and requests that cannot be identified.*/-/** Full-auto modes answer every relayed tool request without prompting (questions and plan approvals still surface). */+/** Whether the run auto-approves tools that stay inside its selected project. */export function isFullAutoMode(mode: string | null | undefined): boolean {return mode === 'bypassPermissions'}-/** A sub-tool is destructive when one of these verbs appears as a whole `-`-bounded segment. */-const POSTHOG_DESTRUCTIVE_SUBTOOL_RE = /(^|-)(partial-update|update|patch|delete|destroy)(-|$)/i--/**- * Destructive-annotated sub-tools whose names carry no destructive verb segment (publish, ship,- * merge, archive, …). Mirrors `POSTHOG_EXEC_DESTRUCTIVE_SUB_TOOLS` in- * `products/tasks/backend/constants.py`, which a backend test keeps complete against the- * `annotations.destructive: true` tools in `products/*\/mcp/*.yaml` — update both together.- */-const POSTHOG_DESTRUCTIVE_SUB_TOOLS = new Set([- // confirmed_action tools register only `<name>-execute` (and `-prepare`); the bare name is- // never a runtime tool, so the destructive `-execute` variant is what must be gated.- 'change-requests-approve-execute',- 'change-requests-reject-execute',- 'cdp-functions-discard-draft',- 'cdp-functions-publish',- 'cdp-functions-restore-revision',- 'error-tracking-bypass-rules-create',- 'error-tracking-issues-merge-create',- 'error-tracking-issues-split-create',- 'error-tracking-suppression-rules-create',- 'experiment-ship-variant',- 'external-data-schemas-resync',- 'external-data-sources-repair-cdc-create',- 'feature-requests-remove-evidence-create',- 'heatmaps-saved-regenerate',- 'inbox-reports-bulk-set-state',- 'inbox-reports-claim',- 'inbox-reports-set-state',- 'llma-prompt-label-set',- 'opt-outs-add',- 'opt-outs-remove',- 'organization-enforce-2fa',- 'organization-enforce-2fa-execute',- 'posthog-connection-forward',- 'scout-scratchpad-forget',- 'signals-scout-scratchpad-forget',- 'skill-archive',- 'user-interview-topics-remove-interviewee',- 'visual-review-runs-finalize-create',- 'web-analytics-path-cleaning-suggestions-apply',- 'workflows-discard-draft',- 'workflows-publish',- 'workflows-restore-revision',- 'workflows-test-run',-])+export type PermissionDecision = 'auto_allow' | 'prompt'-/**- * `posthog-connection-call` runs another PostHog tool in a connected project, so it is exactly as- * destructive as that tool — which rides in its `tool` argument. Judging the wrapper by name alone- * would prompt on every cross-account read; judging it safe by name alone would let a cross-account- * delete through. An unreadable target is not provably safe, so it prompts.- */-const POSTHOG_CONNECTION_CALL_TOOL = 'posthog-connection-call'+const CONNECTED_PROJECT_SUB_TOOLS = new Set(['posthog-connection-call', 'posthog-connection-forward'])-export function isPostHogDestructiveSubTool(subTool: string, innerInput?: Record<string, unknown>): boolean {- if (subTool.toLowerCase() === POSTHOG_CONNECTION_CALL_TOOL) {- const forwardedTool = innerInput?.['tool']- return typeof forwardedTool !== 'string' || isPostHogDestructiveSubTool(forwardedTool)- }- return POSTHOG_DESTRUCTIVE_SUBTOOL_RE.test(subTool) || POSTHOG_DESTRUCTIVE_SUB_TOOLS.has(subTool.toLowerCase())+function isConnectedProjectSubTool(subTool: string): boolean {+ return CONNECTED_PROJECT_SUB_TOOLS.has(subTool.toLowerCase())}-export type PermissionDecision = 'auto_allow' | 'prompt'--/** Read-only exec discovery verbs — safe to auto-approve since they never mutate PostHog data. */-const POSTHOG_EXEC_READ_ONLY_KEYS = new Set([- '__posthog_exec_tools__',- '__posthog_exec_search__',- '__posthog_exec_info__',- '__posthog_exec_schema__',-])+export function isConnectedProjectTool(record: PermissionRequestRecord): boolean {+ const { innerToolName } = resolveToolCall(record.rawToolCall)+ return innerToolName != null && isConnectedProjectSubTool(innerToolName)+}/*** Decide whether a permission request can be auto-approved or must prompt the user. The policy fails* closed: a request only auto-approves when it is positively identified as safe.*- * PostHog `exec` is detected by canonical tool name and by the parsed verb/sub-tool (robust to a- * missing `_meta.claudeCode.toolName`): read-only discovery verbs (`tools`/`search`/`info`/`schema`)- * and non-mutating `call <sub-tool>`s auto-approve; mutating sub-tools prompt, and an exec call whose- * sub-tool can't be resolved (malformed, unknown verb, unrecognized flags) prompts rather than- * silently allowing. A positively-identified built-in (non-MCP tool with a canonical name)- * auto-approves; other MCP servers and any frame we can't identify prompt.+ * PostHog `exec` is detected by canonical tool name and by the parsed command. Operations in the+ * task's project auto-approve. Connected-project calls, other MCP servers, and frames that cannot be+ * identified still prompt.*/export function defaultPermissionDecision(record: PermissionRequestRecord): PermissionDecision {// An `AskUserQuestion` rides the permission framework but is not an approval — auto-approving it@@ -115,19 +47,14 @@ export function defaultPermissionDecision(record: PermissionRequestRecord): Perm}const { toolName } = record- const { resolvedKey, innerToolName, innerInput } = resolveToolCall(record.rawToolCall)+ const { resolvedKey, innerToolName } = resolveToolCall(record.rawToolCall)const isExec = isPostHogExecTool(toolName) || innerToolName != null || resolvedKey.startsWith('__posthog_exec_')if (isExec) {- if (POSTHOG_EXEC_READ_ONLY_KEYS.has(resolvedKey)) {- return 'auto_allow'- }- // A resolved `call <sub-tool>`: auto-approve only non-mutating sub-tools.- if (innerToolName) {- return isPostHogDestructiveSubTool(innerToolName, innerInput) ? 'prompt' : 'auto_allow'+ if (innerToolName != null && isConnectedProjectSubTool(innerToolName)) {+ return 'prompt'}- // Exec call we couldn't resolve to a concrete sub-tool — fail closed.- return 'prompt'+ return 'auto_allow'}if (toolName.startsWith('mcp__')) {@@ -138,56 +65,6 @@ export function defaultPermissionDecision(record: PermissionRequestRecord): Permreturn toolName ? 'auto_allow' : 'prompt'}-/**- * Persist/publish sub-tools that must prompt when (and only when) the run is a foreground stream- * (a run rendered in a surface the user is watching, see `foregroundStreamLogic`).- * These aren't destructive, so `defaultPermissionDecision` still auto-approves them everywhere else- * (background runs, headless runs, replays); the call site in `runStreamLogic`'s- * `routePermissionRequest` forces the prompt path for foreground streams. Scoped to the product- * families from the apply-back migration plan — every enabled tool that persists new content- * (create/copy/add) or publishes to end users (launch/stop). To extend it, add the sub-tool name- * here AND to `POSTHOG_EXEC_PERMISSION_REGEX` in `products/tasks/backend/constants.py` — the- * server only relays sub-tools matching that regex, so a name missing there never reaches this- * gate in modes that don't relay manual approvals.- */-const PERSIST_PROMPT_SUB_TOOLS = new Set([- 'dashboard-create',- 'dashboard-create-tile',- 'dashboard-create-text-tile',- 'dashboard-tile-copy',- 'dashboard-widgets-batch-add',- 'create-feature-flag',- 'feature-flags-copy-flags-create',- 'scheduled-changes-create',- 'survey-create',- 'survey-launch',- 'survey-stop',- 'cdp-functions-create',- 'workflows-create',- 'workflows-create-email-template',- 'llma-parser-recipe-create',-])--/**- * Whether a permission request resolves to a create-family persist tool from `PERSIST_PROMPT_SUB_TOOLS`.- *- * Unwraps `posthog-connection-call` the same way `isPostHogDestructiveSubTool` does: the wrapper- * persists exactly what the tool in its `tool` argument persists, and a survey launched in someone- * else's project is no less worth a foreground prompt than one launched here. An unreadable target- * is not provably safe, so it prompts.- */-export function isPersistPromptTool(record: PermissionRequestRecord): boolean {- const { innerToolName, innerInput } = resolveToolCall(record.rawToolCall)- if (innerToolName == null) {- return false- }- if (innerToolName.toLowerCase() === POSTHOG_CONNECTION_CALL_TOOL) {- const forwardedTool = innerInput?.['tool']- return typeof forwardedTool !== 'string' || PERSIST_PROMPT_SUB_TOOLS.has(forwardedTool)- }- return PERSIST_PROMPT_SUB_TOOLS.has(innerToolName)-}-/** The optionId to auto-send when allowing — prefers the one-shot allow over `allow_always`. */export function findAllowOptionId(record: PermissionRequestRecord): string | null {const allowOnce = record.options.find((o) => o.kind === 'allow_once')diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.pyindex 4d8560d20a36..eacb08eab03e 100644--- a/products/tasks/backend/constants.py+++ b/products/tasks/backend/constants.py@@ -238,88 +238,9 @@ ClaudePermissionMode = Literal["default", "acceptEdits", "plan", "bypassPermissiCodexPermissionMode = Literal["plan", "auto", "read-only", "full-access"]InitialPermissionMode = ClaudePermissionMode | CodexPermissionMode-# PostHog `exec` sub-tools that must be approved by the user before they run, passed to the-# agent-server as `--posthogExecPermissionRegex`. A matching sub-tool is relayed to the connected-# client in every non-background run regardless of permission mode (the client then decides:-# destructive sub-tools always prompt, persist/publish sub-tools prompt only on foreground streams,-# full-auto runs answer everything). Three alternatives: destructive verbs as `-`-bounded segments,-# the exact names of `annotations.destructive: true` tools the verb regex misses, and the exact-# persist/publish tool names from the apply-back product families. Must stay in sync with-# `POSTHOG_DESTRUCTIVE_SUBTOOL_RE`, `POSTHOG_DESTRUCTIVE_SUB_TOOLS`, and `PERSIST_PROMPT_SUB_TOOLS`-# in `products/posthog_ai/frontend/policy/toolPolicy.ts`.-POSTHOG_EXEC_DESTRUCTIVE_VERB_REGEX = r"(^|-)(partial-update|update|patch|delete|destroy)(-|$)"--# Enabled tools annotated `destructive: true` in `products/*/mcp/*.yaml` whose names carry no-# destructive verb segment (publish, ship, merge, archive, …). Kept complete against those-# annotations by `test_exec_permission_regex_covers_destructive_annotated_tools`.-POSTHOG_EXEC_DESTRUCTIVE_SUB_TOOLS: tuple[str, ...] = (- # confirmed_action tools register only `<name>-execute` (and `-prepare`); the bare name is- # never a runtime tool, so the destructive `-execute` variant is what must be gated.- "change-requests-approve-execute",- "change-requests-reject-execute",- "cdp-functions-discard-draft",- "cdp-functions-publish",- "cdp-functions-restore-revision",- "error-tracking-bypass-rules-create",- "error-tracking-issues-merge-create",- "error-tracking-issues-split-create",- "error-tracking-suppression-rules-create",- "experiment-ship-variant",- "external-data-schemas-resync",- "external-data-sources-repair-cdc-create",- "feature-requests-remove-evidence-create",- "heatmaps-saved-regenerate",- "inbox-reports-bulk-set-state",- "inbox-reports-claim",- "inbox-reports-set-state",- "llma-prompt-label-set",- "opt-outs-add",- "opt-outs-remove",- "organization-enforce-2fa",- "organization-enforce-2fa-execute",- # Relayed on every call, not because every call writes: the client decides from the tool it- # runs in the connected project, which only it can read out of the arguments.- "posthog-connection-call",- "posthog-connection-forward",- "scout-scratchpad-forget",- "signals-scout-scratchpad-forget",- "skill-archive",- "user-interview-topics-remove-interviewee",- "visual-review-runs-finalize-create",- "web-analytics-path-cleaning-suggestions-apply",- "workflows-discard-draft",- "workflows-publish",- "workflows-restore-revision",- "workflows-test-run",-)--# Non-destructive tools that persist new content (create/copy/add) or publish to end users-# (launch/stop), from the apply-back product families — the client prompts for these only on-# foreground streams.-POSTHOG_EXEC_PERSIST_SUB_TOOLS: tuple[str, ...] = (- "dashboard-create",- "dashboard-create-tile",- "dashboard-create-text-tile",- "dashboard-tile-copy",- "dashboard-widgets-batch-add",- "create-feature-flag",- "feature-flags-copy-flags-create",- "scheduled-changes-create",- "survey-create",- "survey-launch",- "survey-stop",- "cdp-functions-create",- "workflows-create",- "workflows-create-email-template",- "llma-parser-recipe-create",-)--POSTHOG_EXEC_PERMISSION_REGEX = (- POSTHOG_EXEC_DESTRUCTIVE_VERB_REGEX- + "|^("- + "|".join(POSTHOG_EXEC_DESTRUCTIVE_SUB_TOOLS + POSTHOG_EXEC_PERSIST_SUB_TOOLS)- + ")$"-)+# Starting a task authorizes its selected PostHog project, not projects reached through connections.+# Relay both connection wrappers so the client can require fresh approval before they run.+POSTHOG_EXEC_PERMISSION_REGEX = r"^posthog-connection-(call|forward)$"INITIAL_PERMISSION_MODE_CHOICES: list[str] = list(get_args(ClaudePermissionMode))CODEX_INITIAL_PERMISSION_MODE_CHOICES: list[str] = list(get_args(CodexPermissionMode))diff --git a/products/tasks/backend/logic/services/agent_server_launcher.py b/products/tasks/backend/logic/services/agent_server_launcher.pyindex cd29e5de4821..35b3a62df764 100644--- a/products/tasks/backend/logic/services/agent_server_launcher.py+++ b/products/tasks/backend/logic/services/agent_server_launcher.py@@ -349,7 +349,7 @@ class AgentServerLaunchMixin(SandboxBase):if not self.agent_server_supports_exec_permission_regex():logger.warning(f"Installed agent-server in sandbox {self.id} predates --posthogExecPermissionRegex; "- "exec sub-tools will not prompt"+ "connected-project operations will not prompt")exec_permission_regex = Nonediff --git a/products/tasks/backend/logic/services/docker_sandbox.py b/products/tasks/backend/logic/services/docker_sandbox.pyindex 7d63647e8104..1a0bdc8c6045 100644--- a/products/tasks/backend/logic/services/docker_sandbox.py+++ b/products/tasks/backend/logic/services/docker_sandbox.py@@ -1051,7 +1051,7 @@ class DockerSandbox(SandboxBase):if not self.agent_server_supports_exec_permission_regex():logger.warning(f"Installed agent-server in sandbox {self.id} predates --posthogExecPermissionRegex; "- "exec sub-tools will not prompt"+ "connected-project operations will not prompt")exec_permission_regex = Nonediff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.pyindex 78e9c9db574d..957a0c333dbb 100644--- a/products/tasks/backend/logic/services/sandbox.py+++ b/products/tasks/backend/logic/services/sandbox.py@@ -458,9 +458,6 @@ class SandboxBase(ABC):return result.exit_code == 0def agent_server_supports_exec_permission_regex(self) -> bool:- """Same probe as --autoPublish: check the installed binary before passing- --posthogExecPermissionRegex; unsupported binaries degrade to server-side auto-approval of- exec sub-tools instead of crashing at launch."""result = self.execute("grep -q posthogExecPermissionRegex /scripts/node_modules/.bin/agent-server", timeout_seconds=10)diff --git a/products/tasks/backend/logic/services/tests/test_docker_sandbox.py b/products/tasks/backend/logic/services/tests/test_docker_sandbox.pyindex ba2ac81220c3..f9f5c7cb55d5 100644--- a/products/tasks/backend/logic/services/tests/test_docker_sandbox.py+++ b/products/tasks/backend/logic/services/tests/test_docker_sandbox.py@@ -1,4 +1,3 @@-import reimport shleximport pytest@@ -75,42 +74,23 @@ def test_read_agent_server_boot_metrics_uses_pi_boot_total(sandbox: DockerSandboassert sandbox.read_agent_server_boot_metrics() == (90, {"server_total": 140})-def test_build_agent_server_command_gates_exec_permission_regex(sandbox: DockerSandbox):+def test_build_agent_server_command_gates_connected_project_operations(sandbox: DockerSandbox):with_flag = sandbox._build_agent_server_command(None, "t1", "r1", "interactive", True, posthog_exec_permission_regex=POSTHOG_EXEC_PERMISSION_REGEX)assert f"--posthogExecPermissionRegex {shlex.quote(POSTHOG_EXEC_PERMISSION_REGEX)}" in with_flag- # An agent-server predating the flag rejects unknown options — the builder must omit it entirely.without_flag = sandbox._build_agent_server_command(None, "t1", "r1", "interactive", True)assert "--posthogExecPermissionRegex" not in without_flag- [- ("cdp-functions-partial-update", True),- ("insight-update", True),- ("survey-delete", True),- ("dashboard-create", True),- ("survey-launch", True),- ("workflows-create-email-template", True),- ("insight-create", False),- ("cdp-functions-list", False),- ("dashboard-create-extra", False),- ]-)-def test_exec_permission_regex_matches_gated_sub_tools(sub_tool: str, should_match: bool):- # The constant is hand-concatenated; a broken anchor or alternation silently stops relaying- # approvals for (or starts prompting on) the wrong sub-tools.- assert bool(re.search(POSTHOG_EXEC_PERMISSION_REGEX, sub_tool, re.IGNORECASE)) is should_match--def test_start_agent_server_launch_failure_is_captured(sandbox: DockerSandbox):failed = ExecutionResult(stdout="", stderr="boom", exit_code=1)with (patch.object(sandbox, "is_running", return_value=True),patch.object(sandbox, "write_file"),- patch.object(sandbox, "_build_agent_server_command", return_value="run-agent-server"),+ patch.object(sandbox, "_build_agent_server_command", return_value="run-agent-server") as build_command,+ patch.object(sandbox, "agent_server_supports_exec_permission_regex", return_value=True),patch.object(sandbox, "execute", return_value=failed),patch("products.tasks.backend.exceptions.capture_exception") as capture_exception,pytest.raises(SandboxExecutionError),@@ -119,6 +99,7 @@ def test_start_agent_server_launch_failure_is_captured(sandbox: DockerSandbox):# A genuine non-zero launch is a real fault — it still gets captured.capture_exception.assert_called_once()+ assert build_command.call_args.kwargs["posthog_exec_permission_regex"] == POSTHOG_EXEC_PERMISSION_REGEX@parameterized.expand([("empty", b""), ("with_content", b"GITHUB_TOKEN=ghs_x\x00")])diff --git a/products/tasks/backend/tests/test_constants.py b/products/tasks/backend/tests/test_constants.pyindex b975df94553e..9ece85972ef0 100644--- a/products/tasks/backend/tests/test_constants.py+++ b/products/tasks/backend/tests/test_constants.py@@ -1,47 +1,17 @@import re-from pathlib import Pathfrom django.conf import settings-import yaml-from products.tasks.backend.constants import POSTHOG_EXEC_PERMISSION_REGEXfrom products.tasks.backend.presentation.serializers import TASK_RUN_ARTIFACT_INLINE_MAX_SIZE_BYTES-PRODUCTS_DIR = Path(__file__).resolve().parents[3]---def _enabled_destructive_tools() -> list[str]:- tools: list[str] = []- for config_path in sorted(PRODUCTS_DIR.glob("*/mcp/*.yaml")) + sorted(PRODUCTS_DIR.glob("*/mcp/*.yml")):- config = yaml.safe_load(config_path.read_text())- if not isinstance(config, dict):- continue- declared = config.get("tools") or {}- entries = declared.items() if isinstance(declared, dict) else ((t.get("name"), t) for t in declared)- for name, tool in entries:- if not isinstance(tool, dict) or not isinstance(name, str) or not tool.get("enabled"):- continue- if not (tool.get("annotations") or {}).get("destructive"):- continue- # confirmed_action tools register no bare `<name>`; codegen emits `<name>-prepare`- # (non-destructive) and `<name>-execute` (the destructive action that actually runs).- # Gate the generated execute name, since that is what the client relays for approval.- tools.append(f"{name}-execute" if tool.get("confirmed_action") else name)- return tools---def test_exec_permission_regex_covers_destructive_annotated_tools():- # A destructive-annotated tool the regex misses is never relayed for approval and executes- # silently in `auto` mode — the exact gap this regex exists to close. When this fails, add the- # tool name to `POSTHOG_EXEC_DESTRUCTIVE_SUB_TOOLS` in `constants.py` AND to- # `POSTHOG_DESTRUCTIVE_SUB_TOOLS` in `products/posthog_ai/frontend/policy/toolPolicy.ts`.- destructive = _enabled_destructive_tools()- assert len(destructive) > 0, f"no destructive-annotated MCP tools found under {PRODUCTS_DIR} — glob broken?"+def test_exec_permission_regex_only_matches_connected_project_tools():pattern = re.compile(POSTHOG_EXEC_PERMISSION_REGEX, re.IGNORECASE)- ungated = sorted(name for name in destructive if not pattern.search(name))- assert not ungated, f"destructive-annotated MCP tools not covered by POSTHOG_EXEC_PERMISSION_REGEX: {ungated}"++ assert pattern.search("posthog-connection-call")+ assert pattern.search("posthog-connection-forward")+ assert not pattern.search("feature-flag-delete")def test_inline_artifact_ceiling_stays_reachable_through_the_request_body_limit():