@mastra/mongodb 0.0.0-error-handler-fix-20251020202607 → 0.0.0-esbuild-bundle-worker-20260807182016

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/CHANGELOG.md +4342 -3
  2. package/LICENSE.md +15 -0
  3. package/README.md +48 -25
  4. package/dist/docs/SKILL.md +35 -0
  5. package/dist/docs/assets/SOURCE_MAP.json +6 -0
  6. package/dist/docs/references/docs-memory-semantic-recall.md +401 -0
  7. package/dist/docs/references/docs-memory-working-memory.md +431 -0
  8. package/dist/docs/references/docs-storage-overview.md +214 -0
  9. package/dist/docs/references/guides-rag-retrieval.md +520 -0
  10. package/dist/docs/references/guides-rag-vector-databases.md +669 -0
  11. package/dist/docs/references/reference-storage-composite.md +397 -0
  12. package/dist/docs/references/reference-storage-mongodb.md +267 -0
  13. package/dist/docs/references/reference-vectors-mongodb.md +567 -0
  14. package/dist/index.cjs +11018 -2483
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.js +10999 -2481
  17. package/dist/index.js.map +1 -1
  18. package/dist/storage/connectors/MongoDBConnector.d.ts +14 -0
  19. package/dist/storage/connectors/MongoDBConnector.d.ts.map +1 -1
  20. package/dist/storage/db/index.d.ts +10 -0
  21. package/dist/storage/db/index.d.ts.map +1 -0
  22. package/dist/storage/domains/agents/index.d.ts +57 -0
  23. package/dist/storage/domains/agents/index.d.ts.map +1 -0
  24. package/dist/storage/domains/background-tasks/index.d.ts +36 -0
  25. package/dist/storage/domains/background-tasks/index.d.ts.map +1 -0
  26. package/dist/storage/domains/blobs/index.d.ts +21 -0
  27. package/dist/storage/domains/blobs/index.d.ts.map +1 -0
  28. package/dist/storage/domains/datasets/index.d.ts +46 -0
  29. package/dist/storage/domains/datasets/index.d.ts.map +1 -0
  30. package/dist/storage/domains/experiments/index.d.ts +59 -0
  31. package/dist/storage/domains/experiments/index.d.ts.map +1 -0
  32. package/dist/storage/domains/mcp-clients/index.d.ts +34 -0
  33. package/dist/storage/domains/mcp-clients/index.d.ts.map +1 -0
  34. package/dist/storage/domains/mcp-servers/index.d.ts +34 -0
  35. package/dist/storage/domains/mcp-servers/index.d.ts.map +1 -0
  36. package/dist/storage/domains/memory/index.d.ts +73 -48
  37. package/dist/storage/domains/memory/index.d.ts.map +1 -1
  38. package/dist/storage/domains/notifications/index.d.ts +28 -0
  39. package/dist/storage/domains/notifications/index.d.ts.map +1 -0
  40. package/dist/storage/domains/observability/index.d.ts +92 -0
  41. package/dist/storage/domains/observability/index.d.ts.map +1 -0
  42. package/dist/storage/domains/prompt-blocks/index.d.ts +34 -0
  43. package/dist/storage/domains/prompt-blocks/index.d.ts.map +1 -0
  44. package/dist/storage/domains/schedules/index.d.ts +35 -0
  45. package/dist/storage/domains/schedules/index.d.ts.map +1 -0
  46. package/dist/storage/domains/scorer-definitions/index.d.ts +34 -0
  47. package/dist/storage/domains/scorer-definitions/index.d.ts.map +1 -0
  48. package/dist/storage/domains/scores/index.d.ts +37 -28
  49. package/dist/storage/domains/scores/index.d.ts.map +1 -1
  50. package/dist/storage/domains/skills/index.d.ts +35 -0
  51. package/dist/storage/domains/skills/index.d.ts.map +1 -0
  52. package/dist/storage/domains/utils.d.ts +23 -0
  53. package/dist/storage/domains/utils.d.ts.map +1 -1
  54. package/dist/storage/domains/workflow-definitions/index.d.ts +20 -0
  55. package/dist/storage/domains/workflow-definitions/index.d.ts.map +1 -0
  56. package/dist/storage/domains/workflows/index.d.ts +41 -25
  57. package/dist/storage/domains/workflows/index.d.ts.map +1 -1
  58. package/dist/storage/domains/workspaces/index.d.ts +35 -0
  59. package/dist/storage/domains/workspaces/index.d.ts.map +1 -0
  60. package/dist/storage/index.d.ts +45 -207
  61. package/dist/storage/index.d.ts.map +1 -1
  62. package/dist/storage/retention.d.ts +121 -0
  63. package/dist/storage/retention.d.ts.map +1 -0
  64. package/dist/storage/types.d.ts +129 -4
  65. package/dist/storage/types.d.ts.map +1 -1
  66. package/dist/vector/index.d.ts +408 -13
  67. package/dist/vector/index.d.ts.map +1 -1
  68. package/package.json +25 -20
  69. package/dist/storage/MongoDBConnector.d.ts +0 -23
  70. package/dist/storage/MongoDBConnector.d.ts.map +0 -1
  71. package/dist/storage/domains/legacy-evals/index.d.ts +0 -18
  72. package/dist/storage/domains/legacy-evals/index.d.ts.map +0 -1
  73. package/dist/storage/domains/operations/index.d.ts +0 -38
  74. package/dist/storage/domains/operations/index.d.ts.map +0 -1
  75. package/dist/storage/domains/traces/index.d.ts +0 -18
  76. package/dist/storage/domains/traces/index.d.ts.map +0 -1
package/LICENSE.md CHANGED
@@ -1,3 +1,18 @@
1
+ Portions of this software are licensed as follows:
2
+
3
+ - All content that resides under any directory named "ee/" within this
4
+ repository, including but not limited to:
5
+ - `packages/core/src/auth/ee/`
6
+ - `packages/server/src/server/auth/ee/`
7
+ is licensed under the license defined in `ee/LICENSE`.
8
+
9
+ - All third-party components incorporated into the Mastra Software are
10
+ licensed under the original license provided by the owner of the
11
+ applicable component.
12
+
13
+ - Content outside of the above-mentioned directories or restrictions is
14
+ available under the "Apache License 2.0" as defined below.
15
+
1
16
  # Apache License 2.0
2
17
 
3
18
  Copyright (c) 2025 Kepler Software, Inc.
package/README.md CHANGED
@@ -21,6 +21,7 @@ npm install @mastra/mongodb
21
21
  import { MongoDBVector } from '@mastra/mongodb';
22
22
 
23
23
  const vectorDB = new MongoDBVector({
24
+ id: 'mongodb-vector',
24
25
  uri: 'mongodb://mongodb:mongodb@localhost:27018/?authSource=admin&directConnection=true',
25
26
  dbName: 'vector_db',
26
27
  });
@@ -49,7 +50,6 @@ const results = await vectorDB.query({
49
50
  topK: 10,
50
51
  filter: { text: 'doc1' },
51
52
  includeVector: false,
52
- minScore: 0.5,
53
53
  });
54
54
 
55
55
  // Clean up
@@ -62,47 +62,70 @@ await vectorDB.disconnect();
62
62
  import { MongoDBStore } from '@mastra/mongodb';
63
63
 
64
64
  const store = new MongoDBStore({
65
+ id: 'mongodb-store',
65
66
  uri: 'mongodb://mongodb:mongodb@localhost:27018/?authSource=admin&directConnection=true',
66
67
  dbName: 'mastra',
67
68
  });
68
69
 
69
70
  // Create a thread
70
71
  await store.saveThread({
71
- id: 'thread-123',
72
- resourceId: 'resource-456',
73
- title: 'My Thread',
74
- metadata: { key: 'value' },
72
+ thread: {
73
+ id: 'thread-123',
74
+ resourceId: 'resource-456',
75
+ title: 'My Thread',
76
+ metadata: { key: 'value' },
77
+ createdAt: new Date(),
78
+ },
75
79
  });
76
80
 
77
81
  // Add messages to thread
78
- await store.saveMessages([
79
- {
80
- id: 'msg-789',
81
- threadId: 'thread-123',
82
- role: 'user',
83
- type: 'text',
84
- content: [{ type: 'text', text: 'Hello' }],
85
- },
86
- ]);
82
+ await store.saveMessages({
83
+ messages: [
84
+ {
85
+ id: 'msg-789',
86
+ threadId: 'thread-123',
87
+ role: 'user',
88
+ content: { content: 'Hello' },
89
+ resourceId: 'resource-456',
90
+ createdAt: new Date(),
91
+ },
92
+ ],
93
+ });
87
94
 
88
95
  // Query threads and messages
89
- const savedThread = await store.getThread('thread-123');
90
- const messages = await store.getMessages('thread-123');
96
+ const savedThread = await store.getThreadById({ threadId: 'thread-123' });
97
+ const { messages } = await store.listMessages({ threadId: 'thread-123' });
91
98
  ```
92
99
 
93
100
  ## Configuration
94
101
 
95
102
  The MongoDB vector store is initialized with:
96
103
 
104
+ - `id`: Unique identifier for this store instance
97
105
  - `uri`: MongoDB connection string (with credentials and options)
98
106
  - `dbName`: Name of the database to use
107
+ - `embeddingFieldPath` (optional): Path to the field that stores vector embeddings. Supports nested paths using dot notation (e.g., `'text.contentEmbedding'`). Defaults to `'embedding'`.
99
108
 
100
109
  Example:
101
110
 
102
111
  ```typescript
103
112
  const vectorDB = new MongoDBVector({
113
+ id: 'mongodb-vector',
114
+ uri: 'mongodb://mongodb:mongodb@localhost:27018/?authSource=admin&directConnection=true',
115
+ dbName: 'vector_db',
116
+ });
117
+ ```
118
+
119
+ ### Custom Embedding Field Path
120
+
121
+ If you need to store embeddings in a nested field structure, use the `embeddingFieldPath` option:
122
+
123
+ ```typescript
124
+ const vectorDB = new MongoDBVector({
125
+ id: 'mongodb-vector',
104
126
  uri: 'mongodb://mongodb:mongodb@localhost:27018/?authSource=admin&directConnection=true',
105
127
  dbName: 'vector_db',
128
+ embeddingFieldPath: 'text.contentEmbedding', // Store embeddings at text.contentEmbedding
106
129
  });
107
130
  ```
108
131
 
@@ -112,7 +135,6 @@ const vectorDB = new MongoDBVector({
112
135
 
113
136
  - Vector similarity search with cosine, euclidean, and dotproduct metrics (Atlas Search)
114
137
  - Metadata filtering with MongoDB-style query syntax
115
- - Minimum score threshold for queries
116
138
  - Automatic UUID generation for vectors
117
139
  - Collection (index) management: create, list, describe, delete
118
140
  - Atlas Search readiness checks for reliable testing
@@ -151,24 +173,25 @@ The following distance metrics are supported:
151
173
 
152
174
  - `createIndex({indexName, dimension, metric})`: Create a new collection with vector search support
153
175
  - `upsert({indexName, vectors, metadata?, ids?})`: Add or update vectors
154
- - `query({indexName, queryVector, topK?, filter?, includeVector?, minScore?, documentFilter?})`: Search for similar vectors (optionally filter by document content)
176
+ - `query({indexName, queryVector, topK?, filter?, includeVector?, documentFilter?})`: Search for similar vectors (optionally filter by document content)
155
177
 
156
178
  > **Note:** `documentFilter` allows filtering results based on the content of the `document` field. Example: `{ $contains: 'specific text' }` will return only vectors whose associated document contains the specified text.
157
179
 
180
+ - `updateVector({ indexName, id?, filter?, update })`: Update a single vector by ID or metadata filter
181
+ - `deleteVector({ indexName, id })`: Delete a single vector by ID
182
+ - `deleteVectors({ indexName, ids?, filter? })`: Delete multiple vectors by IDs or metadata filter
158
183
  - `listIndexes()`: List all vector-enabled collections
159
184
  - `describeIndex(indexName)`: Get collection statistics (dimension, count, metric)
160
- - `updateIndexById(indexName, id, { vector?, metadata? })`: Update a vector and/or its metadata by ID
161
- - `deleteIndexById(indexName, id)`: Delete a vector by ID
162
185
  - `deleteIndex(indexName)`: Delete a collection
163
186
  - `disconnect()`: Close the MongoDB connection
164
187
 
165
188
  ## Storage Methods
166
189
 
167
- - `saveThread(thread)`: Create or update a thread
168
- - `getThread(threadId)`: Get a thread by ID
169
- - `deleteThread(threadId)`: Delete a thread and its messages
170
- - `saveMessages(messages)`: Save multiple messages in a transaction
171
- - `getMessages(threadId)`: Get all messages for a thread
190
+ - `saveThread({ thread })`: Create or update a thread
191
+ - `getThreadById({ threadId })`: Get a thread by ID
192
+ - `deleteThread({ threadId })`: Delete a thread and its messages
193
+ - `saveMessages({ messages })`: Save multiple messages in a transaction
194
+ - `listMessages({ threadId, perPage?, page? })`: Get messages for a thread with pagination
172
195
  - `deleteMessages(messageIds)`: Delete specific messages
173
196
 
174
197
  ## Query Response Format
@@ -0,0 +1,35 @@
1
+ ---
2
+ name: mastra-mongodb
3
+ description: Documentation for @mastra/mongodb. Use when working with @mastra/mongodb APIs, configuration, or implementation.
4
+ metadata:
5
+ package: "@mastra/mongodb"
6
+ version: "0.0.0-esbuild-bundle-worker-20260807182016"
7
+ ---
8
+
9
+ ## When to use
10
+
11
+ Use this skill whenever you are working with @mastra/mongodb to obtain the domain-specific knowledge.
12
+
13
+ ## How to use
14
+
15
+ Read the individual reference documents for detailed explanations and code examples.
16
+
17
+ ### Docs
18
+
19
+ - [Semantic recall](references/docs-memory-semantic-recall.md) - Learn how to use semantic recall in Mastra to retrieve relevant messages from past conversations using vector search and embeddings.
20
+ - [Working memory](references/docs-memory-working-memory.md) - Learn how to configure working memory in Mastra to store persistent user data, preferences.
21
+ - [Storage overview](references/docs-storage-overview.md) - Configure storage for Mastra to persist runtime state across agents, workflows, observability, evals, schedules, and memory.
22
+
23
+ ### Guides
24
+
25
+ - [Retrieval, semantic search, reranking](references/guides-rag-retrieval.md) - Guide on retrieval processes in Mastra's RAG systems, including semantic search, filtering, and re-ranking.
26
+ - [Storing embeddings in a vector database](references/guides-rag-vector-databases.md) - Guide on vector storage options in Mastra, including embedded and dedicated vector databases for similarity search.
27
+
28
+ ### Reference
29
+
30
+ - [Reference: Composite storage](references/reference-storage-composite.md) - Documentation for combining multiple storage backends in Mastra.
31
+ - [Reference: MongoDB storage](references/reference-storage-mongodb.md) - Documentation for the MongoDB storage implementation in Mastra.
32
+ - [Reference: MongoDB vector store](references/reference-vectors-mongodb.md) - Documentation for the MongoDBVector class in Mastra, which provides vector search using MongoDB Atlas and Atlas Vector Search.
33
+
34
+
35
+ Read [assets/SOURCE_MAP.json](assets/SOURCE_MAP.json) for source code references.
@@ -0,0 +1,6 @@
1
+ {
2
+ "version": "0.0.0-esbuild-bundle-worker-20260807182016",
3
+ "package": "@mastra/mongodb",
4
+ "exports": {},
5
+ "modules": {}
6
+ }
@@ -0,0 +1,401 @@
1
+ > Discover all available pages from the documentation index: https://mastra.ai/llms.txt
2
+
3
+ # Semantic recall
4
+
5
+ If you ask your friend what they did last weekend, they will search in their memory for events associated with "last weekend" and then tell you what they did. That's sort of like how semantic recall works in Mastra.
6
+
7
+ > **📹 Watch:** Watch [Mastra semantic recall](https://www.youtube.com/watch?v=UVZtK8cK8xQ\&pp=ygUVbWFzdHJhIHdvcmtpbmcgbWVtb3J5) to see how agents retrieve relevant messages from past conversations.
8
+
9
+ ## How semantic recall works
10
+
11
+ Semantic recall is RAG-based search that helps agents maintain context across longer interactions when messages are no longer within [recent message history](https://mastra.ai/docs/memory/message-history).
12
+
13
+ It uses vector embeddings of messages for similarity search and integrates with vector stores, plus has configurable context windows around retrieved messages.
14
+
15
+ ![Diagram showing Mastra Memory semantic recall](/assets/images/semantic-recall-fd7b9336a6d0d18019216cb6d3dbe710.png)
16
+
17
+ When it's enabled, new messages are used to query a vector DB for semantically similar messages.
18
+
19
+ After getting a response from the LLM, all new messages (user, assistant, and tool calls/results) are inserted into the vector DB to be recalled in later interactions.
20
+
21
+ ## Quickstart
22
+
23
+ Semantic recall is disabled by default. To enable it, set `semanticRecall: true` in `options` and provide a `vector` store and `embedder`:
24
+
25
+ **LibSQL**:
26
+
27
+ ```typescript
28
+ import { Agent } from '@mastra/core/agent'
29
+ import { Memory } from '@mastra/memory'
30
+ import { LibSQLStore, LibSQLVector } from '@mastra/libsql'
31
+ import { ModelRouterEmbeddingModel } from '@mastra/core/llm'
32
+
33
+ const agent = new Agent({
34
+ id: 'support-agent',
35
+ name: 'SupportAgent',
36
+ instructions: 'You are a helpful support agent.',
37
+ model: 'openai/gpt-5.6-sol',
38
+ memory: new Memory({
39
+ storage: new LibSQLStore({
40
+ id: 'agent-storage',
41
+ url: 'file:./local.db',
42
+ }),
43
+ vector: new LibSQLVector({
44
+ id: 'agent-vector',
45
+ url: 'file:./local.db',
46
+ }),
47
+ embedder: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
48
+ options: {
49
+ semanticRecall: true,
50
+ },
51
+ }),
52
+ })
53
+ ```
54
+
55
+ **MongoDB**:
56
+
57
+ ```typescript
58
+ import { Agent } from '@mastra/core/agent'
59
+ import { Memory } from '@mastra/memory'
60
+ import { MongoDBStore, MongoDBVector } from '@mastra/mongodb'
61
+ import { ModelRouterEmbeddingModel } from '@mastra/core/llm'
62
+
63
+ const agent = new Agent({
64
+ id: 'support-agent',
65
+ name: 'SupportAgent',
66
+ instructions: 'You are a helpful support agent.',
67
+ model: 'openai/gpt-5.6-sol',
68
+ memory: new Memory({
69
+ storage: new MongoDBStore({
70
+ id: 'agent-storage',
71
+ uri: process.env.MONGODB_URI,
72
+ dbName: process.env.MONGODB_DB_NAME,
73
+ }),
74
+ vector: new MongoDBVector({
75
+ id: 'agent-vector',
76
+ uri: process.env.MONGODB_URI,
77
+ dbName: process.env.MONGODB_DB_NAME,
78
+ }),
79
+ embedder: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
80
+ options: {
81
+ semanticRecall: true,
82
+ },
83
+ }),
84
+ })
85
+ ```
86
+
87
+ ## Using the `recall()` method
88
+
89
+ While `listMessages` retrieves messages by thread ID with basic pagination, [`recall()`](https://mastra.ai/reference/memory/recall) adds support for **semantic search**. When you need to find messages by meaning rather than recency, use `recall()` with a `vectorSearchString`:
90
+
91
+ ```typescript
92
+ const memory = await agent.getMemory()
93
+
94
+ // Basic recall - similar to listMessages
95
+ const { messages } = await memory!.recall({
96
+ threadId: 'thread-123',
97
+ perPage: 50,
98
+ })
99
+
100
+ // Semantic recall - find messages by meaning
101
+ const { messages: relevantMessages } = await memory!.recall({
102
+ threadId: 'thread-123',
103
+ vectorSearchString: 'What did we discuss about the project deadline?',
104
+ threadConfig: {
105
+ semanticRecall: true,
106
+ },
107
+ })
108
+ ```
109
+
110
+ ## Storage configuration
111
+
112
+ Semantic recall relies on a [storage and vector db](https://mastra.ai/reference/memory/memory-class) to store messages and their embeddings.
113
+
114
+ ```ts
115
+ import { Memory } from '@mastra/memory'
116
+ import { Agent } from '@mastra/core/agent'
117
+ import { LibSQLStore, LibSQLVector } from '@mastra/libsql'
118
+
119
+ const agent = new Agent({
120
+ memory: new Memory({
121
+ // this is the default storage db if omitted
122
+ storage: new LibSQLStore({
123
+ id: 'agent-storage',
124
+ url: 'file:./local.db',
125
+ }),
126
+ // this is the default vector db if omitted
127
+ vector: new LibSQLVector({
128
+ id: 'agent-vector',
129
+ url: 'file:./local.db',
130
+ }),
131
+ options: {
132
+ semanticRecall: true,
133
+ },
134
+ }),
135
+ })
136
+ ```
137
+
138
+ Each vector store page below includes installation instructions, configuration parameters, and usage examples:
139
+
140
+ - [Astra](https://mastra.ai/reference/vectors/astra)
141
+ - [Chroma](https://mastra.ai/reference/vectors/chroma)
142
+ - [Cloudflare Vectorize](https://mastra.ai/reference/vectors/vectorize)
143
+ - [Convex](https://mastra.ai/reference/vectors/convex)
144
+ - [Couchbase](https://mastra.ai/reference/vectors/couchbase)
145
+ - [DuckDB](https://mastra.ai/reference/vectors/duckdb)
146
+ - [Elasticsearch](https://mastra.ai/reference/vectors/elasticsearch)
147
+ - [LanceDB](https://mastra.ai/reference/vectors/lance)
148
+ - [libSQL](https://mastra.ai/reference/vectors/libsql)
149
+ - [MongoDB](https://mastra.ai/reference/vectors/mongodb)
150
+ - [OpenSearch](https://mastra.ai/reference/vectors/opensearch)
151
+ - [Pinecone](https://mastra.ai/reference/vectors/pinecone)
152
+ - [PostgreSQL](https://mastra.ai/reference/vectors/pg)
153
+ - [Qdrant](https://mastra.ai/reference/vectors/qdrant)
154
+ - [S3 Vectors](https://mastra.ai/reference/vectors/s3vectors)
155
+ - [Turbopuffer](https://mastra.ai/reference/vectors/turbopuffer)
156
+ - [Upstash](https://mastra.ai/reference/vectors/upstash)
157
+
158
+ ## Recall configuration
159
+
160
+ The following options control semantic recall behavior:
161
+
162
+ 1. **topK**: The number of similar messages to retrieve
163
+ 2. **messageRange**: The surrounding messages to include with each match
164
+ 3. **scope**: Whether to search the current thread or all threads for a resource
165
+ 4. **filter**: Metadata criteria that restrict search results
166
+
167
+ ```typescript
168
+ const agent = new Agent({
169
+ id: 'agent',
170
+ memory: new Memory({
171
+ options: {
172
+ semanticRecall: {
173
+ topK: 3, // Retrieve 3 similar messages
174
+ messageRange: 2, // Include 2 messages before and after each match
175
+ scope: 'resource', // Search all threads for this resource
176
+ filter: { projectId: { $eq: 'project-a' } },
177
+ },
178
+ },
179
+ }),
180
+ })
181
+ ```
182
+
183
+ > **Note:** `scope: 'resource'` is supported by the LibSQL, PostgreSQL, MongoDB, and Upstash storage adapters.
184
+
185
+ ### Metadata filtering
186
+
187
+ The `filter` option restricts semantic recall results to messages with matching thread metadata.
188
+
189
+ ```typescript
190
+ const agent = new Agent({
191
+ id: 'agent',
192
+ memory: new Memory({
193
+ options: {
194
+ semanticRecall: {
195
+ scope: 'resource',
196
+ filter: {
197
+ projectId: { $eq: 'project-a' },
198
+ category: { $in: ['work', 'personal'] },
199
+ },
200
+ },
201
+ },
202
+ }),
203
+ })
204
+ ```
205
+
206
+ Filters match metadata stored on message embeddings when messages are saved. If thread metadata changes later, existing embeddings keep their previous metadata until those messages are saved or indexed again.
207
+
208
+ Supported filter operators:
209
+
210
+ - `$and`: Logical AND
211
+ - `$eq`: Equal to
212
+ - `$gt`: Greater than
213
+ - `$gte`: Greater than or equal
214
+ - `$in`: In array
215
+ - `$lt`: Less than
216
+ - `$lte`: Less than or equal
217
+ - `$ne`: Not equal to
218
+ - `$nin`: Not in array
219
+ - `$or`: Logical OR
220
+
221
+ The following example demonstrates metadata filters for common use cases:
222
+
223
+ ```typescript
224
+ // Filter by project
225
+ const options = {
226
+ semanticRecall: { filter: { projectId: { $eq: 'my-project' } } },
227
+ }
228
+
229
+ // Filter by multiple categories
230
+ const options = {
231
+ semanticRecall: { filter: { category: { $in: ['work', 'research'] } } },
232
+ }
233
+
234
+ // Filter by project and priority
235
+ const options = {
236
+ semanticRecall: {
237
+ filter: {
238
+ $and: [{ projectId: { $eq: 'project-a' } }, { priority: { $gte: 3 } }],
239
+ },
240
+ },
241
+ }
242
+ ```
243
+
244
+ ## Embedder configuration
245
+
246
+ Semantic recall relies on an [embedding model](https://mastra.ai/reference/memory/memory-class) to convert messages into embeddings. Mastra supports embedding models through the model router using `provider/model` strings, or you can use any [embedding model](https://sdk.vercel.ai/docs/ai-sdk-core/embeddings) compatible with the AI SDK.
247
+
248
+ ### Using the Model Router (Recommended)
249
+
250
+ The simplest way is to use a `provider/model` string with autocomplete support:
251
+
252
+ ```ts
253
+ import { Memory } from '@mastra/memory'
254
+ import { Agent } from '@mastra/core/agent'
255
+ import { ModelRouterEmbeddingModel } from '@mastra/core/llm'
256
+
257
+ const agent = new Agent({
258
+ id: 'agent',
259
+ memory: new Memory({
260
+ embedder: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
261
+ options: {
262
+ semanticRecall: true,
263
+ },
264
+ }),
265
+ })
266
+ ```
267
+
268
+ Supported embedding models:
269
+
270
+ - **OpenAI**: `text-embedding-3-small`, `text-embedding-3-large`, `text-embedding-ada-002`
271
+ - **Google**: `gemini-embedding-001`
272
+ - **OpenRouter**: Access embedding models from various providers
273
+
274
+ ```ts
275
+ import { Agent } from '@mastra/core/agent'
276
+ import { Memory } from '@mastra/memory'
277
+ import { ModelRouterEmbeddingModel } from '@mastra/core/llm'
278
+
279
+ const agent = new Agent({
280
+ id: 'agent',
281
+ memory: new Memory({
282
+ embedder: new ModelRouterEmbeddingModel({
283
+ providerId: 'openrouter',
284
+ modelId: 'openai/text-embedding-3-small',
285
+ }),
286
+ }),
287
+ })
288
+ ```
289
+
290
+ The model router automatically handles API key detection from environment variables (`OPENAI_API_KEY`, `GOOGLE_API_KEY`, `OPENROUTER_API_KEY`). Google models also fall back to `GOOGLE_GENERATIVE_AI_API_KEY`.
291
+
292
+ ### Using AI SDK Packages
293
+
294
+ You can also use AI SDK embedding models directly:
295
+
296
+ ```ts
297
+ import { Memory } from '@mastra/memory'
298
+ import { Agent } from '@mastra/core/agent'
299
+ import { ModelRouterEmbeddingModel } from '@mastra/core/llm'
300
+
301
+ const agent = new Agent({
302
+ id: 'agent',
303
+ memory: new Memory({
304
+ embedder: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
305
+ }),
306
+ })
307
+ ```
308
+
309
+ ### Using FastEmbed (local)
310
+
311
+ To use FastEmbed (a local embedding model), install `@mastra/fastembed`:
312
+
313
+ **npm**:
314
+
315
+ ```bash
316
+ npm install @mastra/fastembed@latest
317
+ ```
318
+
319
+ **pnpm**:
320
+
321
+ ```bash
322
+ pnpm add @mastra/fastembed@latest
323
+ ```
324
+
325
+ **Yarn**:
326
+
327
+ ```bash
328
+ yarn add @mastra/fastembed@latest
329
+ ```
330
+
331
+ **Bun**:
332
+
333
+ ```bash
334
+ bun add @mastra/fastembed@latest
335
+ ```
336
+
337
+ Then configure it in your memory:
338
+
339
+ ```ts
340
+ import { Memory } from '@mastra/memory'
341
+ import { Agent } from '@mastra/core/agent'
342
+ import { fastembed } from '@mastra/fastembed'
343
+
344
+ const agent = new Agent({
345
+ id: 'agent',
346
+ memory: new Memory({
347
+ embedder: fastembed,
348
+ }),
349
+ })
350
+ ```
351
+
352
+ ## PostgreSQL index optimization
353
+
354
+ When using PostgreSQL as your vector store, you can optimize semantic recall performance by configuring the vector index. This is particularly important for large-scale deployments with thousands of messages.
355
+
356
+ PostgreSQL supports both IVFFlat and HNSW indexes. By default, Mastra creates an IVFFlat index, but HNSW indexes typically provide better performance, especially with OpenAI embeddings which use inner product distance.
357
+
358
+ ```typescript
359
+ import { Memory } from '@mastra/memory'
360
+ import { PgStore, PgVector } from '@mastra/pg'
361
+
362
+ const agent = new Agent({
363
+ memory: new Memory({
364
+ storage: new PgStore({
365
+ id: 'agent-storage',
366
+ connectionString: process.env.DATABASE_URL,
367
+ }),
368
+ vector: new PgVector({
369
+ id: 'agent-vector',
370
+ connectionString: process.env.DATABASE_URL,
371
+ }),
372
+ options: {
373
+ semanticRecall: {
374
+ topK: 5,
375
+ messageRange: 2,
376
+ indexConfig: {
377
+ type: 'hnsw', // Use HNSW for better performance
378
+ metric: 'dotproduct', // Best for OpenAI embeddings
379
+ m: 16, // Number of bi-directional links (default: 16)
380
+ efConstruction: 64, // Size of candidate list during construction (default: 64)
381
+ },
382
+ },
383
+ },
384
+ }),
385
+ })
386
+ ```
387
+
388
+ For detailed information about index configuration options and performance tuning, see the [PgVector configuration guide](https://mastra.ai/reference/vectors/pg).
389
+
390
+ ## Disable semantic recall
391
+
392
+ Semantic recall is disabled by default (`semanticRecall: false`). Each call adds latency because new messages are converted into embeddings and used to query a vector database before the LLM receives them.
393
+
394
+ Keep semantic recall disabled when:
395
+
396
+ - Message history provides sufficient context for the current conversation.
397
+ - You're building performance-sensitive applications, like realtime two-way audio, where embedding and vector query latency is noticeable.
398
+
399
+ ## Viewing recalled messages
400
+
401
+ When tracing is enabled, any messages retrieved via semantic recall will appear in the agent's trace output, alongside recent message history (if configured).