@mastra/mcp-docs-server 0.13.24 → 0.13.25-alpha.0

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 (105) hide show
  1. package/.docs/organized/changelogs/%40internal%2Fstorage-test-utils.md +8 -8
  2. package/.docs/organized/changelogs/%40internal%2Ftypes-builder.md +2 -0
  3. package/.docs/organized/changelogs/%40mastra%2Fagent-builder.md +12 -0
  4. package/.docs/organized/changelogs/%40mastra%2Fai-sdk.md +11 -0
  5. package/.docs/organized/changelogs/%40mastra%2Fastra.md +10 -10
  6. package/.docs/organized/changelogs/%40mastra%2Fchroma.md +10 -10
  7. package/.docs/organized/changelogs/%40mastra%2Fclickhouse.md +10 -10
  8. package/.docs/organized/changelogs/%40mastra%2Fclient-js.md +29 -29
  9. package/.docs/organized/changelogs/%40mastra%2Fcloud.md +10 -10
  10. package/.docs/organized/changelogs/%40mastra%2Fcloudflare-d1.md +10 -10
  11. package/.docs/organized/changelogs/%40mastra%2Fcloudflare.md +11 -11
  12. package/.docs/organized/changelogs/%40mastra%2Fcore.md +70 -70
  13. package/.docs/organized/changelogs/%40mastra%2Fcouchbase.md +10 -10
  14. package/.docs/organized/changelogs/%40mastra%2Fdeployer-cloud.md +25 -25
  15. package/.docs/organized/changelogs/%40mastra%2Fdeployer-cloudflare.md +23 -23
  16. package/.docs/organized/changelogs/%40mastra%2Fdeployer-netlify.md +24 -24
  17. package/.docs/organized/changelogs/%40mastra%2Fdeployer-vercel.md +24 -24
  18. package/.docs/organized/changelogs/%40mastra%2Fdeployer.md +30 -30
  19. package/.docs/organized/changelogs/%40mastra%2Fdynamodb.md +10 -10
  20. package/.docs/organized/changelogs/%40mastra%2Fevals.md +15 -15
  21. package/.docs/organized/changelogs/%40mastra%2Flance.md +11 -11
  22. package/.docs/organized/changelogs/%40mastra%2Flibsql.md +10 -10
  23. package/.docs/organized/changelogs/%40mastra%2Floggers.md +10 -10
  24. package/.docs/organized/changelogs/%40mastra%2Fmcp-docs-server.md +17 -17
  25. package/.docs/organized/changelogs/%40mastra%2Fmcp-registry-registry.md +10 -10
  26. package/.docs/organized/changelogs/%40mastra%2Fmcp.md +10 -10
  27. package/.docs/organized/changelogs/%40mastra%2Fmemory.md +18 -18
  28. package/.docs/organized/changelogs/%40mastra%2Fmongodb.md +10 -10
  29. package/.docs/organized/changelogs/%40mastra%2Fmssql.md +10 -10
  30. package/.docs/organized/changelogs/%40mastra%2Fopensearch.md +11 -11
  31. package/.docs/organized/changelogs/%40mastra%2Fpg.md +16 -16
  32. package/.docs/organized/changelogs/%40mastra%2Fpinecone.md +10 -10
  33. package/.docs/organized/changelogs/%40mastra%2Fplayground-ui.md +50 -50
  34. package/.docs/organized/changelogs/%40mastra%2Fqdrant.md +11 -11
  35. package/.docs/organized/changelogs/%40mastra%2Frag.md +13 -13
  36. package/.docs/organized/changelogs/%40mastra%2Freact-hooks.md +8 -0
  37. package/.docs/organized/changelogs/%40mastra%2Fs3vectors.md +9 -0
  38. package/.docs/organized/changelogs/%40mastra%2Fschema-compat.md +6 -0
  39. package/.docs/organized/changelogs/%40mastra%2Fserver.md +36 -36
  40. package/.docs/organized/changelogs/%40mastra%2Fturbopuffer.md +10 -10
  41. package/.docs/organized/changelogs/%40mastra%2Fupstash.md +13 -13
  42. package/.docs/organized/changelogs/%40mastra%2Fvectorize.md +10 -10
  43. package/.docs/organized/changelogs/%40mastra%2Fvoice-azure.md +10 -10
  44. package/.docs/organized/changelogs/%40mastra%2Fvoice-cloudflare.md +10 -10
  45. package/.docs/organized/changelogs/%40mastra%2Fvoice-deepgram.md +10 -10
  46. package/.docs/organized/changelogs/%40mastra%2Fvoice-elevenlabs.md +10 -10
  47. package/.docs/organized/changelogs/%40mastra%2Fvoice-gladia.md +9 -0
  48. package/.docs/organized/changelogs/%40mastra%2Fvoice-google-gemini-live.md +9 -0
  49. package/.docs/organized/changelogs/%40mastra%2Fvoice-google.md +11 -11
  50. package/.docs/organized/changelogs/%40mastra%2Fvoice-murf.md +11 -11
  51. package/.docs/organized/changelogs/%40mastra%2Fvoice-openai-realtime.md +11 -11
  52. package/.docs/organized/changelogs/%40mastra%2Fvoice-openai.md +11 -11
  53. package/.docs/organized/changelogs/%40mastra%2Fvoice-playai.md +10 -10
  54. package/.docs/organized/changelogs/%40mastra%2Fvoice-sarvam.md +10 -10
  55. package/.docs/organized/changelogs/%40mastra%2Fvoice-speechify.md +10 -10
  56. package/.docs/organized/changelogs/create-mastra.md +22 -22
  57. package/.docs/organized/changelogs/mastra.md +46 -46
  58. package/.docs/raw/index.mdx +1 -0
  59. package/.docs/raw/observability/ai-tracing/exporters/braintrust.mdx +81 -0
  60. package/.docs/raw/observability/ai-tracing/exporters/cloud.mdx +120 -0
  61. package/.docs/raw/observability/ai-tracing/exporters/default.mdx +167 -0
  62. package/.docs/raw/observability/ai-tracing/exporters/langfuse.mdx +121 -0
  63. package/.docs/raw/observability/ai-tracing/overview.mdx +565 -0
  64. package/.docs/raw/observability/ai-tracing/processors/sensitive-data-filter.mdx +274 -0
  65. package/.docs/raw/observability/{tracing.mdx → otel-tracing.mdx} +2 -2
  66. package/.docs/raw/observability/overview.mdx +66 -0
  67. package/.docs/raw/reference/agents/generate.mdx +39 -1
  68. package/.docs/raw/reference/agents/generateVNext.mdx +34 -2
  69. package/.docs/raw/reference/agents/network.mdx +34 -2
  70. package/.docs/raw/reference/observability/ai-tracing/ai-tracing.mdx +181 -0
  71. package/.docs/raw/reference/observability/ai-tracing/configuration.mdx +233 -0
  72. package/.docs/raw/reference/observability/ai-tracing/exporters/braintrust.mdx +112 -0
  73. package/.docs/raw/reference/observability/ai-tracing/exporters/cloud-exporter.mdx +176 -0
  74. package/.docs/raw/reference/observability/ai-tracing/exporters/console-exporter.mdx +148 -0
  75. package/.docs/raw/reference/observability/ai-tracing/exporters/default-exporter.mdx +196 -0
  76. package/.docs/raw/reference/observability/ai-tracing/exporters/langfuse.mdx +116 -0
  77. package/.docs/raw/reference/observability/ai-tracing/interfaces.mdx +651 -0
  78. package/.docs/raw/reference/observability/ai-tracing/processors/sensitive-data-filter.mdx +178 -0
  79. package/.docs/raw/reference/observability/ai-tracing/span.mdx +371 -0
  80. package/.docs/raw/reference/observability/otel-tracing/providers/index.mdx +22 -0
  81. package/.docs/raw/reference/streaming/agents/stream.mdx +39 -1
  82. package/.docs/raw/reference/streaming/agents/streamVNext.mdx +34 -2
  83. package/.docs/raw/reference/streaming/workflows/stream.mdx +38 -0
  84. package/.docs/raw/reference/streaming/workflows/streamVNext.mdx +38 -0
  85. package/.docs/raw/reference/tools/create-tool.mdx +34 -1
  86. package/.docs/raw/reference/workflows/run-methods/resume.mdx +38 -0
  87. package/.docs/raw/reference/workflows/run-methods/start.mdx +38 -0
  88. package/CHANGELOG.md +7 -0
  89. package/package.json +3 -3
  90. package/.docs/raw/observability/ai-tracing.mdx +0 -597
  91. package/.docs/raw/reference/observability/providers/index.mdx +0 -20
  92. /package/.docs/raw/reference/observability/{logger.mdx → logging/pino-logger.mdx} +0 -0
  93. /package/.docs/raw/reference/observability/{otel-config.mdx → otel-tracing/otel-config.mdx} +0 -0
  94. /package/.docs/raw/reference/observability/{providers → otel-tracing/providers}/arize-ax.mdx +0 -0
  95. /package/.docs/raw/reference/observability/{providers → otel-tracing/providers}/arize-phoenix.mdx +0 -0
  96. /package/.docs/raw/reference/observability/{providers → otel-tracing/providers}/braintrust.mdx +0 -0
  97. /package/.docs/raw/reference/observability/{providers → otel-tracing/providers}/dash0.mdx +0 -0
  98. /package/.docs/raw/reference/observability/{providers → otel-tracing/providers}/keywordsai.mdx +0 -0
  99. /package/.docs/raw/reference/observability/{providers → otel-tracing/providers}/laminar.mdx +0 -0
  100. /package/.docs/raw/reference/observability/{providers → otel-tracing/providers}/langfuse.mdx +0 -0
  101. /package/.docs/raw/reference/observability/{providers → otel-tracing/providers}/langsmith.mdx +0 -0
  102. /package/.docs/raw/reference/observability/{providers → otel-tracing/providers}/langwatch.mdx +0 -0
  103. /package/.docs/raw/reference/observability/{providers → otel-tracing/providers}/new-relic.mdx +0 -0
  104. /package/.docs/raw/reference/observability/{providers → otel-tracing/providers}/signoz.mdx +0 -0
  105. /package/.docs/raw/reference/observability/{providers → otel-tracing/providers}/traceloop.mdx +0 -0
@@ -0,0 +1,565 @@
1
+ ---
2
+ title: "AI Tracing | Observability | Mastra Docs"
3
+ description: "Set up AI tracing for Mastra applications"
4
+ ---
5
+
6
+ import { Callout } from "nextra/components";
7
+
8
+ # AI Tracing
9
+
10
+ AI Tracing provides specialized monitoring and debugging for the AI-related operations in your application. When enabled, Mastra automatically creates traces for agent runs, LLM generations, tool calls, and workflow steps with AI-specific context and metadata.
11
+
12
+ Unlike traditional application tracing, AI Tracing focuses specifically on understanding your AI pipeline — capturing token usage, model parameters, tool execution details, and conversation flows. This makes it easier to debug issues, optimize performance, and understand how your AI systems behave in production.
13
+
14
+ ## How It Works
15
+
16
+ AI Traces are created by:
17
+
18
+ - **Configure exporters** → send trace data to observability platforms
19
+ - **Set sampling strategies** → control which traces are collected
20
+ - **Run agents and workflows** → Mastra auto-instruments them with AI Tracing
21
+
22
+ ## Configuration
23
+
24
+ ### Basic Config
25
+
26
+ ```ts filename="src/mastra/index.ts" showLineNumbers copy
27
+ export const mastra = new Mastra({
28
+ // ... other config
29
+ observability: {
30
+ default: { enabled: true }, // Enables DefaultExporter and CloudExporter
31
+ },
32
+ storage: new LibSQLStore({
33
+ url: "file:./mastra.db", // Storage is required for tracing
34
+ }),
35
+ });
36
+ ```
37
+
38
+ When enabled, the default configuration automatically includes:
39
+ - **Service Name**: `"mastra"`
40
+ - **Sampling**: `"always"`- Sample (100% of traces)
41
+ - **Exporters**:
42
+ - `DefaultExporter` - Persists traces to your configured storage
43
+ - `CloudExporter` - Sends traces to Mastra Cloud (requires `MASTRA_CLOUD_ACCESS_TOKEN`)
44
+ - **Processors**: `SensitiveDataFilter` - Automatically redacts sensitive fields
45
+
46
+ ### Expanded Basic Config
47
+
48
+ This default configuration is a minimal helper that equates to this more verbose configuration:
49
+
50
+ ```ts filename="src/mastra/index.ts" showLineNumbers copy
51
+ import { CloudExporter, DefaultExporter, SensitiveDataFilter } from '@mastra/core/ai-tracing';
52
+
53
+ export const mastra = new Mastra({
54
+ // ... other config
55
+ observability: {
56
+ configs: {
57
+ default: {
58
+ serviceName: "mastra",
59
+ sampling: { type: 'always' },
60
+ processors: [
61
+ new SensitiveDataFilter(),
62
+ ],
63
+ exporters: [
64
+ new CloudExporter(),
65
+ new DefaultExporter(),
66
+ ],
67
+ }
68
+ }
69
+ },
70
+ storage: new LibSQLStore({
71
+ url: "file:./mastra.db", // Storage is required for tracing
72
+ }),
73
+ });
74
+ ```
75
+
76
+
77
+ ## Exporters
78
+
79
+ Exporters determine where your AI trace data is sent and how it's stored. Choosing the right exporters allows you to integrate with your existing observability stack, comply with data residency requirements, and optimize for cost and performance. You can use multiple exporters simultaneously to send the same trace data to different destinations — for example, storing detailed traces locally for debugging while sending sampled data to a cloud provider for production monitoring.
80
+
81
+ ### Internal Exporters
82
+
83
+ Mastra provides two built-in exporters that work out of the box:
84
+
85
+ - **[Default](/docs/observability/ai-tracing/exporters/default)** - Persists traces to local storage for viewing in the Playground
86
+ - **[Cloud](/docs/observability/ai-tracing/exporters/cloud)** - Sends traces to Mastra Cloud for production monitoring and collaboration
87
+
88
+ ### External Exporters
89
+
90
+ In addition to the internal exporters, Mastra supports integration with popular observability platforms. These exporters allow you to leverage your existing monitoring infrastructure and take advantage of platform-specific features like alerting, dashboards, and correlation with other application metrics.
91
+
92
+ - **[Langfuse](/docs/observability/ai-tracing/exporters/langfuse)** - Sends traces to the Langfuse open-source LLM engineering platform
93
+ - **[Braintrust](/docs/observability/ai-tracing/exporters/braintrust)** - Exports traces to Braintrust's eval and observability platform
94
+
95
+ - **Arize** - Coming soon!
96
+ - **LangSmith** - Coming soon!
97
+ - **OpenTelemetry** - Coming soon!
98
+
99
+ ## Sampling Strategies
100
+
101
+ Sampling allows you to control which traces are collected, helping you balance between observability needs and resource costs. In production environments with high traffic, collecting every trace can be expensive and unnecessary. Sampling strategies let you capture a representative subset of traces while ensuring you don't miss critical information about errors or important operations.
102
+
103
+ Mastra supports four sampling strategies:
104
+
105
+ ### Always Sample
106
+ Collects 100% of traces. Best for development, debugging, or low-traffic scenarios where you need complete visibility.
107
+
108
+ ```ts
109
+ sampling: { type: 'always' }
110
+ ```
111
+
112
+ ### Never Sample
113
+ Disables tracing entirely. Useful for specific environments where tracing adds no value or when you need to temporarily disable tracing without removing configuration.
114
+
115
+ ```ts
116
+ sampling: { type: 'never' }
117
+ ```
118
+
119
+ ### Ratio-Based Sampling
120
+ Randomly samples a percentage of traces. Ideal for production environments where you want statistical insights without the cost of full tracing. The probability value ranges from 0 (no traces) to 1 (all traces).
121
+
122
+ ```ts
123
+ sampling: {
124
+ type: 'ratio',
125
+ probability: 0.1 // Sample 10% of traces
126
+ }
127
+ ```
128
+
129
+ ### Custom Sampling
130
+ Implements your own sampling logic based on runtime context, metadata, or business rules. Perfect for complex scenarios like sampling based on user tier, request type, or error conditions.
131
+
132
+ ```ts
133
+ sampling: {
134
+ type: 'custom',
135
+ sampler: (options) => {
136
+ // Sample premium users at higher rate
137
+ if (options?.metadata?.userTier === 'premium') {
138
+ return Math.random() < 0.5; // 50% sampling
139
+ }
140
+
141
+ // Default 1% sampling for others
142
+ return Math.random() < 0.01;
143
+ }
144
+ }
145
+ ```
146
+
147
+ ### Complete Example
148
+
149
+ ```ts filename="src/mastra/index.ts" showLineNumbers copy
150
+ export const mastra = new Mastra({
151
+ observability: {
152
+ configs: {
153
+ "10_percent": {
154
+ serviceName: 'my-service',
155
+ // Sample 10% of traces
156
+ sampling: {
157
+ type: 'ratio',
158
+ probability: 0.1
159
+ },
160
+ exporters: [new DefaultExporter()],
161
+ }
162
+ },
163
+ },
164
+ });
165
+ ```
166
+
167
+ ## Multi-Config Setup
168
+
169
+ Complex applications often require different tracing configurations for different scenarios. You might want detailed traces with full sampling during development, sampled traces sent to external providers in production, and specialized configurations for specific features or customer segments. The `configSelector` function enables dynamic configuration selection at runtime, allowing you to route traces based on request context, environment variables, feature flags, or any custom logic.
170
+
171
+ This approach is particularly valuable when:
172
+ - Running A/B tests with different observability requirements
173
+ - Providing enhanced debugging for specific customers or support cases
174
+ - Gradually rolling out new tracing providers without affecting existing monitoring
175
+ - Optimizing costs by using different sampling rates for different request types
176
+ - Maintaining separate trace streams for compliance or data residency requirements
177
+
178
+ <Callout type="info">
179
+ Note that only a single config can be used for a specific execution. But a single config can send data to multiple exporters simultaneously.
180
+ </Callout>
181
+
182
+ ### Dynamic Configuration Selection
183
+
184
+ Use `configSelector` to choose the appropriate tracing configuration based on runtime context:
185
+
186
+ ```ts filename="src/mastra/index.ts" showLineNumbers copy
187
+ export const mastra = new Mastra({
188
+ observability: {
189
+ default: { enabled: true }, // Provides 'default' instance
190
+ configs: {
191
+ langfuse: {
192
+ serviceName: 'langfuse-service',
193
+ exporters: [langfuseExporter],
194
+ },
195
+ braintrust: {
196
+ serviceName: 'braintrust-service',
197
+ exporters: [braintrustExporter],
198
+ },
199
+ debug: {
200
+ serviceName: 'debug-service',
201
+ sampling: { type: 'always' },
202
+ exporters: [new DefaultExporter()],
203
+ },
204
+ },
205
+ configSelector: (context, availableTracers) => {
206
+ // Use debug config for support requests
207
+ if (context.runtimeContext?.get('supportMode')) {
208
+ return 'debug';
209
+ }
210
+
211
+ // Route specific customers to different providers
212
+ const customerId = context.runtimeContext?.get('customerId');
213
+ if (customerId && premiumCustomers.includes(customerId)) {
214
+ return 'braintrust';
215
+ }
216
+
217
+ // Route specific requests to langfuse
218
+ if (context.runtimeContext?.get('useExternalTracing')) {
219
+ return 'langfuse';
220
+ }
221
+
222
+ return 'default';
223
+ },
224
+ },
225
+ });
226
+ ```
227
+
228
+ ### Environment-Based Configuration
229
+
230
+ A common pattern is to select configurations based on deployment environment:
231
+
232
+ ```ts filename="src/mastra/index.ts" showLineNumbers copy
233
+ export const mastra = new Mastra({
234
+ observability: {
235
+ configs: {
236
+ development: {
237
+ serviceName: 'my-service-dev',
238
+ sampling: { type: 'always' },
239
+ exporters: [new DefaultExporter()],
240
+ },
241
+ staging: {
242
+ serviceName: 'my-service-staging',
243
+ sampling: { type: 'ratio', probability: 0.5 },
244
+ exporters: [langfuseExporter],
245
+ },
246
+ production: {
247
+ serviceName: 'my-service-prod',
248
+ sampling: { type: 'ratio', probability: 0.01 },
249
+ exporters: [cloudExporter, langfuseExporter],
250
+ },
251
+ },
252
+ configSelector: (context, availableTracers) => {
253
+ const env = process.env.NODE_ENV || 'development';
254
+ return env;
255
+ },
256
+ },
257
+ });
258
+ ```
259
+
260
+ ### Common Configuration Patterns & Troubleshooting
261
+
262
+ #### Default Config Takes Priority
263
+
264
+ When you have both the default config enabled and custom configs defined, **the default config will always be used** unless you explicitly select a different config:
265
+
266
+ ```ts filename="src/mastra/index.ts" showLineNumbers copy
267
+ export const mastra = new Mastra({
268
+ observability: {
269
+ default: { enabled: true }, // This will always be used!
270
+ configs: {
271
+ langfuse: {
272
+ serviceName: 'my-service',
273
+ exporters: [langfuseExporter], // This won't be reached
274
+ },
275
+ },
276
+ },
277
+ });
278
+ ```
279
+
280
+ **Solutions:**
281
+
282
+ 1. **Disable the default** and use only custom configs:
283
+ ```ts
284
+ observability: {
285
+ // comment out or remove this line to disable the default config
286
+ // default: { enabled: true },
287
+ configs: {
288
+ langfuse: { /* ... */ }
289
+ }
290
+ }
291
+ ```
292
+
293
+ 2. **Use a configSelector** to choose between configs:
294
+ ```ts
295
+ observability: {
296
+ default: { enabled: true },
297
+ configs: {
298
+ langfuse: { /* ... */ }
299
+ },
300
+ configSelector: (context, availableConfigs) => {
301
+ // Logic to choose between 'default' and 'langfuse'
302
+ return useExternalTracing ? 'langfuse' : 'default';
303
+ }
304
+ }
305
+ ```
306
+
307
+ #### Maintaining Playground and Cloud Access
308
+
309
+ When creating a custom config with external exporters, you might lose access to Mastra Playground and Cloud. To maintain access while adding external exporters, include the default exporters in your custom config:
310
+
311
+ ```ts filename="src/mastra/index.ts" showLineNumbers copy
312
+ import { DefaultExporter, CloudExporter } from '@mastra/core/ai-tracing';
313
+ import { LangfuseExporter } from '@mastra/langfuse';
314
+
315
+ export const mastra = new Mastra({
316
+ observability: {
317
+ default: { enabled: false }, // Disable default to use custom
318
+ configs: {
319
+ production: {
320
+ serviceName: 'my-service',
321
+ exporters: [
322
+ new LangfuseExporter(), // External exporter
323
+ new DefaultExporter(), // Keep Playground access
324
+ new CloudExporter(), // Keep Cloud access
325
+ ],
326
+ },
327
+ },
328
+ },
329
+ });
330
+ ```
331
+
332
+ This configuration sends traces to all three destinations simultaneously:
333
+ - **Langfuse** for external observability
334
+ - **DefaultExporter** for local Playground access
335
+ - **CloudExporter** for Mastra Cloud dashboard
336
+
337
+ <Callout type="info">
338
+ Remember: A single trace can be sent to multiple exporters. You don't need separate configs for each exporter unless you want different sampling rates or processors.
339
+ </Callout>
340
+
341
+ ## Adding Custom Metadata
342
+
343
+ Custom metadata allows you to attach additional context to your traces, making it easier to debug issues and understand system behavior in production. Metadata can include business logic details, performance metrics, user context, or any information that helps you understand what happened during execution.
344
+
345
+ You can add metadata to any span using the tracing context:
346
+
347
+ ```ts showLineNumbers copy
348
+ execute: async ({ inputData, tracingContext }) => {
349
+ const startTime = Date.now();
350
+ const response = await fetch(inputData.endpoint);
351
+
352
+ // Add custom metadata to the current span
353
+ tracingContext.currentSpan?.update({
354
+ metadata: {
355
+ apiStatusCode: response.status,
356
+ endpoint: inputData.endpoint,
357
+ responseTimeMs: Date.now() - startTime,
358
+ userTier: inputData.userTier,
359
+ region: process.env.AWS_REGION,
360
+ }
361
+ });
362
+
363
+ return await response.json();
364
+ }
365
+ ```
366
+
367
+ Metadata set here will be shown in all configured exporters.
368
+
369
+ ## Creating Child Spans
370
+
371
+ Child spans allow you to track fine-grained operations within your workflow steps or tools. They provide visibility into sub-operations like database queries, API calls, file operations, or complex calculations. This hierarchical structure helps you identify performance bottlenecks and understand the exact sequence of operations.
372
+
373
+ Create child spans inside a tool call or workflow step to track specific operations:
374
+
375
+ ```ts showLineNumbers copy
376
+ execute: async ({ input, tracingContext }) => {
377
+ // Create another child span for the main database operation
378
+ const querySpan = tracingContext.currentSpan?.createChildSpan({
379
+ type: 'generic',
380
+ name: 'database-query',
381
+ input: { query: input.query },
382
+ metadata: { database: 'production' },
383
+ });
384
+
385
+ try {
386
+ const results = await db.query(input.query);
387
+ querySpan?.end({
388
+ output: results.data,
389
+ metadata: {
390
+ rowsReturned: results.length,
391
+ queryTimeMs: results.executionTime,
392
+ cacheHit: results.fromCache
393
+ }
394
+ });
395
+ return results;
396
+ } catch (error) {
397
+ querySpan?.error({
398
+ error,
399
+ metadata: { retryable: isRetryableError(error) }
400
+ });
401
+ throw error;
402
+ }
403
+ }
404
+ ```
405
+
406
+ Child spans automatically inherit the trace context from their parent, maintaining the relationship hierarchy in your observability platform.
407
+
408
+ ## Span Processors
409
+
410
+ Span processors allow you to transform, filter, or enrich trace data before it's exported. They act as a pipeline between span creation and export, enabling you to modify spans for security, compliance, or debugging purposes. Mastra includes built-in processors and supports custom implementations.
411
+
412
+ ### Built-in Processors
413
+
414
+ * [Sensitive Data Filter](/docs/observability/processors/sensitive-data-filter) redacts sensitive information. It is enabled in the default observability config.
415
+
416
+ ### Creating Custom Processors
417
+
418
+ You can create custom span processors by implementing the `AISpanProcessor` interface. Here's a simple example that converts all input text in spans to lowercase:
419
+
420
+ ```ts filename="src/processors/lowercase-input-processor.ts" showLineNumbers copy
421
+ import type { AISpanProcessor, AnyAISpan } from '@mastra/core/ai-tracing';
422
+
423
+ export class LowercaseInputProcessor implements AISpanProcessor {
424
+ name = 'lowercase-processor';
425
+
426
+ process(span: AnyAISpan): AnyAISpan {
427
+ span.input = `${span.input}`.toLowerCase()
428
+ return span;
429
+ }
430
+
431
+ async shutdown(): Promise<void> {
432
+ // Cleanup if needed
433
+ }
434
+ }
435
+
436
+ // Use the custom processor
437
+ export const mastra = new Mastra({
438
+ observability: {
439
+ configs: {
440
+ development: {
441
+ processors: [
442
+ new LowercaseInputProcessor(),
443
+ new SensitiveDataFilter(),
444
+ ],
445
+ exporters: [new DefaultExporter()],
446
+ },
447
+ },
448
+ },
449
+ });
450
+ ```
451
+
452
+ Processors are executed in the order they're defined, allowing you to chain multiple transformations. Common use cases for custom processors include:
453
+ - Adding environment-specific metadata
454
+ - Filtering out spans based on criteria
455
+ - Normalizing data formats
456
+ - Sampling high-volume traces
457
+ - Enriching spans with business context
458
+
459
+ ## Retrieving Trace IDs
460
+
461
+ When you execute agents or workflows with tracing enabled, the response includes a `traceId` that you can use to look up the full trace in your observability platform. This is useful for debugging, customer support, or correlating traces with other events in your system.
462
+
463
+ ### Agent Trace IDs
464
+
465
+ Both `generate` and `stream` methods return the trace ID in their response:
466
+
467
+ ```ts showLineNumbers copy
468
+ // Using generate
469
+ const result = await agent.generate({
470
+ messages: [{ role: 'user', content: 'Hello' }]
471
+ });
472
+
473
+ console.log('Trace ID:', result.traceId);
474
+
475
+ // Using stream
476
+ const streamResult = await agent.stream({
477
+ messages: [{ role: 'user', content: 'Tell me a story' }]
478
+ });
479
+
480
+ console.log('Trace ID:', streamResult.traceId);
481
+ ```
482
+
483
+ ### Workflow Trace IDs
484
+
485
+ Workflow executions also return trace IDs:
486
+
487
+ ```ts showLineNumbers copy
488
+ // Create a workflow run
489
+ const run = await mastra.getWorkflow('myWorkflow').createRunAsync();
490
+
491
+ // Start the workflow
492
+ const result = await run.start({
493
+ inputData: { data: 'process this' }
494
+ });
495
+
496
+ console.log('Trace ID:', result.traceId);
497
+
498
+ // Or stream the workflow
499
+ const { stream, getWorkflowState } = run.stream({
500
+ inputData: { data: 'process this' }
501
+ });
502
+
503
+ // Get the final state which includes the trace ID
504
+ const finalState = await getWorkflowState();
505
+ console.log('Trace ID:', finalState.traceId);
506
+ ```
507
+
508
+ ### Using Trace IDs
509
+
510
+ Once you have a trace ID, you can:
511
+
512
+ 1. **Look up traces in Mastra Playground**: Navigate to the traces view and search by ID
513
+ 2. **Query traces in external platforms**: Use the ID in Langfuse, Braintrust, or your observability platform
514
+ 3. **Correlate with logs**: Include the trace ID in your application logs for cross-referencing
515
+ 4. **Share for debugging**: Provide trace IDs to support teams or developers for investigation
516
+
517
+ The trace ID is only available when tracing is enabled. If tracing is disabled or sampling excludes the request, `traceId` will be `undefined`.
518
+
519
+ ## What Gets Traced
520
+
521
+ Mastra automatically creates spans for:
522
+
523
+ ### Agent Operations
524
+ - **Agent runs** - Complete execution with instructions and tools
525
+ - **LLM calls** - Model interactions with tokens and parameters
526
+ - **Tool executions** - Function calls with inputs and outputs
527
+ - **Memory operations** - Thread and semantic recall
528
+
529
+ ### Workflow Operations
530
+ - **Workflow runs** - Full execution from start to finish
531
+ - **Individual steps** - Step processing with inputs/outputs
532
+ - **Control flow** - Conditionals, loops, parallel execution
533
+ - **Wait operations** - Delays and event waiting
534
+
535
+ ## Viewing Traces
536
+
537
+ Traces are available in multiple locations:
538
+
539
+ - **Mastra Playground** - Local development environment
540
+ - **Mastra Cloud** - Production monitoring dashboard
541
+ - **Langfuse Dashboard** - When using Langfuse exporter
542
+ - **Braintrust Console** - When using Braintrust exporter
543
+
544
+ ## See Also
545
+
546
+ ### Examples
547
+ - [Basic AI Tracing Example](/examples/observability/basic-ai-tracing) - Working implementation
548
+ - [Advanced Tracing Patterns](/examples/observability/advanced-tracing) - Complex scenarios
549
+
550
+ ### Reference Documentation
551
+ - [Configuration API](/reference/observability/ai-tracing/configuration) - ObservabilityConfig details
552
+ - [AITracing Classes](/reference/observability/ai-tracing/ai-tracing) - Core classes and methods
553
+ - [Span Interfaces](/reference/observability/ai-tracing/span) - Span types and lifecycle
554
+ - [Type Definitions](/reference/observability/ai-tracing/interfaces) - Complete interface reference
555
+
556
+ ### Exporters
557
+ - [DefaultExporter](/reference/observability/ai-tracing/exporters/default-exporter) - Storage persistence
558
+ - [CloudExporter](/reference/observability/ai-tracing/exporters/cloud-exporter) - Mastra Cloud integration
559
+ - [ConsoleExporter](/reference/observability/ai-tracing/exporters/console-exporter) - Debug output
560
+ - [Langfuse](/reference/observability/ai-tracing/exporters/langfuse) - Langfuse integration
561
+ - [Braintrust](/reference/observability/ai-tracing/exporters/braintrust) - Braintrust integration
562
+
563
+ ### Processors
564
+ - [Sensitive Data Filter](/docs/observability/processors/sensitive-data-filter) - Data redaction
565
+ - [Custom Processors Guide](/docs/observability/processors/custom-processors) - Build your own