mastra-multi-agent
Skill2 starsChanged 29 days agoApache-2.0View on GitHub
Build multi-agent systems in Mastra: supervisor agents with subagents in the agents map, delegation hooks (onDelegationStart, onDelegationComplete, messageFilter), memory isolation, rubric and task-completion loops, and pattern choice between supervisor, workflow, handoff, and council. Use this skill whenever the user wants one agent to delegate to other agents, coordinate specialists, control or reject delegations, filter context passed to subagents, make an agent self-correct until criteria pass, or migrate away from agent.network(). Triggers on supervisor agent, subagents, agents: { ... }, delegation, onDelegationStart, onDelegationComplete, messageFilter, isTaskComplete, createRubricScorer, onIterationComplete, agent.network, routing agent, multi-agent, orchestrator agent, research and writing agents. Also triggers when a single agent has grown too many tools or responsibilities and should be split.
In this repository46 other files it gives its agents.
- mastra-a2a-acpSkill
- mastra-agent-approval-hitlSkill
- mastra-agentic-uiSkill
- mastra-agent-skillsSkill
- mastra-agentsSkill
- mastra-authSkill
- mastra-browserSkill
- mastra-build-playbookSkill
- mastra-channelsSkill
- mastra-classifierSkill
- mastra-cli-apiSkill
- mastra-client-sdkSkill
- mastra-datasets-experimentsSkill
- mastra-deploymentSkill
- mastra-evalsSkill
- mastra-file-based-agentsSkill
- mastra-framework-integrationSkill
- mastra-guideSkill
- mastra-harnessSkill
- mastra-knowledgeSkill
- mastra-mcpSkill
- mastra-memorySkill
- mastra-migrationsSkill
- mastra-modelsSkill
- mastra-observabilitySkill
- mastra-observational-memorySkill
- mastra-platformSkill
- mastra-processors-guardrailsSkill
- mastra-project-setupSkill
- mastra-ragSkill
- mastra-schedulesSkill
- mastra-semantic-recallSkill
- mastra-serverSkill
- mastra-signalsSkill
- mastra-storageSkill
- mastra-streamingSkill
- mastra-structured-outputSkill
- mastra-studio-editorSkill
- mastra-tool-integrationsSkill
- mastra-toolsSkill
- mastra-troubleshootingSkill
- mastra-vector-storesSkill
- mastra-voiceSkill
- mastra-workflowsSkill
- mastra-workflow-suspend-resumeSkill
- mastra-workspace-sandboxSkill
The file
We split this skill into the rules it gives an agent
8 rules. About 0 are common, 1 is distinctive, and 7 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
7
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 108
Start with one agent. Add agents only when the split clearly improves quality, speed, or reliability.
- Very specific: line 114
Verify the API: If node_modules/@mastra/ exists, read node_modules/@mastra/core/dist/docs/ and the installed Agent types for agents and …
- Very specific: line 115
Pick the pattern: Use the table above. If the path is fixed, stop and use mastra-workflows.
- Very specific: line 119
Add delegation hooks: Put shared hooks in the supervisor's defaultOptions.delegation.
- Very specific: line 120
Add a completion check: when quality matters: isTaskComplete with createRubricScorer or a custom scorer.
- Very specific: line 158
Prefer a curated resultText over forwarding error.message.
- Very specific: line 171
Hook errors silently ignored: Default strategy continues.
- Very specific: line 172
Leaking secrets to specialists: Add a messageFilter that redacts or trims history.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Mastra Multi-Agent Systems
Split work across specialist agents and keep one supervisor in control. Mastra exposes each subagent to the supervisor as a tool and gives you hooks to steer every delegation.
When to use
- One agent needs too many tools, too much context, or different prompts per stage
- A task mixes kinds of work (research, writing, review) that benefit from specialists
- The order of steps is not known in advance and a lead agent should decide
- You need to modify, reject, or audit delegations at runtime
- You want an agent to iterate until a checklist (rubric) passes
- Existing code calls
agent.network()and must move to supervisor agents
When NOT to use
- A single agent with a few tools is enough (use
mastra-agents) - The execution path is fixed and known (use
mastra-workflows) - Pausing a subagent's tool for human approval in detail (use
mastra-agent-approval-hitl) - Subagents declared as
subagents/directories (usemastra-file-based-agents) - Long-running delegations as background tasks (use
mastra-harness) - Writing or tuning scorers beyond the completion loop (use
mastra-evals) - Rendering supervisor streams in a UI (use
mastra-streamingandmastra-agentic-ui)
Required inputs
- The overall task and what "done" means (this becomes the success criteria)
- The specialists: one job per subagent, with its tools and model
- What each subagent returns (bullets, paragraphs, JSON), stated in its
description - Whether subagents should see the full conversation or a filtered slice
- Step budgets for the supervisor and each subagent
- Whether memory is needed (supervisor threads, tenant metadata on subagent threads)
The framework: supervisor, subagents, delegation
A supervisor is a normal Agent with an agents map. Mastra converts each entry into an agent-<key> tool. The supervisor model reads each subagent's description to decide when to delegate.
import { Agent } from '@mastra/core/agent'
const researchAgent = new Agent({
id: 'research-agent',
name: 'Research Agent',
description: 'Gathers factual information and returns bullet-point summaries.',
instructions: 'Research the topic. Return concise bullet points with sources.',
model: 'openai/gpt-6-luna',
})
const writingAgent = new Agent({
id: 'writing-agent',
name: 'Writing Agent',
description: 'Transforms research into well-structured articles.',
instructions: 'Turn research notes into a clear article.',
model: 'openai/gpt-6-luna',
})
export const supervisor = new Agent({
id: 'supervisor',
name: 'Supervisor',
instructions: `You coordinate research and writing using specialized agents.
Delegate to research-agent for facts, then writing-agent for content.`,
model: 'openai/gpt-6.1-sol',
agents: { researchAgent, writingAgent },
})
const stream = await supervisor.stream('Research AI in education and write an article', {
maxSteps: 10,
})
for await (const chunk of stream.textStream) process.stdout.write(chunk)Control points
| Control | Where | Use it to |
delegation.onDelegationStart | stream()/generate() options or defaultOptions | Rewrite the prompt, set modifiedMaxSteps, reject, add threadMetadata, set request context for the subagent |
delegation.onDelegationComplete | same | Inspect result, bail(), return feedback (next turn) or resultText (this run) |
delegation.messageFilter | same | Trim or redact the messages forwarded to the subagent |
onIterationComplete | call options | Log, inject feedback, or stop the supervisor loop |
isTaskComplete | call options | Run scorers after each iteration and keep going until they pass |
abortSignal | call options | Cancel the supervisor and in-flight subagents together |
Pattern choice
| Pattern | Who stays in control | Mastra implementation |
| Supervisor | One lead agent | agents map plus delegation hooks |
| Workflow | The execution graph | createWorkflow() with agent steps |
| Handoff | The current specialist | Agents plus workflows plus memory |
| Council | A final synthesis step | Agents in workflow .parallel(), then a synthesis step |
Start with one agent. Add agents only when the split clearly improves quality, speed, or reliability.
Workflow
- Verify the API. If
node_modules/@mastra/exists, readnode_modules/@mastra/core/dist/docs/and the installedAgenttypes foragentsanddelegation. Otherwise fetchhttps://mastra.ai/docs/subagents.mdandhttps://mastra.ai/reference/agents/generate.md. Subagents need@mastra/core@1.8.0or later. Trust these over memory. - Pick the pattern. Use the table above. If the path is fixed, stop and use
mastra-workflows. - Define subagents. One responsibility each. Write
descriptionas routing text: what it does, what it returns, when to use it. - Write supervisor instructions. List available resources, a delegation strategy, and success criteria.
- Bound the loop. Set
maxStepson the supervisor call anddefaultOptions.maxStepson each subagent. The supervisor model can lower a subagent's budget but not raise it. - Add delegation hooks. Put shared hooks in the supervisor's
defaultOptions.delegation. Filter messages when subagents must not see sensitive or bulky context. - Add a completion check when quality matters:
isTaskCompletewithcreateRubricScoreror a custom scorer. - Register the supervisor (and the subagents if you call them directly) on
new Mastra({ agents }). - Test in Studio and inspect the trace: one span per delegation, the prompt sent, and the result returned.
Deep dive: delegation hooks
const stream = await supervisor.stream('Research AI trends', {
maxSteps: 10,
delegation: {
onDelegationStart: async context => {
if (context.primitiveId === 'research-agent') {
context.requestContext.set('audience', 'technical')
return {
proceed: true,
modifiedPrompt: `${context.prompt}\n\nFocus on 2024-2025 data.`,
modifiedMaxSteps: 5,
}
}
if (context.iteration > 8) {
return { proceed: false, rejectionReason: 'Max iterations reached. Synthesize current findings.' }
}
return { proceed: true }
},
onDelegationComplete: ({ success }) => {
if (!success) return { resultText: 'The delegated task failed. Try another approach.' }
},
messageFilter: ({ messages }) => messages.slice(-10),
},
})Rules worth remembering:
- A throwing hook does not fail the delegation by default. Set
hookErrorStrategy: 'throw'to fail it. Failures are recorded underrequestContext.get('__mastra_delegationHookErrors'). feedbackis saved to supervisor memory for the next turn.resultTextchanges what the supervisor sees now.- Prefer a curated
resultTextover forwardingerror.message. Provider errors can leak sensitive data. - Subagents get the full parent context unless you filter, but only the delegation prompt and response are saved to their memory, in a fresh thread per delegation.
Failure patterns
- Subagent never called. Missing or vague
description. Describe purpose, return format, and when to use it. Name each subagent in the supervisor instructions. - Supervisor loops forever or stops early. No
maxSteps. Set it on the call, and give subagentsdefaultOptions.maxSteps. - Supervisor cuts a subagent short. The model passed a low
maxSteps. ReturnmodifiedMaxStepsfromonDelegationStart. - Empty delegation result looks like success. The subagent stopped on a tool-calls step. Detect it in
onDelegationCompleteand return aresultTextthat says so. - Subagent calls a client tool and stalls. Subagents cannot run tools without
execute. Give client tools to the supervisor, or usesuspend()in the subagent's tool. - Supervisor restates earlier results and burns tokens. Set
delegation.enableResultReferences: trueso later delegations reuse results by reference. - Hook errors silently ignored. Default strategy continues. Set
hookErrorStrategy: 'throw'for hooks that must succeed. - Leaking secrets to specialists. Add a
messageFilterthat redacts or trims history. - New code calls
agent.network(). It is deprecated. Usestream()/generate()on a supervisor. Seereferences/api.mdfor the chunk mapping. - Rubric never satisfied. Criteria are vague or not verifiable. Write concrete, checkable criteria and mark nice-to-haves
required: false.
Output format
A finished multi-agent delivery contains:
src/mastra/agents/<subagent-id>.tsfor each specialist, each withdescriptionand a step budgetsrc/mastra/agents/<supervisor-id>.tswithagents, instructions listing resources and success criteria, anddefaultOptions.delegationhooks if shared- Registration in
src/mastra/index.ts - A call site with
maxSteps, andisTaskCompletewhen completion matters - Evidence: a Studio trace showing each delegation, or a test asserting the final output
Reference files
references/api.md-agentsoption,delegationconfig, hook contexts and return values,isTaskComplete,createRubricScorer,network()deprecation map.references/examples.md- Research supervisor, guarded delegation with filtering, rubric self-correction, council with workflow.parallel().references/checklist.md- Pre-production checklist for multi-agent systems.
Live docs
- https://mastra.ai/docs/subagents
- https://mastra.ai/docs/guides/multi-agent-systems
- https://mastra.ai/reference/agents/generate
- https://mastra.ai/reference/streaming/agents/stream
- https://mastra.ai/reference/evals/rubric
- https://mastra.ai/reference/agents/network
- https://mastra.ai/reference/migrations/network-to-supervisor
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

