: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(mcp-analytics): expose harness breakdown as an MCP query wrapper (#65366)
Paul D'Ambra3db61bf352ae
diff --git a/products/mcp_analytics/mcp/tools.yaml b/products/mcp_analytics/mcp/tools.yamlindex 18d5e93812ed..a38011d0230a 100644--- a/products/mcp_analytics/mcp/tools.yaml+++ b/products/mcp_analytics/mcp/tools.yaml@@ -106,3 +106,28 @@ tools:- blocked- attempted_toolfeature_flag: mcp-analytics+wrappers:+ query-mcp-harness-breakdown:+ schema_ref: MCPHarnessBreakdownQuery+ enabled: true+ scopes:+ - query:read+ - mcp_analytics:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Break down MCP tool calls by harness+ description: >+ Group this project's MCP tool-call activity by the resolved client harness — the friendly product label for+ the MCP client (Claude Agent SDK, Claude Code, OpenAI Codex, Cursor, Claude.ai, …). Returns calls, error+ count, error rate, and session count per harness. Accepts the same dateRange / properties /+ filterTestAccounts filters as the dashboard and resolves the harness server-side over the same query runner,+ so results match the UI exactly. Use to answer "which harnesses use our MCP, and how reliably?".+ system_prompt_hint: MCP client/harness breakdown — calls, error rate, sessions per harness+ exclude_properties:+ - response+ - modifiers+ - version+ - tags+ feature_flag: mcp-analyticsdiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 8c8da5a724d3..3bceab360564 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -5717,6 +5717,22 @@},"system_prompt_hint": "Log filtering by severity/service/attribute"},+ "query-mcp-harness-breakdown": {+ "description": "Group this project's MCP tool-call activity by the resolved client harness — the friendly product label for the MCP client (Claude Agent SDK, Claude Code, OpenAI Codex, Cursor, Claude.ai, …). Returns calls, error count, error rate, and session count per harness. Accepts the same dateRange / properties / filterTestAccounts filters as the dashboard and resolves the harness server-side over the same query runner, so results match the UI exactly. Use to answer \"which harnesses use our MCP, and how reliably?\".",+ "category": "MCP analytics",+ "feature": "mcp_analytics",+ "summary": "Break down MCP tool calls by harness",+ "title": "Break down MCP tool calls by harness",+ "required_scopes": ["query:read", "mcp_analytics:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "mcp-analytics",+ "system_prompt_hint": "MCP client/harness breakdown — calls, error rate, sessions per harness"+ },"query-metrics": {"description": "Query server/infrastructure metrics (OTel- or Prometheus-ingested) as bucketed time series. The response is a list of series — `{labels, points: [{time, value}], metric_name, clause}` — where every series shares one time grid (missing buckets are zero-filled). A single ungrouped query returns exactly one series with empty labels.\n\nAll parameters are nested inside a `query` object. Two request forms:\n\n- **Single metric (shorthand):** set `metricName` (+ `aggregation`, `filters`, `groupBy`).\n- **Multi-clause / formula:** set `clauses: [{name, metricName, aggregation, quantile?, filters?, groupBy?}, ...]` and optionally `formula` (e.g. `\"(a - b) / a\"` over clause names; `+ - * /` and parentheses; division by zero yields 0). With a formula set, only the formula result series are returned.\n\n# Workflow — follow this order every time\n\n1. **Discover names first.** Call `metric-names-list` with a substring (`value`) before querying — metric names must match exactly, and the returned `metric_type` tells you the right aggregation.\n2. **Pick the aggregation by metric type:**\n - `sum` counters (usually `_total`): use `rate` (per-second) or `increase` — both are counter-reset safe and temporality-aware. Do NOT use `sum`/`avg` on cumulative counters; absolute counter values are meaningless.\n - `gauge`: `avg` (typical), `p95`, `sum`.\n - `histogram`: `histogram_quantile` with `quantile` (e.g. 0.95). All selected series must share one bucket layout — narrow with `filters` if you get a bounds-mismatch error.\n3. **Narrow with filters.** `filters: [{key, op, value, scope?}]`, ANDed. Ops: `eq`, `neq`, `regex`, `not_regex` (RE2). Leave `scope` at its default `auto` unless you know whether the attribute is per-target (`resource`) or per-datapoint (`attribute`). Negative ops also match rows lacking the key, like Prometheus negative matchers.\n4. **Split with groupBy.** `groupBy: [{key}]` returns one series per label value (capped at the 100 largest). `service_name` is always available; discover other keys from a sample query's labels or ask the user.\n5. **Control the grid with `interval`.** One of `second, minute, minute_5, minute_15, hour, hour_6, day, week`. Omit to auto-pick (~60 buckets across the range). Use the same interval when comparing windows.\n\n# Investigating an anomaly (\"metric X is rising — why?\")\n\n1. Query the metric over a window that includes the anomaly AND an equal-length healthy baseline before it (one call, auto interval).\n2. Find the onset: the first bucket where the value clearly departs from the baseline range.\n3. Re-query grouped by `service_name` (then by other candidate keys) over the same window to see WHICH series moved — a single label value moving points at the culprit; all moving together points at something shared (upstream dependency, infra).\n4. Use `formula` for normalized comparisons, e.g. error ratio `errors / requests` instead of raw error counts.\n5. Correlate the onset window across signals: query logs (`query-logs`, filtered to the same `service.name` and time window, severity error) and traces (APM span tools, same service/window) to find the cause and its blast radius.\n\nCRITICAL: be minimalist — only include filters/settings essential to the question. Time ranges: `dateFrom` is required, ISO 8601; `dateTo` defaults to now.","category": "Metrics",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 924b45303700..1ccf179f1938 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -6168,6 +6168,22 @@},"system_prompt_hint": "Log filtering by severity/service/attribute"},+ "query-mcp-harness-breakdown": {+ "description": "Group this project's MCP tool-call activity by the resolved client harness — the friendly product label for the MCP client (Claude Agent SDK, Claude Code, OpenAI Codex, Cursor, Claude.ai, …). Returns calls, error count, error rate, and session count per harness. Accepts the same dateRange / properties / filterTestAccounts filters as the dashboard and resolves the harness server-side over the same query runner, so results match the UI exactly. Use to answer \"which harnesses use our MCP, and how reliably?\".",+ "category": "MCP analytics",+ "feature": "mcp_analytics",+ "summary": "Break down MCP tool calls by harness",+ "title": "Break down MCP tool calls by harness",+ "required_scopes": ["query:read", "mcp_analytics:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "mcp-analytics",+ "system_prompt_hint": "MCP client/harness breakdown — calls, error rate, sessions per harness"+ },"query-metrics": {"description": "Query server/infrastructure metrics (OTel- or Prometheus-ingested) as bucketed time series. The response is a list of series — `{labels, points: [{time, value}], metric_name, clause}` — where every series shares one time grid (missing buckets are zero-filled). A single ungrouped query returns exactly one series with empty labels.\n\nAll parameters are nested inside a `query` object. Two request forms:\n\n- **Single metric (shorthand):** set `metricName` (+ `aggregation`, `filters`, `groupBy`).\n- **Multi-clause / formula:** set `clauses: [{name, metricName, aggregation, quantile?, filters?, groupBy?}, ...]` and optionally `formula` (e.g. `\"(a - b) / a\"` over clause names; `+ - * /` and parentheses; division by zero yields 0). With a formula set, only the formula result series are returned.\n\n# Workflow — follow this order every time\n\n1. **Discover names first.** Call `metric-names-list` with a substring (`value`) before querying — metric names must match exactly, and the returned `metric_type` tells you the right aggregation.\n2. **Pick the aggregation by metric type:**\n - `sum` counters (usually `_total`): use `rate` (per-second) or `increase` — both are counter-reset safe and temporality-aware. Do NOT use `sum`/`avg` on cumulative counters; absolute counter values are meaningless.\n - `gauge`: `avg` (typical), `p95`, `sum`.\n - `histogram`: `histogram_quantile` with `quantile` (e.g. 0.95). All selected series must share one bucket layout — narrow with `filters` if you get a bounds-mismatch error.\n3. **Narrow with filters.** `filters: [{key, op, value, scope?}]`, ANDed. Ops: `eq`, `neq`, `regex`, `not_regex` (RE2). Leave `scope` at its default `auto` unless you know whether the attribute is per-target (`resource`) or per-datapoint (`attribute`). Negative ops also match rows lacking the key, like Prometheus negative matchers.\n4. **Split with groupBy.** `groupBy: [{key}]` returns one series per label value (capped at the 100 largest). `service_name` is always available; discover other keys from a sample query's labels or ask the user.\n5. **Control the grid with `interval`.** One of `second, minute, minute_5, minute_15, hour, hour_6, day, week`. Omit to auto-pick (~60 buckets across the range). Use the same interval when comparing windows.\n\n# Investigating an anomaly (\"metric X is rising — why?\")\n\n1. Query the metric over a window that includes the anomaly AND an equal-length healthy baseline before it (one call, auto interval).\n2. Find the onset: the first bucket where the value clearly departs from the baseline range.\n3. Re-query grouped by `service_name` (then by other candidate keys) over the same window to see WHICH series moved — a single label value moving points at the culprit; all moving together points at something shared (upstream dependency, infra).\n4. Use `formula` for normalized comparisons, e.g. error ratio `errors / requests` instead of raw error counts.\n5. Correlate the onset window across signals: query logs (`query-logs`, filtered to the same `service.name` and time window, severity error) and traces (APM span tools, same service/window) to find the cause and its blast radius.\n\nCRITICAL: be minimalist — only include filters/settings essential to the question. Time ranges: `dateFrom` is required, ISO 8601; `dateTo` defaults to now.","category": "Metrics",diff --git a/services/mcp/src/tools/generated/mcp_analytics.ts b/services/mcp/src/tools/generated/mcp_analytics.tsindex c6f35dddfee3..514de2024bd2 100644--- a/services/mcp/src/tools/generated/mcp_analytics.ts+++ b/services/mcp/src/tools/generated/mcp_analytics.ts@@ -7,6 +7,7 @@ import {McpAnalyticsMissingCapabilitiesCreateBody,McpAnalyticsSessionsGenerateIntentParams,} from '@/generated/mcp_analytics/api'+import { createQueryWrapper } from '@/tools/query-wrapper-factory'import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'const McpAnalyticsIntentClustersRecomputeSchema = z.object({})@@ -140,10 +141,278 @@ const mcpMissingCapabilityReport = (): ToolBase<},})+// --- Query wrapper schemas from schema.json ---++const DateRange = z.object({+ date_from: z+ .string()+ .nullable()+ .describe(+ 'Start of the date range. Accepts ISO 8601 timestamps (e.g., 2024-01-15T00:00:00Z) or relative formats: -7d (7 days ago), -2w (2 weeks ago), -1m (1 month ago),\n-1h (1 hour ago), -1mStart (start of last month), -1yStart (start of last year).'+ )+ .optional(),+ date_to: z+ .string()+ .nullable()+ .describe('End of the date range. Same format as date_from. Omit or null for "now".')+ .optional(),+ explicitDate: z.coerce+ .boolean()+ .nullable()+ .describe(+ 'Whether the date_from and date_to should be used verbatim. Disables rounding to the start and end of period.'+ )+ .default(false)+ .optional(),+})++const PropertyOperator = z.enum([+ 'exact',+ 'is_not',+ 'icontains',+ 'not_icontains',+ 'regex',+ 'not_regex',+ 'gt',+ 'gte',+ 'lt',+ 'lte',+ 'is_set',+ 'is_not_set',+ 'is_date_exact',+ 'is_date_before',+ 'is_date_after',+ 'between',+ 'not_between',+ 'min',+ 'max',+ 'in',+ 'not_in',+ 'is_cleaned_path_exact',+ 'flag_evaluates_to',+ 'semver_eq',+ 'semver_neq',+ 'semver_gt',+ 'semver_gte',+ 'semver_lt',+ 'semver_lte',+ 'semver_tilde',+ 'semver_caret',+ 'semver_wildcard',+ 'icontains_multi',+ 'not_icontains_multi',+])++const PropertyFilterBaseValue = z.union([z.string(), z.coerce.number(), z.coerce.boolean()])++const PropertyFilterValue = z.union([PropertyFilterBaseValue, z.array(PropertyFilterBaseValue), z.null()])++const EventPropertyFilter = z.object({+ key: z.string(),+ label: z.string().optional(),+ operator: PropertyOperator.default('exact'),+ type: z.literal('event').describe('Event properties').default('event'),+ value: PropertyFilterValue.optional(),+})++const PersonPropertyFilter = z.object({+ key: z.string(),+ label: z.string().optional(),+ operator: PropertyOperator,+ type: z.literal('person').describe('Person properties').default('person'),+ value: PropertyFilterValue.optional(),+})++const ElementPropertyFilter = z.object({+ key: z.enum(['tag_name', 'text', 'href', 'selector']),+ label: z.string().optional(),+ operator: PropertyOperator,+ type: z.literal('element').default('element'),+ value: PropertyFilterValue.optional(),+})++const EventMetadataPropertyFilter = z.object({+ key: z.string(),+ label: z.string().optional(),+ operator: PropertyOperator,+ type: z.literal('event_metadata').default('event_metadata'),+ value: PropertyFilterValue.optional(),+})++const SessionPropertyFilter = z.object({+ key: z.string(),+ label: z.string().optional(),+ operator: PropertyOperator,+ type: z.literal('session').default('session'),+ value: PropertyFilterValue.optional(),+})++const CohortPropertyFilter = z.object({+ cohort_name: z.string().optional(),+ key: z.literal('id').default('id'),+ label: z.string().optional(),+ operator: PropertyOperator.default('in'),+ type: z.literal('cohort').default('cohort'),+ value: z.coerce.number().int(),+})++const DurationType = z.enum(['duration', 'active_seconds', 'inactive_seconds'])++const RecordingPropertyFilter = z.object({+ key: z.union([DurationType, z.literal('snapshot_source'), z.literal('visited_page'), z.literal('comment_text')]),+ label: z.string().optional(),+ operator: PropertyOperator,+ type: z.literal('recording').default('recording'),+ value: PropertyFilterValue.optional(),+})++const LogEntryPropertyFilter = z.object({+ key: z.string(),+ label: z.string().optional(),+ operator: PropertyOperator,+ type: z.literal('log_entry').default('log_entry'),+ value: PropertyFilterValue.optional(),+})++const GroupPropertyFilter = z.object({+ group_key_names: z.record(z.string(), z.string()).optional(),+ group_type_index: z.union([z.coerce.number().int(), z.null()]).optional(),+ key: z.string(),+ label: z.string().optional(),+ operator: PropertyOperator,+ type: z.literal('group').default('group'),+ value: PropertyFilterValue.optional(),+})++const FeaturePropertyFilter = z.object({+ key: z.string(),+ label: z.string().optional(),+ operator: PropertyOperator,+ type: z.literal('feature').describe('Event property with "$feature/" prepended').default('feature'),+ value: PropertyFilterValue.optional(),+})++const FlagPropertyFilter = z.object({+ key: z.string().describe('The key should be the flag ID'),+ label: z.string().optional(),+ operator: z+ .literal('flag_evaluates_to')+ .describe('Only flag_evaluates_to operator is allowed for flag dependencies')+ .default('flag_evaluates_to'),+ type: z.literal('flag').describe('Feature flag dependency').default('flag'),+ value: z.union([z.coerce.boolean(), z.string()]).describe('The value can be true, false, or a variant name'),+})++const HogQLPropertyFilter = z.object({+ key: z.string(),+ label: z.string().optional(),+ type: z.literal('hogql').default('hogql'),+ value: PropertyFilterValue.optional(),+})++const EmptyPropertyFilter = z.object({+ type: z.literal('empty').default('empty').optional(),+})++const DataWarehousePropertyFilter = z.object({+ key: z.string(),+ label: z.string().optional(),+ operator: PropertyOperator,+ type: z.literal('data_warehouse').default('data_warehouse'),+ value: PropertyFilterValue.optional(),+})++const DataWarehousePersonPropertyFilter = z.object({+ key: z.string(),+ label: z.string().optional(),+ operator: PropertyOperator,+ type: z.literal('data_warehouse_person_property').default('data_warehouse_person_property'),+ value: PropertyFilterValue.optional(),+})++const ErrorTrackingIssueFilter = z.object({+ key: z.string(),+ label: z.string().optional(),+ operator: PropertyOperator,+ type: z.literal('error_tracking_issue').default('error_tracking_issue'),+ value: PropertyFilterValue.optional(),+})++const LogPropertyFilterType = z.enum(['log', 'log_attribute', 'log_resource_attribute'])++const LogPropertyFilter = z.object({+ key: z.string(),+ label: z.string().optional(),+ operator: PropertyOperator,+ type: LogPropertyFilterType,+ value: PropertyFilterValue.optional(),+})++const SpanPropertyFilterType = z.enum(['span', 'span_attribute', 'span_resource_attribute'])++const SpanPropertyFilter = z.object({+ key: z.string(),+ label: z.string().optional(),+ operator: PropertyOperator,+ type: SpanPropertyFilterType,+ value: PropertyFilterValue.optional(),+})++const RevenueAnalyticsPropertyFilter = z.object({+ key: z.string(),+ label: z.string().optional(),+ operator: PropertyOperator,+ type: z.literal('revenue_analytics').default('revenue_analytics'),+ value: PropertyFilterValue.optional(),+})++const WorkflowVariablePropertyFilter = z.object({+ key: z.string(),+ label: z.string().optional(),+ operator: PropertyOperator,+ type: z.literal('workflow_variable').default('workflow_variable'),+ value: PropertyFilterValue.optional(),+})++const AnyPropertyFilter = z.union([+ EventPropertyFilter,+ PersonPropertyFilter,+ ElementPropertyFilter,+ EventMetadataPropertyFilter,+ SessionPropertyFilter,+ CohortPropertyFilter,+ RecordingPropertyFilter,+ LogEntryPropertyFilter,+ GroupPropertyFilter,+ FeaturePropertyFilter,+ FlagPropertyFilter,+ HogQLPropertyFilter,+ EmptyPropertyFilter,+ DataWarehousePropertyFilter,+ DataWarehousePersonPropertyFilter,+ ErrorTrackingIssueFilter,+ LogPropertyFilter,+ SpanPropertyFilter,+ RevenueAnalyticsPropertyFilter,+ WorkflowVariablePropertyFilter,+])++const MCPHarnessBreakdownQuery = z.object({+ dateRange: DateRange.optional(),+ filterTestAccounts: z.coerce.boolean().optional(),+ kind: z.literal('MCPHarnessBreakdownQuery').default('MCPHarnessBreakdownQuery'),+ properties: z.array(AnyPropertyFilter).optional(),+})+export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'mcp-analytics-intent-clusters-recompute': mcpAnalyticsIntentClustersRecompute,'mcp-analytics-intent-clusters-retrieve': mcpAnalyticsIntentClustersRetrieve,'mcp-analytics-sessions-generate-intent': mcpAnalyticsSessionsGenerateIntent,'mcp-feedback-submit': mcpFeedbackSubmit,'mcp-missing-capability-report': mcpMissingCapabilityReport,+ 'query-mcp-harness-breakdown': createQueryWrapper({+ name: 'query-mcp-harness-breakdown',+ schema: MCPHarnessBreakdownQuery,+ kind: 'MCPHarnessBreakdownQuery',+ }),}