Mastra: two tools for two kinds of problem
Mastra is a TypeScript framework for building applications with language models, and it offers two tools that are best not confused. The agent is a loop in which the model decides which tools to call and when to stop. The workflow is a graph of steps that you decide, with typed data between one step and the next. The official documentation gives the rule in one line: the agent for open-ended tasks whose steps you do not know, the workflow for processes defined in advance, with a precise order.
A workshop example. "Help me understand why my order is late" is an open-ended task: maybe you need to look at the order status, maybe at the courier, maybe ask the customer for a detail. "When a return arrives, check the code, check the 14-day window, then ask an operator for approval" is a process: you know the steps, and you want no model to skip them. The first is an agent, the second a workflow, and often a workflow contains a step that calls an agent.
A note on time, because this series describes products that change. On 13 November 2026 the npm registry lists @mastra/core at version 1.83.0, last published the day before; the package requires Node 22.13 or later. Many tutorials use names that no longer exist, or never existed: @mastra/sdk answers 404 on the registry, and import { Agent } from 'mastra' is not the current import, which is @mastra/core/agent. Before copying an example, check that the names resolve.
Installing Mastra: a few packages and a version constraint
npm install @mastra/core zod typescript @types/node
# for memory (article, section on the agent):
npm install @mastra/memory @mastra/libsql
The first line brings in the framework, zod for schemas, TypeScript and the Node types. I ran it in a folder outside the repository: it succeeded and npm reported no vulnerabilities. The command recommended by the project's README to get started is instead npm create mastra@latest, which creates a complete project structure. The second line is tricky: @mastra/memory 1.41.1 declares @mastra/core >=1.83.0 <2.0.0 as a peer dependency, so the Mastra packages must be upgraded together and not one at a time.
To run the listings without compiling, Node is enough: the documentation notes that Node 22.18 and later run TypeScript files directly, provided you write the extension in local imports. I used Node 24.11 with node file.ts. In a real project you will use the project's bundler; here what matters is that every listing was run as it stands.
Tools: the schema is the first security check
A tool is a function the model can call. In Mastra you create it with createTool and four elements listed as required: id, description, inputSchema and execute. The documentation warns that a plain function or an object not passed through createTool is not executed, without any error. The input schema acts as the first wall: the model proposes the parameters, but it is the schema that decides whether they are admissible.
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
const findOrder = createTool({
id: 'find-order',
description: 'Returns the status of an order given its code',
inputSchema: z.object({ code: z.string().regex(/^ORD-\d{4}$/) }),
outputSchema: z.object({ code: z.string(), status: z.string() }),
execute: async ({ code }) => ({ code, status: 'shipped' }),
})
// The second argument is supplied by the Mastra runtime; here, outside an agent, we pass an empty context.
const good = await findOrder.execute!({ code: 'ORD-1234' }, {} as any)
console.log('valid input :', JSON.stringify(good))
const bad: any = await findOrder.execute!({ code: 'xyz' } as any, {} as any)
console.log('invalid input:', bad.error, '|', bad.message.split('\n')[1])
// Output:
// valid input : {"code":"ORD-1234","status":"shipped"}
// invalid input: true | - code: Invalid string: must match pattern /^ORD-\d{4}$/
The line that matters is the inputSchema: the code must match the expression ^ORD-\d{4}$, so it admits "ORD-1234" and rejects "xyz". execute already receives the validated input as its first argument; the second, the execution context, is supplied by the runtime, which is why here I pass an empty object. In the output you see the difference that matters: with an invalid input the tool does not throw an exception, it returns an object with error: true and a message that names the field and the rule that was violated.
The reason for the behavior is clear when you look at who reads that message: it is the model, which can correct the call and try again. For an invented order code there is no side effect; if the schema had been a bare z.string(), the call would have reached the database with any text at all. The cost is that every tool now has a contract to maintain. When not to add it: for trivial internal functions that no model calls, one more schema is only maintenance.
A well-made tool has, in the order in which it is best to write them:
- a stable
id, because it appears in traces and logs; - a short
descriptionthat says what it does and when to use it, because it is what the model reads to choose it; - a strict
inputSchema: formats, ranges, allowed values; - an
outputSchemathat declares what you return, so the recipient does not have to guess; - an
executewith no hidden side effects, or with the effect declared in the description.
The order is not random: the description guides the choice, the input schema filters, the output schema guarantees the shape of what comes back. Safety is decided on the input schema and on execute: if a tool can write (refund, delete, send), the description must say so and the flow must provide for an approval, which in Mastra is a suspended workflow step, as the comparison article shows.
Workflow: you decide the steps
A workflow is built with createStep for each step and createWorkflow to compose them. Each step declares an input and an output schema, and the engine checks that the data leaving one step is what the next expects. The listing below is deterministic and uses no model: two steps, one that normalizes a text and one that counts the words.
import { createStep, createWorkflow } from '@mastra/core/workflows'
import { z } from 'zod'
const normalize = createStep({
id: 'normalize',
inputSchema: z.object({ text: z.string() }),
outputSchema: z.object({ words: z.array(z.string()) }),
execute: async ({ inputData }) => ({
words: inputData.text.toLowerCase().split(/\s+/).filter(Boolean),
}),
})
const count = createStep({
id: 'count',
inputSchema: z.object({ words: z.array(z.string()) }),
outputSchema: z.object({ total: z.number(), unique: z.number() }),
execute: async ({ inputData }) => ({
total: inputData.words.length,
unique: new Set(inputData.words).size,
}),
})
const countWords = createWorkflow({
id: 'count-words',
inputSchema: z.object({ text: z.string() }),
outputSchema: z.object({ total: z.number(), unique: z.number() }),
})
.then(normalize)
.then(count)
.commit()
const run = await countWords.createRun()
const outcome = await run.start({ inputData: { text: 'Hello hello world' } })
if (outcome.status === 'success') console.log('outcome:', outcome.status, JSON.stringify(outcome.result))
try {
const other = await countWords.createRun()
await other.start({ inputData: { text: 42 as any } })
} catch (e: any) {
console.log('wrong input:', e.id, '|', e.message.split('\n')[1].trim())
}
// Output:
// outcome: success {"total":3,"unique":2}
// wrong input: WORKFLOW_SCHEMA_VALIDATION_FAILED | - text: Invalid input: expected string, received number
.then(normalize).then(count) declares the order, and .commit() closes the definition: without it, the workflow cannot be run. createRun() creates an execution and start launches it with the input data. In the output the first case comes back with status success and the expected result, three words of which two are unique. The second produces no result: it sends a number where the schema wants a string, and the engine throws a MastraError with id WORKFLOW_SCHEMA_VALIDATION_FAILED right at the start, before running any step.
Two warnings from the documentation, because they are the things that surprise. The first: .branch() evaluates all the conditions, and every true condition runs its step, so a branch can run more than one; to get only one, the conditions must be written so that they exclude each other. The second concerns loops with .dountil(): a loop whose condition never becomes true has no cap. I tried a loop with an always-false condition: after 20 seconds it had printed nothing and timeout stopped it with code 124. You put the cap in yourself, in the condition.
Agent and memory: a sketch to adapt, compiled but not run
An agent needs a model, and therefore a key or a server: the listing that follows is a sketch to adapt. I compiled it with tsc --strict against @mastra/core 1.83.0, @mastra/memory 1.41.1 and @mastra/libsql 1.30.0, so the names and types are the real ones; I did not run it, because no model was called. The model is a server compatible with the OpenAI APIs, for example Ollama, which serves its routes under /v1. (The instructions, the names and the question in the listing are Italian, as in the compiled listing: they are data for the model, not code.)
import { createStep, createWorkflow } from '@mastra/core/workflows'
import { z } from 'zod'
const normalizza = createStep({
id: 'normalizza',
inputSchema: z.object({ testo: z.string() }),
outputSchema: z.object({ parole: z.array(z.string()) }),
execute: async ({ inputData }) => ({
parole: inputData.testo.toLowerCase().split(/\s+/).filter(Boolean),
}),
})
const conta = createStep({
id: 'conta',
inputSchema: z.object({ parole: z.array(z.string()) }),
outputSchema: z.object({ totale: z.number(), uniche: z.number() }),
execute: async ({ inputData }) => ({
totale: inputData.parole.length,
uniche: new Set(inputData.parole).size,
}),
})
const contaParole = createWorkflow({
id: 'conta-parole',
inputSchema: z.object({ testo: z.string() }),
outputSchema: z.object({ totale: z.number(), uniche: z.number() }),
})
.then(normalizza)
.then(conta)
.commit()
const run = await contaParole.createRun()
const esito = await run.start({ inputData: { testo: 'Ciao ciao mondo' } })
if (esito.status === 'success') console.log('esito:', esito.status, JSON.stringify(esito.result))
try {
const altra = await contaParole.createRun()
await altra.start({ inputData: { testo: 42 as any } })
} catch (e: any) {
console.log('input errato:', e.id, '|', e.message.split('\n')[1].trim())
}
// Output:
// esito: success {"totale":3,"uniche":2}
// input errato: WORKFLOW_SCHEMA_VALIDATION_FAILED | - testo: Invalid input: expected string, received number
In the Agent constructor the properties are id, name, instructions and model. For hosted providers, model is a string in the format provider/model and the key is read from the provider's environment variable. Ollama, however, is not a provider of the router: the documentation says that ollama/<model> does not resolve, and proposes either the ollama-ai-provider-v2 package or an endpoint compatible with the OpenAI APIs. Here I use the second route, with the base URL http://localhost:11434/v1 and an id that you replace with the name of your model.
Memory wants two things: a Memory object on the agent and a storage on the Mastra instance. The lastMessages value says how many recent messages enter the context; if you do not write it, it is 10: creating a new Memory() without options and reading the effective configuration with getMergedThreadConfig (version 1.41.1) I found lastMessages 10, semantic search off, working memory disabled and automatic titles off. The reference page does not say so plainly. A sliding window has a cost that the documentation declares: once the limit is exceeded, every turn invalidates the provider's prompt cache, and for long conversations the same page points to observational memory, indicated as the recommended solution.
When you call generate, thread is the conversation and resource is who owns it, usually the user: it is the pair that keeps Alice's and Bruno's memories apart. The storage with file:./mastra.db persists to a file; the documentation uses :memory: for the quickstart. If you configure no storage, Mastra falls back to an in-memory store: I saw this happen while running the suspension workflow from the comparison article, because it prints a warning saying that data is lost on restart and that it is not suitable for production. A memory that disappears at every deploy is not a memory.
When Mastra is not the right choice
Mastra makes sense if your stack is already TypeScript, if you want workflows with suspend and resume, and if you need a development environment with an interface (the README mentions Studio, listening locally on port 4111 during development). It is not the obvious choice if your team works in Python: in that case LangGraph and CrewAI, covered in the comparison, speak your language. The points to weigh before committing:
- Speed of change: version 1.83.0 and the closely spaced releases (core, CLI and memory all have a modification date of 12 November) say that the APIs are moving; pin the versions and read the changelogs.
- License: Apache-2.0 for almost everything, but the
ee/directories have their own license, defined inee/LICENSE, which I did not evaluate. - Provider dependence: the router unifies 40-plus providers according to the README, but each provider wants its own key and its own terms on data.
- State: memory and workflow suspension require a storage; without one, you lose everything on restart.
Read the list as questions to put to your project. The license matters only if you will use the parts under ee/ (for example the auth/ee module of @mastra/core). The speed of change matters if the code must live for years without maintenance. Provider dependence is the same as for every framework: the agent's code does not change, but your data does, and with hosted models the decision about data must be made upstream. State is the only point where a mistake costs you right away.
What you can do now
You can choose between agent and workflow according to how well you know the steps, write a tool with a schema that protects it and see how it behaves with wrong input, compose a typed workflow and avoid the two documented traps (multiple branches and loops without a cap). You also know where an old guide betrays you: nonexistent packages, imports that do not resolve, memory that disappears. The first article showed how Letta approaches memory, a problem that Mastra solves with different tools; the next one puts Mastra beside LangGraph and CrewAI on the same problem, with the three programs run. For the rest of the series, the cost analysis says what it costs to run an agent with a local model, and the article on tracing shows how to read what it does.
Frequently asked questions
Is Mastra open source, and can I use it in a commercial product?
The repository's LICENSE.md applies Apache-2.0 to everything outside the ee/ directories, and for those it refers to ee/LICENSE. The npm registry declares Apache-2.0 for @mastra/core. If you need the modules under ee/, read that license before deciding: I did not evaluate it.
Can I use Mastra with a local model such as Ollama?
Yes, but not with the ollama/model string: the documentation says that Ollama is not a provider of the router. You pass an instance of ollama-ai-provider-v2 or the OpenAI-compatible base URL, which for Ollama is http://localhost:11434/v1. I did not run this connection: it needs a model.
How do you stop a loop that never ends in a Mastra workflow?
There is no default cap that I could observe: a .dountil() with an always-false condition did not terminate within 20 seconds. Write the cap into the condition, for example by counting the turns in the state, as in the program of the comparison article.
Sources
- Mastra docs: Agents - the Agent constructor, the provider/model format, when to use an agent, consulted on 2026-11-13
- Mastra docs: Tools - createTool and the execute(inputData, context) signature, consulted on 2026-11-13
- Mastra docs: Workflows - createStep, createWorkflow, then, commit, consulted on 2026-11-13
- Mastra docs: Control flow - semantics of branch (all true conditions run) and dountil, consulted on 2026-11-13
- Mastra docs: Memory - Memory, mandatory storage, message history, working memory and observational memory, consulted on 2026-11-13
- Mastra docs: Models - local models with an OpenAI-compatible endpoint, consulted on 2026-11-13
- Mastra docs: Ollama provider - Ollama does not resolve as ollama/model; the ollama-ai-provider-v2 package, consulted on 2026-11-13
- mastra-ai/mastra, LICENSE.md - Apache-2.0 with the ee/ directories under their own license, consulted on 2026-11-13
- Ollama: OpenAI compatibility - compatible routes under http://localhost:11434/v1, consulted on 2026-11-13
Versions (@mastra/core 1.83.0, @mastra/memory 1.41.1, @mastra/libsql 1.30.0, zod 4.6.7, Node >=22.13) read with npm view on 2026-11-13; the 404 of @mastra/sdk verified the same day. The tool and workflow programs were run with Node 24.11 twice with the same output; the in-memory storage warning is Mastra's real message on stderr. The agent listing is compiled with tsc strict and is a sketch to adapt: no model was called.

Commenti
Caricamento commenti...
Sign in to comment