Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/mastra-ai/mastra/llms.txt

Use this file to discover all available pages before exploring further.

Overview

MastraMemory is the abstract base class for implementing conversation memory systems in Mastra. It provides thread-based conversation organization, optional vector database integration for semantic similarity search, and working memory templates for structured conversation state.

Type Definition

abstract class MastraMemory extends MastraBase {
  readonly id: string;
  MAX_CONTEXT_TOKENS?: number;
  protected _storage?: MastraCompositeStore;
  vector?: MastraVector;
  embedder?: MastraEmbeddingModel<string>;
  embedderOptions?: MastraEmbeddingOptions;
  protected threadConfig: MemoryConfig;
}

Constructor

constructor(config: {
  id?: string;
  name: string;
  options?: MemoryConfig;
  storage?: MastraCompositeStore;
  vector?: MastraVector;
  embedder?: EmbeddingModelId | MastraEmbeddingModel<string>;
  embedderOptions?: MastraEmbeddingOptions;
})
config
object
required
Memory configuration

Properties

id
string
Unique identifier for the memory instance
MAX_CONTEXT_TOKENS
number | undefined
Maximum context tokens to maintain
storage
MastraCompositeStore
The storage provider (throws error if accessed before initialization)
vector
MastraVector | undefined
Vector store for semantic search
embedder
MastraEmbeddingModel | undefined
Embedding model for generating vectors
embedderOptions
MastraEmbeddingOptions | undefined
Options for the embedding model
hasOwnStorage
boolean
Whether this memory instance has its own storage configured

Abstract Methods

getThreadById

abstract getThreadById(params: { threadId: string }): Promise<StorageThreadType | null>
Retrieves a specific thread by its ID.
params.threadId
string
required
The unique identifier of the thread
thread
StorageThreadType | null
The thread or null if not found

listThreads

abstract listThreads(args: StorageListThreadsInput): Promise<StorageListThreadsOutput>
Lists threads with optional filtering by resourceId and metadata.
args
StorageListThreadsInput
required
Query parameters
result
StorageListThreadsOutput
Paginated thread results with metadata

saveThread

abstract saveThread(params: {
  thread: StorageThreadType;
  memoryConfig?: MemoryConfig;
}): Promise<StorageThreadType>
Saves or updates a thread.
params
object
required
thread
StorageThreadType
The saved thread

saveMessages

abstract saveMessages(args: {
  messages: MastraDBMessage[];
  memoryConfig?: MemoryConfig;
}): Promise<{ messages: MastraDBMessage[]; usage?: { tokens: number } }>
Saves messages to a thread.
args
object
required
result
{ messages: MastraDBMessage[]; usage?: { tokens: number } }
The saved messages with optional token usage

recall

abstract recall(args: StorageListMessagesInput & {
  threadConfig?: MemoryConfig;
  vectorSearchString?: string;
}): Promise<{ messages: MastraDBMessage[]; usage?: { tokens: number } }>
Retrieves messages for a specific thread with optional semantic recall.
args
object
required
result
{ messages: MastraDBMessage[]; usage?: { tokens: number } }
Array of messages in mastra-db format with optional token usage

deleteThread

abstract deleteThread(threadId: string): Promise<void>
Deletes a thread.
threadId
string
required
The ID of the thread to delete

Public Methods

createThread

createThread(params: {
  resourceId: string;
  threadId?: string;
  title?: string;
  metadata?: Record<string, unknown>;
  memoryConfig?: MemoryConfig;
  saveThread?: boolean;
}): Promise<StorageThreadType>
Helper method to create a new thread.
params
object
required
thread
StorageThreadType
The created thread

getSystemMessage

getSystemMessage(input: {
  threadId: string;
  resourceId?: string;
  memoryConfig?: MemoryConfig;
}): Promise<string | null>
Get a system message to inject into the conversation. Can be overridden by implementations.
input
object
required
message
string | null
The system message, or null

listTools

listTools(config?: MemoryConfig): Record<string, ToolAction>
Get tools that should be available to the agent. Can be overridden by implementations.
config
MemoryConfig
Memory configuration
tools
Record<string, ToolAction>
Tools provided by this memory instance

setStorage

setStorage(storage: MastraCompositeStore): void
Sets the storage provider.
storage
MastraCompositeStore
required
The storage provider to use

setVector

setVector(vector: MastraVector): void
Sets the vector store.
vector
MastraVector
required
The vector store to use

setEmbedder

setEmbedder(
  embedder: EmbeddingModelId | MastraEmbeddingModel<string>,
  embedderOptions?: MastraEmbeddingOptions
): void
Sets the embedding model.
embedder
EmbeddingModelId | MastraEmbeddingModel
required
The embedding model to use
embedderOptions
MastraEmbeddingOptions
Options for the embedding model

getMergedThreadConfig

getMergedThreadConfig(config?: MemoryConfig): MemoryConfig
Merges provided config with instance defaults.
config
MemoryConfig
Configuration to merge
config
MemoryConfig
The merged configuration

estimateTokens

estimateTokens(text: string): number
Estimates the number of tokens in a text string.
text
string
required
The text to estimate
tokens
number
Estimated token count

Example Implementation

import { MastraMemory } from '@mastra/core/memory';

export class MyCustomMemory extends MastraMemory {
  async getThreadById({ threadId }: { threadId: string }) {
    // Implementation
    return this.storage.getThreadById(threadId);
  }

  async listThreads(args: StorageListThreadsInput) {
    // Implementation
    return this.storage.listThreads(args);
  }

  async saveThread({ thread, memoryConfig }) {
    // Implementation
    return this.storage.saveThread(thread);
  }

  async saveMessages({ messages, memoryConfig }) {
    // Implementation
    return this.storage.saveMessages(messages);
  }

  async recall(args) {
    // Implementation with optional semantic recall
    const messages = await this.storage.listMessages(args);
    
    if (args.vectorSearchString && this.vector && this.embedder) {
      // Perform semantic search
      const results = await this.vector.query({
        query: args.vectorSearchString,
        topK: 5
      });
      // Merge with chronological messages
    }
    
    return { messages };
  }

  async deleteThread(threadId: string) {
    // Implementation
    await this.storage.deleteThread(threadId);
  }
}

Build docs developers (and LLMs) love