@mastra/mssql 0.0.0-fix-persist-session-cache-option-mcp-server-20251031182703 → 0.0.0-fix-9244-clickhouse-metadata-20251104220626

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/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
2
- import { MastraStorage, StoreOperations, TABLE_WORKFLOW_SNAPSHOT, TABLE_SCHEMAS, TABLE_THREADS, TABLE_MESSAGES, TABLE_TRACES, TABLE_SCORERS, TABLE_AI_SPANS, ScoresStorage, WorkflowsStorage, MemoryStorage, resolveMessageLimit, TABLE_RESOURCES, ObservabilityStorage, safelyParseJSON } from '@mastra/core/storage';
2
+ import { MastraStorage, StoreOperations, TABLE_WORKFLOW_SNAPSHOT, TABLE_SCHEMAS, TABLE_THREADS, TABLE_MESSAGES, TABLE_TRACES, TABLE_SCORERS, TABLE_AI_SPANS, ScoresStorage, normalizePerPage, calculatePagination, WorkflowsStorage, MemoryStorage, resolveMessageLimit, TABLE_RESOURCES, ObservabilityStorage, safelyParseJSON } from '@mastra/core/storage';
3
3
  import sql2 from 'mssql';
4
4
  import { MessageList } from '@mastra/core/agent';
5
5
  import { parseSqlIdentifier } from '@mastra/core/utils';
6
6
  import { randomUUID } from 'crypto';
7
- import { saveScorePayloadSchema } from '@mastra/core/scores';
7
+ import { saveScorePayloadSchema } from '@mastra/core/evals';
8
8
 
9
9
  // src/storage/index.ts
10
10
  function getSchemaName(schema) {
@@ -98,7 +98,7 @@ var MemoryMSSQL = class extends MemoryStorage {
98
98
  });
99
99
  const cleanMessages = messagesWithParsedContent.map(({ seq_id, ...rest }) => rest);
100
100
  const list = new MessageList().add(cleanMessages, "memory");
101
- return format === "v2" ? list.get.all.v2() : list.get.all.v1();
101
+ return format === "v2" ? list.get.all.db() : list.get.all.v1();
102
102
  }
103
103
  constructor({
104
104
  pool,
@@ -148,11 +148,12 @@ var MemoryMSSQL = class extends MemoryStorage {
148
148
  );
149
149
  }
150
150
  }
151
- async getThreadsByResourceIdPaginated(args) {
152
- const { resourceId, page = 0, perPage: perPageInput, orderBy = "createdAt", sortDirection = "DESC" } = args;
151
+ async listThreadsByResourceId(args) {
152
+ const { resourceId, page = 0, perPage: perPageInput, orderBy } = args;
153
+ const perPage = normalizePerPage(perPageInput, 100);
154
+ const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
155
+ const { field, direction } = this.parseOrderBy(orderBy);
153
156
  try {
154
- const perPage = perPageInput !== void 0 ? perPageInput : 100;
155
- const currentOffset = page * perPage;
156
157
  const baseQuery = `FROM ${getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) })} WHERE [resourceId] = @resourceId`;
157
158
  const countQuery = `SELECT COUNT(*) as count ${baseQuery}`;
158
159
  const countRequest = this.pool.request();
@@ -164,17 +165,22 @@ var MemoryMSSQL = class extends MemoryStorage {
164
165
  threads: [],
165
166
  total: 0,
166
167
  page,
167
- perPage,
168
+ perPage: perPageForResponse,
168
169
  hasMore: false
169
170
  };
170
171
  }
171
- const orderByField = orderBy === "createdAt" ? "[createdAt]" : "[updatedAt]";
172
- const dir = (sortDirection || "DESC").toUpperCase() === "ASC" ? "ASC" : "DESC";
172
+ const orderByField = field === "createdAt" ? "[createdAt]" : "[updatedAt]";
173
+ const dir = (direction || "DESC").toUpperCase() === "ASC" ? "ASC" : "DESC";
174
+ const limitValue = perPageInput === false ? total : perPage;
173
175
  const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY ${orderByField} ${dir} OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
174
176
  const dataRequest = this.pool.request();
175
177
  dataRequest.input("resourceId", resourceId);
176
- dataRequest.input("perPage", perPage);
177
- dataRequest.input("offset", currentOffset);
178
+ dataRequest.input("offset", offset);
179
+ if (limitValue > 2147483647) {
180
+ dataRequest.input("perPage", sql2.BigInt, limitValue);
181
+ } else {
182
+ dataRequest.input("perPage", limitValue);
183
+ }
178
184
  const rowsResult = await dataRequest.query(dataQuery);
179
185
  const rows = rowsResult.recordset || [];
180
186
  const threads = rows.map((thread) => ({
@@ -187,13 +193,13 @@ var MemoryMSSQL = class extends MemoryStorage {
187
193
  threads,
188
194
  total,
189
195
  page,
190
- perPage,
191
- hasMore: currentOffset + threads.length < total
196
+ perPage: perPageForResponse,
197
+ hasMore: perPageInput === false ? false : offset + perPage < total
192
198
  };
193
199
  } catch (error) {
194
200
  const mastraError = new MastraError(
195
201
  {
196
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
202
+ id: "MASTRA_STORAGE_MSSQL_STORE_LIST_THREADS_BY_RESOURCE_ID_FAILED",
197
203
  domain: ErrorDomain.STORAGE,
198
204
  category: ErrorCategory.THIRD_PARTY,
199
205
  details: {
@@ -205,7 +211,13 @@ var MemoryMSSQL = class extends MemoryStorage {
205
211
  );
206
212
  this.logger?.error?.(mastraError.toString());
207
213
  this.logger?.trackException?.(mastraError);
208
- return { threads: [], total: 0, page, perPage: perPageInput || 100, hasMore: false };
214
+ return {
215
+ threads: [],
216
+ total: 0,
217
+ page,
218
+ perPage: perPageForResponse,
219
+ hasMore: false
220
+ };
209
221
  }
210
222
  }
211
223
  async saveThread({ thread }) {
@@ -251,31 +263,6 @@ var MemoryMSSQL = class extends MemoryStorage {
251
263
  );
252
264
  }
253
265
  }
254
- /**
255
- * @deprecated use getThreadsByResourceIdPaginated instead
256
- */
257
- async getThreadsByResourceId(args) {
258
- const { resourceId, orderBy = "createdAt", sortDirection = "DESC" } = args;
259
- try {
260
- const baseQuery = `FROM ${getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) })} WHERE [resourceId] = @resourceId`;
261
- const orderByField = orderBy === "createdAt" ? "[createdAt]" : "[updatedAt]";
262
- const dir = (sortDirection || "DESC").toUpperCase() === "ASC" ? "ASC" : "DESC";
263
- const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY ${orderByField} ${dir}`;
264
- const request = this.pool.request();
265
- request.input("resourceId", resourceId);
266
- const resultSet = await request.query(dataQuery);
267
- const rows = resultSet.recordset || [];
268
- return rows.map((thread) => ({
269
- ...thread,
270
- metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
271
- createdAt: thread.createdAt,
272
- updatedAt: thread.updatedAt
273
- }));
274
- } catch (error) {
275
- this.logger?.error?.(`Error getting threads for resource ${resourceId}:`, error);
276
- return [];
277
- }
278
- }
279
266
  /**
280
267
  * Updates a thread's title and metadata, merging with existing metadata. Returns the updated thread.
281
268
  */
@@ -384,8 +371,7 @@ var MemoryMSSQL = class extends MemoryStorage {
384
371
  }
385
372
  async _getIncludedMessages({
386
373
  threadId,
387
- selectBy,
388
- orderByStatement
374
+ selectBy
389
375
  }) {
390
376
  if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
391
377
  const include = selectBy?.include;
@@ -413,7 +399,7 @@ var MemoryMSSQL = class extends MemoryStorage {
413
399
  m.[resourceId],
414
400
  m.seq_id
415
401
  FROM (
416
- SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
402
+ SELECT *, ROW_NUMBER() OVER (ORDER BY [createdAt] ASC) as row_num
417
403
  FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}
418
404
  WHERE [thread_id] = ${pThreadId}
419
405
  ) AS m
@@ -421,15 +407,17 @@ var MemoryMSSQL = class extends MemoryStorage {
421
407
  OR EXISTS (
422
408
  SELECT 1
423
409
  FROM (
424
- SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
410
+ SELECT *, ROW_NUMBER() OVER (ORDER BY [createdAt] ASC) as row_num
425
411
  FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}
426
412
  WHERE [thread_id] = ${pThreadId}
427
413
  ) AS target
428
414
  WHERE target.id = ${pId}
429
415
  AND (
430
- (m.row_num <= target.row_num + ${pPrev} AND m.row_num > target.row_num)
416
+ -- Get previous messages (messages that come BEFORE the target)
417
+ (m.row_num < target.row_num AND m.row_num >= target.row_num - ${pPrev})
431
418
  OR
432
- (m.row_num >= target.row_num - ${pNext} AND m.row_num < target.row_num)
419
+ -- Get next messages (messages that come AFTER the target)
420
+ (m.row_num > target.row_num AND m.row_num <= target.row_num + ${pNext})
433
421
  )
434
422
  )
435
423
  `
@@ -458,8 +446,11 @@ var MemoryMSSQL = class extends MemoryStorage {
458
446
  });
459
447
  return dedupedRows;
460
448
  }
449
+ /**
450
+ * @deprecated use listMessages instead
451
+ */
461
452
  async getMessages(args) {
462
- const { threadId, resourceId, format, selectBy } = args;
453
+ const { threadId, resourceId, selectBy } = args;
463
454
  const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
464
455
  const orderByStatement = `ORDER BY [seq_id] DESC`;
465
456
  const limit = resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
@@ -468,7 +459,7 @@ var MemoryMSSQL = class extends MemoryStorage {
468
459
  let rows = [];
469
460
  const include = selectBy?.include || [];
470
461
  if (include?.length) {
471
- const includeMessages = await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
462
+ const includeMessages = await this._getIncludedMessages({ threadId, selectBy });
472
463
  if (includeMessages) {
473
464
  rows.push(...includeMessages);
474
465
  }
@@ -493,8 +484,19 @@ var MemoryMSSQL = class extends MemoryStorage {
493
484
  const timeDiff = a.seq_id - b.seq_id;
494
485
  return timeDiff;
495
486
  });
496
- rows = rows.map(({ seq_id, ...rest }) => rest);
497
- return this._parseAndFormatMessages(rows, format);
487
+ const messagesWithParsedContent = rows.map((row) => {
488
+ if (typeof row.content === "string") {
489
+ try {
490
+ return { ...row, content: JSON.parse(row.content) };
491
+ } catch {
492
+ return row;
493
+ }
494
+ }
495
+ return row;
496
+ });
497
+ const cleanMessages = messagesWithParsedContent.map(({ seq_id, ...rest }) => rest);
498
+ const list = new MessageList().add(cleanMessages, "memory");
499
+ return { messages: list.get.all.db() };
498
500
  } catch (error) {
499
501
  const mastraError = new MastraError(
500
502
  {
@@ -510,14 +512,11 @@ var MemoryMSSQL = class extends MemoryStorage {
510
512
  );
511
513
  this.logger?.error?.(mastraError.toString());
512
514
  this.logger?.trackException?.(mastraError);
513
- return [];
515
+ return { messages: [] };
514
516
  }
515
517
  }
516
- async getMessagesById({
517
- messageIds,
518
- format
519
- }) {
520
- if (messageIds.length === 0) return [];
518
+ async listMessagesById({ messageIds }) {
519
+ if (messageIds.length === 0) return { messages: [] };
521
520
  const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
522
521
  const orderByStatement = `ORDER BY [seq_id] DESC`;
523
522
  try {
@@ -533,13 +532,23 @@ var MemoryMSSQL = class extends MemoryStorage {
533
532
  const timeDiff = a.seq_id - b.seq_id;
534
533
  return timeDiff;
535
534
  });
536
- rows = rows.map(({ seq_id, ...rest }) => rest);
537
- if (format === `v1`) return this._parseAndFormatMessages(rows, format);
538
- return this._parseAndFormatMessages(rows, `v2`);
535
+ const messagesWithParsedContent = rows.map((row) => {
536
+ if (typeof row.content === "string") {
537
+ try {
538
+ return { ...row, content: JSON.parse(row.content) };
539
+ } catch {
540
+ return row;
541
+ }
542
+ }
543
+ return row;
544
+ });
545
+ const cleanMessages = messagesWithParsedContent.map(({ seq_id, ...rest }) => rest);
546
+ const list = new MessageList().add(cleanMessages, "memory");
547
+ return { messages: list.get.all.db() };
539
548
  } catch (error) {
540
549
  const mastraError = new MastraError(
541
550
  {
542
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_BY_ID_FAILED",
551
+ id: "MASTRA_STORAGE_MSSQL_STORE_LIST_MESSAGES_BY_ID_FAILED",
543
552
  domain: ErrorDomain.STORAGE,
544
553
  category: ErrorCategory.THIRD_PARTY,
545
554
  details: {
@@ -550,110 +559,124 @@ var MemoryMSSQL = class extends MemoryStorage {
550
559
  );
551
560
  this.logger?.error?.(mastraError.toString());
552
561
  this.logger?.trackException?.(mastraError);
553
- return [];
562
+ return { messages: [] };
554
563
  }
555
564
  }
556
- async listMessages(_args) {
557
- throw new Error(
558
- `listMessages is not yet implemented by this storage adapter (${this.constructor.name}). This method is currently being rolled out across all storage adapters. Please use getMessages or getMessagesPaginated as an alternative, or wait for the implementation.`
559
- );
560
- }
561
- async listMessagesById({ messageIds }) {
562
- return this.getMessagesById({ messageIds, format: "v2" });
563
- }
564
- async listThreadsByResourceId(args) {
565
- const { resourceId, limit, offset, orderBy, sortDirection } = args;
566
- const page = Math.floor(offset / limit);
567
- const perPage = limit;
568
- return this.getThreadsByResourceIdPaginated({ resourceId, page, perPage, orderBy, sortDirection });
569
- }
570
- async getMessagesPaginated(args) {
571
- const { threadId, resourceId, format, selectBy } = args;
572
- const { page = 0, perPage: perPageInput, dateRange } = selectBy?.pagination || {};
565
+ async listMessages(args) {
566
+ const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
567
+ if (!threadId.trim()) {
568
+ throw new MastraError(
569
+ {
570
+ id: "STORAGE_MSSQL_LIST_MESSAGES_INVALID_THREAD_ID",
571
+ domain: ErrorDomain.STORAGE,
572
+ category: ErrorCategory.THIRD_PARTY,
573
+ details: { threadId }
574
+ },
575
+ new Error("threadId must be a non-empty string")
576
+ );
577
+ }
578
+ const perPage = normalizePerPage(perPageInput, 40);
579
+ const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
573
580
  try {
574
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
575
- const fromDate = dateRange?.start;
576
- const toDate = dateRange?.end;
581
+ const { field, direction } = this.parseOrderBy(orderBy);
582
+ const orderByStatement = `ORDER BY [${field}] ${direction}`;
577
583
  const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
578
- const orderByStatement = `ORDER BY [seq_id] DESC`;
579
- let messages = [];
580
- if (selectBy?.include?.length) {
581
- const includeMessages = await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
582
- if (includeMessages) messages.push(...includeMessages);
583
- }
584
- const perPage = perPageInput !== void 0 ? perPageInput : resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
585
- const currentOffset = page * perPage;
584
+ const tableName = getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
586
585
  const conditions = ["[thread_id] = @threadId"];
587
586
  const request = this.pool.request();
588
587
  request.input("threadId", threadId);
589
- if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
588
+ if (resourceId) {
589
+ conditions.push("[resourceId] = @resourceId");
590
+ request.input("resourceId", resourceId);
591
+ }
592
+ if (filter?.dateRange?.start) {
590
593
  conditions.push("[createdAt] >= @fromDate");
591
- request.input("fromDate", fromDate.toISOString());
594
+ request.input("fromDate", filter.dateRange.start);
592
595
  }
593
- if (toDate instanceof Date && !isNaN(toDate.getTime())) {
596
+ if (filter?.dateRange?.end) {
594
597
  conditions.push("[createdAt] <= @toDate");
595
- request.input("toDate", toDate.toISOString());
598
+ request.input("toDate", filter.dateRange.end);
596
599
  }
597
600
  const whereClause = `WHERE ${conditions.join(" AND ")}`;
598
- const countQuery = `SELECT COUNT(*) as total FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} ${whereClause}`;
601
+ const countQuery = `SELECT COUNT(*) as total FROM ${tableName} ${whereClause}`;
599
602
  const countResult = await request.query(countQuery);
600
603
  const total = parseInt(countResult.recordset[0]?.total, 10) || 0;
601
- if (total === 0 && messages.length > 0) {
602
- const parsedIncluded = this._parseAndFormatMessages(messages, format);
604
+ const limitValue = perPageInput === false ? total : perPage;
605
+ const dataQuery = `${selectStatement} FROM ${tableName} ${whereClause} ${orderByStatement} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
606
+ request.input("offset", offset);
607
+ if (limitValue > 2147483647) {
608
+ request.input("limit", sql2.BigInt, limitValue);
609
+ } else {
610
+ request.input("limit", limitValue);
611
+ }
612
+ const rowsResult = await request.query(dataQuery);
613
+ const rows = rowsResult.recordset || [];
614
+ const messages = [...rows];
615
+ if (total === 0 && messages.length === 0 && (!include || include.length === 0)) {
603
616
  return {
604
- messages: parsedIncluded,
605
- total: parsedIncluded.length,
617
+ messages: [],
618
+ total: 0,
606
619
  page,
607
- perPage,
620
+ perPage: perPageForResponse,
608
621
  hasMore: false
609
622
  };
610
623
  }
611
- const excludeIds = messages.map((m) => m.id);
612
- if (excludeIds.length > 0) {
613
- const excludeParams = excludeIds.map((_, idx) => `@id${idx}`);
614
- conditions.push(`id NOT IN (${excludeParams.join(", ")})`);
615
- excludeIds.forEach((id, idx) => request.input(`id${idx}`, id));
624
+ const messageIds = new Set(messages.map((m) => m.id));
625
+ if (include && include.length > 0) {
626
+ const selectBy = { include };
627
+ const includeMessages = await this._getIncludedMessages({ threadId, selectBy });
628
+ if (includeMessages) {
629
+ for (const includeMsg of includeMessages) {
630
+ if (!messageIds.has(includeMsg.id)) {
631
+ messages.push(includeMsg);
632
+ messageIds.add(includeMsg.id);
633
+ }
634
+ }
635
+ }
616
636
  }
617
- const finalWhereClause = `WHERE ${conditions.join(" AND ")}`;
618
- const dataQuery = `${selectStatement} FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} ${finalWhereClause} ${orderByStatement} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
619
- request.input("offset", currentOffset);
620
- request.input("limit", perPage);
621
- const rowsResult = await request.query(dataQuery);
622
- const rows = rowsResult.recordset || [];
623
- rows.sort((a, b) => a.seq_id - b.seq_id);
624
- messages.push(...rows);
625
- const parsed = this._parseAndFormatMessages(messages, format);
637
+ const parsed = this._parseAndFormatMessages(messages, "v2");
638
+ let finalMessages = parsed;
639
+ finalMessages = finalMessages.sort((a, b) => {
640
+ const aValue = field === "createdAt" ? new Date(a.createdAt).getTime() : a[field];
641
+ const bValue = field === "createdAt" ? new Date(b.createdAt).getTime() : b[field];
642
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
643
+ });
644
+ const returnedThreadMessageIds = new Set(finalMessages.filter((m) => m.threadId === threadId).map((m) => m.id));
645
+ const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
646
+ const hasMore = perPageInput !== false && !allThreadMessagesReturned && offset + perPage < total;
626
647
  return {
627
- messages: parsed,
648
+ messages: finalMessages,
628
649
  total,
629
650
  page,
630
- perPage,
631
- hasMore: currentOffset + rows.length < total
651
+ perPage: perPageForResponse,
652
+ hasMore
632
653
  };
633
654
  } catch (error) {
634
655
  const mastraError = new MastraError(
635
656
  {
636
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_PAGINATED_FAILED",
657
+ id: "MASTRA_STORAGE_MSSQL_STORE_LIST_MESSAGES_FAILED",
637
658
  domain: ErrorDomain.STORAGE,
638
659
  category: ErrorCategory.THIRD_PARTY,
639
660
  details: {
640
661
  threadId,
641
- resourceId: resourceId ?? "",
642
- page
662
+ resourceId: resourceId ?? ""
643
663
  }
644
664
  },
645
665
  error
646
666
  );
647
667
  this.logger?.error?.(mastraError.toString());
648
668
  this.logger?.trackException?.(mastraError);
649
- return { messages: [], total: 0, page, perPage: perPageInput || 40, hasMore: false };
669
+ return {
670
+ messages: [],
671
+ total: 0,
672
+ page,
673
+ perPage: perPageForResponse,
674
+ hasMore: false
675
+ };
650
676
  }
651
677
  }
652
- async saveMessages({
653
- messages,
654
- format
655
- }) {
656
- if (messages.length === 0) return messages;
678
+ async saveMessages({ messages }) {
679
+ if (messages.length === 0) return { messages: [] };
657
680
  const threadId = messages[0]?.threadId;
658
681
  if (!threadId) {
659
682
  throw new MastraError({
@@ -735,8 +758,7 @@ var MemoryMSSQL = class extends MemoryStorage {
735
758
  return message;
736
759
  });
737
760
  const list = new MessageList().add(messagesWithParsedContent, "memory");
738
- if (format === "v2") return list.get.all.v2();
739
- return list.get.all.v1();
761
+ return { messages: list.get.all.db() };
740
762
  } catch (error) {
741
763
  throw new MastraError(
742
764
  {
@@ -2368,7 +2390,7 @@ var ScoresMSSQL = class extends ScoresStorage {
2368
2390
  );
2369
2391
  }
2370
2392
  }
2371
- async getScoresByScorerId({
2393
+ async listScoresByScorerId({
2372
2394
  scorerId,
2373
2395
  pagination,
2374
2396
  entityId,
@@ -2402,31 +2424,36 @@ var ScoresMSSQL = class extends ScoresStorage {
2402
2424
  });
2403
2425
  const totalResult = await countRequest.query(`SELECT COUNT(*) as count FROM ${tableName} WHERE ${whereClause}`);
2404
2426
  const total = totalResult.recordset[0]?.count || 0;
2427
+ const { page, perPage: perPageInput } = pagination;
2405
2428
  if (total === 0) {
2406
2429
  return {
2407
2430
  pagination: {
2408
2431
  total: 0,
2409
- page: pagination.page,
2410
- perPage: pagination.perPage,
2432
+ page,
2433
+ perPage: perPageInput,
2411
2434
  hasMore: false
2412
2435
  },
2413
2436
  scores: []
2414
2437
  };
2415
2438
  }
2439
+ const perPage = normalizePerPage(perPageInput, 100);
2440
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
2441
+ const limitValue = perPageInput === false ? total : perPage;
2442
+ const end = perPageInput === false ? total : start + perPage;
2416
2443
  const dataRequest = this.pool.request();
2417
2444
  Object.entries(params).forEach(([key, value]) => {
2418
2445
  dataRequest.input(key, value);
2419
2446
  });
2420
- dataRequest.input("perPage", pagination.perPage);
2421
- dataRequest.input("offset", pagination.page * pagination.perPage);
2447
+ dataRequest.input("perPage", limitValue);
2448
+ dataRequest.input("offset", start);
2422
2449
  const dataQuery = `SELECT * FROM ${tableName} WHERE ${whereClause} ORDER BY [createdAt] DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
2423
2450
  const result = await dataRequest.query(dataQuery);
2424
2451
  return {
2425
2452
  pagination: {
2426
2453
  total: Number(total),
2427
- page: pagination.page,
2428
- perPage: pagination.perPage,
2429
- hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
2454
+ page,
2455
+ perPage: perPageForResponse,
2456
+ hasMore: end < total
2430
2457
  },
2431
2458
  scores: result.recordset.map((row) => transformScoreRow(row))
2432
2459
  };
@@ -2442,7 +2469,7 @@ var ScoresMSSQL = class extends ScoresStorage {
2442
2469
  );
2443
2470
  }
2444
2471
  }
2445
- async getScoresByRunId({
2472
+ async listScoresByRunId({
2446
2473
  runId,
2447
2474
  pagination
2448
2475
  }) {
@@ -2453,30 +2480,35 @@ var ScoresMSSQL = class extends ScoresStorage {
2453
2480
  `SELECT COUNT(*) as count FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [runId] = @p1`
2454
2481
  );
2455
2482
  const total = totalResult.recordset[0]?.count || 0;
2483
+ const { page, perPage: perPageInput } = pagination;
2456
2484
  if (total === 0) {
2457
2485
  return {
2458
2486
  pagination: {
2459
2487
  total: 0,
2460
- page: pagination.page,
2461
- perPage: pagination.perPage,
2488
+ page,
2489
+ perPage: perPageInput,
2462
2490
  hasMore: false
2463
2491
  },
2464
2492
  scores: []
2465
2493
  };
2466
2494
  }
2495
+ const perPage = normalizePerPage(perPageInput, 100);
2496
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
2497
+ const limitValue = perPageInput === false ? total : perPage;
2498
+ const end = perPageInput === false ? total : start + perPage;
2467
2499
  const dataRequest = this.pool.request();
2468
2500
  dataRequest.input("p1", runId);
2469
- dataRequest.input("p2", pagination.perPage);
2470
- dataRequest.input("p3", pagination.page * pagination.perPage);
2501
+ dataRequest.input("p2", limitValue);
2502
+ dataRequest.input("p3", start);
2471
2503
  const result = await dataRequest.query(
2472
2504
  `SELECT * FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [runId] = @p1 ORDER BY [createdAt] DESC OFFSET @p3 ROWS FETCH NEXT @p2 ROWS ONLY`
2473
2505
  );
2474
2506
  return {
2475
2507
  pagination: {
2476
2508
  total: Number(total),
2477
- page: pagination.page,
2478
- perPage: pagination.perPage,
2479
- hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
2509
+ page,
2510
+ perPage: perPageForResponse,
2511
+ hasMore: end < total
2480
2512
  },
2481
2513
  scores: result.recordset.map((row) => transformScoreRow(row))
2482
2514
  };
@@ -2492,7 +2524,7 @@ var ScoresMSSQL = class extends ScoresStorage {
2492
2524
  );
2493
2525
  }
2494
2526
  }
2495
- async getScoresByEntityId({
2527
+ async listScoresByEntityId({
2496
2528
  entityId,
2497
2529
  entityType,
2498
2530
  pagination
@@ -2505,31 +2537,36 @@ var ScoresMSSQL = class extends ScoresStorage {
2505
2537
  `SELECT COUNT(*) as count FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [entityId] = @p1 AND [entityType] = @p2`
2506
2538
  );
2507
2539
  const total = totalResult.recordset[0]?.count || 0;
2540
+ const { page, perPage: perPageInput } = pagination;
2541
+ const perPage = normalizePerPage(perPageInput, 100);
2542
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
2508
2543
  if (total === 0) {
2509
2544
  return {
2510
2545
  pagination: {
2511
2546
  total: 0,
2512
- page: pagination.page,
2513
- perPage: pagination.perPage,
2547
+ page,
2548
+ perPage: perPageForResponse,
2514
2549
  hasMore: false
2515
2550
  },
2516
2551
  scores: []
2517
2552
  };
2518
2553
  }
2554
+ const limitValue = perPageInput === false ? total : perPage;
2555
+ const end = perPageInput === false ? total : start + perPage;
2519
2556
  const dataRequest = this.pool.request();
2520
2557
  dataRequest.input("p1", entityId);
2521
2558
  dataRequest.input("p2", entityType);
2522
- dataRequest.input("p3", pagination.perPage);
2523
- dataRequest.input("p4", pagination.page * pagination.perPage);
2559
+ dataRequest.input("p3", limitValue);
2560
+ dataRequest.input("p4", start);
2524
2561
  const result = await dataRequest.query(
2525
2562
  `SELECT * FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [entityId] = @p1 AND [entityType] = @p2 ORDER BY [createdAt] DESC OFFSET @p4 ROWS FETCH NEXT @p3 ROWS ONLY`
2526
2563
  );
2527
2564
  return {
2528
2565
  pagination: {
2529
2566
  total: Number(total),
2530
- page: pagination.page,
2531
- perPage: pagination.perPage,
2532
- hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
2567
+ page,
2568
+ perPage: perPageForResponse,
2569
+ hasMore: end < total
2533
2570
  },
2534
2571
  scores: result.recordset.map((row) => transformScoreRow(row))
2535
2572
  };
@@ -2545,7 +2582,7 @@ var ScoresMSSQL = class extends ScoresStorage {
2545
2582
  );
2546
2583
  }
2547
2584
  }
2548
- async getScoresBySpan({
2585
+ async listScoresBySpan({
2549
2586
  traceId,
2550
2587
  spanId,
2551
2588
  pagination
@@ -2558,34 +2595,38 @@ var ScoresMSSQL = class extends ScoresStorage {
2558
2595
  `SELECT COUNT(*) as count FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [traceId] = @p1 AND [spanId] = @p2`
2559
2596
  );
2560
2597
  const total = totalResult.recordset[0]?.count || 0;
2598
+ const { page, perPage: perPageInput } = pagination;
2599
+ const perPage = normalizePerPage(perPageInput, 100);
2600
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
2561
2601
  if (total === 0) {
2562
2602
  return {
2563
2603
  pagination: {
2564
2604
  total: 0,
2565
- page: pagination.page,
2566
- perPage: pagination.perPage,
2605
+ page,
2606
+ perPage: perPageForResponse,
2567
2607
  hasMore: false
2568
2608
  },
2569
2609
  scores: []
2570
2610
  };
2571
2611
  }
2572
- const limit = pagination.perPage + 1;
2612
+ const limitValue = perPageInput === false ? total : perPage;
2613
+ const end = perPageInput === false ? total : start + perPage;
2573
2614
  const dataRequest = this.pool.request();
2574
2615
  dataRequest.input("p1", traceId);
2575
2616
  dataRequest.input("p2", spanId);
2576
- dataRequest.input("p3", limit);
2577
- dataRequest.input("p4", pagination.page * pagination.perPage);
2617
+ dataRequest.input("p3", limitValue);
2618
+ dataRequest.input("p4", start);
2578
2619
  const result = await dataRequest.query(
2579
2620
  `SELECT * FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [traceId] = @p1 AND [spanId] = @p2 ORDER BY [createdAt] DESC OFFSET @p4 ROWS FETCH NEXT @p3 ROWS ONLY`
2580
2621
  );
2581
2622
  return {
2582
2623
  pagination: {
2583
2624
  total: Number(total),
2584
- page: pagination.page,
2585
- perPage: pagination.perPage,
2586
- hasMore: result.recordset.length > pagination.perPage
2625
+ page,
2626
+ perPage: perPageForResponse,
2627
+ hasMore: end < total
2587
2628
  },
2588
- scores: result.recordset.slice(0, pagination.perPage).map((row) => transformScoreRow(row))
2629
+ scores: result.recordset.map((row) => transformScoreRow(row))
2589
2630
  };
2590
2631
  } catch (error) {
2591
2632
  throw new MastraError(
@@ -2884,12 +2925,12 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
2884
2925
  );
2885
2926
  }
2886
2927
  }
2887
- async getWorkflowRuns({
2928
+ async listWorkflowRuns({
2888
2929
  workflowName,
2889
2930
  fromDate,
2890
2931
  toDate,
2891
- limit,
2892
- offset,
2932
+ page,
2933
+ perPage,
2893
2934
  resourceId
2894
2935
  } = {}) {
2895
2936
  try {
@@ -2927,15 +2968,18 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
2927
2968
  request.input(key, value);
2928
2969
  }
2929
2970
  });
2930
- if (limit !== void 0 && offset !== void 0) {
2971
+ const usePagination = typeof perPage === "number" && typeof page === "number";
2972
+ if (usePagination) {
2931
2973
  const countQuery = `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`;
2932
2974
  const countResult = await request.query(countQuery);
2933
2975
  total = Number(countResult.recordset[0]?.count || 0);
2934
2976
  }
2935
2977
  let query = `SELECT * FROM ${tableName} ${whereClause} ORDER BY [seq_id] DESC`;
2936
- if (limit !== void 0 && offset !== void 0) {
2937
- query += ` OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
2938
- request.input("limit", limit);
2978
+ if (usePagination) {
2979
+ const normalizedPerPage = normalizePerPage(perPage, Number.MAX_SAFE_INTEGER);
2980
+ const offset = page * normalizedPerPage;
2981
+ query += ` OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
2982
+ request.input("perPage", normalizedPerPage);
2939
2983
  request.input("offset", offset);
2940
2984
  }
2941
2985
  const result = await request.query(query);
@@ -2944,7 +2988,7 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
2944
2988
  } catch (error) {
2945
2989
  throw new MastraError(
2946
2990
  {
2947
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUNS_FAILED",
2991
+ id: "MASTRA_STORAGE_MSSQL_STORE_LIST_WORKFLOW_RUNS_FAILED",
2948
2992
  domain: ErrorDomain.STORAGE,
2949
2993
  category: ErrorCategory.THIRD_PARTY,
2950
2994
  details: {
@@ -2955,9 +2999,6 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
2955
2999
  );
2956
3000
  }
2957
3001
  }
2958
- async listWorkflowRuns(args) {
2959
- return this.getWorkflowRuns(args);
2960
- }
2961
3002
  };
2962
3003
 
2963
3004
  // src/storage/index.ts
@@ -3052,7 +3093,7 @@ var MSSQLStore = class extends MastraStorage {
3052
3093
  hasColumn: true,
3053
3094
  createTable: true,
3054
3095
  deleteMessages: true,
3055
- getScoresBySpan: true,
3096
+ listScoresBySpan: true,
3056
3097
  aiTracing: true,
3057
3098
  indexManagement: true
3058
3099
  };
@@ -3091,15 +3132,6 @@ var MSSQLStore = class extends MastraStorage {
3091
3132
  async getThreadById({ threadId }) {
3092
3133
  return this.stores.memory.getThreadById({ threadId });
3093
3134
  }
3094
- /**
3095
- * @deprecated use getThreadsByResourceIdPaginated instead
3096
- */
3097
- async getThreadsByResourceId(args) {
3098
- return this.stores.memory.getThreadsByResourceId(args);
3099
- }
3100
- async getThreadsByResourceIdPaginated(args) {
3101
- return this.stores.memory.getThreadsByResourceIdPaginated(args);
3102
- }
3103
3135
  async saveThread({ thread }) {
3104
3136
  return this.stores.memory.saveThread({ thread });
3105
3137
  }
@@ -3113,17 +3145,14 @@ var MSSQLStore = class extends MastraStorage {
3113
3145
  async deleteThread({ threadId }) {
3114
3146
  return this.stores.memory.deleteThread({ threadId });
3115
3147
  }
3148
+ /**
3149
+ * @deprecated use listMessages instead
3150
+ */
3116
3151
  async getMessages(args) {
3117
3152
  return this.stores.memory.getMessages(args);
3118
3153
  }
3119
- async getMessagesById({
3120
- messageIds,
3121
- format
3122
- }) {
3123
- return this.stores.memory.getMessagesById({ messageIds, format });
3124
- }
3125
- async getMessagesPaginated(args) {
3126
- return this.stores.memory.getMessagesPaginated(args);
3154
+ async listMessagesById({ messageIds }) {
3155
+ return this.stores.memory.listMessagesById({ messageIds });
3127
3156
  }
3128
3157
  async saveMessages(args) {
3129
3158
  return this.stores.memory.saveMessages(args);
@@ -3182,15 +3211,15 @@ var MSSQLStore = class extends MastraStorage {
3182
3211
  }) {
3183
3212
  return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
3184
3213
  }
3185
- async getWorkflowRuns({
3214
+ async listWorkflowRuns({
3186
3215
  workflowName,
3187
3216
  fromDate,
3188
3217
  toDate,
3189
- limit,
3190
- offset,
3218
+ perPage,
3219
+ page,
3191
3220
  resourceId
3192
3221
  } = {}) {
3193
- return this.stores.workflows.getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId });
3222
+ return this.stores.workflows.listWorkflowRuns({ workflowName, fromDate, toDate, perPage, page, resourceId });
3194
3223
  }
3195
3224
  async getWorkflowRunById({
3196
3225
  runId,
@@ -3261,14 +3290,14 @@ var MSSQLStore = class extends MastraStorage {
3261
3290
  async getScoreById({ id: _id }) {
3262
3291
  return this.stores.scores.getScoreById({ id: _id });
3263
3292
  }
3264
- async getScoresByScorerId({
3293
+ async listScoresByScorerId({
3265
3294
  scorerId: _scorerId,
3266
3295
  pagination: _pagination,
3267
3296
  entityId: _entityId,
3268
3297
  entityType: _entityType,
3269
3298
  source: _source
3270
3299
  }) {
3271
- return this.stores.scores.getScoresByScorerId({
3300
+ return this.stores.scores.listScoresByScorerId({
3272
3301
  scorerId: _scorerId,
3273
3302
  pagination: _pagination,
3274
3303
  entityId: _entityId,
@@ -3279,29 +3308,29 @@ var MSSQLStore = class extends MastraStorage {
3279
3308
  async saveScore(_score) {
3280
3309
  return this.stores.scores.saveScore(_score);
3281
3310
  }
3282
- async getScoresByRunId({
3311
+ async listScoresByRunId({
3283
3312
  runId: _runId,
3284
3313
  pagination: _pagination
3285
3314
  }) {
3286
- return this.stores.scores.getScoresByRunId({ runId: _runId, pagination: _pagination });
3315
+ return this.stores.scores.listScoresByRunId({ runId: _runId, pagination: _pagination });
3287
3316
  }
3288
- async getScoresByEntityId({
3317
+ async listScoresByEntityId({
3289
3318
  entityId: _entityId,
3290
3319
  entityType: _entityType,
3291
3320
  pagination: _pagination
3292
3321
  }) {
3293
- return this.stores.scores.getScoresByEntityId({
3322
+ return this.stores.scores.listScoresByEntityId({
3294
3323
  entityId: _entityId,
3295
3324
  entityType: _entityType,
3296
3325
  pagination: _pagination
3297
3326
  });
3298
3327
  }
3299
- async getScoresBySpan({
3328
+ async listScoresBySpan({
3300
3329
  traceId,
3301
3330
  spanId,
3302
3331
  pagination: _pagination
3303
3332
  }) {
3304
- return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination: _pagination });
3333
+ return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination: _pagination });
3305
3334
  }
3306
3335
  };
3307
3336