@mastra/mcp-docs-server 1.3.13 → 1.3.14-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.docs/docs/agents/guardrails.md +3 -3
- package/.docs/docs/agents/human-in-the-loop.md +14 -0
- package/.docs/docs/agents/processors.md +3 -3
- package/.docs/docs/agents/tools.md +2 -0
- package/.docs/docs/deployment/web-framework.md +1 -1
- package/.docs/docs/deployment/workers.md +16 -4
- package/.docs/docs/guides/authentication-identity.md +13 -1
- package/.docs/docs/harness/agent-controller.md +2 -0
- package/.docs/docs/harness/background-tasks.md +3 -1
- package/.docs/docs/knowledge/scopes-and-access.md +1 -1
- package/.docs/docs/sandbox/overview.md +23 -2
- package/.docs/docs/server/mcp.md +33 -1
- package/.docs/docs/server/overview.md +1 -0
- package/.docs/docs/server/request-context.md +1 -1
- package/.docs/docs/server/server-adapters.md +3 -0
- package/.docs/docs/studio/auth.md +5 -1
- package/.docs/docs/studio/editor.md +17 -0
- package/.docs/docs/studio/knowledge.md +34 -0
- package/.docs/docs/studio/overview.md +1 -1
- package/.docs/docs/workflows/overview.md +21 -3
- package/.docs/integrations/deploy/kubernetes-helm.md +8 -9
- package/.docs/integrations/frameworks/next-js.md +22 -6
- package/.docs/integrations/sandboxes/daytona.md +6 -6
- package/.docs/reference/agent-controller/session.md +4 -1
- package/.docs/reference/agents/agent.md +1 -1
- package/.docs/reference/agents/channels.md +4 -4
- package/.docs/reference/auth/auth0.md +2 -0
- package/.docs/reference/auth/clerk.md +4 -0
- package/.docs/reference/auth/jwt.md +4 -0
- package/.docs/reference/code-sdk/mount-agent-controller.md +4 -0
- package/.docs/reference/configuration.md +1 -1
- package/.docs/reference/core/mastra-class.md +8 -4
- package/.docs/reference/index.md +1 -0
- package/.docs/reference/knowledge/knowledge-class.md +1 -1
- package/.docs/reference/knowledge/knowledge-memory-scopes.md +44 -4
- package/.docs/reference/knowledge/scope-declarations.md +7 -3
- package/.docs/reference/observability/metrics/queries.md +9 -9
- package/.docs/reference/observability/tracing/interfaces.md +49 -15
- package/.docs/reference/pubsub/base.md +2 -0
- package/.docs/reference/pubsub/redis-streams.md +3 -3
- package/.docs/reference/pubsub/valkey-streams.md +2 -2
- package/.docs/reference/server/builtin-mcp-tools.md +135 -0
- package/.docs/reference/tools/mcp-server.md +2 -0
- package/.docs/reference/workflows/run-methods/startAsync.md +14 -11
- package/.docs/reference/workflows/workflow-methods/map.md +2 -2
- package/.docs/reference/workflows/workflow.md +2 -2
- package/package.json +4 -4
|
@@ -324,7 +324,7 @@ For output guardrails, run `TokenLimiterProcessor` and `BatchPartsProcessor` seq
|
|
|
324
324
|
```typescript
|
|
325
325
|
import { createWorkflow, createStep } from '@mastra/core/workflows'
|
|
326
326
|
import {
|
|
327
|
-
|
|
327
|
+
ProcessorStepOutputSchema,
|
|
328
328
|
PIIDetector,
|
|
329
329
|
ModerationProcessor,
|
|
330
330
|
SystemPromptScrubber,
|
|
@@ -334,8 +334,8 @@ import {
|
|
|
334
334
|
|
|
335
335
|
export const outputGuardrails = createWorkflow({
|
|
336
336
|
id: 'output-guardrails',
|
|
337
|
-
inputSchema:
|
|
338
|
-
outputSchema:
|
|
337
|
+
inputSchema: ProcessorStepOutputSchema,
|
|
338
|
+
outputSchema: ProcessorStepOutputSchema,
|
|
339
339
|
})
|
|
340
340
|
// Sequential: limit tokens first, then batch stream chunks
|
|
341
341
|
.then(createStep(new TokenLimiterProcessor({ limit: 1000 })))
|
|
@@ -577,6 +577,20 @@ The same discovery is available over HTTP as `GET /agents/:agentId/suspended-run
|
|
|
577
577
|
|
|
578
578
|
> **Note:** Suspended runs only survive restarts when your Mastra instance is configured with a persistent [storage provider](https://mastra.ai/docs/storage). The default in-memory store loses snapshots when the process exits.
|
|
579
579
|
|
|
580
|
+
### Recovering a decision after a crash
|
|
581
|
+
|
|
582
|
+
When `approveToolCall()`, `declineToolCall()`, or `resumeStream()` runs, the run is claimed in storage together with the decision or resume data and the targeted `toolCallId`. If the process handling the resume stops before the run finishes, call `recoverResume()` from any process to finish the run with that stored decision:
|
|
583
|
+
|
|
584
|
+
```typescript
|
|
585
|
+
const stream = await agent.recoverResume({ runId })
|
|
586
|
+
|
|
587
|
+
for await (const chunk of stream.textStream) process.stdout.write(chunk)
|
|
588
|
+
```
|
|
589
|
+
|
|
590
|
+
`recoverResume()` takes over a claim once it's abandoned: claimed but not started for 60 seconds, or, on storage with run fencing, started and its lease not renewed for 60 seconds. Before that, it rejects with `AGENT_RESUME_ALREADY_CLAIMED`. For a run that no resume has claimed, it rejects with `AGENT_RESUME_NOTHING_TO_RECOVER`.
|
|
591
|
+
|
|
592
|
+
> **Warning:** The resumed tool call runs again. A claim counts as abandoned by its age, so a process that stalled for 60 seconds may still be running the tool when the recovery runs it. Make tools with side effects safe to repeat, for example with an idempotency key.
|
|
593
|
+
|
|
580
594
|
## Tool approval: Supervisor agents
|
|
581
595
|
|
|
582
596
|
A [supervisor agent](https://mastra.ai/docs/subagents) 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:
|
|
@@ -905,7 +905,7 @@ You can use Mastra workflows as processors to create complex processing pipeline
|
|
|
905
905
|
```typescript
|
|
906
906
|
import { createWorkflow, createStep } from '@mastra/core/workflows'
|
|
907
907
|
import {
|
|
908
|
-
|
|
908
|
+
ProcessorStepOutputSchema,
|
|
909
909
|
PromptInjectionDetector,
|
|
910
910
|
PIIDetector,
|
|
911
911
|
ModerationProcessor,
|
|
@@ -915,8 +915,8 @@ import { Agent } from '@mastra/core/agent'
|
|
|
915
915
|
// Create a workflow that runs multiple checks in parallel
|
|
916
916
|
const moderationWorkflow = createWorkflow({
|
|
917
917
|
id: 'moderation-pipeline',
|
|
918
|
-
inputSchema:
|
|
919
|
-
outputSchema:
|
|
918
|
+
inputSchema: ProcessorStepOutputSchema,
|
|
919
|
+
outputSchema: ProcessorStepOutputSchema,
|
|
920
920
|
})
|
|
921
921
|
.parallel([
|
|
922
922
|
createStep(
|
|
@@ -598,6 +598,8 @@ export const researchAgent = new Agent({
|
|
|
598
598
|
|
|
599
599
|
The resolved tool ID comes from the provider: `openai.web_search`, `anthropic.web_search_20250305`, `google.google_search`, or `xai.web_search`.
|
|
600
600
|
|
|
601
|
+
Models served through the Mastra gateway, such as `mastra/openai/gpt-5.6-sol`, use the gateway's own web search (`openrouter.web_search`) instead. Results from gateway web search arrive in the model's text response, without separate tool-call or source chunks. Other provider-native tools aren't available through the gateway, so passing one makes the agent run fail with a `MastraError`.
|
|
602
|
+
|
|
601
603
|
The `search` key is only the agent-local tool name. Use any key. The `webSearchTool` value tells Mastra to use provider web search.
|
|
602
604
|
|
|
603
605
|
### Fetch a web page
|
|
@@ -15,7 +15,7 @@ Integration guides:
|
|
|
15
15
|
|
|
16
16
|
## With Next.js on Vercel
|
|
17
17
|
|
|
18
|
-
If you've integrated Mastra with Next.js [
|
|
18
|
+
If you've integrated Mastra with Next.js and plan to deploy to Vercel, make sure your `next.config.ts` sets `serverExternalPackages: ["@mastra/*"]`. The [Next.js guide](https://mastra.ai/integrations/frameworks/next-js) adds it during setup. If your config doesn't have it, add it:
|
|
19
19
|
|
|
20
20
|
```typescript
|
|
21
21
|
import type { NextConfig } from 'next'
|
|
@@ -48,7 +48,15 @@ When a schedule is created at runtime, Mastra publishes a wake event on the PubS
|
|
|
48
48
|
|
|
49
49
|
To poll from startup regardless of whether schedules exist (for example, when your processes don't share a PubSub backend), set `scheduler: { enabled: true }` on the worker or run it with `MASTRA_WORKERS=scheduler`.
|
|
50
50
|
|
|
51
|
-
|
|
51
|
+
You can run more than one scheduler instance against the same storage. Before it publishes, a scheduler claims each occurrence with a compare-and-swap update of the schedule's next fire time. Only one instance wins the claim, and the others skip that occurrence. The built-in storage adapters (PostgreSQL, LibSQL, MySQL, MongoDB, Spanner, Convex) all perform this update atomically. A custom storage adapter must do the same in `updateScheduleNextFire`, or instances can fire the same occurrence twice.
|
|
52
|
+
|
|
53
|
+
The claim stops other scheduler instances from publishing the same occurrence. It doesn't make firing exactly-once:
|
|
54
|
+
|
|
55
|
+
- **Claim and publish aren't one transaction.** If the instance that won the claim crashes, or fails to publish after three attempts, that occurrence can be lost. Mastra records a failed publish as a `failed` trigger with an unknown publication outcome and doesn't replay it automatically.
|
|
56
|
+
- **Retries can publish an occurrence twice.** If a publish reaches the PubSub backend but still reports an error, the retry publishes the occurrence again with the same run ID. For workflows on the default engine, the worker skips a start for a run that already exists, but a duplicate that arrives before the first run is stored can still start. Evented workflows have no such check: a duplicate start sets the existing run back to `running` and executes it again.
|
|
57
|
+
- **Occurrences can overlap.** A new occurrence fires on time even if the run from the previous one hasn't finished.
|
|
58
|
+
|
|
59
|
+
Extra scheduler instances add availability, not throughput. Each one polls storage on every tick.
|
|
52
60
|
|
|
53
61
|
### Background task worker
|
|
54
62
|
|
|
@@ -75,6 +83,8 @@ The server generated by `mastra build` starts these workers automatically. If yo
|
|
|
75
83
|
|
|
76
84
|
This setup needs no external infrastructure beyond your storage adapter. It doesn't survive process crashes, and you can't scale individual components.
|
|
77
85
|
|
|
86
|
+
> **Warning:** The in-memory PubSub delivers events only inside the process that published them. Running several Mastra instances on one storage with it isn't supported for evented workflows: each instance restarts the others' active runs when it boots. Configure a distributed PubSub backend for a multi-instance deployment.
|
|
87
|
+
|
|
78
88
|
### Split processes
|
|
79
89
|
|
|
80
90
|
To run workers in their own processes, configure a distributed [PubSub](https://mastra.ai/docs/server/pubsub) backend and use the `MASTRA_WORKERS` environment variable to control which workers start in each process.
|
|
@@ -374,7 +384,7 @@ kubectl scale deployment/orchestration-worker --replicas=3
|
|
|
374
384
|
kubectl scale deployment/background-task-worker --replicas=2
|
|
375
385
|
```
|
|
376
386
|
|
|
377
|
-
|
|
387
|
+
You can run more than one scheduler worker. Each schedule occurrence is claimed by one instance, as described in [Scheduler worker](#scheduler-worker).
|
|
378
388
|
|
|
379
389
|
### Health checks
|
|
380
390
|
|
|
@@ -384,16 +394,18 @@ Worker build artifacts expose `GET /health` on `PORT`, or port `4111` when `PORT
|
|
|
384
394
|
|
|
385
395
|
A distributed PubSub backend persists unacknowledged events, which lets orchestration and background task workers resume after a restart. When the API is unavailable, a failed step-execution request causes the event to be delivered again.
|
|
386
396
|
|
|
397
|
+
When a worker stops during an evented workflow step, the broker redelivers the step's event to another worker after `reclaimIdleMs` (60 seconds by default) with Redis or Valkey Streams, or after the ack deadline with Google Cloud Pub/Sub, so instances that boot meanwhile don't restart the run. Keep `reclaimIdleMs` at 30 seconds or more: an event reclaimed sooner can arrive while the stopped worker's hold on the step is still active, and is dropped.
|
|
398
|
+
|
|
387
399
|
A step can run more than once. If a worker stops during a step, or after the step finishes but before it publishes the result, the step runs again when its event is redelivered. Make steps with side effects idempotent. See [restarting active workflow runs](https://mastra.ai/docs/workflows/overview) for how to build an idempotency key for a step, and [make tools safe to repeat](https://mastra.ai/docs/harness/durable-agents) for agent tools.
|
|
388
400
|
|
|
389
401
|
The scheduler calculates the next fire time from the current time after it restarts. It doesn't replay schedules that elapsed while it was unavailable.
|
|
390
402
|
|
|
391
|
-
If
|
|
403
|
+
If an instance crashes while a default-engine workflow run is executing, the [recovery loop](https://mastra.ai/docs/workflows/overview) of an instance running the orchestration worker restarts the run at the first pass after the run's lease expired and `recovery.workflowGraceMs` passed. A `mastra worker` process calls `stopWorkers()` on `SIGTERM` and exits without `shutdown()`. The default-engine runs it was executing wait as long as a crashed instance's. See [known limitations](#known-limitations) and [durable agent crash recovery](https://mastra.ai/docs/harness/durable-agents).
|
|
392
404
|
|
|
393
405
|
## Known limitations
|
|
394
406
|
|
|
395
407
|
- **No dead-letter queue**: Failed events are nacked and retried, but there's no DLQ for events that fail after all retries.
|
|
396
|
-
- **
|
|
408
|
+
- **Schedule occurrences can be lost**: If a scheduler crashes or can't publish after claiming an occurrence, that occurrence might not fire, and Mastra doesn't replay it automatically.
|
|
397
409
|
- **Runs stuck in "running" after API crash**: A crash during workflow-step execution leaves the run in `running` status without an automatic retry. For [durable agents](https://mastra.ai/docs/harness/durable-agents), configure `recovery.durableAgents: 'auto'` so a server restart automatically re-drives orphaned runs. See [Crash recovery](https://mastra.ai/docs/harness/durable-agents) for details.
|
|
398
410
|
|
|
399
411
|
## Related
|
|
@@ -82,7 +82,19 @@ Choose the narrowest boundary that matches how people should share state:
|
|
|
82
82
|
| Shared memory for an organization | `user.organizationId` |
|
|
83
83
|
| User memory within a workspace and project | `${workspaceId}:${projectId}:${userId}` |
|
|
84
84
|
|
|
85
|
-
Mastra applies this boundary automatically to memory and thread operations. Application code can continue using the authenticated user in `RequestContext` when it authorizes database records or external services.
|
|
85
|
+
Mastra applies this boundary automatically to memory and thread operations, including Observational Memory. `GET /api/memory/observational-memory`, `POST /api/memory/observational-memory/buffer-status`, and the Observational Memory details in `GET /api/memory/status` return `403` when the requested thread belongs to another resource or an [FGA](https://mastra.ai/docs/auth/fga) check denies it. Without `server.auth`, these routes use the `resourceId` and `threadId` the client sends, but a thread paired with a different `resourceId` still gets `403`. Application code can continue using the authenticated user in `RequestContext` when it authorizes database records or external services.
|
|
86
|
+
|
|
87
|
+
### User IDs from JWT providers
|
|
88
|
+
|
|
89
|
+
[`MastraJwtAuth`](https://mastra.ai/reference/auth/jwt), [Auth0](https://mastra.ai/reference/auth/auth0), and [Clerk](https://mastra.ai/reference/auth/clerk) set the authenticated user's `id` to the token's `sub` claim when the token has no `id` claim. A token with its own `id` claim keeps it. RBAC loads roles by `id`, and `id` is also the owner of the records a user creates when `mapUserToResourceId` isn't set.
|
|
90
|
+
|
|
91
|
+
Without `mapUserToResourceId`, this means:
|
|
92
|
+
|
|
93
|
+
- Each user sees their own stored agents, skills, workspaces, and other owned records plus public ones. Records they create are owned by them and private by default. Records created before your app used these user IDs have no owner and stay visible to everyone. Users with an admin permission such as `stored-agents:admin` still see every record.
|
|
94
|
+
- Per-author tool-provider connections are stored under the user's `id`. Connections saved under the shared `default` owner aren't found, so users reconnect them. Shared connections aren't affected.
|
|
95
|
+
- Feedback is recorded with the user's `id` as the user ID.
|
|
96
|
+
|
|
97
|
+
To keep every user in one shared resource instead, pass `mapUserToResourceId: () => 'default'` to the auth provider. This also shares memory and owned records between all users, so use it only when that's how your app should work.
|
|
86
98
|
|
|
87
99
|
## Enforce identity at the data boundary
|
|
88
100
|
|
|
@@ -280,6 +280,8 @@ const controller = new AgentController({
|
|
|
280
280
|
})
|
|
281
281
|
```
|
|
282
282
|
|
|
283
|
+
Calls to tools the rules allow don't pause the run. On a regular `Agent`, tool calls in one step run concurrently when none of them needs approval or can suspend. Durable agents run them one at a time unless the session's `yolo` state is on.
|
|
284
|
+
|
|
283
285
|
Configure category policies with [`session.permissions.setForCategory()`](https://mastra.ai/reference/agent-controller/session) and tool policies with [`session.permissions.setForTool()`](https://mastra.ai/reference/agent-controller/session):
|
|
284
286
|
|
|
285
287
|
```typescript
|
|
@@ -123,6 +123,8 @@ The `_background` override only _modifies_ tools the developer has already opted
|
|
|
123
123
|
|
|
124
124
|
When a tool call is dispatched, agent-level and tool-level settings determine eligibility and fallback values. For an eligible tool, the LLM `_background` fields override the corresponding values for that call. Manager defaults fill timeout and retry values that remain unset. An `_background` field can't enable a tool that's not eligible.
|
|
125
125
|
|
|
126
|
+
A timeout of `0` means no timeout. Set `timeoutMs: 0` on a tool or agent tool entry, or `defaultTimeoutMs: 0` on the manager, for tasks that should run until they finish or are cancelled.
|
|
127
|
+
|
|
126
128
|
If the agent has `backgroundTasks.disabled: true`, every tool call runs synchronously regardless of the layers above.
|
|
127
129
|
|
|
128
130
|
## Background tasks related stream chunks
|
|
@@ -191,7 +193,7 @@ export const mastra = new Mastra({
|
|
|
191
193
|
|
|
192
194
|
When a deferred task finishes and no `untilIdle` stream is open for its thread, Mastra sends the agent a `notification` signal with the tag `background-task`. The signal names the tool call and task, and tells the agent the result is now on the tool call. It doesn't copy the result into the prompt. This covers a `stream()` call without `untilIdle`, a client that disconnected, and a task resumed after it [suspended](#suspending-and-resuming).
|
|
193
195
|
|
|
194
|
-
- If the thread is idle, the signal wakes the agent, which runs a turn on the thread to report the outcome. The woken run uses the request context of the run that dispatched the task, so a model, instructions, or memory resolved from that context resolve the same way.
|
|
196
|
+
- If the thread is idle, the signal wakes the agent, which runs a turn on the thread to report the outcome. The woken run uses the request context of the run that dispatched the task, so a model, instructions, or memory resolved from that context resolve the same way. This also holds when the agent that claimed the thread runs on another server: the context is sent along with the signal, minus the auth token, the signed-in user, and any values that can't be sent as JSON or are too large to serialize. That server's run keeps its own auth token and user.
|
|
195
197
|
- If a run is already active on the thread, including the run that dispatched the task, the signal is delivered to that run's next model request. If that run ends without making another request, the signal runs as its own turn.
|
|
196
198
|
- If another agent's run holds the thread, for example while it waits for a tool approval, the signal waits and wakes the agent once that run ends.
|
|
197
199
|
- If an `untilIdle` stream is open for the thread, no signal is sent, because that stream runs its own follow-up turn.
|
|
@@ -123,7 +123,7 @@ await support.generate('How do I handle a chargeback?', {
|
|
|
123
123
|
})
|
|
124
124
|
```
|
|
125
125
|
|
|
126
|
-
With Memory, the run also holds the `resource:` and `thread:` scopes from the `memory` option, here `resource:dana` and `thread:ticket-91`. A run can hold only one of each. If you pass a `resource:` scope that differs from `memory.resource`, the run fails.
|
|
126
|
+
With Memory, the run also holds the `resource:` and `thread:` scopes from the `memory` option, here `resource:dana` and `thread:ticket-91`. A run can hold only one of each. If you pass a `resource:` scope that differs from `memory.resource`, the run fails. `resource:` and `thread:` scopes take Memory's IDs unchanged, and Knowledge encodes them. Every other scope is a canonical address: encode an ID that contains `:`, `/`, `#` or `%` with [`encodeKnowledgeScopeId()`](https://mastra.ai/reference/knowledge/knowledge-memory-scopes), such as `` `org:${encodeKnowledgeScopeId(user.orgId)}` ``.
|
|
127
127
|
|
|
128
128
|
### For one agent
|
|
129
129
|
|
|
@@ -192,8 +192,13 @@ import { Workspace } from '@mastra/core/workspace'
|
|
|
192
192
|
import { DaytonaSandbox } from '@mastra/daytona'
|
|
193
193
|
import { S3Filesystem } from '@mastra/s3'
|
|
194
194
|
|
|
195
|
-
const getThreadId = (requestContext: RequestContext) =>
|
|
196
|
-
requestContext.get(MASTRA_THREAD_ID_KEY)
|
|
195
|
+
const getThreadId = (requestContext: RequestContext) => {
|
|
196
|
+
const threadId = requestContext.get(MASTRA_THREAD_ID_KEY)
|
|
197
|
+
if (typeof threadId !== 'string' || !threadId) {
|
|
198
|
+
throw new Error('MASTRA_THREAD_ID_KEY is not set on the request context')
|
|
199
|
+
}
|
|
200
|
+
return threadId
|
|
201
|
+
}
|
|
197
202
|
|
|
198
203
|
const createThreadFilesystem = (threadId: string) =>
|
|
199
204
|
new S3Filesystem({
|
|
@@ -219,6 +224,22 @@ const workspace = new Workspace({
|
|
|
219
224
|
})
|
|
220
225
|
```
|
|
221
226
|
|
|
227
|
+
Resolvers receive only the request context, so the thread ID has to be on it. `agent.stream()` and `agent.generate()` don't copy `memory.thread` to `MASTRA_THREAD_ID_KEY`, so set the key yourself from a trusted thread ID, either in [server middleware](https://mastra.ai/docs/server/request-context) or when you call the agent:
|
|
228
|
+
|
|
229
|
+
```typescript
|
|
230
|
+
import { MASTRA_THREAD_ID_KEY, RequestContext } from '@mastra/core/request-context'
|
|
231
|
+
|
|
232
|
+
const requestContext = new RequestContext()
|
|
233
|
+
requestContext.set(MASTRA_THREAD_ID_KEY, threadId)
|
|
234
|
+
|
|
235
|
+
await agent.stream(message, {
|
|
236
|
+
memory: { thread: threadId, resource: userId },
|
|
237
|
+
requestContext,
|
|
238
|
+
})
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
`getThreadId()` throws when the key is missing, so a request without a thread fails instead of sharing a `threads/undefined` prefix and sandbox with every other such request.
|
|
242
|
+
|
|
222
243
|
The first request in a thread runs the resolver and starts the sandbox. Later requests with the same thread ID reuse the cached sandbox. A different thread ID creates a different sandbox and storage prefix.
|
|
223
244
|
|
|
224
245
|
The example mounts the filesystem inside the resolver because static `mounts` can't be combined with a sandbox resolver. Generated tools resolve the filesystem and sandbox from the request context automatically.
|
package/.docs/docs/server/mcp.md
CHANGED
|
@@ -72,6 +72,35 @@ npx @modelcontextprotocol/inspector --cli http://localhost:4111/api/mcp \
|
|
|
72
72
|
--transport http --header "Authorization: Bearer $MASTRA_TOKEN" --method tools/list
|
|
73
73
|
```
|
|
74
74
|
|
|
75
|
+
Cursor and VS Code read the server from a JSON file. Add it to `.cursor/mcp.json` for Cursor:
|
|
76
|
+
|
|
77
|
+
```json
|
|
78
|
+
{
|
|
79
|
+
"mcpServers": {
|
|
80
|
+
"mastra": {
|
|
81
|
+
"url": "http://localhost:4111/api/mcp",
|
|
82
|
+
"headers": { "Authorization": "Bearer <your-token>" }
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Or to `.vscode/mcp.json` for VS Code:
|
|
89
|
+
|
|
90
|
+
```json
|
|
91
|
+
{
|
|
92
|
+
"servers": {
|
|
93
|
+
"mastra": {
|
|
94
|
+
"type": "http",
|
|
95
|
+
"url": "http://localhost:4111/api/mcp",
|
|
96
|
+
"headers": { "Authorization": "Bearer <your-token>" }
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Leave out `headers` when the server runs without `server.auth`. Clients that take only a URL and can't send an `Authorization` header, such as custom connectors in the Claude apps, need [OAuth discovery](#oauth-discovery) and an identity provider that lets them sign in.
|
|
103
|
+
|
|
75
104
|
The endpoint uses stateless Streamable HTTP and speaks both MCP `2026-07-28` and the 2025 revisions that current clients use, so no session is kept between requests.
|
|
76
105
|
|
|
77
106
|
### In Studio
|
|
@@ -86,6 +115,8 @@ Studio reads this from `GET /api/mcp/builtin`, which needs the `mcp:read` permis
|
|
|
86
115
|
|
|
87
116
|
The server groups tools into toolsets. This section covers `agents`, `workflows`, and `tools`; see [Memory, observability, and agent builder](#memory-observability-and-agent-builder) for the others. Agents and workflows are reached through operation tools that take the id as an argument. The tool list stays the same size however many agents you add.
|
|
88
117
|
|
|
118
|
+
See the [built-in MCP tools reference](https://mastra.ai/reference/server/builtin-mcp-tools) for every tool's arguments, route, and permission.
|
|
119
|
+
|
|
89
120
|
| Toolset | Tools | Backing HTTP route |
|
|
90
121
|
| ----------- | -------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
91
122
|
| `agents` | `list_agents`, `get_agent`, `call_agent` | `GET /agents`, `GET /agents/:agentId`, `POST /agents/:agentId/generate` |
|
|
@@ -189,7 +220,7 @@ In read-only mode, the query and aggregate tools stay available because their ro
|
|
|
189
220
|
|
|
190
221
|
### Agents creating agents
|
|
191
222
|
|
|
192
|
-
`create_stored_agent` lets an MCP client create agents that other clients can then call. It needs `stored-agents:write`. A created agent
|
|
223
|
+
`create_stored_agent` lets an MCP client create agents that other clients can then call. It needs `stored-agents:write`. A created agent is owned by the caller and is private by default. Without a caller identity, such as when `server.auth` isn't configured, the agent has no owner and is public, even with `visibility: 'private'`. Other users don't see a private agent in `list_agents` or `list_stored_agents`, and unless they're admins or granted that agent by id, calling it answers as if it doesn't exist, the same as over HTTP. Set `visibility: 'public'` to let every user call it. Only the owner, admins, and users granted that agent by id can edit it either way. An agent with no owner can be edited by any user with `stored-agents:write`. See [stored agent visibility](https://mastra.ai/docs/studio/editor). When the agent builder restricts models, the MCP tools accept only allowed models for the agent's model (the `provider` and `name` it runs, in each conditional variant), for any model named in `defaultOptions` (such as `structuredOutput.model`), for each enabled entry of the fallback `modelList`, for the memory models (the Observational Memory observer and reflector models and the title model), and for the `model` of every input and output processor step, at any depth of the processor graph. They also reject anything that would run on a default model the policy can't check: `observationalMemory: true`, an Observational Memory config without a `model`, memory left out on create (which the agent builder fills with Observational Memory on its default model), or a processor that needs a model, such as `moderation`, without one. Set an allowed `model` instead. A stored `model` takes only `provider`, `name`, and model settings such as `temperature`. Other keys, such as `modelId` or `providerId`, are rejected. If the agent builder's policy can't be loaded, the tools return an error instead of saving unchecked. `list_available_models` returns the allowed models. The HTTP route doesn't apply this check, so a user who can call `POST /stored/agents` directly can still save any model. Embedding models (`memory.embedder`) aren't on the builder's model list and aren't checked. Tool allowlists aren't checked when an agent is saved, so a created agent can use any tool the server has. Its tools run with the permissions of the user who calls it.
|
|
193
224
|
|
|
194
225
|
Observational Memory starts observing only after a thread reaches its token threshold, 30,000 tokens by default. For a short demo, set a lower `observation.messageTokens` so the agent learns from a few messages. Observational Memory processes messages in the background, so right after `call_agent`, call `get_observations` with `waitForPending: true` to wait (up to 30 seconds) for it to finish before reading.
|
|
195
226
|
|
|
@@ -308,6 +339,7 @@ The endpoint doesn't return `403` with `error="insufficient_scope"` yet. A calle
|
|
|
308
339
|
|
|
309
340
|
## Related
|
|
310
341
|
|
|
342
|
+
- [Built-in MCP tools reference](https://mastra.ai/reference/server/builtin-mcp-tools)
|
|
311
343
|
- [`server.mcp` configuration reference](https://mastra.ai/reference/configuration)
|
|
312
344
|
- [MCP connections](https://mastra.ai/docs/connections/mcp)
|
|
313
345
|
- [Authentication overview](https://mastra.ai/docs/auth/overview)
|
|
@@ -16,6 +16,7 @@ Mastra runs as an HTTP server that exposes your agents, workflows, and other fun
|
|
|
16
16
|
- **[Server Adapters](https://mastra.ai/docs/server/server-adapters)**: Run Mastra with Express, Hono, or your own HTTP server instead of the generated server.
|
|
17
17
|
- **[Custom Adapters](https://mastra.ai/docs/server/custom-adapters)**: Build adapters for frameworks not officially supported.
|
|
18
18
|
- **[Mastra Client SDK](https://mastra.ai/docs/server/mastra-client)**: Type-safe client for calling agents, workflows, and tools from browser or server environments.
|
|
19
|
+
- **[Built-in MCP server](https://mastra.ai/docs/server/mcp)**: Let MCP clients such as Claude Code and Cursor call your agents, workflows, and tools at `/api/mcp`, with the same auth and permissions as the HTTP API.
|
|
19
20
|
- **[A2A](https://mastra.ai/docs/connections/a2a)**: Expose agents through A2A agent cards and task streams, plus push notifications.
|
|
20
21
|
- **[Authentication](https://mastra.ai/docs/auth/overview)**: Secure endpoints with JWT, Clerk, Supabase, Firebase, Auth0, or WorkOS.
|
|
21
22
|
|
|
@@ -328,7 +328,7 @@ requestContext.set(MASTRA_THREAD_ID_KEY, threadId)
|
|
|
328
328
|
| Key | Purpose |
|
|
329
329
|
| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
330
330
|
| `MASTRA_RESOURCE_ID_KEY` | Forces all memory operations to use this resource ID. The server validates that accessed threads belong to this resource and returns 403 if not. |
|
|
331
|
-
| `MASTRA_THREAD_ID_KEY` | Forces thread operations to use this thread ID, overriding client-provided values
|
|
331
|
+
| `MASTRA_THREAD_ID_KEY` | Forces thread operations to use this thread ID, overriding client-provided values. Passing `memory.thread` to an agent call leaves this key unset, so set it yourself wherever you rely on it, such as for a workspace resolver. Tools can read the current run's thread from `context.agent.threadId` instead. |
|
|
332
332
|
| `MASTRA_SCOPES_KEY` | Sets the [scopes](https://mastra.ai/docs/memory/overview) the agent run acts as, as an array of `<type>:<value>` strings. Combined with per-call `scopes`; the agent's `scopes` list adds to them, and a `scopes` function replaces them. A `resource:` or `thread:` scope that conflicts with another resource or thread value returns a 400 error. |
|
|
333
333
|
| `MASTRA_MESSAGE_AUTHOR_KEY` | Names who sent a user message as `{ id, name?, avatarUrl? }`. Agent-controller sessions persist it at `content.metadata.signal.author` and mirror it to `providerMetadata.mastra.author` for compatibility, so a thread shared by several people can show who wrote what. |
|
|
334
334
|
|
|
@@ -448,6 +448,7 @@ Without this call, the following features never run:
|
|
|
448
448
|
- [Scheduled workflows](https://mastra.ai/docs/workflows/scheduled-workflows): Schedule rows aren't created and cron triggers don't fire.
|
|
449
449
|
- [Agent schedules](https://mastra.ai/docs/harness/schedules) created with `mastra.schedules`
|
|
450
450
|
- Event listeners you've registered on the Mastra instance
|
|
451
|
+
- The [recovery loop](https://mastra.ai/docs/workflows/overview): Default-engine workflow runs whose instance stops after this server booted aren't restarted.
|
|
451
452
|
|
|
452
453
|
Call `startWorkers()` once, after the server starts listening:
|
|
453
454
|
|
|
@@ -506,6 +507,8 @@ const server = new MastraServer({
|
|
|
506
507
|
|
|
507
508
|
With this prefix, Mastra routes become `/api/v2/agents`, `/api/v2/workflows`, etc. Custom routes you add directly to the app aren't affected by this prefix.
|
|
508
509
|
|
|
510
|
+
The [built-in MCP server](https://mastra.ai/docs/server/mcp) moves with the prefix to `/api/v2/mcp`. Its OAuth metadata stays at the server root, at `/.well-known/oauth-protected-resource/api/v2/mcp`.
|
|
511
|
+
|
|
509
512
|
## OpenAPI spec
|
|
510
513
|
|
|
511
514
|
Mastra can generate an OpenAPI specification for all registered routes. This is useful for documentation or client generation, including integration with API tools. Enable it by setting the `openapiPath` option:
|
|
@@ -126,7 +126,11 @@ Permissions follow the pattern `{resource}:{action}`, with optional resource-lev
|
|
|
126
126
|
| `agents:execute` | Execute agents only |
|
|
127
127
|
| `agents:read:my-id` | Read a specific agent by ID |
|
|
128
128
|
|
|
129
|
-
Resources include `agents`, `workflows`, `tools`, `datasets`, `memory`, `scores`, `observability`, and others. Actions are `read`, `write`, `create`, `delete`, `execute`, `publish`, and `share`.
|
|
129
|
+
Resources include `agents`, `workflows`, `tools`, `datasets`, `memory`, `scores`, `observability`, `stored-agents`, `mcp`, and others. Actions are `read`, `write`, `create`, `delete`, `execute`, `publish`, and `share`.
|
|
130
|
+
|
|
131
|
+
`mcp:read` and `mcp:execute` gate the [built-in MCP server](https://mastra.ai/docs/server/mcp) and the routes of `MCPServer` instances you register. The default `viewer` role has `mcp:read` only, so a viewer can connect but gets an empty tool list. Each MCP tool call also needs the permission of the route it runs, such as `agents:execute`.
|
|
132
|
+
|
|
133
|
+
Stored agents are private to their owner by default. `stored-agents:*` lets a user see and edit every stored agent. `stored-agents:admin` lifts the owner check, but the user still needs each route's own permission, such as `stored-agents:read` or `stored-agents:write`. The default `admin` role doesn't include either. See [stored agent visibility](https://mastra.ai/docs/studio/editor).
|
|
130
134
|
|
|
131
135
|
### Map external provider roles
|
|
132
136
|
|
|
@@ -331,6 +331,23 @@ The same version controls work when a supervisor calls sub-agents. Developers ca
|
|
|
331
331
|
|
|
332
332
|
See the [Editor versioning reference](https://mastra.ai/reference/editor/versioning) for version selection, sub-agent behavior, REST endpoints, and SDK methods.
|
|
333
333
|
|
|
334
|
+
## Visibility
|
|
335
|
+
|
|
336
|
+
With [`server.auth`](https://mastra.ai/docs/auth/overview) configured, every stored agent has an owner and a `visibility`. An agent created in Studio, through `POST /api/stored/agents`, or with the [built-in MCP server](https://mastra.ai/docs/server/mcp) is owned by the user who created it and is `private` unless they set `visibility: 'public'`. The owner is the caller's resource ID from `mapUserToResourceId`, or the user's `id` without it. Without `server.auth`, or when the caller has neither, stored agents have no owner, are `public`, and every caller can use them.
|
|
337
|
+
|
|
338
|
+
| Who | Can see and call a private agent | Can edit or delete it |
|
|
339
|
+
| -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------- |
|
|
340
|
+
| Owner | Yes | Yes |
|
|
341
|
+
| Users with `*`, `stored-agents:*`, or `stored-agents:admin` | Yes | Yes |
|
|
342
|
+
| Users granted that agent by id, for example `stored-agents:read:support-agent` or `stored-agents:edit:support-agent` | Yes, with a `read` grant. An `execute` grant only lets them call it | Yes, with an `edit` or `delete` grant |
|
|
343
|
+
| Everyone else | No | No |
|
|
344
|
+
|
|
345
|
+
The table covers ownership only. Each route still checks its own permission, such as `stored-agents:write` to edit or `agents:execute` to call, so an admin or id grant works only alongside the route permission. A grant by id only works when the agent is requested by its id. The agent still doesn't appear in their `GET /api/agents` or `GET /api/stored/agents` list.
|
|
346
|
+
|
|
347
|
+
A `public` agent can be seen and called by every user, but only the users in the table can edit or delete it. Agents saved before they had an owner stay visible to everyone, and any user with the route permission can edit or delete them. Code-defined agents aren't affected, including ones with Editor overrides.
|
|
348
|
+
|
|
349
|
+
The rules apply to every route that looks up an agent, not only `/api/stored/agents`. To another user, a private agent behaves like an agent that doesn't exist: `GET /api/agents` leaves it out, the agent, version, workspace, and schedule routes for it answer `404`, and the memory routes answer as they would for a missing agent. Changing its model at runtime with `POST /api/agents/:agentId/model` needs edit access. `POST /api/agents/:agentId/clone` makes the caller the owner of a private clone and ignores an `authorId` in the body.
|
|
350
|
+
|
|
334
351
|
## Programmatic access
|
|
335
352
|
|
|
336
353
|
Everything available in Studio is also available programmatically through [`mastra.getEditor()`](https://mastra.ai/reference/core/getEditor), the REST API, or the Client SDK. Use it to script bulk updates or seed stored configurations from code. It can also power automation that tunes agents based on [evaluation results](https://mastra.ai/docs/evals/experiments).
|
|
@@ -91,6 +91,40 @@ An `authorize` function replaces the server's rules and role checks for every ro
|
|
|
91
91
|
|
|
92
92
|
Set the value to an array of scopes, or `'all'` for someone who should see the whole instance. An empty array reads nothing. See [Knowledge access and errors](https://mastra.ai/reference/server/routes) for what other values return. If you configure `studio.auth`, Studio requests use it instead of `server.auth`, so set the key in that `authorize`.
|
|
93
93
|
|
|
94
|
+
### Providers with `authorizeUser`
|
|
95
|
+
|
|
96
|
+
The server never calls `authorize` when the auth provider defines `authorizeUser`. This includes any `MastraAuthProvider` subclass that implements it, and every `CompositeAuth`. For these providers, set the key in a [server middleware](https://mastra.ai/docs/server/middleware) instead:
|
|
97
|
+
|
|
98
|
+
```typescript
|
|
99
|
+
import { Mastra } from '@mastra/core/mastra'
|
|
100
|
+
import { KNOWLEDGE_ROUTES, MASTRA_KNOWLEDGE_PRINCIPALS_KEY } from '@mastra/server/server-adapter'
|
|
101
|
+
import { auth, getSessionUser } from './auth' // your provider and session lookup
|
|
102
|
+
|
|
103
|
+
export const mastra = new Mastra({
|
|
104
|
+
server: {
|
|
105
|
+
apiRoutes: [...KNOWLEDGE_ROUTES],
|
|
106
|
+
auth,
|
|
107
|
+
middleware: [
|
|
108
|
+
{
|
|
109
|
+
path: '/api/knowledge/*',
|
|
110
|
+
handler: async (c, next) => {
|
|
111
|
+
const user = await getSessionUser(c.req.raw)
|
|
112
|
+
if (user) {
|
|
113
|
+
c.get('requestContext').set(
|
|
114
|
+
MASTRA_KNOWLEDGE_PRINCIPALS_KEY,
|
|
115
|
+
user.isAdmin ? 'all' : [`org:${user.orgId}`, `team:${user.orgId}:${user.teamId}`],
|
|
116
|
+
)
|
|
117
|
+
}
|
|
118
|
+
await next()
|
|
119
|
+
},
|
|
120
|
+
},
|
|
121
|
+
],
|
|
122
|
+
},
|
|
123
|
+
})
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
Server middleware runs before the route's auth check, so the signed-in user isn't on the request context yet. Look the user up from the request with your app's own session check, as above. The route's auth still runs afterwards and rejects callers your provider doesn't accept. Change the middleware `path` if you set a different prefix.
|
|
127
|
+
|
|
94
128
|
### Deployment notes
|
|
95
129
|
|
|
96
130
|
- **No RBAC provider:** the `knowledge:read` check is skipped, so any authenticated user with a principal mapping can read the pages those principals cover, in every instance.
|
|
@@ -97,7 +97,7 @@ See [processors](https://mastra.ai/docs/agents/processors) and [guardrails](http
|
|
|
97
97
|
|
|
98
98
|
### MCP servers
|
|
99
99
|
|
|
100
|
-
List the MCP servers attached to your Mastra instance and explore their available tools.
|
|
100
|
+
List the MCP servers attached to your Mastra instance and explore their available tools. The list starts with **Mastra (built-in)**, the [built-in MCP server](https://mastra.ai/docs/server/mcp) at `/api/mcp`, with its endpoint URL, whether it needs a token, and setup for Claude Code, Cursor, VS Code, and the MCP Inspector.
|
|
101
101
|
|
|
102
102
|
### Tools
|
|
103
103
|
|
|
@@ -500,9 +500,13 @@ Runs restart concurrently, up to `recovery.workflowConcurrency` at a time (defau
|
|
|
500
500
|
|
|
501
501
|
To exclude a workflow from automatic boot-time restarts triggered by `Mastra.restartAllActiveWorkflowRuns()`, set `autoRestartActiveRuns: false` in the workflow's `options`. This is useful for workflows with side effects that must not be re-driven by a blanket restart. Durable agent workflows set this automatically because their recovery is owned by the opt-in `recovery.durableAgents: 'auto'` path.
|
|
502
502
|
|
|
503
|
-
While a run executes, Mastra holds a storage lease on it and renews it in the background. `restart()` refuses to take over a run whose lease hasn't expired: it throws a `WORKFLOW_RESTART_RUN_OWNED` error and the sweep skips the run. The lease is advisory and doesn't fence writes. If a process stops renewing its lease but keeps executing a step, for example because its event loop is blocked for longer than the lease TTL, recovery can run that step a second time.
|
|
503
|
+
While a run executes, Mastra holds a storage lease on it and renews it in the background. `restart()` refuses to take over a run whose lease hasn't expired: it throws a `WORKFLOW_RESTART_RUN_OWNED` error and the sweep skips the run. The lease is advisory and doesn't fence writes. If a process stops renewing its lease but keeps executing a step, for example because its event loop is blocked for longer than the lease TTL, recovery can run that step a second time. `workflow.restartAllActiveWorkflowRuns()` skips such a run without a recheck, so call it after the lease expires if you need to recover that run. Storage adapters without run-ownership support keep the previous behavior and restart every active run.
|
|
504
504
|
|
|
505
|
-
|
|
505
|
+
`mastra.restartAllActiveWorkflowRuns()`, which the server calls on boot, restarts a default-engine run only once it stopped: no instance holds its lease, and neither the run nor its lease changed for `recovery.workflowGraceMs` (2 seconds by default). A run that's still running, or stopped more recently, is left to the [recovery loop](#recovery-loop).
|
|
506
|
+
|
|
507
|
+
Evented runs on a pubsub whose broker redelivers unacknowledged events (Redis Streams, Valkey Streams, Google Cloud Pub/Sub) are left to the broker: when a worker stops mid-step, the broker redelivers the step's event to another worker, and booting instances don't restart the run. Scheduled runs are the exception, because their events stay in the process that fired them, so recovery restarts them. On any other pubsub, including the default in-process one, recovery restarts every active evented run at once. The in-process pubsub delivers events only inside one process, so running several instances on one storage with it isn't supported for evented workflows.
|
|
508
|
+
|
|
509
|
+
A restarted run runs the interrupted step again, even if that step finished before the process stopped but its result wasn't saved. On the evented engine, a step that already saved its result doesn't run again when its event arrives late, for example after a broker redelivery or a `restart()` that ran while the step was saving its result. The run continues from the saved result instead. This needs a storage adapter with run-ownership support. Workflows that set `autoRestartActiveRuns: false`, including durable agent workflows, run the step again. Make steps with side effects idempotent, so a repeated step has no additional effect.
|
|
506
510
|
|
|
507
511
|
A step's `execute` function receives `runId` and `workflowId`. Combine them with the `id` you gave the step in `createStep()`, plus a name for each side effect when the step performs more than one, to build an idempotency key.
|
|
508
512
|
|
|
@@ -514,6 +518,20 @@ Some steps need part of the key to come from their input:
|
|
|
514
518
|
|
|
515
519
|
For tools that agents call, see [make tools safe to repeat](https://mastra.ai/docs/harness/durable-agents).
|
|
516
520
|
|
|
521
|
+
### Recovery loop
|
|
522
|
+
|
|
523
|
+
`mastra.startWorkers()` also starts a recovery loop on an instance that runs the orchestration worker. Every `recovery.workflowScanIntervalMs` (60 seconds by default, give or take a fifth), it restarts the default-engine runs that stopped, by the same rule as `restartAllActiveWorkflowRuns()`. A run whose instance crashed is restarted at the first pass after its lease expired (`MASTRA_AGENT_THREAD_LEASE_TTL_MS`, 15 seconds by default) and `recovery.workflowGraceMs` passed. When a pass finds a run in its grace period, the next pass runs once that period ends, but no sooner than a second later.
|
|
524
|
+
|
|
525
|
+
Instances that share a storage adapter elect one loop leader through a lease row in storage. Only the leader's loop lists runs. The loops of the other instances only try to take its place. The leader keeps the role until its `stopWorkers()` or `shutdown()` hands it back, or until its lease expires after a crash. With `restartAllActiveWorkflowRuns()` at boot, each instance still restarts its own stopped default-engine runs, whichever instance leads. Between boots, the loop recovers only the workflows the leader registers, so instances that register different workflows on one storage get loop recovery for the leader's workflows only and the others' runs at their next boot. A run the loop restarts executes on the leader.
|
|
526
|
+
|
|
527
|
+
```typescript
|
|
528
|
+
export const mastra = new Mastra({
|
|
529
|
+
recovery: { workflowScanIntervalMs: 30_000 },
|
|
530
|
+
})
|
|
531
|
+
```
|
|
532
|
+
|
|
533
|
+
The loop never restarts evented runs. A broker that redelivers unacknowledged events recovers them, and on other pubsubs `restartAllActiveWorkflowRuns()` restarts them at boot. The loop also leaves workflows that set `autoRestartActiveRuns: false` alone, and an instance that registers no other default-engine workflow never claims the leader row. It doesn't run when `recovery.workflows` is `'off'`, on an instance started with `workers: false` or a `MASTRA_WORKERS` filter without `orchestration`, or on a storage adapter without run-ownership support. A process that calls `restartAllActiveWorkflowRuns()` but never `startWorkers()` runs no loop.
|
|
534
|
+
|
|
517
535
|
### Restarting an active workflow run with `restart()`
|
|
518
536
|
|
|
519
537
|
Use `restart()` to restart an active workflow run from the last active step. This will resume execution from the last active step, and the workflow will continue from there.
|
|
@@ -537,7 +555,7 @@ if (activeRuns.runs.length > 0) {
|
|
|
537
555
|
}
|
|
538
556
|
```
|
|
539
557
|
|
|
540
|
-
> **Note:** When
|
|
558
|
+
> **Note:** When the Mastra server starts, it restarts the active workflow runs no instance is running anymore, and its recovery loop keeps doing so for default-engine runs.
|
|
541
559
|
|
|
542
560
|
## Using `RequestContext`
|
|
543
561
|
|
|
@@ -280,7 +280,7 @@ Before setting `replicaCount` above one or enabling `mastra-server.autoscaling`:
|
|
|
280
280
|
- Configure a distributed PubSub backend and shared cache. The [Kubernetes guide](https://mastra.ai/integrations/deploy/kubernetes) uses `RedisStreamsPubSub` and `RedisServerCache`, with `REDIS_URL` stored in the application Secret.
|
|
281
281
|
- Use [durable agents](https://mastra.ai/docs/harness/durable-agents) for streams, approvals, and runs that must continue when requests reach different pods.
|
|
282
282
|
- Start with one replica to initialize the database schema before scaling. For stricter deployments, initialize the schema in a Kubernetes Job and disable initialization in each pod.
|
|
283
|
-
- Review [worker roles](https://mastra.ai/docs/deployment/workers).
|
|
283
|
+
- Review [worker roles](https://mastra.ai/docs/deployment/workers). Multiple scheduler instances are safe, because each schedule occurrence is claimed by one instance.
|
|
284
284
|
|
|
285
285
|
After those requirements are in place, set resource requests and enable autoscaling:
|
|
286
286
|
|
|
@@ -309,7 +309,7 @@ Before enabling workers:
|
|
|
309
309
|
|
|
310
310
|
- **A pull-capable PubSub backend** configured in your Mastra application: Redis Streams, Valkey Streams, or Google Cloud Pub/Sub. Workers pull events from the broker, so request/response-only backends won't work. Put its connection string (for example `REDIS_URL`) in the same Secret the Server uses.
|
|
311
311
|
- **A storage backend that supports the `schedules` domain**, if you enable the scheduler: PostgreSQL, LibSQL, MySQL, MongoDB, Spanner, or Convex. Redis and ClickHouse don't support it, and the scheduler won't find due schedules on them.
|
|
312
|
-
- **`mastra-server.workers.splitDeployment: true`.** Without it the API keeps running workers in-process
|
|
312
|
+
- **`mastra-server.workers.splitDeployment: true`.** Without it the API keeps running workers in-process, so every worker also runs in the API pods alongside the worker Deployments. The chart refuses to render if you enable workers without it.
|
|
313
313
|
|
|
314
314
|
> **Redis eviction policy:** Set `maxmemory-policy` to `noeviction` on Redis or Valkey. Every evicting policy deletes live Mastra state under memory pressure: `allkeys-*` policies evict unacknowledged workflow events, and `volatile-*` policies evict lease keys and streams, which carry a TTL by default. Runs then stall without a run error. `RedisStreamsPubSub` and `ValkeyStreamsPubSub` log a one-time warning after they first connect when the policy can evict. On managed Redis this is a parameter-group setting, and Amazon ElastiCache defaults to `volatile-lru`.
|
|
315
315
|
|
|
@@ -388,11 +388,11 @@ Worker pods mount the **Server's** ConfigMap and Secret rather than defining the
|
|
|
388
388
|
|
|
389
389
|
### Roles and scaling
|
|
390
390
|
|
|
391
|
-
| Role | Scales | Notes
|
|
392
|
-
| ----------------- | ----------------- |
|
|
393
|
-
| `orchestration` | Yes | Consumes the `workflows` topic and calls back into the API to execute steps. The consumer group distributes work across replicas.
|
|
394
|
-
| `scheduler` | **No — always 1** | Polls storage for due cron schedules. The chart pins it to one replica and uses the `Recreate` strategy
|
|
395
|
-
| `backgroundTasks` | Yes | Executes agent tool calls marked `background: { enabled: true }` off the request path.
|
|
391
|
+
| Role | Scales | Notes |
|
|
392
|
+
| ----------------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
393
|
+
| `orchestration` | Yes | Consumes the `workflows` topic and calls back into the API to execute steps. The consumer group distributes work across replicas. |
|
|
394
|
+
| `scheduler` | **No — always 1** | Polls storage for due cron schedules. The chart pins it to one replica and uses the `Recreate` strategy. Extra schedulers are safe but add polling load without adding throughput. |
|
|
395
|
+
| `backgroundTasks` | Yes | Executes agent tool calls marked `background: { enabled: true }` off the request path. |
|
|
396
396
|
|
|
397
397
|
The two scalable roles support autoscaling. Utilization targets need matching resource requests, and the chart fails the render if you enable autoscaling without them:
|
|
398
398
|
|
|
@@ -443,7 +443,7 @@ kubectl rollout restart deploy -n mastra -l app.kubernetes.io/name=mastra-work
|
|
|
443
443
|
- Set resource requests via `mastra-server.resources` and `mastra-studio.resources`.
|
|
444
444
|
- Prefer standalone cert-manager and ingress controller installs over the bundled toggles; CRD lifecycle inside an umbrella chart complicates upgrades.
|
|
445
445
|
- Enable multiple replicas only after configuring shared storage, distributed PubSub, shared cache, and the required process roles.
|
|
446
|
-
- When running background workers, set `mastra-server.workers.splitDeployment: true
|
|
446
|
+
- When running background workers, set `mastra-server.workers.splitDeployment: true` and set `maxmemory-policy` to `noeviction` on Redis or Valkey.
|
|
447
447
|
- The chart applies hardened defaults: non-root containers, read-only root filesystem, seccomp `RuntimeDefault`, and no service account token automount.
|
|
448
448
|
|
|
449
449
|
## Upgrade and uninstall
|
|
@@ -476,7 +476,6 @@ Your database and object store are unaffected, because the chart never manages s
|
|
|
476
476
|
- **Pods crash-loop with a license error.** Production mode requires a valid `MASTRA_EE_LICENSE` in your secret when enterprise features are configured.
|
|
477
477
|
- **Studio shows the server API instead of the UI.** The image was built without Studio assets. Rebuild with `mastra build --studio`.
|
|
478
478
|
- **Worker pods crash-loop with `Cannot find module '/app/.mastra/worker/index.mjs'`.** The image was built without the worker artifact. Run `mastra worker build --output-dir .mastra/worker` and copy it into the image, or override `mastra-workers.command` to match your layout.
|
|
479
|
-
- **Scheduled workflows fire twice.** The API is still running workers in-process alongside the worker Deployments. Set `mastra-server.workers.splitDeployment: true`.
|
|
480
479
|
- **Workflows stall with no error.** The orchestration worker can't reach the API, or Redis evicted unacknowledged events. Check `mastra-workers.server.port` against `mastra-server.service.port`, confirm any restrictive NetworkPolicy admits worker pods, and verify `maxmemory-policy` is `noeviction`.
|
|
481
480
|
- **Worker pods stay in `CreateContainerConfigError`.** They mount the Server's ConfigMap and Secret, so `mastra-workers.server.existingSecret` must match `mastra-server.existingSecret`, and `mastra-workers` can't be installed as a standalone release.
|
|
482
481
|
- **Ingress has no address.** Confirm an ingress controller is running, or set `ingressController.install=true`.
|