@mastra/mcp-docs-server 1.2.1-alpha.1 → 1.2.1-alpha.4

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 (35) hide show
  1. package/.docs/docs/agents/background-tasks.md +89 -14
  2. package/.docs/docs/agents/durable-agents.md +231 -0
  3. package/.docs/docs/agents/using-tools.md +52 -0
  4. package/.docs/docs/getting-started/build-with-ai.md +273 -8
  5. package/.docs/docs/server/pubsub.md +2 -2
  6. package/.docs/docs/workflows/overview.md +71 -0
  7. package/.docs/guides/build-your-ui/ai-sdk-ui.md +3 -3
  8. package/.docs/guides/concepts/streaming.md +317 -0
  9. package/.docs/guides/getting-started/quickstart.md +1 -1
  10. package/.docs/models/gateways/openrouter.md +1 -2
  11. package/.docs/models/gateways/vercel.md +2 -1
  12. package/.docs/models/index.md +1 -1
  13. package/.docs/models/providers/baseten.md +1 -1
  14. package/.docs/models/providers/huggingface.md +27 -5
  15. package/.docs/models/providers/novita-ai.md +3 -2
  16. package/.docs/models/providers/opencode.md +2 -1
  17. package/.docs/reference/agents/durable-agent.md +30 -1
  18. package/.docs/reference/agents/getDefaultOptions.md +1 -1
  19. package/.docs/reference/agents/getDefaultStreamOptions.md +1 -1
  20. package/.docs/reference/agents/inngest-agent.md +339 -0
  21. package/.docs/reference/ai-sdk/handle-workflow-stream.md +1 -1
  22. package/.docs/reference/ai-sdk/workflow-route.md +1 -1
  23. package/.docs/reference/index.md +1 -0
  24. package/.docs/reference/streaming/workflows/timeTravelStream.md +1 -1
  25. package/.docs/reference/tools/create-tool.md +1 -1
  26. package/.docs/reference/workflows/run.md +1 -1
  27. package/CHANGELOG.md +14 -0
  28. package/package.json +5 -5
  29. package/.docs/docs/build-with-ai/mcp-docs-server.md +0 -238
  30. package/.docs/docs/build-with-ai/skills.md +0 -63
  31. package/.docs/docs/streaming/background-task-streaming.md +0 -80
  32. package/.docs/docs/streaming/events.md +0 -148
  33. package/.docs/docs/streaming/overview.md +0 -136
  34. package/.docs/docs/streaming/tool-streaming.md +0 -189
  35. package/.docs/docs/streaming/workflow-streaming.md +0 -109
@@ -1,238 +0,0 @@
1
- # Mastra docs server
2
-
3
- The `@mastra/mcp-docs-server` package provides direct access to Mastra’s full documentation via the [Model Context Protocol (MCP)](https://modelcontextprotocol.io/docs/getting-started/intro). It works with Cursor, Windsurf, Cline, Claude Code, VS Code, Codex or any tool that supports MCP.
4
-
5
- These tools are designed to help agents retrieve precise, task-specific information — whether you're adding a feature to an agent, scaffolding a new project, or exploring how something works.
6
-
7
- In this guide you'll learn how to add Mastra's MCP server to your AI tooling.
8
-
9
- [YouTube video player](https://www.youtube-nocookie.com/embed/vciV57lF0og)
10
-
11
- ## Installation
12
-
13
- ### create-mastra
14
-
15
- During the interactive [create-mastra](https://mastra.ai/reference/cli/create-mastra) wizard, choose one of your tools in the MCP step.
16
-
17
- ### Manual setup
18
-
19
- If there are no specific instructions for your tool below, you may be able to add the MCP server with this common JSON configuration anyways.
20
-
21
- ```json
22
- {
23
- "mcpServers": {
24
- "mastra": {
25
- "type": "stdio",
26
- "command": "npx",
27
- "args": ["-y", "@mastra/mcp-docs-server@latest"]
28
- }
29
- }
30
- }
31
- ```
32
-
33
- ### Claude Code CLI
34
-
35
- Install using the terminal command:
36
-
37
- ```bash
38
- claude mcp add --scope project mastra -- npx -y @mastra/mcp-docs-server@latest
39
- ```
40
-
41
- This creates a project-scoped `.mcp.json` file if one doesn't already exist. You can use the same command when using Claude Code as a [Visual Studio Code extension](https://code.claude.com/docs/en/vs-code#connect-to-external-tools-with-mcp).
42
-
43
- [More info on using MCP servers with Claude Code](https://docs.claude.com/en/docs/claude-code/mcp)
44
-
45
- ### OpenAI Codex CLI
46
-
47
- 1. Register it from the terminal:
48
-
49
- ```bash
50
- codex mcp add mastra-docs -- npx -y @mastra/mcp-docs-server@latest
51
- ```
52
-
53
- 2. Run `codex mcp list` to confirm the server shows as `enabled`.
54
-
55
- [More info on using MCP servers with OpenAI Codex](https://developers.openai.com/codex/mcp)
56
-
57
- ### Cursor
58
-
59
- Install by selecting the button below:
60
-
61
- [![Install MCP Server](https://cursor.com/deeplink/mcp-install-light.svg)](cursor://anysphere.cursor-deeplink/mcp/install?name=mastra\&config=eyJjb21tYW5kIjoibnB4IC15IEBtYXN0cmEvbWNwLWRvY3Mtc2VydmVyIn0%3D)
62
-
63
- If you followed the automatic installation, you'll see a popup when you open cursor in the bottom left corner to prompt you to enable the Mastra Docs MCP Server.
64
-
65
- ![Popup inside Cursor showing: \"New MCP server detected: mastra\". The user can \"Skip\" or \"Enable\" it as an action.](/assets/images/enable-mastra-docs-cursor-cd5872abdc36c0e10951a59a47f25e12.png)
66
-
67
- [More info on using MCP servers with Cursor](https://cursor.com/de/docs/context/mcp)
68
-
69
- ### Antigravity
70
-
71
- Google Antigravity is an agent-first development platform that supports MCP servers for accessing external documentation, APIs, and project context.
72
-
73
- 1. Open your Antigravity MCP configuration file:
74
-
75
- - Click on **Agent session** and select the **“…” dropdown** at the top of the editor’s side panel, then select **MCP Servers** to access the **MCP Store**.
76
- - You can access it through the MCP Store interface in Antigravity
77
-
78
- ![The Antigravity MCP store. At the top is a search bar and below a list of available MCP servers. On the very top right is a dropdown menu.](/assets/images/antigravity_mcp_server-689ea495d9c7139cc431f1f1b9827f9b.png)
79
-
80
- 2. To add a custom MCP server, select **Manage MCP Servers** at the top of the MCP Store and select **View raw config** in the main tab.
81
-
82
- ![The Antigravity MCP store showing the Manage MCP Servers option and the View raw config button.](/assets/images/antigravity_managed_mcp-b661e8c04b3219000f8d842e5eb26a1a.png)
83
-
84
- 3. Add the Mastra MCP server configuration:
85
-
86
- ```json
87
- {
88
- "mcpServers": {
89
- "mastra-docs": {
90
- "command": "npx",
91
- "args": ["-y", "@mastra/mcp-docs-server"]
92
- }
93
- }
94
- }
95
- ```
96
-
97
- 4. Save the configuration and restart Antigravity
98
-
99
- ![The UI shows that the MCP server is enabled. You can also toggle individual tools.](/assets/images/antigravity_final_interface_mcp-7fa132dbe76cdee9f61136a26d6e6615.png)
100
-
101
- Once configured, the Mastra MCP server exposes the following to Antigravity agents:
102
-
103
- - Indexed documentation and API schemas for Mastra, enabling programmatic retrieval of relevant context during code generation
104
- - Access to example code snippets and usage patterns stored in Mastra Docs
105
- - Structured data for error handling and debugging references in the editor
106
- - Metadata about current Mastra project patterns for code suggestion and completion
107
-
108
- The MCP server will appear in Antigravity's MCP Store, where you can manage its connection status and authentication if needed.
109
-
110
- [More info on using MCP servers with Antigravity](https://antigravity.google)
111
-
112
- ### Visual Studio Code
113
-
114
- 1. Create a `.vscode/mcp.json` file in your workspace
115
-
116
- 2. Insert the following configuration:
117
-
118
- ```json
119
- {
120
- "servers": {
121
- "mastra": {
122
- "type": "stdio",
123
- "command": "npx",
124
- "args": ["-y", "@mastra/mcp-docs-server@latest"]
125
- }
126
- }
127
- }
128
- ```
129
-
130
- Once you installed the MCP server, you can use it like so:
131
-
132
- 1. Open VSCode settings.
133
-
134
- 2. Navigate to MCP settings.
135
-
136
- 3. Click "enable" on the Chat > MCP option.
137
-
138
- ![Entry in VSCode\'s settings page. The option is called \"Chat \> MCP: Enabled (Preview)\". The description says: \"Enables integration with Model Context Protocol servers to provide additional tools and functionality.\"](/assets/images/vscode-mcp-setting-8d1eb4f3df1e33606503f8c5e937e9e3.png)
139
-
140
- MCP only works in Agent mode in VSCode. Once you are in agent mode, open the `mcp.json` file and select the "start" button. Note that the "start" button will only appear if the `.vscode` folder containing `mcp.json` is in your workspace root, or the highest level of the in-editor file explorer.
141
-
142
- ![A screenshot of the mcp.json file showing the start button in the editor](/assets/images/vscode-start-mcp-26480d86080c4907cb497a325de106a4.png)
143
-
144
- After starting the MCP server, select the tools button in the Copilot pane to see available tools.
145
-
146
- ![Tools page of VSCode to see available tools](/assets/images/vscode-mcp-running-d92d6ed234d1148093dc804b0ead3515.png)
147
-
148
- [More info on using MCP servers with Visual Studio Code](https://code.visualstudio.com/docs/copilot/customization/mcp-servers)
149
-
150
- ### Windsurf
151
-
152
- 1. Open `~/.codeium/windsurf/mcp_config.json` in your editor
153
-
154
- 2. Insert the following configuration:
155
-
156
- ```json
157
- {
158
- "mcpServers": {
159
- "mastra": {
160
- "command": "npx",
161
- "args": ["-y", "@mastra/mcp-docs-server@latest"]
162
- }
163
- }
164
- }
165
- ```
166
-
167
- 3. Save the configuration and restart Windsurf
168
-
169
- [More info on using MCP servers with Windsurf](https://docs.windsurf.com/windsurf/cascade/mcp#mcp-config-json)
170
-
171
- ### OpenCode
172
-
173
- You can define MCP servers in your [OpenCode configuration](https://opencode.ai/docs/config/) under `mcp`. Create an `opencode.jsonc` file in your project root with the following content:
174
-
175
- ```json
176
- {
177
- "$schema": "https://opencode.ai/config.json",
178
- "mcp": {
179
- "mastra": {
180
- "type": "local",
181
- "command": ["npx", "-y", "@mastra/mcp-docs-server@latest"],
182
- "enabled": true
183
- }
184
- }
185
- }
186
- ```
187
-
188
- [More info on using MCP servers with OpenCode](https://opencode.ai/docs/mcp-servers)
189
-
190
- ### Zed
191
-
192
- 1. Open `~/.config/zed/settings.json` in your editor
193
- 2. Insert the following configuration:
194
-
195
- ```json
196
- {
197
- "context_servers": {
198
- "Mastra": {
199
- "command": "npx",
200
- "args": ["-y", "@mastra/mcp-docs-server@latest"]
201
- }
202
- }
203
- }
204
- ```
205
-
206
- ## Usage
207
-
208
- Once configured, you can ask your AI tool questions about Mastra or instruct it to take actions. For these steps, it'll take the up-to-date information from Mastra's MCP server.
209
-
210
- **Add features:**
211
-
212
- - "Add evals to my agent and write tests"
213
- - "Write me a workflow that does the following `[task]`"
214
- - "Make a new tool that allows my agent to access `[3rd party API]`"
215
-
216
- **Ask about integrations:**
217
-
218
- - "Does Mastra work with the AI SDK? How can I use it in my `[React/Svelte/etc]` project?"
219
- - "Does Mastra support `[provider]` speech and voice APIs? Show me an example in my code of how I can use it."
220
-
221
- **Debug or update existing code:**
222
-
223
- - "I'm running into a bug with agent memory, have there been any related changes or bug fixes recently?"
224
- - "How does working memory behave in Mastra and how can I use it to do `[task]`? It doesn't seem to work the way I expect."
225
- - "I saw there are new workflow features, explain them to me and then update `[workflow]` to use them."
226
-
227
- ### Troubleshooting
228
-
229
- 1. **Server Not Starting**
230
-
231
- - Ensure [npx](https://docs.npmjs.com/cli/v11/commands/npx) is installed and working.
232
- - Check for conflicting MCP servers.
233
- - Verify your configuration file syntax.
234
-
235
- 2. **Tool Calls Failing**
236
-
237
- - Restart the MCP server and/or your IDE.
238
- - Update to the latest version of your IDE.
@@ -1,63 +0,0 @@
1
- # Mastra skills
2
-
3
- Mastra Skills are folders of instructions, scripts, and resources that agents can discover and use to gain Mastra knowledge. They contain setup instructions, best practices, and methods to fetch up-to-date information from Mastra's documentation.
4
-
5
- ## Installation
6
-
7
- To install all available Mastra skills, run the following command:
8
-
9
- **npm**:
10
-
11
- ```bash
12
- npx skills add mastra-ai/skills
13
- ```
14
-
15
- **pnpm**:
16
-
17
- ```bash
18
- pnpm dlx skills add mastra-ai/skills
19
- ```
20
-
21
- **Yarn**:
22
-
23
- ```bash
24
- yarn dlx skills add mastra-ai/skills
25
- ```
26
-
27
- **Bun**:
28
-
29
- ```bash
30
- bun x skills add mastra-ai/skills
31
- ```
32
-
33
- Mastra skills work with any coding agent that supports the [Skills standard](https://agentskills.io/), including Claude Code, Cursor, Codex, OpenCode, and others.
34
-
35
- They're also available on [GitHub](https://github.com/mastra-ai/skills).
36
-
37
- ## Update skill
38
-
39
- To update to the latest version of the Mastra skill, run:
40
-
41
- **npm**:
42
-
43
- ```bash
44
- npx skills update mastra
45
- ```
46
-
47
- **pnpm**:
48
-
49
- ```bash
50
- pnpm dlx skills update mastra
51
- ```
52
-
53
- **Yarn**:
54
-
55
- ```bash
56
- yarn dlx skills update mastra
57
- ```
58
-
59
- **Bun**:
60
-
61
- ```bash
62
- bun x skills update mastra
63
- ```
@@ -1,80 +0,0 @@
1
- # Background task streaming
2
-
3
- **Added in:** `@mastra/core@1.29.0`
4
-
5
- `mastra.backgroundTaskManager.stream()` returns a `ReadableStream` of [background task](https://mastra.ai/docs/agents/background-tasks) lifecycle events. Use it to monitor running tasks across the system, for example to drive a status dashboard, surface progress in your own UI, or pipe events into an SSE response.
6
-
7
- The stream emits the same chunk types that appear inside `Agent.streamUntilIdle()` (`background-task-running`, `background-task-output`, `background-task-completed`, `background-task-failed`, `background-task-cancelled`). See [background task chunks](https://mastra.ai/reference/streaming/ChunkType) for the full payload shapes.
8
-
9
- > **Note:** Background tasks must be [enabled on the Mastra instance](https://mastra.ai/reference/configuration) before `backgroundTaskManager` is available. When disabled, `mastra.backgroundTaskManager` is `undefined`.
10
-
11
- ## Subscribe to all task events
12
-
13
- Calling `stream()` with no filter returns a stream of every task event in the system. On connection, the stream emits a snapshot of all currently running tasks, then forwards live events as they happen.
14
-
15
- ```typescript
16
- const bgManager = mastra.backgroundTaskManager
17
- if (!bgManager) throw new Error('Background tasks are not enabled')
18
-
19
- const controller = new AbortController()
20
- const stream = bgManager.stream({ abortSignal: controller.signal })
21
-
22
- for await (const chunk of stream) {
23
- switch (chunk.type) {
24
- case 'background-task-running':
25
- console.log('started', chunk.payload.taskId, chunk.payload.toolName)
26
- break
27
- case 'background-task-completed':
28
- console.log('done', chunk.payload.taskId, chunk.payload.result)
29
- break
30
- case 'background-task-failed':
31
- console.error('failed', chunk.payload.taskId, chunk.payload.error)
32
- break
33
- }
34
- }
35
- ```
36
-
37
- The stream stays open until the caller's `AbortSignal` fires. Always pass an `abortSignal` so you can disconnect cleanly.
38
-
39
- ## Filter the stream
40
-
41
- Pass any combination of filter options to narrow the events you receive. Filters apply to both the initial snapshot and the live event subscription.
42
-
43
- ```typescript
44
- const stream = bgManager.stream({
45
- agentId: 'researcher',
46
- threadId: 't1',
47
- resourceId: 'u1',
48
- abortSignal: controller.signal,
49
- })
50
- ```
51
-
52
- | Filter | Description |
53
- | ------------- | --------------------------------------------------- |
54
- | `agentId` | Only events from tasks dispatched by this agent |
55
- | `runId` | Only events from this specific agent run |
56
- | `threadId` | Only events from tasks scoped to this memory thread |
57
- | `resourceId` | Only events from tasks scoped to this resource |
58
- | `taskId` | Only events for a single task |
59
- | `abortSignal` | Closes the stream when the signal aborts |
60
-
61
- ## Look up task state directly
62
-
63
- For one-off lookups instead of a live stream, use `getTask` and `listTasks`:
64
-
65
- ```typescript
66
- const task = await mastra.backgroundTaskManager?.getTask(taskId)
67
- const { tasks, total } = await mastra.backgroundTaskManager?.listTasks({
68
- status: 'running',
69
- agentId: 'researcher',
70
- })
71
- ```
72
-
73
- These read from storage rather than the pubsub stream, so they're suitable for paginated lists and detail views.
74
-
75
- ## Related
76
-
77
- - [Background tasks](https://mastra.ai/docs/agents/background-tasks)
78
- - [`Agent.streamUntilIdle()` reference](https://mastra.ai/reference/streaming/agents/streamUntilIdle)
79
- - [Background task chunks](https://mastra.ai/reference/streaming/ChunkType)
80
- - [backgroundTasks configuration reference](https://mastra.ai/reference/configuration)
@@ -1,148 +0,0 @@
1
- # Streaming events
2
-
3
- Streaming from agents or workflows provides real-time visibility into either the LLM’s output or the status of a workflow run. This feedback can be passed directly to the user, or used within applications to handle workflow status more effectively, creating a smoother and more responsive experience.
4
-
5
- Events emitted from agents or workflows represent different stages of generation and execution, such as when a run starts, when text is produced, or when a tool is invoked.
6
-
7
- ## Event types
8
-
9
- Below is a complete list of events emitted from `.stream()`. Depending on whether you’re streaming from an **agent** or a **workflow**, only a subset of these events will occur:
10
-
11
- - **start**: Marks the beginning of an agent or workflow run.
12
- - **step-start**: Indicates a workflow step has begun execution.
13
- - **text-delta**: Incremental text chunks as they're generated by the LLM.
14
- - **tool-call**: When the agent decides to use a tool, including the tool name and arguments.
15
- - **tool-result**: The result returned from tool execution.
16
- - **step-finish**: Confirms that a specific step has fully finalized, and may include metadata like the finish reason for that step.
17
- - **finish**: When the agent or workflow completes, including usage statistics.
18
-
19
- ## Network event types
20
-
21
- When using `agent.network()` for multi-agent collaboration, additional event types are emitted to track the orchestration flow:
22
-
23
- - **routing-agent-start**: The routing agent begins analyzing the task to decide which primitive (agent/workflow/tool) to delegate to.
24
- - **routing-agent-text-delta**: Incremental text as the routing agent processes the response from the selected primitive.
25
- - **routing-agent-end**: The routing agent completes its selection, including the selected primitive and reason for selection.
26
- - **agent-execution-start**: A delegated agent begins execution.
27
- - **agent-execution-end**: A delegated agent completes execution.
28
- - **agent-execution-event-\***: Events from the delegated agent's execution (e.g., `agent-execution-event-text-delta`).
29
- - **workflow-execution-start**: A delegated workflow begins execution.
30
- - **workflow-execution-end**: A delegated workflow completes execution.
31
- - **workflow-execution-event-\***: Events from the delegated workflow's execution.
32
- - **tool-execution-start**: A delegated tool begins execution.
33
- - **tool-execution-end**: A delegated tool completes execution.
34
- - **network-execution-event-step-finish**: A network iteration step completes.
35
- - **network-execution-event-finish**: The entire network execution completes.
36
-
37
- ## Inspecting agent streams
38
-
39
- Iterate over the `stream` with a `for await` loop to inspect all emitted event chunks.
40
-
41
- ```typescript
42
- const testAgent = mastra.getAgent('testAgent')
43
-
44
- const stream = await testAgent.stream([{ role: 'user', content: 'Help me organize my day' }])
45
-
46
- for await (const chunk of stream) {
47
- console.log(chunk)
48
- }
49
- ```
50
-
51
- > **Info:** Visit [Agent.stream()](https://mastra.ai/reference/streaming/agents/stream) for more information.
52
-
53
- ### Example agent output
54
-
55
- Below is an example of events that may be emitted. Each event always includes a `type` and can include additional fields like `from` and `payload`.
56
-
57
- ```typescript
58
- {
59
- type: 'start',
60
- from: 'AGENT',
61
- // ..
62
- }
63
- {
64
- type: 'step-start',
65
- from: 'AGENT',
66
- payload: {
67
- messageId: 'msg-cdUrkirvXw8A6oE4t5lzDuxi',
68
- // ...
69
- }
70
- }
71
- {
72
- type: 'tool-call',
73
- from: 'AGENT',
74
- payload: {
75
- toolCallId: 'call_jbhi3s1qvR6Aqt9axCfTBMsA',
76
- toolName: 'testTool'
77
- // ..
78
- }
79
- }
80
- ```
81
-
82
- ## Inspecting workflow streams
83
-
84
- Iterate over the `stream` with a `for await` loop to inspect all emitted event chunks.
85
-
86
- ```typescript
87
- const testWorkflow = mastra.getWorkflow('testWorkflow')
88
-
89
- const run = await testWorkflow.createRun()
90
-
91
- const stream = await run.stream({
92
- inputData: {
93
- value: 'initial data',
94
- },
95
- })
96
-
97
- for await (const chunk of stream) {
98
- console.log(chunk)
99
- }
100
- ```
101
-
102
- ### Example workflow output
103
-
104
- Below is an example of events that may be emitted. Each event always includes a `type` and can include additional fields like `from` and `payload`.
105
-
106
- ```typescript
107
- {
108
- type: 'workflow-start',
109
- runId: '221333ed-d9ee-4737-922b-4ab4d9de73e6',
110
- from: 'WORKFLOW',
111
- // ...
112
- }
113
- {
114
- type: 'workflow-step-start',
115
- runId: '221333ed-d9ee-4737-922b-4ab4d9de73e6',
116
- from: 'WORKFLOW',
117
- payload: {
118
- stepName: 'step-1',
119
- args: { value: 'initial data' },
120
- stepCallId: '9e8c5217-490b-4fe7-8c31-6e2353a3fc98',
121
- startedAt: 1755269732792,
122
- status: 'running'
123
- }
124
- }
125
- ```
126
-
127
- ### Foreach progress events
128
-
129
- When a workflow uses `.foreach()`, each iteration emits a `workflow-step-progress` event. You can use these to track real-time progress:
130
-
131
- ```typescript
132
- for await (const chunk of stream) {
133
- if (chunk.type === 'workflow-step-progress') {
134
- console.log(
135
- `${chunk.payload.id}: ${chunk.payload.completedCount}/${chunk.payload.totalCount} — ${chunk.payload.iterationStatus}`,
136
- )
137
- }
138
- }
139
- ```
140
-
141
- Each progress event includes:
142
-
143
- - **`id`**: The step ID of the foreach step
144
- - **`completedCount`**: Number of iterations completed so far
145
- - **`totalCount`**: Total number of iterations
146
- - **`currentIndex`**: Index of the iteration that completed
147
- - **`iterationStatus`**: Status of the iteration (`success`, `failed`, or `suspended`)
148
- - **`iterationOutput`**: Output of the iteration (when successful)
@@ -1,136 +0,0 @@
1
- # Streaming overview
2
-
3
- Mastra supports real-time, incremental responses from agents and workflows, allowing users to see output as it’s generated instead of waiting for completion. This is useful for chat, long-form content, multi-step workflows, or any scenario where immediate feedback matters.
4
-
5
- ## Getting started
6
-
7
- Mastra's streaming API adapts based on your model version:
8
-
9
- - **`.stream()`**: For V2 models, supports **AI SDK v5** and later (`LanguageModelV2`).
10
- - **`.streamLegacy()`**: For V1 models, supports **AI SDK v4** (`LanguageModelV1`).
11
-
12
- ## Streaming with agents
13
-
14
- You can pass a single string for basic prompts, an array of strings when providing multiple pieces of context, or an array of message objects with `role` and `content` for precise control over roles and conversational flows.
15
-
16
- ### Using `Agent.stream()`
17
-
18
- A `textStream` breaks the response into chunks as it's generated, allowing output to stream progressively instead of arriving all at once. Iterate over the `textStream` using a `for await` loop to inspect each stream chunk.
19
-
20
- ```typescript
21
- const testAgent = mastra.getAgent('testAgent')
22
-
23
- const stream = await testAgent.stream([{ role: 'user', content: 'Help me organize my day' }])
24
-
25
- for await (const chunk of stream.textStream) {
26
- process.stdout.write(chunk)
27
- }
28
- ```
29
-
30
- > **Info:** Visit [Agent.stream()](https://mastra.ai/reference/streaming/agents/stream) for more information.
31
-
32
- > **Tip:** For agents that dispatch [background tasks](https://mastra.ai/docs/agents/background-tasks), use [`Agent.streamUntilIdle()`](https://mastra.ai/reference/streaming/agents/streamUntilIdle) to keep the stream open until those tasks complete and the agent has had a chance to respond to their results.
33
-
34
- ### Output from `Agent.stream()`
35
-
36
- The output streams the generated response from the agent.
37
-
38
- ```text
39
- Of course!
40
- To help you organize your day effectively, I need a bit more information.
41
- Here are some questions to consider:
42
- ...
43
- ```
44
-
45
- ### Agent stream properties
46
-
47
- An agent stream provides access to various response properties:
48
-
49
- - **`stream.textStream`**: A readable stream that emits text chunks.
50
- - **`stream.text`**: Promise that resolves to the full text response.
51
- - **`stream.finishReason`**: The reason the agent stopped streaming.
52
- - **`stream.usage`**: Token usage information.
53
-
54
- ### AI SDK v5+ Compatibility
55
-
56
- AI SDK v5 (and later) uses `LanguageModelV2` for the model providers. If you are getting an error that you are using an AI SDK v4 model you will need to upgrade your model package to the next major version.
57
-
58
- For integration with AI SDK v5+, use the `toAISdkV5Stream()` utility from `@mastra/ai-sdk` to convert Mastra streams to AI SDK-compatible format:
59
-
60
- ```typescript
61
- import { toAISdkV5Stream } from '@mastra/ai-sdk'
62
-
63
- const testAgent = mastra.getAgent('testAgent')
64
-
65
- const stream = await testAgent.stream([{ role: 'user', content: 'Help me organize my day' }])
66
-
67
- // Convert to AI SDK v5+ compatible stream
68
- const aiSDKStream = toAISdkV5Stream(stream, { from: 'agent' })
69
- ```
70
-
71
- For converting messages to AI SDK v5+ format, use the `toAISdkV5Messages()` utility from `@mastra/ai-sdk/ui`:
72
-
73
- ```typescript
74
- import { toAISdkV5Messages } from '@mastra/ai-sdk/ui'
75
-
76
- const messages = [{ role: 'user', content: 'Hello' }]
77
- const aiSDKMessages = toAISdkV5Messages(messages)
78
- ```
79
-
80
- ## Streaming with workflows
81
-
82
- Streaming from a workflow returns a sequence of structured events describing the run lifecycle, rather than incremental text chunks. This event-based format makes it possible to track and respond to workflow progress in real time once a run is created using `.createRun()`.
83
-
84
- ### Using `Run.stream()`
85
-
86
- The `stream()` method returns a `ReadableStream` of events directly.
87
-
88
- ```typescript
89
- const run = await testWorkflow.createRun()
90
-
91
- const stream = await run.stream({
92
- inputData: {
93
- value: 'initial data',
94
- },
95
- })
96
-
97
- for await (const chunk of stream) {
98
- console.log(chunk)
99
- }
100
- ```
101
-
102
- > **Info:** Visit [Run.stream()](https://mastra.ai/reference/streaming/workflows/stream) for more information.
103
-
104
- ### Output from `Run.stream()`
105
-
106
- The event structure includes `runId` and `from` at the top level, making it easier to identify and track workflow runs without digging into the payload.
107
-
108
- ```typescript
109
- {
110
- type: 'workflow-start',
111
- runId: '1eeaf01a-d2bf-4e3f-8d1b-027795ccd3df',
112
- from: 'WORKFLOW',
113
- payload: {
114
- stepName: 'step-1',
115
- args: { value: 'initial data' },
116
- stepCallId: '8e15e618-be0e-4215-a5d6-08e58c152068',
117
- startedAt: 1755121710066,
118
- status: 'running'
119
- }
120
- }
121
- ```
122
-
123
- ### Workflow stream properties
124
-
125
- A workflow stream provides access to various response properties:
126
-
127
- - **`stream.status`**: The status of the workflow run.
128
- - **`stream.result`**: The result of the workflow run.
129
- - **`stream.usage`**: The total token usage of the workflow run.
130
-
131
- ## Related
132
-
133
- - [Streaming events](https://mastra.ai/docs/streaming/events)
134
- - [Background tasks](https://mastra.ai/docs/agents/background-tasks)
135
- - [Using Agents](https://mastra.ai/docs/agents/overview)
136
- - [Workflows overview](https://mastra.ai/docs/workflows/overview)