A 45-minute hands-on workshop on Mastra Processors — the middleware system that lets you intercept, modify, and control every phase of an AI agent's execution loop.
The premise: Guardrails are just the beginning. Processors give you hooks into five phases of the agent loop — input validation, per-step model/tool control, real-time stream monitoring, step-level quality checks, and post-completion side effects. This workshop shows how to use all of them.
- pnpm
- An OpenAI API key (
OPENAI_API_KEY) - An OpenRouter API key (
OPENROUTER_API_KEY) — used for the safeguard classification model
# Install dependencies for all examples
cd examples/00-guardrails && pnpm i && cd ../..
cd examples/01-beyond-guardrails && pnpm i && cd ../..
cd examples/02-enterprise-pipeline && pnpm i && cd ../..
# Start all three servers (ports 4111, 4112, 4113)
./start-all.sh
# Open slides in your browser
open slides/01-intro.htmlThe workshop is split into slides (HTML presentations) and live code examples (Mastra projects that run in Studio).
| # | Slide | What it covers |
|---|---|---|
| 01 | Intro | Workshop goals, what we'll build |
| 02 | The Problem | Agents are black boxes — you can't see or control what happens between input and output |
| 03 | Everything Is a Processor | Memory, skills, tool search, structured output, prepareStep — all processors internally |
| 04 | The 5 Process Functions | Animated flow diagram of the agent loop with interactive phase explorer |
| 05 | The Processors UI | Live Mastra Studio embed — inspect processors, traces, and agent state in real time |
| 06 | Building Processors | Tabbed code walkthrough of all three examples |
| 06b | Performance | Not every check needs an LLM — regex pre-filters, parallel execution, model routing, conditional checks |
| 06c | Enterprise Flow | Animated diagram showing all 10 processors in the enterprise pipeline |
| 07 | Built-in Processors | Overview of Mastra's 13+ built-in processors |
| 08 | Wrap-up | Key takeaways and resources |
Use arrow keys to navigate between slides. Each slide links to the next.
The workshop builds through three progressively complex examples. Each is a standalone Mastra project with its own Studio UI.
Story: TechMart's support bot needs input safety checks before responding.
| Processor | Phase | How it works |
|---|---|---|
| Topic Guard | processInput |
Internal agent (gpt-oss-safeguard-20b) classifies if the message is on-topic. Off-topic → abort() with typed metadata ({ category, confidence }). |
| PII Guard | processInput |
Regex-only detection for emails, SSNs, credit cards, phone numbers. No LLM — runs in microseconds. |
| Compliance Pipeline | ProcessorWorkflow |
Composes Topic Guard + PII Guard + built-in ModerationProcessor into a parallel workflow. All three run concurrently; first abort stops the pipeline. |
What you learn:
Processor<TId, TMetadata>— the second generic types your abort metadataabort(reason, { metadata })carries structured data about what triggered the tripwire- Not every guard needs an LLM (regex PII guard = zero latency, zero cost)
createWorkflow().parallel().map()for concurrent processor composition
Story: TechMart wants smarter agent behavior — not just safety, but intelligence and cost optimization.
| Processor | Phase | How it works |
|---|---|---|
| Model Router | processInputStep |
Step 0 → gpt-5.2 (full power). Step 1+ → gpt-5-nano (cheap). Saves ~90% on follow-up steps like tool result processing. |
| Tool Dependency Enforcer | processInputStep |
create_order is only available after search_products AND check_inventory have been called. Filters activeTools based on conversation history. |
| Task Drift Monitor | processOutputStep |
Every 2 steps, an internal nano agent compares the latest response against the original user intent. Drifting → abort({ retry: true }) with corrective feedback. |
| Cost Tracker | processOutputStream |
Counts tokens in text-delta chunks as they stream. Emits data-cost-update events via writer.custom(). Aborts if budget exceeded. |
| Response Enricher | processOutputResult |
Appends a disclaimer footer to the final response after all steps complete. |
What you learn:
processInputStepcan swap models and control tool availability per stepprocessOutputStepusesstepNumberfor periodic quality checks +abort({ retry: true })for self-correctionprocessOutputStreamuseswriter.custom()for real-time client-side data eventsprocessOutputResultfor final post-processing after the agent loop ends- Each phase has a distinct purpose — not everything is a guardrail
Story: TechMart's production deployment. Multiple processing layers, conditional logic, performance optimizations, and business logic side effects.
| Processor | Phase | How it works |
|---|---|---|
| Regex Pre-Filter | processInput |
Fast PII + profanity detection using regex. First line of defense — runs in microseconds. |
| Topic Guard | processInput |
Safeguard-model topic classification (same as Example 00). |
| Input Pipeline | ProcessorWorkflow |
.then(regexPreFilter).parallel([topicGuard, moderationProcessor]).map(merge) — cheap checks first, expensive checks in parallel after. |
| Model Router | processInputStep |
Per-step model swapping (same as Example 01). |
| Tool Dependency Enforcer | processInputStep |
Tool prerequisite gating (same as Example 01). |
| Wrap-Up Enforcer | processInputStep |
When stepNumber >= MAX_STEPS - 2, injects a system message telling the agent to wrap up, summarize progress, and list remaining work. Prevents getting cut off mid-task. |
| Output Pipeline | ProcessorWorkflow |
.branch([every 5th step → TaskDriftMonitor]) — only checks drift periodically, not every step. |
| Order Confirmation | processOutputResult |
Scans for create_order tool results and fires a webhook with order details. |
| Escalation Detector | processOutputResult |
Uses a nano agent to evaluate if the conversation needs human escalation (unresolved issues, frustration, repeated failures). |
What you learn:
- Layered defense: regex first (free) → LLM checks in parallel (pay once for the slowest)
- Conditional branching with
.branch()— only run expensive checks when needed processOutputResultas an onFinish hook for business logic (webhooks, escalation)- Shared
MAX_STEPSconstant between agent config and processors - Full agent config:
inputProcessors+outputProcessors+maxProcessorRetries
| Purpose | Model | Why |
|---|---|---|
| Main agent | openai/gpt-5.2 |
Full capability for user-facing responses |
| Follow-up steps | openai/gpt-5-nano |
Cheap model for tool result processing, drift evaluation, escalation scoring |
| Safeguard / classification | openrouter/openai/gpt-oss-safeguard-20b |
Fast, purpose-built model for topic classification and content moderation |
The workshop emphasizes that not every check needs an LLM:
Regex pre-filters → μs latency, $0 cost
Safeguard models → ms latency, ¢ cost
Parallel LLM checks → latency = slowest check (not sum)
Model routing per step → ~90% savings on follow-up steps
Conditional checks → only pay when the condition fires
Stream-time abort → stop generation mid-stream if budget exceeded
workshop-processors/
├── slides/ # HTML presentation slides
│ ├── 01-intro.html
│ ├── 02-the-problem.html
│ ├── 03-everything-is-a-processor.html
│ ├── 04-five-phases.html
│ ├── 05-the-ui.html # Live Studio iframe embed
│ ├── 06-building-processors.html # Tabbed code walkthrough
│ ├── 06b-performance.html
│ ├── 06c-enterprise-flow.html # Animated enterprise pipeline diagram
│ ├── 07-built-ins.html
│ ├── 08-wrap-up.html
│ ├── shared.css # Shared slide styles
│ └── index.html # Slide index
├── examples/
│ ├── 00-guardrails/ # processInput + parallel workflows
│ ├── 01-beyond-guardrails/ # All 5 phases demonstrated
│ └── 02-enterprise-pipeline/ # Full production pipeline
├── start-all.sh # Start all 3 servers
└── README.md
Each example is a standalone Mastra project:
cd examples/00-guardrails
pnpm i
pnpm dev # Studio at http://localhost:4111cd examples/01-beyond-guardrails
pnpm i
pnpm dev # Studio at http://localhost:4112cd examples/02-enterprise-pipeline
pnpm i
pnpm dev # Studio at http://localhost:4113