Background tasks
Added in: @mastra/core@1.29.0
Background tasks let an agent dispatch a long-running tool call without blocking the agentic loop. The tool returns an immediate acknowledgement while the LLM continues responding. The task then runs to completion in the background. When it finishes, its result is written to memory and if you use stream() with the untilIdle option the agent is re-invoked automatically so the result is processed in the same call.
When to use background tasksDirect link to When to use background tasks
Use background tasks when a tool call may take long enough that the user shouldn't wait for it before seeing a response. Common cases:
- Subagent delegations that themselves run multi-step research or writing.
- Tool calls that hit slow external services, queues, or large data jobs.
- Workflows triggered from a tool call that may take minutes to complete.
For tool calls that return quickly, foreground execution using agent.stream() and agent.generate() is simpler.
Background tasks require a configured storage backend on the Mastra instance. Tasks are persisted so they survive process restarts.
QuickstartDirect link to Quickstart
Background tasks are off by default. Enable them by setting backgroundTasks.enabled on the Mastra instance:
import { Mastra } from '@mastra/core'
import { LibSQLStore } from '@mastra/libsql'
export const mastra = new Mastra({
storage: new LibSQLStore({ id: 'storage', url: 'file:mastra.db' }),
backgroundTasks: {
enabled: true,
globalConcurrency: 10,
perAgentConcurrency: 5,
backpressure: 'queue',
defaultTimeoutMs: 300_000,
},
})
The full set of options is listed in the backgroundTasks configuration reference.
Run a tool in the backgroundDirect link to Run a tool in the background
Enabling the manager doesn't run anything in the background by itself. Tools become eligible at one of two layers:
- Tool-level config: the tool itself declares it as background-eligible.
- Agent-level config: the agent declares which of its tools are background-eligible.
Eligible tools default to deferred execution. Set defaultDisposition: 'foreground' at either layer when eligibility should only give the LLM the option to run a call in the background. The LLM can include a _background field in the tool arguments to select foreground, deferred, or awaited execution for a specific call and override its timeout or retries.
Tool-levelDirect link to Tool-level
Set background.enabled: true on the tool definition. Tools opted in at this layer are eligible for background execution when called by an agent that has the manager enabled. Their configured default disposition determines whether each call runs inline or in the background unless the call includes a _background override.
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
export const researchTool = createTool({
id: 'research',
description: 'Run a long research job',
inputSchema: z.object({ topic: z.string() }),
background: {
enabled: true,
defaultDisposition: 'deferred',
timeoutMs: 600_000,
maxRetries: 1,
},
execute: async ({ topic }) => {
// Run the research job for topic
},
})
Agent-levelDirect link to Agent-level
Use backgroundTasks.tools on the agent to opt in specific tools or override timeouts for individual tools, or alternatively run all background-eligible tools in the background. Use disabled: true to short-circuit background dispatch for the agent entirely.
import { Agent } from '@mastra/core/agent'
export const researcher = new Agent({
id: 'researcher',
instructions: 'You research topics and answer questions.',
model: 'openai/gpt-5.6-sol',
tools: { researchTool, summarizeTool },
backgroundTasks: {
tools: {
researchTool: { enabled: true, timeoutMs: 600_000 },
summarizeTool: false,
},
},
})
Set tools: 'all' to opt in every tool the agent has.
LLM per-call overrideDirect link to LLM per-call override
When a tool is registered on an agent that has background tasks enabled, the model can include a _background field in the tool arguments to override the resolved configuration for that specific call. The model only includes what it wants to override, all fields in _background are optional. The override is stripped from the arguments before the tool runs.
{
"topic": "solana",
"_background": { "disposition": "awaited", "timeoutMs": 900000 }
}
The available dispositions are:
foreground: Run the tool synchronously without background-work lifecycle signals.deferred: Dispatch the tool and let the agent continue. The task remains attached to the run, and streams usinguntilIdlewait for it to reconcile.awaited: Dispatch the tool through the background task manager, but hold the current branch until its authoritative result has been reconciled.
For compatibility, _background.enabled: true selects deferred, and _background.enabled: false selects foreground. An explicit disposition takes precedence over enabled.
The _background override only modifies tools the developer has already opted in at the tool or agent layer. If a tool hasn't been opted in, a model-selected background disposition is ignored and the tool runs in the foreground. This keeps deterministic, foreground-only tools (calculators, lookups, schema validators) from being silently dispatched as tasks.
Resolution orderDirect link to Resolution order
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.
If the agent has backgroundTasks.disabled: true, every tool call runs synchronously regardless of the layers above.
Background tasks related stream chunksDirect link to Background tasks related stream chunks
When a tool call dispatches as a background task, two streams may surface lifecycle events for it: the agent's own stream and the backgroundTaskManager.stream() SSE stream. Each stream covers a different set of chunk types:
| Chunk type | When it fires | Emitted by |
|---|---|---|
background-task-started | The task has been enqueued and assigned a taskId. | Agent stream |
background-task-running | The task picked up a worker and started executing. | Manager stream |
background-task-progress | Shows number of running background tasks. | Agent stream |
background-task-output | A streamed output chunk from the task's execute. | Manager stream |
background-task-completed | The task finished successfully. The payload.result matches the eventual tool result. | Manager stream |
background-task-failed | The task threw or timed out. | Manager stream |
background-task-cancelled | The task was cancelled before completing. | Manager stream |
background-task-suspended | The tool called suspend() from inside its execute. | Manager stream |
background-task-resumed | A suspended task was resumed via manager.resume(taskId, resumeData). | Manager stream |
agent.stream().fullStream only emits the agent-loop chunks (background-task-started, background-task-progress) on its own. agent.stream() with untilIdle: true emits the same two chunks and additionally subscribes to the manager pubsub for the run's memory scope and pipes the seven manager chunks (background-task-running, background-task-output, background-task-completed, background-task-failed, background-task-cancelled, background-task-suspended, background-task-resumed) into the same fullStream.
backgroundTaskManager.stream() only emits the seven manager chunks.
The full payload shapes are documented in the background task chunks reference.
Keep the agent stream open with untilIdleDirect link to keep-the-agent-stream-open-with-untilidle
agent.stream() returns once the LLM emits a final response even if a background task is still running. Pass untilIdle: true when you want the stream to stay open until every dispatched background task has completed and the LLM has had a chance to respond to the result:
const stream = await agent.stream('Research solana for me', {
memory: { thread: 't1', resource: 'u1' },
untilIdle: true,
})
for await (const chunk of stream.fullStream) {
// chunks from the initial turn AND any continuation turns triggered by
// background task completions flow through here
}
When a background task completes, the result is injected into the agent memory, stream() re-enters the agentic loop so the LLM can react to it. The stream closes when no tasks are running and no completions are queued.
Customize the idle timeout by passing an object instead of true. The timer only runs while the wrapper is between turns, so a slow first token won't close the stream. The default is 5 minutes:
const stream = await agent.stream('Research solana for me', {
memory: { thread: 't1', resource: 'u1' },
untilIdle: { maxIdleMs: 30_000 },
})
Visit Agent.stream() for the full API.
Aggregate propertiesDirect link to Aggregate properties
stream() with untilIdle returns a MastraModelOutput that looks like the one from a regular stream() call, but fullStream alone spans the initial turn and any auto-continuations. Aggregate properties (text, toolCalls, toolResults, finishReason, messageList, getFullOutput()) still resolve against the first turn's internal buffer. If you need an aggregate view across continuations, consume fullStream yourself and accumulate.
Subagents in the backgroundDirect link to Subagents in the background
Subagent invocations are dispatched as tool calls under the hood, so the same background configuration applies. The recommended pattern is to opt each subagent in on the supervisor, it's clearer and lets you tune timeoutMs per subagent in one place:
import { Agent } from '@mastra/core/agent'
const supervisor = new Agent({
id: 'supervisor',
instructions: 'Coordinate research and writing using the available agents.',
model: 'openai/gpt-5.6-sol',
agents: { researchAgent, writingAgent },
backgroundTasks: {
tools: {
researchAgent: { enabled: true, timeoutMs: 900_000 },
writingAgent: { enabled: true, timeoutMs: 900_000 },
},
},
})
const stream = await supervisor.stream('Research AI in education and write an article', {
memory: { thread: 't1', resource: 'u1' },
untilIdle: true,
})
Inheriting from the subagentDirect link to Inheriting from the subagent
If a subagent isn't listed under the supervisor's backgroundTasks.tools but has background-eligible tools of its own (either via tool-level background.enabled: true or its own backgroundTasks.tools entry) the framework still dispatches the entire subagent invocation as a background task. The supervisor inherits the subagent's intent: the subagent itself becomes the background task, and it can dispatch its eligible ordinary tools in the background inside its loop. Further delegated-agent calls run in the foreground.
The background config used for the inherited dispatch (for example waitTimeoutMs) is derived from the subagent's own backgroundTasks config.
const researchAgent = new Agent({
id: 'research-agent',
description: 'Gathers factual information.',
model: 'openai/gpt-5-mini',
tools: { deepResearchTool },
backgroundTasks: {
tools: {
deepResearchTool: { enabled: true, timeoutMs: 600_000 },
},
waitTimeoutMs: 900_000,
},
})
When this researchAgent is delegated to from a supervisor that has no background task configuration for the researchAgent, the supervisor still dispatches the whole researchAgent invocation as a background task.
Mastra supports one nested background-tool level inside a delegated run: a root agent can delegate to a subagent, and that subagent can dispatch an eligible ordinary tool in the background. A second delegated-agent edge runs in the foreground and doesn't receive nested background guidance. This limit is execution-scoped and doesn't mutate the shared subagent configuration.
Which layer to use depends on where consistency matters: subagent-level configuration travels with the agent, so its background behavior stays the same under every supervisor, whereas the supervisor-side opt-in above centralizes that tuning in one place. This boundary stops at a single nested delegation level and has no workflow integration.
Suspending and resumingDirect link to Suspending and resuming
A background task can pause itself mid-execution and wait for an external signal before continuing. This is useful for human approvals, webhooks, or any flow where the next step depends on data that arrives later.
A tool calls suspend(data) from inside its execute, which:
- Persists
status: 'suspended'and thedatapayload on the task record. - Saves the workflow snapshot so the run survives process restarts.
- Emits a
background-task-suspendedchunk on the manager stream. - Releases the concurrency slot so other tasks can run.
Resume the task with mastra.backgroundTaskManager.resume(taskId, resumeData). The resumeData arrives in the tool's execute options on the resumed run, and the task transitions back to running.
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
export const reviewTool = createTool({
id: 'review',
description: 'Submit a draft for human review.',
inputSchema: z.object({ draft: z.string() }),
outputSchema: z.object({ approvedBy: z.string(), edits: z.string().optional() }),
background: { enabled: true },
execute: async ({ draft }, context) => {
const { suspend, resumeData } = context.agent
if (!resumeData) {
await suspend?.({ awaiting: 'approval', draft })
return { approvedBy: '', edits: undefined }
}
const { reviewer, edits } = resumeData as { reviewer: string; edits?: string }
return { approvedBy: reviewer, edits }
},
})
The first invocation of execute sees resumeData === undefined and calls suspend. After the task is resumed, the runtime restarts the tool with resumeData populated. The if condition is false, so the tool returns its real result.
To resume the task once an approval arrives:
await mastra.backgroundTaskManager?.resume(taskId, {
reviewer: 'alice@example.com',
edits: 'Reworded paragraph 3.',
})
What happens to the agent loopDirect link to What happens to the agent loop
When a task suspends mid-stream() with untilIdle, the wrapper treats it as terminal for the current iteration and closes. Once the resume payload is available, call agent.resumeStream(resumeData, { runId, toolCallId, memory, untilIdle: true }) to continue immediately. The resumed background task completes and adds its result to the message list before the agent runs a follow-up turn on the same SSE connection. To drive the resume out of band, call mastra.backgroundTaskManager.resume(taskId, resumeData) directly. Its result is still written into the thread for the next user turn.
Re-registering the executor on resumeDirect link to Re-registering the executor on resume
The manager keeps tool executors in process memory. If the process restarts while a task is suspended, the executor closure is gone, the caller of resume() must re-register it first via manager.registerTaskContext(taskId, ...). Tasks dispatched and resumed inside the same process don't need this.
Cancelling a suspended taskDirect link to Cancelling a suspended task
manager.cancel(taskId) works against suspended tasks the same way it works for running ones. The row changes to cancelled and the workflow snapshot is cleaned up. A task.cancelled event then fires.
Lifecycle callbacksDirect link to Lifecycle callbacks
Each layer can register terminal-state callbacks. They don't replace one another, and success/failure hooks fire for their outcomes:
- Tool-level
background.onComplete/onFailed: scoped to one tool. - Agent-level
backgroundTasks.onTaskComplete/onTaskFailed: scoped to all tasks dispatched by this agent. - Manager-level
onTaskComplete/onTaskFailed: scoped globally.
export const mastra = new Mastra({
storage,
backgroundTasks: {
enabled: true,
onTaskComplete: task => {
logger.info('Background task complete', { taskId: task.id, toolName: task.toolName })
},
onTaskFailed: task => {
logger.error('Background task failed', { taskId: task.id, error: task.error })
},
},
})
StreamingDirect link to Streaming
Subscribe to all task eventsDirect link to Subscribe to all task events
Calling stream() with no filter returns a stream of every task event in the system. On connection, the stream emits a snapshot of all currently running tasks, then forwards live events as they happen.
const bgManager = mastra.backgroundTaskManager;
if (!bgManager) throw new Error('Background tasks are not enabled');
const controller = new AbortController();
const stream = bgManager.stream({ abortSignal: controller.signal });
for await (const chunk of stream) {
switch (chunk.type) {
case 'background-task-running':
console.log('started', chunk.payload.taskId, chunk.payload.toolName);
break;
case 'background-task-completed':
console.log('done', chunk.payload.taskId, chunk.payload.result);
break;
case 'background-task-failed':
console.error('failed', chunk.payload.taskId, chunk.payload.error);
break;
}
}
The stream stays open until the caller's AbortSignal fires. Always pass an abortSignal so you can disconnect cleanly.
Filter the streamDirect link to Filter the stream
Pass any combination of filter options to narrow the events you receive. Filters apply to both the initial snapshot and the live event subscription.
const stream = bgManager.stream({
agentId: 'researcher',
threadId: 't1',
resourceId: 'u1',
abortSignal: controller.signal,
})
| Filter | Description |
|---|---|
agentId | Only events from tasks dispatched by this agent |
runId | Only events from this specific agent run |
threadId | Only events from tasks scoped to this memory thread |
resourceId | Only events from tasks scoped to this resource |
taskId | Only events for a single task |
abortSignal | Closes the stream when the signal aborts |
Look up task state directlyDirect link to Look up task state directly
For one-off lookups instead of a live stream, use getTask and listTasks:
const task = await mastra.backgroundTaskManager?.getTask(taskId)
const { tasks, total } = await mastra.backgroundTaskManager?.listTasks({
status: 'running',
agentId: 'researcher',
})
These read from storage rather than the pubsub stream, so they're suitable for paginated lists and detail views.