mastra-streaming
Skill2 starsChanged 29 days agoApache-2.0View on GitHub
Stream Mastra agent and workflow output: agent.stream() and its MastraModelOutput (textStream, fullStream, objectStream, text, usage, getFullOutput), chunk types and payloads, workflow run.stream() events, custom events from tools and steps through the writer API, smoothStream pacing, abort handling, timeouts, and AI SDK conversion. Use this skill whenever the user wants to show tokens as they arrive, inspect tool calls or reasoning mid-run, emit progress from a tool or workflow step, pipe an agent stream inside a workflow, cancel a running stream, or debug a WritableStream is locked error. Triggers on agent.stream, textStream, fullStream, MastraModelOutput, ChunkType, text-delta, tool-call chunk, finish chunk, run.stream, workflow-step-output, writer.write, writer.custom, data-* chunks, transient chunks, smoothStream, @mastra/core/stream, abortSignal, onChunk, consumeStream, toAISdkStream, untilIdle.
In this repository46 other files it gives its agents.
- mastra-a2a-acpSkill
- mastra-agent-approval-hitlSkill
- mastra-agentic-uiSkill
- mastra-agent-skillsSkill
- mastra-agentsSkill
- mastra-authSkill
- mastra-browserSkill
- mastra-build-playbookSkill
- mastra-channelsSkill
- mastra-classifierSkill
- mastra-cli-apiSkill
- mastra-client-sdkSkill
- mastra-datasets-experimentsSkill
- mastra-deploymentSkill
- mastra-evalsSkill
- mastra-file-based-agentsSkill
- mastra-framework-integrationSkill
- mastra-guideSkill
- mastra-harnessSkill
- mastra-knowledgeSkill
- mastra-mcpSkill
- mastra-memorySkill
- mastra-migrationsSkill
- mastra-modelsSkill
- mastra-multi-agentSkill
- mastra-observabilitySkill
- mastra-observational-memorySkill
- mastra-platformSkill
- mastra-processors-guardrailsSkill
- mastra-project-setupSkill
- mastra-ragSkill
- mastra-schedulesSkill
- mastra-semantic-recallSkill
- mastra-serverSkill
- mastra-signalsSkill
- mastra-storageSkill
- mastra-structured-outputSkill
- mastra-studio-editorSkill
- mastra-tool-integrationsSkill
- mastra-toolsSkill
- mastra-troubleshootingSkill
- mastra-vector-storesSkill
- mastra-voiceSkill
- mastra-workflowsSkill
- mastra-workflow-suspend-resumeSkill
- mastra-workspace-sandboxSkill
The file
We split this skill into the rules it gives an agent
3 rules. About 0 are common, 0 are distinctive, and 3 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 94
Every chunk has type, runId, from (AGENT, USER, SYSTEM, WORKFLOW), and usually payload.
- Very specific: line 109
Verify the API: If node_modules/@mastra/ exists, read node_modules/@mastra/core/dist/docs/ and the MastraModelOutput and ChunkType types.
- Very specific: line 155
maxTokensignored: Use modelSettings.maxOutputTokens.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Mastra Streaming
Stream agent tokens and workflow events as they happen. Agents return a MastraModelOutput with streams and promises. Workflows return a stream of lifecycle events. Tools and steps can add their own chunks with writer.
When to use
- Showing an agent's answer progressively in a CLI, server route, or UI
- Reacting to tool calls, tool results, reasoning, or step boundaries mid-run
- Streaming typed partial objects with
structuredOutput - Emitting progress or custom data from a tool's
executeor a workflow step - Streaming a workflow run, observing it later, or resuming its stream
- Smoothing choppy token output, aborting a run, or bounding its duration
When NOT to use
- Agent definition and
generate()basics (usemastra-agents) - Schema design for typed output (use
mastra-structured-output) - Route handlers and React hooks for chat UIs (use
mastra-agentic-ui) - Streaming from a frontend through
@mastra/client-js(usemastra-client-sdk) - Workflow structure, suspend, and resume semantics (use
mastra-workflowsandmastra-workflow-suspend-resume) - Approving tool calls from the stream (use
mastra-agent-approval-hitl) - Background tasks and
untilIdlecontinuations in depth (usemastra-harness) - Thread subscriptions and signals (use
mastra-signals)
Required inputs
- What is streamed: agent text, full event stream, structured object, or workflow events
- The consumer: terminal, HTTP response, AI SDK UI, or another stream
- Which events matter (text only, tool calls, reasoning, custom progress)
- Whether the run must be cancellable or time-bounded
- Whether custom chunks must persist in memory or stay transient
The framework: one output, many views
const agent = mastra.getAgentById('test-agent')
const stream = await agent.stream('Help me organize my day')
// 1. Text only
for await (const text of stream.textStream) process.stdout.write(text)
// 2. Promises that resolve when the run ends
const text = await stream.text
const usage = await stream.usage
const finishReason = await stream.finishReasonOr read every chunk:
const stream = await agent.stream('Complex task')
for await (const chunk of stream.fullStream) {
switch (chunk.type) {
case 'text-delta':
process.stdout.write(chunk.payload.text)
break
case 'tool-call':
console.log(`Calling ${chunk.payload.toolName}...`)
break
case 'tool-result':
console.log('Tool result:', chunk.payload.result)
break
case 'reasoning-delta':
console.log(`Reasoning: ${chunk.payload.text}`)
break
case 'finish':
console.log('Done:', chunk.payload.stepResult.reason, chunk.payload.output.usage)
break
case 'error':
console.error('Error:', chunk.payload.error)
break
}
}Every chunk has type, runId, from (AGENT, USER, SYSTEM, WORKFLOW), and usually payload. Pick one consumer per stream: iterate textStream or fullStream, then await promises.
Agent vs workflow streams
Agent stream() | Workflow run.stream() | |
| Returns | MastraModelOutput | WorkflowRunOutput |
| Iterate | textStream, fullStream, objectStream | the output itself or fullStream |
| Main events | text-delta, tool-call, tool-result, step-finish, finish | workflow-start, workflow-step-start, workflow-step-output, workflow-step-result, workflow-finish |
| Final values | text, object, usage, toolCalls, getFullOutput() | result, status, usage |
Workflow
- Verify the API. If
node_modules/@mastra/exists, readnode_modules/@mastra/core/dist/docs/and theMastraModelOutputandChunkTypetypes. Otherwise fetchhttps://mastra.ai/docs/guides/streaming.md,https://mastra.ai/reference/streaming/agents/stream.md, andhttps://mastra.ai/reference/streaming/ChunkType.md. Trust these over memory. - Choose the view.
textStreamfor plain text,fullStreamfor tool and step events,objectStreamfor structured output,run.stream()for workflows. - Bound the run. Set
maxStepsandmodelSettings.timeout(totalMs,stepMs,firstChunkMs) for user-facing paths. - Wire cancellation. Pass an
AbortControllersignal asabortSignaland handle theabortchunk oronAbort. - Emit custom progress from tools with
context?.writer?.write()orcontext?.writer?.custom({ type: 'data-...' }), and from steps withwriter.write(). Alwaysawaitthe call. - Handle errors with
try/catcharound consumption,onError, orconsumeStream({ onError }). - Convert for the UI with
toAISdkStream()when the frontend uses the AI SDK (seemastra-agentic-ui). - Test by logging
fullStreamonce to confirm the chunk sequence, then narrow to the chunks you handle.
Deep dive: writer API in tools and steps
import { createTool } from '@mastra/core/tools'
export const buildTool = createTool({
id: 'build',
description: 'Builds the project',
execute: async (inputData, context) => {
await context?.writer?.custom({ type: 'data-tool-progress', status: 'pending' })
await context?.writer?.custom({
type: 'data-build-log',
data: { line: 'Compiling module 3 of 12...' },
transient: true, // streamed live, not saved to memory
})
await context?.writer?.custom({ type: 'data-tool-progress', status: 'success' })
return { ok: true }
},
})writer.write(value)nests the value inside a tool or step output chunk.writer.custom({ type: 'data-...' })emits a top-level chunk that UI frameworks read directly.data-*chunks persist with message history unlesstransient: true.- In a workflow step,
writeris an argument ofexecute. Pipe an agent into it withawait stream.textStream.pipeTo(writer). Mastra aggregates the agent's usage into the workflow run.
Failure patterns
WritableStream is locked. Awriter.write()orwriter.custom()call was not awaited. Await every call.- Nothing printed, promise never settles. Nobody consumed the stream. Iterate a stream, or call
await stream.consumeStream()before awaitingtext. chunk.textis undefined. Payload fields live underchunk.payload(chunk.payload.text,chunk.payload.toolName).maxTokensignored. UsemodelSettings.maxOutputTokens.stopWhenthrows and the loop hangs.fullStreamrejects without afinishorerrorchunk. Wrap consumption intry/catch.- Abort leaves side effects. Abort is cooperative. Running tool code may finish. Make tools idempotent and check state before retrying.
- Smoothing changes
texttiming expectations.smoothStream()only affects the piped stream.result.textandonChunkkeep original timing. - Background results never arrive. Plain
stream()closes after the first turn. Usestream(..., { untilIdle: true, memory }).streamUntilIdle()is deprecated. - Using
.network()event names. They are deprecated. Map them to standard chunks (seemastra-multi-agent). - Model version mismatch error.
stream()targets V2 models. Legacy V1 models needstreamLegacy(); plan an upgrade withmastra-migrations.
Output format
A finished streaming delivery contains:
- The call site with
stream()options (maxSteps,modelSettings.timeout,abortSignal) and a consumer loop - Typed handling for each chunk type the feature depends on
- Tool or step code that awaits every
writercall, withtransient: truefor noisy chunks - An error path (
try/catch,onError, orconsumeStream({ onError })) - Evidence: a logged
fullStreamsample or a test asserting the chunk sequence
Reference files
references/api.md-stream()options,MastraModelOutputproperties and methods, chunk catalog with payloads, workflow stream methods,smoothStream().references/examples.md- Chunk router with abort and timeout, tool progress withwriter.custom, workflow streaming with an agent step, smoothed output for an AI SDK route.references/checklist.md- Streaming checklist.
Live docs
- https://mastra.ai/docs/guides/streaming
- https://mastra.ai/reference/streaming/agents/stream
- https://mastra.ai/reference/streaming/agents/MastraModelOutput
- https://mastra.ai/reference/streaming/ChunkType
- https://mastra.ai/reference/streaming/smoothStream
- https://mastra.ai/reference/streaming/workflows/stream
- https://mastra.ai/reference/streaming/workflows/observeStream
- https://mastra.ai/reference/streaming/workflows/resumeStream
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

