@mastra/mcp-docs-server 1.2.3-alpha.7 → 1.2.3

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 (33) hide show
  1. package/.docs/docs/agent-builder/memory.md +4 -2
  2. package/.docs/docs/agent-controller/overview.md +1 -1
  3. package/.docs/docs/agents/agent-approval.md +38 -0
  4. package/.docs/docs/agents/file-based-agents.md +286 -0
  5. package/.docs/docs/agents/heartbeats.md +211 -0
  6. package/.docs/docs/getting-started/project-structure.md +18 -14
  7. package/.docs/docs/memory/observational-memory.md +114 -0
  8. package/.docs/docs/memory/working-memory.md +2 -0
  9. package/.docs/docs/observability/integrations/exporters/otel.md +23 -2
  10. package/.docs/models/gateways/netlify.md +3 -1
  11. package/.docs/models/gateways/openrouter.md +1 -3
  12. package/.docs/models/index.md +1 -1
  13. package/.docs/models/providers/anthropic.md +3 -2
  14. package/.docs/models/providers/deepinfra.md +2 -1
  15. package/.docs/models/providers/llmgateway.md +5 -7
  16. package/.docs/models/providers/novita-ai.md +1 -1
  17. package/.docs/models/providers/opencode-go.md +1 -1
  18. package/.docs/models/providers/sakana.md +73 -0
  19. package/.docs/models/providers/stepfun.md +1 -1
  20. package/.docs/models/providers/subconscious.md +71 -0
  21. package/.docs/models/providers/synthetic.md +8 -6
  22. package/.docs/models/providers/xiaomi.md +2 -2
  23. package/.docs/models/providers/zeldoc.md +1 -1
  24. package/.docs/models/providers.md +2 -0
  25. package/.docs/reference/agent-controller/agent-controller-class.md +9 -9
  26. package/.docs/reference/agents/listSuspendedRuns.md +91 -0
  27. package/.docs/reference/client-js/agents.md +21 -0
  28. package/.docs/reference/coding-agent/build-base-prompt.md +75 -0
  29. package/.docs/reference/coding-agent/create-coding-agent.md +97 -0
  30. package/.docs/reference/index.md +3 -0
  31. package/.docs/reference/memory/observational-memory.md +90 -0
  32. package/CHANGELOG.md +58 -0
  33. package/package.json +6 -6
@@ -25,9 +25,11 @@ Observational memory lets the agent learn long-lived facts from past conversatio
25
25
 
26
26
  ## Observational memory model
27
27
 
28
- Observational memory runs an Observer and Reflector model on top of every conversation. The default model is `google/gemini-2.5-flash`, which requires a `GOOGLE_API_KEY` environment variable in any environment where the Builder agent will run. Mastra also falls back to `GOOGLE_GENERATIVE_AI_API_KEY`.
28
+ Observational memory runs an Observer and Reflector model on top of every conversation. For Agent Builder agents, the default model is `openai/gpt-5-mini`, which requires an `OPENAI_API_KEY` environment variable in any environment where the Builder agent will run.
29
29
 
30
- To use a different model, set `observationalMemory.model` to any model ID supported by the Mastra model router (and provide the matching provider credentials):
30
+ > **Note:** This default applies only to agents created through the Agent Builder. Core (non-builder) agents configured with `observationalMemory: true` keep the framework default `google/gemini-2.5-flash` (which uses `GOOGLE_API_KEY`, falling back to `GOOGLE_GENERATIVE_AI_API_KEY`).
31
+
32
+ To use a different model, set `observationalMemory.model` to any model ID supported by the Mastra model router (and provide the matching provider credentials). An explicit model always wins over the Builder default:
31
33
 
32
34
  ```typescript
33
35
  new MastraEditor({
@@ -18,7 +18,7 @@ The AgentController gives you the runtime pieces to ship interactive agent appli
18
18
  - **Let users pick the right model for each step.** Per-mode [model management](https://mastra.ai/reference/agent-controller/agent-controller-class) switches models at runtime and tracks usage, which powers copilot UIs where users trade speed for capability.
19
19
  - **Delegate focused work to child agents.** [Subagents](https://mastra.ai/docs/agent-controller/subagents) run subtasks with constrained tools and can fork the parent conversation, so a research mode can spin off web search or code review without polluting the main thread.
20
20
  - **Drive a live UI from agent activity.** The [event system](https://mastra.ai/docs/agent-controller/session) emits typed events and coalesced display snapshots, so your TUI or web app reflects message updates, mode changes, and pending approvals in real time.
21
- - **Run long-lived autonomous agents.** Structured task lists, heartbeat handlers, and observational memory keep background task runners on track and let them learn across threads.
21
+ - **Run long-lived autonomous agents.** Structured task lists, interval handlers, and observational memory keep background task runners on track and let them learn across threads.
22
22
 
23
23
  ## When to use the AgentController
24
24
 
@@ -357,6 +357,44 @@ For automatic tool resumption to work:
357
357
 
358
358
  Both approaches work with the same tool definitions. Automatic resumption triggers only when suspended tools exist in the message history and the user sends a new message on the same thread.
359
359
 
360
+ ## Resuming after a restart
361
+
362
+ The examples above hold on to `stream.runId` between suspension and approval. That works while the process stays alive, but in production the approval often arrives later — after a page refresh, a server restart, or on a different server instance behind a load balancer.
363
+
364
+ Use [`listSuspendedRuns()`](https://mastra.ai/reference/agents/listSuspendedRuns) to rediscover the pending run for a conversation from storage:
365
+
366
+ ```typescript
367
+ // In the request handler that receives the user's decision
368
+ const { runs } = await agent.listSuspendedRuns({
369
+ threadId: 'thread-123',
370
+ resourceId: 'user-456',
371
+ })
372
+
373
+ const run = runs[0]
374
+ const toolCall = run?.toolCalls[0]
375
+
376
+ if (run && toolCall) {
377
+ let stream
378
+ if (toolCall.requiresApproval) {
379
+ // Suspended by requireApproval — approve or decline the tool call
380
+ stream = await agent.approveToolCall({ runId: run.runId, toolCallId: toolCall.toolCallId })
381
+ } else {
382
+ // Suspended by suspend() — resume with the data the tool asked for
383
+ console.log('Tool asked:', toolCall.suspendPayload)
384
+ stream = await agent.resumeStream({ name: 'San Francisco' }, { runId: run.runId })
385
+ }
386
+ for await (const chunk of stream.textStream) process.stdout.write(chunk)
387
+ }
388
+ ```
389
+
390
+ Each returned run includes the suspended tool calls (`toolCallId`, `toolName`, `args`, and `requiresApproval`). Approval suspensions (`requiresApproval: true`) are answered with `approveToolCall()` / `declineToolCall()`, while `suspend()`-based suspensions carry their `suspendPayload` and expect `resumeStream()` with resume data — so you can rebuild the right UI for either flow without keeping any state in memory.
391
+
392
+ `sendToolApproval()` uses the same storage-backed discovery automatically: when no active run is found in memory for the thread, it looks up the suspended run in storage before failing. If several suspended runs match the thread, pass a `toolCallId` to disambiguate.
393
+
394
+ The same discovery is available over HTTP as `GET /agents/:agentId/suspended-runs` and in the client SDK as [`agent.listSuspendedRuns()`](https://mastra.ai/reference/client-js/agents), so browser-based approval UIs can rediscover pending runs directly.
395
+
396
+ > **Note:** Suspended runs only survive restarts when your Mastra instance is configured with a persistent [storage provider](https://mastra.ai/docs/memory/storage). The default in-memory store loses snapshots when the process exits.
397
+
360
398
  ## Tool approval: Supervisor agents
361
399
 
362
400
  A [supervisor agent](https://mastra.ai/docs/agents/supervisor-agents) coordinates multiple subagents using `.stream()` or `.generate()`. When a subagent calls a tool that requires approval, the request propagates up through the delegation chain and surfaces at the supervisor level:
@@ -0,0 +1,286 @@
1
+ # File-based agents
2
+
3
+ **Added in:** `@mastra/core@1.48.0`
4
+
5
+ > **Beta:** This feature is in beta. Breaking changes may occur without a major version bump until the API is stable.
6
+
7
+ You can define an agent by file convention instead of constructing it in code. Mastra discovers a directory under `src/mastra/agents/<name>/`, assembles an [`Agent`](https://mastra.ai/reference/agents/agent), and registers it on your [`Mastra`](https://mastra.ai/reference/core/mastra-class) instance.
8
+
9
+ ## When to use file-based agents
10
+
11
+ Use file-based agents when you want one directory per agent, with configuration, instructions, tools, skills, workspace files, and subagents grouped together.
12
+
13
+ Keep using [`new Agent()`](https://mastra.ai/reference/agents/agent) in code when you need dynamic configuration, programmatic registration, or a shared agent instance across modules. Both approaches can coexist: code-registered agents are always present, and the bundler adds file-based agents when you run through the Mastra CLI.
14
+
15
+ ## Quickstart
16
+
17
+ Create a directory for the agent and add a `config.ts`. Use `agentConfig` so the partial config is typed while sibling files supply the rest.
18
+
19
+ ```typescript
20
+ import { agentConfig } from '@mastra/core/agent'
21
+
22
+ export default agentConfig({
23
+ model: 'openai/gpt-5.5',
24
+ // instructions omitted -> taken from instructions.md
25
+ // tools omitted -> taken from tools/*.ts
26
+ })
27
+ ```
28
+
29
+ Add the agent instructions:
30
+
31
+ ```markdown
32
+ You are a helpful weather assistant. Answer questions about current conditions and forecasts.
33
+ ```
34
+
35
+ Add a tool. The filename becomes the tool key, so this file is exposed as `get_weather`.
36
+
37
+ ```typescript
38
+ import { createTool } from '@mastra/core/tools'
39
+ import { z } from 'zod'
40
+
41
+ export default createTool({
42
+ id: 'get_weather',
43
+ description: 'Get the current weather for a city',
44
+ inputSchema: z.object({ city: z.string() }),
45
+ execute: async ({ context }) => ({ city: context.city, tempC: 21 }),
46
+ })
47
+ ```
48
+
49
+ Your `src/mastra/index.ts` stays the same. The discovered agent is registered automatically when you run the app through `mastra dev` or `mastra build`.
50
+
51
+ ```typescript
52
+ import { Mastra } from '@mastra/core'
53
+ import { Agent } from '@mastra/core/agent'
54
+
55
+ const supportAgent = new Agent({
56
+ id: 'support',
57
+ name: 'support',
58
+ instructions: 'You are a support agent.',
59
+ model: 'openai/gpt-5.5',
60
+ })
61
+
62
+ // `support` is registered in code; `weather` is discovered from the filesystem.
63
+ export const mastra = new Mastra({
64
+ agents: { support: supportAgent },
65
+ })
66
+ ```
67
+
68
+ Start the app through the Mastra CLI:
69
+
70
+ **npm**:
71
+
72
+ ```bash
73
+ npx mastra dev
74
+ ```
75
+
76
+ **pnpm**:
77
+
78
+ ```bash
79
+ pnpm dlx mastra dev
80
+ ```
81
+
82
+ **Yarn**:
83
+
84
+ ```bash
85
+ yarn dlx mastra dev
86
+ ```
87
+
88
+ **Bun**:
89
+
90
+ ```bash
91
+ bun x mastra dev
92
+ ```
93
+
94
+ ## Folder structure
95
+
96
+ The following table shows the supported file-based agent surface:
97
+
98
+ | File / directory | Maps to |
99
+ | --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
100
+ | `agents/<name>/config.ts` | Default export merged into the agent config. `id` and `name` default to `<name>`. |
101
+ | `agents/<name>/instructions.md` | The agent `instructions`. The file contents are inlined into generated code. |
102
+ | `agents/<name>/tools/*.ts` | Each default-exported [`createTool()`](https://mastra.ai/reference/tools/create-tool). The tool key defaults to the filename. |
103
+ | `agents/<name>/skills/*.ts` | Each default-exported [`createSkill()`](https://mastra.ai/reference/agents/createSkill), added to the agent `skills`. |
104
+ | `agents/<name>/skills/<skill>/SKILL.md` | A packaged skill. Frontmatter supplies `name` and `description`, the body is the instructions, and files under `references/` are inlined. |
105
+ | `agents/<name>/skills/<skill>.md` | A flat skill. The filename is the skill name and the body is the instructions. |
106
+ | `agents/<name>/memory.ts` | Default export: a [`Memory`](https://mastra.ai/reference/memory/memory-class) instance used as the agent `memory`. |
107
+ | `agents/<name>/workspace.ts` | Default export: a [`Workspace`](https://mastra.ai/reference/workspace/workspace-class) for the agent. |
108
+ | `agents/<name>/workspace/` | Seed files mirrored into the agent's default workspace at build time. |
109
+ | `agents/<name>/subagents/<childId>/` | A declared subagent with the same layout as an agent directory. Wired into the parent as a delegation tool named `<childId>`. |
110
+
111
+ Test files named `*.test.ts`, `*.spec.ts`, `*.test.js`, and `*.spec.js` are ignored during tool and skill discovery.
112
+
113
+ ## Add skills
114
+
115
+ Add skills to a file-based agent by placing them under `agents/<name>/skills/`. Three layouts are supported, and they're inlined into the bundle at build time so the deployed agent doesn't read them from disk at runtime.
116
+
117
+ - A `.ts` file can default-export `createSkill()`:
118
+
119
+ ```typescript
120
+ import { createSkill } from '@mastra/core/skills'
121
+
122
+ export default createSkill({
123
+ name: 'forecasting',
124
+ description: 'Use when the user asks about multi-day forecasts.',
125
+ instructions: 'Summarize the forecast day by day and call out precipitation.',
126
+ })
127
+ ```
128
+
129
+ > **Note:** Visit [`createSkill()` reference](https://mastra.ai/reference/agents/createSkill) for the full API.
130
+
131
+ - A packaged `SKILL.md` directory uses frontmatter for the name and description. Files under `references/` are inlined with the skill.
132
+
133
+ ```markdown
134
+ ---
135
+ name: severe-weather
136
+ description: Use when conditions include storms, flooding, or other hazards.
137
+ ---
138
+
139
+ Lead with the active alert, then give safety guidance.
140
+ ```
141
+
142
+ - A flat `<skill>.md` file uses the filename as the skill name:
143
+
144
+ ```markdown
145
+ Always report temperatures in both Celsius and Fahrenheit.
146
+ ```
147
+
148
+ Discovered skills merge with any `skills` in `config.ts`. On a name collision, `config.skills` wins and a warning is logged. If `config.skills` is a function, discovered skills are ignored with a warning because they can't be statically merged.
149
+
150
+ ## Add memory
151
+
152
+ Give a file-based agent [memory](https://mastra.ai/docs/memory/overview) by adding a `memory.ts` that default-exports a [`Memory`](https://mastra.ai/reference/memory/memory-class) instance:
153
+
154
+ ```typescript
155
+ import { Memory } from '@mastra/memory'
156
+
157
+ export default new Memory()
158
+ ```
159
+
160
+ The exported instance becomes the agent's `memory`. You can also set `memory` directly in `config.ts`. `config.memory` wins over `memory.ts`, and a warning is logged when both are present. If neither is present, the agent has no memory, which is the default.
161
+
162
+ ## Add a workspace
163
+
164
+ When a file-based agent is discovered through `mastra dev` or `mastra build`, it gets a default workspace unless `config.workspace` or `workspace.ts` supplies one. The default workspace uses a contained filesystem and shell sandbox rooted at a per-agent `workspace/` directory in the bundle.
165
+
166
+ To customize it, add a `workspace.ts` that default-exports a [`Workspace`](https://mastra.ai/reference/workspace/workspace-class):
167
+
168
+ ```typescript
169
+ import { Workspace, LocalFilesystem, LocalSandbox } from '@mastra/core/workspace'
170
+
171
+ export default new Workspace({
172
+ name: 'weather-workspace',
173
+ filesystem: new LocalFilesystem({ basePath: './data/weather' }),
174
+ sandbox: new LocalSandbox({ workingDirectory: './data/weather' }),
175
+ })
176
+ ```
177
+
178
+ You can also set `workspace` directly in `config.ts`. `config.workspace` wins over `workspace.ts`, and `workspace.ts` wins over the default workspace.
179
+
180
+ ### Seed files
181
+
182
+ Add a `workspace/` directory to ship files with the agent. Mastra mirrors every file under it into the agent's default workspace at build time, so the agent starts with those files on disk:
183
+
184
+ ```text
185
+ src/mastra/agents/weather/
186
+ config.ts
187
+ workspace/
188
+ README.md
189
+ data/cities.json
190
+ ```
191
+
192
+ Seed files are copied into the bundle next to the running server. Commit the starting files alongside the agent that uses them.
193
+
194
+ ## Add subagents
195
+
196
+ A file-based agent can declare **subagents**, specialist child agents it can delegate to. Add a `subagents/` directory under the agent, with one directory per subagent. Each subagent directory has the same layout as a top-level agent: `config.ts`, `instructions.md`, `tools/`, `skills/`, `memory.ts`, `workspace.ts`, and `workspace/`.
197
+
198
+ ```text
199
+ src/mastra/agents/
200
+ supervisor/
201
+ config.ts
202
+ instructions.md
203
+ subagents/
204
+ researcher/
205
+ config.ts
206
+ instructions.md
207
+ tools/
208
+ search.ts
209
+ ```
210
+
211
+ Each subagent is assembled as its own agent and wired into the parent's `agents` map. The agent loop lowers it into a model-visible delegation tool. The tool name is the bare directory name, so the example above exposes `researcher` to the supervisor.
212
+
213
+ A subagent's `config.ts` must set a non-empty `description`. The description is what the model sees when deciding whether to delegate, so the build fails if it's missing.
214
+
215
+ ```typescript
216
+ import { agentConfig } from '@mastra/core/agent'
217
+
218
+ export default agentConfig({
219
+ model: 'openai/gpt-5.5',
220
+ description: 'Researches a topic and returns cited findings.',
221
+ })
222
+ ```
223
+
224
+ Subagents are isolated. A subagent inherits nothing from its parent. Its tools, skills, and workspace come only from its own directory, and any absent slot falls back to the same framework defaults as a top-level agent.
225
+
226
+ Subagents are one level deep. A `subagents/` directory nested inside a subagent is ignored with a warning.
227
+
228
+ Naming rules:
229
+
230
+ - A subagent id that collides with one of the parent's tool keys is a build error.
231
+ - A duplicate subagent id under the same parent is a build error.
232
+ - If a subagent id also exists in the parent's `config.agents`, the `config.agents` entry wins and logs a warning.
233
+ - If `config.agents` is a function, discovered subagents are ignored with a warning because they can't be statically merged.
234
+
235
+ ## Precedence rules
236
+
237
+ File-based and code-based agents coexist with deterministic rules:
238
+
239
+ - **Code wins on name collisions:** If an agent name exists in both code and the filesystem, the code-registered agent is kept and a warning is logged.
240
+ - **A folder can hold a code agent:** If `config.ts` exports `new Agent({...})`, that instance is used as-is. Sibling `instructions.md`, `tools/`, `skills/`, `memory.ts`, `workspace.ts`, and `subagents/` entries are ignored with warnings.
241
+ - **Instructions:** Dynamic function instructions in `config.ts` win over `instructions.md`. Otherwise, `instructions.md` wins over a static `instructions` string. If neither is present, the build fails for that agent.
242
+ - **Model:** A missing `model` fails the build and names the agent directory.
243
+ - **Tools:** Tools from `tools/*.ts` merge with `config.tools`. On a key collision, `config.tools` wins and a warning is logged. If `config.tools` is a function, discovered tools are ignored with a warning.
244
+ - **Skills:** Skills from `skills/` merge with `config.skills`. On a name collision, `config.skills` wins and a warning is logged. If `config.skills` is a function, discovered skills are ignored with a warning.
245
+ - **Memory:** `config.memory` wins over `memory.ts`, and a warning is logged when both are present. If neither is set, the agent has no memory.
246
+ - **Workspace:** `config.workspace` wins over `workspace.ts`, which wins over the default workspace.
247
+ - **Subagents:** Subagents from `subagents/` merge with `config.agents`. On an id collision, `config.agents` wins and a warning is logged. A subagent id that collides with a tool key, or a duplicate subagent id, is a build error.
248
+
249
+ ## What happens at build time
250
+
251
+ File-based agents are discovered by the Mastra **bundler**, the step that runs under `mastra dev` and `mastra build`.
252
+
253
+ File-based agents are registered only when your app runs through the Mastra CLI. If you import your `mastra` instance directly, `agents/<name>/` directories aren't discovered.
254
+
255
+ When you consume Mastra as a library, register those agents in code instead of relying on file discovery:
256
+
257
+ ```typescript
258
+ import { Mastra } from '@mastra/core'
259
+ import { Agent } from '@mastra/core/agent'
260
+
261
+ const weather = new Agent({
262
+ id: 'weather',
263
+ name: 'weather',
264
+ instructions: 'You are a helpful weather assistant.',
265
+ model: 'openai/gpt-5.5',
266
+ })
267
+
268
+ export const mastra = new Mastra({
269
+ agents: { weather },
270
+ })
271
+ ```
272
+
273
+ ## Related
274
+
275
+ - [Agents overview](https://mastra.ai/docs/agents/overview)
276
+ - [Tools](https://mastra.ai/docs/agents/using-tools)
277
+ - [Skills](https://mastra.ai/docs/agents/skills)
278
+ - [Memory](https://mastra.ai/docs/memory/overview)
279
+ - [Supervisor agents](https://mastra.ai/docs/agents/supervisor-agents)
280
+ - [Workspace](https://mastra.ai/docs/workspace/overview)
281
+ - [Studio overview](https://mastra.ai/docs/studio/overview)
282
+ - [`Agent` reference](https://mastra.ai/reference/agents/agent)
283
+ - [`createTool()` reference](https://mastra.ai/reference/tools/create-tool)
284
+ - [`createSkill()` reference](https://mastra.ai/reference/agents/createSkill)
285
+ - [`Memory` reference](https://mastra.ai/reference/memory/memory-class)
286
+ - [`Workspace` reference](https://mastra.ai/reference/workspace/workspace-class)
@@ -0,0 +1,211 @@
1
+ # Heartbeats
2
+
3
+ **Added in:** `@mastra/core@1.46.0`
4
+
5
+ > **Beta:** This feature is in alpha. Breaking changes may occur without a major version bump until the API is stable.
6
+
7
+ A heartbeat runs an agent on a cron schedule. On each fire, Mastra sends a prompt to the agent, either as a [signal](https://mastra.ai/docs/agents/signals) into a thread or as a threadless `agent.generate()` run. Use heartbeats for recurring agent work such as daily summaries, periodic checks, or scheduled nudges into a conversation.
8
+
9
+ Heartbeats are persisted, so they survive restarts and redeploys. Manage them at runtime through `mastra.heartbeats`, the canonical create, read, update, and delete (CRUD) surface.
10
+
11
+ ## Prerequisites
12
+
13
+ Heartbeats require a [storage](https://mastra.ai/docs/memory/storage) adapter that implements the schedules domain, for example `@mastra/libsql`. Without one, `mastra.heartbeats.create()` throws.
14
+
15
+ ## Quickstart
16
+
17
+ The following heartbeat runs the `pinger` agent every hour. It has no thread, so each fire is an isolated `agent.generate()` run.
18
+
19
+ ```typescript
20
+ import { Mastra } from '@mastra/core'
21
+ import { Agent } from '@mastra/core/agent'
22
+ import { LibSQLStore } from '@mastra/libsql'
23
+
24
+ const pinger = new Agent({
25
+ id: 'pinger',
26
+ name: 'Pinger',
27
+ instructions: 'Report the current system status in one sentence.',
28
+ model: 'openai/gpt-5.5',
29
+ })
30
+
31
+ const mastra = new Mastra({
32
+ agents: { pinger },
33
+ storage: new LibSQLStore({ url: 'file:./mastra.db' }),
34
+ })
35
+
36
+ await mastra.heartbeats.create({
37
+ agentId: 'pinger',
38
+ cron: '0 * * * *',
39
+ prompt: 'Give me a status update.',
40
+ })
41
+ ```
42
+
43
+ Mastra starts the scheduler the first time a heartbeat is created, then fires the agent on the cron you specify.
44
+
45
+ ## Cadence
46
+
47
+ Heartbeats fire on a cron expression. The `cron` field accepts a standard 5-, 6-, or 7-part cron expression, and it's validated when you create or update the heartbeat.
48
+
49
+ Croner nicknames also work, for example `@hourly`, `@daily`, `@weekly`, `@monthly`, and `@midnight`. For day-and-time combinations, write the cron field directly:
50
+
51
+ ```typescript
52
+ // Every weekday at 9am
53
+ await mastra.heartbeats.create({
54
+ agentId: 'pinger',
55
+ cron: '0 9 * * 1-5',
56
+ prompt: 'Start-of-day check.',
57
+ })
58
+ ```
59
+
60
+ Set `timezone` to an IANA timezone, for example `America/New_York`, so fire times don't depend on the host's locale. When omitted, the cron resolves against the host's local timezone.
61
+
62
+ For more readable cron construction, you can use a userland builder such as [`cron-time-generator`](https://www.npmjs.com/package/cron-time-generator) and pass its output to `cron`.
63
+
64
+ ## Threadless and threaded heartbeats
65
+
66
+ A heartbeat fires in one of two modes, decided by whether you pass a `threadId`.
67
+
68
+ ### Threadless
69
+
70
+ Without a `threadId`, each fire is an isolated `agent.generate()` run. Nothing is written to a conversation thread. This is the simplest mode and suits status checks, reports, and other work that doesn't need conversation context.
71
+
72
+ ### Threaded
73
+
74
+ With a `threadId`, the heartbeat sends a [signal](https://mastra.ai/docs/agents/signals) into that thread, so the prompt joins the agent's conversation. Threaded heartbeats require a `resourceId` alongside the `threadId`.
75
+
76
+ ```typescript
77
+ await mastra.heartbeats.create({
78
+ agentId: 'pinger',
79
+ cron: '0 9 * * *',
80
+ prompt: 'Summarize anything new since yesterday.',
81
+ threadId: 'thread-123',
82
+ resourceId: 'user-456',
83
+ })
84
+ ```
85
+
86
+ Threaded heartbeats accept extra fields that control how the signal behaves. They mirror the options [`agent.sendSignal`](https://mastra.ai/docs/agents/signals) accepts and stay JSON-serializable so they persist with the schedule.
87
+
88
+ - `signalType`: the [signal type](https://mastra.ai/docs/agents/signals) to send, for example `notification` or `system-reminder`. Defaults to `notification`.
89
+ - `tagName`: the XML tag the signal renders as. Defaults to `heartbeat`, so a fire surfaces to the agent as `<heartbeat>…</heartbeat>`.
90
+ - `attributes`: values rendered onto the signal's XML tag.
91
+ - `ifActive`: behavior when the thread is already streaming, as `{ behavior, attributes }`. `behavior` is one of `deliver`, `persist`, or `discard`.
92
+ - `ifIdle`: behavior when the thread is idle, as `{ behavior, attributes, streamOptions }`. `behavior` is one of `wake`, `persist`, or `discard`. `streamOptions.requestContext` is applied to the woken run.
93
+
94
+ These fields require a `threadId`. Passing them on a threadless heartbeat throws.
95
+
96
+ ```typescript
97
+ await mastra.heartbeats.create({
98
+ agentId: 'pinger',
99
+ cron: '0 9 * * *',
100
+ prompt: 'Summarize anything new since yesterday.',
101
+ threadId: 'thread-123',
102
+ resourceId: 'user-456',
103
+ tagName: 'check-in', // renders as <check-in>…</check-in>
104
+ attributes: { source: 'cron' },
105
+ ifActive: { behavior: 'discard' }, // skip if the thread is mid-stream
106
+ ifIdle: {
107
+ behavior: 'wake', // wake the agent if the thread is idle
108
+ streamOptions: { requestContext: { locale: 'en-US' } },
109
+ },
110
+ })
111
+ ```
112
+
113
+ `providerOptions` are merged into the signal payload on every fire and apply to both threaded and threadless heartbeats.
114
+
115
+ ## Managing heartbeats
116
+
117
+ Use `mastra.heartbeats` for all heartbeat operations. To scope to a single agent, pass `agentId` to `create` or `list`.
118
+
119
+ ```typescript
120
+ // Create
121
+ const hb = await mastra.heartbeats.create({
122
+ agentId: 'pinger',
123
+ cron: '0 * * * *',
124
+ prompt: 'Status check.',
125
+ })
126
+
127
+ // Read
128
+ await mastra.heartbeats.get(hb.id)
129
+ await mastra.heartbeats.list({ agentId: 'pinger' })
130
+
131
+ // Update — changing cron or timezone recomputes the next fire time
132
+ await mastra.heartbeats.update(hb.id, { cron: '*/30 * * * *' })
133
+
134
+ // Pause and resume
135
+ await mastra.heartbeats.pause(hb.id)
136
+ await mastra.heartbeats.resume(hb.id)
137
+
138
+ // Fire once now, off-schedule
139
+ await mastra.heartbeats.run(hb.id)
140
+
141
+ // Delete
142
+ await mastra.heartbeats.delete(hb.id)
143
+ ```
144
+
145
+ A few rules worth knowing:
146
+
147
+ - `pause` and `resume` are durable and idempotent. A paused heartbeat survives restarts, and `resume` recomputes the next fire time from now rather than firing backlogged runs.
148
+ - `run` fires the heartbeat once immediately without affecting its schedule.
149
+ - `list` filters by `agentId`, `threadId`, `resourceId`, and `name`.
150
+
151
+ ### Custom IDs
152
+
153
+ By default `create` generates a random `hb_<uuid>` id. Pass `id` to choose a stable one, for example when you want a predictable handle to look up, update, or delete later:
154
+
155
+ ```typescript
156
+ await mastra.heartbeats.create({
157
+ id: 'nightly-summary',
158
+ agentId: 'pinger',
159
+ cron: '0 9 * * *',
160
+ prompt: 'Summarize anything new since yesterday.',
161
+ })
162
+ // stored as `hb_nightly-summary`
163
+ ```
164
+
165
+ The id is normalized to `hb_<slug>`: the `hb_` prefix is added if missing and the rest is slugified. Creating a heartbeat with an id that already exists throws, so use `update` to change an existing one.
166
+
167
+ ### From the client
168
+
169
+ The same operations are available from `@mastra/client-js` over the server routes, so you can manage heartbeats from a separate process or a UI.
170
+
171
+ ## Lifecycle hooks
172
+
173
+ Hooks let you run code at key points in a heartbeat's lifecycle, for example to compute fire-time parameters or react to the outcome. Configure them on the `Mastra` constructor under `heartbeat`. The hooks are a single flat bundle that runs for every agent's heartbeats; each hook context carries the firing `agentId`, so branch on it when you need per-agent behavior. Hooks live at the `Mastra` level so they apply to both code-defined and stored agents.
174
+
175
+ ```typescript
176
+ const mastra = new Mastra({
177
+ agents: { pinger },
178
+ storage: new LibSQLStore({ url: 'file:./mastra.db' }),
179
+ heartbeat: {
180
+ prepare: async ({ agentId, heartbeat, trigger }) => {
181
+ // Return overrides, null to skip this fire, or undefined for defaults
182
+ return { prompt: `Status as of ${trigger.firedAt.toISOString()}` }
183
+ },
184
+ onFinish: async ({ agentId, outcome, runId }) => {
185
+ // Runs on any non-error, non-abort outcome
186
+ },
187
+ onError: async ({ agentId, phase, error }) => {
188
+ // Runs when prepare, the signal, or the agent run threw
189
+ },
190
+ onAbort: async ({ agentId, runId }) => {
191
+ // Runs when the run was aborted mid-stream
192
+ },
193
+ },
194
+ })
195
+ ```
196
+
197
+ The hooks are:
198
+
199
+ - `prepare`: runs before the fire. Return an object to override fire-time parameters such as `prompt` or `threadId`, `null` to skip the fire, or `undefined` to use the stored defaults.
200
+ - `onFinish`: runs once per trigger that reached a non-error, non-abort terminal state.
201
+ - `onError`: runs when `prepare`, the signal, or the agent run threw.
202
+ - `onAbort`: runs when the run was aborted mid-stream.
203
+
204
+ Every hook context includes `agentId` (the agent the heartbeat fired for) alongside `heartbeat` and `trigger`.
205
+
206
+ Hook exceptions are caught and logged. They never re-route the worker or trigger another hook.
207
+
208
+ ## Related
209
+
210
+ - [Signals](https://mastra.ai/docs/agents/signals): the delivery mechanism behind threaded heartbeats.
211
+ - [Scheduled workflows](https://mastra.ai/docs/workflows/scheduled-workflows): run a workflow, rather than an agent, on a cron schedule.
@@ -2,13 +2,13 @@
2
2
 
3
3
  Your new Mastra project, created with the `create mastra` command, comes with a predefined set of files and folders to help you get started.
4
4
 
5
- Mastra is a framework, but it's **unopinionated** about how you organize or colocate your files. The CLI provides a sensible default structure that works well for most projects, but you're free to adapt it to your workflow or team conventions. You could even build your entire project in a single file if you wanted! Whatever structure you choose, keep it consistent to ensure your code stays maintainable and straightforward to navigate.
5
+ Mastra is a framework, but it's mostly **unopinionated** about how you organize or colocate your files. The CLI provides a sensible default structure that works well for most projects, but you're free to adapt it to your workflow or team conventions. You could even build your entire project in a single file if you wanted! Whatever structure you choose, keep it consistent to ensure your code stays maintainable and straightforward to navigate.
6
6
 
7
7
  ## Default project structure
8
8
 
9
9
  A project created with the `create mastra` command looks like this:
10
10
 
11
- ```text
11
+ ```bash
12
12
  src/
13
13
  ├── mastra/
14
14
  │ ├── agents/
@@ -25,21 +25,25 @@ src/
25
25
  └── tsconfig.json
26
26
  ```
27
27
 
28
- > **Tip:** Use the predefined files as templates. Duplicate and adapt them to quickly create your own agents, tools, workflows, etc.
28
+ Use the predefined files as templates. Duplicate and adapt them to quickly create your own agents, tools, workflows, etc.
29
29
 
30
30
  ### Folders
31
31
 
32
- Folders organize your agent's resources, like agents, tools, and workflows.
33
-
34
- | Folder | Description |
35
- | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
36
- | `src/mastra` | Entry point for all Mastra-related code and configuration. |
37
- | `src/mastra/agents` | Define and configure your agents - their behavior, goals, and tools. |
38
- | `src/mastra/workflows` | Define multi-step workflows that orchestrate agents and tools together. |
39
- | `src/mastra/tools` | Create reusable tools that your agents can call |
40
- | `src/mastra/mcp` | (Optional) Implement custom MCP servers to share your tools with external agents |
41
- | `src/mastra/scorers` | (Optional) Define scorers for evaluating agent performance over time |
42
- | `src/mastra/public` | (Optional) Contents are copied into the `.build/output` directory during the build process, making them available for serving at runtime |
32
+ Mastra recommends organizing your code into the following folders:
33
+
34
+ | Folder | Description |
35
+ | ---------------------- | ----------------------------------------------------------------------- |
36
+ | `src/mastra` | Entry point for all Mastra-related code and configuration. |
37
+ | `src/mastra/agents` | Define and configure your agents - their behavior, goals, and tools. |
38
+ | `src/mastra/workflows` | Define multi-step workflows that orchestrate agents and tools together. |
39
+ | `src/mastra/tools` | Create reusable tools that your agents can call |
40
+ | `src/mastra/mcp` | Implement custom MCP servers to share your tools with external agents |
41
+ | `src/mastra/scorers` | Define scorers for evaluating agent performance over time |
42
+
43
+ There are two special folder conventions in Mastra:
44
+
45
+ - `src/mastra/agents/<name>`: You can define an agent by file convention instead of constructing it in code. Learn more in the [file-based agents](https://mastra.ai/docs/agents/file-based-agents) guide.
46
+ - `src/mastra/public`: Contents are copied into the `.build/output` directory during the build process, making them available for serving at runtime.
43
47
 
44
48
  ### Top-level files
45
49