mastra-helper
Mastra AI agent framework for TypeScript - agents, tools, workflows, memory, and MCP integration When user works with Mastra, AI agents, LLM orchestration, or mentions mastra commands and patterns
What this skill does
# Mastra Helper Agent
## What's New in Mastra v1 (2025)
- **Stable API**: v1 beta signals production-readiness with no breaking changes planned
- **Multi-model support**: OpenAI, Anthropic, Gemini, Llama, and more through AI SDK integration
- **Human-in-the-loop**: Suspend/resume with persistent state across sessions
- **MCP integration**: Model Context Protocol for universal tool sharing
- **Built-in evals**: Automated testing with model-graded and rule-based scoring
- **Enhanced memory**: Working memory, semantic recall, and conversation history
## Installation
```bash
# Create new Mastra project
npm create mastra@latest
# Or add to existing project
npm install @mastra/core
```
## Core Concepts
Mastra provides:
1. **Agents**: Autonomous LLM-powered systems with tools
2. **Tools**: Functions agents can call to interact with external systems
3. **Workflows**: Graph-based orchestration for multi-step processes
4. **Memory**: Context management across conversations
5. **MCP**: Model Context Protocol for tool/resource sharing
## Creating Agents
### Basic Agent
```typescript
import { Agent } from "@mastra/core/agent";
export const myAgent = new Agent({
name: "my-agent",
instructions: "You are a helpful assistant that answers questions clearly.",
model: "openai/gpt-4o-mini",
});
```
### Agent with Tools
```typescript
import { Agent } from "@mastra/core/agent";
import { weatherTool, searchTool } from "./tools";
export const assistantAgent = new Agent({
name: "assistant",
instructions: `You are a helpful assistant.
Use the weather tool to check weather conditions.
Use the search tool to find information.`,
model: "anthropic/claude-sonnet-4-20250514",
tools: { weatherTool, searchTool },
});
```
### Agent Configuration Options
```typescript
export const agent = new Agent({
name: "configured-agent",
instructions: "Your system prompt here",
model: "openai/gpt-4o",
// Limit sequential LLM calls (default: 5)
maxSteps: 10,
// Callback after each step
onStepFinish: async ({ step, result }) => {
console.log(`Step ${step} completed:`, result);
},
// Callback after completion
onFinish: async ({ result, usage }) => {
console.log("Total tokens:", usage.totalTokens);
},
});
```
### Dynamic Configuration with RuntimeContext
```typescript
import { Agent, RuntimeContext } from "@mastra/core/agent";
export const agent = new Agent({
name: "dynamic-agent",
// Dynamic model selection
model: async ({ runtimeContext }) => {
const tier = runtimeContext.get("user-tier");
return tier === "enterprise" ? "openai/gpt-4o" : "openai/gpt-4o-mini";
},
// Dynamic instructions
instructions: async ({ runtimeContext }) => {
const lang = runtimeContext.get("language");
return `Respond in ${lang}. Be helpful and concise.`;
},
});
// Usage
const ctx = new RuntimeContext();
ctx.set("user-tier", "enterprise");
ctx.set("language", "Spanish");
await agent.generate("Hello!", { runtimeContext: ctx });
```
## Using Agents
### Generate Text
```typescript
const result = await agent.generate("What's the weather in Tokyo?");
console.log(result.text);
```
### Stream Response
```typescript
const stream = await agent.stream("Tell me a story");
for await (const chunk of stream.textStream) {
process.stdout.write(chunk);
}
```
### Structured Output
```typescript
import { z } from "zod";
const WeatherSchema = z.object({
location: z.string(),
temperature: z.number(),
conditions: z.string(),
humidity: z.number(),
});
const result = await agent.generate("Get weather for NYC", {
output: WeatherSchema,
});
// result.object is typed: { location, temperature, conditions, humidity }
console.log(result.object.temperature);
```
## Creating Tools
### Basic Tool
```typescript
import { createTool } from "@mastra/core/tools";
import { z } from "zod";
export const weatherTool = createTool({
id: "weather-tool",
description: "Fetches current weather for a location",
inputSchema: z.object({
location: z.string().describe("City name or coordinates"),
}),
outputSchema: z.object({
temperature: z.number(),
conditions: z.string(),
humidity: z.number(),
}),
execute: async ({ context }) => {
const { location } = context;
// Fetch weather from API
const response = await fetch(`https://api.weather.com/${location}`);
const data = await response.json();
return {
temperature: data.temp,
conditions: data.weather,
humidity: data.humidity,
};
},
});
```
### Tool with Runtime Context
```typescript
export const apiTool = createTool({
id: "api-tool",
description: "Makes authenticated API calls",
inputSchema: z.object({
endpoint: z.string(),
}),
outputSchema: z.object({
data: z.any(),
}),
execute: async ({ context, runtimeContext }) => {
const apiKey = runtimeContext.get("api-key");
const response = await fetch(context.endpoint, {
headers: { Authorization: `Bearer ${apiKey}` },
});
return { data: await response.json() };
},
});
```
## Workflows
### Creating Steps
```typescript
import { createStep } from "@mastra/core/workflows";
import { z } from "zod";
const fetchDataStep = createStep({
id: "fetch-data",
inputSchema: z.object({
userId: z.string(),
}),
outputSchema: z.object({
user: z.object({
name: z.string(),
email: z.string(),
}),
}),
execute: async ({ inputData }) => {
const user = await db.users.findUnique({ where: { id: inputData.userId } });
return { user };
},
});
```
### Creating Workflows
```typescript
import { createWorkflow } from "@mastra/core/workflows";
const userWorkflow = createWorkflow({
id: "user-workflow",
inputSchema: z.object({
userId: z.string(),
}),
outputSchema: z.object({
result: z.string(),
}),
})
.then(fetchDataStep)
.then(processStep)
.then(notifyStep)
.commit();
```
### Branching
```typescript
const workflow = createWorkflow({ id: "branching-example", ... })
.then(validateStep)
.branch([
// Condition: user is premium
[async ({ inputData }) => inputData.isPremium, premiumProcessStep],
// Condition: user is basic
[async ({ inputData }) => !inputData.isPremium, basicProcessStep],
])
.then(finalizeStep)
.commit();
```
### Parallel Execution
```typescript
const workflow = createWorkflow({ id: "parallel-example", ... })
.then(initialStep)
.parallel([
fetchFromApiA,
fetchFromApiB,
fetchFromApiC,
])
.then(mergeResultsStep)
.commit();
```
### Loops
```typescript
const workflow = createWorkflow({ id: "loop-example", ... })
// Do-until loop
.dountil(
retryStep,
async ({ inputData }) => inputData.success === true,
{ maxIterations: 5 }
)
// Do-while loop
.dowhile(
processItemStep,
async ({ inputData }) => inputData.hasMore,
{ maxIterations: 100 }
)
// For-each loop
.foreach(
processItemStep,
async ({ inputData }) => inputData.items,
{ concurrency: 3 }
)
.commit();
```
### Suspend and Resume (Human-in-the-Loop)
```typescript
const approvalStep = createStep({
id: "await-approval",
inputSchema: z.object({ requestId: z.string() }),
outputSchema: z.object({ approved: z.boolean() }),
resumeSchema: z.object({
approved: z.boolean(),
approverNotes: z.string().optional(),
}),
execute: async ({ inputData, suspend, resumeData }) => {
// If we have resume data, use it
if (resumeData) {
return { approved: resumeData.approved };
}
// Otherwise, suspend and wait for human input
await suspend({ requestId: inputData.requestId });
},
});
// Resume suspended workflow
await workflow.resume({
runId: "run-123",
stepId: "await-approval",
resumeData: { approved: true, approverNotes: "Looks good!" },
});
```
### Running Workflows
```typescript
// Start and wait for completion
const result = await workflow.start({
inputData: { userId: "useRelated in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.