MessageHistory
The MessageHistory is a hybrid processor that handles both retrieval and persistence of message history. On input, it fetches historical messages from storage and prepends them to the conversation. On output, it persists new messages to storage.
Usage exampleDirect link to Usage example
import { MessageHistory } from "@mastra/core/processors";
const processor = new MessageHistory({
storage: memoryStorage,
lastMessages: 50,
});
Constructor parametersDirect link to Constructor parameters
options:
MessageHistoryOptions
Configuration options for the message history processor
OptionsDirect link to Options
storage:
MemoryStorage
Storage instance for retrieving and persisting messages
lastMessages?:
number
Maximum number of historical messages to retrieve. If not specified, retrieves all messages
ReturnsDirect link to Returns
id:
string
Processor identifier set to 'message-history'
name:
string
Processor display name set to 'MessageHistory'
processInput:
(args: { messages: MastraDBMessage[]; messageList: MessageList; abort: (reason?: string) => never; tracingContext?: TracingContext; requestContext?: RequestContext }) => Promise<MessageList | MastraDBMessage[]>
Fetches historical messages from storage and adds them to the message list
processOutputResult:
(args: { messages: MastraDBMessage[]; messageList: MessageList; abort: (reason?: string) => never; tracingContext?: TracingContext; requestContext?: RequestContext }) => Promise<MessageList>
Persists new messages (user input and assistant response) to storage, excluding system messages
Extended usage exampleDirect link to Extended usage example
src/mastra/agents/memory-agent.ts
import { Agent } from "@mastra/core/agent";
import { MessageHistory } from "@mastra/core/processors";
import { PostgresStorage } from "@mastra/pg";
const storage = new PostgresStorage({
connectionString: process.env.DATABASE_URL,
});
export const agent = new Agent({
name: "memory-agent",
instructions: "You are a helpful assistant with conversation memory",
model: "openai:gpt-4o",
inputProcessors: [
new MessageHistory({
storage,
lastMessages: 100,
}),
],
outputProcessors: [
new MessageHistory({
storage,
}),
],
});
BehaviorDirect link to Behavior
Input processingDirect link to Input processing
- Retrieves
threadIdfrom the request context - Fetches historical messages from storage (ordered by creation date, descending)
- Filters out system messages (they should not be stored in the database)
- Merges historical messages with incoming messages, avoiding duplicates by ID
- Adds historical messages with
source: 'memory'tag
Output processingDirect link to Output processing
- Retrieves
threadIdfrom the request context - Skips persistence if
readOnlyis set in memory config - Filters out incomplete tool calls from messages
- Persists new user input and assistant response messages to storage
- Updates the thread's
updatedAttimestamp