@mastra/mssql 0.0.0-scorers-ui-refactored-20250916094952 → 0.0.0-scorers-logs-20251208093427

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/README.md CHANGED
@@ -17,78 +17,365 @@ npm install @mastra/mssql
17
17
 
18
18
  ### Storage
19
19
 
20
+ #### Basic Configuration
21
+
22
+ MSSQLStore supports multiple connection methods:
23
+
24
+ **1. Connection String (Recommended)**
25
+
20
26
  ```typescript
21
27
  import { MSSQLStore } from '@mastra/mssql';
22
28
 
23
29
  const store = new MSSQLStore({
30
+ id: 'mssql-storage',
31
+ connectionString:
32
+ 'Server=localhost,1433;Database=mastra;User Id=sa;Password=yourPassword;Encrypt=true;TrustServerCertificate=true',
33
+ });
34
+ ```
35
+
36
+ **2. Server/Port/Database Configuration**
37
+
38
+ ```typescript
39
+ const store = new MSSQLStore({
40
+ id: 'mssql-storage',
24
41
  server: 'localhost',
25
42
  port: 1433,
26
43
  database: 'mastra',
27
44
  user: 'sa',
28
45
  password: 'yourStrong(!)Password',
29
- // options: { encrypt: true, trustServerCertificate: true }, // Optional
46
+ options: { encrypt: true, trustServerCertificate: true }, // Optional
30
47
  });
48
+ ```
31
49
 
32
- // Create a thread
33
- await store.saveThread({
34
- id: 'thread-123',
35
- resourceId: 'resource-456',
36
- title: 'My Thread',
37
- metadata: { key: 'value' },
50
+ #### Advanced Options
51
+
52
+ ```typescript
53
+ const store = new MSSQLStore({
54
+ id: 'mssql-storage',
55
+ connectionString:
56
+ 'Server=localhost,1433;Database=mastra;User Id=sa;Password=yourPassword;Encrypt=true;TrustServerCertificate=true',
57
+ schemaName: 'custom_schema', // Use custom schema (default: dbo)
58
+ options: {
59
+ encrypt: true,
60
+ trustServerCertificate: true,
61
+ connectTimeout: 30000,
62
+ requestTimeout: 30000,
63
+ pool: {
64
+ max: 20,
65
+ min: 0,
66
+ idleTimeoutMillis: 30000,
67
+ },
68
+ },
38
69
  });
70
+ ```
39
71
 
40
- // Add messages to thread
41
- await store.saveMessages([
42
- {
43
- id: 'msg-789',
44
- threadId: 'thread-123',
45
- role: 'user',
46
- type: 'text',
47
- content: [{ type: 'text', text: 'Hello' }],
72
+ #### Usage Example
73
+
74
+ ```typescript
75
+ // Create a thread
76
+ await store.saveThread({
77
+ thread: {
78
+ id: 'thread-123',
48
79
  resourceId: 'resource-456',
80
+ title: 'My Thread',
81
+ metadata: { key: 'value' },
49
82
  createdAt: new Date(),
83
+ updatedAt: new Date(),
50
84
  },
51
- ]);
85
+ });
86
+
87
+ // Add messages to thread
88
+ await store.saveMessages({
89
+ messages: [
90
+ {
91
+ id: 'msg-789',
92
+ threadId: 'thread-123',
93
+ role: 'user',
94
+ type: 'text',
95
+ content: [{ type: 'text', text: 'Hello' }],
96
+ resourceId: 'resource-456',
97
+ createdAt: new Date(),
98
+ },
99
+ ],
100
+ });
52
101
 
53
102
  // Query threads and messages
54
103
  const savedThread = await store.getThreadById({ threadId: 'thread-123' });
55
- const messages = await store.getMessages({ threadId: 'thread-123' });
104
+ const messages = await store.listMessages({ threadId: 'thread-123' });
56
105
  ```
57
106
 
58
107
  ## Configuration
59
108
 
60
- The MSSQL store can be initialized with either:
109
+ ### Identifier
110
+
111
+ - `id`: Unique identifier for this store instance (required)
112
+
113
+ ### Connection Methods
114
+
115
+ MSSQLStore supports multiple connection methods:
116
+
117
+ 1. **Connection String**
118
+
119
+ ```typescript
120
+ {
121
+ id: 'mssql-storage',
122
+ connectionString: 'Server=localhost,1433;Database=mastra;User Id=sa;Password=yourPassword;Encrypt=true;TrustServerCertificate=true';
123
+ }
124
+ ```
125
+
126
+ 2. **Server/Port/Database**
127
+ ```typescript
128
+ {
129
+ id: 'mssql-storage',
130
+ server: 'localhost',
131
+ port: 1433,
132
+ database: 'mastra',
133
+ user: 'sa',
134
+ password: 'password'
135
+ }
136
+ ```
137
+
138
+ ### Optional Configuration
61
139
 
62
- - `connectionString`: Microsoft SQL Server connection string
63
- - Configuration object with server, port, database, user, and password
140
+ - `schemaName`: Custom SQL Server schema (default: `dbo`)
141
+ - `options.encrypt`: Enable encryption (default: `true`)
142
+ - `options.trustServerCertificate`: Trust self-signed certificates (default: `true`)
143
+ - `options.connectTimeout`: Connection timeout in milliseconds (default: `15000`)
144
+ - `options.requestTimeout`: Request timeout in milliseconds (default: `15000`)
145
+ - `options.pool.max`: Maximum pool connections (default: `10`)
146
+ - `options.pool.min`: Minimum pool connections (default: `0`)
147
+ - `options.pool.idleTimeoutMillis`: Idle connection timeout (default: `30000`)
64
148
 
65
- Connection pool settings are managed by the [mssql](https://www.npmjs.com/package/mssql) package.
149
+ ### Default Connection Pool Settings
150
+
151
+ - Maximum connections: 10
152
+ - Minimum connections: 0
153
+ - Idle timeout: 30 seconds
154
+ - Connection timeout: 15 seconds
155
+ - Request timeout: 15 seconds
66
156
 
67
157
  ## Features
68
158
 
69
- - Thread and message storage with JSON support
70
- - Atomic transactions for data consistency
71
- - Efficient batch operations
72
- - Rich metadata support
73
- - Timestamp tracking
74
- - Cascading deletes (emulated)
159
+ ### Storage Features
160
+
161
+ - **Thread and Message Management**
162
+ - Thread and message storage with JSON support
163
+ - Message format versioning (v1 and v2)
164
+ - Pagination support for threads and messages
165
+ - Atomic transactions for batch operations (save, update, delete)
166
+ - Automatic thread timestamp updates
167
+ - Cascading deletes
168
+ - **Resources**
169
+ - Resource storage with working memory
170
+ - Rich metadata support
171
+ - Update working memory and metadata independently
172
+
173
+ - **Tracing & Observability**
174
+ - Trace AI agent execution with spans
175
+ - Query traces with pagination and filtering
176
+ - Batch operations for high-volume tracing
177
+ - Parent-child span relationships
178
+ - Span metadata and timing information
179
+
180
+ - **Workflow Management**
181
+ - Persist and restore workflow execution state
182
+ - Track workflow run history
183
+ - Step-by-step result tracking with row-level locking
184
+ - Workflow status management with row-level locking
185
+ - Query workflow runs by date range or resource
186
+ - Concurrent update protection for parallel workflow execution
187
+
188
+ - **Scoring & Evaluation**
189
+ - Store evaluation scores and metrics
190
+ - Query scores by scorer, run, entity, or span
191
+ - Support for multiple scoring sources
192
+ - Pagination support for large score datasets
193
+
194
+ - **Performance & Scalability**
195
+ - Connection pooling with configurable limits
196
+ - Atomic transactions for all batch operations
197
+ - Efficient batch insert/update/delete with transaction safety
198
+ - Row-level locking for concurrent updates
199
+ - Automatic performance indexes
200
+ - Index management (create, list, describe, drop)
201
+ - Timestamp tracking with high precision
202
+ - **Data Management**
203
+ - Custom schema support
204
+ - Table operations (create, alter, clear, drop)
205
+ - Low-level insert and load operations
206
+ - JSON data type support
75
207
 
76
208
  ## Storage Methods
77
209
 
210
+ ### Initialization & Connection
211
+
212
+ - `init()`: Initialize the store and create tables
213
+ - `close()`: Close database connection pool
214
+
215
+ ### Threads
216
+
78
217
  - `saveThread({ thread })`: Create or update a thread
79
218
  - `getThreadById({ threadId })`: Get a thread by ID
219
+ - `updateThread({ id, title, metadata })`: Update thread title and metadata
80
220
  - `deleteThread({ threadId })`: Delete a thread and its messages
81
- - `saveMessages({ messages })`: Save multiple messages in a transaction
82
- - `getMessages({ threadId })`: Get all messages for a thread
83
- - `updateMessages({ messages })`: Update messages by ID
84
- - `getThreadsByResourceIdPaginated({ resourceId, page, perPage })`: Paginated thread listing
85
- - `getMessagesPaginated({ threadId, selectBy })`: Paginated message listing
86
- - `clearTable({ tableName })`: Remove all rows from a table (with cascade)
87
- - `createTable({ tableName, schema })`: Create a table if it does not exist
88
- - `alterTable({ tableName, schema, ifNotExists })`: Add columns if they do not exist
89
- - `saveResource({ resource })`: Save a resource
221
+ - `listThreadsByResourceId({ resourceId, offset, limit, orderBy? })`: List paginated threads for a resource
222
+
223
+ ### Messages
224
+
225
+ - `saveMessages({ messages })`: Save multiple messages with atomic transaction
226
+ - `listMessagesById({ messageIds })`: Get messages by their IDs
227
+ - `listMessages({ threadId, resourceId?, page?, perPage?, orderBy?, filter? })`: Get paginated messages for a thread with filtering and sorting
228
+ - `updateMessages({ messages })`: Update existing messages with atomic transaction
229
+ - `deleteMessages(messageIds)`: Delete specific messages with atomic transaction
230
+
231
+ ### Resources
232
+
233
+ - `saveResource({ resource })`: Save a resource with working memory
90
234
  - `getResourceById({ resourceId })`: Get a resource by ID
91
- - `updateResource({ resourceId, ... })`: Update a resource
235
+ - `updateResource({ resourceId, workingMemory?, metadata? })`: Update resource working memory and metadata
236
+
237
+ ### Tracing & Observability
238
+
239
+ - `createSpan(span)`: Create a trace span
240
+ - `updateSpan({ spanId, traceId, updates })`: Update an existing span
241
+ - `getTrace(traceId)`: Get complete trace with all spans
242
+ - `getTracesPaginated({ filters?, pagination? })`: Query traces with pagination and filters
243
+ - `batchCreateSpans({ records })`: Batch create multiple spans
244
+ - `batchUpdateSpans({ records })`: Batch update multiple spans
245
+ - `batchDeleteTraces({ traceIds })`: Batch delete traces
246
+
247
+ ### Index Management
248
+
249
+ - `createIndex({ name, table, columns, unique?, where? })`: Create a new index
250
+ - `listIndexes(tableName?)`: List all indexes or indexes for a specific table
251
+ - `describeIndex(indexName)`: Get detailed index statistics and information
252
+ - `dropIndex(indexName)`: Drop an existing index
253
+
254
+ ### Workflows
255
+
256
+ - `persistWorkflowSnapshot({ workflowName, runId, resourceId?, snapshot })`: Save workflow execution state
257
+ - `loadWorkflowSnapshot({ workflowName, runId })`: Load workflow execution state
258
+ - `updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext })`: Update step results (transaction + row locking)
259
+ - `updateWorkflowState({ workflowName, runId, opts })`: Update workflow run status (transaction + row locking)
260
+ - `listWorkflowRuns({ workflowName?, fromDate?, toDate?, limit?, offset?, resourceId? })`: Query workflow runs
261
+ - `getWorkflowRunById({ runId, workflowName? })`: Get specific workflow run
262
+
263
+ ### Scores & Evaluation
264
+
265
+ - `saveScore(score)`: Save evaluation score
266
+ - `getScoreById({ id })`: Get score by ID
267
+ - `listScoresByScorerId({ scorerId, pagination, entityId?, entityType?, source? })`: Get scores by scorer
268
+ - `listScoresByRunId({ runId, pagination })`: Get scores for a run
269
+ - `listScoresByEntityId({ entityId, entityType, pagination })`: Get scores for an entity
270
+ - `listScoresBySpan({ traceId, spanId, pagination })`: Get scores for a trace span
271
+
272
+ ### Traces (Legacy)
273
+
274
+ - `getTracesPaginated({ filters?, pagination? })`: Get paginated legacy traces
275
+ - `batchTraceInsert({ records })`: Batch insert legacy trace records
276
+
277
+ ### Evals (Legacy)
278
+
279
+ - `getEvals({ agentName?, type?, page?, perPage? })`: Get paginated evaluations
280
+
281
+ ### Low-level Operations
282
+
283
+ - `createTable({ tableName, schema })`: Create a new table
284
+ - `alterTable({ tableName, schema, ifNotExists })`: Add columns to existing table
285
+ - `clearTable({ tableName })`: Remove all rows from a table
286
+ - `dropTable({ tableName })`: Drop a table
287
+ - `insert({ tableName, record })`: Insert a single record
288
+ - `batchInsert({ tableName, records })`: Batch insert multiple records
289
+ - `load<R>({ tableName, keys })`: Load a record by key(s)
290
+
291
+ ## Index Management
292
+
293
+ The MSSQL store provides comprehensive index management capabilities to optimize query performance.
294
+
295
+ ### Automatic Performance Indexes
296
+
297
+ MSSQL storage automatically creates composite indexes during initialization for common query patterns. These indexes significantly improve performance for filtered queries with sorting.
298
+
299
+ ### Creating Custom Indexes
300
+
301
+ ```typescript
302
+ // Basic index for common queries
303
+ await store.createIndex({
304
+ name: 'idx_threads_resource',
305
+ table: 'mastra_threads',
306
+ columns: ['resourceId'],
307
+ });
308
+
309
+ // Composite index with sort order for filtering + sorting
310
+ await store.createIndex({
311
+ name: 'idx_messages_composite',
312
+ table: 'mastra_messages',
313
+ columns: ['thread_id', 'seq_id DESC'],
314
+ });
315
+
316
+ // Unique index for constraints
317
+ await store.createIndex({
318
+ name: 'idx_unique_constraint',
319
+ table: 'mastra_resources',
320
+ columns: ['id'],
321
+ unique: true,
322
+ });
323
+
324
+ // Filtered index (partial indexing)
325
+ await store.createIndex({
326
+ name: 'idx_active_threads',
327
+ table: 'mastra_threads',
328
+ columns: ['resourceId'],
329
+ where: "status = 'active'",
330
+ });
331
+ ```
332
+
333
+ ### Managing Indexes
334
+
335
+ ```typescript
336
+ // List all indexes
337
+ const allIndexes = await store.listIndexes();
338
+
339
+ // List indexes for specific table
340
+ const threadIndexes = await store.listIndexes('mastra_threads');
341
+
342
+ // Get detailed statistics for an index
343
+ const stats = await store.describeIndex('idx_threads_resource');
344
+ console.log(stats);
345
+ // {
346
+ // name: 'idx_threads_resource',
347
+ // table: 'mastra_threads',
348
+ // columns: ['resourceId', 'seq_id'],
349
+ // unique: false,
350
+ // size: '128 KB',
351
+ // method: 'nonclustered',
352
+ // scans: 1542, // Number of index seeks
353
+ // tuples_read: 45230, // Tuples read via index
354
+ // tuples_fetched: 12050 // Tuples fetched via index
355
+ // }
356
+
357
+ // Drop an index
358
+ await store.dropIndex('idx_threads_resource');
359
+ ```
360
+
361
+ ### Monitoring Index Performance
362
+
363
+ ```typescript
364
+ // Check index usage statistics
365
+ const stats = await store.describeIndex('idx_threads_resource');
366
+
367
+ // Identify unused indexes
368
+ if (stats.scans === 0) {
369
+ console.log(`Index ${stats.name} is unused - consider removing`);
370
+ await store.dropIndex(stats.name);
371
+ }
372
+
373
+ // Monitor index efficiency
374
+ const efficiency = stats.tuples_fetched / stats.tuples_read;
375
+ if (efficiency < 0.5) {
376
+ console.log(`Index ${stats.name} has low efficiency: ${efficiency}`);
377
+ }
378
+ ```
92
379
 
93
380
  ## Related Links
94
381