@mastra/mcp-docs-server 1.3.9-alpha.1 → 1.3.9-alpha.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/.docs/docs/agents/guardrails.md +3 -0
  2. package/.docs/docs/agents/human-in-the-loop.md +2 -1
  3. package/.docs/docs/agents/processors.md +3 -0
  4. package/.docs/docs/harness/agent-controller.md +1 -1
  5. package/.docs/docs/harness/background-tasks.md +11 -0
  6. package/.docs/docs/harness/durable-agents.md +24 -8
  7. package/.docs/docs/harness/signals.md +3 -1
  8. package/.docs/docs/mastra-platform/connect/channels.md +14 -2
  9. package/.docs/docs/mastra-platform/connect/overview.md +1 -1
  10. package/.docs/docs/mastra-platform/connect/providers.md +1 -0
  11. package/.docs/docs/mastra-platform/connect/tools.md +25 -3
  12. package/.docs/docs/mastra-platform/observability.md +1 -1
  13. package/.docs/docs/memory/observational-memory.md +4 -2
  14. package/.docs/docs/memory/semantic-recall.md +2 -0
  15. package/.docs/docs/studio/overview.md +8 -0
  16. package/.docs/docs/workflows/control-flow.md +3 -1
  17. package/.docs/docs/workflows/overview.md +2 -0
  18. package/.docs/docs/workflows/time-travel.md +1 -1
  19. package/.docs/integrations/databases/clickhouse.md +1 -1
  20. package/.docs/integrations/voice/google.md +6 -0
  21. package/.docs/models/embeddings.md +2 -1
  22. package/.docs/models/environment-variables.md +2 -0
  23. package/.docs/models/gateways/merge-gateway.md +3 -1
  24. package/.docs/models/gateways/netlify.md +8 -4
  25. package/.docs/models/gateways/openrouter.md +8 -4
  26. package/.docs/models/gateways/vercel.md +9 -4
  27. package/.docs/models/index.md +3 -1
  28. package/.docs/models/providers/302ai.md +2 -1
  29. package/.docs/models/providers/aimlapi.md +3 -3
  30. package/.docs/models/providers/alibaba-token-plan-cn.md +31 -30
  31. package/.docs/models/providers/baseten.md +27 -25
  32. package/.docs/models/providers/cloudflare-workers-ai.md +2 -1
  33. package/.docs/models/providers/commandcode.md +147 -0
  34. package/.docs/models/providers/coralbricks.md +5 -8
  35. package/.docs/models/providers/cortecs.md +5 -6
  36. package/.docs/models/providers/databricks.md +2 -1
  37. package/.docs/models/providers/deepinfra.md +2 -1
  38. package/.docs/models/providers/edenai.md +11 -3
  39. package/.docs/models/providers/empiriolabs.md +3 -1
  40. package/.docs/models/providers/engy.md +12 -11
  41. package/.docs/models/providers/fireworks-ai.md +2 -1
  42. package/.docs/models/providers/huggingface.md +2 -1
  43. package/.docs/models/providers/hyper.md +26 -25
  44. package/.docs/models/providers/kenari.md +1 -1
  45. package/.docs/models/providers/kilo.md +29 -24
  46. package/.docs/models/providers/llmgateway-providers.md +9 -12
  47. package/.docs/models/providers/llmgateway.md +3 -4
  48. package/.docs/models/providers/melious.md +16 -15
  49. package/.docs/models/providers/minimax-cn-coding-plan.md +2 -1
  50. package/.docs/models/providers/minimax-cn.md +3 -2
  51. package/.docs/models/providers/minimax-coding-plan.md +2 -1
  52. package/.docs/models/providers/minimax.md +3 -2
  53. package/.docs/models/providers/nano-gpt.md +61 -55
  54. package/.docs/models/providers/nearai.md +1 -1
  55. package/.docs/models/providers/nebius.md +2 -1
  56. package/.docs/models/providers/novita-ai.md +2 -1
  57. package/.docs/models/providers/nvidia.md +2 -1
  58. package/.docs/models/providers/ofox.md +26 -25
  59. package/.docs/models/providers/ollama-cloud.md +31 -29
  60. package/.docs/models/providers/openai.md +1 -1
  61. package/.docs/models/providers/opencode-go.md +7 -7
  62. package/.docs/models/providers/opencode.md +91 -91
  63. package/.docs/models/providers/pioneer.md +120 -119
  64. package/.docs/models/providers/prime.md +4 -1
  65. package/.docs/models/providers/reflection.md +77 -0
  66. package/.docs/models/providers/requesty.md +6 -2
  67. package/.docs/models/providers/scaleway.md +2 -1
  68. package/.docs/models/providers/standardcompute.md +47 -8
  69. package/.docs/models/providers/togetherai.md +4 -1
  70. package/.docs/models/providers/upstage.md +8 -7
  71. package/.docs/models/providers/wandb.md +4 -2
  72. package/.docs/models/providers/xai.md +0 -1
  73. package/.docs/models/providers/zenmux.md +2 -1
  74. package/.docs/models/providers.md +2 -0
  75. package/.docs/reference/agent-controller/session.md +3 -2
  76. package/.docs/reference/agents/channels.md +5 -1
  77. package/.docs/reference/agents/durable-agent.md +16 -7
  78. package/.docs/reference/agents/inngest-agent.md +4 -4
  79. package/.docs/reference/classifier/classifier.md +31 -7
  80. package/.docs/reference/cli/mastra.md +43 -6
  81. package/.docs/reference/client-js/agent-controller.md +2 -0
  82. package/.docs/reference/client-js/agents.md +20 -0
  83. package/.docs/reference/client-js/observability.md +165 -6
  84. package/.docs/reference/configuration.md +30 -0
  85. package/.docs/reference/connect/channels.md +2 -2
  86. package/.docs/reference/connect/providers.md +38 -3
  87. package/.docs/reference/connect/tools.md +21 -2
  88. package/.docs/reference/core/mastra-class.md +7 -1
  89. package/.docs/reference/datasets/list.md +9 -1
  90. package/.docs/reference/evals/create-classifier-scorer.md +1 -0
  91. package/.docs/reference/index.md +1 -1
  92. package/.docs/reference/memory/observational-memory.md +2 -2
  93. package/.docs/reference/memory/settled.md +13 -5
  94. package/.docs/reference/observability/metrics/automatic-metrics.md +3 -3
  95. package/.docs/reference/observability/metrics/queries.md +1 -0
  96. package/.docs/reference/observability/tracing/{trace-query.md → advanced-queries.md} +484 -158
  97. package/.docs/reference/observability/tracing/interfaces.md +6 -0
  98. package/.docs/reference/processors/classifier-processor.md +8 -6
  99. package/.docs/reference/processors/model-selection-processor.md +2 -2
  100. package/.docs/reference/processors/moderation-processor.md +5 -1
  101. package/.docs/reference/processors/system-prompt-scrubber.md +4 -0
  102. package/.docs/reference/rag/embeddings.md +18 -0
  103. package/.docs/reference/signals/create-notification-inbox-tool.md +11 -9
  104. package/.docs/reference/streaming/agents/stream.md +19 -1
  105. package/.docs/reference/tools/create-tool.md +2 -2
  106. package/.docs/reference/tools/mcp-client.md +2 -2
  107. package/.docs/reference/workflows/dynamic-workflow-definition.md +1 -1
  108. package/.docs/reference/workflows/run-methods/resume.md +1 -1
  109. package/.docs/reference/workflows/run-methods/timeTravel.md +15 -16
  110. package/.docs/reference/workflows/step.md +1 -0
  111. package/.docs/reference/workflows/workflow-methods/classifier.md +1 -0
  112. package/.docs/reference/workspace/factory-sandbox.md +2 -0
  113. package/.docs/reference/workspace/filesystem.md +4 -0
  114. package/.docs/reference/workspace/workspace-class.md +10 -10
  115. package/package.json +7 -8
@@ -2,26 +2,52 @@
2
2
 
3
3
  > Discover all available pages from the documentation index: https://mastra.ai/llms.txt
4
4
 
5
- # Trace queries
5
+ # Advanced trace queries
6
6
 
7
- Use `queryTraces()`, `mastra api trace query`, or `POST /api/observability/traces/query` to find completed traces by their fields and related spans. All three accept the same query structure. The filters, operators, sorting, and pagination options on this page apply to each interface.
7
+ Advanced trace queries select completed traces with a structured time range and predicate, then either list or aggregate the matching traces:
8
8
 
9
- For example, find traces with a failed tool call or a duration above a threshold. Each result represents a trace. Use its `traceId` to [retrieve the full trace](https://mastra.ai/reference/client-js/observability).
9
+ | API | Use it to | Client SDK | HTTP endpoint |
10
+ | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- | ------------------------------------------ |
11
+ | Query traces | List matching traces, paginate through them, and poll for new ones. | `queryTraces()` | `POST /api/observability/traces/query` |
12
+ | Aggregate traces | Count matching traces and compute measures, such as error rate, latency percentiles, tokens, and cost, optionally grouped by dimensions and time buckets. | `aggregateTraces()` | `POST /api/observability/traces/aggregate` |
10
13
 
11
- The endpoint uses the same authentication as other observability routes and requires the `observability:read` permission. The configured observability store must support trace queries. Every query requires a time range.
14
+ Both APIs accept the same [trace selection](#select-traces). The filters, operators, and limits on this page apply to each. Use the aggregate API to find the group that needs attention, such as an agent with a high error rate, then send the same predicate plus the group's dimensions to the query API to list the traces behind it. Each query result represents a trace. Use its `traceId` to [retrieve the full trace](https://mastra.ai/reference/client-js/observability).
15
+
16
+ The endpoints use the same authentication as other observability routes and require the `observability:read` permission. Every request requires a time range.
12
17
 
13
18
  For hosted traces, see [Query observability data on Mastra Platform](https://mastra.ai/docs/mastra-platform/observability) for project credentials and regional endpoints.
14
19
 
15
- ## Query traces with the client SDK
20
+ ## Check capabilities
16
21
 
17
- This query finds traces containing a tool call with an error:
22
+ The configured observability store must support each API. Call `getObservabilityCapabilities()` or `GET /api/observability/capabilities` and check these flags before showing a feature:
18
23
 
19
- ```typescript
20
- import { MastraClient } from '@mastra/client-js'
24
+ | Capability | Store feature | Enables |
25
+ | -------------------------------- | -------------------------------------- | -------------------------------------------------------------------------------------- |
26
+ | `traceQuery` | `trace-query` | `queryTraces()` |
27
+ | `traceAggregate` | `trace-aggregate` | `aggregateTraces()` |
28
+ | `traceQueryRootDuration` | `trace-query-root-duration` | Trace-scope `durationMs` predicates |
29
+ | `traceQueryTimeToFirstChunk` | `trace-query-time-to-first-chunk` | `timeToFirstChunkMs` predicates and results |
30
+ | `traceQueryTimeToFirstChunkSort` | `trace-query-time-to-first-chunk-sort` | `orderBy` on `timeToFirstChunkMs` |
31
+ | `traceQueryContextIds` | `trace-query-context-ids` | `runId`, `sessionId`, `userId`, and `organizationId` predicates |
32
+ | `traceQueryRootSpanFields` | `trace-query-root-span-fields` | Trace-scope `name` and `spanType` predicates, dimensions, and `countDistinct` measures |
33
+ | `traceQueryDiscovery` | `trace-query-discovery` | [Field and value discovery](#discover-fields-and-values) |
34
+ | `traceQueryTenantScope` | `trace-query-tenant-scope` | [Trusted tenant scope](#trusted-tenant-scope) |
21
35
 
22
- const mastraClient = new MastraClient({ baseUrl: 'http://localhost:4111' })
36
+ A missing `traceAggregate` value means the server doesn't support aggregation. Servers without the aggregate route return `404`, and stores without the feature return `501 TRACE_AGGREGATE_UNSUPPORTED`. Against a store without a sub-feature, a request that uses a gated field returns `501` before storage runs. Root span `name` and `spanType` are the exception and return `422` with a `field_not_allowed` issue.
23
37
 
24
- const result = await mastraClient.queryTraces({
38
+ ## Select traces
39
+
40
+ Every request selects traces with two fields:
41
+
42
+ | Field | Required | Description |
43
+ | ----------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
44
+ | `timeRange` | Yes | Trace start-time boundary. `from` is inclusive and `to` is exclusive. Both values must be ISO timestamps, and `from` must be earlier than `to`. |
45
+ | `where` | No | Recursive trace predicate. Supports scalar conditions and `spans.some` or `spans.none` clauses. |
46
+
47
+ This selection matches traces from the first week of August that contain a tool call with an error:
48
+
49
+ ```typescript
50
+ const selection = {
25
51
  timeRange: {
26
52
  from: '2026-08-01T00:00:00.000Z',
27
53
  to: '2026-08-08T00:00:00.000Z',
@@ -37,140 +63,35 @@ const result = await mastraClient.queryTraces({
37
63
  },
38
64
  },
39
65
  },
40
- orderBy: [{ field: 'startedAt', direction: 'desc' }],
41
- page: { limit: 25 },
42
- })
66
+ }
43
67
  ```
44
68
 
69
+ The same selection returns the same traces from either API. Aggregation counts exactly the traces that a query would list.
70
+
45
71
  A `spans.some` clause matches when one span satisfies all its conditions. In this example, the same span must be a tool call and have an error. Use `spans.none` to find traces with no spans matching the conditions.
46
72
 
47
73
  Span clauses examine the current root span and current child spans. The root `timeRange` applies only to the selected current root's `startedAt`. Related spans can participate even when their own timestamps are outside that range. Related records correlate only through a matching non-null `traceId`.
48
74
 
49
- ## Query traces with the CLI
50
-
51
- Pass the query as one JSON argument to `mastra api trace query`. Filters and pagination options belong in the JSON input. This command runs the same failed-tool query as the SDK example:
52
-
53
- ```bash
54
- mastra api --url http://localhost:4111 trace query '{
55
- "timeRange": {
56
- "from": "2026-08-01T00:00:00.000Z",
57
- "to": "2026-08-08T00:00:00.000Z"
58
- },
59
- "where": {
60
- "spans": {
61
- "some": {
62
- "op": "and",
63
- "args": [
64
- { "op": "eq", "left": { "path": "spanType" }, "right": { "literal": "tool_call" } },
65
- { "op": "exists", "path": "error" }
66
- ]
67
- }
68
- }
69
- },
70
- "orderBy": [{ "field": "startedAt", "direction": "desc" }],
71
- "page": { "limit": 25 }
72
- }'
73
- ```
74
-
75
- The explicit `--url` targets a local Mastra server. Without it, observability commands default to `https://observability.mastra.ai`, even when a local server is running. See [CLI target resolution](https://mastra.ai/reference/cli/mastra) for authentication and regional endpoints. The target server and configured store must support the requested query capabilities.
76
-
77
- Inspect the command with:
78
-
79
- ```bash
80
- mastra api trace query --help
81
- ```
82
-
83
- For a local Mastra server, inspect its request and response schemas with:
84
-
85
- ```bash
86
- mastra api --url http://localhost:4111 trace query --schema
87
- ```
88
-
89
- Mastra Platform doesn't currently expose the schema endpoint used by `--schema`. Use [Request fields](#request-fields) and [Fields and operators](#fields-and-operators) to construct queries for either target. To find fields and values recorded in your project, use [field and value discovery](#discover-fields-and-values).
90
-
91
- ## Send an HTTP request
92
-
93
- Send the same query as a JSON request body:
94
-
95
- ```bash
96
- curl --request POST \
97
- --url http://localhost:4111/api/observability/traces/query \
98
- --header 'Authorization: Bearer <token>' \
99
- --header 'Content-Type: application/json' \
100
- --data '{
101
- "timeRange": {
102
- "from": "2026-08-01T00:00:00.000Z",
103
- "to": "2026-08-08T00:00:00.000Z"
104
- },
105
- "where": {
106
- "spans": {
107
- "some": {
108
- "op": "and",
109
- "args": [
110
- { "op": "eq", "left": { "path": "spanType" }, "right": { "literal": "tool_call" } },
111
- { "op": "exists", "path": "error" }
112
- ]
113
- }
114
- }
115
- },
116
- "orderBy": [{ "field": "startedAt", "direction": "desc" }],
117
- "page": { "limit": 25 }
118
- }'
119
- ```
120
-
121
- ## Request fields
122
-
123
- | Field | Required | Description |
124
- | ------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
125
- | `timeRange` | Yes | Trace start-time boundary. `from` is inclusive and `to` is exclusive. Both values must be ISO timestamps, and `from` must be earlier than `to`. |
126
- | `where` | No | Recursive trace predicate. Supports scalar conditions and `spans.some` or `spans.none` clauses. |
127
- | `orderBy` | No | One item ordering results by `startedAt` or `endedAt`, in `asc` or `desc` order. Defaults to `startedAt desc`. Not accepted in delta mode. |
128
- | `page` | No | `{ limit, after }`. `limit` defaults to 100 and has a maximum of 1000. Pass the opaque `page.next` value as `after`. |
129
- | `pagination` | No | Numbered pages: `{ page, perPage }`. Defaults to page 0 and 10 results. `perPage` has a maximum of 100. |
130
- | `mode` | No | Set to `'delta'` to poll using a delta cursor instead of `page` or `pagination`. |
131
- | `after` | No | Delta mode only. Opaque `deltaCursor` from a numbered page or previous poll. Omit to establish the current watermark. |
132
- | `limit` | No | Delta mode only. Maximum results per batch. Defaults to 10 and has a maximum of 100. |
133
-
134
- Unknown fields are rejected. Requests can't select a projection, declare joins, request counts or measures, or control authorization. Request bodies are limited to 256 KiB.
135
-
136
- ## Query limits
137
-
138
- The planner rejects a query before storage execution when it exceeds any of these limits:
139
-
140
- | Input | Maximum |
141
- | ----------------------------------------- | ----------------- |
142
- | Predicate nesting depth | 12 levels |
143
- | Predicate nodes | 100 |
144
- | Related `spans` clauses | 8 total |
145
- | Values in one `in` or `notIn` set | 100 |
146
- | Comparison literals and membership values | 1,000 total |
147
- | String literal | 4,096 UTF-8 bytes |
148
- | Raw predicate path | 128 UTF-8 bytes |
149
- | `page.limit` | 1,000 |
150
- | HTTP request body | 256 KiB |
151
-
152
- Each comparison literal counts as one literal. Each member of an `in` or `notIn` set also counts as one literal, even when the set is within its per-set limit.
153
-
154
- Hono and Fastify enforce the request-body limit before JSON parsing. Express and Elysia reject an oversized body before the route handler or storage runs, but the host framework may already have parsed a request without a reliable `Content-Length` header. Configure the host application's JSON parser or body limit when you need a hard pre-parse memory ceiling.
155
-
156
- ## Fields and operators
75
+ ### Fields and operators
157
76
 
158
77
  | Predicate context | Fields | Operators |
159
78
  | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------- |
160
- | Trace | `traceId`, `threadId`, `resourceId`, `runId`, `sessionId`, `userId`, `organizationId`, `entityName`, `entityType`, `environment`, `status` | `eq`, `ne`, `in`, `notIn`, `exists`, `notExists` |
79
+ | Trace | `traceId`, `threadId`, `resourceId`, `runId`, `sessionId`, `userId`, `organizationId`, `entityName`, `entityType`, `name`, `spanType`, `environment`, `status` | `eq`, `ne`, `in`, `notIn`, `exists`, `notExists` |
161
80
  | Trace metadata | `metadata.<key>` | `eq`, `ne`, `in`, `notIn`, `exists`, `notExists` |
162
- | Trace | `startedAt`, `endedAt`, `durationMs` | `eq`, `ne`, `in`, `notIn`, `lt`, `lte`, `gt`, `gte`, `exists`, `notExists` |
81
+ | Trace | `startedAt`, `endedAt`, `durationMs`, `timeToFirstChunkMs` | `eq`, `ne`, `in`, `notIn`, `lt`, `lte`, `gt`, `gte`, `exists`, `notExists` |
163
82
  | Trace | `tags` | `includes`, `notIncludes`, `exists`, `notExists` |
164
83
  | Span | `name` | `eq`, `ne`, `in`, `notIn`, `exists`, `notExists`, `matches`, `notMatches` |
165
84
  | Span | `spanType`, `model`, `provider`, `status`, `entityType`, `entityId`, `entityName`, `entityVersionId`, `parentEntityVersionId`, `rootEntityVersionId`, `runId`, `sessionId`, `userId`, `organizationId` | `eq`, `ne`, `in`, `notIn`, `exists`, `notExists` |
166
- | Span | `startedAt`, `endedAt`, `durationMs` | `eq`, `ne`, `in`, `notIn`, `lt`, `lte`, `gt`, `gte`, `exists`, `notExists` |
85
+ | Span | `startedAt`, `endedAt`, `durationMs`, `timeToFirstChunkMs` | `eq`, `ne`, `in`, `notIn`, `lt`, `lte`, `gt`, `gte`, `exists`, `notExists` |
167
86
  | Span | `error` | `exists`, `notExists` |
168
87
 
88
+ Trace-scope `name` and `spanType` read the current root span, so `{ op: 'eq', left: { path: 'spanType' }, right: { literal: 'workflow_run' } }` selects traces started by a workflow run. Inside `spans.some` or `spans.none`, the same fields match any span in the trace.
89
+
169
90
  Compose predicates with `{ op: 'and', args: [...] }`, `{ op: 'or', args: [...] }`, and `{ op: 'not', arg: ... }`. Comparison predicates place a field reference on the left and a literal on the right. Membership predicates use a field reference in `value` and a homogeneous literal array in `set`. Tag predicates name the stored tag collection in `path`. `includes` and `notIncludes` also take one tag in `value`, while `exists` and `notExists` take only `op` and `path`. See [Filter by tags](#filter-by-tags). Text predicates use the comparison shape with a string literal. See [Filter by text](#filter-by-text).
170
91
 
171
- String comparisons are case-sensitive, and literals are never coerced. `matches` and `notMatches` are the exception: they compare words case-insensitively. Canonical string fields compare exact stored values. Metadata string values are trimmed before comparison, as described below. Duration predicates require numbers, while timestamp predicates require ISO timestamp strings. A missing value satisfies neither positive nor ordered predicates, although it does satisfy the negative operators `ne` and `notIn`. Combine a negative predicate with `exists` when the field must also be present.
92
+ String comparisons are case-sensitive, and literals are never coerced. `matches` and `notMatches` are the exception: they compare words case-insensitively. Canonical string fields compare exact stored values. Metadata string values are trimmed before comparison, as described below. Duration and time-to-first-chunk predicates require numbers, while timestamp predicates require ISO timestamp strings. A missing value satisfies neither positive nor ordered predicates, although it does satisfy the negative operators `ne` and `notIn`. Combine a negative predicate with `exists` when the field must also be present.
172
93
 
173
- ### Filter by root duration
94
+ #### Filter by root duration
174
95
 
175
96
  At trace scope, `durationMs` is the current completed root span's elapsed time in milliseconds. The value is derived from `endedAt - startedAt` when the query runs:
176
97
 
@@ -186,7 +107,37 @@ This top-level predicate doesn't inspect child spans. In contrast, `spans.some`
186
107
 
187
108
  Trace queries exclude incomplete roots before evaluating predicates. As a result, `{ op: 'notExists', path: 'durationMs' }` doesn't find running traces or malformed roots without a usable `endedAt`.
188
109
 
189
- ### Filter by context identifiers
110
+ #### Filter by time to first chunk
111
+
112
+ `timeToFirstChunkMs` is the time in milliseconds from a span's start to the first chunk of its model response. Agent run and model spans record it when the model streams a response. At trace scope, the field reads the current root span's value. Inside `spans.some` or `spans.none`, it reads each related span.
113
+
114
+ This predicate finds traces with a model call that took more than 2 seconds to stream its first chunk:
115
+
116
+ ```typescript
117
+ const slowFirstChunk = {
118
+ spans: {
119
+ some: {
120
+ op: 'and',
121
+ args: [
122
+ { op: 'eq', left: { path: 'spanType' }, right: { literal: 'model_generation' } },
123
+ { op: 'gt', left: { path: 'timeToFirstChunkMs' }, right: { literal: 2000 } },
124
+ ],
125
+ },
126
+ },
127
+ }
128
+ ```
129
+
130
+ The value is `null` when the span didn't stream a chunk, for example a tool call or a workflow run. A `null` value counts as missing, so it matches `notExists` and never matches ordered predicates. A value of `0` isn't missing. It means the first chunk arrived in the same millisecond the span started.
131
+
132
+ Trace query results include the root span's `timeToFirstChunkMs`, and `querySpans()` results include each span's value. Stores advertise support through the `trace-query-time-to-first-chunk` feature, and the server reports it as the `traceQueryTimeToFirstChunk` capability. Against an older store, results omit the field, a predicate on it returns `501` before storage runs, and field discovery omits it.
133
+
134
+ #### Sort by time to first chunk
135
+
136
+ Pass `orderBy: [{ field: 'timeToFirstChunkMs', direction: 'desc' }]` to list the slowest first chunks first. Traces sort by the root span's value. Missing values sort last in both directions, and `0` sorts as a value. Ties break by `traceId` for traces and by span identity for `querySpans()`.
137
+
138
+ Stores advertise the sort through the `trace-query-time-to-first-chunk-sort` feature, and the server reports it as the `traceQueryTimeToFirstChunkSort` capability. Against an older store, the sort returns `501` before storage runs.
139
+
140
+ #### Filter by context identifiers
190
141
 
191
142
  `runId`, `sessionId`, `userId`, and `organizationId` are available at trace scope and inside `spans.some` / `spans.none`. Trace-scope predicates read the current root span. Span-scope predicates bind to one related current span, so a run recorded only on a child span is found through `spans.some`:
192
143
 
@@ -207,7 +158,7 @@ const sessionTracesWithRun = {
207
158
 
208
159
  These identifiers support `eq`, `ne`, `in`, `notIn`, `exists`, and `notExists`. Field discovery lists them, but value discovery doesn't return their recorded values. Stores advertise support through the `trace-query-context-ids` feature. A predicate on one of these fields against an older store returns `501` before storage runs, and field discovery omits them for that store.
209
160
 
210
- ### Filter by span properties
161
+ #### Filter by span properties
211
162
 
212
163
  Every condition inside one `spans.some` or `spans.none` clause applies to the same current span. For example, this predicate finds a failed tool span whose name is `medication_lookup`; a matching name on one span and an error on another don't satisfy it:
213
164
 
@@ -287,7 +238,7 @@ const versionedRetrieval = {
287
238
  }
288
239
  ```
289
240
 
290
- ### Filter by metadata
241
+ #### Filter by metadata
291
242
 
292
243
  Use `metadata.<key>` paths for custom dimensions stored on the current root span. Metadata predicates compare trimmed, non-empty string values exactly and case-sensitively. Leading and trailing whitespace in a stored string value is ignored. Values empty after trimming count as missing. Null, numeric, boolean, object, and array values also count as missing.
293
244
 
@@ -314,7 +265,7 @@ The key must name one top-level property. Empty keys and nested paths are reject
314
265
 
315
266
  Trace-query discovery returns executable top-level string metadata fields observed in the selected time range.
316
267
 
317
- ### Filter by tags
268
+ #### Filter by tags
318
269
 
319
270
  Tags are a list of strings stored on the current root span, so they use collection operators instead of the scalar `in` and `notIn` operators. This query finds production traces tagged for manual review that don't carry the `archived` tag:
320
271
 
@@ -340,7 +291,7 @@ Tags compare exactly and case-sensitively as whole strings. `value` must be one
340
291
 
341
292
  `tags` is available in trace predicates only. `in`, `notIn`, and the comparison operators are rejected for `tags`. Value discovery for `tags` returns each observed tag with the number of qualifying traces that carry it.
342
293
 
343
- ### Filter by text
294
+ #### Filter by text
344
295
 
345
296
  Span names support word matching in addition to exact comparison. `matches` succeeds when the literal's words appear in the field, in order, as whole words. `notMatches` succeeds when the field exists but doesn't contain those words. This query finds traces with a span whose name contains the words "document search":
346
297
 
@@ -365,7 +316,148 @@ Both the literal and the stored value are lowercased and split into words. A wor
365
316
 
366
317
  The literal must contain at least one letter or digit; otherwise the request fails with `422 TRACE_QUERY_INVALID`. A missing field satisfies neither operator. Use `{ op: 'not', arg: { op: 'matches', ... } }` when records without the field should also match. Text operators are available on span `name`. Other string fields, numbers, timestamps, tags, and metadata reject them. Substring, wildcard, regular-expression, and fuzzy matching aren't supported, and there is no search across several fields.
367
318
 
368
- ## Responses
319
+ ### Query limits
320
+
321
+ The planner rejects a query before storage execution when it exceeds any of these limits:
322
+
323
+ | Input | Maximum |
324
+ | ----------------------------------------- | ----------------- |
325
+ | Predicate nesting depth | 12 levels |
326
+ | Predicate nodes | 100 |
327
+ | Related `spans` clauses | 8 total |
328
+ | Values in one `in` or `notIn` set | 100 |
329
+ | Comparison literals and membership values | 1,000 total |
330
+ | String literal | 4,096 UTF-8 bytes |
331
+ | Raw predicate path | 128 UTF-8 bytes |
332
+ | `page.limit` | 1,000 |
333
+ | HTTP request body | 256 KiB |
334
+
335
+ Each comparison literal counts as one literal. Each member of an `in` or `notIn` set also counts as one literal, even when the set is within its per-set limit.
336
+
337
+ Hono and Fastify enforce the request-body limit before JSON parsing. Express and Elysia reject an oversized body before the route handler or storage runs, but the host framework may already have parsed a request without a reliable `Content-Length` header. Configure the host application's JSON parser or body limit when you need a hard pre-parse memory ceiling.
338
+
339
+ ## Query traces
340
+
341
+ Use `queryTraces()`, `mastra api trace query`, or `POST /api/observability/traces/query` to list the selected traces. All three accept the same request, which adds ordering and pagination to the [trace selection](#select-traces).
342
+
343
+ ### Query traces with the client SDK
344
+
345
+ This query finds traces containing a tool call with an error:
346
+
347
+ ```typescript
348
+ import { MastraClient } from '@mastra/client-js'
349
+
350
+ const mastraClient = new MastraClient({ baseUrl: 'http://localhost:4111' })
351
+
352
+ const result = await mastraClient.queryTraces({
353
+ timeRange: {
354
+ from: '2026-08-01T00:00:00.000Z',
355
+ to: '2026-08-08T00:00:00.000Z',
356
+ },
357
+ where: {
358
+ spans: {
359
+ some: {
360
+ op: 'and',
361
+ args: [
362
+ { op: 'eq', left: { path: 'spanType' }, right: { literal: 'tool_call' } },
363
+ { op: 'exists', path: 'error' },
364
+ ],
365
+ },
366
+ },
367
+ },
368
+ orderBy: [{ field: 'startedAt', direction: 'desc' }],
369
+ page: { limit: 25 },
370
+ })
371
+ ```
372
+
373
+ ### Query traces with the CLI
374
+
375
+ Pass the query as one JSON argument to `mastra api trace query`. Filters and pagination options belong in the JSON input. This command runs the same failed-tool query as the SDK example:
376
+
377
+ ```bash
378
+ mastra api --url http://localhost:4111 trace query '{
379
+ "timeRange": {
380
+ "from": "2026-08-01T00:00:00.000Z",
381
+ "to": "2026-08-08T00:00:00.000Z"
382
+ },
383
+ "where": {
384
+ "spans": {
385
+ "some": {
386
+ "op": "and",
387
+ "args": [
388
+ { "op": "eq", "left": { "path": "spanType" }, "right": { "literal": "tool_call" } },
389
+ { "op": "exists", "path": "error" }
390
+ ]
391
+ }
392
+ }
393
+ },
394
+ "orderBy": [{ "field": "startedAt", "direction": "desc" }],
395
+ "page": { "limit": 25 }
396
+ }'
397
+ ```
398
+
399
+ The explicit `--url` targets a local Mastra server. Without it, observability commands default to `https://observability.mastra.ai`, even when a local server is running. See [CLI target resolution](https://mastra.ai/reference/cli/mastra) for authentication and regional endpoints. The target server and configured store must support the requested query capabilities.
400
+
401
+ Inspect the command with:
402
+
403
+ ```bash
404
+ mastra api trace query --help
405
+ ```
406
+
407
+ For a local Mastra server, inspect its request and response schemas with:
408
+
409
+ ```bash
410
+ mastra api --url http://localhost:4111 trace query --schema
411
+ ```
412
+
413
+ Mastra Platform doesn't currently expose the schema endpoint used by `--schema`. Use [Request fields](#request-fields) and [Fields and operators](#fields-and-operators) to construct queries for either target. To find fields and values recorded in your project, use [field and value discovery](#discover-fields-and-values).
414
+
415
+ ### Send an HTTP request
416
+
417
+ Send the same query as a JSON request body:
418
+
419
+ ```bash
420
+ curl --request POST \
421
+ --url http://localhost:4111/api/observability/traces/query \
422
+ --header 'Authorization: Bearer <token>' \
423
+ --header 'Content-Type: application/json' \
424
+ --data '{
425
+ "timeRange": {
426
+ "from": "2026-08-01T00:00:00.000Z",
427
+ "to": "2026-08-08T00:00:00.000Z"
428
+ },
429
+ "where": {
430
+ "spans": {
431
+ "some": {
432
+ "op": "and",
433
+ "args": [
434
+ { "op": "eq", "left": { "path": "spanType" }, "right": { "literal": "tool_call" } },
435
+ { "op": "exists", "path": "error" }
436
+ ]
437
+ }
438
+ }
439
+ },
440
+ "orderBy": [{ "field": "startedAt", "direction": "desc" }],
441
+ "page": { "limit": 25 }
442
+ }'
443
+ ```
444
+
445
+ ### Request fields
446
+
447
+ | Field | Required | Description |
448
+ | ------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
449
+ | `timeRange` | Yes | Trace start-time boundary. `from` is inclusive and `to` is exclusive. Both values must be ISO timestamps, and `from` must be earlier than `to`. |
450
+ | `where` | No | Recursive trace predicate. Supports scalar conditions and `spans.some` or `spans.none` clauses. |
451
+ | `orderBy` | No | One item ordering results by `startedAt`, `endedAt`, or `timeToFirstChunkMs`, in `asc` or `desc` order. Defaults to `startedAt desc`. Not accepted in delta mode. |
452
+ | `page` | No | `{ limit, after }`. `limit` defaults to 100 and has a maximum of 1000. Pass the opaque `page.next` value as `after`. |
453
+ | `pagination` | No | Numbered pages: `{ page, perPage }`. Defaults to page 0 and 10 results. `perPage` has a maximum of 100. |
454
+ | `mode` | No | Set to `'delta'` to poll using a delta cursor instead of `page` or `pagination`. |
455
+ | `after` | No | Delta mode only. Opaque `deltaCursor` from a numbered page or previous poll. Omit to establish the current watermark. |
456
+ | `limit` | No | Delta mode only. Maximum results per batch. Defaults to 10 and has a maximum of 100. |
457
+
458
+ Unknown fields are rejected. Requests can't select a projection, declare joins, request counts or measures, or control authorization. Use [`aggregateTraces()`](#aggregate-traces) for counts and measures. Request bodies are limited to 256 KiB.
459
+
460
+ ### Responses
369
461
 
370
462
  A query using keyset pagination returns lightweight completed traces and a cursor for the next page:
371
463
 
@@ -382,16 +474,19 @@ A query using keyset pagination returns lightweight completed traces and a curso
382
474
  "entityName": "support-agent",
383
475
  "entityType": "agent",
384
476
  "environment": "production",
385
- "status": "success"
477
+ "status": "success",
478
+ "timeToFirstChunkMs": 412
386
479
  }
387
480
  ],
388
481
  "page": { "next": null }
389
482
  }
390
483
  ```
391
484
 
485
+ `timeToFirstChunkMs` is present only when the configured store supports it. See [Filter by time to first chunk](#filter-by-time-to-first-chunk).
486
+
392
487
  The response doesn't include the related spans that matched the predicate. Use [`getTrace()`](https://mastra.ai/reference/client-js/observability) to load the full trace after selecting a result.
393
488
 
394
- ### CLI responses
489
+ #### CLI responses
395
490
 
396
491
  The CLI wraps the API response in `data`:
397
492
 
@@ -410,9 +505,9 @@ Each CLI invocation makes one query. To fetch another keyset page, pass `data.pa
410
505
 
411
506
  To inspect a selected trace, use `mastra api --url http://localhost:4111 trace get <traceId> --verbose`. Use the same target and authentication as the query.
412
507
 
413
- ## Pagination and errors
508
+ ### Pagination and errors
414
509
 
415
- ### Choose a pagination mode
510
+ #### Choose a pagination mode
416
511
 
417
512
  Trace queries support three mutually exclusive modes:
418
513
 
@@ -424,7 +519,7 @@ Trace queries support three mutually exclusive modes:
424
519
 
425
520
  Numbered pages are zero-based. Their total and rows are read consistently within each request. Don't combine `page`, `pagination`, or delta mode. Top-level `after` and `limit` are accepted only in delta mode.
426
521
 
427
- ### Poll after loading a numbered page
522
+ #### Poll after loading a numbered page
428
523
 
429
524
  Use the numbered response's `deltaCursor` to replace the numbered-page-to-delta-polling workflow of `listTracesLight()`. Results use `traces` instead of `spans` and contain completed traces only. The configured store must support delta polling.
430
525
 
@@ -474,7 +569,7 @@ ClickHouse polling is best effort. Its delta index and trace records use separat
474
569
 
475
570
  ClickHouse's delta index retains two days of events and doesn't backfill historical rows. Reload numbered pages after a polling interruption longer than this retention window. Delta polling isn't a durable change feed and doesn't guarantee delivery of every matching trace.
476
571
 
477
- ### Keyset ordering and errors
572
+ #### Keyset ordering and errors
478
573
 
479
574
  Ordering is deterministic. Trace ordering appends `traceId` ascending as a tie-breaker.
480
575
 
@@ -482,20 +577,6 @@ Keyset cursors are bound to the operation, accepted normalized query, and orderi
482
577
 
483
578
  Numbered-page handoff cursors and delta cursors also bind the authorization state. Changes to the caller's roles or permissions invalidate these cursors and return `409`. If a delta poll returns `409`, reload the numbered pages and resume polling with the new `deltaCursor`. A malformed cursor returns `400`.
484
579
 
485
- ### Trusted tenant scope
486
-
487
- Hosts that serve more than one tenant supply a trusted scope outside the query document. The server reads the reserved `organizationId` request-context key, which only server-side authentication can set, and passes `{ organizationId }` to the planner. The scope is carried on the trusted plan and ANDed into every scan: current roots, related spans and both discovery routes. A related record from another tenant that shares a `traceId` never qualifies a trace.
488
-
489
- Hosts that call storage directly can pass a fuller scope to `planTraceQuery()`, `planTraceQueryObservedFields()`, and `planTraceQueryValues()`:
490
-
491
- ```typescript
492
- const plan = planTraceQuery(parseTraceQueryRequest(request), {
493
- scope: { organizationId: 'org_123', resourceId: 'project_456' },
494
- })
495
- ```
496
-
497
- `resourceId` is optional and narrows within the organization. Keyset and delta cursors are bound to the scope. A cursor created under one scope and reused under another returns `409` before storage runs. A scoped request against an observability store or `@mastra/core` that predates tenant scope returns `501` instead of running unscoped. Stores advertise support through the `trace-query-tenant-scope` feature. Callers can't name `projectId` in predicates. An `organizationId` predicate compares recorded data and is ANDed with the scope, so it can only narrow the tenant's own traces and never widens it. Without a scope the routes behave as before, so self-hosted installations keep their own tenant model.
498
-
499
580
  Cursor pagination is deterministic, but it isn't a database snapshot. Traces or replacement signals written between page requests can change later pages.
500
581
 
501
582
  PostgreSQL and ClickHouse stop trace queries after 15 seconds by default and return `504` when the database timeout is exceeded. Set `traceQueryTimeoutMs` in the store's vNext observability configuration to an integer from 1 through 300,000 milliseconds to change the timeout. DuckDB doesn't currently provide query-scoped timeout or cancellation through its driver wrapper, so this `504` guarantee doesn't apply to DuckDB.
@@ -510,6 +591,230 @@ PostgreSQL and ClickHouse stop trace queries after 15 seconds by default and ret
510
591
  | `503` | Discovery exceeded a backend memory or resource budget and returned `TRACE_QUERY_RESOURCE_LIMIT`. |
511
592
  | `504` | A PostgreSQL or ClickHouse query exceeded its configured database execution timeout. Discovery returns `TRACE_QUERY_EXECUTION_TIMEOUT`. |
512
593
 
594
+ ## Aggregate traces
595
+
596
+ Use `aggregateTraces()` or `POST /api/observability/traces/aggregate` to count the selected traces and compute measures over them. Add `groupBy` to split the result by up to two dimensions, and `interval` to split each group into time buckets. The response contains one row per group, or one row per group and bucket.
597
+
598
+ ### Aggregate traces with the client SDK
599
+
600
+ This request compares agents by volume, error rate, and latency over one week:
601
+
602
+ ```typescript
603
+ import { MastraClient } from '@mastra/client-js'
604
+
605
+ const mastraClient = new MastraClient({ baseUrl: 'http://localhost:4111' })
606
+
607
+ const { capabilities } = await mastraClient.getObservabilityCapabilities()
608
+
609
+ if (capabilities.traceAggregate) {
610
+ const { rows, truncated } = await mastraClient.aggregateTraces({
611
+ timeRange: {
612
+ from: '2026-08-01T00:00:00.000Z',
613
+ to: '2026-08-08T00:00:00.000Z',
614
+ },
615
+ where: { op: 'eq', left: { path: 'entityType' }, right: { literal: 'agent' } },
616
+ groupBy: ['entityName'],
617
+ measures: ['count', 'errorRate', 'duration.p95'],
618
+ orderBy: { field: 'errorRate', direction: 'desc' },
619
+ limit: 10,
620
+ })
621
+ }
622
+ ```
623
+
624
+ The client retries server errors like `queryTraces()`, but doesn't retry `422` validation errors.
625
+
626
+ ### Send an aggregate HTTP request
627
+
628
+ Send the same request as a JSON body:
629
+
630
+ ```bash
631
+ curl --request POST \
632
+ --url http://localhost:4111/api/observability/traces/aggregate \
633
+ --header 'Authorization: Bearer <token>' \
634
+ --header 'Content-Type: application/json' \
635
+ --data '{
636
+ "timeRange": {
637
+ "from": "2026-08-01T00:00:00.000Z",
638
+ "to": "2026-08-08T00:00:00.000Z"
639
+ },
640
+ "where": { "op": "eq", "left": { "path": "entityType" }, "right": { "literal": "agent" } },
641
+ "groupBy": ["entityName"],
642
+ "measures": ["count", "errorRate", "duration.p95"],
643
+ "orderBy": { "field": "errorRate", "direction": "desc" },
644
+ "limit": 10
645
+ }'
646
+ ```
647
+
648
+ ### Aggregate request fields
649
+
650
+ | Field | Required | Description |
651
+ | ----------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
652
+ | `timeRange` | Yes | Trace start-time boundary, as in [Select traces](#select-traces). The range can span up to 365 days. |
653
+ | `where` | No | Trace predicate, as in [Select traces](#select-traces). |
654
+ | `measures` | Yes | One or more distinct [measure names](#measures). |
655
+ | `groupBy` | No | Up to two distinct [dimensions](#dimensions). Defaults to `[]`, which returns one row for all selected traces. |
656
+ | `interval` | No | Bucket width: `'1m'`, `'5m'`, `'15m'`, `'1h'`, or `'1d'`. See [Time buckets](#time-buckets). |
657
+ | `having` | No | Scalar predicate over measures that removes groups after grouping. See [Filter and order groups](#filter-and-order-groups). |
658
+ | `orderBy` | No | `{ field, direction }`. `field` is a requested measure, `count`, or a `groupBy` dimension, and `direction` is `asc` or `desc`. Defaults to `count desc`. |
659
+ | `limit` | No | Maximum number of groups. Defaults to 100 and has a maximum of 1,000. |
660
+
661
+ Unknown fields are rejected. Aggregation isn't paginated. Narrow the selection, or rank by a different measure, when `truncated` is `true`.
662
+
663
+ ### Dimensions
664
+
665
+ Dimensions read the current root span of each selected trace:
666
+
667
+ | Dimension | Notes |
668
+ | ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
669
+ | `entityType`, `entityName`, `environment`, `status`, `serviceName`, `executionSource` | Root span attributes. |
670
+ | `threadId`, `resourceId`, `userId`, `sessionId`, `organizationId`, `experimentId` | Context identifiers recorded on the root span. |
671
+ | `name`, `spanType` | Root span name and type. Requires the `traceQueryRootSpanFields` capability. |
672
+ | `metadata.<key>` | One non-empty top-level metadata key. Values are trimmed. Missing, empty, and non-string values group as `null`. |
673
+
674
+ Every dimension except `serviceName`, `executionSource`, and `experimentId` is also a trace-scope `where` field, so you can drill into a group by adding its values to the predicate. `traceId`, `spanId`, `runId`, and `requestId` aren't groupable. Traces with no value for a dimension form their own group with a `null` value.
675
+
676
+ ### Measures
677
+
678
+ | Measure | Value |
679
+ | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
680
+ | `count` | Number of selected traces. |
681
+ | `countDistinct.<field>` | Number of distinct non-null values of a dimension or `traceId`, such as `countDistinct.userId`. |
682
+ | `duration.avg`, `duration.min`, `duration.max` | Root span duration in milliseconds. |
683
+ | `duration.p50`, `duration.p90`, `duration.p95`, `duration.p99` | Root span duration percentile in milliseconds. Percentiles can be approximate, depending on the store. |
684
+ | `errorCount` | Number of traces whose root span recorded an error. |
685
+ | `errorRate` | `errorCount` divided by `count`, from 0 to 1. |
686
+ | `tokens.input.sum`, `tokens.input.avg` | Input tokens. |
687
+ | `tokens.output.sum`, `tokens.output.avg` | Output tokens. |
688
+ | `tokens.total.sum`, `tokens.total.avg` | Input plus output tokens. |
689
+ | `tokens.reasoning.sum`, `tokens.reasoning.avg` | Reasoning output tokens. |
690
+ | `tokens.cached.sum`, `tokens.cached.avg` | Input tokens read from the provider's cache. |
691
+ | `cost.sum`, `cost.avg` | Estimated model cost. |
692
+
693
+ Numeric measures over metadata aren't supported.
694
+
695
+ #### Token and cost measures
696
+
697
+ Token and cost measures read the model usage metrics recorded for each trace, so they're only available when the store retains metrics for the selected time range. A metric belongs to a trace when it shares the trace's `traceId` and was recorded at or after `timeRange.from`. Every such metric counts, including usage recorded after `timeRange.to` and usage recorded before a suspend and resume. Retried metric exports are counted once.
698
+
699
+ A trace that recorded at least one usage metric is usage-bearing. `tokens.<kind>.sum` adds the tokens of a group's usage-bearing traces, and `tokens.<kind>.avg` divides that sum by the number of usage-bearing traces, not by `count`. Both are `null` when the group has no usage-bearing traces.
700
+
701
+ Cost comes from estimated cost recorded on total input and total output token metrics. `cost.sum` adds the cost of traces with at least one priced metric, and `cost.avg` divides by the number of those traces. A metric whose pricing failed, including a partial cost, isn't priced.
702
+
703
+ When you request any `cost.*` measure, every row also includes a `cost` object:
704
+
705
+ | Field | Description |
706
+ | ---------- | ------------------------------------------------------------------------------------------------------------------------------ |
707
+ | `coverage` | Fraction of usage-bearing traces whose usage was fully priced, from 0 to 1. `null` when the group has no usage-bearing traces. |
708
+ | `unit` | Cost unit of the priced metrics, such as `USD`. `'mixed'` when they use more than one unit, and `null` when none are priced. |
709
+
710
+ `cost.sum` and `cost.avg` are `null` when the group has no priced traces or `unit` is `'mixed'`. A coverage below 1 means the cost understates the group's spend. The `cost` object isn't a measure, so `having` and `orderBy` can't reference it.
711
+
712
+ ### Filter and order groups
713
+
714
+ A group is one distinct combination of `groupBy` values. `having`, `orderBy`, and `limit` operate on groups and use each group's measures over the whole time range, even when `interval` is set. The server applies `having` first, then orders the remaining groups and keeps the first `limit`. `truncated` is `true` when more groups remained than `limit`.
715
+
716
+ `having` uses the scalar predicate shape with a measure name as the path, such as `{ op: 'gt', left: { path: 'duration.p95' }, right: { literal: 5000 } }`. It can reference requested measures and `count`, even when `count` isn't requested. It supports comparison operators, `in`, and `notIn` with number literals, combined with `and`, `or`, and `not`. Presence, tag, and text operators aren't supported. A `null` measure never satisfies a `having` comparison, so the group is removed.
717
+
718
+ This request keeps workflows with a 95th-percentile duration above five seconds:
719
+
720
+ ```typescript
721
+ const slowWorkflows = await mastraClient.aggregateTraces({
722
+ timeRange: {
723
+ from: '2026-08-01T00:00:00.000Z',
724
+ to: '2026-08-08T00:00:00.000Z',
725
+ },
726
+ where: { op: 'eq', left: { path: 'entityType' }, right: { literal: 'workflow_run' } },
727
+ groupBy: ['entityName'],
728
+ measures: ['count', 'duration.p95', 'duration.p99'],
729
+ having: { op: 'gt', left: { path: 'duration.p95' }, right: { literal: 5000 } },
730
+ orderBy: { field: 'duration.p95', direction: 'desc' },
731
+ })
732
+ ```
733
+
734
+ Ordering is deterministic. Ties are broken by dimension values in ascending order. `null` measure and dimension values sort last in both directions.
735
+
736
+ ### Time buckets
737
+
738
+ With `interval`, each group that survives `having` and `limit` expands into one row per non-empty bucket. Buckets are aligned to UTC, so `1d` buckets start at midnight UTC, and each row's `bucket` is the ISO start time of its bucket. A trace belongs to the bucket containing its root `startedAt`. Rows are ordered by group, then by `bucket` ascending.
739
+
740
+ Buckets without traces are omitted rather than returned as zero rows. Fill gaps on the client when you draw a chart. Because groups are ranked over the whole time range first, every returned group includes its full series of non-empty buckets.
741
+
742
+ This request returns daily token usage and cost for each agent:
743
+
744
+ ```typescript
745
+ const dailyCost = await mastraClient.aggregateTraces({
746
+ timeRange: {
747
+ from: '2026-08-01T00:00:00.000Z',
748
+ to: '2026-08-08T00:00:00.000Z',
749
+ },
750
+ where: { op: 'eq', left: { path: 'entityType' }, right: { literal: 'agent' } },
751
+ groupBy: ['entityName'],
752
+ interval: '1d',
753
+ measures: ['count', 'tokens.total.sum', 'cost.sum', 'cost.avg'],
754
+ orderBy: { field: 'cost.sum', direction: 'desc' },
755
+ limit: 5,
756
+ })
757
+ ```
758
+
759
+ ### Aggregate responses
760
+
761
+ ```json
762
+ {
763
+ "rows": [
764
+ {
765
+ "dimensions": { "entityName": "supportAgent" },
766
+ "bucket": "2026-08-01T00:00:00.000Z",
767
+ "measures": {
768
+ "count": 412,
769
+ "tokens.total.sum": 1830442,
770
+ "cost.sum": 4.21,
771
+ "cost.avg": 0.0103
772
+ },
773
+ "cost": { "coverage": 0.99, "unit": "USD" }
774
+ }
775
+ ],
776
+ "truncated": false
777
+ }
778
+ ```
779
+
780
+ `dimensions` is keyed by `groupBy` field and is present when `groupBy` isn't empty. `bucket` is present when `interval` is set. `measures` is keyed by the requested measure names. When no traces match, or `having` removes every group, `rows` is empty.
781
+
782
+ ### Aggregate limits and errors
783
+
784
+ | Limit | Maximum |
785
+ | ------------------------- | ------------ |
786
+ | Time range | 365 days |
787
+ | `groupBy` dimensions | 2 |
788
+ | `limit` | 1,000 groups |
789
+ | Buckets in the time range | 1,000 |
790
+ | `limit` × buckets | 10,000 rows |
791
+
792
+ Predicate limits from [Query limits](#query-limits) apply to both `where` and `having`, and the request body is limited to 256 KiB. A time range that doesn't start on a bucket boundary touches one more bucket than its length divided by the interval. If the range has too many buckets, choose a wider `interval`. If `limit` × buckets exceeds 10,000, reduce `limit` or widen the interval.
793
+
794
+ PostgreSQL and ClickHouse stop aggregations after the same `traceQueryTimeoutMs` timeout as trace queries, which defaults to 15 seconds. The timeout doesn't apply to DuckDB.
795
+
796
+ | Status | Meaning |
797
+ | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
798
+ | `400` | Malformed JSON. |
799
+ | `413` | The request body exceeds 256 KiB. |
800
+ | `422` | The request is invalid and returns `TRACE_QUERY_INVALID` with issues. Issue codes include `time_range_too_large`, `too_many_buckets`, `too_many_rows`, `field_not_allowed`, `invalid_metadata_key`, and `operator_not_allowed`. |
801
+ | `501` | The installed Core or configured observability store doesn't support aggregation or a requested field. Returns `TRACE_AGGREGATE_UNSUPPORTED`. |
802
+ | `504` | A PostgreSQL or ClickHouse aggregation exceeded its execution timeout. Returns `TRACE_QUERY_EXECUTION_TIMEOUT` without partial results. |
803
+
804
+ ## Trusted tenant scope
805
+
806
+ Hosts that serve more than one tenant supply a trusted scope outside the query document. The server reads the reserved `organizationId` request-context key, which only server-side authentication can set, and passes `{ organizationId }` to the planner. The scope is carried on the trusted plan and ANDed into every scan: current roots, related spans, the usage metrics read by token and cost measures, and both discovery routes. A related record from another tenant that shares a `traceId` never qualifies a trace.
807
+
808
+ Hosts that call storage directly can pass a fuller scope to `planTraceQuery()`, `planTraceAggregate()`, `planTraceQueryObservedFields()`, and `planTraceQueryValues()`:
809
+
810
+ ```typescript
811
+ const plan = planTraceQuery(parseTraceQueryRequest(request), {
812
+ scope: { organizationId: 'org_123', resourceId: 'project_456' },
813
+ })
814
+ ```
815
+
816
+ `resourceId` is optional and narrows within the organization. Keyset and delta cursors are bound to the scope. A cursor created under one scope and reused under another returns `409` before storage runs. A scoped request against an observability store or `@mastra/core` that predates tenant scope returns `501` instead of running unscoped. Stores advertise support through the `trace-query-tenant-scope` feature. Callers can't name `projectId` in predicates. An `organizationId` predicate compares recorded data and is ANDed with the scope, so it can only narrow the tenant's own traces and never widens it. Without a scope the routes behave as before, so self-hosted installations keep their own tenant model.
817
+
513
818
  ## Discover fields and values
514
819
 
515
820
  Use trace-query discovery to build field and value autocomplete without scanning trace payloads or copying the query grammar into your client. The configured observability store must support `trace-query-discovery`.
@@ -561,6 +866,27 @@ Canonical fields come from the same registry used to validate trace queries. The
561
866
 
562
867
  A field picker can request the `trace` and `spans` scopes in parallel and label each field with its scope. Every returned path is directly accepted by `queryTraces()` in its matching scope. `metadata` by itself isn't a field. A user interface can offer manual metadata-key entry separately.
563
868
 
869
+ For the `trace` scope, when the server and store support aggregation, the fields response also includes an `aggregate` object that describes what `aggregateTraces()` accepts:
870
+
871
+ ```json
872
+ {
873
+ "aggregate": {
874
+ "dimensions": [{ "path": "entityName", "valueKind": "string" }],
875
+ "measures": [
876
+ {
877
+ "name": "duration.p95",
878
+ "kind": "duration",
879
+ "statistic": "p95",
880
+ "unit": "milliseconds",
881
+ "approximate": true
882
+ }
883
+ ]
884
+ }
885
+ }
886
+ ```
887
+
888
+ `dimensions` lists the canonical dimensions that the store supports. Every observed `metadata.<key>` field is also a dimension, and `countDistinct.<field>` accepts any dimension or `traceId`. `measures` lists each fixed measure with its `kind`, `unit`, and whether it's `approximate`.
889
+
564
890
  After a user selects one field with `valueSuggestions: true`, call `getTraceQueryValues()`:
565
891
 
566
892
  ```typescript
@@ -591,12 +917,12 @@ Discovery returns string values only. Missing values, empty strings, and strings
591
917
 
592
918
  Value suggestions are available for these canonical fields:
593
919
 
594
- | Scope | Fields |
595
- | ----- | ----------------------------------------------------------------------------- |
596
- | Trace | `entityName`, `entityType`, `environment`, `status`, `tags` |
597
- | Spans | `name`, `spanType`, `model`, `provider`, `status`, `entityType`, `entityName` |
920
+ | Scope | Fields |
921
+ | ----- | ------------------------------------------------------------------------------- |
922
+ | Trace | `entityName`, `entityType`, `name`, `spanType`, `environment`, `status`, `tags` |
923
+ | Spans | `name`, `spanType`, `model`, `provider`, `status`, `entityType`, `entityName` |
598
924
 
599
- Each executable top-level string `metadata.<key>` field also supports value suggestions in the `trace` scope. Identifiers, timestamps, durations, errors, and version IDs don't. The fields response still includes canonical fields with `valueSuggestions: false`. The values endpoint rejects those paths with `422 TRACE_QUERY_INVALID`.
925
+ Each executable top-level string `metadata.<key>` field also supports value suggestions in the `trace` scope. Identifiers, timestamps, durations, time to first chunk, errors, and version IDs don't. The fields response still includes canonical fields with `valueSuggestions: false`. The values endpoint rejects those paths with `422 TRACE_QUERY_INVALID`.
600
926
 
601
927
  Both discovery requests require a half-open time range. They use the same current-record semantics as `queryTraces()`: qualifying completed roots satisfy `from <= startedAt < to`, and related values come only from current records joined to those roots by `traceId`. Discovery doesn't accept or apply a draft `where` predicate.
602
928
 
@@ -610,7 +936,7 @@ Both routes require `observability:read` and use the configured observability st
610
936
 
611
937
  ## Limitations
612
938
 
613
- Trace queries consider completed traces only. They don't support running traces, custom projections, embedded evidence, summaries, aggregations, measures, or custom grouping. Numbered trace pages include a total count.
939
+ Both APIs consider completed traces only and don't include running traces. Trace queries can't return custom projections, embedded evidence, or summaries, and numbered trace pages include a total count. Aggregation can't group by span fields, `traceId`, or `attributes.*`, compute numeric measures over metadata, paginate groups, or zero-fill empty buckets. The CLI doesn't expose a trace aggregation command, so use the SDK or the HTTP endpoint.
614
940
 
615
941
  ## Related
616
942