# Memory processors

Memory processors transform and filter messages as they pass through an agent with memory enabled. They manage context window limits, remove unnecessary content, and optimize the information sent to the language model.

When memory is enabled on an agent, Mastra adds memory processors to the agent's processor pipeline. These processors retrieve message history, working memory, and semantically relevant messages, then persist new messages after the model responds.

Memory processors are [processors](https://mastra.ai/docs/agents/processors) that operate specifically on memory-related messages and state.

## Built-in memory processors

Mastra automatically adds these processors when memory is enabled:

### `MessageHistory`

Retrieves message history and persists new messages.

**When you configure:**

```typescript
memory: new Memory({
  lastMessages: 10,
})
```

**Mastra internally:**

1. Creates a `MessageHistory` processor with `limit: 10`
2. Adds it to the agent's input processors (runs before the LLM)
3. Adds it to the agent's output processors (runs after the LLM)

**What it does:**

- **Input**: Fetches the last 10 messages from storage and prepends them to the conversation
- **Output**: Persists new messages to storage after the model responds

**Example:**

```typescript
import { Agent } from '@mastra/core/agent'
import { Memory } from '@mastra/memory'
import { LibSQLStore } from '@mastra/libsql'
import { openai } from '@ai-sdk/openai'

const agent = new Agent({
  id: 'test-agent',
  name: 'Test Agent',
  instructions: 'You are a helpful assistant',
  model: 'openai/gpt-5.4',
  memory: new Memory({
    storage: new LibSQLStore({
      id: 'memory-store',
      url: 'file:memory.db',
    }),
    lastMessages: 10, // MessageHistory processor automatically added
  }),
})
```

### `SemanticRecall`

Retrieves semantically relevant messages based on the current input and creates embeddings for new messages.

**When you configure:**

```typescript
memory: new Memory({
  semanticRecall: { enabled: true },
  vector: myVectorStore,
  embedder: myEmbedder,
})
```

**Mastra internally:**

1. Creates a `SemanticRecall` processor
2. Adds it to the agent's input processors (runs before the LLM)
3. Adds it to the agent's output processors (runs after the LLM)
4. Requires both a vector store and embedder to be configured

**What it does:**

- **Input**: Performs vector similarity search to find relevant past messages and prepends them to the conversation
- **Output**: Creates embeddings for new messages and stores them in the vector store for future retrieval

**Example:**

```typescript
import { Agent } from '@mastra/core/agent'
import { Memory } from '@mastra/memory'
import { LibSQLStore } from '@mastra/libsql'
import { PineconeVector } from '@mastra/pinecone'
import { OpenAIEmbedder } from '@mastra/openai'
import { openai } from '@ai-sdk/openai'

const agent = new Agent({
  name: 'semantic-agent',
  instructions: 'You are a helpful assistant with semantic memory',
  model: 'openai/gpt-5.4',
  memory: new Memory({
    storage: new LibSQLStore({
      id: 'memory-store',
      url: 'file:memory.db',
    }),
    vector: new PineconeVector({
      id: 'memory-vector',
      apiKey: process.env.PINECONE_API_KEY!,
    }),
    embedder: new OpenAIEmbedder({
      model: 'text-embedding-3-small',
      apiKey: process.env.OPENAI_API_KEY!,
    }),
    semanticRecall: { enabled: true }, // SemanticRecall processor automatically added
  }),
})
```

### `WorkingMemory`

Manages working memory state across conversations.

**When you configure:**

```typescript
memory: new Memory({
  workingMemory: { enabled: true },
})
```

**Mastra internally:**

1. Creates a `WorkingMemory` processor
2. Adds it to the agent's input processors (runs before the LLM)
3. Requires a storage adapter to be configured

**What it does:**

- **Input**: Retrieves working memory state for the current thread and prepends it to the conversation
- **Output**: No output processing

**Example:**

```typescript
import { Agent } from '@mastra/core/agent'
import { Memory } from '@mastra/memory'
import { LibSQLStore } from '@mastra/libsql'
import { openai } from '@ai-sdk/openai'

const agent = new Agent({
  name: 'working-memory-agent',
  instructions: 'You are an assistant with working memory',
  model: 'openai/gpt-5.4',
  memory: new Memory({
    storage: new LibSQLStore({
      id: 'memory-store',
      url: 'file:memory.db',
    }),
    workingMemory: { enabled: true }, // WorkingMemory processor automatically added
  }),
})
```

## Manual control and deduplication

If you manually add a memory processor to `inputProcessors` or `outputProcessors`, Mastra **won't** automatically add it. This gives you full control over processor ordering:

```typescript
import { Agent } from '@mastra/core/agent'
import { Memory } from '@mastra/memory'
import { MessageHistory } from '@mastra/core/processors'
import { TokenLimiter } from '@mastra/core/processors'
import { LibSQLStore } from '@mastra/libsql'
import { openai } from '@ai-sdk/openai'

// Custom MessageHistory with different configuration
const customMessageHistory = new MessageHistory({
  storage: new LibSQLStore({ id: 'memory-store', url: 'file:memory.db' }),
  lastMessages: 20,
})

const agent = new Agent({
  name: 'custom-memory-agent',
  instructions: 'You are a helpful assistant',
  model: 'openai/gpt-5.4',
  memory: new Memory({
    storage: new LibSQLStore({ id: 'memory-store', url: 'file:memory.db' }),
    lastMessages: 10, // This would normally add MessageHistory(10)
  }),
  inputProcessors: [
    customMessageHistory, // Your custom one is used instead
    new TokenLimiter({ limit: 4000 }), // Runs after your custom MessageHistory
  ],
})
```

## Processor execution order

Understanding the execution order is important when combining guardrails with memory:

### Input Processors

```text
[Memory Processors] → [Your inputProcessors]
```

1. **Memory processors run FIRST**: `WorkingMemory`, `MessageHistory`, `SemanticRecall`
2. **Your input processors run AFTER**: guardrails, filters, validators

This means memory loads message history before your processors can validate or filter the input.

### Output Processors

```text
[Your outputProcessors] → [Memory Processors]
```

1. **Your output processors run FIRST**: guardrails, filters, validators
2. **Memory processors run AFTER**: `SemanticRecall` (embeddings), `MessageHistory` (persistence)

This ordering is designed to be **safe by default**: if your output guardrail calls `abort()`, the memory processors never run and **no messages are saved**.

## Guardrails and memory

The default execution order provides safe guardrail behavior:

### Output guardrails (recommended)

Output guardrails run **before** memory processors save messages. If a guardrail aborts:

- The tripwire is triggered
- Memory processors are skipped
- **No messages are persisted to storage**

```typescript
import { Agent } from '@mastra/core/agent'
import { Memory } from '@mastra/memory'
import { openai } from '@ai-sdk/openai'

// Output guardrail that blocks inappropriate content
const contentBlocker = {
  id: 'content-blocker',
  processOutputResult: async ({ messages, abort }) => {
    const hasInappropriateContent = messages.some(msg => containsBadContent(msg))
    if (hasInappropriateContent) {
      abort('Content blocked by guardrail')
    }
    return messages
  },
}

const agent = new Agent({
  name: 'safe-agent',
  instructions: 'You are a helpful assistant',
  model: 'openai/gpt-5.4',
  memory: new Memory({ lastMessages: 10 }),
  // Your guardrail runs BEFORE memory saves
  outputProcessors: [contentBlocker],
})

// If the guardrail aborts, nothing is saved to memory
const result = await agent.generate('Hello')
if (result.tripwire) {
  console.log('Blocked:', result.tripwire.reason)
  // Memory is empty - no messages were persisted
}
```

### Input guardrails

Input guardrails run **after** memory processors load history. If a guardrail aborts:

- The tripwire is triggered
- The LLM is never called
- Output processors (including memory persistence) are skipped
- **No messages are persisted to storage**

```typescript
// Input guardrail that validates user input
const inputValidator = {
  id: 'input-validator',
  processInput: async ({ messages, abort }) => {
    const lastUserMessage = messages.findLast(m => m.role === 'user')
    if (isInvalidInput(lastUserMessage)) {
      abort('Invalid input detected')
    }
    return messages
  },
}

const agent = new Agent({
  name: 'validated-agent',
  instructions: 'You are a helpful assistant',
  model: 'openai/gpt-5.4',
  memory: new Memory({ lastMessages: 10 }),
  // Your guardrail runs AFTER memory loads history
  inputProcessors: [inputValidator],
})
```

### Summary

| Guardrail Type | When it runs               | If it aborts                  |
| -------------- | -------------------------- | ----------------------------- |
| Input          | After memory loads history | LLM not called, nothing saved |
| Output         | Before memory saves        | Nothing saved to storage      |

Both scenarios are safe - guardrails prevent inappropriate content from being persisted to memory

## Related documentation

- [Processors](https://mastra.ai/docs/agents/processors): General processor concepts and custom processor creation
- [Guardrails](https://mastra.ai/docs/agents/guardrails): Security and validation processors
- [Memory Overview](https://mastra.ai/docs/memory/overview): Memory types and configuration

When creating custom processors avoid mutating the input `messages` array or its objects directly.