: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
feat(platform_features): add org 2FA-enforcement MCP tool (#72589)
Yasen6d9d6c50667a
diff --git a/products/platform_features/mcp/tools.yaml b/products/platform_features/mcp/tools.yamlindex 8cc666bf9926..02edb27cc042 100644--- a/products/platform_features/mcp/tools.yaml+++ b/products/platform_features/mcp/tools.yaml@@ -255,6 +255,44 @@ tools:description: >List all members of the current organization with their names, emails, membership levels (member, admin,owner), and last login times.+ organization-enforce-2fa:+ operation: partial_update+ enabled: true+ scopes:+ - organization:write+ annotations:+ readOnly: false+ destructive: true+ idempotent: true+ title: Enforce two-factor authentication org-wide+ description: >+ Enable or disable organization-wide two-factor authentication (2FA) enforcement. When enabled, every member+ of the organization is required to set up 2FA before they can continue using PostHog. This is an admin-only,+ security-sensitive change that affects all members at once. Requires human typed confirmation. Set+ `enforce_2fa` to true to require 2FA org-wide, or false to lift the requirement.+ include_params:+ - enforce_2fa+ param_overrides:+ id:+ description: |+ Organization ID. If omitted, targets the active organization.+ optional: true+ fallback: orgId+ enforce_2fa:+ description: >+ Set to true to require every organization member to have 2FA enabled; false to lift the requirement.+ Applies org-wide and takes effect immediately.+ required: true+ feature_entitlement: 2fa_enforcement+ response:+ include:+ - enforce_2fa+ confirmed_action:+ message: >+ About to set organization-wide two-factor-authentication enforcement to {enforce_2fa}. This immediately+ affects every member of the organization — when enabled, all members must set up 2FA before they can+ continue using PostHog. Reply 'confirm' to proceed.+ action_label: change 2FA enforcementorganization-get:operation: retrieveenabled: truediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 874d1c0cab9d..87fc64f17911 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -6607,6 +6607,36 @@"readOnlyHint": true}},+ "organization-enforce-2fa-execute": {+ "description": "Step 2 of 2 for change 2FA enforcement. Verifies the confirmation_hash from -prepare and the literal \"confirm\" string typed by the user, then performs the action. ONLY call this after the user has explicitly typed \"confirm\" in chat. Original action: Enable or disable organization-wide two-factor authentication (2FA) enforcement. When enabled, every member of the organization is required to set up 2FA before they can continue using PostHog. This is an admin-only, security-sensitive change that affects all members at once. Requires human typed confirmation. Set `enforce_2fa` to true to require 2FA org-wide, or false to lift the requirement.",+ "category": "Platform Features",+ "feature": "platform_features",+ "summary": "Enforce two-factor authentication org-wide (execute)",+ "title": "Enforce two-factor authentication org-wide (execute)",+ "required_scopes": ["organization:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_entitlement": "2fa_enforcement"+ },+ "organization-enforce-2fa-prepare": {+ "description": "Step 1 of 2 for change 2FA enforcement. Validates the arguments and returns a signed confirmation_hash plus a message to surface to the user. The user must reply with the literal word \"confirm\" before you call the matching -execute tool with the hash. Original action: Enable or disable organization-wide two-factor authentication (2FA) enforcement. When enabled, every member of the organization is required to set up 2FA before they can continue using PostHog. This is an admin-only, security-sensitive change that affects all members at once. Requires human typed confirmation. Set `enforce_2fa` to true to require 2FA org-wide, or false to lift the requirement.",+ "category": "Platform Features",+ "feature": "platform_features",+ "summary": "Enforce two-factor authentication org-wide (prepare)",+ "title": "Enforce two-factor authentication org-wide (prepare)",+ "required_scopes": ["organization:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_entitlement": "2fa_enforcement"+ },"organization-get": {"description": "Get details of an organization by ID including name, membership level, member count, teams, and projects. If no ID is provided, returns the active organization.","category": "Platform Features",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 9dbda2682a12..ba2b0e3dc366 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -7086,6 +7086,36 @@"readOnlyHint": true}},+ "organization-enforce-2fa-execute": {+ "description": "Step 2 of 2 for change 2FA enforcement. Verifies the confirmation_hash from -prepare and the literal \"confirm\" string typed by the user, then performs the action. ONLY call this after the user has explicitly typed \"confirm\" in chat. Original action: Enable or disable organization-wide two-factor authentication (2FA) enforcement. When enabled, every member of the organization is required to set up 2FA before they can continue using PostHog. This is an admin-only, security-sensitive change that affects all members at once. Requires human typed confirmation. Set `enforce_2fa` to true to require 2FA org-wide, or false to lift the requirement.",+ "category": "Platform Features",+ "feature": "platform_features",+ "summary": "Enforce two-factor authentication org-wide (execute)",+ "title": "Enforce two-factor authentication org-wide (execute)",+ "required_scopes": ["organization:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_entitlement": "2fa_enforcement"+ },+ "organization-enforce-2fa-prepare": {+ "description": "Step 1 of 2 for change 2FA enforcement. Validates the arguments and returns a signed confirmation_hash plus a message to surface to the user. The user must reply with the literal word \"confirm\" before you call the matching -execute tool with the hash. Original action: Enable or disable organization-wide two-factor authentication (2FA) enforcement. When enabled, every member of the organization is required to set up 2FA before they can continue using PostHog. This is an admin-only, security-sensitive change that affects all members at once. Requires human typed confirmation. Set `enforce_2fa` to true to require 2FA org-wide, or false to lift the requirement.",+ "category": "Platform Features",+ "feature": "platform_features",+ "summary": "Enforce two-factor authentication org-wide (prepare)",+ "title": "Enforce two-factor authentication org-wide (prepare)",+ "required_scopes": ["organization:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_entitlement": "2fa_enforcement"+ },"organization-get": {"description": "Get details of an organization by ID including name, membership level, member count, teams, and projects. If no ID is provided, returns the active organization.","category": "Platform Features",diff --git a/services/mcp/scripts/generate-tools.ts b/services/mcp/scripts/generate-tools.tsindex aa8a31f14e50..0ab58e3eb4d6 100644--- a/services/mcp/scripts/generate-tools.ts+++ b/services/mcp/scripts/generate-tools.ts@@ -1224,6 +1224,7 @@ function generateToolCode(resultType,needsProjectId,needsOrgId,+ paramFallbacks: composition.paramFallbacks,})return {code: wrapped.code,@@ -1296,9 +1297,19 @@ function buildConfirmedActionFactories(args: {resultType: stringneedsProjectId: booleanneedsOrgId: boolean+ paramFallbacks: Record<string, string>}): { code: string } {- const { toolName, config, schemaName, schemaDecl, originalHandlerBody, resultType, needsProjectId, needsOrgId } =- args+ const {+ toolName,+ config,+ schemaName,+ schemaDecl,+ originalHandlerBody,+ resultType,+ needsProjectId,+ needsOrgId,+ paramFallbacks,+ } = argsconst baseFactory = toCamelCase(toolName)const prepareName = `${toolName}-prepare`const executeName = `${toolName}-execute`@@ -1363,12 +1374,40 @@ function buildConfirmedActionFactories(args: {)}+ // Optional params with a state fallback (e.g. an omitted org/project `id`+ // that defaults to the active one) are resolved to a concrete value BEFORE+ // signing, so the confirmation is bound to the exact target the user saw.+ // Otherwise the fallback would be re-read at execute time and a+ // `switch-organization` / `switch-project` between prepare and execute+ // could retarget the confirmed action at a different entity.+ const fallbackMethodMap: Record<string, string> = {+ orgId: 'context.stateManager.getOrgID()',+ projectId: 'context.stateManager.getProjectId()',+ }+ let prepareFallbackBlock = ''+ const resolvedFallbackNames: string[] = []+ for (const [paramName, fallbackKey] of Object.entries(paramFallbacks)) {+ const method = fallbackMethodMap[fallbackKey]+ if (!method) {+ continue+ }+ const entity = fallbackKey === 'orgId' ? 'organization' : 'project'+ prepareFallbackBlock += ` const ${paramName} = params.${paramName} ?? await ${method}\n`+ prepareFallbackBlock += ` if (!${paramName}) {\n`+ prepareFallbackBlock += ` throw new Error('${paramName} is required. Provide it explicitly or set an active ${entity} first.')\n`+ prepareFallbackBlock += ` }\n`+ resolvedFallbackNames.push(paramName)+ }+ const prepareArgsExpr =+ resolvedFallbackNames.length > 0 ? `{ ...params, ${resolvedFallbackNames.join(', ')} }` : 'params'+// Prepare handler: validate args via the base schema (already happens// before our handler runs) and call into the runtime. Args are signed- // verbatim — bound to user identity + purpose (+ active scope).+ // (with any state fallbacks resolved) — bound to user identity + purpose+ // (+ active scope).const prepareHandler = ` const __runtime = getConfirmedActionRuntime()-${scopeResolveBlock} return await prepareConfirmedAction(context, {- args: params,+${scopeResolveBlock}${prepareFallbackBlock} return await prepareConfirmedAction(context, {+ args: ${prepareArgsExpr},purpose: ${JSON.stringify(toolName)},actionLabel: ${JSON.stringify(actionLabel)},messageTemplate: ${JSON.stringify(messageTemplate)},diff --git a/services/mcp/src/generated/platform_features/api.ts b/services/mcp/src/generated/platform_features/api.tsindex af094ddf3c5e..bd69808fa074 100644--- a/services/mcp/src/generated/platform_features/api.ts+++ b/services/mcp/src/generated/platform_features/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 19 enabled ops+ * PostHog API - MCP 20 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -17,6 +17,50 @@ export const RetrieveParams = /* @__PURE__ */ zod.object({id: zod.string().describe('A UUID string identifying this organization.'),})+export const PartialUpdateParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this organization.'),+})++export const partialUpdateBodyNameMax = 64++export const PartialUpdateBody = /* @__PURE__ */ zod.object({+ name: zod.string().max(partialUpdateBodyNameMax).optional(),+ logo_media_id: zod.string().nullish(),+ enforce_2fa: zod.boolean().nullish(),+ members_can_invite: zod.boolean().nullish(),+ members_can_create_projects: zod+ .boolean()+ .nullish()+ .describe(+ 'When True, organization members (below admin) are allowed to create new projects. Admins and owners can always create projects.'+ ),+ members_can_use_personal_api_keys: zod.boolean().optional(),+ allow_publicly_shared_resources: zod.boolean().optional(),+ is_ai_data_processing_approved: zod.boolean().nullish(),+ is_ai_training_opted_in: zod+ .boolean()+ .nullish()+ .describe('When True, this organization allows its data to be used to train PostHog AI models.'),+ default_experiment_stats_method: zod+ .union([+ zod.enum(['bayesian', 'frequentist']).describe('* `bayesian` - Bayesian\n* `frequentist` - Frequentist'),+ zod.enum(['']),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Default statistical method for new experiments in this organization.\n\n* `bayesian` - Bayesian\n* `frequentist` - Frequentist'+ ),+ default_anonymize_ips: zod+ .boolean()+ .optional()+ .describe("Default setting for 'Discard client IP data' for new projects in this organization."),+ default_role_id: zod+ .string()+ .nullish()+ .describe('ID of the role to automatically assign to new members joining the organization'),+})+export const MembersListParams = /* @__PURE__ */ zod.object({organization_id: zod.string()diff --git a/services/mcp/src/tools/generated/platform_features.ts b/services/mcp/src/tools/generated/platform_features.tsindex c8a56b18f7f7..e79dfdc658f1 100644--- a/services/mcp/src/tools/generated/platform_features.ts+++ b/services/mcp/src/tools/generated/platform_features.ts@@ -14,6 +14,8 @@ import {ListQueryParams,MembersGithubLoginRetrieveParams,MembersListQueryParams,+ PartialUpdateBody,+ PartialUpdateParams,RetrieveParams,RolesListQueryParams,RolesRetrieveParams,@@ -23,6 +25,12 @@ import {UserHomeSettingsPartialUpdateParams,UserHomeSettingsRetrieveParams,} from '@/generated/platform_features/api'+import { getConfirmedActionRuntime } from '@/tools/confirmed-action-registry'+import {+ executeConfirmedAction,+ prepareConfirmedAction,+ type PrepareConfirmedActionResult,+} from '@/tools/confirmed-action-runtime'import { withPostHogUrl, pickResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'@@ -318,6 +326,97 @@ const orgMembersList = (): ToolBase<typeof OrgMembersListSchema, Schemas.Paginat},})+const OrganizationEnforce2faSchema = PartialUpdateParams.extend(+ PartialUpdateBody.omit({+ name: true,+ logo_media_id: true,+ members_can_invite: true,+ members_can_create_projects: true,+ members_can_use_personal_api_keys: true,+ allow_publicly_shared_resources: true,+ is_ai_data_processing_approved: true,+ is_ai_training_opted_in: true,+ default_experiment_stats_method: true,+ default_anonymize_ips: true,+ default_role_id: true,+ }).shape+).extend({+ id: PartialUpdateParams.shape['id']+ .describe('Organization ID. If omitted, targets the active organization.')+ .optional(),+ enforce_2fa: PartialUpdateBody.shape['enforce_2fa']+ .unwrap()+ .describe(+ 'Set to true to require every organization member to have 2FA enabled; false to lift the requirement. Applies org-wide and takes effect immediately.'+ ),+})++const OrganizationEnforce2faSchemaExecute = z.strictObject({+ confirmation_hash: z+ .string()+ .describe('The confirmation_hash returned by the matching -prepare tool. Pass it back verbatim.'),+ confirmation: z.string().describe('The literal string "confirm", typed by the user in chat. Required to proceed.'),+})++const organizationEnforce2faPrepare = (): ToolBase<+ typeof OrganizationEnforce2faSchema,+ PrepareConfirmedActionResult+> => ({+ name: 'organization-enforce-2fa-prepare',+ schema: OrganizationEnforce2faSchema,+ handler: async (context: Context, params: z.infer<typeof OrganizationEnforce2faSchema>) => {+ const __runtime = getConfirmedActionRuntime()+ const id = params.id ?? (await context.stateManager.getOrgID())+ if (!id) {+ throw new Error('id is required. Provide it explicitly or set an active organization first.')+ }+ return await prepareConfirmedAction(context, {+ args: { ...params, id },+ purpose: 'organization-enforce-2fa',+ actionLabel: 'change 2FA enforcement',+ messageTemplate:+ "About to set organization-wide two-factor-authentication enforcement to {enforce_2fa}. This immediately affects every member of the organization — when enabled, all members must set up 2FA before they can continue using PostHog. Reply 'confirm' to proceed.\n",+ codec: __runtime.codec,+ })+ },+})++const organizationEnforce2faExecute = (): ToolBase<+ typeof OrganizationEnforce2faSchemaExecute,+ Schemas.Organization+> => ({+ name: 'organization-enforce-2fa-execute',+ schema: OrganizationEnforce2faSchemaExecute,+ handler: async (context: Context, confirmationParams: z.infer<typeof OrganizationEnforce2faSchemaExecute>) => {+ const __runtime = getConfirmedActionRuntime()+ const __guard = await executeConfirmedAction<z.infer<typeof OrganizationEnforce2faSchema>>(context, {+ incomingArgs: confirmationParams,+ purpose: 'organization-enforce-2fa',+ codec: __runtime.codec,+ ledger: __runtime.ledger,+ })+ if (!__guard.ok) {+ return __guard.result as never+ }+ const params = __guard.verifiedArgs+ const id = params.id ?? (await context.stateManager.getOrgID())+ if (!id) {+ throw new Error('id is required. Provide it explicitly or set an active organization first.')+ }+ const body: Record<string, unknown> = {}+ if (params.enforce_2fa !== undefined) {+ body['enforce_2fa'] = params.enforce_2fa+ }+ const result = await context.api.request<Schemas.Organization>({+ method: 'PATCH',+ path: `/api/organizations/${encodeURIComponent(String(id))}/`,+ body,+ })+ const filtered = pickResponseFields(result, ['enforce_2fa']) as typeof result+ return filtered+ },+})+const OrganizationGetSchema = RetrieveParams.extend({id: RetrieveParams.shape['id'].describe('Organization ID. If omitted, uses the active organization.').optional(),})@@ -493,6 +592,8 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'comments-list': commentsList,'org-member-get-github-login': orgMemberGetGithubLogin,'org-members-list': orgMembersList,+ 'organization-enforce-2fa-prepare': organizationEnforce2faPrepare,+ 'organization-enforce-2fa-execute': organizationEnforce2faExecute,'organization-get': organizationGet,'organizations-list': organizationsList,'role-get': roleGet,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/organization-enforce-2fa-execute.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/organization-enforce-2fa-execute.jsonnew file mode 100644index 000000000000..f9e863b2ae53--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/organization-enforce-2fa-execute.json@@ -0,0 +1,16 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "additionalProperties": false,+ "properties": {+ "confirmation": {+ "description": "The literal string \"confirm\", typed by the user in chat. Required to proceed.",+ "type": "string"+ },+ "confirmation_hash": {+ "description": "The confirmation_hash returned by the matching -prepare tool. Pass it back verbatim.",+ "type": "string"+ }+ },+ "required": ["confirmation_hash", "confirmation"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/organization-enforce-2fa-prepare.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/organization-enforce-2fa-prepare.jsonnew file mode 100644index 000000000000..d78d7ed2a734--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/organization-enforce-2fa-prepare.json@@ -0,0 +1,22 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "enforce_2fa": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "description": "Set to true to require every organization member to have 2FA enabled; false to lift the requirement. Applies org-wide and takes effect immediately."+ },+ "id": {+ "description": "Organization ID. If omitted, targets the active organization.",+ "type": "string"+ }+ },+ "required": ["enforce_2fa"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/generate-tools.test.ts b/services/mcp/tests/unit/generate-tools.test.tsindex d868a4f13aeb..250cd67c90bf 100644--- a/services/mcp/tests/unit/generate-tools.test.ts+++ b/services/mcp/tests/unit/generate-tools.test.ts@@ -2005,6 +2005,32 @@ describe('generateToolCode with confirmed_action', () => {'const params = __guard.verifiedArgs\n const projectId = await context.stateManager.getProjectId()')})++ it('resolves an omitted state-fallback id and signs it into the confirmed args (cross-org replay guard)', () => {+ // When the target id is optional with a state fallback, prepare must+ // resolve the active org/project to a concrete value and sign it, so a+ // switch-organization between prepare and execute can't retarget the+ // confirmed action at a different entity where the user is also an admin.+ const config: ToolConfig = {+ ...makeConfirmedConfig(),+ param_overrides: {+ id: { optional: true, fallback: 'orgId', description: 'Organization ID.' },+ },+ }+ const result = generateToolCode(+ 'organization-enforce-2fa-update',+ config,+ makePatchResolved(),+ defaultCategory,+ makeSpec(),+ new Set<string>(),+ stubGetQuerySchema+ )+ expect(result.code).toContain('const id = params.id ?? await context.stateManager.getOrgID()')+ expect(result.code).toContain('args: { ...params, id }')+ // The unresolved args object must not be what gets signed.+ expect(result.code).not.toContain('args: params,')+ })})describe('optional param with state fallback', () => {