@mastra/mcp-docs-server 1.3.10 → 1.3.11-alpha.1

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 (88) 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/frameworks/angular.md +367 -0
  39. package/.docs/integrations/observability/langfuse.md +13 -0
  40. package/.docs/integrations/sandboxes/vercel.md +3 -1
  41. package/.docs/integrations.md +1 -0
  42. package/.docs/models/gateways/netlify.md +2 -5
  43. package/.docs/models/gateways/openrouter.md +2 -10
  44. package/.docs/models/gateways/vercel.md +1 -1
  45. package/.docs/models/index.md +1 -1
  46. package/.docs/models/providers/cortecs.md +1 -1
  47. package/.docs/models/providers/deepinfra.md +0 -1
  48. package/.docs/models/providers/edenai.md +25 -4
  49. package/.docs/models/providers/empiriolabs.md +2 -1
  50. package/.docs/models/providers/google.md +1 -4
  51. package/.docs/models/providers/inceptron.md +4 -4
  52. package/.docs/models/providers/kilo.md +10 -23
  53. package/.docs/models/providers/llmgateway-providers.md +5 -18
  54. package/.docs/models/providers/llmgateway.md +4 -3
  55. package/.docs/models/providers/melious.md +10 -10
  56. package/.docs/models/providers/mistral.md +25 -24
  57. package/.docs/models/providers/nano-gpt.md +7 -18
  58. package/.docs/models/providers/ofox.md +3 -1
  59. package/.docs/models/providers/openai.md +1 -4
  60. package/.docs/models/providers/opencode.md +0 -1
  61. package/.docs/reference/agents/channels.md +61 -1
  62. package/.docs/reference/agents/generate.md +0 -10
  63. package/.docs/reference/agents/generateLegacy.md +0 -10
  64. package/.docs/reference/agents/network.md +0 -10
  65. package/.docs/reference/browser/agent-browser.md +7 -3
  66. package/.docs/reference/browser/mastra-browser.md +34 -0
  67. package/.docs/reference/classifier/classifier.md +3 -1
  68. package/.docs/reference/cli/mastra.md +8 -0
  69. package/.docs/reference/client-js/observability.md +16 -15
  70. package/.docs/reference/configuration.md +3 -1
  71. package/.docs/reference/connect/providers.md +65 -1
  72. package/.docs/reference/core/getDeployer.md +1 -1
  73. package/.docs/reference/core/mastra-class.md +1 -1
  74. package/.docs/reference/deployer/vercel.md +24 -1
  75. package/.docs/reference/editor/mastra-editor.md +1 -1
  76. package/.docs/reference/evals/tool-call-accuracy.md +7 -4
  77. package/.docs/reference/memory/memory-class.md +77 -0
  78. package/.docs/reference/observability/tracing/advanced-queries.md +33 -16
  79. package/.docs/reference/observability/tracing/exporters/langfuse.md +11 -0
  80. package/.docs/reference/observability/tracing/exporters/otel.md +123 -3
  81. package/.docs/reference/observability/tracing/interfaces.md +15 -0
  82. package/.docs/reference/observability/tracing/spans.md +1 -1
  83. package/.docs/reference/signals/signal-provider.md +42 -1
  84. package/.docs/reference/streaming/agents/stream.md +19 -10
  85. package/.docs/reference/streaming/agents/streamLegacy.md +0 -10
  86. package/.docs/reference/workspace/filesystem.md +1 -1
  87. package/.docs/reference/workspace/local-filesystem.md +1 -1
  88. package/package.json +4 -4
@@ -4,7 +4,7 @@
4
4
 
5
5
  # Provider toolsets
6
6
 
7
- This page documents generated toolsets for 24 providers (948 tools in this version of `@mastra/connect`). It isn't an exhaustive list of providers registered in the SDK or available in the platform catalog. [`tools()`](https://mastra.ai/reference/connect/tools) exposes a provider's toolset when the project has an active connection for its provider ID.
7
+ This page documents generated toolsets for 26 providers (996 tools in this version of `@mastra/connect`). It isn't an exhaustive list of providers registered in the SDK or available in the platform catalog. [`tools()`](https://mastra.ai/reference/connect/tools) exposes a provider's toolset when the project has an active connection for its provider ID.
8
8
 
9
9
  Tool keys are stable identifiers of the form `<provider>_<action>` and are the values accepted by `allowTools` and `disallowTools`. Toolsets are versioned with the package: the exact list depends on the installed `@mastra/connect` version, and this page reflects the version it was generated from.
10
10
 
@@ -27,9 +27,11 @@ MCP providers (Attio, Canva, Clay, Neon, Render, Robinhood, and Sanity) serve th
27
27
  | ![](https://cdn.simpleicons.org/linear?viewbox=auto\&size=28) [Linear](#linear) | `linear` | 46 |
28
28
  | ![](https://app.nango.dev/images/template-logos/microsoft-powerpoint.svg) [Microsoft PowerPoint](#microsoft-powerpoint) | `microsoft-powerpoint` | 18 |
29
29
  | ![](https://cdn.simpleicons.org/microsoftteams?viewbox=auto\&size=28) [Microsoft Teams](#microsoft-teams) | `microsoft-teams` | 25 |
30
+ | ![](https://app.nango.dev/images/template-logos/microsoft-word.svg) [Microsoft Word](#microsoft-word) | `microsoft-word` | 18 |
30
31
  | ![](https://cdn.simpleicons.org/notion?viewbox=auto\&size=28) [Notion](#notion) | `notion` | 44 |
31
32
  | [OneDrive](#onedrive) | `one-drive` | 20 |
32
33
  | ![](https://svgl.app/library/openai.svg) [OpenAI](#openai) | `openai` | 26 |
34
+ | ![](https://cdn.simpleicons.org/microsoftoutlook?viewbox=auto\&size=28) [Microsoft Outlook](#microsoft-outlook) | `outlook` | 30 |
33
35
  | ![](https://cdn.simpleicons.org/posthog?viewbox=auto\&size=28) [PostHog](#posthog) | `posthog` | 67 |
34
36
  | ![](https://cdn.simpleicons.org/resend?viewbox=auto\&size=28) [Resend](#resend) | `resend` | 80 |
35
37
  | ![](https://svgl.app/library/slack.svg) [Slack](#slack) | `slack` | 52 |
@@ -719,6 +721,31 @@ Provider ID: `microsoft-teams` · 25 tools
719
721
  | `microsoft_teams_reply_to_channel_message` | Reply to a channel message thread. |
720
722
  | `microsoft_teams_update_channel` | Update mutable channel properties. |
721
723
 
724
+ ## Microsoft Word
725
+
726
+ Provider ID: `microsoft-word` · 18 tools
727
+
728
+ | Tool | Description |
729
+ | ----------------------------------------------- | ----------------------------------------------------------------------------------- |
730
+ | `microsoft_word_copy_word_document` | Copy a Word document to a (possibly different) folder, optionally renaming it. |
731
+ | `microsoft_word_create_folder` | Create a folder in a drive to organize Word documents. |
732
+ | `microsoft_word_create_sharing_link` | Create a sharing link for a Word document. |
733
+ | `microsoft_word_create_word_document` | Upload a new Word document to a drive folder |
734
+ | `microsoft_word_delete_word_document` | Delete a Word document. |
735
+ | `microsoft_word_get_site_drive` | Get the default document library (drive) for a SharePoint site. |
736
+ | `microsoft_word_get_user_drive` | Get the connected user's OneDrive, or another user's drive when userId is provided. |
737
+ | `microsoft_word_get_word_document` | Retrieve metadata for a Word document (driveItem). |
738
+ | `microsoft_word_get_word_document_as_pdf` | Download a Word document converted to PDF |
739
+ | `microsoft_word_get_word_document_content` | Download the raw .docx content of a Word document. |
740
+ | `microsoft_word_list_sites` | Search/list SharePoint sites accessible to the app |
741
+ | `microsoft_word_list_users` | List/search tenant users, to resolve a user id for personal OneDrive access. |
742
+ | `microsoft_word_list_word_document_permissions` | List sharing permissions on a Word document. |
743
+ | `microsoft_word_list_word_document_versions` | List the version history of a Word document. |
744
+ | `microsoft_word_list_word_documents` | List/search .docx files within a drive |
745
+ | `microsoft_word_move_word_document` | Move a Word document to a different folder. |
746
+ | `microsoft_word_update_word_document_content` | Replace the content of an existing Word document. |
747
+ | `microsoft_word_update_word_document_metadata` | Rename a Word document or update its description, without touching content. |
748
+
722
749
  ## Notion
723
750
 
724
751
  Provider ID: `notion` · 44 tools
@@ -830,6 +857,43 @@ Provider ID: `openai` · 26 tools
830
857
  | `openai_search_vector_store` | Search a vector store for semantically matching content chunks |
831
858
  | `openai_update_vector_store` | Update a vector store in OpenAI |
832
859
 
860
+ ## Microsoft Outlook
861
+
862
+ Provider ID: `outlook` · 30 tools
863
+
864
+ | Tool | Description |
865
+ | ------------------------------------- | ------------------------------------------------------------------------- |
866
+ | `outlook_add_event_attachment` | Attach a small file (under 3 MB) to an Outlook event. |
867
+ | `outlook_add_message_attachment` | Attach a file to a draft message. Note: 3 MB simple upload limit applies. |
868
+ | `outlook_cancel_event` | Cancel a meeting and send the cancellation notice to attendees |
869
+ | `outlook_copy_message` | Copy a message to another mail folder. |
870
+ | `outlook_create_calendar` | Create a secondary calendar in the mailbox. |
871
+ | `outlook_create_draft_message` | Create a draft email message |
872
+ | `outlook_create_event` | Create an event on a calendar. |
873
+ | `outlook_create_mail_folder` | Create a child mail folder in Outlook. |
874
+ | `outlook_delete_calendar` | Delete a secondary calendar. |
875
+ | `outlook_delete_event` | Delete an event from a calendar. |
876
+ | `outlook_delete_message` | Delete a message from the mailbox |
877
+ | `outlook_download_message_attachment` | Download the content of a file attachment on a message. |
878
+ | `outlook_get_calendar` | Retrieve a calendar by ID. |
879
+ | `outlook_get_event` | Retrieve an event by ID from the user's calendar |
880
+ | `outlook_get_message` | Retrieve a message by ID. |
881
+ | `outlook_list_calendar_events` | List events from a calendar or date window. |
882
+ | `outlook_list_calendars` | List calendars in the mailbox. |
883
+ | `outlook_list_event_attachments` | List attachments on an event. |
884
+ | `outlook_list_mail_folder_children` | List child folders under a mail folder |
885
+ | `outlook_list_mail_folders` | List top-level mail folders from the mailbox |
886
+ | `outlook_list_message_attachments` | List attachments on a message. |
887
+ | `outlook_list_messages` | List messages from a mail folder. |
888
+ | `outlook_move_message` | Move a message to another mail folder. |
889
+ | `outlook_reply_all_to_message` | Reply to all recipients on a message |
890
+ | `outlook_reply_to_message` | Reply to a message sender. |
891
+ | `outlook_send_draft_message` | Send an existing draft message. |
892
+ | `outlook_send_mail` | Send a new email message immediately |
893
+ | `outlook_update_calendar` | Update calendar properties. |
894
+ | `outlook_update_event` | Update event details in Outlook calendar. |
895
+ | `outlook_update_message` | Update a draft or mutable message fields. |
896
+
833
897
  ## PostHog
834
898
 
835
899
  Provider ID: `posthog` · 67 tools
@@ -18,7 +18,7 @@ This method doesn't accept any parameters.
18
18
 
19
19
  ## Returns
20
20
 
21
- **deployer** (`MastraDeployer | undefined`): The configured deployer instance, or undefined if no deployer has been configured.
21
+ **deployer** (`IDeployer | undefined`): The configured deployer instance, or undefined if no deployer has been configured.
22
22
 
23
23
  ## Related
24
24
 
@@ -77,7 +77,7 @@ Visit the [Configuration reference](https://mastra.ai/reference/configuration) f
77
77
 
78
78
  **environment** (`string`): Deployment environment name (e.g. production, staging, development). When set, automatically attached to all observability signals so they can be filtered by environment without passing tracingOptions.metadata.environment on each call. When unset, resolves to development for mastra dev runs, then falls back to process.env.NODE_ENV; left undefined if none are set. Per-call tracingOptions.metadata.environment always takes precedence.
79
79
 
80
- **deployer** (`MastraDeployer`): An instance of a MastraDeployer for managing deployments.
80
+ **deployer** (`IDeployer`): A deployer for managing deployments, such as VercelDeployer from @mastra/deployer-vercel.
81
81
 
82
82
  **server** (`ServerConfig`): Server configuration including port, host, timeout, API routes, middleware, CORS settings, and build options for Swagger UI, API request logging, and OpenAPI docs.
83
83
 
@@ -52,7 +52,7 @@ export const mastra = new Mastra({
52
52
  The deployer accepts the following options:
53
53
 
54
54
  - `studio?: boolean`: Deploy [Studio](https://mastra.ai/docs/studio/overview) alongside your API as static assets served from Vercel's Edge CDN. Defaults to `false`.
55
- - `maxDuration?: number`: Function execution timeout (in seconds)
55
+ - `maxDuration?: number`: Function execution timeout (in seconds). This sets Vercel's limit only; Mastra's own request timeout is configured separately, see [Request timeouts](#request-timeouts).
56
56
  - `memory?: number`: Function memory (in MB)
57
57
  - `regions?: string[]`: Regions to deploy the function (e.g. `['sfo1','iad1']`)
58
58
 
@@ -74,6 +74,29 @@ export const mastra = new Mastra({
74
74
  })
75
75
  ```
76
76
 
77
+ ## Request timeouts
78
+
79
+ Vercel's function execution time and Mastra's request timeout are enforced separately:
80
+
81
+ - **Vercel function execution time**: set by the deployer's `maxDuration` option, in seconds.
82
+ - **Mastra request timeout**: set by `server.timeout` in your `Mastra` config, in milliseconds. When unset it defaults to `180000` (180 seconds), and requests that exceed it are answered with `504 Gateway Timeout`.
83
+
84
+ `maxDuration` doesn't change `server.timeout`. A request that takes longer than 180 seconds fails even if `maxDuration` is higher, so raise both when you run long requests such as workflow runs or streaming agents:
85
+
86
+ ```typescript
87
+ import { Mastra } from '@mastra/core'
88
+ import { VercelDeployer } from '@mastra/deployer-vercel'
89
+
90
+ export const mastra = new Mastra({
91
+ deployer: new VercelDeployer({
92
+ maxDuration: 600, // seconds
93
+ }),
94
+ server: {
95
+ timeout: 600_000, // milliseconds, keep at or below maxDuration
96
+ },
97
+ })
98
+ ```
99
+
77
100
  ## Build output
78
101
 
79
102
  After running `mastra build`, the deployer generates a `.vercel/output` directory conforming to Vercel's [Build Output API (v3)](https://vercel.com/docs/build-output-api/v3). This directory contains routing configuration and serverless function bundles that Vercel deploys directly, bypassing framework detection.
@@ -40,7 +40,7 @@ export const mastra = new Mastra({
40
40
 
41
41
  **source** (`'code' | 'db'`): Where agent overrides are stored. With 'db', overrides live in the configured storage backend and Studio shows the save and publish flow. With 'code', overrides live as per-agent JSON files on disk (routed through a local FilesystemStore) and Studio shows filesystem actions. See Editor storage options for the difference. (Default: `'db'`)
42
42
 
43
- **codePath** (`string`): Directory used by the 'code' source for per-agent JSON files. Ignored when source is not 'code'. (Default: `'./mastra/editor/'`)
43
+ **codePath** (`string`): Directory used by the 'code' source for per-agent JSON files. Ignored when source is not 'code'. (Default: `'./mastra/editor'`)
44
44
 
45
45
  ### Provider interfaces
46
46
 
@@ -285,6 +285,8 @@ The `createToolCallAccuracyScorerLLM()` function from `@mastra/evals/scorers/pre
285
285
 
286
286
  **availableTools** (`Tool[]`): Tools available to the agent, for example created with createTool(). Each tool's id and description are passed to the judge as context.
287
287
 
288
+ Pass the tools available for the specific agent run in `availableTools`. If tool availability changes between runs, create a scorer with each run's tool snapshot. A global superset can cause the judge to report unavailable tools as missing and lower the score.
289
+
288
290
  ### Features
289
291
 
290
292
  The LLM-based scorer provides:
@@ -299,12 +301,13 @@ The LLM-based scorer provides:
299
301
 
300
302
  1. **Extract Tool Calls**: Identifies tools mentioned in agent output
301
303
  2. **Analyze Appropriateness**: Evaluates each tool against user request
302
- 3. **Generate Score**: Calculates score based on appropriate vs total tool calls
304
+ 3. **Generate Score**: Divides appropriate calls by the number of actual calls plus judge-reported missing tools
303
305
  4. **Generate Reasoning**: Provides human-readable explanation
304
306
 
305
307
  ## LLM-based scoring details
306
308
 
307
- - **Fractional scores**: Returns values between 0.0 and 1.0
309
+ - **Fractional scores**: Returns values between 0.0 and 1.0, rounded to two decimal places. The score counts appropriate evaluations only when they match actual calls to that tool, so extra evaluations don't increase it. The denominator counts all actual calls plus judge-reported missing tools.
310
+ - **No tool calls**: Returns 0 if the judge reports missing tools, or 1 if no tools were needed.
308
311
  - **Context-aware**: Considers user intent and appropriateness
309
312
  - **Explanatory**: Provides reasoning for scores
310
313
 
@@ -436,8 +439,8 @@ const inappropriateOutput = [
436
439
  const run = createAgentTestRun({ inputMessages, output: inappropriateOutput })
437
440
  const result = await llmScorer.run(run)
438
441
 
439
- console.log(result.score) // 0.5 - partially appropriate
440
- console.log(result.reason) // "The agent used search-tool when weather-tool would have been more appropriate for a direct weather query."
442
+ console.log(result.score) // 0 - if the judge marks search-tool inappropriate and reports weather-tool as missing
443
+ console.log(result.reason) // The judge explains why search-tool was inappropriate for this weather request.
441
444
  ```
442
445
 
443
446
  ### Evaluating clarification requests
@@ -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`