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 exampleUsage example的直接链接
import { MessageHistory } from '@mastra/core/processors'
const processor = new MessageHistory({
storage: memoryStorage,
lastMessages: 50,
})
Constructor parametersConstructor parameters的直接链接
options:
MessageHistoryOptions
Configuration options for the message history processor
MessageHistoryOptions
storage:
MemoryStorage
Storage instance for retrieving and persisting messages
lastMessages?:
number
Maximum number of historical messages to retrieve. If not specified, retrieves all messages
ReturnsReturns的直接链接
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 exampleExtended usage example的直接链接
src/mastra/agents/memory-agent.ts
import { Agent } from '@mastra/core/agent'
import { MessageHistory } from '@mastra/core/processors'
import { PostgresStore } from '@mastra/pg'
const storage = new PostgresStore({
id: 'pg-storage',
connectionString: process.env.DATABASE_URL,
})
export const agent = new Agent({
id: 'memory-agent',
name: 'memory-agent',
instructions: 'You are a helpful assistant with conversation memory',
model: 'openai/gpt-5.6-sol',
inputProcessors: [
new MessageHistory({
storage,
lastMessages: 100,
}),
],
outputProcessors: [
new MessageHistory({
storage,
}),
],
})
BehaviorBehavior的直接链接
Input processingInput processing的直接链接
- Retrieves
threadIdfrom the request context - Fetches historical messages from storage (ordered by creation date, descending)
- Filters out system messages (they shouldn't be stored in the database)
- Merges historical messages with incoming messages, avoiding duplicates by ID
- Adds historical messages with
source: 'memory'tag
Output processingOutput 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