@mastra/mcp-docs-server 1.3.11-alpha.0 → 1.3.11-alpha.2

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 (87) hide show
  1. package/.docs/course/01-first-agent/16-adding-memory-to-agent.md +7 -1
  2. package/.docs/course/02-agent-tools-mcp/25-creating-notes-directory.md +8 -0
  3. package/.docs/course/02-agent-tools-mcp/26-updating-mcp-config-filesystem.md +10 -7
  4. package/.docs/course/02-agent-tools-mcp/27-updating-agent-instructions-filesystem.md +3 -1
  5. package/.docs/course/02-agent-tools-mcp/29-troubleshooting-filesystem.md +3 -2
  6. package/.docs/course/02-agent-tools-mcp/31-enhancing-memory-configuration.md +2 -2
  7. package/.docs/course/03-agent-memory/04-creating-basic-memory-agent.md +3 -1
  8. package/.docs/course/03-agent-memory/08-configuring-conversation-history.md +1 -1
  9. package/.docs/course/03-agent-memory/09-using-memory-in-application.md +8 -6
  10. package/.docs/course/03-agent-memory/10-storage-configuration.md +11 -1
  11. package/.docs/course/03-agent-memory/12-handling-memory-frontend.md +5 -3
  12. package/.docs/course/03-agent-memory/13-vector-store-configuration.md +4 -2
  13. package/.docs/course/03-agent-memory/16-configuring-semantic-recall.md +2 -2
  14. package/.docs/course/03-agent-memory/18-advanced-configuration-semantic-recall.md +2 -2
  15. package/.docs/course/03-agent-memory/21-configuring-working-memory.md +2 -2
  16. package/.docs/course/03-agent-memory/22-custom-working-memory-templates.md +2 -5
  17. package/.docs/course/03-agent-memory/25-combining-memory-features.md +2 -2
  18. package/.docs/course/03-agent-memory/27-creating-learning-assistant.md +2 -2
  19. package/.docs/course/04-workflows/05-chaining-steps-together.md +2 -1
  20. package/.docs/course/04-workflows/12-using-agent-in-workflow.md +11 -14
  21. package/.docs/course/04-workflows/20-building-conditional-workflow.md +32 -6
  22. package/.docs/docs/agents/guardrails.md +1 -1
  23. package/.docs/docs/agents/human-in-the-loop.md +1 -1
  24. package/.docs/docs/agents/structured-output.md +11 -0
  25. package/.docs/docs/channels.md +2 -0
  26. package/.docs/docs/classifier.md +103 -0
  27. package/.docs/docs/deployment/mastra-server.md +3 -1
  28. package/.docs/docs/evals/custom-scorers.md +20 -0
  29. package/.docs/docs/evals/quick-checks.md +7 -7
  30. package/.docs/docs/guides/context-engineering.md +2 -2
  31. package/.docs/docs/mastra-platform/observability.md +1 -1
  32. package/.docs/docs/memory/memory-processors.md +49 -3
  33. package/.docs/docs/memory/observational-memory.md +27 -1
  34. package/.docs/docs/observability/tracing/overview.md +41 -1
  35. package/.docs/docs/workflows/control-flow.md +1 -1
  36. package/.docs/integrations/databases/postgresql.md +31 -0
  37. package/.docs/integrations/deploy/vercel.md +11 -0
  38. package/.docs/integrations/observability/langfuse.md +13 -0
  39. package/.docs/models/gateways/netlify.md +2 -5
  40. package/.docs/models/gateways/openrouter.md +2 -11
  41. package/.docs/models/gateways/vercel.md +1 -1
  42. package/.docs/models/index.md +1 -1
  43. package/.docs/models/providers/cortecs.md +1 -1
  44. package/.docs/models/providers/deepinfra.md +0 -1
  45. package/.docs/models/providers/edenai.md +25 -4
  46. package/.docs/models/providers/empiriolabs.md +2 -1
  47. package/.docs/models/providers/google.md +1 -4
  48. package/.docs/models/providers/inceptron.md +4 -4
  49. package/.docs/models/providers/kilo.md +13 -27
  50. package/.docs/models/providers/llmgateway-providers.md +16 -21
  51. package/.docs/models/providers/llmgateway.md +4 -3
  52. package/.docs/models/providers/melious.md +10 -10
  53. package/.docs/models/providers/mistral.md +25 -24
  54. package/.docs/models/providers/nano-gpt.md +10 -21
  55. package/.docs/models/providers/nvidia.md +0 -1
  56. package/.docs/models/providers/ofox.md +3 -1
  57. package/.docs/models/providers/openai.md +1 -4
  58. package/.docs/models/providers/opencode.md +0 -1
  59. package/.docs/models/providers/scaleway.md +1 -1
  60. package/.docs/reference/agents/channels.md +61 -1
  61. package/.docs/reference/agents/generate.md +0 -10
  62. package/.docs/reference/agents/generateLegacy.md +0 -10
  63. package/.docs/reference/agents/network.md +0 -10
  64. package/.docs/reference/browser/agent-browser.md +7 -3
  65. package/.docs/reference/browser/mastra-browser.md +34 -0
  66. package/.docs/reference/classifier/classifier.md +3 -1
  67. package/.docs/reference/client-js/observability.md +16 -15
  68. package/.docs/reference/configuration.md +3 -1
  69. package/.docs/reference/connect/providers.md +65 -1
  70. package/.docs/reference/core/getDeployer.md +1 -1
  71. package/.docs/reference/core/mastra-class.md +1 -1
  72. package/.docs/reference/deployer/vercel.md +24 -1
  73. package/.docs/reference/editor/mastra-editor.md +1 -1
  74. package/.docs/reference/evals/tool-call-accuracy.md +7 -4
  75. package/.docs/reference/memory/memory-class.md +77 -0
  76. package/.docs/reference/observability/tracing/advanced-queries.md +33 -16
  77. package/.docs/reference/observability/tracing/exporters/langfuse.md +11 -0
  78. package/.docs/reference/observability/tracing/exporters/otel.md +123 -3
  79. package/.docs/reference/observability/tracing/interfaces.md +15 -0
  80. package/.docs/reference/observability/tracing/spans.md +1 -1
  81. package/.docs/reference/signals/signal-provider.md +42 -1
  82. package/.docs/reference/streaming/agents/stream.md +19 -10
  83. package/.docs/reference/streaming/agents/streamLegacy.md +0 -10
  84. package/.docs/reference/workspace/factory-sandbox.md +18 -0
  85. package/.docs/reference/workspace/filesystem.md +1 -1
  86. package/.docs/reference/workspace/local-filesystem.md +1 -1
  87. package/package.json +3 -3
@@ -61,6 +61,83 @@ export const agent = new Agent({
61
61
 
62
62
  **memory** (`Memory`): A new Memory instance with the specified configuration.
63
63
 
64
+ ## `saveMessages()`
65
+
66
+ `agent.generate()` and `agent.stream()` persist messages for you. Call `memory.saveMessages()` when you need to write messages yourself, for example to seed a thread, to import a transcript, or to store messages that originated outside Mastra. Each message needs a `threadId` and a `resourceId`, so create the thread with [`createThread()`](https://mastra.ai/reference/memory/createThread) before saving into it.
67
+
68
+ ```typescript
69
+ await memory.saveMessages({
70
+ messages: [
71
+ {
72
+ id: 'msg-1',
73
+ threadId: 'thread-123',
74
+ resourceId: 'user-456',
75
+ role: 'user',
76
+ createdAt: new Date(),
77
+ content: {
78
+ format: 2,
79
+ parts: [{ type: 'text', text: 'Where is my order?' }],
80
+ },
81
+ },
82
+ ],
83
+ })
84
+ ```
85
+
86
+ ### Parameters
87
+
88
+ **messages** (`MastraDBMessage[]`): The messages to save. Every message must include a threadId and a resourceId.
89
+
90
+ **memoryConfig** (`MemoryConfig`): Per-call memory options. Merged over the options passed to the constructor.
91
+
92
+ **observabilityContext** (`Partial<ObservabilityContext>`): Tracing context attached to the save operation.
93
+
94
+ Returns `Promise<{ messages: MastraDBMessage[]; usage?: { tokens: number } }>`. `usage` is present when the embedder reports token usage while indexing messages for semantic recall.
95
+
96
+ ### `MastraDBMessage`
97
+
98
+ Storage uses a single message shape, `MastraDBMessage`. The methods that hand messages back or take them in use this shape, including `saveMessages()` and [`recall()`](https://mastra.ai/reference/memory/recall).
99
+
100
+ **id** (`string`): Message identifier.
101
+
102
+ **role** (`'user' | 'assistant' | 'system' | 'signal'`): Who produced the message. System messages and transient signals are not persisted.
103
+
104
+ **threadId** (`string`): Thread the message belongs to. Required when saving.
105
+
106
+ **resourceId** (`string`): Resource (usually a user or tenant) the message belongs to. Required when saving.
107
+
108
+ **createdAt** (`Date`): Message timestamp.
109
+
110
+ **content** (`MastraMessageContentV2`): The message body. Its parts array holds the text, reasoning, tool calls, and attachments.
111
+
112
+ `content.parts` is the part the agent actually reads. `content.format` is always `2` for stored messages, and `content.metadata` carries arbitrary custom data. `content.toolInvocations`, `content.reasoning`, and `content.experimental_attachments` are flat mirrors kept for AI SDK v4 compatibility; write to `parts` instead.
113
+
114
+ ```typescript
115
+ const assistantMessage = {
116
+ id: 'msg-2',
117
+ threadId: 'thread-123',
118
+ resourceId: 'user-456',
119
+ role: 'assistant',
120
+ createdAt: new Date(),
121
+ content: {
122
+ format: 2,
123
+ parts: [
124
+ { type: 'text', text: 'It ships tomorrow.' },
125
+ {
126
+ type: 'tool-invocation',
127
+ toolInvocation: {
128
+ state: 'result',
129
+ toolCallId: 'call-1',
130
+ toolName: 'lookupOrder',
131
+ args: { orderId: 'A-1' },
132
+ result: { eta: '2026-10-30' },
133
+ },
134
+ },
135
+ ],
136
+ metadata: { source: 'import' },
137
+ },
138
+ }
139
+ ```
140
+
64
141
  ## Extended usage example
65
142
 
66
143
  ```typescript
@@ -30,6 +30,8 @@ The configured observability store must support each API. Call `getObservability
30
30
  | `traceQueryRootDuration` | `trace-query-root-duration` | Trace-scope `durationMs` predicates |
31
31
  | `traceQueryTimeToFirstChunk` | `trace-query-time-to-first-chunk` | `timeToFirstChunkMs` predicates and results |
32
32
  | `traceQueryTimeToFirstChunkSort` | `trace-query-time-to-first-chunk-sort` | `orderBy` on `timeToFirstChunkMs` |
33
+ | `traceQueryTimeToFirstToken` | `trace-query-time-to-first-token` | `timeToFirstTokenMs` predicates and results |
34
+ | `traceQueryTimeToFirstTokenSort` | `trace-query-time-to-first-token-sort` | `orderBy` on `timeToFirstTokenMs` |
33
35
  | `traceQueryContextIds` | `trace-query-context-ids` | `runId`, `sessionId`, `userId`, and `organizationId` predicates |
34
36
  | `traceQueryRootSpanFields` | `trace-query-root-span-fields` | Trace-scope `name` and `spanType` predicates, dimensions, and `countDistinct` measures |
35
37
  | `traceQueryRootEntityId` | `trace-query-root-entity-id` | Trace-scope `entityId` predicates, dimensions, and `countDistinct` measures |
@@ -81,18 +83,18 @@ Span clauses examine the current root span and current child spans. The root `ti
81
83
  | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------- |
82
84
  | Trace | `traceId`, `threadId`, `resourceId`, `runId`, `sessionId`, `userId`, `organizationId`, `entityId`, `entityName`, `entityType`, `name`, `spanType`, `environment`, `status` | `eq`, `ne`, `in`, `notIn`, `exists`, `notExists` |
83
85
  | Trace metadata | `metadata.<key>` | `eq`, `ne`, `in`, `notIn`, `exists`, `notExists` |
84
- | Trace | `startedAt`, `endedAt`, `durationMs`, `timeToFirstChunkMs` | `eq`, `ne`, `in`, `notIn`, `lt`, `lte`, `gt`, `gte`, `exists`, `notExists` |
86
+ | Trace | `startedAt`, `endedAt`, `durationMs`, `timeToFirstChunkMs`, `timeToFirstTokenMs` | `eq`, `ne`, `in`, `notIn`, `lt`, `lte`, `gt`, `gte`, `exists`, `notExists` |
85
87
  | Trace | `tags` | `includes`, `notIncludes`, `exists`, `notExists` |
86
88
  | Span | `name` | `eq`, `ne`, `in`, `notIn`, `exists`, `notExists`, `matches`, `notMatches` |
87
89
  | Span | `spanType`, `model`, `provider`, `status`, `entityType`, `entityId`, `entityName`, `entityVersionId`, `parentEntityVersionId`, `rootEntityVersionId`, `runId`, `sessionId`, `userId`, `organizationId` | `eq`, `ne`, `in`, `notIn`, `exists`, `notExists` |
88
- | Span | `startedAt`, `endedAt`, `durationMs`, `timeToFirstChunkMs` | `eq`, `ne`, `in`, `notIn`, `lt`, `lte`, `gt`, `gte`, `exists`, `notExists` |
90
+ | Span | `startedAt`, `endedAt`, `durationMs`, `timeToFirstChunkMs`, `timeToFirstTokenMs` | `eq`, `ne`, `in`, `notIn`, `lt`, `lte`, `gt`, `gte`, `exists`, `notExists` |
89
91
  | Span | `error` | `exists`, `notExists` |
90
92
 
91
93
  Trace-scope `name`, `spanType`, and `entityId` 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.
92
94
 
93
95
  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).
94
96
 
95
- 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.
97
+ 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, time-to-first-chunk, and time-to-first-token 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.
96
98
 
97
99
  #### Filter by root duration
98
100
 
@@ -140,6 +142,20 @@ Pass `orderBy: [{ field: 'timeToFirstChunkMs', direction: 'desc' }]` to list the
140
142
 
141
143
  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.
142
144
 
145
+ #### Filter and sort by time to first token
146
+
147
+ `timeToFirstTokenMs` is the time in milliseconds from the start of a model call, the provider request itself, to the first chunk that call streams. It leaves out the work Mastra does before calling the model, such as input processors. The value is measured once, on the model inference span that streamed the chunk. Model step, model generation, and agent run spans carry the value of the nearest such inference below them: each step takes its own, and the generation and agent run take the first step's. A step can run more than one inference, for example a fallback model or a retry that opens a new inference span. The value then comes from the first inference that streamed a chunk. A fallback attempt that failed ends its inference span with its error. That span has a value only if it streamed a chunk first. Mastra storage keeps the value in its own column and leaves it out of the stored `attributes`. Read it from the span's `timeToFirstTokenMs` field. When an in-process agent retries a failed model call, the AI SDK retries inside a single inference span. The value then includes the failed attempt and the retry wait. Durable agents open one inference span per attempt and don't. At trace scope, the field reads the current root span's value. Inside `spans.some` or `spans.none`, it reads each related span.
148
+
149
+ This predicate finds traces whose root agent waited more than 2 seconds for the model's first token:
150
+
151
+ ```typescript
152
+ const slowFirstToken = { op: 'gt', left: { path: 'timeToFirstTokenMs' }, right: { literal: 2000 } }
153
+ ```
154
+
155
+ `null`, `0`, and missing values follow the same rules as `timeToFirstChunkMs`. Pass `orderBy: [{ field: 'timeToFirstTokenMs', direction: 'desc' }]` to list the slowest first tokens first, with the same ordering and tie-breaks.
156
+
157
+ Stores advertise support through the `trace-query-time-to-first-token` feature and the sort through the `trace-query-time-to-first-token-sort` feature. The server reports them as the `traceQueryTimeToFirstToken` and `traceQueryTimeToFirstTokenSort` capabilities. Against an older store, results omit the field, and a predicate or sort on it returns `501` before storage runs.
158
+
143
159
  #### Filter by context identifiers
144
160
 
145
161
  `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`:
@@ -447,16 +463,16 @@ curl --request POST \
447
463
 
448
464
  ### Request fields
449
465
 
450
- | Field | Required | Description |
451
- | ------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
452
- | `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`. |
453
- | `where` | No | Recursive trace predicate. Supports scalar conditions and `spans.some` or `spans.none` clauses. |
454
- | `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. |
455
- | `page` | No | `{ limit, after }`. `limit` defaults to 100 and has a maximum of 1000. Pass the opaque `page.next` value as `after`. |
456
- | `pagination` | No | Numbered pages: `{ page, perPage }`. Defaults to page 0 and 10 results. `perPage` has a maximum of 100. |
457
- | `mode` | No | Set to `'delta'` to poll using a delta cursor instead of `page` or `pagination`. |
458
- | `after` | No | Delta mode only. Opaque `deltaCursor` from a numbered page or previous poll. Omit to establish the current watermark. |
459
- | `limit` | No | Delta mode only. Maximum results per batch. Defaults to 10 and has a maximum of 100. |
466
+ | Field | Required | Description |
467
+ | ------------ | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
468
+ | `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`. |
469
+ | `where` | No | Recursive trace predicate. Supports scalar conditions and `spans.some` or `spans.none` clauses. |
470
+ | `orderBy` | No | One item ordering results by `startedAt`, `endedAt`, `timeToFirstChunkMs`, or `timeToFirstTokenMs`, in `asc` or `desc` order. Defaults to `startedAt desc`. Not accepted in delta mode. |
471
+ | `page` | No | `{ limit, after }`. `limit` defaults to 100 and has a maximum of 1000. Pass the opaque `page.next` value as `after`. |
472
+ | `pagination` | No | Numbered pages: `{ page, perPage }`. Defaults to page 0 and 10 results. `perPage` has a maximum of 100. |
473
+ | `mode` | No | Set to `'delta'` to poll using a delta cursor instead of `page` or `pagination`. |
474
+ | `after` | No | Delta mode only. Opaque `deltaCursor` from a numbered page or previous poll. Omit to establish the current watermark. |
475
+ | `limit` | No | Delta mode only. Maximum results per batch. Defaults to 10 and has a maximum of 100. |
460
476
 
461
477
  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.
462
478
 
@@ -478,14 +494,15 @@ A query using keyset pagination returns lightweight completed traces and a curso
478
494
  "entityType": "agent",
479
495
  "environment": "production",
480
496
  "status": "success",
481
- "timeToFirstChunkMs": 412
497
+ "timeToFirstChunkMs": 412,
498
+ "timeToFirstTokenMs": 380
482
499
  }
483
500
  ],
484
501
  "page": { "next": null }
485
502
  }
486
503
  ```
487
504
 
488
- `timeToFirstChunkMs` is present only when the configured store supports it. See [Filter by time to first chunk](#filter-by-time-to-first-chunk).
505
+ `timeToFirstChunkMs` and `timeToFirstTokenMs` are present only when the configured store supports them. See [Filter by time to first chunk](#filter-by-time-to-first-chunk) and [Filter and sort by time to first token](#filter-and-sort-by-time-to-first-token).
489
506
 
490
507
  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.
491
508
 
@@ -1005,7 +1022,7 @@ Value suggestions are available for these canonical fields:
1005
1022
  | Trace | `entityName`, `entityType`, `name`, `spanType`, `environment`, `status`, `tags` |
1006
1023
  | Spans | `name`, `spanType`, `model`, `provider`, `status`, `entityType`, `entityName` |
1007
1024
 
1008
- 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`.
1025
+ Each executable top-level string `metadata.<key>` field also supports value suggestions in the `trace` scope. Identifiers, timestamps, durations, time to first chunk, time to first token, 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`.
1009
1026
 
1010
1027
  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.
1011
1028
 
@@ -94,6 +94,17 @@ Mastra spans are converted to OTel format and sent to Langfuse via `LangfuseSpan
94
94
  - All other spans → Langfuse spans
95
95
  - Parent-child relationships are preserved via OTel trace/span IDs
96
96
 
97
+ ## Cost tracking
98
+
99
+ Langfuse reports cost from `langfuse.observation.cost_details`. The exporter sends that field only for model generation spans whose cost metadata meets all of these conditions:
100
+
101
+ - The span is a `MODEL_GENERATION` span.
102
+ - `costContext.costMetadata.source` is `'provider_reported'`, meaning the model provider returned the cost. Estimated costs aren't exported, so Langfuse can apply its own model pricing instead.
103
+ - `costContext.costUnit` is `'USD'`.
104
+ - `costContext.estimatedCost` is a finite, non-negative number.
105
+
106
+ When any condition fails, the generation is exported without cost details and Langfuse falls back to its own pricing model, which also covers providers such as most self-hosted or direct model APIs that don't report cost until you configure model prices in Langfuse.
107
+
97
108
  ## Prompt linking
98
109
 
99
110
  Link LLM generations to [Langfuse Prompt Management](https://langfuse.com/docs/prompt-management) using the `withLangfusePrompt` helper:
@@ -24,9 +24,45 @@ interface OtelExporterConfig {
24
24
  timeout?: number
25
25
  batchSize?: number
26
26
  logLevel?: 'debug' | 'info' | 'warn' | 'error'
27
+ metadataMapping?: Record<string, string>
27
28
  }
28
29
  ```
29
30
 
31
+ **provider** (`ProviderConfig`): Provider-specific configuration (see below)
32
+
33
+ **signals** (`{ traces?: boolean; logs?: boolean }`): Per-signal toggle. Both default to true. Set a value to false to disable that signal. Log export also requires the matching @opentelemetry/exporter-logs-otlp-\* package to be installed for the chosen protocol.
34
+
35
+ **timeout** (`number`): Export timeout in milliseconds (default: 30000)
36
+
37
+ **batchSize** (`number`): Number of spans/logs per batch (default: 512)
38
+
39
+ **logLevel** (`'debug' | 'info' | 'warn' | 'error'`): Logger level (default: 'warn')
40
+
41
+ **metadataMapping** (`Record<string, string>`): Maps metadata keys to top-level span attribute names, for example { userId: "user.id" }. Disabled by default. Namespaced metadata is retained. See Metadata mapping below for value conversion and precedence.
42
+
43
+ **resourceAttributes** (`DetectedResourceAttributes`): Optional OpenTelemetry Resource Attributes (values here override any defaults)
44
+
45
+ ## Metadata mapping
46
+
47
+ Use `metadataMapping` when your backend expects metadata such as `userId` under a specific span attribute name:
48
+
49
+ ```typescript
50
+ import { OtelExporter } from '@mastra/otel-exporter'
51
+
52
+ const exporter = new OtelExporter({
53
+ provider: {
54
+ custom: { endpoints: { traces: 'https://collector.example.com/v1/traces' } },
55
+ },
56
+ metadataMapping: { userId: 'user.id', tenantId: 'tenant.id' },
57
+ })
58
+ ```
59
+
60
+ A span with metadata `{ userId: 'user-123', tenantId: 'acme' }` exports both `user.id` and `tenant.id`, alongside the existing `mastra.metadata.userId` and `mastra.metadata.tenantId` attributes. Mappings apply to every span that contains the selected metadata keys, including child spans.
61
+
62
+ Mapped values are strings. Objects and arrays are JSON-encoded. Missing keys, `null`, `undefined`, and empty strings are omitted. `0` and `false` become `"0"` and `"false"`. Keys are matched literally, so a key containing a dot doesn't select a nested property. Empty destination names are ignored.
63
+
64
+ Explicit mappings overwrite existing attributes with the same destination name. If multiple metadata keys map to the same name, the last mapping with a non-empty value wins. Mapping doesn't affect log records or resource attributes.
65
+
30
66
  ## Provider configurations
31
67
 
32
68
  ### `Dash0Config`
@@ -39,6 +75,12 @@ interface Dash0Config {
39
75
  }
40
76
  ```
41
77
 
78
+ **apiKey** (`string`): Dash0 API key. Falls back to DASH0_API_KEY env var.
79
+
80
+ **endpoint** (`string`): Dash0 ingress endpoint. Falls back to DASH0_ENDPOINT env var.
81
+
82
+ **dataset** (`string`): Dataset name. Falls back to DASH0_DATASET env var.
83
+
42
84
  ### `SignozConfig`
43
85
 
44
86
  ```typescript
@@ -49,6 +91,12 @@ interface SignozConfig {
49
91
  }
50
92
  ```
51
93
 
94
+ **apiKey** (`string`): SigNoz ingestion key. Falls back to SIGNOZ_API_KEY env var.
95
+
96
+ **region** (`'us' | 'eu' | 'in'`): SigNoz cloud region. Falls back to SIGNOZ_REGION env var. (default: 'us')
97
+
98
+ **endpoint** (`string`): Custom endpoint. Falls back to SIGNOZ_ENDPOINT env var.
99
+
52
100
  ### `NewRelicConfig`
53
101
 
54
102
  ```typescript
@@ -58,6 +106,10 @@ interface NewRelicConfig {
58
106
  }
59
107
  ```
60
108
 
109
+ **apiKey** (`string`): New Relic license key. Falls back to NEW_RELIC_LICENSE_KEY env var.
110
+
111
+ **endpoint** (`string`): Custom endpoint. Falls back to NEW_RELIC_ENDPOINT env var. (default: https\://otlp.nr-data.net:443/v1/traces)
112
+
61
113
  ### `TraceloopConfig`
62
114
 
63
115
  ```typescript
@@ -68,6 +120,12 @@ interface TraceloopConfig {
68
120
  }
69
121
  ```
70
122
 
123
+ **apiKey** (`string`): Traceloop API key. Falls back to TRACELOOP_API_KEY env var.
124
+
125
+ **destinationId** (`string`): Destination identifier. Falls back to TRACELOOP_DESTINATION_ID env var.
126
+
127
+ **endpoint** (`string`): Custom endpoint. Falls back to TRACELOOP_ENDPOINT env var. (default: https\://api.traceloop.com/v1/traces)
128
+
71
129
  ### `LaminarConfig`
72
130
 
73
131
  ```typescript
@@ -77,16 +135,78 @@ interface LaminarConfig {
77
135
  }
78
136
  ```
79
137
 
138
+ **apiKey** (`string`): Laminar project API key. Falls back to LMNR_PROJECT_API_KEY env var.
139
+
140
+ **endpoint** (`string`): Custom endpoint. Falls back to LAMINAR_ENDPOINT env var. (default: https\://api.lmnr.ai/v1/traces)
141
+
80
142
  ### `CustomConfig`
81
143
 
82
144
  ```typescript
83
- interface CustomConfig {
84
- endpoint: string
145
+ type CustomConfig = {
85
146
  protocol?: 'http/json' | 'http/protobuf' | 'grpc' | 'zipkin'
86
147
  headers?: Record<string, string>
87
- }
148
+ } & (
149
+ | { endpoint?: string; endpoints?: never }
150
+ | {
151
+ endpoint?: never
152
+ endpoints:
153
+ | { traces: string | undefined; logs?: string | undefined }
154
+ | { traces?: string | undefined; logs: string | undefined }
155
+ }
156
+ )
88
157
  ```
89
158
 
159
+ **endpoint** (`string`): Legacy collector endpoint. Cannot be combined with endpoints. Uses the existing signal-path derivation for OTLP.
160
+
161
+ **endpoints** (`{ traces: string | undefined; logs?: string | undefined } | { traces?: string | undefined; logs: string | undefined }`): Exact per-signal URLs. Supply at least one endpoint. Omitted signals are not exported. Cannot be combined with endpoint.
162
+
163
+ **protocol** (`'http/json' | 'http/protobuf' | 'grpc' | 'zipkin'`): Export protocol (default: 'http/json')
164
+
165
+ **headers** (`Record<string, string>`): Custom headers for authentication
166
+
167
+ ### Custom signal endpoints
168
+
169
+ Supply either `endpoint` or `endpoints`, never both. TypeScript rejects configurations with both options. Runtime validation also rejects them and disables the exporter with an error message.
170
+
171
+ Use `endpoints` to supply the exact URL for each signal. URLs are passed to the selected exporter without adding, removing, or replacing path segments. Trace and log endpoints can use different hosts and unrelated paths:
172
+
173
+ ```typescript
174
+ import { OtelExporter } from '@mastra/otel-exporter'
175
+
176
+ const exporter = new OtelExporter({
177
+ provider: {
178
+ custom: {
179
+ protocol: 'http/protobuf',
180
+ endpoints: {
181
+ traces: 'https://traces.example.com/api/ingest/?tenant=acme',
182
+ logs: 'https://logs.example.com/events',
183
+ },
184
+ },
185
+ },
186
+ })
187
+ ```
188
+
189
+ Supply at least one signal endpoint. Omit `logs` for trace-only export or `traces` for log-only export. The `signals` toggles can still disable a configured signal. Protocol and headers apply to both endpoints. The selected protocol must support the signal. A custom `exporter` instance overrides trace transport as before.
190
+
191
+ You can pass environment-variable values explicitly:
192
+
193
+ ```typescript
194
+ const exporter = new OtelExporter({
195
+ provider: {
196
+ custom: {
197
+ endpoints: {
198
+ traces: process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT,
199
+ logs: process.env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT,
200
+ },
201
+ },
202
+ },
203
+ })
204
+ ```
205
+
206
+ The type requires at least one signal key and allows `undefined` values for environment-variable configuration. At runtime, at least one URL must be non-empty. A missing value disables that signal. Mastra doesn't load endpoint environment variables automatically.
207
+
208
+ The singular `endpoint` option retains its existing behavior for compatibility: OTLP signal paths are derived from the collector URL, and Zipkin uses the configured URL directly. For custom paths, use `endpoints` instead.
209
+
90
210
  ## Methods
91
211
 
92
212
  ### `exportTracingEvent`
@@ -555,6 +555,9 @@ interface AgentRunAttributes {
555
555
 
556
556
  /** When the run's model streamed its first chunk, copied from the agent's own first generation */
557
557
  completionStartTime?: Date
558
+
559
+ /** Time to first token of the model inference that streamed the run's first chunk, copied the same way */
560
+ timeToFirstTokenMs?: number
558
561
  }
559
562
  ```
560
563
 
@@ -606,6 +609,12 @@ interface ModelGenerationAttributes {
606
609
  /** Whether this was a streaming response */
607
610
  streaming?: boolean
608
611
 
612
+ /** When the generation's first inference streamed its first chunk */
613
+ completionStartTime?: Date
614
+
615
+ /** Time to first token of the model inference that streamed the generation's first chunk */
616
+ timeToFirstTokenMs?: number
617
+
609
618
  /** Reason the generation finished */
610
619
  finishReason?: string
611
620
  }
@@ -665,6 +674,9 @@ interface ModelStepAttributes {
665
674
 
666
675
  /** When the step's first inference streamed its first chunk */
667
676
  completionStartTime?: Date
677
+
678
+ /** Time to first token of the model inference that streamed the step's first chunk */
679
+ timeToFirstTokenMs?: number
668
680
  }
669
681
  ```
670
682
 
@@ -695,6 +707,9 @@ interface ModelInferenceAttributes {
695
707
  /** When the first token/chunk of the completion was received */
696
708
  completionStartTime?: Date
697
709
 
710
+ /** Milliseconds from the start of the model inference that streamed the first chunk to that chunk */
711
+ timeToFirstTokenMs?: number
712
+
698
713
  /** Result warnings */
699
714
  warnings?: Record<string, any>
700
715
 
@@ -161,7 +161,7 @@ interface ExportedSpan<TType extends SpanType> extends BaseSpan<TType> {
161
161
  /** Structured details behind stopReason, such as the limit that was hit */
162
162
  stopReasonContext?: Record<string, unknown>
163
163
 
164
- /** Milliseconds from the model call to the first token received */
164
+ /** Milliseconds from the start of the model inference that streamed the first chunk to that chunk */
165
165
  timeToFirstTokenMs?: number
166
166
 
167
167
  /** Errors in this span and all nested spans */
@@ -293,7 +293,7 @@ provider.stopPolling()
293
293
 
294
294
  Handle an incoming webhook request. Override to parse the payload and match it to subscriptions. Then emit notification signals. See [`WebhookSignalProvider`](https://mastra.ai/reference/signals/webhook-signal-provider) for a ready-to-use implementation.
295
295
 
296
- Call this method from an application-defined HTTP endpoint after verifying the webhook request.
296
+ Call this method from a route returned by [`getRoutes()`](#getroutes) or from your own HTTP endpoint, after verifying the webhook request.
297
297
 
298
298
  ```typescript
299
299
  async handleWebhook(request) {
@@ -313,6 +313,47 @@ async handleWebhook(request) {
313
313
 
314
314
  Returns: `Promise<{ status?: number; body?: unknown }>`
315
315
 
316
+ #### `getRoutes()`
317
+
318
+ Return API routes this provider needs on the Mastra server, such as webhook receivers or OAuth callbacks. Optional. When the provider's agent is registered, Mastra adds these routes to `server.apiRoutes`, so you don't add them by hand.
319
+
320
+ Routes are collected when the agent is registered. If you add an agent with `addAgent()` after the server has started, its provider routes aren't served until the server restarts. `removeAgent()` removes the agent's provider routes, unless another registered agent uses the same provider instance.
321
+
322
+ If a route with the same method and path is already registered, the existing route wins:
323
+
324
+ - A provider shared by several agents mounts its routes once.
325
+ - A route in `server.apiRoutes` or a file-system route replaces the provider route, and Mastra logs a warning.
326
+ - If two different providers declare the same route, the first one registered is mounted and Mastra logs a warning.
327
+
328
+ ```typescript
329
+ getRoutes() {
330
+ return [
331
+ registerApiRoute('/acme/webhook', {
332
+ method: 'POST',
333
+ requiresAuth: false,
334
+ handler: async c => {
335
+ // Public route: verify the sender before handling the payload
336
+ const rawBody = await c.req.text()
337
+ if (!verifyAcmeSignature(rawBody, c.req.header('x-acme-signature'))) {
338
+ return c.json({ error: 'invalid signature' }, 401)
339
+ }
340
+ const result = await this.handleWebhook({ body: JSON.parse(rawBody), headers: c.req.header() })
341
+ return c.json(result.body ?? {}, result.status ?? 200)
342
+ },
343
+ }),
344
+ ]
345
+ }
346
+ ```
347
+
348
+ Returns: `ApiRoute[]`
349
+
350
+ Provider routes follow the same rules as other [custom API routes](https://mastra.ai/docs/server/custom-api-routes). Adding a provider to an agent mounts its routes with no extra step from the user, so set access on each route deliberately:
351
+
352
+ - Routes require authentication by default when the server has auth configured.
353
+ - A route with `requiresAuth: false` is public. Verify the sender, for example with a webhook signature, before calling `handleWebhook()`.
354
+ - An authenticated route should set `requiresPermission` or `fga`. When an FGA provider audits protected routes, routes with neither are reported at startup.
355
+ - Paths can't start with the server's `apiPrefix` (`/api` by default). The server throws at startup. Use a provider-specific prefix such as `/acme/...`.
356
+
316
357
  ### Lifecycle
317
358
 
318
359
  #### `start()`
@@ -138,16 +138,6 @@ const stream = await agent.stream('message for agent')
138
138
 
139
139
  **options.onStepFinish** (`StreamTextOnStepFinishCallback<any> | never`): Callback function called after each execution step. Receives step details as a JSON string. Unavailable for structured output
140
140
 
141
- **options.telemetry** (`TelemetrySettings`): Settings for OTLP telemetry collection during streaming (not Tracing).
142
-
143
- **options.telemetry.isEnabled** (`boolean`): Enable or disable telemetry. Disabled by default while experimental.
144
-
145
- **options.telemetry.recordInputs** (`boolean`): Enable or disable input recording. Enabled by default. You might want to disable input recording to avoid recording sensitive information.
146
-
147
- **options.telemetry.recordOutputs** (`boolean`): Enable or disable output recording. Enabled by default. You might want to disable output recording to avoid recording sensitive information.
148
-
149
- **options.telemetry.functionId** (`string`): Identifier for this function. Used to group telemetry data by function.
150
-
151
141
  **options.modelSettings** (`CallSettings`): Model-specific settings like temperature, maxOutputTokens, topP, etc. These settings control how the language model generates responses.
152
142
 
153
143
  **options.modelSettings.temperature** (`number`): Controls randomness in generation (0-2). Higher values make output more random.
@@ -294,6 +284,25 @@ Unlike streams, [memory recall](https://mastra.ai/reference/memory/recall) hides
294
284
 
295
285
  Exclusions control returned data, not authorization or delivery. They aren't a security boundary. Signal options such as `ifActive`, `ifIdle`, `persist`/`discard`, and `transient` retain their delivery and persistence meanings.
296
286
 
287
+ ## Aborting a run
288
+
289
+ Pass an [`abortSignal`](#parameters) to stop a run from outside the agent:
290
+
291
+ ```ts
292
+ const controller = new AbortController()
293
+ const stream = await agent.stream('Summarize this repo', { abortSignal: controller.signal })
294
+
295
+ setTimeout(() => controller.abort(), 5_000)
296
+ ```
297
+
298
+ What abort does and doesn't do:
299
+
300
+ - **The stream carries an `abort` chunk.** When the signal fires, the run stops at its next check and `fullStream` emits an `abort` chunk. The run's status ends as canceled with an `aborted` finish reason, and `onAbort` receives the steps that completed before the abort plus the assistant text streamed so far for the in-flight step.
301
+ - **The abort is cooperative.** It takes effect at the next check inside the run. It doesn't forcibly stop tool code or an `onOutput` hook that's already executing, and side effects those started may still complete.
302
+ - **Text the user already saw is saved.** With writable memory, the assistant text streamed before the abort is persisted to the thread as an ordinary assistant message, without an error part. Canceled runs still pass through output processors, so a processor that throws can still affect that save. Output that never reaches them isn't persisted.
303
+
304
+ To abort a run you no longer hold a handle to, use the `runId` with [`durableAgent.abortRunStream(runId)`](https://mastra.ai/reference/agents/durable-agent), which ends the run the same way.
305
+
297
306
  ## Extended usage example
298
307
 
299
308
  ### Mastra Format (Default)
@@ -58,16 +58,6 @@ await agent.streamLegacy('message for agent')
58
58
 
59
59
  **options.resourceId** (`string`): \*\*Deprecated.\*\* Use memory.resource instead. Identifier for the user or resource interacting with the agent. Must be provided if threadId is provided.
60
60
 
61
- **options.telemetry** (`TelemetrySettings`): Settings for telemetry collection during streaming.
62
-
63
- **options.telemetry.isEnabled** (`boolean`): Enable or disable telemetry. Disabled by default while experimental.
64
-
65
- **options.telemetry.recordInputs** (`boolean`): Enable or disable input recording. Enabled by default. You might want to disable input recording to avoid recording sensitive information.
66
-
67
- **options.telemetry.recordOutputs** (`boolean`): Enable or disable output recording. Enabled by default. You might want to disable output recording to avoid recording sensitive information.
68
-
69
- **options.telemetry.functionId** (`string`): Identifier for this function. Used to group telemetry data by function.
70
-
71
61
  **options.temperature** (`number`): Controls randomness in the model's output. Higher values (e.g., 0.8) make the output more random, lower values (e.g., 0.2) make it more focused and deterministic.
72
62
 
73
63
  **options.threadId** (`string`): \*\*Deprecated.\*\* Use memory.thread instead. Identifier for the conversation thread. Allows for maintaining context across multiple interactions. Must be provided if resourceId is provided.
@@ -49,6 +49,20 @@ new LocalFactorySandbox() // reads MASTRACODE_LOCAL_SANDBOX_ROOT, defaults to ~/
49
49
 
50
50
  `LocalFactorySandbox` runs every session on the host machine under `join(root, sessionId)`. Without `env`, commands only see an allow-list of host variables that git and TLS need, such as `HOME`, `USER`, `SHELL` and `SSL_CERT_FILE`, plus `PATH`. App secrets stay out of commands that run in repository checkouts.
51
51
 
52
+ ### Scope env to one factory
53
+
54
+ Every provider's `env` option takes a record or a function of the session's `FactorySandboxContext`. Use the function form when one deployment hosts several factories and a credential belongs to only one of them:
55
+
56
+ ```typescript
57
+ new PlatformFactorySandbox({
58
+ env: ctx => (ctx.factoryId === PLATFORM_FACTORY_ID ? { PLATFORM_TOKEN } : {}),
59
+ })
60
+ ```
61
+
62
+ Compare `factoryId`, not `factoryName`: names can be edited and aren't unique.
63
+
64
+ Platform and Docker apply `env` only when they provision a sandbox. A sandbox that resumes keeps the environment it started with. If you remove a credential from some factories, recreate their running sandboxes so the credential doesn't stay in them.
65
+
52
66
  ## Default sandbox
53
67
 
54
68
  When you omit the `sandbox` option and Platform credentials (`MASTRA_PLATFORM_ACCESS_TOKEN` or `MASTRA_PLATFORM_SECRET_KEY`) are set, `MastraFactory` installs a sandbox itself:
@@ -146,6 +160,10 @@ Everything Factory knows about the session, passed to `create`, `template` and t
146
160
 
147
161
  **sandboxId** (`string`): The provider sandbox id persisted from a prior start. Forward it so resume reattaches the original VM.
148
162
 
163
+ **factoryId** (`string`): Id of the factory the session belongs to. Absent for sessions created before factories.
164
+
165
+ **factoryName** (`string`): Display name of the factory, for logs and readable config. Names can be edited and two factories can share one, so scope secrets by factoryId.
166
+
149
167
  **repoFullName** (`string`): owner/name of the session repository.
150
168
 
151
169
  **setupCommand** (`string`): The repository setup command, part of the template identity.
@@ -200,7 +200,7 @@ const stat = await filesystem.stat('docs/guide.md')
200
200
  ```typescript
201
201
  interface FileStat {
202
202
  name: string // File or directory name (basename only)
203
- path: string // Path relative to the filesystem basePath
203
+ path: string // Path within the filesystem namespace; relative to basePath for LocalFilesystem
204
204
  type: 'file' | 'directory'
205
205
  size: number
206
206
  createdAt: Date
@@ -147,7 +147,7 @@ await filesystem.writeFile('nested/path/file.md', content, { recursive: true })
147
147
 
148
148
  ### `appendFile(path, content)`
149
149
 
150
- Append content to an existing file.
150
+ Append content to a file, creating it if it doesn't exist.
151
151
 
152
152
  ```typescript
153
153
  await filesystem.appendFile('logs/app.log', 'New log entry\n')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/mcp-docs-server",
3
- "version": "1.3.11-alpha.0",
3
+ "version": "1.3.11-alpha.2",
4
4
  "description": "MCP server for accessing Mastra.ai documentation, changelogs, and news.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -26,7 +26,7 @@
26
26
  "@mastra/mcp-legacy": "npm:@mastra/mcp@^1.18.0",
27
27
  "local-pkg": "^1.2.1",
28
28
  "zod": "^4.6.7",
29
- "@mastra/core": "1.80.0",
29
+ "@mastra/core": "1.81.0-alpha.1",
30
30
  "@mastra/mcp": "^2.6.0"
31
31
  },
32
32
  "devDependencies": {
@@ -44,7 +44,7 @@
44
44
  "vitest": "4.1.12",
45
45
  "@internal/lint": "0.0.146",
46
46
  "@internal/types-builder": "0.0.121",
47
- "@mastra/core": "1.80.0"
47
+ "@mastra/core": "1.81.0-alpha.1"
48
48
  },
49
49
  "homepage": "https://mastra.ai",
50
50
  "repository": {