Skip to main content

Memory class

The Memory class provides a reliable system for managing conversation history and thread-based message storage in Mastra. It enables persistent storage of conversations, semantic search capabilities, and efficient message retrieval. You must configure a storage provider for conversation history, and if you enable semantic recall you will also need to provide a vector store and, unless that vector store embeds text itself, an embedder.

Usage example
Direct link to Usage example

src/mastra/agents/test-agent.ts
import { Memory } from '@mastra/memory'
import { Agent } from '@mastra/core/agent'

export const agent = new Agent({
id: 'test-agent',
name: 'test-agent',
instructions: 'You are an agent with memory.',
model: 'openai/gpt-6.1-sol',
memory: new Memory({
options: {
workingMemory: {
enabled: true,
},
},
}),
})
note

To enable workingMemory on an agent, you’ll need a storage provider configured on your main Mastra instance. See Mastra class for more information.

Constructor parameters
Direct link to Constructor parameters

storage?:

MastraCompositeStore
Storage implementation for persisting memory data. Optional: when omitted, an agent uses the storage of the Mastra instance it belongs to. If neither is configured, accessing memory.storage throws Memory requires a storage provider to function.

vector?:

MastraVector | false
Vector store for semantic search capabilities. Set to false to disable vector operations.

embedder?:

string | EmbeddingModel<string> | EmbeddingModelV2<string>
Embedder for vector embeddings, as a model-router ID string (for example "openai/text-embedding-3-small"), an EmbeddingModel, or an EmbeddingModelV2. Required when semantic recall is enabled and the vector store doesn't generate embeddings itself (vector.isSelfEmbedding is false).

embeddingDimension?:

number
Output dimension of the embedder, as a positive integer. When set, Memory uses it to name the semantic recall index instead of embedding a probe string on first use. It must match the vectors the embedder returns: a mismatch throws a MASTRA_MEMORY_EMBEDDING_DIMENSION_MISMATCH error before any index is created. See Setting the embedding dimension.

options?:

MemoryConfig
Memory configuration options.

lastMessages?:

number | false
Number of most recent messages to include in context. Set to false to disable the message history feature entirely (messages are not loaded into context or saved). Use Number.MAX_SAFE_INTEGER to retrieve all messages with no limit. To load messages without saving new ones, use the readOnly option. The window slides forward on every request, so once a thread exceeds the limit, each turn invalidates the provider prompt cache. For long-running conversations, use Observational Memory instead.

messageHistory?:

{ maxTokens: number; atMaxRemoveTokens?: number }
Token budget for the complete prompt, including remembered history, system instructions, context, and the current turn. When the prompt exceeds maxTokens, the oldest remembered messages are dropped until the prompt is at most maxTokens - atMaxRemoveTokens (defaults to 25% of maxTokens). Protected content is never removed. Linked tool calls and results are removed together. During agent runs, trimmed history is excluded from later turns via a persisted per-thread boundary, but the messages themselves stay in storage. When set without an explicit lastMessages, the default 10-message cap is not applied. Set maxTokens to 0 to disable message history. Prefer this over lastMessages, since message count is a poor proxy for context size.

readOnly?:

boolean
When true, prevents memory from saving new messages and provides working memory as read-only context (without the updateWorkingMemory tool). Useful for read-only operations like previews, internal routing agents, or sub agents that should reference but not modify memory.

retainFullInput?:

boolean
When true, the request input is processed exactly as supplied instead of being filtered against stored history. Use this when you assemble the input yourself and need the message sequence preserved. Stored history is still loaded underneath, and every input message that isn't already stored is saved to the thread, including few-shot examples. Can be set per call on memory.options or agent-wide in the memory constructor options.

semanticRecall?:

boolean | { topK: number; messageRange: number | { before: number; after: number }; scope?: 'thread' | 'resource'; maxChunkChars?: number }
Enable semantic search in message history. Can be a boolean or an object with configuration options. When enabled, requires a vector store, and an embedder unless the vector store embeds text itself (isSelfEmbedding). Default topK is 4, default messageRange is {before: 1, after: 1}. maxChunkChars caps the characters of message text per embedded chunk; see Long messages.

workingMemory?:

WorkingMemory
Configuration for working memory feature. Can be { enabled: boolean; template?: string; schema?: ZodObject<any> | JSONSchema7; scope?: 'thread' | 'resource' } or { enabled: boolean } to disable.

observationalMemory?:

boolean | ObservationalMemoryOptions
Enable Observational Memory for long-context agentic memory. Set to true for defaults, or pass a config object to customize token budgets, models, and scope. See Observational Memory reference for configuration details.

generateTitle?:

boolean | { model?: DynamicArgument<MastraModelConfig>; instructions?: DynamicArgument<string>; minMessages?: number; emitEvent?: boolean }
Controls automatic thread title generation from the conversation transcript. Accepts a boolean or an object with a custom model (any MastraModelConfig: a model instance, a "provider/model" ID, or an OpenAI-compatible config; defaults to the agent's own model), custom instructions, a minimum message count, and emitEvent. With emitEvent: true the run's stream waits for the title and emits it as a transient data-thread-title chunk before finish (durable and evented agents persist the title but don't emit the chunk yet).

Returns
Direct link to Returns

memory:

Memory
A new Memory instance with the specified configuration.

saveMessages()
Direct link to savemessages

agent.generate() and agent.stream() persist messages for you. Call memory.saveMessages() when you need to write messages yourself, for example to seed a thread, to import a transcript, or to store messages that originated outside Mastra. Each message needs a threadId and a resourceId, so create the thread with createThread() before saving into it.

await memory.saveMessages({
messages: [
{
id: 'msg-1',
threadId: 'thread-123',
resourceId: 'user-456',
role: 'user',
createdAt: new Date(),
content: {
format: 2,
parts: [{ type: 'text', text: 'Where is my order?' }],
},
},
],
})

Parameters
Direct link to Parameters

messages:

MastraDBMessage[]
The messages to save. Every message must include a threadId and a resourceId.

memoryConfig?:

MemoryConfig
Per-call memory options. Merged over the options passed to the constructor.

observabilityContext?:

Partial<ObservabilityContext>
Tracing context attached to the save operation.

Returns Promise<{ messages: MastraDBMessage[]; usage?: { tokens: number } }>. usage is present when the embedder reports token usage while indexing messages for semantic recall.

MastraDBMessage
Direct link to mastradbmessage

Storage uses a single message shape, MastraDBMessage. The methods that hand messages back or take them in use this shape, including saveMessages() and recall().

id:

string
Message identifier.

role:

'user' | 'assistant' | 'system' | 'signal'
Who produced the message. System messages and transient signals are not persisted.

threadId?:

string
Thread the message belongs to. Required when saving.

resourceId?:

string
Resource (usually a user or tenant) the message belongs to. Required when saving.

createdAt:

Date
Message timestamp.

content:

MastraMessageContentV2
The message body. Its parts array holds the text, reasoning, tool calls, and attachments.

content.parts is the part the agent actually reads. content.format is always 2 for stored messages, and content.metadata carries arbitrary custom data. content.toolInvocations, content.reasoning, and content.experimental_attachments are flat mirrors kept for AI SDK v4 compatibility; write to parts instead.

const assistantMessage = {
id: 'msg-2',
threadId: 'thread-123',
resourceId: 'user-456',
role: 'assistant',
createdAt: new Date(),
content: {
format: 2,
parts: [
{ type: 'text', text: 'It ships tomorrow.' },
{
type: 'tool-invocation',
toolInvocation: {
state: 'result',
toolCallId: 'call-1',
toolName: 'lookupOrder',
args: { orderId: 'A-1' },
result: { eta: '2026-10-30' },
},
},
],
metadata: { source: 'import' },
},
}

Extended usage example
Direct link to Extended usage example

src/mastra/agents/test-agent.ts
import { Memory } from '@mastra/memory'
import { Agent } from '@mastra/core/agent'
import { LibSQLStore, LibSQLVector } from '@mastra/libsql'

export const agent = new Agent({
name: 'test-agent',
instructions: 'You are an agent with memory.',
model: 'openai/gpt-6.1-sol',
memory: new Memory({
storage: new LibSQLStore({
id: 'test-agent-storage',
url: 'file:./working-memory.db',
}),
vector: new LibSQLVector({
id: 'test-agent-vector',
url: 'file:./vector-memory.db',
}),
options: {
lastMessages: 10,
semanticRecall: {
topK: 3,
messageRange: 2,
scope: 'resource',
},
workingMemory: {
enabled: true,
},
generateTitle: true,
},
}),
})

PostgreSQL with index configuration
Direct link to PostgreSQL with index configuration

src/mastra/agents/pg-agent.ts
import { Memory } from '@mastra/memory'
import { Agent } from '@mastra/core/agent'
import { ModelRouterEmbeddingModel } from '@mastra/core/llm'
import { PostgresStore, PgVector } from '@mastra/pg'

export const agent = new Agent({
name: 'pg-agent',
instructions: 'You are an agent with optimized PostgreSQL memory.',
model: 'openai/gpt-6.1-sol',
memory: new Memory({
storage: new PostgresStore({
id: 'pg-agent-storage',
connectionString: process.env.DATABASE_URL,
}),
vector: new PgVector({
id: 'pg-agent-vector',
connectionString: process.env.DATABASE_URL,
}),
embedder: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
options: {
lastMessages: 20,
semanticRecall: {
topK: 5,
messageRange: 3,
scope: 'resource',
indexConfig: {
type: 'hnsw', // Use HNSW for better performance
metric: 'dotproduct', // Optimal for OpenAI embeddings
hnsw: {
m: 16, // Number of bi-directional links
efConstruction: 64, // Construction-time candidate list size
},
},
},
workingMemory: {
enabled: true,
},
},
}),
})