: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): clarify and expand model coverage (#98761)
Lucas Fariaf030215b50ec
diff --git a/docs/internal/mcp-model-identification.md b/docs/internal/mcp-model-identification.mdnew file mode 100644index 000000000000..d8a386c8395f--- /dev/null+++ b/docs/internal/mcp-model-identification.md@@ -0,0 +1,46 @@+# MCP model identification++The MCP analytics model chart shows the six most-used reported model identifiers.+Other models combines the remaining identifiers and counts toward the identified percentage.+Unknown counts calls with no captured model identifier.+The coverage summary separates unknown calls from the model ranking.+It remains visible when every call is unknown, showing 0% identified coverage.+The ranking shows named models by call count, followed by Other models; all percentages use all calls, including unknown calls, as the denominator.+Show all models expands a table of individual reported identifiers, loaded on demand in pages of 50.+The table uses the dashboard filters and keeps unknown calls in the percentage denominator.+Unknown calls stay in the coverage summary, and changing filters resets the expanded table.+For a date range ending now, the first page fixes the time bounds for subsequent pages and retries.+Late-arriving events within those bounds can still affect counts; the table is not a database snapshot.+The query's `includeAllModels` option enables this ungrouped view; `limit` (1 to 100) and `offset` select a page, and `hasMore` indicates another page is available.+Explore models opens a Trends table that trims model identifiers and groups missing or blank values under Unknown, with the dashboard's date range, property filters, and test-account exclusion preserved.+The table can show up to 50 identifiers before grouping the remaining values.+Identifiers come from client metadata or the agent's self-report; the identified percentage measures reporting coverage, not verified model identity.++PostHog's MCP server asks for `llm_model` on advertised tools and prefers recognized client metadata when available.+Agents can report `unknown` when they do not know their model.+Calls continue to work when the argument is omitted or invalid.++## Investigating unknown calls++When no model is captured, PostHog's MCP server adds `$mcp_llm_model_missing_reason` to `$mcp_tool_call`:++| Value | Meaning |+| --------------- | ---------------------------------------------------------------------------------------------------------------------- |+| `missing` | The call omitted the `llm_model` argument. |+| `unknown` | The argument was `unknown`, ignoring case and surrounding whitespace. |+| `invalid` | The argument was blank or was not a string. |+| `not_captured` | A nonempty report was supplied but the analytics SDK did not capture it, for example when the tool owns that argument. |+| `capture_error` | Analytics preparation failed. |++The reason describes the model argument only after client metadata and self-report resolution produced no model.+A model resolved from client metadata has no missing reason, even if the agent supplied `unknown` or an invalid argument.+Only the reason is recorded; rejected values and exception messages are not added to this property.++Break down unknown calls by this property and client over a period after deployment.+Use `missing` to investigate callers with older tool schemas or scripts that do not supply a model.+Use `unknown` to find clients where agents lack model identity and client-supplied metadata would help.+Do not infer a model from the client name or assume a scripted call has a calling model.++Historical events and other instrumented MCP servers may have no missing reason.+That absence does not mean the agent reported `unknown`.+This instrumentation does not backfill historical events or change the model chart's counts.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 5c23bd1a3eef..69228240417b 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -8520,6 +8520,10 @@ snapshots:hash: v1.k794b7964.e2688d6015e59ab3c4591b183f0dfc5f63b664c884c0c84da49dad113b1b5ec6.3o0fDZhH1au5zqzAax1ESTjpZyuZoRto4W6bBJ2Cbfcscenes-app-mcp-analytics-dashboard-cards--key-metrics-in-progress-bucket--light:hash: v1.k794b7964.987a4b9f762bab3f88f39ea33fb0eca000d0e5f6aeb2c0a89e2979399f4d5797.ziZ_6D2TpdPk2pVJqrCMfEcmRufZDVVVqN51I5vIHgM+ scenes-app-mcp-analytics-dashboard-cards--overview-unknown-models--dark:+ hash: v1.k794b7964.c7b952beb385aae0c27e30c97a0da5beaea922f2a224b910ca6498d5db1078e8.eXQ2J15_K2joBhu0FN6xhK283C6qX6-GPqE5ptnKW6c+ scenes-app-mcp-analytics-dashboard-cards--overview-unknown-models--light:+ hash: v1.k794b7964.1a835f6179dfaade64ea9989ef56b224ba81b92e5c51e623083d3e2e22a93248.DDSOC8EQig1B0ZBYysiEaCZkdf1mM2H02UQt3DYcBigscenes-app-mcp-analytics-dashboard-cards--share-by-harness--dark:hash: v1.k794b7964.085facb7ddb323955c333d1471e181110b3a4e2f4b9515204835355e71bbaaef.1dQCdLYloR9Tk_UkxdWllVUrfTy5k69BzzX8yO-LErwscenes-app-mcp-analytics-dashboard-cards--share-by-harness--light:@@ -8541,13 +8545,37 @@ snapshots:scenes-app-mcp-analytics-dashboard-cards--share-by-harness-other-only--light:hash: v1.k794b7964.3840a56231cceb8235aa7a2453ac98085a9d7d4512310bfc2d4b2c06504a6841.NaSlblb4-MUJVz5TGs6sFT-siZ63-pBuiLzaSyqyh8gscenes-app-mcp-analytics-dashboard-cards--share-by-model--dark:- hash: v1.k794b7964.f1cd0d50270811709b21860ec24f74dbc4a0ccce9841fc41b4cecabcd97ca447.S1pSjSh-DsFc_Onzdgc7zvj6g4n5Q5YROMGTKnp3iuc+ hash: v1.k794b7964.c5e6c50a93e46a027e6a40f3c55b2ea40a7b0716c2cff9f02c767d901b7fd656.ryQb5J5N1bDN0df0WzMy_sRnEeCmooIi4adG7atavxgscenes-app-mcp-analytics-dashboard-cards--share-by-model--light:- hash: v1.k794b7964.40b706717d21cabf7fc288b6531698ee207368c6b3fb83a6b66ca6acfe2af6df.2Xva50fHqEd4vwrvAvd5-8wBy1icz-LK_EgpRSjO0Eg+ hash: v1.k794b7964.a2b43c511f5001f798e01aba057ada6d4b1d466a318bac3d53bd5c7bc8d90846.mkC3aS7gqrGGYeIl5RaXjd9__Ft4c4j-6xou3WNiBzA+ scenes-app-mcp-analytics-dashboard-cards--share-by-model-empty--dark:+ hash: v1.k794b7964.f87219dd5b2edd63b02462c778709738670354e3d692bda5df365bedaf50c23b.GGf6F61g7ryPKyOJFCXe3al5sTPZyorAKysWdCEUbRE+ scenes-app-mcp-analytics-dashboard-cards--share-by-model-empty--light:+ hash: v1.k794b7964.487200243e85e444e819223741d2b5d1fdd3b2c96b6bffdef377383284cbaf1a.-fT2CAHBFI50h5d8mHXXlzv55uul_3MFC0BU2xi__uU+ scenes-app-mcp-analytics-dashboard-cards--share-by-model-expanded-narrow--dark:+ hash: v1.k794b7964.c0aa813270ae671f218cf6b097676cc73a831ecb7d20f4a082851d793eac96c6.q8ooUxbx90vMP85fpz_iH1T9msAPtI22qGGyxZItMuo+ scenes-app-mcp-analytics-dashboard-cards--share-by-model-expanded-narrow--light:+ hash: v1.k794b7964.b5039e979db28caaafa3a388173786cb41d3a194d89b7e26e3faa12e31b8749b.muswqr9OIAl2h6eqEUxTr3hTIC4jRRw8ZXNz9RVIyf4+ scenes-app-mcp-analytics-dashboard-cards--share-by-model-full-coverage--dark:+ hash: v1.k794b7964.2b3b6c894bb4d15ed2fb9f7b48f001bcde92fb5c012fa38e261f25ae2ef48443.bidQXWkzOZi6-y0jDgBraBun0U8Uxcre_vIFN3guOmg+ scenes-app-mcp-analytics-dashboard-cards--share-by-model-full-coverage--light:+ hash: v1.k794b7964.bb0899deedf673a1c8352df868a13d616fd43def2a483f6c2c28910f73bf0615.MJTbJhKat5PhlbxfZLaH09fum80jLFhyvhqs6eX9CCY+ scenes-app-mcp-analytics-dashboard-cards--share-by-model-load-error--dark:+ hash: v1.k794b7964.c5e6c50a93e46a027e6a40f3c55b2ea40a7b0716c2cff9f02c767d901b7fd656.SKLJ2d6tSZjHBQ_jckVOVLz82Qyjgq0TW7kNHSW66NM+ scenes-app-mcp-analytics-dashboard-cards--share-by-model-load-error--light:+ hash: v1.k794b7964.a2b43c511f5001f798e01aba057ada6d4b1d466a318bac3d53bd5c7bc8d90846.LzbA4Uc56InKiCcznaBzEiIrGv58xPRBh0Ufsc_f5Yg+ scenes-app-mcp-analytics-dashboard-cards--share-by-model-low-coverage--dark:+ hash: v1.k794b7964.532275709d7eda34220a370351034c733cef5237de74426a7888dee24552199f.4WzuAIHgSTM-2Azxh7PpOE1rk8u3ekhtnib8HZtofrw+ scenes-app-mcp-analytics-dashboard-cards--share-by-model-low-coverage--light:+ hash: v1.k794b7964.91e025ee6f80c99d81b4204ac5ceadb4a0264375fbc7ca54245d3d6dccd2ebc6.arhn_hiPUFwgL0xt13YSQbXhrk8fmytZ8OUYZ4RWTlQscenes-app-mcp-analytics-dashboard-cards--share-by-model-narrow--dark:- hash: v1.k794b7964.1565523b8bf28f1b9e9da27d78ac894e48190990f52542bc29a056ddec18bbad.wcFDEppca70quTjgH2H8u2NzA6c0GteoGLnViMcQ2E0+ hash: v1.k794b7964.d13c92f2fdb426623be6d96511fbd87f320f6669715726a6e57a2ecab81455b1.U3PljF_oYmXEyc4KG8E43Qf8NQCjl7a1DxZvjtzzYsIscenes-app-mcp-analytics-dashboard-cards--share-by-model-narrow--light:- hash: v1.k794b7964.bafbff928ee418e609247d0bb7d9c380056d1c1415800545ca69c3e77679b526.ySislSzbxIwQSNIVnbQKs-69P8F70MmLOzvlq9Yi2fQ+ hash: v1.k794b7964.4d0874588ebd0d857e5922c76fe60a26a5daee2cfb87fa8359c3067bd8fca4d0.Pms6BQvSKI42snnB4nOc5zw54nuteUOrpmGsozbWpGA+ scenes-app-mcp-analytics-dashboard-cards--share-by-model-unknown-only--dark:+ hash: v1.k794b7964.34eaaeb24c9c19f5440c58b38af3b4d8fe82358117cb5c8c4ed964e8ef251dd1.GKRgxxPsxFgr4o_vT9NkFwr7l6xgDLtjnJ4kdX3s3YY+ scenes-app-mcp-analytics-dashboard-cards--share-by-model-unknown-only--light:+ hash: v1.k794b7964.2dd14db88e508501922301ab7c664d298098d3d5598f5c71a3c07b12b7765063.Qjn7vJJaaR1kvnOPPv5hbfRFFPDaCQ7tOw8pGdzP4NIscenes-app-mcp-analytics-missing-capabilities-preview--example-reports--dark:hash: v1.k794b7964.e1dfe15b20b22dec1f74881db821597e40d534cf0c9773fc032948311de642f7.iAS_FuPfykHZ7rjy90ExdGbsAT1eKhSIwVLvxUg1aGMscenes-app-mcp-analytics-missing-capabilities-preview--example-reports--light:diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 2957654e8e96..2a46ba00a8a5 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -10112,6 +10112,10 @@"description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.","type": "string"},+ "hasMore": {+ "description": "Whether another page of individual model identifiers is available.",+ "type": "boolean"+ },"hogql": {"description": "Generated HogQL query.","type": "string"@@ -32607,14 +32611,29 @@"filterTestAccounts": {"type": "boolean"},+ "includeAllModels": {+ "description": "Return individual reported models, excluding Unknown, instead of the top-six grouping.",+ "type": "boolean"+ },"kind": {"const": "MCPModelBreakdownQuery","type": "string"},+ "limit": {+ "$ref": "#/definitions/integer",+ "description": "Page size when includeAllModels is enabled.",+ "maximum": 100,+ "minimum": 1+ },"modifiers": {"$ref": "#/definitions/HogQLQueryModifiers","description": "Modifiers used when performing the query"},+ "offset": {+ "$ref": "#/definitions/integer",+ "description": "Number of individual models to skip when includeAllModels is enabled.",+ "minimum": 0+ },"properties": {"items": {"$ref": "#/definitions/AnyPropertyFilter"@@ -32642,6 +32661,10 @@"description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.","type": "string"},+ "hasMore": {+ "description": "Whether another page of individual model identifiers is available.",+ "type": "boolean"+ },"hogql": {"description": "Generated HogQL query.","type": "string"@@ -47769,6 +47792,10 @@"description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.","type": "string"},+ "hasMore": {+ "description": "Whether another page of individual model identifiers is available.",+ "type": "boolean"+ },"hogql": {"description": "Generated HogQL query.","type": "string"diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 48539f59a39b..d8521febca36 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -3425,6 +3425,8 @@ export interface MCPModelBreakdownItem {}export interface MCPModelBreakdownQueryResponse extends AnalyticsQueryResponseBase {+ /** Whether another page of individual model identifiers is available. */+ hasMore?: booleanresults: MCPModelBreakdownItem[]}@@ -3434,6 +3436,19 @@ export interface MCPModelBreakdownQuery extends DataNode<MCPModelBreakdownQueryRdateRange?: DateRangeproperties?: AnyPropertyFilter[]filterTestAccounts?: boolean+ /** Return individual reported models, excluding Unknown, instead of the top-six grouping. */+ includeAllModels?: boolean+ /**+ * Page size when includeAllModels is enabled.+ * @minimum 1+ * @maximum 100+ */+ limit?: integer+ /**+ * Number of individual models to skip when includeAllModels is enabled.+ * @minimum 0+ */+ offset?: integer}export type CachedMCPModelBreakdownQueryResponse = CachedQueryResponse<MCPModelBreakdownQueryResponse>diff --git a/frontend/src/taxonomy/core-filter-definitions-by-group.json b/frontend/src/taxonomy/core-filter-definitions-by-group.jsonindex 1ced3767958f..c3c4a4f73f6c 100644--- a/frontend/src/taxonomy/core-filter-definitions-by-group.json+++ b/frontend/src/taxonomy/core-filter-definitions-by-group.json@@ -2280,6 +2280,17 @@],"label": "MCP model"},+ "$mcp_llm_model_missing_reason": {+ "description": "Why PostHog's MCP server captured no model identifier. missing means llm_model was omitted; unknown means the agent explicitly reported unknown; invalid means the argument was blank or not a string; not_captured means a nonempty report was not captured by the analytics SDK; capture_error means analytics preparation failed. Only set when no model was captured. Older events and other MCP servers may omit this property.",+ "examples": [+ "missing",+ "unknown",+ "invalid",+ "not_captured",+ "capture_error"+ ],+ "label": "MCP model missing reason"+ },"$mcp_llm_model_source": {"description": "How the model identifier was obtained. client_metadata means the MCP client supplied recognized metadata. self_reported means the agent filled the injected llm_model argument. Both sources are unverified.","examples": [@@ -4585,6 +4596,17 @@],"label": "MCP model"},+ "$mcp_llm_model_missing_reason": {+ "description": "Why PostHog's MCP server captured no model identifier. missing means llm_model was omitted; unknown means the agent explicitly reported unknown; invalid means the argument was blank or not a string; not_captured means a nonempty report was not captured by the analytics SDK; capture_error means analytics preparation failed. Only set when no model was captured. Older events and other MCP servers may omit this property.",+ "examples": [+ "missing",+ "unknown",+ "invalid",+ "not_captured",+ "capture_error"+ ],+ "label": "MCP model missing reason"+ },"$mcp_llm_model_source": {"description": "How the model identifier was obtained. client_metadata means the MCP client supplied recognized metadata. self_reported means the agent filled the injected llm_model argument. Both sources are unverified.","examples": [@@ -7423,6 +7445,17 @@],"label": "MCP model"},+ "$mcp_llm_model_missing_reason": {+ "description": "Why PostHog's MCP server captured no model identifier. missing means llm_model was omitted; unknown means the agent explicitly reported unknown; invalid means the argument was blank or not a string; not_captured means a nonempty report was not captured by the analytics SDK; capture_error means analytics preparation failed. Only set when no model was captured. Older events and other MCP servers may omit this property.",+ "examples": [+ "missing",+ "unknown",+ "invalid",+ "not_captured",+ "capture_error"+ ],+ "label": "MCP model missing reason"+ },"$mcp_llm_model_source": {"description": "How the model identifier was obtained. client_metadata means the MCP client supplied recognized metadata. self_reported means the agent filled the injected llm_model argument. Both sources are unverified.","examples": [diff --git a/posthog/schema.py b/posthog/schema.pyindex 01cac3cc0499..16f82968b701 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -12315,6 +12315,10 @@ class CachedMCPModelBreakdownQueryResponse(BaseModel):"Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."),)+ hasMore: bool | None = Field(+ default=None,+ description=("Whether another page of individual model identifiers is available."),+ )hogql: str | None = Field(default=None, description="Generated HogQL query.")is_cached: boollast_refresh: AwareDatetime@@ -18030,6 +18034,10 @@ class MCPModelBreakdownQueryResponse(BaseModel):"Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."),)+ hasMore: bool | None = Field(+ default=None,+ description=("Whether another page of individual model identifiers is available."),+ )hogql: str | None = Field(default=None, description="Generated HogQL query.")modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")query_status: QueryStatus | None = Field(@@ -23316,6 +23324,10 @@ class QueryResponseAlternative97(BaseModel):"Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."),)+ hasMore: bool | None = Field(+ default=None,+ description=("Whether another page of individual model identifiers is available."),+ )hogql: str | None = Field(default=None, description="Generated HogQL query.")modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")query_status: QueryStatus | None = Field(@@ -26843,8 +26855,17 @@ class MCPModelBreakdownQuery(BaseModel):)dateRange: DateRange | None = NonefilterTestAccounts: bool | None = None+ includeAllModels: bool | None = Field(+ default=None,+ description=("Return individual reported models, excluding Unknown, instead of the top-six grouping."),+ )kind: Literal["MCPModelBreakdownQuery"] = "MCPModelBreakdownQuery"+ limit: int | None = Field(default=None, description="Page size when includeAllModels is enabled.")modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ offset: int | None = Field(+ default=None,+ description=("Number of individual models to skip when includeAllModels is enabled."),+ )properties: list[AnyPropertyFilterDiscriminated] | None = Noneresponse: MCPModelBreakdownQueryResponse | None = Nonetags: QueryLogTags | None = Nonediff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.pyindex d5c2343e7380..df0519246a9c 100644--- a/posthog/taxonomy/taxonomy.py+++ b/posthog/taxonomy/taxonomy.py@@ -2927,6 +2927,11 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {"description": "How the model identifier was obtained. client_metadata means the MCP client supplied recognized metadata. self_reported means the agent filled the injected llm_model argument. Both sources are unverified.","examples": ["client_metadata", "self_reported"],},+ "$mcp_llm_model_missing_reason": {+ "label": "MCP model missing reason",+ "description": "Why PostHog's MCP server captured no model identifier. missing means llm_model was omitted; unknown means the agent explicitly reported unknown; invalid means the argument was blank or not a string; not_captured means a nonempty report was not captured by the analytics SDK; capture_error means analytics preparation failed. Only set when no model was captured. Older events and other MCP servers may omit this property.",+ "examples": ["missing", "unknown", "invalid", "not_captured", "capture_error"],+ },"$mcp_intent": {"label": "MCP intent","description": "Free-text description of why the agent is calling this tool, written by the agent itself. Comes from a context argument the client supplied at call time, or — if none was supplied — from an intentFallback the MCP server provides.",diff --git a/products/mcp_analytics/backend/hogql_queries/model_breakdown.py b/products/mcp_analytics/backend/hogql_queries/model_breakdown.pyindex 91f9c63eaf98..1e5c28006d2c 100644--- a/products/mcp_analytics/backend/hogql_queries/model_breakdown.py+++ b/products/mcp_analytics/backend/hogql_queries/model_breakdown.py@@ -25,6 +25,8 @@ if TYPE_CHECKING:MODEL_SERIES_LIMIT = 6+MODEL_PAGE_SIZE = 50+MODEL_MAX_PAGE_SIZE = 100class MCPModelBreakdownQueryRunner(AnalyticsQueryRunner[MCPModelBreakdownQueryResponse]):@@ -38,6 +40,10 @@ class MCPModelBreakdownQueryRunner(AnalyticsQueryRunner[MCPModelBreakdownQueryRedef query_date_range(self) -> QueryDateRange:return mcp_query_date_range(self.team, self.query.dateRange)+ @cached_property+ def page_size(self) -> int:+ return max(1, min(self.query.limit if self.query.limit is not None else MODEL_PAGE_SIZE, MODEL_MAX_PAGE_SIZE))+def _where(self) -> ast.Expr:exprs = [parse_expr("event = {event}", placeholders={"event": ast.Constant(value=MCP_TOOL_CALL_EVENT)}),@@ -54,6 +60,33 @@ class MCPModelBreakdownQueryRunner(AnalyticsQueryRunner[MCPModelBreakdownQueryRereturn ast.And(exprs=exprs)def to_query(self) -> ast.SelectQuery | ast.SelectSetQuery:+ model_totals = parse_select(+ """+ SELECT+ coalesce(nullIf(trim(toString(properties.$mcp_llm_model)), ''), 'Unknown') AS model,+ count() AS total_calls+ FROM events+ WHERE {where}+ GROUP BY model+ """,+ placeholders={"where": self._where()},+ )+ if self.query.includeAllModels:+ return parse_select(+ """+ SELECT model, total_calls+ FROM {model_totals}+ WHERE model != 'Unknown'+ ORDER BY total_calls DESC, model ASC+ LIMIT {limit} OFFSET {offset}+ """,+ placeholders={+ "model_totals": model_totals,+ "limit": ast.Constant(value=self.page_size + 1),+ "offset": ast.Constant(value=max(0, self.query.offset or 0)),+ },+ )+return parse_select("""SELECT@@ -64,20 +97,13 @@ class MCPModelBreakdownQueryRunner(AnalyticsQueryRunner[MCPModelBreakdownQueryRemodel,total_calls,row_number() OVER (ORDER BY model = 'Unknown' ASC, total_calls DESC, model ASC) AS model_rank- FROM (- SELECT- coalesce(nullIf(trim(toString(properties.$mcp_llm_model)), ''), 'Unknown') AS model,- count() AS total_calls- FROM events- WHERE {where}- GROUP BY model- )+ FROM {model_totals})GROUP BY model_groupORDER BY total_calls DESC, model_group ASC""",placeholders={- "where": self._where(),+ "model_totals": model_totals,"limit": ast.Constant(value=MODEL_SERIES_LIMIT),},)@@ -99,12 +125,16 @@ class MCPModelBreakdownQueryRunner(AnalyticsQueryRunner[MCPModelBreakdownQueryRelimit_context=self.limit_context,)- results = [- MCPModelBreakdownItem(model=str(row[0]), total_calls=int(row[1] or 0)) for row in (response.results or [])- ]+ rows = response.results or []+ has_more = False+ if self.query.includeAllModels:+ has_more = len(rows) > self.page_size+ rows = rows[: self.page_size]+ results = [MCPModelBreakdownItem(model=str(row[0]), total_calls=int(row[1] or 0)) for row in rows]return MCPModelBreakdownQueryResponse(results=results,+ hasMore=has_more,timings=response.timings,hogql=response.hogql,modifiers=self.modifiers,diff --git a/products/mcp_analytics/backend/tests/test_model_breakdown.py b/products/mcp_analytics/backend/tests/test_model_breakdown.pyindex 5cbc150526c3..86d205093d40 100644--- a/products/mcp_analytics/backend/tests/test_model_breakdown.py+++ b/products/mcp_analytics/backend/tests/test_model_breakdown.py@@ -83,3 +83,36 @@ class TestMCPModelBreakdownQueryRunner(_MCPAnalyticsTeamScopedTestMixin, Clickhoassert rows["Other"].total_calls == 15assert sum(row.total_calls for row in rows.values()) == expected_totalassert len([model for model in rows if model not in {"Other", "Unknown"}]) == MODEL_SERIES_LIMIT - 1++ expanded_rows: list[MCPModelBreakdownItem] = []+ for offset in (0, 3, 6):+ page = MCPModelBreakdownQueryRunner(+ query=MCPModelBreakdownQuery(+ dateRange=DateRange(date_from="-90d"), includeAllModels=True, limit=3, offset=offset+ ),+ team=self.team,+ ).calculate()+ assert len(page.results) == 3+ assert page.hasMore == (offset < 6)+ expanded_rows.extend(page.results)++ assert [row.model for row in expanded_rows] == ["Other", *[f"model-{index}" for index in range(8)]]+ assert expanded_rows[0].total_calls == 9+ assert sum(row.total_calls for row in expanded_rows) == expected_total - 1++ def test_bounds_pages_and_orders_tied_models_consistently(self) -> None:+ for index in range(101):+ self._emit(distinct_id=f"model-{index}", properties={"$mcp_llm_model": f"model-{index:03}"})+ flush_persons_and_events()++ first_page = MCPModelBreakdownQueryRunner(+ query=MCPModelBreakdownQuery(includeAllModels=True, limit=1000, offset=-1), team=self.team+ ).calculate()+ assert first_page.hasMore+ assert [row.model for row in first_page.results] == [f"model-{index:03}" for index in range(100)]++ last_page = MCPModelBreakdownQueryRunner(+ query=MCPModelBreakdownQuery(includeAllModels=True, limit=0, offset=100), team=self.team+ ).calculate()+ assert not last_page.hasMore+ assert last_page.results == [MCPModelBreakdownItem(model="model-100", total_calls=1)]diff --git a/products/mcp_analytics/frontend/MCPAnalyticsDashboardOverview.tsx b/products/mcp_analytics/frontend/MCPAnalyticsDashboardOverview.tsxindex e95097652843..26ddd7fcb60c 100644--- a/products/mcp_analytics/frontend/MCPAnalyticsDashboardOverview.tsx+++ b/products/mcp_analytics/frontend/MCPAnalyticsDashboardOverview.tsx@@ -33,7 +33,7 @@ export function MCPAnalyticsDashboardOverview(): JSX.Element {harnessRows,harnessRowsLoading,modelRows,- hasKnownModelData,+ hasModelData,dailyActivity,activityRowsLoading,activityIncompleteTail,@@ -46,6 +46,7 @@ export function MCPAnalyticsDashboardOverview(): JSX.Element {interval,filterTestAccounts,propertyFilters,+ queryFilters,} = useValues(mcpDashboardOverviewLogic)const { setDateFilter, setFilterTestAccounts, setPropertyFilters } = useActions(mcpDashboardOverviewLogic)const { timezone } = useValues(teamLogic)@@ -109,7 +110,7 @@ export function MCPAnalyticsDashboardOverview(): JSX.Element {<divclassName={cn('grid grid-cols-1 gap-[22px]',- hasKnownModelData ? 'lg:grid-cols-4' : 'lg:grid-cols-3'+ hasModelData ? 'lg:grid-cols-4' : 'lg:grid-cols-3')}><div className="flex lg:col-span-2">@@ -123,7 +124,7 @@ export function MCPAnalyticsDashboardOverview(): JSX.Element {/></div><HarnessBarChart rows={harnessRows} loading={harnessRowsLoading} theme={theme} />- {hasKnownModelData ? <ModelBarChart rows={modelRows} theme={theme} /> : null}+ {hasModelData ? <ModelBarChart rows={modelRows} theme={theme} filters={queryFilters} /> : null}</div><div className="grid grid-cols-1 gap-[22px] lg:grid-cols-2"><ToolErrorRateChart rows={toolRows} loading={toolRowsLoading} theme={theme} />diff --git a/products/mcp_analytics/frontend/dashboard/DashboardCards.stories.tsx b/products/mcp_analytics/frontend/dashboard/DashboardCards.stories.tsxindex fc0e7d9c656f..0e0f2a7cd3b1 100644--- a/products/mcp_analytics/frontend/dashboard/DashboardCards.stories.tsx+++ b/products/mcp_analytics/frontend/dashboard/DashboardCards.stories.tsx@@ -4,6 +4,10 @@ import { type ChartTheme } from '@posthog/quill-charts'import { buildTheme } from 'lib/charts/utils/theme'+import { mswDecorator } from '~/mocks/browser'+import { MCPModelBreakdownQuery } from '~/queries/schema/schema-general'++import { MCPAnalyticsDashboardOverview } from '../MCPAnalyticsDashboardOverview'import {type DailyActivity,type HarnessRow,@@ -78,6 +82,31 @@ const MODEL_ROWS: ModelRow[] = [{ model: 'grok-3', total_calls: 320 },]+const ALL_MODEL_ROWS: ModelRow[] = [+ ...MODEL_ROWS.filter((row) => row.model !== 'Unknown' && row.model !== 'Other'),+ ...Array.from({ length: 58 }, (_, index) => ({+ model: `example-provider/model-with-a-long-version-name-${String(index + 1).padStart(2, '0')}`,+ total_calls: 10,+ })),+]++const modelPagesDecorator = mswDecorator({+ post: {+ '/api/environments/:team_id/query/:kind': async ({ request }) => {+ const { query } = (await request.json()) as { query: MCPModelBreakdownQuery }+ const offset = query.offset ?? 0+ const limit = query.limit ?? 50+ return [+ 200,+ {+ results: ALL_MODEL_ROWS.slice(offset, offset + limit),+ hasMore: offset + limit < ALL_MODEL_ROWS.length,+ },+ ]+ },+ },+})+const NOTABLE_SESSIONS: NotableSession[] = [{rule: 'worst_error_rate',@@ -270,6 +299,25 @@ export const ShareByHarnessOtherOnly: Story = {}export const ShareByModel: Story = {+ decorators: [modelPagesDecorator],+ render: withTheme((theme) => <ModelBarChart rows={MODEL_ROWS} theme={theme} />),+}++export const ShareByModelExpandedNarrow: Story = {+ decorators: [modelPagesDecorator],+ render: () => (+ <div className="w-80">+ <ModelBarChart rows={MODEL_ROWS} theme={buildTheme()} />+ </div>+ ),+}++export const ShareByModelLoadError: Story = {+ decorators: [+ mswDecorator({+ post: { '/api/environments/:team_id/query/:kind': [500, { detail: 'Could not load models' }] },+ }),+ ],render: withTheme((theme) => <ModelBarChart rows={MODEL_ROWS} theme={theme} />),}@@ -293,6 +341,31 @@ export const ShareByModelNarrow: Story = {),}+export const ShareByModelLowCoverage: Story = {+ render: withTheme((theme) => (+ <ModelBarChart+ rows={[+ { model: 'Unknown', total_calls: 900 },+ { model: 'example-model', total_calls: 70 },+ { model: 'Other', total_calls: 30 },+ ]}+ theme={theme}+ />+ )),+}++export const ShareByModelFullCoverage: Story = {+ render: withTheme((theme) => <ModelBarChart rows={[{ model: 'example-model', total_calls: 100 }]} theme={theme} />),+}++export const ShareByModelUnknownOnly: Story = {+ render: withTheme((theme) => <ModelBarChart rows={[{ model: 'Unknown', total_calls: 100 }]} theme={theme} />),+}++export const ShareByModelEmpty: Story = {+ render: withTheme((theme) => <ModelBarChart rows={[]} theme={theme} />),+}+export const ErrorRateByTool: Story = {render: withTheme((theme) => <ToolErrorRateChart rows={TOOL_ROWS} loading={false} theme={theme} />),}@@ -310,3 +383,23 @@ export const FlaggedSessions: Story = {</div>),}++export const OverviewUnknownModels: Story = {+ decorators: [+ mswDecorator({+ post: {+ '/api/environments/:team_id/query/:kind': async ({ request }) => {+ const { query } = (await request.json()) as { query: { kind: string } }+ return [+ 200,+ {+ results:+ query.kind === 'MCPModelBreakdownQuery' ? [{ model: 'Unknown', total_calls: 100 }] : [],+ },+ ]+ },+ },+ }),+ ],+ render: () => <MCPAnalyticsDashboardOverview />,+}diff --git a/products/mcp_analytics/frontend/dashboard/ModelBarChart.tsx b/products/mcp_analytics/frontend/dashboard/ModelBarChart.tsxindex e9699a5ece5d..63a5ba09571d 100644--- a/products/mcp_analytics/frontend/dashboard/ModelBarChart.tsx+++ b/products/mcp_analytics/frontend/dashboard/ModelBarChart.tsx@@ -1,5 +1,7 @@+import { useActions, useValues } from 'kea'import { useMemo } from 'react'+import { IconChevronDown } from '@posthog/icons'import {BarChart,type BarChartConfig,@@ -10,14 +12,26 @@ import {} from '@posthog/quill-charts'import { useChartConfig } from 'lib/charts/hooks'+import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { LemonCard } from 'lib/lemon-ui/LemonCard'+import { LemonProgress } from 'lib/lemon-ui/LemonProgress'import { formatPercentage } from 'lib/utils/numbers'+import { urls } from 'scenes/urls'++import { HogQLFilters } from '~/queries/schema/schema-general'import { type ModelRow } from '../mcpDashboardOverviewLogic'-import { Card } from './Card'import { ChartTooltip } from './ChartTooltip'import { formatNumber } from './formatters'+import { buildModelExplorationQuery, summarizeModelBreakdown } from './modelBreakdown'+import { modelBreakdownLogic } from './modelBreakdownLogic'+import { ModelBreakdownTable } from './ModelBreakdownTable'import { modelColor } from './modelColors'+function modelLabel(model: string): string {+ return model === 'Other' ? 'Other models' : model+}+function ModelBarLabels({ rows, totalCalls }: { rows: ModelRow[]; totalCalls: number }): JSX.Element {const { scales } = useChartLayout()return (@@ -28,8 +42,8 @@ function ModelBarLabels({ rows, totalCalls }: { rows: ModelRow[]; totalCalls: nuclassName="absolute left-0 right-0 flex items-center justify-between gap-2 text-xs"style={{ top: (scales.x(row.model) ?? 0) - 26 }}>- <span className="truncate" title={row.model}>- {row.model}+ <span className="truncate" title={modelLabel(row.model)}>+ {modelLabel(row.model)}</span><span className="shrink-0 text-secondary tabular-nums">{formatPercentage(totalCalls > 0 ? (row.total_calls / totalCalls) * 100 : 0, { compact: true })}{' '}@@ -49,18 +63,33 @@ function renderTooltip(ctx: TooltipContext<ModelRow & { share: number }>): JSX.E}return (<ChartTooltip- title={row.model}+ title={modelLabel(row.model)}rows={[['Calls', formatNumber(row.total_calls)],- ['Share', formatPercentage(row.share, { compact: true })],+ ['Share of all calls', formatPercentage(row.share, { compact: true })],]}/>)}-export function ModelBarChart({ rows, theme }: { rows: ModelRow[]; theme: ChartTheme }): JSX.Element {- const totalCalls = rows.reduce((total, row) => total + row.total_calls, 0)- const sortedRows = useMemo(() => [...rows].sort((a, b) => b.total_calls - a.total_calls), [rows])+export function ModelBarChart({+ rows,+ theme,+ filters = {},+}: {+ rows: ModelRow[]+ theme: ChartTheme+ filters?: HogQLFilters+}): JSX.Element {+ const logic = modelBreakdownLogic({ filters })+ const { expanded, modelPageLoading } = useValues(logic)+ const { setExpanded } = useActions(logic)+ const {+ totalCalls,+ unknownCalls,+ identifiedShare,+ rankedModels: sortedRows,+ } = useMemo(() => summarizeModelBreakdown(rows), [rows])const labels = useMemo(() => sortedRows.map((row) => row.model), [sortedRows])const series = useMemo<Series<ModelRow & { share: number }>[]>(() => [@@ -69,7 +98,7 @@ export function ModelBarChart({ rows, theme }: { rows: ModelRow[]; theme: ChartTlabel: 'Calls',data: sortedRows.map((row) => row.total_calls),bars: sortedRows.map((row) => ({- label: row.model,+ label: modelLabel(row.model),color: modelColor(theme, row.model),meta: { ...row, share: totalCalls > 0 ? (row.total_calls / totalCalls) * 100 : 0 },})),@@ -77,8 +106,6 @@ export function ModelBarChart({ rows, theme }: { rows: ModelRow[]; theme: ChartT],[sortedRows, theme, totalCalls])- const identifiedCalls = totalCalls - (rows.find((row) => row.model === 'Unknown')?.total_calls ?? 0)- const identifiedShare = totalCalls > 0 ? (identifiedCalls / totalCalls) * 100 : 0const config = useChartConfig<BarChartConfig>(() => ({axisOrientation: 'horizontal',@@ -89,21 +116,93 @@ export function ModelBarChart({ rows, theme }: { rows: ModelRow[]; theme: ChartTshowTickMarks: false,margins: { left: 0, right: 0, top: 20, bottom: 0 },barCornerRadius: 4,- bars: { bandPadding: 0.65, maxBandRange: rows.length * 40 },+ bars: { bandPadding: 0.65, maxBandRange: sortedRows.length * 40 },}),- [rows.length]+ [sortedRows.length])return (- <Card className="flex flex-1 flex-col" title="Share of calls by model">- <div className="text-xs text-secondary" translate="no">- {formatPercentage(identifiedShare, { compact: true })} identified+ <LemonCard className="flex min-w-0 flex-1 flex-col p-0 overflow-hidden" hoverEffect={false}>+ <div className="flex flex-wrap items-center justify-between gap-2 border-b px-4 py-3">+ <h3 className="mb-0 text-sm font-semibold">Share of calls by model</h3>+ <LemonButton+ type="tertiary"+ size="xsmall"+ to={urls.insightNew({ query: buildModelExplorationQuery(filters) })}+ >+ Explore models+ </LemonButton></div>- <div className="flex h-80 flex-col" translate="no">- <BarChart series={series} labels={labels} theme={theme} config={config} tooltip={renderTooltip}>- <ModelBarLabels rows={sortedRows} totalCalls={totalCalls} />- </BarChart>+ <div className="flex flex-col gap-4 p-4">+ <div className="flex flex-col gap-2">+ <div className="flex flex-wrap justify-between gap-1 text-xs">+ <span className="font-medium">Model coverage</span>+ <span className="text-secondary tabular-nums">{formatNumber(totalCalls)} calls</span>+ </div>+ <LemonProgress+ percent={identifiedShare}+ smoothing={false}+ bgColor="var(--color-border-primary)"+ role="progressbar"+ aria-label="Model identification coverage"+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuenow={identifiedShare}+ />+ <div className="flex flex-wrap justify-between gap-x-3 gap-y-1 text-xs tabular-nums">+ <span>{formatPercentage(identifiedShare, { compact: true })} identified</span>+ <span className="text-secondary">+ {formatNumber(unknownCalls)} unknown+ {totalCalls > 0+ ? ` (${formatPercentage((unknownCalls / totalCalls) * 100, { compact: true })})`+ : ''}+ </span>+ </div>+ </div>+ {sortedRows.length > 0 ? (+ <div>+ <div className="mb-2 text-xs text-secondary">Reported models · % of all calls</div>+ <div className="flex flex-col" style={{ height: sortedRows.length * 40 + 20 }} translate="no">+ <BarChart+ series={series}+ labels={labels}+ theme={theme}+ config={config}+ tooltip={renderTooltip}+ >+ <ModelBarLabels rows={sortedRows} totalCalls={totalCalls} />+ </BarChart>+ </div>+ </div>+ ) : (+ <p className="mb-0 text-xs text-secondary">+ {totalCalls > 0+ ? 'No model identifiers were captured for these calls.'+ : 'No calls in this period.'}+ </p>+ )}+ <p className="mb-0 text-xs text-secondary">+ {sortedRows.some((row) => row.model === 'Other')+ ? 'Other models includes identified models outside the top six. '+ : ''}+ Unknown means no model identifier was captured. Model names are reported by clients or agents.+ </p>+ {expanded || sortedRows.some((row) => row.model === 'Other') ? (+ <LemonButton+ type="tertiary"+ size="small"+ fullWidth+ center+ icon={<IconChevronDown className={expanded ? 'rotate-180' : undefined} />}+ loading={modelPageLoading}+ aria-expanded={expanded}+ onClick={() => setExpanded(!expanded)}+ >+ {expanded ? 'Show fewer models' : 'Show all models'}+ </LemonButton>+ ) : null}+ {expanded ? <ModelBreakdownTable filters={filters} totalCalls={totalCalls} /> : null}</div>- </Card>+ </LemonCard>)}diff --git a/products/mcp_analytics/frontend/dashboard/ModelBreakdownTable.tsx b/products/mcp_analytics/frontend/dashboard/ModelBreakdownTable.tsxnew file mode 100644index 000000000000..6d408cd1d3b0--- /dev/null+++ b/products/mcp_analytics/frontend/dashboard/ModelBreakdownTable.tsx@@ -0,0 +1,98 @@+import { useActions, useValues } from 'kea'++import { LemonBanner } from 'lib/lemon-ui/LemonBanner'+import { LemonTable } from 'lib/lemon-ui/LemonTable'+import { PaginationControl, usePagination } from 'lib/lemon-ui/PaginationControl'+import { formatPercentage } from 'lib/utils/numbers'++import { HogQLFilters, MCPModelBreakdownItem } from '~/queries/schema/schema-general'++import { formatNumber } from './formatters'+import { MODEL_PAGE_SIZE, modelBreakdownLogic } from './modelBreakdownLogic'++export function ModelBreakdownTable({+ filters,+ totalCalls,+}: {+ filters: HogQLFilters+ totalCalls: number+}): JSX.Element {+ const logic = modelBreakdownLogic({ filters })+ const { modelPage, modelPageLoading, loadFailed, requestedOffset } = useValues(logic)+ const { loadModels } = useActions(logic)+ const pagination = usePagination(modelPage?.results ?? [], {+ controlled: true,+ useUrl: false,+ hideOnSinglePage: false,+ onForward:+ modelPage?.hasMore && !modelPageLoading ? () => loadModels(modelPage.offset + MODEL_PAGE_SIZE) : undefined,+ onBackward:+ modelPage && modelPage.offset > 0 && !modelPageLoading+ ? () => loadModels(Math.max(0, modelPage.offset - MODEL_PAGE_SIZE))+ : undefined,+ })++ if (loadFailed) {+ return (+ <LemonBanner type="error" action={{ children: 'Retry', onClick: () => loadModels(requestedOffset) }}>+ Couldn't load models. Try again.+ </LemonBanner>+ )+ }++ return (+ <div className="flex flex-col gap-2">+ <div className="h-96">+ <LemonTable<MCPModelBreakdownItem>+ key={modelPage?.offset ?? 0}+ dataSource={modelPage?.results ?? []}+ rowKey="model"+ size="small"+ embedded+ tableLayout="fixed"+ allowContentScroll+ uppercaseHeader={false}+ loading={modelPageLoading}+ loadingSkeletonRows={3}+ disableTableWhileLoading+ nouns={['model', 'models']}+ emptyState="No reported models match these filters."+ columns={[+ {+ title: 'Model',+ dataIndex: 'model',+ render: (_, row) => (+ <span className="break-all" translate="no">+ {row.model}+ </span>+ ),+ },+ {+ title: 'Calls',+ width: 75,+ align: 'right',+ render: (_, row) => (+ <span className="tabular-nums" title={String(row.total_calls)}>+ {formatNumber(row.total_calls)}+ </span>+ ),+ },+ {+ title: '% of all calls',+ width: 100,+ align: 'right',+ render: (_, row) => (+ <span className="tabular-nums">+ {formatPercentage(totalCalls > 0 ? (row.total_calls / totalCalls) * 100 : 0, {+ compact: true,+ })}+ </span>+ ),+ },+ ]}+ />+ </div>+ <PaginationControl {...pagination} nouns={['model', 'models']} />+ </div>+ )+}diff --git a/products/mcp_analytics/frontend/dashboard/modelBreakdown.test.ts b/products/mcp_analytics/frontend/dashboard/modelBreakdown.test.tsnew file mode 100644index 000000000000..6f61440c5da7--- /dev/null+++ b/products/mcp_analytics/frontend/dashboard/modelBreakdown.test.ts@@ -0,0 +1,86 @@+import { HogQLFilters, NodeKind } from '~/queries/schema/schema-general'+import { PropertyFilterType, PropertyOperator } from '~/types'++import { buildModelExplorationQuery, freezeModelDateRange, summarizeModelBreakdown } from './modelBreakdown'++describe('model breakdown', () => {+ beforeEach(() => jest.useFakeTimers())+ afterEach(() => jest.useRealTimers())++ it('keeps unknown calls in coverage and the denominator while ranking named models before Other', () => {+ const rows = [+ { model: 'Unknown', total_calls: 50 },+ { model: 'Other', total_calls: 30 },+ { model: 'example-small', total_calls: 5 },+ { model: 'example-large', total_calls: 15 },+ ]+ const summary = summarizeModelBreakdown(rows)++ expect(summary.totalCalls).toBe(100)+ expect(summary.unknownCalls).toBe(50)+ expect(summary.identifiedShare).toBe(50)+ expect(summary.rankedModels).toEqual([rows[3], rows[2], rows[1]])+ expect(summary.rankedModels[0].total_calls / summary.totalCalls).toBe(0.15)+ expect(rows[0].model).toBe('Unknown')+ })++ it.each([+ { rows: [], totalCalls: 0, unknownCalls: 0, identifiedShare: 0 },+ {+ rows: [{ model: 'Unknown', total_calls: 12 }],+ totalCalls: 12,+ unknownCalls: 12,+ identifiedShare: 0,+ },+ {+ rows: [{ model: 'example-model', total_calls: 12 }],+ totalCalls: 12,+ unknownCalls: 0,+ identifiedShare: 100,+ },+ ])('handles coverage without both known and unknown calls: $rows', ({ rows, ...expected }) => {+ expect(summarizeModelBreakdown(rows)).toMatchObject(expected)+ })++ it('opens a model count table with the same date, property, and test-account filters', () => {+ const filters: HogQLFilters = {+ dateRange: { date_from: '-14d', date_to: null },+ filterTestAccounts: true,+ properties: [+ {+ key: '$mcp_server_name',+ type: PropertyFilterType.Event,+ operator: PropertyOperator.Exact,+ value: ['example-server'],+ },+ ],+ }+ const query = buildModelExplorationQuery(filters)++ expect(query).toMatchObject(filters)+ expect(query.series).toEqual([{ kind: NodeKind.EventsNode, event: '$mcp_tool_call', math: 'total' }])+ expect(query.breakdownFilter).toMatchObject({+ breakdown: "coalesce(nullIf(trim(toString(properties.$mcp_llm_model)), ''), 'Unknown')",+ breakdown_type: 'hogql',+ })+ expect(query.trendsFilter?.display).toBe('ActionsTable')+ })+ it.each([+ { date_from: '-14d', expectedFrom: '2026-08-28T07:00:00.000Z' },+ { date_from: '-1h', expectedFrom: '2026-09-11T14:00:00.000Z' },+ { date_from: 'all', expectedFrom: 'all' },+ { date_from: '2026-09-10T14:25:00Z', expectedFrom: '2026-09-10T14:25:00Z' },+ ])('freezes the open range $date_from in the project timezone', ({ date_from, expectedFrom }) => {+ jest.setSystemTime(new Date('2026-09-11T15:30:00Z'))+ expect(freezeModelDateRange({ date_from }, 'America/Los_Angeles')).toEqual({+ date_from: expectedFrom,+ date_to: '2026-09-11T15:30:00.000Z',+ explicitDate: true,+ })+ })++ it('preserves a fixed date range', () => {+ const dateRange = { date_from: '2026-09-01', date_to: '2026-09-05' }+ expect(freezeModelDateRange(dateRange, 'America/Los_Angeles')).toEqual(dateRange)+ })+})diff --git a/products/mcp_analytics/frontend/dashboard/modelBreakdown.ts b/products/mcp_analytics/frontend/dashboard/modelBreakdown.tsnew file mode 100644index 000000000000..7c6f8a652e80--- /dev/null+++ b/products/mcp_analytics/frontend/dashboard/modelBreakdown.ts@@ -0,0 +1,59 @@+import { dayjs } from 'lib/dayjs'+import { dateStringToComponents, dateStringToDayJs } from 'lib/utils/dateFilters'++import { DateRange, HogQLFilters, MCPModelBreakdownItem, NodeKind, TrendsQuery } from '~/queries/schema/schema-general'+import { BaseMathType, ChartDisplayType } from '~/types'++export function summarizeModelBreakdown(rows: MCPModelBreakdownItem[]): {+ totalCalls: number+ unknownCalls: number+ identifiedShare: number+ rankedModels: MCPModelBreakdownItem[]+} {+ const totalCalls = rows.reduce((total, row) => total + row.total_calls, 0)+ const unknownCalls = rows+ .filter((row) => row.model === 'Unknown')+ .reduce((total, row) => total + row.total_calls, 0)++ return {+ totalCalls,+ unknownCalls,+ identifiedShare: totalCalls > 0 ? ((totalCalls - unknownCalls) / totalCalls) * 100 : 0,+ rankedModels: rows+ .filter((row) => row.model !== 'Unknown')+ .sort((a, b) => Number(a.model === 'Other') - Number(b.model === 'Other') || b.total_calls - a.total_calls),+ }+}++export function buildModelExplorationQuery(filters: HogQLFilters): TrendsQuery {+ return {+ ...filters,+ kind: NodeKind.TrendsQuery,+ series: [{ kind: NodeKind.EventsNode, event: '$mcp_tool_call', math: BaseMathType.TotalCount }],+ breakdownFilter: {+ breakdown: "coalesce(nullIf(trim(toString(properties.$mcp_llm_model)), ''), 'Unknown')",+ breakdown_type: 'hogql',+ breakdown_limit: 50,+ },+ trendsFilter: { display: ChartDisplayType.ActionsTable },+ }+}++export function freezeModelDateRange(dateRange: DateRange | undefined, timezone: string): DateRange {+ if (dateRange?.date_to) {+ return dateRange+ }+ const dateFrom = dateRange?.date_from ?? '-7d'+ const components = dateStringToComponents(dateFrom)+ let start = components ? dateStringToDayJs(dateFrom, timezone) : null+ // Match the model query's relative hour rounding before sending an explicit range.+ if (start && components?.unit === 'hour') {+ start = start.startOf('hour')+ }+ return {+ ...dateRange,+ date_from: start?.toISOString() ?? dateFrom,+ date_to: dayjs().toISOString(),+ explicitDate: true,+ }+}diff --git a/products/mcp_analytics/frontend/dashboard/modelBreakdownLogic.test.ts b/products/mcp_analytics/frontend/dashboard/modelBreakdownLogic.test.tsnew file mode 100644index 000000000000..94147d652840--- /dev/null+++ b/products/mcp_analytics/frontend/dashboard/modelBreakdownLogic.test.ts@@ -0,0 +1,113 @@+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'++import { expectLogic } from 'kea-test-utils'++import api from 'lib/api'+import { dayjs } from 'lib/dayjs'++import { HogQLFilters, NodeKind } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'+import { PropertyFilterType, PropertyOperator } from '~/types'++import { MODEL_PAGE_SIZE, modelBreakdownLogic } from './modelBreakdownLogic'++jest.mock('lib/api')++const mockApi = api as jest.Mocked<typeof api>++describe('modelBreakdownLogic', () => {+ beforeEach(() => {+ jest.clearAllMocks()+ initKeaTests()+ jest.useFakeTimers({ doNotFake: ['setTimeout', 'clearTimeout', 'queueMicrotask'] })+ jest.setSystemTime(new Date('2026-09-11T15:30:00Z'))+ })++ afterEach(() => {+ jest.useRealTimers()+ })++ it('loads individual models on expansion and preserves filters across pages', async () => {+ const filters: HogQLFilters = {+ dateRange: { date_from: '-14d' },+ filterTestAccounts: true,+ properties: [+ {+ key: '$mcp_server_name',+ type: PropertyFilterType.Event,+ operator: PropertyOperator.Exact,+ value: ['example-server'],+ },+ ],+ }+ const logic = modelBreakdownLogic({ filters })+ logic.mount()+ expect(mockApi.query).not.toHaveBeenCalled()+ mockApi.query.mockResolvedValueOnce({ results: [{ model: 'example-a', total_calls: 10 }], hasMore: true })++ await expectLogic(logic, () => logic.actions.setExpanded(true)).toFinishAllListeners()+ const frozenDateRange = {+ date_from: dayjs().tz(MOCK_DEFAULT_TEAM.timezone).startOf('day').subtract(14, 'day').toISOString(),+ date_to: dayjs().toISOString(),+ explicitDate: true,+ }+ expect(mockApi.query).toHaveBeenLastCalledWith({+ ...filters,+ dateRange: frozenDateRange,+ kind: NodeKind.MCPModelBreakdownQuery,+ includeAllModels: true,+ limit: MODEL_PAGE_SIZE,+ offset: 0,+ })+ expect(logic.values.modelPage?.results[0].model).toBe('example-a')++ jest.setSystemTime(new Date('2026-09-12T15:30:00Z'))+ mockApi.query.mockResolvedValueOnce({ results: [{ model: 'example-b', total_calls: 5 }], hasMore: false })+ await expectLogic(logic, () => logic.actions.loadModels(MODEL_PAGE_SIZE)).toFinishAllListeners()+ expect(mockApi.query).toHaveBeenLastCalledWith({+ ...filters,+ dateRange: frozenDateRange,+ kind: NodeKind.MCPModelBreakdownQuery,+ includeAllModels: true,+ limit: MODEL_PAGE_SIZE,+ offset: MODEL_PAGE_SIZE,+ })+ expect(logic.values.modelPage).toMatchObject({+ offset: MODEL_PAGE_SIZE,+ hasMore: false,+ results: [{ model: 'example-b', total_calls: 5 }],+ })++ await expectLogic(logic, () => {+ logic.actions.setExpanded(false)+ logic.actions.setExpanded(true)+ }).toFinishAllListeners()+ expect(mockApi.query).toHaveBeenCalledTimes(2)++ const changedFiltersLogic = modelBreakdownLogic({ filters: { ...filters, dateRange: { date_from: '-7d' } } })+ changedFiltersLogic.mount()+ expect(changedFiltersLogic.values).toMatchObject({ expanded: false, modelPage: null })+ })++ it('exposes failed loads and retries the requested page', async () => {+ const logic = modelBreakdownLogic({ filters: {} })+ logic.mount()+ mockApi.query.mockRejectedValueOnce(new Error('Query failed'))+ await expectLogic(logic, () => logic.actions.loadModels(MODEL_PAGE_SIZE)).toFinishAllListeners()+ expect(logic.values).toMatchObject({+ loadFailed: true,+ requestedOffset: MODEL_PAGE_SIZE,+ modelPageLoading: false,+ })++ const failedDateRange = mockApi.query.mock.calls[0][0].dateRange+ jest.setSystemTime(new Date('2026-09-12T15:30:00Z'))+ mockApi.query.mockResolvedValueOnce({ results: [], hasMore: false })+ await expectLogic(logic, () => logic.actions.loadModels(logic.values.requestedOffset)).toFinishAllListeners()+ expect(mockApi.query.mock.calls[1][0].dateRange).toEqual(failedDateRange)+ expect(logic.values).toMatchObject({+ loadFailed: false,+ modelPage: { results: [], hasMore: false, offset: MODEL_PAGE_SIZE },+ })+ })+})diff --git a/products/mcp_analytics/frontend/dashboard/modelBreakdownLogic.ts b/products/mcp_analytics/frontend/dashboard/modelBreakdownLogic.tsnew file mode 100644index 000000000000..49becf5489a8--- /dev/null+++ b/products/mcp_analytics/frontend/dashboard/modelBreakdownLogic.ts@@ -0,0 +1,94 @@+import { MakeLogicType, actions, kea, key, listeners, path, props, reducers } from 'kea'+import { loaders } from 'kea-loaders'++import api from 'lib/api'+import { teamLogic } from 'scenes/teamLogic'++import {+ HogQLFilters,+ MCPModelBreakdownItem,+ MCPModelBreakdownQueryResponse,+ NodeKind,+} from '~/queries/schema/schema-general'++import { freezeModelDateRange } from './modelBreakdown'++export const MODEL_PAGE_SIZE = 50++interface ModelBreakdownLogicProps {+ filters: HogQLFilters+}++interface ModelPage {+ results: MCPModelBreakdownItem[]+ hasMore: boolean+ offset: number+}++export interface modelBreakdownLogicValues {+ expanded: boolean+ modelPage: ModelPage | null+ modelPageLoading: boolean+ loadFailed: boolean+ requestedOffset: number+}++export interface modelBreakdownLogicActions {+ setExpanded: (expanded: boolean) => { expanded: boolean }+ loadModels: (offset: number) => { offset: number }+ loadModelsSuccess: (+ modelPage: ModelPage | null,+ payload?: { offset: number }+ ) => { modelPage: ModelPage | null; payload?: { offset: number } }+ loadModelsFailure: (error: string, errorObject?: unknown) => { error: string; errorObject?: unknown }+}++export type modelBreakdownLogicType = MakeLogicType<+ modelBreakdownLogicValues,+ modelBreakdownLogicActions,+ ModelBreakdownLogicProps+>++export const modelBreakdownLogic = kea<modelBreakdownLogicType>([+ props({} as ModelBreakdownLogicProps),+ key(({ filters }) => JSON.stringify(filters)),+ path((key) => ['products', 'mcp_analytics', 'frontend', 'dashboard', 'modelBreakdownLogic', key]),+ actions({+ setExpanded: (expanded: boolean) => ({ expanded }),+ loadModels: (offset: number) => ({ offset }),+ }),+ loaders(({ props, cache }) => ({+ modelPage: [+ null as ModelPage | null,+ {+ loadModels: async ({ offset }: { offset: number }, breakpoint): Promise<ModelPage> => {+ const { dateRange, properties, filterTestAccounts } = props.filters+ cache.dateRange ??= freezeModelDateRange(dateRange, teamLogic.values.timezone)+ const response = (await api.query({+ kind: NodeKind.MCPModelBreakdownQuery,+ dateRange: cache.dateRange,+ properties,+ filterTestAccounts,+ includeAllModels: true,+ limit: MODEL_PAGE_SIZE,+ offset,+ })) as MCPModelBreakdownQueryResponse+ breakpoint()+ return { results: response.results, hasMore: response.hasMore ?? false, offset }+ },+ },+ ],+ })),+ reducers({+ expanded: [false, { setExpanded: (_, { expanded }) => expanded }],+ requestedOffset: [0, { loadModels: (_, { offset }) => offset }],+ loadFailed: [false, { loadModels: () => false, loadModelsFailure: () => true }],+ }),+ listeners(({ actions, values }) => ({+ setExpanded: ({ expanded }) => {+ if (expanded && !values.modelPage && !values.modelPageLoading) {+ actions.loadModels(0)+ }+ },+ })),+])diff --git a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.tsindex 5fa2640d2bcd..e7e9892a09a4 100644--- a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts+++ b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts@@ -394,22 +394,18 @@ describe('mcpDashboardOverviewLogic', () => {jest.spyOn(mockApi, 'query').mockResolvedValue({ results: [] } as any)})- it('shows model data only when at least one identified model has calls', async () => {+ it.each([+ { rows: [], visible: false },+ { rows: [{ model: 'Unknown', total_calls: 12 }], visible: true },+ { rows: [{ model: 'gpt-5.6-sol', total_calls: 1 }], visible: true },+ { rows: [{ model: 'claude-sonnet-5', total_calls: 0 }], visible: false },+ ])('shows model coverage when calls exist: $rows', async ({ rows, visible }) => {const logic = mcpDashboardOverviewLogic()logic.mount()await expectLogic(logic).toFinishAllListeners()- logic.actions.loadModelRowsSuccess([{ model: 'Unknown', total_calls: 12 }])- expect(logic.values.hasKnownModelData).toBe(false)-- logic.actions.loadModelRowsSuccess([{ model: 'gpt-5.6-sol', total_calls: 1 }])- expect(logic.values.hasKnownModelData).toBe(true)-- logic.actions.loadModelRowsSuccess([- { model: 'Unknown', total_calls: 12 },- { model: 'claude-sonnet-5', total_calls: 0 },- ])- expect(logic.values.hasKnownModelData).toBe(false)+ logic.actions.loadModelRowsSuccess(rows)+ expect(logic.values.hasModelData).toBe(visible)})})diff --git a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.tsindex 93afb904283f..8d98908a5d14 100644--- a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts+++ b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts@@ -391,7 +391,7 @@ export interface mcpDashboardOverviewLogicValues {filterTestAccountsOverride: boolean | nullharnessRows: HarnessRow[]harnessRowsLoading: boolean- hasKnownModelData: boolean+ hasModelData: booleanintentClusterCount: KPIMetricinterval: IntervalTypekpiIncompleteTail: boolean@@ -612,7 +612,7 @@ export interface mcpDashboardOverviewLogicMeta {dailyActivity: (activityRows: ActivityRow[], bucketKeys: string[]) => DailyActivitytoolDailySeries: (toolDailyRows: ToolDailyRow[], bucketKeys: string[]) => ToolDailySeriesnotableSessions: (sessionRows: SessionRow[]) => NotableSession[]- hasKnownModelData: (modelRows: ModelRow[]) => boolean+ hasModelData: (modelRows: ModelRow[]) => booleanintentClusterCount: (totalClusterCount: number) => KPIMetric}}@@ -905,9 +905,9 @@ export const mcpDashboardOverviewLogic = kea<mcpDashboardOverviewLogicType>([(s) => [s.sessionRows],(sessionRows: SessionRow[]): NotableSession[] => pickNotableSessions(sessionRows),],- hasKnownModelData: [+ hasModelData: [(s) => [s.modelRows],- (modelRows: ModelRow[]): boolean => modelRows.some((row) => row.model !== 'Unknown' && row.total_calls > 0),+ (modelRows: ModelRow[]): boolean => modelRows.some((row) => row.total_calls > 0),],intentClusterCount: [// The snapshot only stores the top clusters by call volume — reportdiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex faaaa769b6f2..5067280cc04e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -46732,6 +46732,8 @@ export namespace Schemas {export interface MCPModelBreakdownQueryResponse {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;+ /** Whether another page of individual model identifiers is available. */+ hasMore?: boolean | null;/** Generated HogQL query. */hogql?: string | null;/** Modifiers used when performing the query */@@ -46754,9 +46756,15 @@ export namespace Schemas {export interface MCPModelBreakdownQuery {dateRange?: DateRange | null;filterTestAccounts?: boolean | null;+ /** Return individual reported models, excluding Unknown, instead of the top-six grouping. */+ includeAllModels?: boolean | null;kind?: 'MCPModelBreakdownQuery';+ /** Page size when includeAllModels is enabled. */+ limit?: number | null;/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiers | null;+ /** Number of individual models to skip when includeAllModels is enabled. */+ offset?: number | null;properties?: (EventPropertyFilter | PersonPropertyFilter | PersonMetadataPropertyFilter | ElementPropertyFilter | EventMetadataPropertyFilter | SessionPropertyFilter | CohortPropertyFilter | RecordingPropertyFilter | LogEntryPropertyFilter | GroupPropertyFilter | FeaturePropertyFilter | FlagPropertyFilter | HogQLPropertyFilter | EmptyPropertyFilter | DataWarehousePropertyFilter | DataWarehousePersonPropertyFilter | ErrorTrackingIssueFilter | LogPropertyFilter | MetricPropertyFilter | SpanPropertyFilter | RevenueAnalyticsPropertyFilter | AccountCustomPropertyFilter | WorkflowVariablePropertyFilter | BehavioralPropertyFilter)[] | null;response?: MCPModelBreakdownQueryResponse | null;tags?: QueryLogTags | null;@@ -76407,6 +76415,8 @@ export namespace Schemas {export interface QueryResponseAlternative97 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;+ /** Whether another page of individual model identifiers is available. */+ hasMore?: boolean | null;/** Generated HogQL query. */hogql?: string | null;/** Modifiers used when performing the query */diff --git a/services/mcp/src/hono/analytics.ts b/services/mcp/src/hono/analytics.tsindex 1130c50d9913..7a3b33165349 100644--- a/services/mcp/src/hono/analytics.ts+++ b/services/mcp/src/hono/analytics.ts@@ -119,6 +119,21 @@ export async function trackInitEvent(state: ResolvedState): Promise<void> {}}+type ModelMissingReason = 'missing' | 'unknown' | 'invalid' | 'not_captured' | 'capture_error'++export function getModelMissingReason(modelArgument: unknown): ModelMissingReason {+ if (modelArgument === undefined) {+ return 'missing'+ }+ if (typeof modelArgument !== 'string' || !modelArgument.trim()) {+ return 'invalid'+ }+ if (modelArgument.trim().toLowerCase() === 'unknown') {+ return 'unknown'+ }+ return 'not_captured'+}+export interface ToolCallAnalyticsMeta {/** The agent's stated intent (the injected `context` arg) → `$mcp_intent`. */intent?: string@@ -128,6 +143,7 @@ export interface ToolCallAnalyticsMeta {llmModel?: string/** Where the model identifier came from -> `$mcp_llm_model_source`. */llmModelSource?: MCPAnalyticsModelSource+ llmModelMissingReason?: ModelMissingReason}export async function trackToolCall(@@ -183,6 +199,9 @@ export async function trackToolCall(properties: {...properties,tool_name: toolName,+ ...(!analyticsMeta?.llmModel && analyticsMeta?.llmModelMissingReason+ ? { $mcp_llm_model_missing_reason: analyticsMeta.llmModelMissingReason }+ : {}),...(toolCategory ? { $mcp_tool_category: toolCategory } : {}),...(toolDescription ? { $mcp_tool_description: toolDescription } : {}),// Which vendor ran the tool, so "who do people actually call" is adiff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex 43df171e0b54..b8a915f525c1 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -39,6 +39,7 @@ import { formatSkillLookupMiss } from '@/tools/skills/notFound'import type { Context, Tool, ZodObjectAny } from '@/tools/types'import {+ getModelMissingReason,trackExecuteSqlGeneration,trackToolCall,trackToolSpan,@@ -251,11 +252,12 @@ export class ToolExecutor {intentSource: prepared.intentSource,llmModel: prepared.llmModel,llmModelSource: prepared.llmModelSource,+ llmModelMissingReason: prepared.llmModel ? undefined : getModelMissingReason(rawArgs.llm_model),},args: prepared.args ?? rawArgs,}} catch {- return { analyticsMeta: {}, args: rawArgs }+ return { analyticsMeta: { llmModelMissingReason: 'capture_error' }, args: rawArgs }}}diff --git a/services/mcp/tests/hono/analytics.test.ts b/services/mcp/tests/hono/analytics.test.tsindex d1b9881c4741..79236a1363e6 100644--- a/services/mcp/tests/hono/analytics.test.ts+++ b/services/mcp/tests/hono/analytics.test.ts@@ -151,6 +151,16 @@ describe('Hono MCP analytics contexts', () => {expect(properties.mcp_session_vendor_client).toBeUndefined()})+ it.each([+ { llmModel: undefined, llmModelMissingReason: 'unknown' as const, expected: 'unknown' },+ { llmModel: 'example-model', llmModelMissingReason: 'unknown' as const, expected: undefined },+ { llmModel: undefined, llmModelMissingReason: undefined, expected: undefined },+ ])('emits a missing model reason only for unresolved calls: $llmModel', async ({ expected, ...analyticsMeta }) => {+ await trackToolCall('user-get', 12, false, makeState(), undefined, analyticsMeta)++ expect(mockCaptureToolCall.mock.calls[0]![0].properties.$mcp_llm_model_missing_reason).toBe(expected)+ })+it('categorizes a proxied third-party tool and names its server', async () => {// A gateway tool has no catalog entry, so without the fallback it lands// uncategorized and disappears from every category-sliced view.diff --git a/services/mcp/tests/hono/tool-executor-intent.test.ts b/services/mcp/tests/hono/tool-executor-intent.test.tsindex 401f8f815915..da43bbe1a76e 100644--- a/services/mcp/tests/hono/tool-executor-intent.test.ts+++ b/services/mcp/tests/hono/tool-executor-intent.test.ts@@ -1,4 +1,12 @@-import { beforeAll, describe, expect, it, vi } from 'vitest'+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'++vi.mock('@/tools', async () => {+ const { default: executeSql } = await import('@/tools/posthogAiTools/executeSql')+ const { default: getProjects } = await import('@/tools/projects/getProjects')+ return { TOOL_MAP: { 'execute-sql': executeSql, 'projects-get': getProjects } }+})++vi.mock('@/tools/generated', () => ({ GENERATED_TOOL_MAP: {} }))vi.mock('@/resources/internals', () => ({fetchContextMillResources: vi.fn().mockRejectedValue(new Error('mocked')),@@ -83,6 +91,10 @@ describe('ToolExecutor analytics capture', () => {let catalog: ToolCataloglet executor: ToolExecutor+ afterEach(() => {+ vi.restoreAllMocks()+ })+beforeAll(async () => {catalog = new ToolCatalog()await catalog.warmup()@@ -117,6 +129,7 @@ describe('ToolExecutor analytics capture', () => {expectedSource: 'context_parameter',expectedModel: 'gpt-5.6-codex',expectedModelSource: 'self_reported',+ expectedMissingReason: undefined,},{label: 'prefers Codex request metadata over an unknown self-report',@@ -130,6 +143,7 @@ describe('ToolExecutor analytics capture', () => {expectedSource: 'context_parameter',expectedModel: 'gpt-5.6-sol',expectedModelSource: 'client_metadata',+ expectedMissingReason: undefined,},{label: 'captures no intent when the agent omits context',@@ -138,10 +152,34 @@ describe('ToolExecutor analytics capture', () => {expectedSource: undefined,expectedModel: undefined,expectedModelSource: undefined,+ expectedMissingReason: 'missing',},+ ...[+ { llm_model: ' UnKnOwN ', reason: 'unknown' },+ { llm_model: ' ', reason: 'invalid' },+ { llm_model: null, reason: 'invalid' },+ { llm_model: 42, reason: 'invalid' },+ ].map(({ llm_model, reason }) => ({+ label: `records ${reason} for model argument ${JSON.stringify(llm_model)}`,+ args: { command: 'tools', llm_model },+ requestMeta: undefined,+ expectedIntent: undefined,+ expectedSource: undefined,+ expectedModel: undefined,+ expectedModelSource: undefined,+ expectedMissingReason: reason,+ })),])('exec call $label',- async ({ args, requestMeta, expectedIntent, expectedSource, expectedModel, expectedModelSource }) => {+ async ({+ args,+ requestMeta,+ expectedIntent,+ expectedSource,+ expectedModel,+ expectedModelSource,+ expectedMissingReason,+ }) => {const captureSpy = vi.spyOn(getPostHogClient(), 'captureToolCall').mockImplementation(() => {})const filteredTools = catalog@@ -165,11 +203,36 @@ describe('ToolExecutor analytics capture', () => {expect(arg.intentSource).toBe(expectedSource)expect(arg.llmModel).toBe(expectedModel)expect(arg.llmModelSource).toBe(expectedModelSource)+ expect(arg.properties?.$mcp_llm_model_missing_reason).toBe(expectedMissingReason)captureSpy.mockRestore()})+ it.each(['not_captured', 'capture_error'] as const)(+ 'records %s when analytics preparation cannot capture a supplied model',+ async (reason) => {+ const client = getPostHogClient()+ vi.spyOn(client, 'prepareToolCall').mockImplementationOnce((_name, args) => {+ if (reason === 'capture_error') {+ throw new Error('Analytics preparation failed')+ }+ return { args, isMissingCapability: false, isFeedback: false }+ })+ const captureSpy = vi.spyOn(client, 'captureToolCall').mockImplementation(() => {})++ const result = (await executor.handleToolCall(+ { name: 'exec', arguments: { command: 'tools', llm_model: 'example-model' } },+ makeState([], { useSingleExec: true })+ )) as { isError?: boolean }++ expect(result.isError).toBeFalsy()+ expect(captureSpy).toHaveBeenCalledTimes(1)+ expect(captureSpy.mock.calls[0]![0].properties?.$mcp_llm_model_missing_reason).toBe(reason)+ expect(captureSpy.mock.calls[0]![0].llmModel).toBeUndefined()+ }+ )+// A native (non-exec) tool call with context: proves the native callTool path// strips context and forwards intent. The native path now also tracks schema// rejections, so "captureToolCall fired" alone no longer implies validation@@ -199,6 +262,7 @@ describe('ToolExecutor analytics capture', () => {expect(arg.intent).toBe('looking up the current user')expect(arg.llmModel).toBe('claude-sonnet-4-20250514')expect(arg.llmModelSource).toBe('self_reported')+ expect(arg.properties).not.toHaveProperty('$mcp_llm_model_missing_reason')expect(arg.properties?.$mcp_error_type).not.toBe('validation')captureSpy.mockRestore()@@ -256,6 +320,7 @@ describe('ToolExecutor analytics capture', () => {expect(result.content).toBeTruthy()expect(captureSpy).toHaveBeenCalledTimes(1)expect(captureSpy.mock.calls[0]![0].intent).toBeUndefined()+ expect(captureSpy.mock.calls[0]![0].properties?.$mcp_llm_model_missing_reason).toBe('missing')captureSpy.mockRestore()})