@mastra/mongodb 1.5.1 → 1.5.2-alpha.0

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # @mastra/mongodb
2
2
 
3
+ ## 1.5.2-alpha.0
4
+
5
+ ### Patch Changes
6
+
7
+ - Fixed observation activation to always preserve a minimum amount of context. Previously, swapping buffered observation chunks could unexpectedly drop the context window to near-zero tokens. ([#13476](https://github.com/mastra-ai/mastra/pull/13476))
8
+
9
+ - Add a clear runtime error when `queryVector` is omitted for vector stores that require a vector for queries. Previously, omitting `queryVector` would produce confusing SDK-level errors; now each store throws a structured `MastraError` with `ErrorCategory.USER` explaining that metadata-only queries are not supported by that backend. ([#13286](https://github.com/mastra-ai/mastra/pull/13286))
10
+
11
+ - Updated dependencies [[`df170fd`](https://github.com/mastra-ai/mastra/commit/df170fd139b55f845bfd2de8488b16435bd3d0da), [`ae55343`](https://github.com/mastra-ai/mastra/commit/ae5534397fc006fd6eef3e4f80c235bcdc9289ef), [`c290cec`](https://github.com/mastra-ai/mastra/commit/c290cec5bf9107225de42942b56b487107aa9dce), [`f03e794`](https://github.com/mastra-ai/mastra/commit/f03e794630f812b56e95aad54f7b1993dc003add), [`aa4a5ae`](https://github.com/mastra-ai/mastra/commit/aa4a5aedb80d8d6837bab8cbb2e301215d1ba3e9), [`de3f584`](https://github.com/mastra-ai/mastra/commit/de3f58408752a8d80a295275c7f23fc306cf7f4f), [`d3fb010`](https://github.com/mastra-ai/mastra/commit/d3fb010c98f575f1c0614452667396e2653815f6), [`702ee1c`](https://github.com/mastra-ai/mastra/commit/702ee1c41be67cc532b4dbe89bcb62143508f6f0), [`f495051`](https://github.com/mastra-ai/mastra/commit/f495051eb6496a720f637fc85b6d69941c12554c), [`e622f1d`](https://github.com/mastra-ai/mastra/commit/e622f1d3ab346a8e6aca6d1fe2eac99bd961e50b), [`861f111`](https://github.com/mastra-ai/mastra/commit/861f11189211b20ddb70d8df81a6b901fc78d11e), [`00f43e8`](https://github.com/mastra-ai/mastra/commit/00f43e8e97a80c82b27d5bd30494f10a715a1df9), [`1b6f651`](https://github.com/mastra-ai/mastra/commit/1b6f65127d4a0d6c38d0a1055cb84527db529d6b), [`96a1702`](https://github.com/mastra-ai/mastra/commit/96a1702ce362c50dda20c8b4a228b4ad1a36a17a), [`cb9f921`](https://github.com/mastra-ai/mastra/commit/cb9f921320913975657abb1404855d8c510f7ac5), [`114e7c1`](https://github.com/mastra-ai/mastra/commit/114e7c146ac682925f0fb37376c1be70e5d6e6e5), [`1b6f651`](https://github.com/mastra-ai/mastra/commit/1b6f65127d4a0d6c38d0a1055cb84527db529d6b), [`72df4a8`](https://github.com/mastra-ai/mastra/commit/72df4a8f9bf1a20cfd3d9006a4fdb597ad56d10a)]:
12
+ - @mastra/core@1.8.0-alpha.0
13
+
3
14
  ## 1.5.1
4
15
 
5
16
  ### Patch Changes
@@ -0,0 +1,29 @@
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: "1.5.2-alpha.0"
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
+ - [Working Memory](references/docs-memory-working-memory.md) - Learn how to configure working memory in Mastra to store persistent user data, preferences.
20
+ - [Retrieval, Semantic Search, Reranking](references/docs-rag-retrieval.md) - Guide on retrieval processes in Mastra's RAG systems, including semantic search, filtering, and re-ranking.
21
+ - [Storing Embeddings in A Vector Database](references/docs-rag-vector-databases.md) - Guide on vector storage options in Mastra, including embedded and dedicated vector databases for similarity search.
22
+
23
+ ### Reference
24
+
25
+ - [Reference: MongoDB Storage](references/reference-storage-mongodb.md) - Documentation for the MongoDB storage implementation in Mastra.
26
+ - [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.
27
+
28
+
29
+ Read [assets/SOURCE_MAP.json](assets/SOURCE_MAP.json) for source code references.
@@ -0,0 +1,6 @@
1
+ {
2
+ "version": "1.5.2-alpha.0",
3
+ "package": "@mastra/mongodb",
4
+ "exports": {},
5
+ "modules": {}
6
+ }
@@ -0,0 +1,400 @@
1
+ # Working Memory
2
+
3
+ While [message history](https://mastra.ai/docs/memory/message-history) and [semantic recall](https://mastra.ai/docs/memory/semantic-recall) help agents remember conversations, working memory allows them to maintain persistent information about users across interactions.
4
+
5
+ Think of it as the agent's active thoughts or scratchpad – the key information they keep available about the user or task. It's similar to how a person would naturally remember someone's name, preferences, or important details during a conversation.
6
+
7
+ This is useful for maintaining ongoing state that's always relevant and should always be available to the agent.
8
+
9
+ Working memory can persist at two different scopes:
10
+
11
+ - **Resource-scoped** (default): Memory persists across all conversation threads for the same user
12
+ - **Thread-scoped**: Memory is isolated per conversation thread
13
+
14
+ **Important:** Switching between scopes means the agent won't see memory from the other scope - thread-scoped memory is completely separate from resource-scoped memory.
15
+
16
+ ## Quick Start
17
+
18
+ Here's a minimal example of setting up an agent with working memory:
19
+
20
+ ```typescript
21
+ import { Agent } from '@mastra/core/agent'
22
+ import { Memory } from '@mastra/memory'
23
+
24
+ // Create agent with working memory enabled
25
+ const agent = new Agent({
26
+ id: 'personal-assistant',
27
+ name: 'PersonalAssistant',
28
+ instructions: 'You are a helpful personal assistant.',
29
+ model: 'openai/gpt-5.1',
30
+ memory: new Memory({
31
+ options: {
32
+ workingMemory: {
33
+ enabled: true,
34
+ },
35
+ },
36
+ }),
37
+ })
38
+ ```
39
+
40
+ ## How it Works
41
+
42
+ Working memory is a block of Markdown text that the agent is able to update over time to store continuously relevant information:
43
+
44
+ [YouTube video player](https://www.youtube-nocookie.com/embed/UMy_JHLf1n8)
45
+
46
+ ## Memory Persistence Scopes
47
+
48
+ Working memory can operate in two different scopes, allowing you to choose how memory persists across conversations:
49
+
50
+ ### Resource-Scoped Memory (Default)
51
+
52
+ By default, working memory persists across all conversation threads for the same user (resourceId), enabling persistent user memory:
53
+
54
+ ```typescript
55
+ const memory = new Memory({
56
+ storage,
57
+ options: {
58
+ workingMemory: {
59
+ enabled: true,
60
+ scope: 'resource', // Memory persists across all user threads
61
+ template: `# User Profile
62
+ - **Name**:
63
+ - **Location**:
64
+ - **Interests**:
65
+ - **Preferences**:
66
+ - **Long-term Goals**:
67
+ `,
68
+ },
69
+ },
70
+ })
71
+ ```
72
+
73
+ **Use cases:**
74
+
75
+ - Personal assistants that remember user preferences
76
+ - Customer service bots that maintain customer context
77
+ - Educational applications that track student progress
78
+
79
+ ### Usage with Agents
80
+
81
+ When using resource-scoped memory, make sure to pass the `resource` parameter in the memory options:
82
+
83
+ ```typescript
84
+ // Resource-scoped memory requires resource
85
+ const response = await agent.generate('Hello!', {
86
+ memory: {
87
+ thread: 'conversation-123',
88
+ resource: 'user-alice-456', // Same user across different threads
89
+ },
90
+ })
91
+ ```
92
+
93
+ ### Thread-Scoped Memory
94
+
95
+ Thread-scoped memory isolates working memory to individual conversation threads. Each thread maintains its own isolated memory:
96
+
97
+ ```typescript
98
+ const memory = new Memory({
99
+ storage,
100
+ options: {
101
+ workingMemory: {
102
+ enabled: true,
103
+ scope: 'thread', // Memory is isolated per thread
104
+ template: `# User Profile
105
+ - **Name**:
106
+ - **Interests**:
107
+ - **Current Goal**:
108
+ `,
109
+ },
110
+ },
111
+ })
112
+ ```
113
+
114
+ **Use cases:**
115
+
116
+ - Different conversations about separate topics
117
+ - Temporary or session-specific information
118
+ - Workflows where each thread needs working memory but threads are ephemeral and not related to each other
119
+
120
+ ## Storage Adapter Support
121
+
122
+ Resource-scoped working memory requires specific storage adapters that support the `mastra_resources` table:
123
+
124
+ ### Supported Storage Adapters
125
+
126
+ - **libSQL** (`@mastra/libsql`)
127
+ - **PostgreSQL** (`@mastra/pg`)
128
+ - **Upstash** (`@mastra/upstash`)
129
+ - **MongoDB** (`@mastra/mongodb`)
130
+
131
+ ## Custom Templates
132
+
133
+ Templates guide the agent on what information to track and update in working memory. While a default template is used if none is provided, you'll typically want to define a custom template tailored to your agent's specific use case to ensure it remembers the most relevant information.
134
+
135
+ Here's an example of a custom template. In this example the agent will store the users name, location, timezone, etc as soon as the user sends a message containing any of the info:
136
+
137
+ ```typescript
138
+ const memory = new Memory({
139
+ options: {
140
+ workingMemory: {
141
+ enabled: true,
142
+ template: `
143
+ # User Profile
144
+
145
+ ## Personal Info
146
+
147
+ - Name:
148
+ - Location:
149
+ - Timezone:
150
+
151
+ ## Preferences
152
+
153
+ - Communication Style: [e.g., Formal, Casual]
154
+ - Project Goal:
155
+ - Key Deadlines:
156
+ - [Deadline 1]: [Date]
157
+ - [Deadline 2]: [Date]
158
+
159
+ ## Session State
160
+
161
+ - Last Task Discussed:
162
+ - Open Questions:
163
+ - [Question 1]
164
+ - [Question 2]
165
+ `,
166
+ },
167
+ },
168
+ })
169
+ ```
170
+
171
+ ## Designing Effective Templates
172
+
173
+ A well-structured template keeps the information easy for the agent to parse and update. Treat the template as a short form that you want the assistant to keep up to date.
174
+
175
+ - **Short, focused labels.** Avoid paragraphs or very long headings. Keep labels brief (for example `## Personal Info` or `- Name:`) so updates are easy to read and less likely to be truncated.
176
+ - **Use consistent casing.** Inconsistent capitalization (`Timezone:` vs `timezone:`) can cause messy updates. Stick to Title Case or lower case for headings and bullet labels.
177
+ - **Keep placeholder text simple.** Use hints such as `[e.g., Formal]` or `[Date]` to help the LLM fill in the correct spots.
178
+ - **Abbreviate very long values.** If you only need a short form, include guidance like `- Name: [First name or nickname]` or `- Address (short):` rather than the full legal text.
179
+ - **Mention update rules in `instructions`.** You can instruct how and when to fill or clear parts of the template directly in the agent's `instructions` field.
180
+
181
+ ### Alternative Template Styles
182
+
183
+ Use a shorter single block if you only need a few items:
184
+
185
+ ```typescript
186
+ const basicMemory = new Memory({
187
+ options: {
188
+ workingMemory: {
189
+ enabled: true,
190
+ template: `User Facts:\n- Name:\n- Favorite Color:\n- Current Topic:`,
191
+ },
192
+ },
193
+ })
194
+ ```
195
+
196
+ You can also store the key facts in a short paragraph format if you prefer a more narrative style:
197
+
198
+ ```typescript
199
+ const paragraphMemory = new Memory({
200
+ options: {
201
+ workingMemory: {
202
+ enabled: true,
203
+ template: `Important Details:\n\nKeep a short paragraph capturing the user's important facts (name, main goal, current task).`,
204
+ },
205
+ },
206
+ })
207
+ ```
208
+
209
+ ## Structured Working Memory
210
+
211
+ Working memory can also be defined using a structured schema instead of a Markdown template. This allows you to specify the exact fields and types that should be tracked, using a [Zod](https://zod.dev/) schema. When using a schema, the agent will see and update working memory as a JSON object matching your schema.
212
+
213
+ **Important:** You must specify either `template` or `schema`, but not both.
214
+
215
+ ### Example: Schema-Based Working Memory
216
+
217
+ ```typescript
218
+ import { z } from 'zod'
219
+ import { Memory } from '@mastra/memory'
220
+
221
+ const userProfileSchema = z.object({
222
+ name: z.string().optional(),
223
+ location: z.string().optional(),
224
+ timezone: z.string().optional(),
225
+ preferences: z
226
+ .object({
227
+ communicationStyle: z.string().optional(),
228
+ projectGoal: z.string().optional(),
229
+ deadlines: z.array(z.string()).optional(),
230
+ })
231
+ .optional(),
232
+ })
233
+
234
+ const memory = new Memory({
235
+ options: {
236
+ workingMemory: {
237
+ enabled: true,
238
+ schema: userProfileSchema,
239
+ // template: ... (do not set)
240
+ },
241
+ },
242
+ })
243
+ ```
244
+
245
+ When a schema is provided, the agent receives the working memory as a JSON object. For example:
246
+
247
+ ```json
248
+ {
249
+ "name": "Sam",
250
+ "location": "Berlin",
251
+ "timezone": "CET",
252
+ "preferences": {
253
+ "communicationStyle": "Formal",
254
+ "projectGoal": "Launch MVP",
255
+ "deadlines": ["2025-07-01"]
256
+ }
257
+ }
258
+ ```
259
+
260
+ ### Merge Semantics for Schema-Based Memory
261
+
262
+ Schema-based working memory uses **merge semantics**, meaning the agent only needs to include fields it wants to add or update. Existing fields are preserved automatically.
263
+
264
+ - **Object fields are deep merged:** Only provided fields are updated; others remain unchanged
265
+ - **Set a field to `null` to delete it:** This explicitly removes the field from memory
266
+ - **Arrays are replaced entirely:** When an array field is provided, it replaces the existing array (arrays are not merged element-by-element)
267
+
268
+ ## Choosing Between Template and Schema
269
+
270
+ - Use a **template** (Markdown) if you want the agent to maintain memory as a free-form text block, such as a user profile or scratchpad. Templates use **replace semantics** — the agent must provide the complete memory content on each update.
271
+ - Use a **schema** if you need structured, type-safe data that can be validated and programmatically accessed as JSON. Schemas use **merge semantics** — the agent only provides fields to update, and existing fields are preserved.
272
+ - Only one mode can be active at a time: setting both `template` and `schema` is not supported.
273
+
274
+ ## Example: Multi-step Retention
275
+
276
+ Below is a simplified view of how the `User Profile` template updates across a short user conversation:
277
+
278
+ ```nohighlight
279
+ # User Profile
280
+
281
+ ## Personal Info
282
+
283
+ - Name:
284
+ - Location:
285
+ - Timezone:
286
+
287
+ --- After user says "My name is **Sam** and I'm from **Berlin**" ---
288
+
289
+ # User Profile
290
+ - Name: Sam
291
+ - Location: Berlin
292
+ - Timezone:
293
+
294
+ --- After user adds "By the way I'm normally in **CET**" ---
295
+
296
+ # User Profile
297
+ - Name: Sam
298
+ - Location: Berlin
299
+ - Timezone: CET
300
+ ```
301
+
302
+ The agent can now refer to `Sam` or `Berlin` in later responses without requesting the information again because it has been stored in working memory.
303
+
304
+ If your agent is not properly updating working memory when you expect it to, you can add system instructions on _how_ and _when_ to use this template in your agent's `instructions` setting.
305
+
306
+ ## Setting Initial Working Memory
307
+
308
+ While agents typically update working memory through the `updateWorkingMemory` tool, you can also set initial working memory programmatically when creating or updating threads. This is useful for injecting user data (like their name, preferences, or other info) that you want available to the agent without passing it in every request.
309
+
310
+ ### Setting Working Memory via Thread Metadata
311
+
312
+ When creating a thread, you can provide initial working memory through the metadata's `workingMemory` key:
313
+
314
+ ```typescript
315
+ // Create a thread with initial working memory
316
+ const thread = await memory.createThread({
317
+ threadId: 'thread-123',
318
+ resourceId: 'user-456',
319
+ title: 'Medical Consultation',
320
+ metadata: {
321
+ workingMemory: `# Patient Profile
322
+ - Name: John Doe
323
+ - Blood Type: O+
324
+ - Allergies: Penicillin
325
+ - Current Medications: None
326
+ - Medical History: Hypertension (controlled)
327
+ `,
328
+ },
329
+ })
330
+
331
+ // The agent will now have access to this information in all messages
332
+ await agent.generate("What's my blood type?", {
333
+ memory: {
334
+ thread: thread.id,
335
+ resource: 'user-456',
336
+ },
337
+ })
338
+ // Response: "Your blood type is O+."
339
+ ```
340
+
341
+ ### Updating Working Memory Programmatically
342
+
343
+ You can also update an existing thread's working memory:
344
+
345
+ ```typescript
346
+ // Update thread metadata to add/modify working memory
347
+ await memory.updateThread({
348
+ id: 'thread-123',
349
+ title: thread.title,
350
+ metadata: {
351
+ ...thread.metadata,
352
+ workingMemory: `# Patient Profile
353
+ - Name: John Doe
354
+ - Blood Type: O+
355
+ - Allergies: Penicillin, Ibuprofen // Updated
356
+ - Current Medications: Lisinopril 10mg daily // Added
357
+ - Medical History: Hypertension (controlled)
358
+ `,
359
+ },
360
+ })
361
+ ```
362
+
363
+ ### Direct Memory Update
364
+
365
+ Alternatively, use the `updateWorkingMemory` method directly:
366
+
367
+ ```typescript
368
+ await memory.updateWorkingMemory({
369
+ threadId: 'thread-123',
370
+ resourceId: 'user-456', // Required for resource-scoped memory
371
+ workingMemory: 'Updated memory content...',
372
+ })
373
+ ```
374
+
375
+ ## Read-Only Working Memory
376
+
377
+ In some scenarios, you may want an agent to have access to working memory data without the ability to modify it. This is useful for:
378
+
379
+ - **Routing agents** that need context but shouldn't update user profiles
380
+ - **Sub agents** in a multi-agent system that should reference but not own the memory
381
+
382
+ To enable read-only mode, set `readOnly: true` in the memory options:
383
+
384
+ ```typescript
385
+ const response = await agent.generate('What do you know about me?', {
386
+ memory: {
387
+ thread: 'conversation-123',
388
+ resource: 'user-alice-456',
389
+ options: {
390
+ readOnly: true, // Working memory is provided but cannot be updated
391
+ },
392
+ },
393
+ })
394
+ ```
395
+
396
+ ## Examples
397
+
398
+ - [Working memory with template](https://github.com/mastra-ai/mastra/tree/main/examples/memory-with-template)
399
+ - [Working memory with schema](https://github.com/mastra-ai/mastra/tree/main/examples/memory-with-schema)
400
+ - [Per-resource working memory](https://github.com/mastra-ai/mastra/tree/main/examples/memory-per-resource-example) - Complete example showing resource-scoped memory persistence