@mastra/memory 1.0.0-beta.8 → 1.0.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.
@@ -0,0 +1,1139 @@
1
+ # Storage API Reference
2
+
3
+ > API reference for storage - 5 entries
4
+
5
+
6
+ ---
7
+
8
+ ## Reference: DynamoDB Storage
9
+
10
+ > Documentation for the DynamoDB storage implementation in Mastra, using a single-table design with ElectroDB.
11
+
12
+ The DynamoDB storage implementation provides a scalable and performant NoSQL database solution for Mastra, leveraging a single-table design pattern with [ElectroDB](https://electrodb.dev/).
13
+
14
+ ## Features
15
+
16
+ - Efficient single-table design for all Mastra storage needs
17
+ - Based on ElectroDB for type-safe DynamoDB access
18
+ - Support for AWS credentials, regions, and endpoints
19
+ - Compatible with AWS DynamoDB Local for development
20
+ - Stores Thread, Message, Trace, Eval, and Workflow data
21
+ - Optimized for serverless environments
22
+ - Configurable TTL (Time To Live) for automatic data expiration per entity type
23
+
24
+ ## Installation
25
+
26
+ ```bash
27
+ npm install @mastra/dynamodb@beta
28
+ # or
29
+ pnpm add @mastra/dynamodb@beta
30
+ # or
31
+ yarn add @mastra/dynamodb@beta
32
+ ```
33
+
34
+ ## Prerequisites
35
+
36
+ Before using this package, you **must** create a DynamoDB table with a specific structure, including primary keys and Global Secondary Indexes (GSIs). This adapter expects the DynamoDB table and its GSIs to be provisioned externally.
37
+
38
+ Detailed instructions for setting up the table using AWS CloudFormation or AWS CDK are available in [TABLE_SETUP.md](https://github.com/mastra-ai/mastra/blob/main/stores/dynamodb/TABLE_SETUP.md). Please ensure your table is configured according to those instructions before proceeding.
39
+
40
+ ## Usage
41
+
42
+ ### Basic Usage
43
+
44
+ ```typescript
45
+ import { Memory } from "@mastra/memory";
46
+ import { DynamoDBStore } from "@mastra/dynamodb";
47
+
48
+ // Initialize the DynamoDB storage
49
+ const storage = new DynamoDBStore({
50
+ id: "dynamodb", // Unique identifier for this storage instance
51
+ config: {
52
+ tableName: "mastra-single-table", // Name of your DynamoDB table
53
+ region: "us-east-1", // Optional: AWS region, defaults to 'us-east-1'
54
+ // endpoint: "http://localhost:8000", // Optional: For local DynamoDB
55
+ // credentials: { accessKeyId: "YOUR_ACCESS_KEY", secretAccessKey: "YOUR_SECRET_KEY" } // Optional
56
+ },
57
+ });
58
+
59
+ // Example: Initialize Memory with DynamoDB storage
60
+ const memory = new Memory({
61
+ storage,
62
+ options: {
63
+ lastMessages: 10,
64
+ },
65
+ });
66
+ ```
67
+
68
+ ### Local Development with DynamoDB Local
69
+
70
+ For local development, you can use [DynamoDB Local](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.html).
71
+
72
+ 1. **Run DynamoDB Local (e.g., using Docker):**
73
+
74
+ ```bash
75
+ docker run -p 8000:8000 amazon/dynamodb-local
76
+ ```
77
+
78
+ 2. **Configure `DynamoDBStore` to use the local endpoint:**
79
+
80
+ ```typescript
81
+ import { DynamoDBStore } from "@mastra/dynamodb";
82
+
83
+ const storage = new DynamoDBStore({
84
+ id: "dynamodb-local",
85
+ config: {
86
+ tableName: "mastra-single-table", // Ensure this table is created in your local DynamoDB
87
+ region: "localhost", // Can be any string for local, 'localhost' is common
88
+ endpoint: "http://localhost:8000",
89
+ // For DynamoDB Local, credentials are not typically required unless configured.
90
+ // If you've configured local credentials:
91
+ // credentials: { accessKeyId: "fakeMyKeyId", secretAccessKey: "fakeSecretAccessKey" }
92
+ },
93
+ });
94
+ ```
95
+
96
+ You will still need to create the table and GSIs in your local DynamoDB instance, for example, using the AWS CLI pointed to your local endpoint.
97
+
98
+ ## Parameters
99
+
100
+ ## TTL (Time To Live) Configuration
101
+
102
+ DynamoDB TTL allows you to automatically delete items after a specified time period. This is useful for:
103
+
104
+ - **Cost optimization**: Automatically remove old data to reduce storage costs
105
+ - **Data lifecycle management**: Implement retention policies for compliance
106
+ - **Performance**: Prevent tables from growing indefinitely
107
+ - **Privacy compliance**: Automatically purge personal data after specified periods
108
+
109
+ ### Enabling TTL
110
+
111
+ To use TTL, you must:
112
+
113
+ 1. **Configure TTL in DynamoDBStore** (shown below)
114
+ 2. **Enable TTL on your DynamoDB table** via AWS Console or CLI, specifying the attribute name (default: `ttl`)
115
+
116
+ ```typescript
117
+ import { DynamoDBStore } from "@mastra/dynamodb";
118
+
119
+ const storage = new DynamoDBStore({
120
+ name: "dynamodb",
121
+ config: {
122
+ tableName: "mastra-single-table",
123
+ region: "us-east-1",
124
+ ttl: {
125
+ // Messages expire after 30 days
126
+ message: {
127
+ enabled: true,
128
+ defaultTtlSeconds: 30 * 24 * 60 * 60, // 30 days
129
+ },
130
+ // Threads expire after 90 days
131
+ thread: {
132
+ enabled: true,
133
+ defaultTtlSeconds: 90 * 24 * 60 * 60, // 90 days
134
+ },
135
+ // Traces expire after 7 days with custom attribute name
136
+ trace: {
137
+ enabled: true,
138
+ attributeName: "expiresAt", // Custom TTL attribute
139
+ defaultTtlSeconds: 7 * 24 * 60 * 60, // 7 days
140
+ },
141
+ // Workflow snapshots don't expire
142
+ workflow_snapshot: {
143
+ enabled: false,
144
+ },
145
+ },
146
+ },
147
+ });
148
+ ```
149
+
150
+ ### Supported Entity Types
151
+
152
+ TTL can be configured for these entity types:
153
+
154
+ | Entity | Description |
155
+ |--------|-------------|
156
+ | `thread` | Conversation threads |
157
+ | `message` | Messages within threads |
158
+ | `trace` | Observability traces |
159
+ | `eval` | Evaluation results |
160
+ | `workflow_snapshot` | Workflow state snapshots |
161
+ | `resource` | User/resource data |
162
+ | `score` | Scoring results |
163
+
164
+ ### TTL Entity Configuration
165
+
166
+ Each entity type accepts the following configuration:
167
+
168
+ ### Enabling TTL on Your DynamoDB Table
169
+
170
+ After configuring TTL in your code, you must enable TTL on the DynamoDB table itself:
171
+
172
+ **Using AWS CLI:**
173
+
174
+ ```bash
175
+ aws dynamodb update-time-to-live \
176
+ --table-name mastra-single-table \
177
+ --time-to-live-specification "Enabled=true, AttributeName=ttl"
178
+ ```
179
+
180
+ **Using AWS Console:**
181
+
182
+ 1. Go to the DynamoDB console
183
+ 2. Select your table
184
+ 3. Go to "Additional settings" tab
185
+ 4. Under "Time to Live (TTL)", click "Manage TTL"
186
+ 5. Enable TTL and specify the attribute name (default: `ttl`)
187
+
188
+ > **Note**: DynamoDB deletes expired items within 48 hours after expiration. Items remain queryable until actually deleted.
189
+
190
+ ## AWS IAM Permissions
191
+
192
+ The IAM role or user executing the code needs appropriate permissions to interact with the specified DynamoDB table and its indexes. Below is a sample policy. Replace `${YOUR_TABLE_NAME}` with your actual table name and `${YOUR_AWS_REGION}` and `${YOUR_AWS_ACCOUNT_ID}` with appropriate values.
193
+
194
+ ```json
195
+ {
196
+ "Version": "2012-10-17",
197
+ "Statement": [
198
+ {
199
+ "Effect": "Allow",
200
+ "Action": [
201
+ "dynamodb:DescribeTable",
202
+ "dynamodb:GetItem",
203
+ "dynamodb:PutItem",
204
+ "dynamodb:UpdateItem",
205
+ "dynamodb:DeleteItem",
206
+ "dynamodb:Query",
207
+ "dynamodb:Scan",
208
+ "dynamodb:BatchGetItem",
209
+ "dynamodb:BatchWriteItem"
210
+ ],
211
+ "Resource": [
212
+ "arn:aws:dynamodb:${YOUR_AWS_REGION}:${YOUR_AWS_ACCOUNT_ID}:table/${YOUR_TABLE_NAME}",
213
+ "arn:aws:dynamodb:${YOUR_AWS_REGION}:${YOUR_AWS_ACCOUNT_ID}:table/${YOUR_TABLE_NAME}/index/*"
214
+ ]
215
+ }
216
+ ]
217
+ }
218
+ ```
219
+
220
+ ## Key Considerations
221
+
222
+ Before diving into the architectural details, keep these key points in mind when working with the DynamoDB storage adapter:
223
+
224
+ - **External Table Provisioning:** This adapter _requires_ you to create and configure the DynamoDB table and its Global Secondary Indexes (GSIs) yourself, prior to using the adapter. Follow the guide in [TABLE_SETUP.md](https://github.com/mastra-ai/mastra/blob/main/stores/dynamodb/TABLE_SETUP.md).
225
+ - **Single-Table Design:** All Mastra data (threads, messages, etc.) is stored in one DynamoDB table. This is a deliberate design choice optimized for DynamoDB, differing from relational database approaches.
226
+ - **Understanding GSIs:** Familiarity with how the GSIs are structured (as per `TABLE_SETUP.md`) is important for understanding data retrieval and potential query patterns.
227
+ - **ElectroDB:** The adapter uses ElectroDB to manage interactions with DynamoDB, providing a layer of abstraction and type safety over raw DynamoDB operations.
228
+
229
+ ## Architectural Approach
230
+
231
+ This storage adapter utilizes a **single-table design pattern** leveraging [ElectroDB](https://electrodb.dev/), a common and recommended approach for DynamoDB. This differs architecturally from relational database adapters (like `@mastra/pg` or `@mastra/libsql`) that typically use multiple tables, each dedicated to a specific entity (threads, messages, etc.).
232
+
233
+ Key aspects of this approach:
234
+
235
+ - **DynamoDB Native:** The single-table design is optimized for DynamoDB's key-value and query capabilities, often leading to better performance and scalability compared to mimicking relational models.
236
+ - **External Table Management:** Unlike some adapters that might offer helper functions to create tables via code, this adapter **expects the DynamoDB table and its associated Global Secondary Indexes (GSIs) to be provisioned externally** before use. Please refer to [TABLE_SETUP.md](https://github.com/mastra-ai/mastra/blob/main/stores/dynamodb/TABLE_SETUP.md) for detailed instructions using tools like AWS CloudFormation or CDK. The adapter focuses solely on interacting with the pre-existing table structure.
237
+ - **Consistency via Interface:** While the underlying storage model differs, this adapter adheres to the same `MastraStorage` interface as other adapters, ensuring it can be used interchangeably within the Mastra `Memory` component.
238
+
239
+ ### Mastra Data in the Single Table
240
+
241
+ Within the single DynamoDB table, different Mastra data entities (such as Threads, Messages, Traces, Evals, and Workflows) are managed and distinguished using ElectroDB. ElectroDB defines specific models for each entity type, which include unique key structures and attributes. This allows the adapter to store and retrieve diverse data types efficiently within the same table.
242
+
243
+ For example, a `Thread` item might have a primary key like `THREAD#<threadId>`, while a `Message` item belonging to that thread might use `THREAD#<threadId>` as a partition key and `MESSAGE#<messageId>` as a sort key. The Global Secondary Indexes (GSIs), detailed in `TABLE_SETUP.md`, are strategically designed to support common access patterns across these different entities, such as fetching all messages for a thread or querying traces associated with a particular workflow.
244
+
245
+ ### Advantages of Single-Table Design
246
+
247
+ This implementation uses a single-table design pattern with ElectroDB, which offers several advantages within the context of DynamoDB:
248
+
249
+ 1. **Lower cost (potentially):** Fewer tables can simplify Read/Write Capacity Unit (RCU/WCU) provisioning and management, especially with on-demand capacity.
250
+ 2. **Better performance:** Related data can be co-located or accessed efficiently through GSIs, enabling fast lookups for common access patterns.
251
+ 3. **Simplified administration:** Fewer distinct tables to monitor, back up, and manage.
252
+ 4. **Reduced complexity in access patterns:** ElectroDB helps manage the complexity of item types and access patterns on a single table.
253
+ 5. **Transaction support:** DynamoDB transactions can be used across different "entity" types stored within the same table if needed.
254
+
255
+ ---
256
+
257
+ ## Reference: libSQL Storage
258
+
259
+ > Documentation for the libSQL storage implementation in Mastra.
260
+
261
+ [libSQL](https://docs.turso.tech/libsql) is an open-source, SQLite-compatible database that supports both local and remote deployments. It can be used to store message history, workflow snapshots, traces, and eval scores.
262
+
263
+ For vectors like semantic recall or traditional RAG, use [libSQL Vector](https://mastra.ai/reference/v1/vectors/libsql) which covers embeddings and vector search.
264
+
265
+ ## Installation
266
+
267
+ Storage providers must be installed as separate packages:
268
+
269
+ ```bash
270
+ npm install @mastra/libsql@beta
271
+ ```
272
+
273
+ ## Usage
274
+
275
+ ```typescript
276
+ import { LibSQLStore } from "@mastra/libsql";
277
+ import { Mastra } from "@mastra/core";
278
+
279
+ const mastra = new Mastra({
280
+ storage: new LibSQLStore({
281
+ id: 'libsql-storage',
282
+ url: "file:./storage.db",
283
+ }),
284
+ });
285
+ ```
286
+
287
+ Agent-level file storage:
288
+
289
+ ```typescript
290
+ import { Memory } from "@mastra/memory";
291
+ import { Agent } from "@mastra/core/agent";
292
+ import { LibSQLStore } from "@mastra/libsql";
293
+
294
+ export const agent = new Agent({
295
+ id: "example-agent",
296
+ memory: new Memory({
297
+ storage: new LibSQLStore({
298
+ id: 'libsql-storage',
299
+ url: "file:./agent.db",
300
+ }),
301
+ }),
302
+ });
303
+ ```
304
+
305
+ > **Note:**
306
+ File storage doesn't work with serverless platforms that have ephemeral file systems. For serverless deployments, use [Turso](https://turso.tech) or a different database engine.
307
+
308
+ Production with remote database:
309
+
310
+ ```typescript
311
+ storage: new LibSQLStore({
312
+ id: 'libsql-storage',
313
+ url: "libsql://your-db-name.aws-ap-northeast-1.turso.io",
314
+ authToken: process.env.TURSO_AUTH_TOKEN,
315
+ })
316
+ ```
317
+
318
+ For local development and testing, you can store data in memory:
319
+
320
+ ```typescript
321
+ storage: new LibSQLStore({
322
+ id: 'libsql-storage',
323
+ url: ":memory:",
324
+ })
325
+ ```
326
+ > **Note:**
327
+ In-memory storage resets when the process changes. Only suitable for development.
328
+
329
+ ## Options
330
+
331
+ ## Initialization
332
+
333
+ When you pass storage to the Mastra class, `init()` is called automatically to create the [core schema](https://mastra.ai/reference/v1/storage/overview#core-schema):
334
+
335
+ ```typescript
336
+ import { Mastra } from "@mastra/core";
337
+ import { LibSQLStore } from "@mastra/libsql";
338
+
339
+ const storage = new LibSQLStore({
340
+ id: 'libsql-storage',
341
+ url: "file:./storage.db",
342
+ });
343
+
344
+ const mastra = new Mastra({
345
+ storage, // init() called automatically
346
+ });
347
+ ```
348
+
349
+ If using storage directly without Mastra, call `init()` explicitly:
350
+
351
+ ```typescript
352
+ import { LibSQLStore } from "@mastra/libsql";
353
+
354
+ const storage = new LibSQLStore({
355
+ id: 'libsql-storage',
356
+ url: "file:./storage.db",
357
+ });
358
+
359
+ await storage.init();
360
+
361
+ // Access domain-specific stores via getStore()
362
+ const memoryStore = await storage.getStore('memory');
363
+ const thread = await memoryStore?.getThreadById({ threadId: "..." });
364
+ ```
365
+
366
+ ---
367
+
368
+ ## Reference: MongoDB Storage
369
+
370
+ > Documentation for the MongoDB storage implementation in Mastra.
371
+
372
+ The MongoDB storage implementation provides a scalable storage solution using MongoDB databases with support for both document storage and vector operations.
373
+
374
+ ## Installation
375
+
376
+ ```bash
377
+ npm install @mastra/mongodb@beta
378
+ ```
379
+
380
+ ## Usage
381
+
382
+ Ensure you have a MongoDB Atlas Local (via Docker) or MongoDB Atlas Cloud instance with Atlas Search enabled. MongoDB 7.0+ is recommended.
383
+
384
+ ```typescript
385
+ import { MongoDBStore } from "@mastra/mongodb";
386
+
387
+ const storage = new MongoDBStore({
388
+ id: 'mongodb-storage',
389
+ uri: process.env.MONGODB_URI,
390
+ dbName: process.env.MONGODB_DATABASE,
391
+ });
392
+ ```
393
+
394
+ ## Parameters
395
+
396
+ > **Deprecation Notice**
397
+ The `url` parameter is deprecated but still supported for backward compatibility. Please use `uri` instead in all new code.
398
+
399
+ ## Constructor Examples
400
+
401
+ You can instantiate `MongoDBStore` in the following ways:
402
+
403
+ ```ts
404
+ import { MongoDBStore } from "@mastra/mongodb";
405
+
406
+ // Basic connection without custom options
407
+ const store1 = new MongoDBStore({
408
+ id: 'mongodb-storage-01',
409
+ uri: "mongodb+srv://user:password@cluster.mongodb.net",
410
+ dbName: "mastra_storage",
411
+ });
412
+
413
+ // Using connection string with options
414
+ const store2 = new MongoDBStore({
415
+ id: 'mongodb-storage-02',
416
+ uri: "mongodb+srv://user:password@cluster.mongodb.net",
417
+ dbName: "mastra_storage",
418
+ options: {
419
+ retryWrites: true,
420
+ maxPoolSize: 10,
421
+ serverSelectionTimeoutMS: 5000,
422
+ socketTimeoutMS: 45000,
423
+ },
424
+ });
425
+ ```
426
+
427
+ ## Additional Notes
428
+
429
+ ### Collection Management
430
+
431
+ The storage implementation handles collection creation and management automatically. It creates the following collections:
432
+
433
+ - `mastra_workflow_snapshot`: Stores workflow state and execution data
434
+ - `mastra_evals`: Stores evaluation results and metadata
435
+ - `mastra_threads`: Stores conversation threads
436
+ - `mastra_messages`: Stores individual messages
437
+ - `mastra_traces`: Stores telemetry and tracing data
438
+ - `mastra_scorers`: Stores scoring and evaluation data
439
+ - `mastra_resources`: Stores resource working memory data
440
+
441
+ ### Initialization
442
+
443
+ When you pass storage to the Mastra class, `init()` is called automatically before any storage operation:
444
+
445
+ ```typescript
446
+ import { Mastra } from "@mastra/core";
447
+ import { MongoDBStore } from "@mastra/mongodb";
448
+
449
+ const storage = new MongoDBStore({
450
+ id: 'mongodb-storage',
451
+ uri: process.env.MONGODB_URI,
452
+ dbName: process.env.MONGODB_DATABASE,
453
+ });
454
+
455
+ const mastra = new Mastra({
456
+ storage, // init() is called automatically
457
+ });
458
+ ```
459
+
460
+ If you're using storage directly without Mastra, you must call `init()` explicitly to create the collections:
461
+
462
+ ```typescript
463
+ import { MongoDBStore } from "@mastra/mongodb";
464
+
465
+ const storage = new MongoDBStore({
466
+ id: 'mongodb-storage',
467
+ uri: process.env.MONGODB_URI,
468
+ dbName: process.env.MONGODB_DATABASE,
469
+ });
470
+
471
+ // Required when using storage directly
472
+ await storage.init();
473
+
474
+ // Access domain-specific stores via getStore()
475
+ const memoryStore = await storage.getStore('memory');
476
+ const thread = await memoryStore?.getThreadById({ threadId: "..." });
477
+ ```
478
+
479
+ > **Note:**
480
+ If `init()` is not called, collections won't be created and storage operations will fail silently or throw errors.
481
+
482
+ ## Vector Search Capabilities
483
+
484
+ MongoDB storage includes built-in vector search capabilities for AI applications:
485
+
486
+ ### Vector Index Creation
487
+
488
+ ```typescript
489
+ import { MongoDBVector } from "@mastra/mongodb";
490
+
491
+ const vectorStore = new MongoDBVector({
492
+ id: 'mongodb-vector',
493
+ uri: process.env.MONGODB_URI,
494
+ dbName: process.env.MONGODB_DATABASE,
495
+ });
496
+
497
+ // Create a vector index for embeddings
498
+ await vectorStore.createIndex({
499
+ indexName: "document_embeddings",
500
+ dimension: 1536,
501
+ });
502
+ ```
503
+
504
+ ### Vector Operations
505
+
506
+ ```typescript
507
+ // Store vectors with metadata
508
+ await vectorStore.upsert({
509
+ indexName: "document_embeddings",
510
+ vectors: [
511
+ {
512
+ id: "doc-1",
513
+ values: [0.1, 0.2, 0.3, ...], // 1536-dimensional vector
514
+ metadata: {
515
+ title: "Document Title",
516
+ category: "technical",
517
+ source: "api-docs",
518
+ },
519
+ },
520
+ ],
521
+ });
522
+
523
+ // Similarity search
524
+ const results = await vectorStore.query({
525
+ indexName: "document_embeddings",
526
+ vector: queryEmbedding,
527
+ topK: 5,
528
+ filter: {
529
+ category: "technical",
530
+ },
531
+ });
532
+ ```
533
+
534
+ ## Usage Example
535
+
536
+ ### Adding memory to an agent
537
+
538
+ To add MongoDB memory to an agent use the `Memory` class and create a new `storage` key using `MongoDBStore`. The configuration supports both local and remote MongoDB instances.
539
+
540
+ ```typescript title="src/mastra/agents/example-mongodb-agent.ts"
541
+ import { Memory } from "@mastra/memory";
542
+ import { Agent } from "@mastra/core/agent";
543
+ import { MongoDBStore } from "@mastra/mongodb";
544
+
545
+ export const mongodbAgent = new Agent({
546
+ id: "mongodb-agent",
547
+ name: "mongodb-agent",
548
+ instructions:
549
+ "You are an AI agent with the ability to automatically recall memories from previous interactions.",
550
+ model: "openai/gpt-5.1",
551
+ memory: new Memory({
552
+ storage: new MongoDBStore({
553
+ uri: process.env.MONGODB_URI!,
554
+ dbName: process.env.MONGODB_DB_NAME!,
555
+ }),
556
+ options: {
557
+ generateTitle: true,
558
+ },
559
+ }),
560
+ });
561
+ ```
562
+
563
+ ### Using the agent
564
+
565
+ Use `memoryOptions` to scope recall for this request. Set `lastMessages: 5` to limit recency-based recall, and use `semanticRecall` to fetch the `topK: 3` most relevant messages, including `messageRange: 2` neighboring messages for context around each match.
566
+
567
+ ```typescript title="src/test-mongodb-agent.ts"
568
+ import "dotenv/config";
569
+
570
+ import { mastra } from "./mastra";
571
+
572
+ const threadId = "123";
573
+ const resourceId = "user-456";
574
+
575
+ const agent = mastra.getAgent("mongodbAgent");
576
+
577
+ const message = await agent.stream("My name is Mastra", {
578
+ memory: {
579
+ thread: threadId,
580
+ resource: resourceId,
581
+ },
582
+ });
583
+
584
+ await message.textStream.pipeTo(new WritableStream());
585
+
586
+ const stream = await agent.stream("What's my name?", {
587
+ memory: {
588
+ thread: threadId,
589
+ resource: resourceId,
590
+ },
591
+ memoryOptions: {
592
+ lastMessages: 5,
593
+ semanticRecall: {
594
+ topK: 3,
595
+ messageRange: 2,
596
+ },
597
+ },
598
+ });
599
+
600
+ for await (const chunk of stream.textStream) {
601
+ process.stdout.write(chunk);
602
+ }
603
+ ```
604
+
605
+ ---
606
+
607
+ ## Reference: PostgreSQL Storage
608
+
609
+ > Documentation for the PostgreSQL storage implementation in Mastra.
610
+
611
+ The PostgreSQL storage implementation provides a production-ready storage solution using PostgreSQL databases.
612
+
613
+ ## Installation
614
+
615
+ ```bash
616
+ npm install @mastra/pg@beta
617
+ ```
618
+
619
+ ## Usage
620
+
621
+ ```typescript
622
+ import { PostgresStore } from "@mastra/pg";
623
+
624
+ const storage = new PostgresStore({
625
+ id: 'pg-storage',
626
+ connectionString: process.env.DATABASE_URL,
627
+ });
628
+ ```
629
+
630
+ ## Parameters
631
+
632
+ ## Constructor Examples
633
+
634
+ You can instantiate `PostgresStore` in the following ways:
635
+
636
+ ```ts
637
+ import { PostgresStore } from "@mastra/pg";
638
+
639
+ // Using a connection string only
640
+ const store1 = new PostgresStore({
641
+ id: 'pg-storage-1',
642
+ connectionString: "postgresql://user:password@localhost:5432/mydb",
643
+ });
644
+
645
+ // Using a connection string with a custom schema name
646
+ const store2 = new PostgresStore({
647
+ id: 'pg-storage-2',
648
+ connectionString: "postgresql://user:password@localhost:5432/mydb",
649
+ schemaName: "custom_schema", // optional
650
+ });
651
+
652
+ // Using individual connection parameters
653
+ const store4 = new PostgresStore({
654
+ id: 'pg-storage-3',
655
+ host: "localhost",
656
+ port: 5432,
657
+ database: "mydb",
658
+ user: "user",
659
+ password: "password",
660
+ });
661
+
662
+ // Individual parameters with schemaName
663
+ const store5 = new PostgresStore({
664
+ id: 'pg-storage-4',
665
+ host: "localhost",
666
+ port: 5432,
667
+ database: "mydb",
668
+ user: "user",
669
+ password: "password",
670
+ schemaName: "custom_schema", // optional
671
+ });
672
+ ```
673
+
674
+ ## Additional Notes
675
+
676
+ ### Schema Management
677
+
678
+ The storage implementation handles schema creation and updates automatically. It creates the following tables:
679
+
680
+ - `mastra_workflow_snapshot`: Stores workflow state and execution data
681
+ - `mastra_evals`: Stores evaluation results and metadata
682
+ - `mastra_threads`: Stores conversation threads
683
+ - `mastra_messages`: Stores individual messages
684
+ - `mastra_traces`: Stores telemetry and tracing data
685
+ - `mastra_scorers`: Stores scoring and evaluation data
686
+ - `mastra_resources`: Stores resource working memory data
687
+
688
+ ### Initialization
689
+
690
+ When you pass storage to the Mastra class, `init()` is called automatically before any storage operation:
691
+
692
+ ```typescript
693
+ import { Mastra } from "@mastra/core";
694
+ import { PostgresStore } from "@mastra/pg";
695
+
696
+ const storage = new PostgresStore({
697
+ id: 'pg-storage',
698
+ connectionString: process.env.DATABASE_URL,
699
+ });
700
+
701
+ const mastra = new Mastra({
702
+ storage, // init() is called automatically
703
+ });
704
+ ```
705
+
706
+ If you're using storage directly without Mastra, you must call `init()` explicitly to create the tables:
707
+
708
+ ```typescript
709
+ import { PostgresStore } from "@mastra/pg";
710
+
711
+ const storage = new PostgresStore({
712
+ id: 'pg-storage',
713
+ connectionString: process.env.DATABASE_URL,
714
+ });
715
+
716
+ // Required when using storage directly
717
+ await storage.init();
718
+
719
+ // Access domain-specific stores via getStore()
720
+ const memoryStore = await storage.getStore('memory');
721
+ const thread = await memoryStore?.getThreadById({ threadId: "..." });
722
+ ```
723
+
724
+ > **Note:**
725
+ If `init()` is not called, tables won't be created and storage operations will fail silently or throw errors.
726
+
727
+ ### Direct Database and Pool Access
728
+
729
+ `PostgresStore` exposes both the underlying database object and the pg-promise instance as public fields:
730
+
731
+ ```typescript
732
+ store.db; // pg-promise database instance
733
+ store.pgp; // pg-promise main instance
734
+ ```
735
+
736
+ This enables direct queries and custom transaction management. When using these fields:
737
+
738
+ - You are responsible for proper connection and transaction handling.
739
+ - Closing the store (`store.close()`) will destroy the associated connection pool.
740
+ - Direct access bypasses any additional logic or validation provided by PostgresStore methods.
741
+
742
+ This approach is intended for advanced scenarios where low-level access is required.
743
+
744
+ ### Using with Next.js
745
+
746
+ When using `PostgresStore` in Next.js applications, [Hot Module Replacement (HMR)](https://nextjs.org/docs/architecture/fast-refresh) during development can cause multiple storage instances to be created, resulting in this warning:
747
+
748
+ ```
749
+ WARNING: Creating a duplicate database object for the same connection.
750
+ ```
751
+
752
+ To prevent this, store the `PostgresStore` instance on the global object so it persists across HMR reloads:
753
+
754
+ ```typescript title="src/mastra/storage.ts"
755
+ import { PostgresStore } from "@mastra/pg";
756
+ import { Memory } from "@mastra/memory";
757
+
758
+ // Extend the global type to include our instances
759
+ declare global {
760
+ var pgStore: PostgresStore | undefined;
761
+ var memory: Memory | undefined;
762
+ }
763
+
764
+ // Get or create the PostgresStore instance
765
+ function getPgStore(): PostgresStore {
766
+ if (!global.pgStore) {
767
+ if (!process.env.DATABASE_URL) {
768
+ throw new Error("DATABASE_URL is not defined in environment variables");
769
+ }
770
+ global.pgStore = new PostgresStore({
771
+ id: "pg-storage",
772
+ connectionString: process.env.DATABASE_URL,
773
+ ssl:
774
+ process.env.DATABASE_SSL === "true"
775
+ ? { rejectUnauthorized: false }
776
+ : false,
777
+ });
778
+ }
779
+ return global.pgStore;
780
+ }
781
+
782
+ // Get or create the Memory instance
783
+ function getMemory(): Memory {
784
+ if (!global.memory) {
785
+ global.memory = new Memory({
786
+ storage: getPgStore(),
787
+ });
788
+ }
789
+ return global.memory;
790
+ }
791
+
792
+ export const storage = getPgStore();
793
+ export const memory = getMemory();
794
+ ```
795
+
796
+ Then use the exported instances in your Mastra configuration:
797
+
798
+ ```typescript title="src/mastra/index.ts"
799
+ import { Mastra } from "@mastra/core/mastra";
800
+ import { storage } from "./storage";
801
+
802
+ export const mastra = new Mastra({
803
+ storage,
804
+ // ...other config
805
+ });
806
+ ```
807
+
808
+ This pattern ensures only one `PostgresStore` instance is created regardless of how many times the module is reloaded during development. The same pattern can be applied to other storage providers like `LibSQLStore`.
809
+
810
+ > **Note:**
811
+ This singleton pattern is only necessary during local development with HMR. In production builds, modules are only loaded once.
812
+
813
+ ## Usage Example
814
+
815
+ ### Adding memory to an agent
816
+
817
+ To add PostgreSQL memory to an agent use the `Memory` class and create a new `storage` key using `PostgresStore`. The `connectionString` can either be a remote location, or a local database connection.
818
+
819
+ ```typescript title="src/mastra/agents/example-pg-agent.ts"
820
+ import { Memory } from "@mastra/memory";
821
+ import { Agent } from "@mastra/core/agent";
822
+ import { PostgresStore } from "@mastra/pg";
823
+
824
+ export const pgAgent = new Agent({
825
+ id: "pg-agent",
826
+ name: "PG Agent",
827
+ instructions:
828
+ "You are an AI agent with the ability to automatically recall memories from previous interactions.",
829
+ model: "openai/gpt-5.1",
830
+ memory: new Memory({
831
+ storage: new PostgresStore({
832
+ id: 'pg-agent-storage',
833
+ connectionString: process.env.DATABASE_URL!,
834
+ }),
835
+ options: {
836
+ generateTitle: true, // Explicitly enable automatic title generation
837
+ },
838
+ }),
839
+ });
840
+ ```
841
+
842
+ ### Using the agent
843
+
844
+ Use `memoryOptions` to scope recall for this request. Set `lastMessages: 5` to limit recency-based recall, and use `semanticRecall` to fetch the `topK: 3` most relevant messages, including `messageRange: 2` neighboring messages for context around each match.
845
+
846
+ ```typescript title="src/test-pg-agent.ts"
847
+ import "dotenv/config";
848
+
849
+ import { mastra } from "./mastra";
850
+
851
+ const threadId = "123";
852
+ const resourceId = "user-456";
853
+
854
+ const agent = mastra.getAgent("pg-agent");
855
+
856
+ const message = await agent.stream("My name is Mastra", {
857
+ memory: {
858
+ thread: threadId,
859
+ resource: resourceId,
860
+ },
861
+ });
862
+
863
+ await message.textStream.pipeTo(new WritableStream());
864
+
865
+ const stream = await agent.stream("What's my name?", {
866
+ memory: {
867
+ thread: threadId,
868
+ resource: resourceId,
869
+ },
870
+ memoryOptions: {
871
+ lastMessages: 5,
872
+ semanticRecall: {
873
+ topK: 3,
874
+ messageRange: 2,
875
+ },
876
+ },
877
+ });
878
+
879
+ for await (const chunk of stream.textStream) {
880
+ process.stdout.write(chunk);
881
+ }
882
+ ```
883
+
884
+ ## Index Management
885
+
886
+ PostgreSQL storage provides index management to optimize query performance.
887
+
888
+ ### Default Indexes
889
+
890
+ PostgreSQL storage creates composite indexes during initialization for common query patterns:
891
+
892
+ - `mastra_threads_resourceid_createdat_idx`: (resourceId, createdAt DESC)
893
+ - `mastra_messages_thread_id_createdat_idx`: (thread_id, createdAt DESC)
894
+ - `mastra_ai_spans_traceid_startedat_idx`: (traceId, startedAt DESC)
895
+ - `mastra_ai_spans_parentspanid_startedat_idx`: (parentSpanId, startedAt DESC)
896
+ - `mastra_ai_spans_name_startedat_idx`: (name, startedAt DESC)
897
+ - `mastra_ai_spans_scope_startedat_idx`: (scope, startedAt DESC)
898
+ - `mastra_scores_trace_id_span_id_created_at_idx`: (traceId, spanId, createdAt DESC)
899
+
900
+ These indexes improve performance for filtered queries with sorting, including `dateRange` filters on message queries.
901
+
902
+ ### Configuring Indexes
903
+
904
+ You can control index creation via constructor options:
905
+
906
+ ```typescript
907
+ import { PostgresStore } from "@mastra/pg";
908
+
909
+ // Skip default indexes (manage indexes separately)
910
+ const store = new PostgresStore({
911
+ id: 'pg-storage',
912
+ connectionString: process.env.DATABASE_URL,
913
+ skipDefaultIndexes: true,
914
+ });
915
+
916
+ // Add custom indexes during initialization
917
+ const storeWithCustomIndexes = new PostgresStore({
918
+ id: 'pg-storage',
919
+ connectionString: process.env.DATABASE_URL,
920
+ indexes: [
921
+ {
922
+ name: "idx_threads_metadata_type",
923
+ table: "mastra_threads",
924
+ columns: ["metadata->>'type'"],
925
+ },
926
+ {
927
+ name: "idx_messages_status",
928
+ table: "mastra_messages",
929
+ columns: ["metadata->>'status'"],
930
+ },
931
+ ],
932
+ });
933
+ ```
934
+
935
+ For advanced index types, you can specify additional options:
936
+
937
+ - `unique: true` for unique constraints
938
+ - `where: 'condition'` for partial indexes
939
+ - `method: 'brin'` for time-series data
940
+ - `storage: { fillfactor: 90 }` for update-heavy tables
941
+ - `concurrent: true` for non-blocking creation (default)
942
+
943
+ ### Index Options
944
+
945
+ ### Schema-Specific Indexes
946
+
947
+ When using custom schemas, index names are prefixed with the schema name:
948
+
949
+ ```typescript
950
+ const storage = new PostgresStore({
951
+ id: 'pg-storage',
952
+ connectionString: process.env.DATABASE_URL,
953
+ schemaName: "custom_schema",
954
+ indexes: [
955
+ {
956
+ name: "idx_threads_status",
957
+ table: "mastra_threads",
958
+ columns: ["status"],
959
+ },
960
+ ],
961
+ });
962
+
963
+ // Creates index as: custom_schema_idx_threads_status
964
+ ```
965
+
966
+ ### Managing Indexes via SQL
967
+
968
+ For advanced index management (listing, dropping, analyzing), use direct SQL queries via the `db` accessor:
969
+
970
+ ```typescript
971
+ // List indexes for a table
972
+ const indexes = await storage.db.any(`
973
+ SELECT indexname, indexdef
974
+ FROM pg_indexes
975
+ WHERE tablename = 'mastra_messages'
976
+ `);
977
+
978
+ // Drop an index
979
+ await storage.db.none('DROP INDEX IF EXISTS idx_my_custom_index');
980
+
981
+ // Analyze index usage
982
+ const stats = await storage.db.one(`
983
+ SELECT idx_scan, idx_tup_read
984
+ FROM pg_stat_user_indexes
985
+ WHERE indexrelname = 'mastra_messages_thread_id_createdat_idx'
986
+ `);
987
+ ```
988
+
989
+ ### Index Types and Use Cases
990
+
991
+ PostgreSQL offers different index types optimized for specific scenarios:
992
+
993
+ | Index Type | Best For | Storage | Speed |
994
+ | ------------------- | --------------------------------------- | ---------- | -------------------------- |
995
+ | **btree** (default) | Range queries, sorting, general purpose | Moderate | Fast |
996
+ | **hash** | Equality comparisons only | Small | Very fast for `=` |
997
+ | **gin** | JSONB, arrays, full-text search | Large | Fast for contains |
998
+ | **gist** | Geometric data, full-text search | Moderate | Fast for nearest-neighbor |
999
+ | **spgist** | Non-balanced data, text patterns | Small | Fast for specific patterns |
1000
+ | **brin** | Large tables with natural ordering | Very small | Fast for ranges |
1001
+
1002
+ ---
1003
+
1004
+ ## Reference: Upstash Storage
1005
+
1006
+ > Documentation for the Upstash storage implementation in Mastra.
1007
+
1008
+ The Upstash storage implementation provides a serverless-friendly storage solution using Upstash's Redis-compatible key-value store.
1009
+
1010
+ > **Note:**
1011
+
1012
+ **Important:** When using Mastra with Upstash, the pay-as-you-go model can result in unexpectedly high costs due to the high volume of Redis commands generated during agent conversations. We strongly recommend using a **fixed pricing plan** for predictable costs. See [Upstash pricing](https://upstash.com/pricing/redis) for details and [GitHub issue #5850](https://github.com/mastra-ai/mastra/issues/5850) for context.
1013
+
1014
+ ## Installation
1015
+
1016
+ ```bash
1017
+ npm install @mastra/upstash@beta
1018
+ ```
1019
+
1020
+ ## Usage
1021
+
1022
+ ```typescript
1023
+ import { UpstashStore } from "@mastra/upstash";
1024
+
1025
+ const storage = new UpstashStore({
1026
+ id: 'upstash-storage',
1027
+ url: process.env.UPSTASH_URL,
1028
+ token: process.env.UPSTASH_TOKEN,
1029
+ });
1030
+ ```
1031
+
1032
+ ## Parameters
1033
+
1034
+ ## Additional Notes
1035
+
1036
+ ### Key Structure
1037
+
1038
+ The Upstash storage implementation uses a key-value structure:
1039
+
1040
+ - Thread keys: `{prefix}thread:{threadId}`
1041
+ - Message keys: `{prefix}message:{messageId}`
1042
+ - Metadata keys: `{prefix}metadata:{entityId}`
1043
+
1044
+ ### Serverless Benefits
1045
+
1046
+ Upstash storage is particularly well-suited for serverless deployments:
1047
+
1048
+ - No connection management needed
1049
+ - Pay-per-request pricing
1050
+ - Global replication options
1051
+ - Edge-compatible
1052
+
1053
+ ### Data Persistence
1054
+
1055
+ Upstash provides:
1056
+
1057
+ - Automatic data persistence
1058
+ - Point-in-time recovery
1059
+ - Cross-region replication options
1060
+
1061
+ ### Performance Considerations
1062
+
1063
+ For optimal performance:
1064
+
1065
+ - Use appropriate key prefixes to organize data
1066
+ - Monitor Redis memory usage
1067
+ - Consider data expiration policies if needed
1068
+
1069
+ ## Usage Example
1070
+
1071
+ ### Adding memory to an agent
1072
+
1073
+ To add Upstash memory to an agent use the `Memory` class and create a new `storage` key using `UpstashStore` and a new `vector` key using `UpstashVector`. The configuration can point to either a remote service or a local setup.
1074
+
1075
+ ```typescript title="src/mastra/agents/example-upstash-agent.ts"
1076
+ import { Memory } from "@mastra/memory";
1077
+ import { Agent } from "@mastra/core/agent";
1078
+ import { UpstashStore } from "@mastra/upstash";
1079
+
1080
+ export const upstashAgent = new Agent({
1081
+ id: "upstash-agent",
1082
+ name: "Upstash Agent",
1083
+ instructions:
1084
+ "You are an AI agent with the ability to automatically recall memories from previous interactions.",
1085
+ model: "openai/gpt-5.1",
1086
+ memory: new Memory({
1087
+ storage: new UpstashStore({
1088
+ id: 'upstash-agent-storage',
1089
+ url: process.env.UPSTASH_REDIS_REST_URL!,
1090
+ token: process.env.UPSTASH_REDIS_REST_TOKEN!,
1091
+ }),
1092
+ options: {
1093
+ generateTitle: true, // Explicitly enable automatic title generation
1094
+ },
1095
+ }),
1096
+ });
1097
+ ```
1098
+
1099
+ ### Using the agent
1100
+
1101
+ Use `memoryOptions` to scope recall for this request. Set `lastMessages: 5` to limit recency-based recall, and use `semanticRecall` to fetch the `topK: 3` most relevant messages, including `messageRange: 2` neighboring messages for context around each match.
1102
+
1103
+ ```typescript title="src/test-upstash-agent.ts"
1104
+ import "dotenv/config";
1105
+
1106
+ import { mastra } from "./mastra";
1107
+
1108
+ const threadId = "123";
1109
+ const resourceId = "user-456";
1110
+
1111
+ const agent = mastra.getAgent("upstashAgent");
1112
+
1113
+ const message = await agent.stream("My name is Mastra", {
1114
+ memory: {
1115
+ thread: threadId,
1116
+ resource: resourceId,
1117
+ },
1118
+ });
1119
+
1120
+ await message.textStream.pipeTo(new WritableStream());
1121
+
1122
+ const stream = await agent.stream("What's my name?", {
1123
+ memory: {
1124
+ thread: threadId,
1125
+ resource: resourceId,
1126
+ },
1127
+ memoryOptions: {
1128
+ lastMessages: 5,
1129
+ semanticRecall: {
1130
+ topK: 3,
1131
+ messageRange: 2,
1132
+ },
1133
+ },
1134
+ });
1135
+
1136
+ for await (const chunk of stream.textStream) {
1137
+ process.stdout.write(chunk);
1138
+ }
1139
+ ```