: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(mcp): list accepted billing usage types (#105798)
Pawel Cebulaf6d693bc2a38
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.mdindex 7b11ecdd3306..2fd9e1f0abb6 100644--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md@@ -150,6 +150,12 @@ codes and public request fields, replaces upstream messages with controlled textand masks unrecognized failures. The shared MCP client handles these errors withouta billing-specific tool wrapper.+The billing usage/spend tools accept `usage_types` as an array of strings.+Their field description lists the accepted identifiers from `ee/billing/billing_types.py`, through the generated API schema.+The MCP client JSON-encodes the array for the HTTP API.+The billing overview, usage, and spend tools do not need a rollout flag.+API scopes and billing access checks still apply.+System tables are defined in [`posthog/hogql/database/schema/system.py`](https://github.com/PostHog/posthog/blob/master/posthog/hogql/database/schema/system.py) as `PostgresTable` instances.Each table must include a `team_id` column for data isolation.diff --git a/products/billing/mcp/tools.yaml b/products/billing/mcp/tools.yamlindex b20daa03a865..d6480f46c6b4 100644--- a/products/billing/mcp/tools.yaml+++ b/products/billing/mcp/tools.yaml@@ -144,7 +144,6 @@ tools:exclude_params:- limit- offset- feature_flag: billing-mcp-read-toolsurl_prefix: /organization/billing/overviewresponse:exclude:@@ -286,7 +285,6 @@ tools:project, which is the default and the right choice for most questions. Set it only when anorganization has enough projects that the full response is unwieldy, and say so in your answer,because a limited response names only the largest spenders.- feature_flag: billing-mcp-read-toolsurl_prefix: /organization/billing/spendresponse:informational_wrapper:@@ -463,7 +461,6 @@ tools:description: >The `next` cursor from the previous page. Opaque - do not construct one. Omit it for the first page,and stop when a response comes back with `next` null.- feature_flag: billing-mcp-read-toolsurl_prefix: /organization/billing/usageresponse:informational_wrapper:diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 0713e496b1ce..735468a72490 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -1156,8 +1156,7 @@"idempotentHint": true,"openWorldHint": true,"readOnlyHint": true- },- "feature_flag": "billing-mcp-read-tools"+ }},"billing-product-get": {"description": "One product by key, for example product_analytics or session_replay, with its add-ons, features, price schedule and subscribed state. Call billing-products-summary-get first to find the key. Pass include_plans=true for the plan list. Readable by any member. Beta: behind the organization-billing-api flag, and the output shape may change while it is.",@@ -1216,8 +1215,7 @@"idempotentHint": true,"openWorldHint": true,"readOnlyHint": true- },- "feature_flag": "billing-mcp-read-tools"+ }},"billing-spend-summary-get": {"description": "Amounts accrued so far this billing period, before and after discount, per product, add-on and tier, with the two totals. An organization total, so it needs full billing access: owners always, and admins when owner-only billing is off. Use it for \"what have we spent so far this month\". For the projection to the end of the period call billing-forecast-get, and for spend over time call billing-spend-timeseries-get. Beta: behind the organization-billing-api flag, and the output shape may change while it is.",@@ -1276,8 +1274,7 @@"idempotentHint": true,"openWorldHint": true,"readOnlyHint": true- },- "feature_flag": "billing-mcp-read-tools"+ }},"billing-usage-status-get": {"description": "Per product and add-on: the limit in effect, whether usage is over or approaching it, and whether the resource is being limited right now. No counts, so any member can read it. Use it for \"am I near my events limit\" or \"is ingestion being limited\"; for the counts call billing-usage-summary-get. Beta: behind the organization-billing-api flag, and the output shape may change while it is.",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex c84f6f6e2d15..21f83b8ae844 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -1171,8 +1171,7 @@"idempotentHint": true,"openWorldHint": true,"readOnlyHint": true- },- "feature_flag": "billing-mcp-read-tools"+ }},"billing-product-get": {"description": "One product by key, for example product_analytics or session_replay, with its add-ons, features, price schedule and subscribed state. Call billing-products-summary-get first to find the key. Pass include_plans=true for the plan list. Readable by any member. Beta: behind the organization-billing-api flag, and the output shape may change while it is.",@@ -1231,8 +1230,7 @@"idempotentHint": true,"openWorldHint": true,"readOnlyHint": true- },- "feature_flag": "billing-mcp-read-tools"+ }},"billing-spend-summary-get": {"description": "Amounts accrued so far this billing period, before and after discount, per product, add-on and tier, with the two totals. An organization total, so it needs full billing access: owners always, and admins when owner-only billing is off. Use it for \"what have we spent so far this month\". For the projection to the end of the period call billing-forecast-get, and for spend over time call billing-spend-timeseries-get. Beta: behind the organization-billing-api flag, and the output shape may change while it is.",@@ -1291,8 +1289,7 @@"idempotentHint": true,"openWorldHint": true,"readOnlyHint": true- },- "feature_flag": "billing-mcp-read-tools"+ }},"billing-usage-status-get": {"description": "Per product and add-on: the limit in effect, whether usage is over or approaching it, and whether the resource is being limited right now. No counts, so any member can read it. Use it for \"am I near my events limit\" or \"is ingestion being limited\"; for the counts call billing-usage-summary-get. Beta: behind the organization-billing-api flag, and the output shape may change while it is.",diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.jsonindex 3f4c21893920..dfe2cfe5d49a 100644--- a/services/mcp/schema/tool-inputs.json+++ b/services/mcp/schema/tool-inputs.json@@ -62,7 +62,7 @@]},"BillingUsageTypesSchema": {- "description": "Usage type identifiers to filter by, e.g. `[\"event_count_in_period\"]` or `[\"event_count_in_period\",\"recording_count_in_period\"]`. Omit for all usage types.",+ "description": "Array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_mb_in_period, logs_retention_30d_mb_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. [\"event_count_in_period\",\"recording_count_in_period\"]. Omit for all types.","anyOf": [{"type": "array",diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.tsindex bd083cee904f..d4759f775edd 100644--- a/services/mcp/src/schema/tool-inputs.ts+++ b/services/mcp/src/schema/tool-inputs.ts@@ -1,5 +1,6 @@import { z } from 'zod'+import { BillingUsageRetrieveQueryParams } from '../generated/billing/api'// Relative (not `@/`) imports: this module is loaded by the tsx schema-generation// script, and both modules are pure constants/functions — no `.md` imports to choke on.import { castStringToInt, normalizeParamAliases } from '../tools/cast-helpers'@@ -102,9 +103,7 @@ export const BillingTeamIdsSchema = zexport const BillingUsageTypesSchema = z.array(z.string().min(1)).nullish()- .describe(- 'Usage type identifiers to filter by, e.g. `["event_count_in_period"]` or `["event_count_in_period","recording_count_in_period"]`. Omit for all usage types.'- )+ .describe(BillingUsageRetrieveQueryParams().shape.usage_types.description!.replace('JSON-encoded array', 'Array'))export const BillingSpendBreakdownsSchema = z.array(z.enum(['type', 'team']))diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-spend-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-spend-get.jsonindex 96a6eb93dd85..2f16f5da6410 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-spend-get.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-spend-get.json@@ -116,7 +116,7 @@"type": "null"}],- "description": "Usage type identifiers to filter by, e.g. `[\"event_count_in_period\"]` or `[\"event_count_in_period\",\"recording_count_in_period\"]`. Omit for all usage types."+ "description": "Array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_mb_in_period, logs_retention_30d_mb_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. [\"event_count_in_period\",\"recording_count_in_period\"]. Omit for all types."}},"type": "object"diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-usage-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-usage-get.jsonindex 4460a4e385eb..3266a9951df0 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-usage-get.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-usage-get.json@@ -116,7 +116,7 @@"type": "null"}],- "description": "Usage type identifiers to filter by, e.g. `[\"event_count_in_period\"]` or `[\"event_count_in_period\",\"recording_count_in_period\"]`. Omit for all usage types."+ "description": "Array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_mb_in_period, logs_retention_30d_mb_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. [\"event_count_in_period\",\"recording_count_in_period\"]. Omit for all types."}},"type": "object"diff --git a/services/mcp/tests/unit/billing-filter-schema.test.ts b/services/mcp/tests/unit/billing-filter-schema.test.tsindex 8b5658dc1c1f..d9183336a91c 100644--- a/services/mcp/tests/unit/billing-filter-schema.test.ts+++ b/services/mcp/tests/unit/billing-filter-schema.test.ts@@ -1,8 +1,21 @@import { describe, expect, it } from 'vitest'+import { z } from 'zod'import { GENERATED_TOOLS } from '@/tools/generated/billing'describe('billing usage filters', () => {+ it.each(['billing-spend-get', 'billing-usage-get'])('%s documents usage types for array inputs', (toolName) => {+ const schema = z.toJSONSchema(GENERATED_TOOLS[toolName]!().schema)+ const usageTypes = schema.properties!.usage_types!++ expect(usageTypes).toHaveProperty('description', expect.stringContaining('survey_responses_count_in_period'))+ expect(usageTypes).not.toHaveProperty('description', expect.stringContaining('JSON-encoded'))+ expect(usageTypes).toMatchObject({+ anyOf: [{ type: 'array', items: { type: 'string' } }, { type: 'null' }],+ })+ expect(schema.required ?? []).not.toContain('usage_types')+ })+it.each(['billing-spend-get', 'billing-usage-get'])('%s accepts null filters', (toolName) => {const input = { team_ids: null, usage_types: null, breakdowns: null }const result = GENERATED_TOOLS[toolName]!().schema.safeParse(input)diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.tsindex 41536518d761..2dc2d8ac3564 100644--- a/services/mcp/tests/unit/tool-filtering.test.ts+++ b/services/mcp/tests/unit/tool-filtering.test.ts@@ -292,6 +292,18 @@ const createMockContext = (})describe('Tool Filtering - API Scopes', () => {+ it.each([+ { scopes: ['billing:read'], visible: true },+ { scopes: [], visible: false },+ ])('billing read tools require a scope but no rollout flag: $visible', async ({ scopes, visible }) => {+ const tools = await getToolsFromContext(createMockContext(scopes), { featureFlags: {} })+ const names = tools.map((tool) => tool.name)++ for (const name of ['billing-overview-get', 'billing-usage-get', 'billing-spend-get']) {+ expect(names.includes(name)).toBe(visible)+ }+ })+it('should return all tools when user has * scope', async () => {const context = createMockContext(['*'])const tools = await getToolsFromContext(context)@@ -915,19 +927,6 @@ describe('Tool Filtering - Feature Flags', () => {expect(on).not.toContain('notebooks-partial-update')})- it('billing-mcp-read-tools flag gates the existing billing read tools', () => {- const existing = ['billing-overview-get', 'billing-usage-get', 'billing-spend-get']- const off = getToolsForFeatures({ featureFlags: { 'billing-mcp-read-tools': false } })- for (const tool of existing) {- expect(off).not.toContain(tool)- }-- const on = getToolsForFeatures({ featureFlags: { 'billing-mcp-read-tools': true } })- for (const tool of existing) {- expect(on).toContain(tool)- }- })-it('organization-billing-api flag gates the tools that call the organization billing API', () => {const gated = ['billing-subscription-get',@@ -1023,7 +1022,6 @@ describe('Tool Filtering - Feature Flags', () => {'review-hog','warehouse-person-properties','billing-alerts',- 'billing-mcp-read-tools','organization-billing-api','streamlit-apps','posthog-connect',@@ -1035,7 +1033,7 @@ describe('Tool Filtering - Feature Flags', () => {'warehouse-multi-destination',]))- expect(flags).toHaveLength(37)+ expect(flags).toHaveLength(36)})it('every loops tool is gated on the loops flag', () => {diff --git a/services/mcp/tests/unit/tool-schema-snapshots.test.ts b/services/mcp/tests/unit/tool-schema-snapshots.test.tsindex ca8aeb9bf02e..2fc70c12c685 100644--- a/services/mcp/tests/unit/tool-schema-snapshots.test.ts+++ b/services/mcp/tests/unit/tool-schema-snapshots.test.ts@@ -90,7 +90,7 @@ describe('Tool schema snapshots', () => {const shouldUpdateSnapshots = isSnapshotUpdateAll()const root = path.resolve(__dirname, '__snapshots__', 'tool-schemas')// Enable flag-gated tools we snapshot here: tracing (APM spans), tasks, loops,- // dashboard-widgets, billing read tools, and experiment setup context. Other flag-gated tools (logs-alerts,+ // dashboard-widgets and experiment setup context. Other flag-gated tools (logs-alerts,// visual-review, etc.) stay off to keep the surface stable.// agent-feedback is always_available and no longer flag-gated, so it appears regardless.const featureFlags = {@@ -101,7 +101,6 @@ describe('Tool schema snapshots', () => {'dashboard-widgets': true,'agent-platform': true,'billing-alerts': true,- 'billing-mcp-read-tools': true,'experiment-setup-context': true,}const tools = [...(await getToolsFromContext(context, { featureFlags }))].sort((a, b) =>