@mastra/client-js 1.56.0-alpha.4 → 1.56.0-alpha.6

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.
@@ -3,7 +3,7 @@ name: mastra-client-js
3
3
  description: Documentation for @mastra/client-js. Use when working with @mastra/client-js APIs, configuration, or implementation.
4
4
  metadata:
5
5
  package: "@mastra/client-js"
6
- version: "1.56.0-alpha.4"
6
+ version: "1.56.0-alpha.6"
7
7
  ---
8
8
 
9
9
  ## When to use
@@ -54,7 +54,7 @@ Read the individual reference documents for detailed explanations and code examp
54
54
  - [Reference: Versioning](references/reference-editor-versioning.md) - Editor versions stored agents and prompt blocks. Database-backed resources use draft and publish operations.
55
55
  - [Client SDK](references/reference-migrations-upgrade-to-v1-client.md) - Client SDK changes align with server-side API updates, including utility renames, updated pagination, and type naming conventions.
56
56
  - [Reference: Metric queries](references/reference-observability-metrics-queries.md) - Metric queries read raw and aggregated metric data from the observability storage domain. For exporter and storage setup, see the Metrics overview.
57
- - [Trace queries](references/reference-observability-tracing-trace-query.md) - Find completed traces by trace fields and related spans. Filter results, paginate, poll for updates, and discover query fields.
57
+ - [Reference: Advanced trace queries](references/reference-observability-tracing-advanced-queries.md) - Find, count, and measure completed traces with structured predicates. List matching traces, aggregate them into grouped measures, paginate, poll, and discover query fields.
58
58
 
59
59
 
60
60
  Read [assets/SOURCE_MAP.json](assets/SOURCE_MAP.json) for source code references.
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.56.0-alpha.4",
2
+ "version": "1.56.0-alpha.6",
3
3
  "package": "@mastra/client-js",
4
4
  "exports": {},
5
5
  "modules": {}
@@ -248,7 +248,7 @@ const result = await mastraClient.queryTraces({
248
248
  })
249
249
  ```
250
250
 
251
- See [Trace queries](https://mastra.ai/reference/observability/tracing/trace-query) for request fields, predicates, limits, response shapes, and errors.
251
+ See [Query traces](https://mastra.ai/reference/observability/tracing/advanced-queries) for request fields, predicates, limits, response shapes, and errors.
252
252
 
253
253
  ### Load a page and poll for traces
254
254
 
@@ -275,7 +275,7 @@ const changes = await mastraClient.queryTraces({
275
275
 
276
276
  Merge `changes.traces` by `traceId`, retain `changes.deltaCursor`, and continue while `changes.delta.hasMore` is `true`. Keep the same time range and predicate across polls. Only completed traces are returned; polling doesn't guarantee notifications for related-record updates, deletions, or traces that stop matching.
277
277
 
278
- See [Delta polling](https://mastra.ai/reference/observability/tracing/trace-query) for bootstrap behavior, cursor lifetime, retention, and a complete polling loop.
278
+ See [Delta polling](https://mastra.ai/reference/observability/tracing/advanced-queries) for bootstrap behavior, cursor lifetime, retention, and a complete polling loop.
279
279
 
280
280
  ### Aggregate traces
281
281
 
@@ -300,11 +300,9 @@ if (capabilities.traceAggregate) {
300
300
  }
301
301
  ```
302
302
 
303
- `groupBy` accepts the root span's `name` and `spanType` as well as entity and context fields. Every `groupBy` field can also be used in `where` to drill into a group, except `serviceName`, `executionSource`, and `experimentId`, which are groupable only.
303
+ Each row has `dimensions` keyed by `groupBy` field, `measures` keyed by measure name, a `bucket` timestamp when `interval` is set, and `cost` coverage when a cost measure is requested. `truncated` is `true` when more groups matched than `limit`. Check `capabilities.traceAggregate` before calling. The client retries server errors like `queryTraces()` but doesn't retry `422` validation errors.
304
304
 
305
- Each row has `dimensions` keyed by `groupBy` field, `measures` keyed by measure name, a `bucket` timestamp when `interval` is set, and `cost` coverage when a cost measure is requested. `truncated` is `true` when more groups matched than `limit`.
306
-
307
- Check `capabilities.traceAggregate` before calling. Unlike `traceQuery`, a missing value means the server doesn't support aggregation. The client retries server errors like `queryTraces()` but doesn't retry `422` validation errors.
305
+ See [Aggregate traces](https://mastra.ai/reference/observability/tracing/advanced-queries) for dimensions, measures, token and cost semantics, time buckets, limits, and errors.
308
306
 
309
307
  ### Discover trace-query fields and values
310
308
 
@@ -324,7 +322,7 @@ const fields = await mastraClient.getTraceQueryFields({
324
322
  })
325
323
  ```
326
324
 
327
- For the `trace` scope on a server that supports aggregation, the response also includes `aggregate`: the `dimensions` you can pass to `groupBy` and the `measures` you can request. Every observed metadata field is also a dimension, and `countDistinct.<field>` accepts any dimension or `traceId`.
325
+ For the `trace` scope on a server that supports aggregation, the response also includes `aggregate`: the `dimensions` you can pass to `groupBy` and the `measures` you can request. See [Discover fields and values](https://mastra.ai/reference/observability/tracing/advanced-queries).
328
326
 
329
327
  Use the exact local path from the response with the same scope. For example, `model` belongs inside a `spans.some` or `spans.none` predicate. A field picker can fetch the `trace` and `spans` scopes in parallel.
330
328
 
@@ -502,7 +500,7 @@ const ratingPercentiles = await mastraClient.getFeedbackPercentiles({
502
500
 
503
501
  ## Related
504
502
 
505
- - [Trace queries](https://mastra.ai/reference/observability/tracing/trace-query): Query completed traces with recursive predicates
503
+ - [Advanced trace queries](https://mastra.ai/reference/observability/tracing/advanced-queries): Query and aggregate completed traces with recursive predicates
506
504
  - [Feedback guide](https://mastra.ai/docs/observability/feedback): Learn how to create, list, and query feedback
507
505
  - [Feedback reference](https://mastra.ai/reference/observability/feedback): Review feedback schemas and HTTP routes
508
506
  - [Agents API](https://mastra.ai/reference/client-js/agents): Learn about agent interactions that generate traces
@@ -2,26 +2,51 @@
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
+ | `traceQueryContextIds` | `trace-query-context-ids` | `runId`, `sessionId`, `userId`, and `organizationId` predicates |
31
+ | `traceQueryRootSpanFields` | `trace-query-root-span-fields` | Trace-scope `name` and `spanType` predicates, dimensions, and `countDistinct` measures |
32
+ | `traceQueryDiscovery` | `trace-query-discovery` | [Field and value discovery](#discover-fields-and-values) |
33
+ | `traceQueryTenantScope` | `trace-query-tenant-scope` | [Trusted tenant scope](#trusted-tenant-scope) |
21
34
 
22
- const mastraClient = new MastraClient({ baseUrl: 'http://localhost:4111' })
35
+ 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
36
 
24
- const result = await mastraClient.queryTraces({
37
+ ## Select traces
38
+
39
+ Every request selects traces with two fields:
40
+
41
+ | Field | Required | Description |
42
+ | ----------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
43
+ | `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`. |
44
+ | `where` | No | Recursive trace predicate. Supports scalar conditions and `spans.some` or `spans.none` clauses. |
45
+
46
+ This selection matches traces from the first week of August that contain a tool call with an error:
47
+
48
+ ```typescript
49
+ const selection = {
25
50
  timeRange: {
26
51
  from: '2026-08-01T00:00:00.000Z',
27
52
  to: '2026-08-08T00:00:00.000Z',
@@ -37,123 +62,16 @@ const result = await mastraClient.queryTraces({
37
62
  },
38
63
  },
39
64
  },
40
- orderBy: [{ field: 'startedAt', direction: 'desc' }],
41
- page: { limit: 25 },
42
- })
65
+ }
43
66
  ```
44
67
 
68
+ The same selection returns the same traces from either API. Aggregation counts exactly the traces that a query would list.
69
+
45
70
  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
71
 
47
72
  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
73
 
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
74
+ ### Fields and operators
157
75
 
158
76
  | Predicate context | Fields | Operators |
159
77
  | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------- |
@@ -172,7 +90,7 @@ Compose predicates with `{ op: 'and', args: [...] }`, `{ op: 'or', args: [...] }
172
90
 
173
91
  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.
174
92
 
175
- ### Filter by root duration
93
+ #### Filter by root duration
176
94
 
177
95
  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:
178
96
 
@@ -188,7 +106,7 @@ This top-level predicate doesn't inspect child spans. In contrast, `spans.some`
188
106
 
189
107
  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`.
190
108
 
191
- ### Filter by time to first chunk
109
+ #### Filter by time to first chunk
192
110
 
193
111
  `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.
194
112
 
@@ -212,7 +130,7 @@ The value is `null` when the span didn't stream a chunk, for example a tool call
212
130
 
213
131
  Trace query results include the root span's `timeToFirstChunkMs`, and `querySpans()` results include each span's value. Sorting by this field isn't supported. 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.
214
132
 
215
- ### Filter by context identifiers
133
+ #### Filter by context identifiers
216
134
 
217
135
  `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`:
218
136
 
@@ -233,7 +151,7 @@ const sessionTracesWithRun = {
233
151
 
234
152
  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.
235
153
 
236
- ### Filter by span properties
154
+ #### Filter by span properties
237
155
 
238
156
  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:
239
157
 
@@ -313,7 +231,7 @@ const versionedRetrieval = {
313
231
  }
314
232
  ```
315
233
 
316
- ### Filter by metadata
234
+ #### Filter by metadata
317
235
 
318
236
  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.
319
237
 
@@ -340,7 +258,7 @@ The key must name one top-level property. Empty keys and nested paths are reject
340
258
 
341
259
  Trace-query discovery returns executable top-level string metadata fields observed in the selected time range.
342
260
 
343
- ### Filter by tags
261
+ #### Filter by tags
344
262
 
345
263
  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:
346
264
 
@@ -366,7 +284,7 @@ Tags compare exactly and case-sensitively as whole strings. `value` must be one
366
284
 
367
285
  `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.
368
286
 
369
- ### Filter by text
287
+ #### Filter by text
370
288
 
371
289
  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":
372
290
 
@@ -391,7 +309,148 @@ Both the literal and the stored value are lowercased and split into words. A wor
391
309
 
392
310
  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.
393
311
 
394
- ## Responses
312
+ ### Query limits
313
+
314
+ The planner rejects a query before storage execution when it exceeds any of these limits:
315
+
316
+ | Input | Maximum |
317
+ | ----------------------------------------- | ----------------- |
318
+ | Predicate nesting depth | 12 levels |
319
+ | Predicate nodes | 100 |
320
+ | Related `spans` clauses | 8 total |
321
+ | Values in one `in` or `notIn` set | 100 |
322
+ | Comparison literals and membership values | 1,000 total |
323
+ | String literal | 4,096 UTF-8 bytes |
324
+ | Raw predicate path | 128 UTF-8 bytes |
325
+ | `page.limit` | 1,000 |
326
+ | HTTP request body | 256 KiB |
327
+
328
+ 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.
329
+
330
+ 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.
331
+
332
+ ## Query traces
333
+
334
+ 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).
335
+
336
+ ### Query traces with the client SDK
337
+
338
+ This query finds traces containing a tool call with an error:
339
+
340
+ ```typescript
341
+ import { MastraClient } from '@mastra/client-js'
342
+
343
+ const mastraClient = new MastraClient({ baseUrl: 'http://localhost:4111' })
344
+
345
+ const result = await mastraClient.queryTraces({
346
+ timeRange: {
347
+ from: '2026-08-01T00:00:00.000Z',
348
+ to: '2026-08-08T00:00:00.000Z',
349
+ },
350
+ where: {
351
+ spans: {
352
+ some: {
353
+ op: 'and',
354
+ args: [
355
+ { op: 'eq', left: { path: 'spanType' }, right: { literal: 'tool_call' } },
356
+ { op: 'exists', path: 'error' },
357
+ ],
358
+ },
359
+ },
360
+ },
361
+ orderBy: [{ field: 'startedAt', direction: 'desc' }],
362
+ page: { limit: 25 },
363
+ })
364
+ ```
365
+
366
+ ### Query traces with the CLI
367
+
368
+ 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:
369
+
370
+ ```bash
371
+ mastra api --url http://localhost:4111 trace query '{
372
+ "timeRange": {
373
+ "from": "2026-08-01T00:00:00.000Z",
374
+ "to": "2026-08-08T00:00:00.000Z"
375
+ },
376
+ "where": {
377
+ "spans": {
378
+ "some": {
379
+ "op": "and",
380
+ "args": [
381
+ { "op": "eq", "left": { "path": "spanType" }, "right": { "literal": "tool_call" } },
382
+ { "op": "exists", "path": "error" }
383
+ ]
384
+ }
385
+ }
386
+ },
387
+ "orderBy": [{ "field": "startedAt", "direction": "desc" }],
388
+ "page": { "limit": 25 }
389
+ }'
390
+ ```
391
+
392
+ 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.
393
+
394
+ Inspect the command with:
395
+
396
+ ```bash
397
+ mastra api trace query --help
398
+ ```
399
+
400
+ For a local Mastra server, inspect its request and response schemas with:
401
+
402
+ ```bash
403
+ mastra api --url http://localhost:4111 trace query --schema
404
+ ```
405
+
406
+ 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).
407
+
408
+ ### Send an HTTP request
409
+
410
+ Send the same query as a JSON request body:
411
+
412
+ ```bash
413
+ curl --request POST \
414
+ --url http://localhost:4111/api/observability/traces/query \
415
+ --header 'Authorization: Bearer <token>' \
416
+ --header 'Content-Type: application/json' \
417
+ --data '{
418
+ "timeRange": {
419
+ "from": "2026-08-01T00:00:00.000Z",
420
+ "to": "2026-08-08T00:00:00.000Z"
421
+ },
422
+ "where": {
423
+ "spans": {
424
+ "some": {
425
+ "op": "and",
426
+ "args": [
427
+ { "op": "eq", "left": { "path": "spanType" }, "right": { "literal": "tool_call" } },
428
+ { "op": "exists", "path": "error" }
429
+ ]
430
+ }
431
+ }
432
+ },
433
+ "orderBy": [{ "field": "startedAt", "direction": "desc" }],
434
+ "page": { "limit": 25 }
435
+ }'
436
+ ```
437
+
438
+ ### Request fields
439
+
440
+ | Field | Required | Description |
441
+ | ------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
442
+ | `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`. |
443
+ | `where` | No | Recursive trace predicate. Supports scalar conditions and `spans.some` or `spans.none` clauses. |
444
+ | `orderBy` | No | One item ordering results by `startedAt` or `endedAt`, in `asc` or `desc` order. Defaults to `startedAt desc`. Not accepted in delta mode. |
445
+ | `page` | No | `{ limit, after }`. `limit` defaults to 100 and has a maximum of 1000. Pass the opaque `page.next` value as `after`. |
446
+ | `pagination` | No | Numbered pages: `{ page, perPage }`. Defaults to page 0 and 10 results. `perPage` has a maximum of 100. |
447
+ | `mode` | No | Set to `'delta'` to poll using a delta cursor instead of `page` or `pagination`. |
448
+ | `after` | No | Delta mode only. Opaque `deltaCursor` from a numbered page or previous poll. Omit to establish the current watermark. |
449
+ | `limit` | No | Delta mode only. Maximum results per batch. Defaults to 10 and has a maximum of 100. |
450
+
451
+ 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.
452
+
453
+ ### Responses
395
454
 
396
455
  A query using keyset pagination returns lightweight completed traces and a cursor for the next page:
397
456
 
@@ -420,7 +479,7 @@ A query using keyset pagination returns lightweight completed traces and a curso
420
479
 
421
480
  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.
422
481
 
423
- ### CLI responses
482
+ #### CLI responses
424
483
 
425
484
  The CLI wraps the API response in `data`:
426
485
 
@@ -439,9 +498,9 @@ Each CLI invocation makes one query. To fetch another keyset page, pass `data.pa
439
498
 
440
499
  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.
441
500
 
442
- ## Pagination and errors
501
+ ### Pagination and errors
443
502
 
444
- ### Choose a pagination mode
503
+ #### Choose a pagination mode
445
504
 
446
505
  Trace queries support three mutually exclusive modes:
447
506
 
@@ -453,7 +512,7 @@ Trace queries support three mutually exclusive modes:
453
512
 
454
513
  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.
455
514
 
456
- ### Poll after loading a numbered page
515
+ #### Poll after loading a numbered page
457
516
 
458
517
  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.
459
518
 
@@ -503,7 +562,7 @@ ClickHouse polling is best effort. Its delta index and trace records use separat
503
562
 
504
563
  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.
505
564
 
506
- ### Keyset ordering and errors
565
+ #### Keyset ordering and errors
507
566
 
508
567
  Ordering is deterministic. Trace ordering appends `traceId` ascending as a tie-breaker.
509
568
 
@@ -511,20 +570,6 @@ Keyset cursors are bound to the operation, accepted normalized query, and orderi
511
570
 
512
571
  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`.
513
572
 
514
- ### Trusted tenant scope
515
-
516
- 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.
517
-
518
- Hosts that call storage directly can pass a fuller scope to `planTraceQuery()`, `planTraceQueryObservedFields()`, and `planTraceQueryValues()`:
519
-
520
- ```typescript
521
- const plan = planTraceQuery(parseTraceQueryRequest(request), {
522
- scope: { organizationId: 'org_123', resourceId: 'project_456' },
523
- })
524
- ```
525
-
526
- `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.
527
-
528
573
  Cursor pagination is deterministic, but it isn't a database snapshot. Traces or replacement signals written between page requests can change later pages.
529
574
 
530
575
  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.
@@ -539,6 +584,230 @@ PostgreSQL and ClickHouse stop trace queries after 15 seconds by default and ret
539
584
  | `503` | Discovery exceeded a backend memory or resource budget and returned `TRACE_QUERY_RESOURCE_LIMIT`. |
540
585
  | `504` | A PostgreSQL or ClickHouse query exceeded its configured database execution timeout. Discovery returns `TRACE_QUERY_EXECUTION_TIMEOUT`. |
541
586
 
587
+ ## Aggregate traces
588
+
589
+ 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.
590
+
591
+ ### Aggregate traces with the client SDK
592
+
593
+ This request compares agents by volume, error rate, and latency over one week:
594
+
595
+ ```typescript
596
+ import { MastraClient } from '@mastra/client-js'
597
+
598
+ const mastraClient = new MastraClient({ baseUrl: 'http://localhost:4111' })
599
+
600
+ const { capabilities } = await mastraClient.getObservabilityCapabilities()
601
+
602
+ if (capabilities.traceAggregate) {
603
+ const { rows, truncated } = await mastraClient.aggregateTraces({
604
+ timeRange: {
605
+ from: '2026-08-01T00:00:00.000Z',
606
+ to: '2026-08-08T00:00:00.000Z',
607
+ },
608
+ where: { op: 'eq', left: { path: 'entityType' }, right: { literal: 'agent' } },
609
+ groupBy: ['entityName'],
610
+ measures: ['count', 'errorRate', 'duration.p95'],
611
+ orderBy: { field: 'errorRate', direction: 'desc' },
612
+ limit: 10,
613
+ })
614
+ }
615
+ ```
616
+
617
+ The client retries server errors like `queryTraces()`, but doesn't retry `422` validation errors.
618
+
619
+ ### Send an aggregate HTTP request
620
+
621
+ Send the same request as a JSON body:
622
+
623
+ ```bash
624
+ curl --request POST \
625
+ --url http://localhost:4111/api/observability/traces/aggregate \
626
+ --header 'Authorization: Bearer <token>' \
627
+ --header 'Content-Type: application/json' \
628
+ --data '{
629
+ "timeRange": {
630
+ "from": "2026-08-01T00:00:00.000Z",
631
+ "to": "2026-08-08T00:00:00.000Z"
632
+ },
633
+ "where": { "op": "eq", "left": { "path": "entityType" }, "right": { "literal": "agent" } },
634
+ "groupBy": ["entityName"],
635
+ "measures": ["count", "errorRate", "duration.p95"],
636
+ "orderBy": { "field": "errorRate", "direction": "desc" },
637
+ "limit": 10
638
+ }'
639
+ ```
640
+
641
+ ### Aggregate request fields
642
+
643
+ | Field | Required | Description |
644
+ | ----------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
645
+ | `timeRange` | Yes | Trace start-time boundary, as in [Select traces](#select-traces). The range can span up to 365 days. |
646
+ | `where` | No | Trace predicate, as in [Select traces](#select-traces). |
647
+ | `measures` | Yes | One or more distinct [measure names](#measures). |
648
+ | `groupBy` | No | Up to two distinct [dimensions](#dimensions). Defaults to `[]`, which returns one row for all selected traces. |
649
+ | `interval` | No | Bucket width: `'1m'`, `'5m'`, `'15m'`, `'1h'`, or `'1d'`. See [Time buckets](#time-buckets). |
650
+ | `having` | No | Scalar predicate over measures that removes groups after grouping. See [Filter and order groups](#filter-and-order-groups). |
651
+ | `orderBy` | No | `{ field, direction }`. `field` is a requested measure, `count`, or a `groupBy` dimension, and `direction` is `asc` or `desc`. Defaults to `count desc`. |
652
+ | `limit` | No | Maximum number of groups. Defaults to 100 and has a maximum of 1,000. |
653
+
654
+ Unknown fields are rejected. Aggregation isn't paginated. Narrow the selection, or rank by a different measure, when `truncated` is `true`.
655
+
656
+ ### Dimensions
657
+
658
+ Dimensions read the current root span of each selected trace:
659
+
660
+ | Dimension | Notes |
661
+ | ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
662
+ | `entityType`, `entityName`, `environment`, `status`, `serviceName`, `executionSource` | Root span attributes. |
663
+ | `threadId`, `resourceId`, `userId`, `sessionId`, `organizationId`, `experimentId` | Context identifiers recorded on the root span. |
664
+ | `name`, `spanType` | Root span name and type. Requires the `traceQueryRootSpanFields` capability. |
665
+ | `metadata.<key>` | One non-empty top-level metadata key. Values are trimmed. Missing, empty, and non-string values group as `null`. |
666
+
667
+ 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.
668
+
669
+ ### Measures
670
+
671
+ | Measure | Value |
672
+ | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
673
+ | `count` | Number of selected traces. |
674
+ | `countDistinct.<field>` | Number of distinct non-null values of a dimension or `traceId`, such as `countDistinct.userId`. |
675
+ | `duration.avg`, `duration.min`, `duration.max` | Root span duration in milliseconds. |
676
+ | `duration.p50`, `duration.p90`, `duration.p95`, `duration.p99` | Root span duration percentile in milliseconds. Percentiles can be approximate, depending on the store. |
677
+ | `errorCount` | Number of traces whose root span recorded an error. |
678
+ | `errorRate` | `errorCount` divided by `count`, from 0 to 1. |
679
+ | `tokens.input.sum`, `tokens.input.avg` | Input tokens. |
680
+ | `tokens.output.sum`, `tokens.output.avg` | Output tokens. |
681
+ | `tokens.total.sum`, `tokens.total.avg` | Input plus output tokens. |
682
+ | `tokens.reasoning.sum`, `tokens.reasoning.avg` | Reasoning output tokens. |
683
+ | `tokens.cached.sum`, `tokens.cached.avg` | Input tokens read from the provider's cache. |
684
+ | `cost.sum`, `cost.avg` | Estimated model cost. |
685
+
686
+ Numeric measures over metadata aren't supported.
687
+
688
+ #### Token and cost measures
689
+
690
+ 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.
691
+
692
+ 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.
693
+
694
+ 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.
695
+
696
+ When you request any `cost.*` measure, every row also includes a `cost` object:
697
+
698
+ | Field | Description |
699
+ | ---------- | ------------------------------------------------------------------------------------------------------------------------------ |
700
+ | `coverage` | Fraction of usage-bearing traces whose usage was fully priced, from 0 to 1. `null` when the group has no usage-bearing traces. |
701
+ | `unit` | Cost unit of the priced metrics, such as `USD`. `'mixed'` when they use more than one unit, and `null` when none are priced. |
702
+
703
+ `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.
704
+
705
+ ### Filter and order groups
706
+
707
+ 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`.
708
+
709
+ `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.
710
+
711
+ This request keeps workflows with a 95th-percentile duration above five seconds:
712
+
713
+ ```typescript
714
+ const slowWorkflows = await mastraClient.aggregateTraces({
715
+ timeRange: {
716
+ from: '2026-08-01T00:00:00.000Z',
717
+ to: '2026-08-08T00:00:00.000Z',
718
+ },
719
+ where: { op: 'eq', left: { path: 'entityType' }, right: { literal: 'workflow_run' } },
720
+ groupBy: ['entityName'],
721
+ measures: ['count', 'duration.p95', 'duration.p99'],
722
+ having: { op: 'gt', left: { path: 'duration.p95' }, right: { literal: 5000 } },
723
+ orderBy: { field: 'duration.p95', direction: 'desc' },
724
+ })
725
+ ```
726
+
727
+ Ordering is deterministic. Ties are broken by dimension values in ascending order. `null` measure and dimension values sort last in both directions.
728
+
729
+ ### Time buckets
730
+
731
+ 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.
732
+
733
+ 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.
734
+
735
+ This request returns daily token usage and cost for each agent:
736
+
737
+ ```typescript
738
+ const dailyCost = await mastraClient.aggregateTraces({
739
+ timeRange: {
740
+ from: '2026-08-01T00:00:00.000Z',
741
+ to: '2026-08-08T00:00:00.000Z',
742
+ },
743
+ where: { op: 'eq', left: { path: 'entityType' }, right: { literal: 'agent' } },
744
+ groupBy: ['entityName'],
745
+ interval: '1d',
746
+ measures: ['count', 'tokens.total.sum', 'cost.sum', 'cost.avg'],
747
+ orderBy: { field: 'cost.sum', direction: 'desc' },
748
+ limit: 5,
749
+ })
750
+ ```
751
+
752
+ ### Aggregate responses
753
+
754
+ ```json
755
+ {
756
+ "rows": [
757
+ {
758
+ "dimensions": { "entityName": "supportAgent" },
759
+ "bucket": "2026-08-01T00:00:00.000Z",
760
+ "measures": {
761
+ "count": 412,
762
+ "tokens.total.sum": 1830442,
763
+ "cost.sum": 4.21,
764
+ "cost.avg": 0.0103
765
+ },
766
+ "cost": { "coverage": 0.99, "unit": "USD" }
767
+ }
768
+ ],
769
+ "truncated": false
770
+ }
771
+ ```
772
+
773
+ `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.
774
+
775
+ ### Aggregate limits and errors
776
+
777
+ | Limit | Maximum |
778
+ | ------------------------- | ------------ |
779
+ | Time range | 365 days |
780
+ | `groupBy` dimensions | 2 |
781
+ | `limit` | 1,000 groups |
782
+ | Buckets in the time range | 1,000 |
783
+ | `limit` × buckets | 10,000 rows |
784
+
785
+ 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.
786
+
787
+ 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.
788
+
789
+ | Status | Meaning |
790
+ | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
791
+ | `400` | Malformed JSON. |
792
+ | `413` | The request body exceeds 256 KiB. |
793
+ | `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`. |
794
+ | `501` | The installed Core or configured observability store doesn't support aggregation or a requested field. Returns `TRACE_AGGREGATE_UNSUPPORTED`. |
795
+ | `504` | A PostgreSQL or ClickHouse aggregation exceeded its execution timeout. Returns `TRACE_QUERY_EXECUTION_TIMEOUT` without partial results. |
796
+
797
+ ## Trusted tenant scope
798
+
799
+ 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.
800
+
801
+ Hosts that call storage directly can pass a fuller scope to `planTraceQuery()`, `planTraceAggregate()`, `planTraceQueryObservedFields()`, and `planTraceQueryValues()`:
802
+
803
+ ```typescript
804
+ const plan = planTraceQuery(parseTraceQueryRequest(request), {
805
+ scope: { organizationId: 'org_123', resourceId: 'project_456' },
806
+ })
807
+ ```
808
+
809
+ `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.
810
+
542
811
  ## Discover fields and values
543
812
 
544
813
  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`.
@@ -590,6 +859,27 @@ Canonical fields come from the same registry used to validate trace queries. The
590
859
 
591
860
  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.
592
861
 
862
+ For the `trace` scope, when the server and store support aggregation, the fields response also includes an `aggregate` object that describes what `aggregateTraces()` accepts:
863
+
864
+ ```json
865
+ {
866
+ "aggregate": {
867
+ "dimensions": [{ "path": "entityName", "valueKind": "string" }],
868
+ "measures": [
869
+ {
870
+ "name": "duration.p95",
871
+ "kind": "duration",
872
+ "statistic": "p95",
873
+ "unit": "milliseconds",
874
+ "approximate": true
875
+ }
876
+ ]
877
+ }
878
+ }
879
+ ```
880
+
881
+ `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`.
882
+
593
883
  After a user selects one field with `valueSuggestions: true`, call `getTraceQueryValues()`:
594
884
 
595
885
  ```typescript
@@ -639,7 +929,7 @@ Both routes require `observability:read` and use the configured observability st
639
929
 
640
930
  ## Limitations
641
931
 
642
- 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.
932
+ 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.
643
933
 
644
934
  ## Related
645
935
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/client-js",
3
- "version": "1.56.0-alpha.4",
3
+ "version": "1.56.0-alpha.6",
4
4
  "description": "The official TypeScript library for the Mastra Client API",
5
5
  "author": "",
6
6
  "type": "module",
@@ -37,8 +37,8 @@
37
37
  "canonicalize": "^1.0.8",
38
38
  "jose": "^6.2.11",
39
39
  "json-schema": "^0.4.0",
40
- "@mastra/core": "1.79.0-alpha.4",
41
- "@mastra/schema-compat": "1.3.16-alpha.0"
40
+ "@mastra/schema-compat": "1.3.16-alpha.0",
41
+ "@mastra/core": "1.79.0-alpha.6"
42
42
  },
43
43
  "peerDependencies": {
44
44
  "zod": "^3.25.0 || ^4.0.0"
@@ -55,8 +55,8 @@
55
55
  "zod": "^4.6.7",
56
56
  "@internal/ai-sdk-v4": "0.0.91",
57
57
  "@internal/ai-sdk-v5": "0.0.91",
58
- "@internal/lint": "0.0.144",
59
- "@internal/types-builder": "0.0.119"
58
+ "@internal/types-builder": "0.0.119",
59
+ "@internal/lint": "0.0.144"
60
60
  },
61
61
  "engines": {
62
62
  "node": ">=22.13.0"