Skip to content

: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.

feat(metrics): expose query-metrics and metric-names-list MCP tools (#63130)

Daniel Visca791bd0465f84
diff --git a/posthog/api/oauth/test_dcr.py b/posthog/api/oauth/test_dcr.py
index b27bfc711cf4..4770474fea1b 100644
--- a/posthog/api/oauth/test_dcr.py
+++ b/posthog/api/oauth/test_dcr.py
@@ -383,7 +383,7 @@ class TestDynamicClientRegistration(APIBaseTest):
("strips_internal", "experiment:read signal_scout_internal:write", ["experiment:read"], "experiment:read"),
(
"strips_hidden",
- "experiment:read metrics:read wizard_session:write",
+ "experiment:read wizard_session:write",
["experiment:read"],
"experiment:read",
),
@@ -420,7 +420,7 @@ class TestDynamicClientRegistration(APIBaseTest):
@parameterized.expand(
[
("only_privileged", "llm_gateway:read llm_gateway:write"),
- ("only_internal_hidden_junk", "signal_scout_internal:write metrics:read not_a_real:scope"),
+ ("only_internal_hidden_junk", "signal_scout_internal:write wizard_session:read not_a_real:scope"),
]
)
def test_register_with_only_ungrantable_scopes_is_rejected(self, _name, scope):
diff --git a/posthog/scopes.py b/posthog/scopes.py
index be1dc5ac8fd5..e60d933b5947 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -144,7 +144,7 @@ INTERNAL_API_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset(
# OAuth metadata. Used for alpha / not-yet-public products where a user can
# manually paste the scope into a PAT but where we don't want OAuth-based
# clients (the consent screen, MCP, third-party apps) to discover it.
-OAUTH_HIDDEN_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset({"metrics", "wizard_session"})
+OAUTH_HIDDEN_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset({"wizard_session"})
PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION: list[tuple[APIScopeObject, APIScopeActions]] = [
("endpoint", "read"),
diff --git a/products/metrics/mcp/prompts/metric-names-list.md b/products/metrics/mcp/prompts/metric-names-list.md
new file mode 100644
index 000000000000..0569980f5b36
--- /dev/null
+++ b/products/metrics/mcp/prompts/metric-names-list.md
@@ -0,0 +1,9 @@
+List the distinct metric names this project has ingested, with each metric's OTel type (`gauge`, `sum`, `histogram`, `summary`, `exponential_histogram`). Names are ordered by recent activity and exact matches float to the top.
+
+ALWAYS call this before `query-metrics` unless you already know the exact metric name — metric queries match names exactly, so a guessed name silently returns no data.
+
+Use `value` for a case-insensitive substring search (e.g. `value: "lag"` finds `metrics_rate_limiter_message_lag_seconds`). The metric's type tells you which aggregations make sense:
+
+- `sum` (counters, usually `_total`-suffixed): use `rate` or `increase`
+- `gauge`: use `avg`, `p95`, or `sum`
+- `histogram`: use `histogram_quantile` with a `quantile`
diff --git a/products/metrics/mcp/prompts/query-metrics.md b/products/metrics/mcp/prompts/query-metrics.md
new file mode 100644
index 000000000000..5c6d12cd9e5d
--- /dev/null
+++ b/products/metrics/mcp/prompts/query-metrics.md
@@ -0,0 +1,27 @@
+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.
+
+All parameters are nested inside a `query` object. Two request forms:
+
+- **Single metric (shorthand):** set `metricName` (+ `aggregation`, `filters`, `groupBy`).
+- **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.
+
+# Workflow — follow this order every time
+
+1. **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.
+2. **Pick the aggregation by metric type:**
+ - `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.
+ - `gauge`: `avg` (typical), `p95`, `sum`.
+ - `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.
+3. **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.
+4. **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.
+5. **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.
+
+# Investigating an anomaly ("metric X is rising — why?")
+
+1. Query the metric over a window that includes the anomaly AND an equal-length healthy baseline before it (one call, auto interval).
+2. Find the onset: the first bucket where the value clearly departs from the baseline range.
+3. 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).
+4. Use `formula` for normalized comparisons, e.g. error ratio `errors / requests` instead of raw error counts.
+5. 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.
+
+CRITICAL: be minimalist — only include filters/settings essential to the question. Time ranges: `dateFrom` is required, ISO 8601; `dateTo` defaults to now.
diff --git a/products/metrics/mcp/tools.yaml b/products/metrics/mcp/tools.yaml
new file mode 100644
index 000000000000..9a4d065e5344
--- /dev/null
+++ b/products/metrics/mcp/tools.yaml
@@ -0,0 +1,46 @@
+# MCP tool definition — tool entries are scaffolded from the OpenAPI schema.
+# The tool list and operation IDs are kept in sync automatically:
+# pnpm --filter=@posthog/mcp run scaffold-yaml -- --sync-all
+#
+# To enable a tool, set enabled: true and add required scopes + annotations.
+# All other fields (title, description, enrich_url, etc.) are yours to configure.
+category: Metrics
+feature: metrics
+url_prefix: /metrics
+ui_apps: {}
+tools:
+ metric-names-list:
+ operation: metrics_values_retrieve
+ enabled: true
+ scopes:
+ - metrics:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: List metric names
+ description_file: ./prompts/metric-names-list.md
+ system_prompt_hint: Discover which server/infrastructure metrics exist before querying them
+ feature_flag: metrics
+ response:
+ include:
+ - results
+ metrics-has-metrics-retrieve:
+ operation: metrics_has_metrics_retrieve
+ enabled: false
+ query-metrics:
+ operation: metrics_query_create
+ enabled: true
+ scopes:
+ - metrics:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Query metrics
+ description_file: ./prompts/query-metrics.md
+ system_prompt_hint: Server/infrastructure metrics (OTel/Prometheus) — time series, rates, quantiles, formulas
+ feature_flag: metrics
+ response:
+ include:
+ - results
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 0d344e4ec3c3..7cc9f04228ab 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -4883,6 +4883,22 @@
},
"feature_flag": "mcp-analytics"
},
+ "metric-names-list": {
+ "description": "List the distinct metric names this project has ingested, with each metric's OTel type (`gauge`, `sum`, `histogram`, `summary`, `exponential_histogram`). Names are ordered by recent activity and exact matches float to the top.\n\nALWAYS call this before `query-metrics` unless you already know the exact metric name — metric queries match names exactly, so a guessed name silently returns no data.\n\nUse `value` for a case-insensitive substring search (e.g. `value: \"lag\"` finds `metrics_rate_limiter_message_lag_seconds`). The metric's type tells you which aggregations make sense:\n\n- `sum` (counters, usually `_total`-suffixed): use `rate` or `increase`\n- `gauge`: use `avg`, `p95`, or `sum`\n- `histogram`: use `histogram_quantile` with a `quantile`",
+ "category": "Metrics",
+ "feature": "metrics",
+ "summary": "List metric names",
+ "title": "List metric names",
+ "required_scopes": ["metrics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "metrics",
+ "system_prompt_hint": "Discover which server/infrastructure metrics exist before querying them"
+ },
"notebooks-create": {
"description": "Create a new notebook. Provide a title and content. Content is a JSON object representing the notebook's rich text document structure (ProseMirror-based). Returns the created notebook with its short_id.\nEmbedded charts use `{type: \"ph-query\", attrs: {nodeId, query}}` nodes. The `query` object must be one of: (a) `{kind: \"DataVisualizationNode\", source: {kind: \"HogQLQuery\", query: \"SELECT ...\"}, display: \"ActionsBar\", chartSettings: {...}}` for SQL charts — do NOT wrap this in an InsightVizNode; (b) `{kind: \"InsightVizNode\", source: <TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery>}` for product-analytics insights; or (c) `{kind: \"SavedInsightNode\", shortId: \"...\"}` to embed a saved insight. The server rejects other shapes and auto-corrects the common `InsightVizNode` wrapping a SQL chart.",
"category": "Notebooks",
@@ -5401,6 +5417,22 @@
},
"system_prompt_hint": "Log filtering by severity/service/attribute"
},
+ "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",
+ "feature": "metrics",
+ "summary": "Query metrics",
+ "title": "Query metrics",
+ "required_scopes": ["metrics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "metrics",
+ "system_prompt_hint": "Server/infrastructure metrics (OTel/Prometheus) — time series, rates, quantiles, formulas"
+ },
"query-paths": {
"description": "Run a paths query to analyze the most common sequences of events or pages that users navigate through. Paths insights visualize user flows as a directed graph, showing how users move between steps and where they drop off.\n\nUse 'read-data-schema' to discover available events, actions, and properties for filters.\n\nExamples of use cases include:\n\n- What do users do after signing up?\n- What pages do users visit before making a purchase?\n- What are the most common navigation flows on your website?\n- Where do users drop off in a particular flow?\n- What custom events lead to a conversion?\n\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters to narrow results. Only include property filters when they are essential to directly answer the user's question. Avoid adding them if the question can be addressed without additional segmentation and always use the minimum set of property filters needed.\n\nIMPORTANT: Do not check if a property is set unless the user explicitly asks for it.\n\nWhen using a property filter, you should:\n\n- **Prioritize properties directly related to the context or objective of the user's query.** Avoid using properties for identification like IDs. Instead, prioritize filtering based on general properties like `paidCustomer` or `icp_score`.\n- **Ensure that you find both the property group and name.** Property groups should be one of the following: event, person, session, group.\n- After selecting a property, **validate that the property value accurately reflects the intended criteria**.\n- **Find the suitable operator for type** (e.g., `contains`, `is set`).\n- If the operator requires a value, use the `read-data-schema` tool to find the property values.\n- You set logical operators to combine multiple properties of a single series: AND or OR.\n\nInfer the property groups from the user's request. If your first guess doesn't yield any results, try to adjust the property group.\n\nSupported operators for the String type are:\n\n- equals (exact)\n- doesn't equal (is_not)\n- contains (icontains)\n- doesn't contain (not_icontains)\n- matches regex (regex)\n- doesn't match regex (not_regex)\n- is set\n- is not set\n\nSupported operators for the Numeric type are:\n\n- equals (exact)\n- doesn't equal (is_not)\n- greater than (gt)\n- less than (lt)\n- is set\n- is not set\n\nSupported operators for the DateTime type are:\n\n- equals (is_date_exact)\n- doesn't equal (is_not for existence check)\n- before (is_date_before)\n- after (is_date_after)\n- is set\n- is not set\n\nSupported operators for the Boolean type are:\n\n- equals\n- doesn't equal\n- is set\n- is not set\n\nAll operators take a single value except for `equals` and `doesn't equal` which can take one or more values (as an array).\n\n## Time period\n\nYou should not filter events by time using property filters. Instead, use the `dateRange` field. If the question doesn't mention time, use last 30 days as a default time period.\n\n# Paths guidelines\n\n## Event types\n\nPaths analyze sequences of events. Specify which event types to include using `includeEventTypes`. If omitted, all events are included without type filtering.\n\n- `$pageview` - web page views. Path values come from `$current_url`, with trailing slashes stripped, so they must match your stored URL format. This is often a path like `/login`, but may also be a full URL like `https://example.com/login`. Best for analyzing website navigation flows. This is the most common choice.\n- `$screen` - mobile screen views. Path values are screen names (from `$screen_name`). Use for mobile app navigation analysis.\n- `custom_event` - custom events (any event whose name does not start with `$`). Path values are event names. Use for analyzing flows of custom-tracked events like button clicks, form submissions, or feature usage.\n- `hogql` - custom HogQL expression. Use with `pathsHogQLExpression` for advanced path definitions.\n\nYou can combine multiple types. For example, include both `$pageview` and `custom_event` to see how page views and custom events interleave.\n\n## Start and end points\n\nUse `startPoint` to filter paths that begin at a specific step, or `endPoint` to filter paths that end at a specific step. The value format depends on the event type:\n\n- For `$pageview`: use the same URL format as your `$current_url` values, often paths like `/login`, `/dashboard`, `/settings`, but sometimes full URLs\n- For `$screen`: use screen names\n- For `custom_event`: use event names like `user signed up`, `purchase completed`\n\n## Path cleaning\n\nUse `localPathCleaningFilters` to normalize dynamic URLs. Each filter has a `regex` pattern (ClickHouse regex syntax) and an `alias` replacement. Filters are applied in sequence using `replaceRegexpAll(path, regex, alias)`. For example, to normalize product URLs: `{ \"regex\": \"\\\\/product\\\\/\\\\d+\", \"alias\": \"/product/:id\" }`.\n\nUse `pathGroupings` for simpler glob-like grouping of paths into single nodes. Use `*` as a wildcard — the patterns are auto-escaped so only `*` has special meaning. For example, `/product/*` groups all product sub-pages into one node.\n\n## Exclusions\n\nUse `excludeEvents` to remove specific path items that clutter the visualization. The values must match path item values, not event types: for `$pageview` paths these must match your stored `$current_url` format (e.g., `/health-check` or `https://example.com/health-check`), for `custom_event` paths these are event names (e.g., `heartbeat`). To control which event types are included, use `includeEventTypes` instead.\n\n# Examples\n\n## What pages do users visit after the homepage?\n\n```json\n{\n \"kind\": \"PathsQuery\",\n \"pathsFilter\": {\n \"includeEventTypes\": [\"$pageview\"],\n \"startPoint\": \"/\",\n \"stepLimit\": 5\n },\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"filterTestAccounts\": true\n}\n```\n\n## What do users do after signing up?\n\n```json\n{\n \"kind\": \"PathsQuery\",\n \"pathsFilter\": {\n \"includeEventTypes\": [\"custom_event\"],\n \"startPoint\": \"user signed up\",\n \"stepLimit\": 5\n },\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"filterTestAccounts\": true\n}\n```\n\n## Navigation paths excluding noisy URLs\n\n```json\n{\n \"kind\": \"PathsQuery\",\n \"pathsFilter\": {\n \"includeEventTypes\": [\"$pageview\"],\n \"excludeEvents\": [\"/health-check\", \"/ping\"],\n \"stepLimit\": 5,\n \"edgeLimit\": 30\n },\n \"dateRange\": { \"date_from\": \"-14d\" },\n \"filterTestAccounts\": true\n}\n```\n\n## Custom event paths excluding noisy events\n\n```json\n{\n \"kind\": \"PathsQuery\",\n \"pathsFilter\": {\n \"includeEventTypes\": [\"custom_event\"],\n \"excludeEvents\": [\"heartbeat\"],\n \"stepLimit\": 5\n },\n \"dateRange\": { \"date_from\": \"-14d\" },\n \"filterTestAccounts\": true\n}\n```\n\n## Paths with URL cleaning for dynamic segments\n\n```json\n{\n \"kind\": \"PathsQuery\",\n \"pathsFilter\": {\n \"includeEventTypes\": [\"$pageview\"],\n \"stepLimit\": 5,\n \"localPathCleaningFilters\": [\n { \"regex\": \"\\\\/user\\\\/\\\\d+\", \"alias\": \"/user/:id\" },\n { \"regex\": \"\\\\/project\\\\/[a-f0-9-]+\", \"alias\": \"/project/:id\" }\n ]\n },\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"filterTestAccounts\": true\n}\n```\n\n## What paths lead to the pricing page for mobile users?\n\n```json\n{\n \"kind\": \"PathsQuery\",\n \"pathsFilter\": {\n \"includeEventTypes\": [\"$pageview\"],\n \"endPoint\": \"/pricing\",\n \"stepLimit\": 5\n },\n \"properties\": [{ \"key\": \"$os\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"iOS\", \"Android\"] }],\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"filterTestAccounts\": true\n}\n```\n\n# Reminders\n\n- Ensure that any properties included are directly relevant to the context and objectives of the user's question. Avoid unnecessary or unrelated details.\n- Avoid overcomplicating the response with excessive property filters. Focus on the simplest solution.\n- Always specify `includeEventTypes` to scope the analysis to relevant event types. If omitted, all events are included which may produce noisy results.\n- Use `$pageview` as the default event type for web navigation questions.\n- Path cleaning filters (`localPathCleaningFilters`) use ClickHouse regex and are only needed when dynamic URL segments would fragment the visualization. Path groupings (`pathGroupings`) use glob-like patterns with `*` wildcards for simpler cases.\n- Paths group events into sessions with a 30-minute inactivity threshold — events more than 30 minutes apart start a new path session.",
"category": "Query wrappers",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 5b5a6e1c2e86..6603158513ff 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -5291,6 +5291,22 @@
},
"feature_flag": "mcp-analytics"
},
+ "metric-names-list": {
+ "description": "List the distinct metric names this project has ingested, with each metric's OTel type (`gauge`, `sum`, `histogram`, `summary`, `exponential_histogram`). Names are ordered by recent activity and exact matches float to the top.\n\nALWAYS call this before `query-metrics` unless you already know the exact metric name — metric queries match names exactly, so a guessed name silently returns no data.\n\nUse `value` for a case-insensitive substring search (e.g. `value: \"lag\"` finds `metrics_rate_limiter_message_lag_seconds`). The metric's type tells you which aggregations make sense:\n\n- `sum` (counters, usually `_total`-suffixed): use `rate` or `increase`\n- `gauge`: use `avg`, `p95`, or `sum`\n- `histogram`: use `histogram_quantile` with a `quantile`",
+ "category": "Metrics",
+ "feature": "metrics",
+ "summary": "List metric names",
+ "title": "List metric names",
+ "required_scopes": ["metrics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "metrics",
+ "system_prompt_hint": "Discover which server/infrastructure metrics exist before querying them"
+ },
"notebook-edit": {
"description": "Edit part of a notebook's content. Use this for any change inside a notebook — text, headings, attributes, whole paragraphs. Call `notebooks-retrieve` first to see what to target.\n\nMatching is by content. The tool finds `old_value` anywhere in the notebook and swaps it for `new_value` in place.\n\nOn success, returns the updated notebook with the new content and bumped version. On a 409 or 410 error, the notebook has changed since you loaded it — call `notebooks-retrieve` and re-apply your edit against the latest content.",
"category": "Notebooks",
@@ -5838,6 +5854,22 @@
},
"system_prompt_hint": "Log filtering by severity/service/attribute"
},
+ "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",
+ "feature": "metrics",
+ "summary": "Query metrics",
+ "title": "Query metrics",
+ "required_scopes": ["metrics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "metrics",
+ "system_prompt_hint": "Server/infrastructure metrics (OTel/Prometheus) — time series, rates, quantiles, formulas"
+ },
"query-paths": {
"description": "Run a paths query to analyze the most common sequences of events or pages that users navigate through. Paths insights visualize user flows as a directed graph, showing how users move between steps and where they drop off.\n\nUse 'read-data-schema' to discover available events, actions, and properties for filters.\n\nExamples of use cases include:\n\n- What do users do after signing up?\n- What pages do users visit before making a purchase?\n- What are the most common navigation flows on your website?\n- Where do users drop off in a particular flow?\n- What custom events lead to a conversion?\n\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters to narrow results. Only include property filters when they are essential to directly answer the user's question. Avoid adding them if the question can be addressed without additional segmentation and always use the minimum set of property filters needed.\n\nIMPORTANT: Do not check if a property is set unless the user explicitly asks for it.\n\nWhen using a property filter, you should:\n\n- **Prioritize properties directly related to the context or objective of the user's query.** Avoid using properties for identification like IDs. Instead, prioritize filtering based on general properties like `paidCustomer` or `icp_score`.\n- **Ensure that you find both the property group and name.** Property groups should be one of the following: event, person, session, group.\n- After selecting a property, **validate that the property value accurately reflects the intended criteria**.\n- **Find the suitable operator for type** (e.g., `contains`, `is set`).\n- If the operator requires a value, use the `read-data-schema` tool to find the property values.\n- You set logical operators to combine multiple properties of a single series: AND or OR.\n\nInfer the property groups from the user's request. If your first guess doesn't yield any results, try to adjust the property group.\n\nSupported operators for the String type are:\n\n- equals (exact)\n- doesn't equal (is_not)\n- contains (icontains)\n- doesn't contain (not_icontains)\n- matches regex (regex)\n- doesn't match regex (not_regex)\n- is set\n- is not set\n\nSupported operators for the Numeric type are:\n\n- equals (exact)\n- doesn't equal (is_not)\n- greater than (gt)\n- less than (lt)\n- is set\n- is not set\n\nSupported operators for the DateTime type are:\n\n- equals (is_date_exact)\n- doesn't equal (is_not for existence check)\n- before (is_date_before)\n- after (is_date_after)\n- is set\n- is not set\n\nSupported operators for the Boolean type are:\n\n- equals\n- doesn't equal\n- is set\n- is not set\n\nAll operators take a single value except for `equals` and `doesn't equal` which can take one or more values (as an array).\n\n## Time period\n\nYou should not filter events by time using property filters. Instead, use the `dateRange` field. If the question doesn't mention time, use last 30 days as a default time period.\n\n# Paths guidelines\n\n## Event types\n\nPaths analyze sequences of events. Specify which event types to include using `includeEventTypes`. If omitted, all events are included without type filtering.\n\n- `$pageview` - web page views. Path values come from `$current_url`, with trailing slashes stripped, so they must match your stored URL format. This is often a path like `/login`, but may also be a full URL like `https://example.com/login`. Best for analyzing website navigation flows. This is the most common choice.\n- `$screen` - mobile screen views. Path values are screen names (from `$screen_name`). Use for mobile app navigation analysis.\n- `custom_event` - custom events (any event whose name does not start with `$`). Path values are event names. Use for analyzing flows of custom-tracked events like button clicks, form submissions, or feature usage.\n- `hogql` - custom HogQL expression. Use with `pathsHogQLExpression` for advanced path definitions.\n\nYou can combine multiple types. For example, include both `$pageview` and `custom_event` to see how page views and custom events interleave.\n\n## Start and end points\n\nUse `startPoint` to filter paths that begin at a specific step, or `endPoint` to filter paths that end at a specific step. The value format depends on the event type:\n\n- For `$pageview`: use the same URL format as your `$current_url` values, often paths like `/login`, `/dashboard`, `/settings`, but sometimes full URLs\n- For `$screen`: use screen names\n- For `custom_event`: use event names like `user signed up`, `purchase completed`\n\n## Path cleaning\n\nUse `localPathCleaningFilters` to normalize dynamic URLs. Each filter has a `regex` pattern (ClickHouse regex syntax) and an `alias` replacement. Filters are applied in sequence using `replaceRegexpAll(path, regex, alias)`. For example, to normalize product URLs: `{ \"regex\": \"\\\\/product\\\\/\\\\d+\", \"alias\": \"/product/:id\" }`.\n\nUse `pathGroupings` for simpler glob-like grouping of paths into single nodes. Use `*` as a wildcard — the patterns are auto-escaped so only `*` has special meaning. For example, `/product/*` groups all product sub-pages into one node.\n\n## Exclusions\n\nUse `excludeEvents` to remove specific path items that clutter the visualization. The values must match path item values, not event types: for `$pageview` paths these must match your stored `$current_url` format (e.g., `/health-check` or `https://example.com/health-check`), for `custom_event` paths these are event names (e.g., `heartbeat`). To control which event types are included, use `includeEventTypes` instead.\n\n# Examples\n\n## What pages do users visit after the homepage?\n\n```json\n{\n \"kind\": \"PathsQuery\",\n \"pathsFilter\": {\n \"includeEventTypes\": [\"$pageview\"],\n \"startPoint\": \"/\",\n \"stepLimit\": 5\n },\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"filterTestAccounts\": true\n}\n```\n\n## What do users do after signing up?\n\n```json\n{\n \"kind\": \"PathsQuery\",\n \"pathsFilter\": {\n \"includeEventTypes\": [\"custom_event\"],\n \"startPoint\": \"user signed up\",\n \"stepLimit\": 5\n },\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"filterTestAccounts\": true\n}\n```\n\n## Navigation paths excluding noisy URLs\n\n```json\n{\n \"kind\": \"PathsQuery\",\n \"pathsFilter\": {\n \"includeEventTypes\": [\"$pageview\"],\n \"excludeEvents\": [\"/health-check\", \"/ping\"],\n \"stepLimit\": 5,\n \"edgeLimit\": 30\n },\n \"dateRange\": { \"date_from\": \"-14d\" },\n \"filterTestAccounts\": true\n}\n```\n\n## Custom event paths excluding noisy events\n\n```json\n{\n \"kind\": \"PathsQuery\",\n \"pathsFilter\": {\n \"includeEventTypes\": [\"custom_event\"],\n \"excludeEvents\": [\"heartbeat\"],\n \"stepLimit\": 5\n },\n \"dateRange\": { \"date_from\": \"-14d\" },\n \"filterTestAccounts\": true\n}\n```\n\n## Paths with URL cleaning for dynamic segments\n\n```json\n{\n \"kind\": \"PathsQuery\",\n \"pathsFilter\": {\n \"includeEventTypes\": [\"$pageview\"],\n \"stepLimit\": 5,\n \"localPathCleaningFilters\": [\n { \"regex\": \"\\\\/user\\\\/\\\\d+\", \"alias\": \"/user/:id\" },\n { \"regex\": \"\\\\/project\\\\/[a-f0-9-]+\", \"alias\": \"/project/:id\" }\n ]\n },\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"filterTestAccounts\": true\n}\n```\n\n## What paths lead to the pricing page for mobile users?\n\n```json\n{\n \"kind\": \"PathsQuery\",\n \"pathsFilter\": {\n \"includeEventTypes\": [\"$pageview\"],\n \"endPoint\": \"/pricing\",\n \"stepLimit\": 5\n },\n \"properties\": [{ \"key\": \"$os\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"iOS\", \"Android\"] }],\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"filterTestAccounts\": true\n}\n```\n\n# Reminders\n\n- Ensure that any properties included are directly relevant to the context and objectives of the user's question. Avoid unnecessary or unrelated details.\n- Avoid overcomplicating the response with excessive property filters. Focus on the simplest solution.\n- Always specify `includeEventTypes` to scope the analysis to relevant event types. If omitted, all events are included which may produce noisy results.\n- Use `$pageview` as the default event type for web navigation questions.\n- Path cleaning filters (`localPathCleaningFilters`) use ClickHouse regex and are only needed when dynamic URL segments would fragment the visualization. Path groupings (`pathGroupings`) use glob-like patterns with `*` wildcards for simpler cases.\n- Paths group events into sessions with a 30-minute inactivity threshold — events more than 30 minutes apart start a new path session.",
"category": "Query wrappers",
diff --git a/services/mcp/src/generated/metrics/api.ts b/services/mcp/src/generated/metrics/api.ts
new file mode 100644
index 000000000000..0b3e75d1be6e
--- /dev/null
+++ b/services/mcp/src/generated/metrics/api.ts
@@ -0,0 +1,251 @@
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * MCP service uses these Zod schemas for generated tool handlers.
+ * To regenerate: hogli build:openapi
+ *
+ * PostHog API - MCP 2 enabled ops
+ * OpenAPI spec version: 1.0.0
+ */
+import * as zod from 'zod'
+
+export const MetricsQueryCreateParams = /* @__PURE__ */ zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const metricsQueryCreateBodyQueryOneMetricNameMax = 255
+
+export const metricsQueryCreateBodyQueryOneAggregationDefault = `sum`
+export const metricsQueryCreateBodyQueryOneQuantileMin = 0
+export const metricsQueryCreateBodyQueryOneQuantileMax = 1
+
+export const metricsQueryCreateBodyQueryOneFiltersItemKeyMax = 255
+
+export const metricsQueryCreateBodyQueryOneFiltersItemOpDefault = `eq`
+export const metricsQueryCreateBodyQueryOneFiltersItemScopeDefault = `auto`
+export const metricsQueryCreateBodyQueryOneGroupByItemKeyMax = 255
+
+export const metricsQueryCreateBodyQueryOneGroupByItemScopeDefault = `auto`
+export const metricsQueryCreateBodyQueryOneClausesItemNameMax = 64
+
+export const metricsQueryCreateBodyQueryOneClausesItemMetricNameMax = 255
+
+export const metricsQueryCreateBodyQueryOneClausesItemAggregationDefault = `sum`
+export const metricsQueryCreateBodyQueryOneClausesItemQuantileMin = 0
+export const metricsQueryCreateBodyQueryOneClausesItemQuantileMax = 1
+
+export const metricsQueryCreateBodyQueryOneClausesItemFiltersItemKeyMax = 255
+
+export const metricsQueryCreateBodyQueryOneClausesItemFiltersItemOpDefault = `eq`
+export const metricsQueryCreateBodyQueryOneClausesItemFiltersItemScopeDefault = `auto`
+export const metricsQueryCreateBodyQueryOneClausesItemGroupByItemKeyMax = 255
+
+export const metricsQueryCreateBodyQueryOneClausesItemGroupByItemScopeDefault = `auto`
+export const metricsQueryCreateBodyQueryOneFormulaMax = 512
+
+export const MetricsQueryCreateBody = /* @__PURE__ */ zod.object({
+ query: zod
+ .object({
+ metricName: zod
+ .string()
+ .max(metricsQueryCreateBodyQueryOneMetricNameMax)
+ .optional()
+ .describe(
+ "Exact metric name to query (e.g. 'http.server.duration'). Single-clause shorthand — mutually exclusive with 'clauses'."
+ ),
+ aggregation: zod
+ .enum(['sum', 'avg', 'count', 'p95', 'rate', 'increase', 'histogram_quantile'])
+ .describe(
+ '* `sum` - sum\n* `avg` - avg\n* `count` - count\n* `p95` - p95\n* `rate` - rate\n* `increase` - increase\n* `histogram_quantile` - histogram_quantile'
+ )
+ .default(metricsQueryCreateBodyQueryOneAggregationDefault)
+ .describe(
+ "Aggregation applied per time bucket. 'rate' (per-second) and 'increase' are counter-aware: per-series deltas with Prometheus counter-reset handling, temporality-aware (delta-temporality samples count as-is). 'histogram_quantile' interpolates from OTel histogram buckets and requires 'quantile'.\n\n* `sum` - sum\n* `avg` - avg\n* `count` - count\n* `p95` - p95\n* `rate` - rate\n* `increase` - increase\n* `histogram_quantile` - histogram_quantile"
+ ),
+ quantile: zod
+ .number()
+ .min(metricsQueryCreateBodyQueryOneQuantileMin)
+ .max(metricsQueryCreateBodyQueryOneQuantileMax)
+ .nullish()
+ .describe("Quantile in (0, 1) for 'histogram_quantile' (e.g. 0.95). Ignored for other aggregations."),
+ filters: zod
+ .array(
+ zod.object({
+ key: zod
+ .string()
+ .max(metricsQueryCreateBodyQueryOneFiltersItemKeyMax)
+ .describe(
+ "Attribute name to filter on, without any type-tag suffix (e.g. 'k8s.pod.name', 'env')."
+ ),
+ op: zod
+ .enum(['eq', 'neq', 'regex', 'not_regex'])
+ .describe('* `eq` - eq\n* `neq` - neq\n* `regex` - regex\n* `not_regex` - not_regex')
+ .default(metricsQueryCreateBodyQueryOneFiltersItemOpDefault)
+ .describe(
+ "Comparison operator. 'regex'/'not_regex' use RE2 syntax. Negative operators also match rows that lack the key entirely, mirroring Prometheus negative matchers.\n\n* `eq` - eq\n* `neq` - neq\n* `regex` - regex\n* `not_regex` - not_regex"
+ ),
+ value: zod
+ .string()
+ .describe('Value to compare against. For regex operators this is the pattern.'),
+ scope: zod
+ .enum(['resource', 'attribute', 'auto'])
+ .describe('* `resource` - resource\n* `attribute` - attribute\n* `auto` - auto')
+ .default(metricsQueryCreateBodyQueryOneFiltersItemScopeDefault)
+ .describe(
+ "Where the attribute lives: 'resource' = per-target resource attributes (k8s.pod.name, service.version), 'attribute' = per-datapoint attributes (http.method, path), 'auto' = resource first with per-datapoint fallback. Use 'auto' unless you know the exact scope.\n\n* `resource` - resource\n* `attribute` - attribute\n* `auto` - auto"
+ ),
+ })
+ )
+ .optional()
+ .describe('Label predicates ANDed together. Rows must satisfy every filter.'),
+ groupBy: zod
+ .array(
+ zod.object({
+ key: zod
+ .string()
+ .max(metricsQueryCreateBodyQueryOneGroupByItemKeyMax)
+ .describe("Attribute name to split series by (e.g. 'k8s.pod.name', 'env')."),
+ scope: zod
+ .enum(['resource', 'attribute', 'auto'])
+ .describe('* `resource` - resource\n* `attribute` - attribute\n* `auto` - auto')
+ .default(metricsQueryCreateBodyQueryOneGroupByItemScopeDefault)
+ .describe(
+ "Where the attribute lives; same semantics as filter scope. Use 'auto' unless you know the exact scope.\n\n* `resource` - resource\n* `attribute` - attribute\n* `auto` - auto"
+ ),
+ })
+ )
+ .optional()
+ .describe(
+ 'Labels to split the result into separate series by. Series share one time grid and are capped at the 100 largest.'
+ ),
+ interval: zod
+ .union([
+ zod
+ .enum(['second', 'minute', 'minute_5', 'minute_15', 'hour', 'hour_6', 'day', 'week'])
+ .describe(
+ '* `second` - second\n* `minute` - minute\n* `minute_5` - minute_5\n* `minute_15` - minute_15\n* `hour` - hour\n* `hour_6` - hour_6\n* `day` - day\n* `week` - week'
+ ),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Bucket size for the shared time grid. Omit to auto-pick (~60 buckets across the range).\n\n* `second` - second\n* `minute` - minute\n* `minute_5` - minute_5\n* `minute_15` - minute_15\n* `hour` - hour\n* `hour_6` - hour_6\n* `day` - day\n* `week` - week'
+ ),
+ clauses: zod
+ .array(
+ zod.object({
+ name: zod
+ .string()
+ .max(metricsQueryCreateBodyQueryOneClausesItemNameMax)
+ .describe("Clause name a formula refers to (e.g. 'a')."),
+ metricName: zod
+ .string()
+ .max(metricsQueryCreateBodyQueryOneClausesItemMetricNameMax)
+ .describe('Exact metric name this clause queries.'),
+ aggregation: zod
+ .enum(['sum', 'avg', 'count', 'p95', 'rate', 'increase', 'histogram_quantile'])
+ .describe(
+ '* `sum` - sum\n* `avg` - avg\n* `count` - count\n* `p95` - p95\n* `rate` - rate\n* `increase` - increase\n* `histogram_quantile` - histogram_quantile'
+ )
+ .default(metricsQueryCreateBodyQueryOneClausesItemAggregationDefault)
+ .describe(
+ 'Aggregation applied per time bucket; same semantics as the top-level aggregation.\n\n* `sum` - sum\n* `avg` - avg\n* `count` - count\n* `p95` - p95\n* `rate` - rate\n* `increase` - increase\n* `histogram_quantile` - histogram_quantile'
+ ),
+ quantile: zod
+ .number()
+ .min(metricsQueryCreateBodyQueryOneClausesItemQuantileMin)
+ .max(metricsQueryCreateBodyQueryOneClausesItemQuantileMax)
+ .nullish()
+ .describe("Quantile in (0, 1) for 'histogram_quantile'."),
+ filters: zod
+ .array(
+ zod.object({
+ key: zod
+ .string()
+ .max(metricsQueryCreateBodyQueryOneClausesItemFiltersItemKeyMax)
+ .describe(
+ "Attribute name to filter on, without any type-tag suffix (e.g. 'k8s.pod.name', 'env')."
+ ),
+ op: zod
+ .enum(['eq', 'neq', 'regex', 'not_regex'])
+ .describe(
+ '* `eq` - eq\n* `neq` - neq\n* `regex` - regex\n* `not_regex` - not_regex'
+ )
+ .default(metricsQueryCreateBodyQueryOneClausesItemFiltersItemOpDefault)
+ .describe(
+ "Comparison operator. 'regex'/'not_regex' use RE2 syntax. Negative operators also match rows that lack the key entirely, mirroring Prometheus negative matchers.\n\n* `eq` - eq\n* `neq` - neq\n* `regex` - regex\n* `not_regex` - not_regex"
+ ),
+ value: zod
+ .string()
+ .describe('Value to compare against. For regex operators this is the pattern.'),
+ scope: zod
+ .enum(['resource', 'attribute', 'auto'])
+ .describe('* `resource` - resource\n* `attribute` - attribute\n* `auto` - auto')
+ .default(metricsQueryCreateBodyQueryOneClausesItemFiltersItemScopeDefault)
+ .describe(
+ "Where the attribute lives: 'resource' = per-target resource attributes (k8s.pod.name, service.version), 'attribute' = per-datapoint attributes (http.method, path), 'auto' = resource first with per-datapoint fallback. Use 'auto' unless you know the exact scope.\n\n* `resource` - resource\n* `attribute` - attribute\n* `auto` - auto"
+ ),
+ })
+ )
+ .optional()
+ .describe('Label predicates ANDed together for this clause.'),
+ groupBy: zod
+ .array(
+ zod.object({
+ key: zod
+ .string()
+ .max(metricsQueryCreateBodyQueryOneClausesItemGroupByItemKeyMax)
+ .describe("Attribute name to split series by (e.g. 'k8s.pod.name', 'env')."),
+ scope: zod
+ .enum(['resource', 'attribute', 'auto'])
+ .describe('* `resource` - resource\n* `attribute` - attribute\n* `auto` - auto')
+ .default(metricsQueryCreateBodyQueryOneClausesItemGroupByItemScopeDefault)
+ .describe(
+ "Where the attribute lives; same semantics as filter scope. Use 'auto' unless you know the exact scope.\n\n* `resource` - resource\n* `attribute` - attribute\n* `auto` - auto"
+ ),
+ })
+ )
+ .optional()
+ .describe('Labels to split this clause into separate series by.'),
+ })
+ )
+ .optional()
+ .describe(
+ "Full multi-clause form: each clause is an independent metric selection sharing the request's time grid. Mutually exclusive with 'metricName'."
+ ),
+ formula: zod
+ .string()
+ .max(metricsQueryCreateBodyQueryOneFormulaMax)
+ .nullish()
+ .describe(
+ "Arithmetic over clause names evaluated server-side per grid point, e.g. '(a - b) / a'. Supports + - * / and parentheses; division by zero yields 0. When set, only the formula result series are returned."
+ ),
+ dateFrom: zod.iso
+ .datetime({ offset: true })
+ .describe('Lower bound (inclusive) for the query range. ISO 8601.'),
+ dateTo: zod.iso
+ .datetime({ offset: true })
+ .optional()
+ .describe('Upper bound (exclusive) for the query range. Defaults to now if omitted.'),
+ })
+ .describe('The metric query to execute.'),
+})
+
+/**
+ * Distinct metric names for the team. Backs the picker UI.
+ */
+export const MetricsValuesRetrieveParams = /* @__PURE__ */ zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const MetricsValuesRetrieveQueryParams = /* @__PURE__ */ zod.object({
+ limit: zod.number().optional().describe('Max number of names to return. Defaults to 100, capped at 1000.'),
+ value: zod.string().optional().describe('Substring filter (case-insensitive) applied to metric names.'),
+})
diff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.ts
index 33bab491b8c6..9e18a66c7f7d 100644
--- a/services/mcp/src/lib/oauth-scopes.generated.ts
+++ b/services/mcp/src/lib/oauth-scopes.generated.ts
@@ -121,6 +121,8 @@ export const OAUTH_SCOPES_SUPPORTED = [
'marketing_analytics:write',
'mcp_analytics:read',
'mcp_analytics:write',
+ 'metrics:read',
+ 'metrics:write',
'notebook:read',
'notebook:write',
'organization:read',
diff --git a/services/mcp/src/tools/generated/index.ts b/services/mcp/src/tools/generated/index.ts
index e4b038a5ffec..4223f1ea2306 100644
--- a/services/mcp/src/tools/generated/index.ts
+++ b/services/mcp/src/tools/generated/index.ts
@@ -30,6 +30,7 @@ import { GENERATED_TOOLS as integrations } from './integrations'
import { GENERATED_TOOLS as logs } from './logs'
import { GENERATED_TOOLS as marketing_analytics } from './marketing_analytics'
import { GENERATED_TOOLS as mcp_analytics } from './mcp_analytics'
+import { GENERATED_TOOLS as metrics } from './metrics'
import { GENERATED_TOOLS as notebooks } from './notebooks'
import { GENERATED_TOOLS as persons } from './persons'
import { GENERATED_TOOLS as platform_features } from './platform_features'
@@ -79,6 +80,7 @@ export const GENERATED_TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> =
...logs,
...marketing_analytics,
...mcp_analytics,
+ ...metrics,
...notebooks,
...persons,
...platform_features,
diff --git a/services/mcp/src/tools/generated/metrics.ts b/services/mcp/src/tools/generated/metrics.ts
new file mode 100644
index 000000000000..594d7111c249
--- /dev/null
+++ b/services/mcp/src/tools/generated/metrics.ts
@@ -0,0 +1,53 @@
+// AUTO-GENERATED from products/metrics/mcp/tools.yaml + OpenAPI — do not edit
+import { z } from 'zod'
+
+import type { Schemas } from '@/api/generated'
+import { MetricsQueryCreateBody, MetricsValuesRetrieveQueryParams } from '@/generated/metrics/api'
+import { pickResponseFields } from '@/tools/tool-utils'
+import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
+
+const MetricNamesListSchema = MetricsValuesRetrieveQueryParams
+
+const metricNamesList = (): ToolBase<typeof MetricNamesListSchema, Schemas._MetricNamesResponse> => ({
+ name: 'metric-names-list',
+ schema: MetricNamesListSchema,
+ handler: async (context: Context, params: z.infer<typeof MetricNamesListSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas._MetricNamesResponse>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/metrics/values/`,
+ query: {
+ limit: params.limit,
+ value: params.value,
+ },
+ })
+ const filtered = pickResponseFields(result, ['results']) as typeof result
+ return filtered
+ },
+})
+
+const QueryMetricsSchema = MetricsQueryCreateBody
+
+const queryMetrics = (): ToolBase<typeof QueryMetricsSchema, Schemas._MetricQueryResponse> => ({
+ name: 'query-metrics',
+ schema: QueryMetricsSchema,
+ handler: async (context: Context, params: z.infer<typeof QueryMetricsSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.query !== undefined) {
+ body['query'] = params.query
+ }
+ const result = await context.api.request<Schemas._MetricQueryResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/metrics/query/`,
+ body,
+ })
+ const filtered = pickResponseFields(result, ['results']) as typeof result
+ return filtered
+ },
+})
+
+export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
+ 'metric-names-list': metricNamesList,
+ 'query-metrics': queryMetrics,
+}
diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.ts
index 5b25b16af848..7d9e54f5dc3e 100644
--- a/services/mcp/tests/unit/tool-filtering.test.ts
+++ b/services/mcp/tests/unit/tool-filtering.test.ts
@@ -750,9 +750,10 @@ describe('Tool Filtering - Feature Flags', () => {
'product-business-knowledge',
'field-notes',
'mcp-analytics',
+ 'metrics',
])
)
- expect(flags).toHaveLength(18)
+ expect(flags).toHaveLength(19)
})
// Exercise the real predicate (toolPassesFlagGate) over hand-rolled entries