@frontmcp/plugin-cache 1.8.6 → 1.9.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,13 @@
1
+ /**
2
+ * Error classes for the cache plugin.
3
+ *
4
+ * @module @frontmcp/plugin-cache
5
+ */
6
+ /**
7
+ * Raised when `CachePlugin` is configured with options it cannot honour, when the plugin is
8
+ * created (`CachePlugin.init()`), so the server never starts with a setting that silently does nothing.
9
+ */
10
+ export declare class CachePluginConfigurationError extends Error {
11
+ constructor(message: string);
12
+ }
13
+ //# sourceMappingURL=cache.errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache.errors.d.ts","sourceRoot":"","sources":["../src/cache.errors.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;;GAGG;AACH,qBAAa,6BAA8B,SAAQ,KAAK;gBAC1C,OAAO,EAAE,MAAM;CAI5B"}
@@ -1 +1 @@
1
- {"version":3,"file":"cache.plugin.d.ts","sourceRoot":"","sources":["../src/cache.plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,aAAa,EAOb,KAAK,SAAS,EAEd,KAAK,YAAY,EAClB,MAAM,eAAe,CAAC;AAIvB,OAAO,EAAE,KAAK,kBAAkB,EAAsC,MAAM,eAAe,CAAC;AA8C5F,MAAM,CAAC,OAAO,OAAO,WAAY,SAAQ,aAAa,CAAC,kBAAkB,CAAC;IACxE,OAAgB,gBAAgB,GAAI,SAAS,kBAAkB,oBAuD7D;IAEF,MAAM,CAAC,cAAc,EAAE,kBAAkB,CAEvC;IACF,OAAO,EAAE,kBAAkB,CAAC;gBAEhB,OAAO,GAAE,kBAA+C;IAQpE;;OAEG;IACH,OAAO,CAAC,eAAe;IAkBvB;;;OAGG;IACH,OAAO,CAAC,iBAAiB;IAsBzB;;OAEG;IACH,OAAO,CAAC,MAAM;IAQR,aAAa,CAAC,OAAO,EAAE,SAAS,CAAC,iBAAiB,CAAC;IA0DnD,cAAc,CAAC,OAAO,EAAE,SAAS,CAAC,iBAAiB,CAAC;IAyB1D;;;;;;;;;OASG;IACH,OAAO,CAAC,qBAAqB;IAyB7B;;;;;;OAMG;IACH,OAAO,CAAC,aAAa;IAQrB;;;OAGG;IACH,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO;CAGvC"}
1
+ {"version":3,"file":"cache.plugin.d.ts","sourceRoot":"","sources":["../src/cache.plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,aAAa,EAOb,KAAK,SAAS,EAEd,KAAK,YAAY,EAClB,MAAM,eAAe,CAAC;AAKvB,OAAO,EAAE,KAAK,kBAAkB,EAAsC,MAAM,eAAe,CAAC;AAkE5F,MAAM,CAAC,OAAO,OAAO,WAAY,SAAQ,aAAa,CAAC,kBAAkB,CAAC;IACxE,OAAgB,gBAAgB,GAAI,SAAS,kBAAkB,oBAuD7D;IAEF,MAAM,CAAC,cAAc,EAAE,kBAAkB,CAEvC;IACF,OAAO,EAAE,kBAAkB,CAAC;gBAEhB,OAAO,GAAE,kBAA+C;IASpE;;OAEG;IACH,OAAO,CAAC,eAAe;IAkBvB;;;OAGG;IACH,OAAO,CAAC,iBAAiB;IAsBzB;;OAEG;IACH,OAAO,CAAC,MAAM;IAQR,aAAa,CAAC,OAAO,EAAE,SAAS,CAAC,iBAAiB,CAAC;IA4DnD,cAAc,CAAC,OAAO,EAAE,SAAS,CAAC,iBAAiB,CAAC;IAgC1D;;;;;;;;;OASG;IACH,OAAO,CAAC,qBAAqB;IAyB7B;;;;;;OAMG;IACH,OAAO,CAAC,aAAa;IAQrB;;;OAGG;IACH,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO;CAGvC"}
package/cache.types.d.ts CHANGED
@@ -10,7 +10,9 @@ export interface CachePluginToolOptions {
10
10
  */
11
11
  ttl?: number;
12
12
  /**
13
- * If true, the cache value will be updated with the new value after the TTL.
13
+ * If true, every cache hit refreshes the entry's TTL (`ttl`, or the plugin's `defaultTTL`), so an
14
+ * entry that keeps being read stays cached. Without it an entry expires `ttl` seconds after it was
15
+ * written, however often it is read. `cache: true` does not slide.
14
16
  * Default is false.
15
17
  */
16
18
  slideWindow?: boolean;
@@ -35,8 +37,9 @@ export interface BaseCachePluginOptions {
35
37
  * HTTP header name that clients can send to bypass cache for a specific request.
36
38
  * When this header is present with a truthy value ('true' or '1'), cache read/write is skipped.
37
39
  *
38
- * Note: Headers must use the `x-frontmcp-*` prefix to be captured by the context storage.
39
- * Custom bypass headers should also follow this convention.
40
+ * Must start with `x-frontmcp-`: the plugin reads the header from the request context, which
41
+ * keeps only a request's `x-frontmcp-*` headers. Any other name throws
42
+ * `CachePluginConfigurationError` when the plugin is created.
40
43
  *
41
44
  * @default 'x-frontmcp-disable-cache'
42
45
  *
@@ -1 +1 @@
1
- {"version":3,"file":"cache.types.d.ts","sourceRoot":"","sources":["../src/cache.types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,IAAI,WAAW,EAAE,MAAM,SAAS,CAAC;AAE/C,OAAO,CAAC,MAAM,CAAC;IACb,UAAU,0BAA0B;QAClC,KAAK,CAAC,EAAE,sBAAsB,GAAG,IAAI,CAAC;KACvC;CACF;AAED,MAAM,WAAW,sBAAsB;IACrC;;OAEG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC;IAEb;;;OAGG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB;AAED,MAAM,WAAW,sBAAsB;IACrC;;OAEG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;;;;;;;;OASG;IACH,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IAExB;;;;;;;;;;;;;;;;;;;OAmBG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB;;;;;;;;;;;;OAYG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB;AAED,MAAM,WAAW,6BAA8B,SAAQ,sBAAsB;IAC3E,IAAI,EAAE,cAAc,CAAC;IACrB,MAAM,EAAE,WAAW,CAAC;CACrB;AAED,MAAM,WAAW,uBAAwB,SAAQ,sBAAsB;IACrE,IAAI,EAAE,OAAO,CAAC;IACd,MAAM,EAAE;QACN,IAAI,EAAE,MAAM,CAAC;QACb,IAAI,EAAE,MAAM,CAAC;QACb,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,EAAE,CAAC,EAAE,MAAM,CAAC;KACb,CAAC;CACH;AAED,MAAM,MAAM,wBAAwB,GAAG,sBAAsB,GAAG;IAC9D,IAAI,EAAE,QAAQ,CAAC;CAChB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,WAAW,6BAA8B,SAAQ,sBAAsB;IAC3E,IAAI,EAAE,cAAc,CAAC;CACtB;AAED,MAAM,MAAM,iBAAiB,GAAG,6BAA6B,GAAG,uBAAuB,CAAC;AAExF,MAAM,MAAM,kBAAkB,GAAG,wBAAwB,GAAG,iBAAiB,GAAG,6BAA6B,CAAC;AAE9G,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAE1E,QAAQ,CAAC,CAAC,GAAG,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC,CAAC;IAE7E,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAEnC,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAEtC,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB"}
1
+ {"version":3,"file":"cache.types.d.ts","sourceRoot":"","sources":["../src/cache.types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,IAAI,WAAW,EAAE,MAAM,SAAS,CAAC;AAE/C,OAAO,CAAC,MAAM,CAAC;IACb,UAAU,0BAA0B;QAClC,KAAK,CAAC,EAAE,sBAAsB,GAAG,IAAI,CAAC;KACvC;CACF;AAED,MAAM,WAAW,sBAAsB;IACrC;;OAEG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC;IAEb;;;;;OAKG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB;AAED,MAAM,WAAW,sBAAsB;IACrC;;OAEG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;;;;;;;;OASG;IACH,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IAExB;;;;;;;;;;;;;;;;;;;;OAoBG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB;;;;;;;;;;;;OAYG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB;AAED,MAAM,WAAW,6BAA8B,SAAQ,sBAAsB;IAC3E,IAAI,EAAE,cAAc,CAAC;IACrB,MAAM,EAAE,WAAW,CAAC;CACrB;AAED,MAAM,WAAW,uBAAwB,SAAQ,sBAAsB;IACrE,IAAI,EAAE,OAAO,CAAC;IACd,MAAM,EAAE;QACN,IAAI,EAAE,MAAM,CAAC;QACb,IAAI,EAAE,MAAM,CAAC;QACb,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,EAAE,CAAC,EAAE,MAAM,CAAC;KACb,CAAC;CACH;AAED,MAAM,MAAM,wBAAwB,GAAG,sBAAsB,GAAG;IAC9D,IAAI,EAAE,QAAQ,CAAC;CAChB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,WAAW,6BAA8B,SAAQ,sBAAsB;IAC3E,IAAI,EAAE,cAAc,CAAC;CACtB;AAED,MAAM,MAAM,iBAAiB,GAAG,6BAA6B,GAAG,uBAAuB,CAAC;AAExF,MAAM,MAAM,kBAAkB,GAAG,wBAAwB,GAAG,iBAAiB,GAAG,6BAA6B,CAAC;AAE9G,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAE1E,QAAQ,CAAC,CAAC,GAAG,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC,CAAC;IAE7E,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAEnC,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAEtC,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB"}
package/esm/index.mjs CHANGED
@@ -1,3 +1,6 @@
1
+ var __frontmcpModule = typeof process !== "undefined" && typeof process.getBuiltinModule === "function" ? process.getBuiltinModule("module") : undefined;
2
+ const require = __frontmcpModule ? __frontmcpModule.createRequire(import.meta.url || 'file:///') : undefined;
3
+ // __frontmcpCreateRequire
1
4
  var __create = Object.create;
2
5
  var __defProp = Object.defineProperty;
3
6
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -296,7 +299,6 @@ import {
296
299
  } from "@frontmcp/sdk";
297
300
 
298
301
  // libs/utils/dist/esm/index.mjs
299
- import { createRequire as __frontmcpCreateRequire } from "module";
300
302
  import { z } from "@frontmcp/lazy-zod";
301
303
  var import_event_emitter = __toESM(require_node_event_emitter(), 1);
302
304
  import { z as z2 } from "@frontmcp/lazy-zod";
@@ -308,8 +310,8 @@ import { hkdf } from "@noble/hashes/hkdf.js";
308
310
  import { randomBytes as nobleRandomBytes } from "@noble/hashes/utils.js";
309
311
  import { gcm } from "@noble/ciphers/aes.js";
310
312
  import { analyzeForReDoS, REDOS_THRESHOLDS } from "@enclave-vm/ast";
311
- import { z as z3 } from "@frontmcp/lazy-zod";
312
- var require2 = __frontmcpCreateRequire(import.meta.url || "file:///");
313
+ var __frontmcpModule = typeof process !== "undefined" && typeof process.getBuiltinModule === "function" ? process.getBuiltinModule("module") : void 0;
314
+ var require2 = __frontmcpModule ? __frontmcpModule.createRequire(import.meta.url || "file:///") : void 0;
313
315
  var __defProp2 = Object.defineProperty;
314
316
  var __getOwnPropNames2 = Object.getOwnPropertyNames;
315
317
  var __require2 = /* @__PURE__ */ ((x) => typeof require2 !== "undefined" ? require2 : typeof Proxy !== "undefined" ? new Proxy(x, {
@@ -645,8 +647,8 @@ var init_key_persistence = __esm({
645
647
  */
646
648
  async get(kid) {
647
649
  if (this.enableCache) {
648
- const cached4 = this.cache.get(kid);
649
- if (cached4) return cached4;
650
+ const cached = this.cache.get(kid);
651
+ if (cached) return cached;
650
652
  }
651
653
  const raw = await this.storage.get(kid);
652
654
  if (!raw) return null;
@@ -902,6 +904,61 @@ var init_errors = __esm({
902
904
  };
903
905
  }
904
906
  });
907
+ function globToRegex(pattern) {
908
+ if (pattern.length > MAX_PATTERN_LENGTH) {
909
+ throw new StoragePatternError(
910
+ pattern.substring(0, 50) + "...",
911
+ `Pattern exceeds maximum length of ${MAX_PATTERN_LENGTH} characters`
912
+ );
913
+ }
914
+ const wildcardCount = (pattern.match(/[*?]/g) || []).length;
915
+ if (wildcardCount > MAX_WILDCARDS) {
916
+ throw new StoragePatternError(pattern, `Pattern has too many wildcards (max: ${MAX_WILDCARDS})`);
917
+ }
918
+ if (pattern === "" || pattern === "*") {
919
+ return /^.*$/;
920
+ }
921
+ let regexStr = "^";
922
+ let prevChar = "";
923
+ for (let i = 0; i < pattern.length; i++) {
924
+ const char = pattern[i];
925
+ switch (char) {
926
+ case "*":
927
+ if (prevChar !== "*") {
928
+ regexStr += ".*";
929
+ }
930
+ break;
931
+ case "?":
932
+ regexStr += ".";
933
+ break;
934
+ default:
935
+ regexStr += char.replace(REGEX_SPECIAL_CHARS, "\\$&");
936
+ }
937
+ prevChar = char;
938
+ }
939
+ regexStr += "$";
940
+ try {
941
+ return new RegExp(regexStr);
942
+ } catch {
943
+ throw new StoragePatternError(pattern, "Failed to compile pattern to regex");
944
+ }
945
+ }
946
+ function matchesPattern(key, pattern) {
947
+ const regex = globToRegex(pattern);
948
+ return regex.test(key);
949
+ }
950
+ var MAX_PATTERN_LENGTH;
951
+ var MAX_WILDCARDS;
952
+ var REGEX_SPECIAL_CHARS;
953
+ var init_pattern = __esm({
954
+ "libs/utils/src/storage/utils/pattern.ts"() {
955
+ "use strict";
956
+ init_errors();
957
+ MAX_PATTERN_LENGTH = 500;
958
+ MAX_WILDCARDS = 20;
959
+ REGEX_SPECIAL_CHARS = /[.+^${}()|[\]\\]/g;
960
+ }
961
+ });
905
962
  function validateTTL(ttlSeconds) {
906
963
  if (typeof ttlSeconds !== "number") {
907
964
  throw new StorageTTLError(ttlSeconds, `TTL must be a number, got ${typeof ttlSeconds}`);
@@ -1010,6 +1067,17 @@ var init_base = __esm({
1010
1067
  const matchedKeys = await this.keys(pattern);
1011
1068
  return matchedKeys.length;
1012
1069
  }
1070
+ /**
1071
+ * Default: not supported, since a read followed by a delete is not atomic.
1072
+ * Override in adapters whose backend can compare and delete in one step.
1073
+ */
1074
+ async deleteIfEquals(_key, _expectedValue) {
1075
+ throw new StorageNotSupportedError(
1076
+ "deleteIfEquals",
1077
+ this.backendName,
1078
+ "Use the memory, Redis, Upstash or Vercel KV adapter for an atomic compare-and-delete."
1079
+ );
1080
+ }
1013
1081
  // ============================================
1014
1082
  // Pub/Sub (default: not supported)
1015
1083
  // ============================================
@@ -1057,71 +1125,16 @@ var init_base = __esm({
1057
1125
  };
1058
1126
  }
1059
1127
  });
1060
- function globToRegex(pattern) {
1061
- if (pattern.length > MAX_PATTERN_LENGTH) {
1062
- throw new StoragePatternError(
1063
- pattern.substring(0, 50) + "...",
1064
- `Pattern exceeds maximum length of ${MAX_PATTERN_LENGTH} characters`
1065
- );
1066
- }
1067
- const wildcardCount = (pattern.match(/[*?]/g) || []).length;
1068
- if (wildcardCount > MAX_WILDCARDS) {
1069
- throw new StoragePatternError(pattern, `Pattern has too many wildcards (max: ${MAX_WILDCARDS})`);
1070
- }
1071
- if (pattern === "" || pattern === "*") {
1072
- return /^.*$/;
1073
- }
1074
- let regexStr = "^";
1075
- let prevChar = "";
1076
- for (let i = 0; i < pattern.length; i++) {
1077
- const char = pattern[i];
1078
- switch (char) {
1079
- case "*":
1080
- if (prevChar !== "*") {
1081
- regexStr += ".*";
1082
- }
1083
- break;
1084
- case "?":
1085
- regexStr += ".";
1086
- break;
1087
- default:
1088
- regexStr += char.replace(REGEX_SPECIAL_CHARS, "\\$&");
1089
- }
1090
- prevChar = char;
1091
- }
1092
- regexStr += "$";
1093
- try {
1094
- return new RegExp(regexStr);
1095
- } catch {
1096
- throw new StoragePatternError(pattern, "Failed to compile pattern to regex");
1097
- }
1098
- }
1099
- function matchesPattern(key, pattern) {
1100
- const regex = globToRegex(pattern);
1101
- return regex.test(key);
1102
- }
1103
- var MAX_PATTERN_LENGTH;
1104
- var MAX_WILDCARDS;
1105
- var REGEX_SPECIAL_CHARS;
1106
- var init_pattern = __esm({
1107
- "libs/utils/src/storage/utils/pattern.ts"() {
1108
- "use strict";
1109
- init_errors();
1110
- MAX_PATTERN_LENGTH = 500;
1111
- MAX_WILDCARDS = 20;
1112
- REGEX_SPECIAL_CHARS = /[.+^${}()|[\]\\]/g;
1113
- }
1114
- });
1115
1128
  var DEFAULT_SWEEP_INTERVAL_SECONDS;
1116
1129
  var MAX_TIMEOUT_MS;
1117
1130
  var MemoryStorageAdapter;
1118
1131
  var init_memory = __esm({
1119
1132
  "libs/utils/src/storage/adapters/memory.ts"() {
1120
1133
  "use strict";
1121
- init_base();
1122
1134
  init_errors();
1123
1135
  init_pattern();
1124
1136
  init_ttl();
1137
+ init_base();
1125
1138
  DEFAULT_SWEEP_INTERVAL_SECONDS = 60;
1126
1139
  MAX_TIMEOUT_MS = 2147483647;
1127
1140
  MemoryStorageAdapter = class extends BaseStorageAdapter {
@@ -1213,6 +1226,12 @@ var init_memory = __esm({
1213
1226
  this.ensureConnected();
1214
1227
  return this.deleteEntry(key);
1215
1228
  }
1229
+ async deleteIfEquals(key, expectedValue) {
1230
+ this.ensureConnected();
1231
+ const entry = this.store.get(key);
1232
+ if (!entry || isExpired(entry.expiresAt) || entry.value !== expectedValue) return false;
1233
+ return this.deleteEntry(key);
1234
+ }
1216
1235
  async exists(key) {
1217
1236
  this.ensureConnected();
1218
1237
  const entry = this.store.get(key);
@@ -2545,15 +2564,56 @@ var init_crypto = __esm({
2545
2564
  HKDF_SHA256_MAX_LENGTH = 255 * 32;
2546
2565
  }
2547
2566
  });
2567
+ function attachRedisErrorListener(client, options = {}) {
2568
+ const label = options.label ?? "redis";
2569
+ const intervalMs = options.intervalMs ?? DEFAULT_REDIS_ERROR_LOG_INTERVAL_MS;
2570
+ let lastLoggedAt = 0;
2571
+ let suppressed = 0;
2572
+ const listener = (error) => {
2573
+ const now = Date.now();
2574
+ if (lastLoggedAt !== 0 && now - lastLoggedAt < intervalMs) {
2575
+ suppressed++;
2576
+ return;
2577
+ }
2578
+ const extra = suppressed > 0 ? ` (${suppressed} similar error(s) suppressed)` : "";
2579
+ suppressed = 0;
2580
+ lastLoggedAt = now;
2581
+ const message = `[${label}] Redis connection error: ${error?.message ?? String(error)}${extra}`;
2582
+ if (options.logger) {
2583
+ options.logger.warn(message);
2584
+ } else {
2585
+ console.warn(message);
2586
+ }
2587
+ };
2588
+ client.on("error", listener);
2589
+ return () => {
2590
+ client.removeListener("error", listener);
2591
+ };
2592
+ }
2593
+ var DEFAULT_REDIS_ERROR_LOG_INTERVAL_MS;
2594
+ var init_redis_error_listener = __esm({
2595
+ "libs/utils/src/storage/redis-error-listener.ts"() {
2596
+ "use strict";
2597
+ DEFAULT_REDIS_ERROR_LOG_INTERVAL_MS = 3e4;
2598
+ }
2599
+ });
2548
2600
  var init_utils = __esm({
2549
2601
  "libs/utils/src/storage/utils/index.ts"() {
2550
2602
  "use strict";
2551
2603
  init_ttl();
2552
2604
  }
2553
2605
  });
2606
+ var COMPARE_AND_DELETE_SCRIPT;
2607
+ var init_compare_and_delete = __esm({
2608
+ "libs/utils/src/storage/utils/compare-and-delete.ts"() {
2609
+ "use strict";
2610
+ COMPARE_AND_DELETE_SCRIPT = `if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end return 0`;
2611
+ }
2612
+ });
2554
2613
  var redis_exports = {};
2555
2614
  __export(redis_exports, {
2556
- RedisStorageAdapter: () => RedisStorageAdapter
2615
+ RedisStorageAdapter: () => RedisStorageAdapter,
2616
+ createRedisClient: () => createRedisClient
2557
2617
  });
2558
2618
  function getRedisClass() {
2559
2619
  try {
@@ -2571,12 +2631,28 @@ function getRedisClass() {
2571
2631
  });
2572
2632
  }
2573
2633
  }
2634
+ function createRedisClient(options) {
2635
+ const RedisClass = getRedisClass();
2636
+ const baseOptions = { lazyConnect: false, maxRetriesPerRequest: 3 };
2637
+ const client = options.url ? new RedisClass(options.url, baseOptions) : new RedisClass({
2638
+ ...baseOptions,
2639
+ host: options.host ?? "localhost",
2640
+ port: options.port ?? 6379,
2641
+ password: options.password,
2642
+ db: options.db ?? 0,
2643
+ tls: options.tls ? {} : void 0
2644
+ });
2645
+ attachRedisErrorListener(client, { label: options.label ?? "redis", logger: options.logger });
2646
+ return client;
2647
+ }
2574
2648
  var RedisStorageAdapter;
2575
2649
  var init_redis = __esm({
2576
2650
  "libs/utils/src/storage/adapters/redis.ts"() {
2577
2651
  "use strict";
2578
2652
  init_errors();
2653
+ init_redis_error_listener();
2579
2654
  init_utils();
2655
+ init_compare_and_delete();
2580
2656
  init_base();
2581
2657
  RedisStorageAdapter = class extends BaseStorageAdapter {
2582
2658
  backendName = "redis";
@@ -2584,6 +2660,7 @@ var init_redis = __esm({
2584
2660
  subscriber;
2585
2661
  options;
2586
2662
  ownsClient;
2663
+ detachErrorListener;
2587
2664
  connecting;
2588
2665
  keyPrefix;
2589
2666
  subscriptionHandlers = /* @__PURE__ */ new Map();
@@ -2640,7 +2717,10 @@ var init_redis = __esm({
2640
2717
  await client.ping();
2641
2718
  this.client = client;
2642
2719
  this.connected = true;
2643
- if (this.ownsClient) client.removeListener("error", recordSocketError);
2720
+ if (this.ownsClient) {
2721
+ client.removeListener("error", recordSocketError);
2722
+ this.detachErrorListener = attachRedisErrorListener(client, { label: "RedisStorage" });
2723
+ }
2644
2724
  } catch (e) {
2645
2725
  if (this.ownsClient && client) {
2646
2726
  try {
@@ -2661,6 +2741,8 @@ var init_redis = __esm({
2661
2741
  if (this.ownsClient && this.client) {
2662
2742
  await this.client.quit();
2663
2743
  }
2744
+ this.detachErrorListener?.();
2745
+ this.detachErrorListener = void 0;
2664
2746
  this.client = void 0;
2665
2747
  this.connected = false;
2666
2748
  this.subscriptionHandlers.clear();
@@ -2725,6 +2807,15 @@ var init_redis = __esm({
2725
2807
  const result = await this.getConnectedClient().del(this.prefixKey(key));
2726
2808
  return result > 0;
2727
2809
  }
2810
+ async deleteIfEquals(key, expectedValue) {
2811
+ const deleted = await this.getConnectedClient().eval(
2812
+ COMPARE_AND_DELETE_SCRIPT,
2813
+ 1,
2814
+ this.prefixKey(key),
2815
+ expectedValue
2816
+ );
2817
+ return deleted === 1;
2818
+ }
2728
2819
  async exists(key) {
2729
2820
  const result = await this.getConnectedClient().exists(this.prefixKey(key));
2730
2821
  return result > 0;
@@ -2888,6 +2979,7 @@ var init_redis = __esm({
2888
2979
  } else {
2889
2980
  throw new StorageConfigError("redis", "Cannot create subscriber without url, config, or client");
2890
2981
  }
2982
+ attachRedisErrorListener(subscriber, { label: "RedisStorage:subscriber" });
2891
2983
  subscriber.on("message", (channel, message) => {
2892
2984
  const handlers = this.subscriptionHandlers.get(channel);
2893
2985
  if (handlers) {
@@ -2930,9 +3022,12 @@ var vercel_kv_exports = {};
2930
3022
  __export(vercel_kv_exports, {
2931
3023
  VercelKvStorageAdapter: () => VercelKvStorageAdapter
2932
3024
  });
2933
- function getVercelKv() {
3025
+ async function loadVercelKv() {
2934
3026
  try {
2935
- return __require2("@vercel/kv");
3027
+ const mod = await import("@vercel/kv");
3028
+ const resolved = typeof mod.createClient === "function" ? mod : mod.default;
3029
+ if (!resolved || typeof resolved.createClient !== "function") throw new Error("createClient missing");
3030
+ return resolved;
2936
3031
  } catch {
2937
3032
  throw new Error("@vercel/kv is required for Vercel KV storage adapter. Install it with: npm install @vercel/kv");
2938
3033
  }
@@ -2941,9 +3036,10 @@ var VercelKvStorageAdapter;
2941
3036
  var init_vercel_kv = __esm({
2942
3037
  "libs/utils/src/storage/adapters/vercel-kv.ts"() {
2943
3038
  "use strict";
2944
- init_base();
2945
3039
  init_errors();
3040
+ init_compare_and_delete();
2946
3041
  init_ttl();
3042
+ init_base();
2947
3043
  VercelKvStorageAdapter = class extends BaseStorageAdapter {
2948
3044
  backendName = "vercel-kv";
2949
3045
  client;
@@ -2968,17 +3064,13 @@ var init_vercel_kv = __esm({
2968
3064
  async connect() {
2969
3065
  if (this.connected) return;
2970
3066
  try {
2971
- const { createClient, kv } = getVercelKv();
2972
- if (this.options.url === process.env["KV_REST_API_URL"]) {
2973
- this.client = kv;
2974
- } else {
2975
- const url = this.options.url;
2976
- const token = this.options.token;
2977
- if (!url || !token) {
2978
- throw new StorageConfigError("vercel-kv", "URL and token are required");
2979
- }
2980
- this.client = createClient({ url, token });
3067
+ const { createClient } = await loadVercelKv();
3068
+ const url = this.options.url;
3069
+ const token = this.options.token;
3070
+ if (!url || !token) {
3071
+ throw new StorageConfigError("vercel-kv", "URL and token are required");
2981
3072
  }
3073
+ this.client = createClient({ url, token, cache: void 0 });
2982
3074
  await this.client.exists("__healthcheck__");
2983
3075
  this.connected = true;
2984
3076
  } catch (e) {
@@ -3040,6 +3132,14 @@ var init_vercel_kv = __esm({
3040
3132
  const result = await this.getConnectedClient().del(this.prefixKey(key));
3041
3133
  return result > 0;
3042
3134
  }
3135
+ async deleteIfEquals(key, expectedValue) {
3136
+ const deleted = await this.getConnectedClient().eval(
3137
+ COMPARE_AND_DELETE_SCRIPT,
3138
+ [this.prefixKey(key)],
3139
+ [expectedValue]
3140
+ );
3141
+ return deleted === 1;
3142
+ }
3043
3143
  async exists(key) {
3044
3144
  const result = await this.getConnectedClient().exists(this.prefixKey(key));
3045
3145
  return result > 0;
@@ -3156,9 +3256,10 @@ var UpstashStorageAdapter;
3156
3256
  var init_upstash = __esm({
3157
3257
  "libs/utils/src/storage/adapters/upstash.ts"() {
3158
3258
  "use strict";
3159
- init_base();
3160
3259
  init_errors();
3260
+ init_compare_and_delete();
3161
3261
  init_ttl();
3262
+ init_base();
3162
3263
  PUBSUB_POLL_INTERVAL_MS = 100;
3163
3264
  UpstashStorageAdapter = class extends BaseStorageAdapter {
3164
3265
  backendName = "upstash";
@@ -3263,6 +3364,14 @@ var init_upstash = __esm({
3263
3364
  const result = await this.getConnectedClient().del(this.prefixKey(key));
3264
3365
  return result > 0;
3265
3366
  }
3367
+ async deleteIfEquals(key, expectedValue) {
3368
+ const deleted = await this.getConnectedClient().eval(
3369
+ COMPARE_AND_DELETE_SCRIPT,
3370
+ [this.prefixKey(key)],
3371
+ [expectedValue]
3372
+ );
3373
+ return deleted === 1;
3374
+ }
3266
3375
  async exists(key) {
3267
3376
  const result = await this.getConnectedClient().exists(this.prefixKey(key));
3268
3377
  return result > 0;
@@ -3451,7 +3560,9 @@ var init_cloudflare_kv = __esm({
3451
3560
  constructor(options) {
3452
3561
  super();
3453
3562
  if (!options?.namespace) {
3454
- throw new Error("CloudflareKvStorageAdapter: a bound KV `namespace` is required (resolve it from the Worker `env`).");
3563
+ throw new Error(
3564
+ "CloudflareKvStorageAdapter: a bound KV `namespace` is required (resolve it from the Worker `env`)."
3565
+ );
3455
3566
  }
3456
3567
  this.kv = options.namespace;
3457
3568
  this.keyPrefix = options.keyPrefix ?? "";
@@ -3545,6 +3656,13 @@ var init_cloudflare_kv = __esm({
3545
3656
  "Cloudflare KV has no atomic increment (a get+put is racy under eventual consistency). Use a Durable Object for atomic counters."
3546
3657
  );
3547
3658
  }
3659
+ async deleteIfEquals(_key, _expectedValue) {
3660
+ throw new StorageNotSupportedError(
3661
+ "deleteIfEquals",
3662
+ this.backendName,
3663
+ "Cloudflare KV has no compare-and-set; use a Durable Object for an atomic compare-and-delete."
3664
+ );
3665
+ }
3548
3666
  // ── Pub/Sub (unsupported) ────────────────────────────────────────────────
3549
3667
  getPubSubSuggestion() {
3550
3668
  return "Cloudflare KV does not support pub/sub. Use a Durable Object (or Queues) for fan-out.";
@@ -3658,18 +3776,10 @@ function compileBlocks(entries, parseNetwork) {
3658
3776
  }
3659
3777
  init_fs2();
3660
3778
  init_crypto();
3661
- var entryAvailabilitySchema = z3.object({
3662
- os: z3.array(z3.string().min(1)).optional(),
3663
- platform: z3.array(z3.string().min(1)).optional(),
3664
- runtime: z3.array(z3.string().min(1)).optional(),
3665
- deployment: z3.array(z3.string().min(1)).optional(),
3666
- provider: z3.array(z3.string().min(1)).optional(),
3667
- target: z3.array(z3.string().min(1)).optional(),
3668
- surface: z3.array(z3.enum(["mcp", "cli", "http-trigger", "job", "agent"])).optional(),
3669
- env: z3.array(z3.string().min(1)).optional()
3670
- }).strict();
3779
+ init_errors();
3671
3780
  init_errors();
3672
3781
  init_memory();
3782
+ init_redis_error_listener();
3673
3783
  init_errors();
3674
3784
  init_crypto();
3675
3785
  init_errors();
@@ -3686,6 +3796,14 @@ init_ttl();
3686
3796
  init_crypto();
3687
3797
  init_runtime();
3688
3798
 
3799
+ // plugins/plugin-cache/src/cache.errors.ts
3800
+ var CachePluginConfigurationError = class extends Error {
3801
+ constructor(message) {
3802
+ super(message);
3803
+ this.name = "CachePluginConfigurationError";
3804
+ }
3805
+ };
3806
+
3689
3807
  // plugins/plugin-cache/src/cache.symbol.ts
3690
3808
  var CacheStoreToken = /* @__PURE__ */ Symbol("plugin:cache:store");
3691
3809
 
@@ -3917,6 +4035,15 @@ CacheVercelKvProvider = __decorateClass([
3917
4035
 
3918
4036
  // plugins/plugin-cache/src/cache.plugin.ts
3919
4037
  var DEFAULT_BYPASS_HEADER = "x-frontmcp-disable-cache";
4038
+ var BYPASS_HEADER_PREFIX = "x-frontmcp-";
4039
+ function assertReadableBypassHeader(bypassHeader) {
4040
+ if (bypassHeader === void 0) return;
4041
+ const name = bypassHeader.toLowerCase();
4042
+ if (name.startsWith(BYPASS_HEADER_PREFIX) && name.length > BYPASS_HEADER_PREFIX.length) return;
4043
+ throw new CachePluginConfigurationError(
4044
+ `CachePlugin bypassHeader "${bypassHeader}" is never seen by the plugin: only request headers that start with "${BYPASS_HEADER_PREFIX}" reach it. Rename it, e.g. "${BYPASS_HEADER_PREFIX}no-cache".`
4045
+ );
4046
+ }
3920
4047
  function matchesToolPattern(toolName, patterns) {
3921
4048
  if (!patterns || patterns.length === 0) return false;
3922
4049
  return patterns.some((pattern) => {
@@ -3932,6 +4059,7 @@ var CachePlugin = class extends DynamicPlugin {
3932
4059
  options;
3933
4060
  constructor(options = CachePlugin.defaultOptions) {
3934
4061
  super();
4062
+ assertReadableBypassHeader(options.bypassHeader);
3935
4063
  this.options = {
3936
4064
  defaultTTL: 60 * 60 * 24,
3937
4065
  ...options
@@ -3989,15 +4117,13 @@ var CachePlugin = class extends DynamicPlugin {
3989
4117
  const hash = this.buildCacheKey(tool.fullName, toolContext);
3990
4118
  const cached = await cacheStore.getValue(hash);
3991
4119
  if (cached !== void 0 && cached !== null) {
3992
- const cacheConfig = typeof cache === "object" ? cache : void 0;
3993
- if (cache === true || cacheConfig?.ttl && cacheConfig?.slideWindow) {
3994
- const ttl = this.getTtl(cache);
3995
- await cacheStore.setValue(hash, cached, ttl);
3996
- }
3997
- if (!tool.safeParseOutput(cached).success) {
4120
+ if (isErrorResult(cached) || !tool.safeParseOutput(cached).success) {
3998
4121
  await cacheStore.delete(hash);
3999
4122
  return;
4000
4123
  }
4124
+ if (typeof cache === "object" && cache.slideWindow) {
4125
+ await cacheStore.setValue(hash, cached, this.getTtl(cache));
4126
+ }
4001
4127
  flowCtx.state.set("resultMeta", { ...flowCtx.state.resultMeta, cache: "hit" });
4002
4128
  flowCtx.state.set("rawOutput", cached);
4003
4129
  toolContext.respond(cached);
@@ -4014,6 +4140,9 @@ var CachePlugin = class extends DynamicPlugin {
4014
4140
  if (!shouldCache || typeof toolContext.input === "undefined") {
4015
4141
  return;
4016
4142
  }
4143
+ if (isErrorResult(toolContext.output)) {
4144
+ return;
4145
+ }
4017
4146
  const cacheStore = this.get(CacheStoreToken);
4018
4147
  const ttl = this.getTtl(cache);
4019
4148
  const hash = this.buildCacheKey(tool.fullName, toolContext);
@@ -4138,6 +4267,11 @@ CachePlugin = __decorateClass([
4138
4267
  ]
4139
4268
  })
4140
4269
  ], CachePlugin);
4270
+ function isErrorResult(output) {
4271
+ if (typeof output !== "object" || output === null) return false;
4272
+ const result = output;
4273
+ return result.isError === true && Array.isArray(result.content);
4274
+ }
4141
4275
  function stableValue(value) {
4142
4276
  if (Array.isArray(value)) {
4143
4277
  return value.map(stableValue);
@@ -4153,5 +4287,6 @@ function stableValue(value) {
4153
4287
  }
4154
4288
  export {
4155
4289
  CachePlugin,
4290
+ CachePluginConfigurationError,
4156
4291
  CachePlugin as default
4157
4292
  };
package/esm/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@frontmcp/plugin-cache",
3
- "version": "1.8.6",
3
+ "version": "1.9.0",
4
4
  "description": "Cache plugin for FrontMCP - Redis, Vercel KV, and in-memory caching with automatic tool result caching",
5
5
  "author": "AgentFront <info@agentfront.dev>",
6
6
  "license": "Apache-2.0",
@@ -48,8 +48,8 @@
48
48
  }
49
49
  },
50
50
  "dependencies": {
51
- "@frontmcp/sdk": "1.8.6",
52
- "@frontmcp/utils": "1.8.6",
51
+ "@frontmcp/sdk": "1.9.0",
52
+ "@frontmcp/utils": "1.9.0",
53
53
  "ioredis": "^5.8.0"
54
54
  },
55
55
  "peerDependencies": {
package/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export { default, default as CachePlugin } from './cache.plugin';
2
2
  export * from './cache.types';
3
+ export { CachePluginConfigurationError } from './cache.errors';
3
4
  //# sourceMappingURL=index.d.ts.map
package/index.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,gBAAgB,CAAC;AACjE,cAAc,eAAe,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,gBAAgB,CAAC;AACjE,cAAc,eAAe,CAAC;AAC9B,OAAO,EAAE,6BAA6B,EAAE,MAAM,gBAAgB,CAAC"}
package/index.js CHANGED
@@ -288,6 +288,7 @@ var require_node = __commonJS({
288
288
  var index_exports = {};
289
289
  __export(index_exports, {
290
290
  CachePlugin: () => CachePlugin,
291
+ CachePluginConfigurationError: () => CachePluginConfigurationError,
291
292
  default: () => CachePlugin
292
293
  });
293
294
  module.exports = __toCommonJS(index_exports);
@@ -296,7 +297,6 @@ module.exports = __toCommonJS(index_exports);
296
297
  var import_sdk4 = require("@frontmcp/sdk");
297
298
 
298
299
  // libs/utils/dist/esm/index.mjs
299
- var import_module = require("module");
300
300
  var import_lazy_zod = require("@frontmcp/lazy-zod");
301
301
  var import_lazy_zod2 = require("@frontmcp/lazy-zod");
302
302
  var import_event_emitter = __toESM(require_node_event_emitter(), 1);
@@ -308,9 +308,9 @@ var import_utils = require("@noble/hashes/utils.js");
308
308
  var import_aes = require("@noble/ciphers/aes.js");
309
309
  var import_crypto_provider = __toESM(require_node(), 1);
310
310
  var import_ast = require("@enclave-vm/ast");
311
- var import_lazy_zod3 = require("@frontmcp/lazy-zod");
312
311
  var import_meta = {};
313
- var require2 = (0, import_module.createRequire)(import_meta.url || "file:///");
312
+ var __frontmcpModule = typeof process !== "undefined" && typeof process.getBuiltinModule === "function" ? process.getBuiltinModule("module") : void 0;
313
+ var require2 = __frontmcpModule ? __frontmcpModule.createRequire(import_meta.url || "file:///") : void 0;
314
314
  var __defProp2 = Object.defineProperty;
315
315
  var __getOwnPropNames2 = Object.getOwnPropertyNames;
316
316
  var __require = /* @__PURE__ */ ((x) => typeof require2 !== "undefined" ? require2 : typeof Proxy !== "undefined" ? new Proxy(x, {
@@ -646,8 +646,8 @@ var init_key_persistence = __esm({
646
646
  */
647
647
  async get(kid) {
648
648
  if (this.enableCache) {
649
- const cached4 = this.cache.get(kid);
650
- if (cached4) return cached4;
649
+ const cached = this.cache.get(kid);
650
+ if (cached) return cached;
651
651
  }
652
652
  const raw = await this.storage.get(kid);
653
653
  if (!raw) return null;
@@ -903,6 +903,61 @@ var init_errors = __esm({
903
903
  };
904
904
  }
905
905
  });
906
+ function globToRegex(pattern) {
907
+ if (pattern.length > MAX_PATTERN_LENGTH) {
908
+ throw new StoragePatternError(
909
+ pattern.substring(0, 50) + "...",
910
+ `Pattern exceeds maximum length of ${MAX_PATTERN_LENGTH} characters`
911
+ );
912
+ }
913
+ const wildcardCount = (pattern.match(/[*?]/g) || []).length;
914
+ if (wildcardCount > MAX_WILDCARDS) {
915
+ throw new StoragePatternError(pattern, `Pattern has too many wildcards (max: ${MAX_WILDCARDS})`);
916
+ }
917
+ if (pattern === "" || pattern === "*") {
918
+ return /^.*$/;
919
+ }
920
+ let regexStr = "^";
921
+ let prevChar = "";
922
+ for (let i = 0; i < pattern.length; i++) {
923
+ const char = pattern[i];
924
+ switch (char) {
925
+ case "*":
926
+ if (prevChar !== "*") {
927
+ regexStr += ".*";
928
+ }
929
+ break;
930
+ case "?":
931
+ regexStr += ".";
932
+ break;
933
+ default:
934
+ regexStr += char.replace(REGEX_SPECIAL_CHARS, "\\$&");
935
+ }
936
+ prevChar = char;
937
+ }
938
+ regexStr += "$";
939
+ try {
940
+ return new RegExp(regexStr);
941
+ } catch {
942
+ throw new StoragePatternError(pattern, "Failed to compile pattern to regex");
943
+ }
944
+ }
945
+ function matchesPattern(key, pattern) {
946
+ const regex = globToRegex(pattern);
947
+ return regex.test(key);
948
+ }
949
+ var MAX_PATTERN_LENGTH;
950
+ var MAX_WILDCARDS;
951
+ var REGEX_SPECIAL_CHARS;
952
+ var init_pattern = __esm({
953
+ "libs/utils/src/storage/utils/pattern.ts"() {
954
+ "use strict";
955
+ init_errors();
956
+ MAX_PATTERN_LENGTH = 500;
957
+ MAX_WILDCARDS = 20;
958
+ REGEX_SPECIAL_CHARS = /[.+^${}()|[\]\\]/g;
959
+ }
960
+ });
906
961
  function validateTTL(ttlSeconds) {
907
962
  if (typeof ttlSeconds !== "number") {
908
963
  throw new StorageTTLError(ttlSeconds, `TTL must be a number, got ${typeof ttlSeconds}`);
@@ -1011,6 +1066,17 @@ var init_base = __esm({
1011
1066
  const matchedKeys = await this.keys(pattern);
1012
1067
  return matchedKeys.length;
1013
1068
  }
1069
+ /**
1070
+ * Default: not supported, since a read followed by a delete is not atomic.
1071
+ * Override in adapters whose backend can compare and delete in one step.
1072
+ */
1073
+ async deleteIfEquals(_key, _expectedValue) {
1074
+ throw new StorageNotSupportedError(
1075
+ "deleteIfEquals",
1076
+ this.backendName,
1077
+ "Use the memory, Redis, Upstash or Vercel KV adapter for an atomic compare-and-delete."
1078
+ );
1079
+ }
1014
1080
  // ============================================
1015
1081
  // Pub/Sub (default: not supported)
1016
1082
  // ============================================
@@ -1058,71 +1124,16 @@ var init_base = __esm({
1058
1124
  };
1059
1125
  }
1060
1126
  });
1061
- function globToRegex(pattern) {
1062
- if (pattern.length > MAX_PATTERN_LENGTH) {
1063
- throw new StoragePatternError(
1064
- pattern.substring(0, 50) + "...",
1065
- `Pattern exceeds maximum length of ${MAX_PATTERN_LENGTH} characters`
1066
- );
1067
- }
1068
- const wildcardCount = (pattern.match(/[*?]/g) || []).length;
1069
- if (wildcardCount > MAX_WILDCARDS) {
1070
- throw new StoragePatternError(pattern, `Pattern has too many wildcards (max: ${MAX_WILDCARDS})`);
1071
- }
1072
- if (pattern === "" || pattern === "*") {
1073
- return /^.*$/;
1074
- }
1075
- let regexStr = "^";
1076
- let prevChar = "";
1077
- for (let i = 0; i < pattern.length; i++) {
1078
- const char = pattern[i];
1079
- switch (char) {
1080
- case "*":
1081
- if (prevChar !== "*") {
1082
- regexStr += ".*";
1083
- }
1084
- break;
1085
- case "?":
1086
- regexStr += ".";
1087
- break;
1088
- default:
1089
- regexStr += char.replace(REGEX_SPECIAL_CHARS, "\\$&");
1090
- }
1091
- prevChar = char;
1092
- }
1093
- regexStr += "$";
1094
- try {
1095
- return new RegExp(regexStr);
1096
- } catch {
1097
- throw new StoragePatternError(pattern, "Failed to compile pattern to regex");
1098
- }
1099
- }
1100
- function matchesPattern(key, pattern) {
1101
- const regex = globToRegex(pattern);
1102
- return regex.test(key);
1103
- }
1104
- var MAX_PATTERN_LENGTH;
1105
- var MAX_WILDCARDS;
1106
- var REGEX_SPECIAL_CHARS;
1107
- var init_pattern = __esm({
1108
- "libs/utils/src/storage/utils/pattern.ts"() {
1109
- "use strict";
1110
- init_errors();
1111
- MAX_PATTERN_LENGTH = 500;
1112
- MAX_WILDCARDS = 20;
1113
- REGEX_SPECIAL_CHARS = /[.+^${}()|[\]\\]/g;
1114
- }
1115
- });
1116
1127
  var DEFAULT_SWEEP_INTERVAL_SECONDS;
1117
1128
  var MAX_TIMEOUT_MS;
1118
1129
  var MemoryStorageAdapter;
1119
1130
  var init_memory = __esm({
1120
1131
  "libs/utils/src/storage/adapters/memory.ts"() {
1121
1132
  "use strict";
1122
- init_base();
1123
1133
  init_errors();
1124
1134
  init_pattern();
1125
1135
  init_ttl();
1136
+ init_base();
1126
1137
  DEFAULT_SWEEP_INTERVAL_SECONDS = 60;
1127
1138
  MAX_TIMEOUT_MS = 2147483647;
1128
1139
  MemoryStorageAdapter = class extends BaseStorageAdapter {
@@ -1214,6 +1225,12 @@ var init_memory = __esm({
1214
1225
  this.ensureConnected();
1215
1226
  return this.deleteEntry(key);
1216
1227
  }
1228
+ async deleteIfEquals(key, expectedValue) {
1229
+ this.ensureConnected();
1230
+ const entry = this.store.get(key);
1231
+ if (!entry || isExpired(entry.expiresAt) || entry.value !== expectedValue) return false;
1232
+ return this.deleteEntry(key);
1233
+ }
1217
1234
  async exists(key) {
1218
1235
  this.ensureConnected();
1219
1236
  const entry = this.store.get(key);
@@ -2546,15 +2563,56 @@ var init_crypto = __esm({
2546
2563
  HKDF_SHA256_MAX_LENGTH = 255 * 32;
2547
2564
  }
2548
2565
  });
2566
+ function attachRedisErrorListener(client, options = {}) {
2567
+ const label = options.label ?? "redis";
2568
+ const intervalMs = options.intervalMs ?? DEFAULT_REDIS_ERROR_LOG_INTERVAL_MS;
2569
+ let lastLoggedAt = 0;
2570
+ let suppressed = 0;
2571
+ const listener = (error) => {
2572
+ const now = Date.now();
2573
+ if (lastLoggedAt !== 0 && now - lastLoggedAt < intervalMs) {
2574
+ suppressed++;
2575
+ return;
2576
+ }
2577
+ const extra = suppressed > 0 ? ` (${suppressed} similar error(s) suppressed)` : "";
2578
+ suppressed = 0;
2579
+ lastLoggedAt = now;
2580
+ const message = `[${label}] Redis connection error: ${error?.message ?? String(error)}${extra}`;
2581
+ if (options.logger) {
2582
+ options.logger.warn(message);
2583
+ } else {
2584
+ console.warn(message);
2585
+ }
2586
+ };
2587
+ client.on("error", listener);
2588
+ return () => {
2589
+ client.removeListener("error", listener);
2590
+ };
2591
+ }
2592
+ var DEFAULT_REDIS_ERROR_LOG_INTERVAL_MS;
2593
+ var init_redis_error_listener = __esm({
2594
+ "libs/utils/src/storage/redis-error-listener.ts"() {
2595
+ "use strict";
2596
+ DEFAULT_REDIS_ERROR_LOG_INTERVAL_MS = 3e4;
2597
+ }
2598
+ });
2549
2599
  var init_utils = __esm({
2550
2600
  "libs/utils/src/storage/utils/index.ts"() {
2551
2601
  "use strict";
2552
2602
  init_ttl();
2553
2603
  }
2554
2604
  });
2605
+ var COMPARE_AND_DELETE_SCRIPT;
2606
+ var init_compare_and_delete = __esm({
2607
+ "libs/utils/src/storage/utils/compare-and-delete.ts"() {
2608
+ "use strict";
2609
+ COMPARE_AND_DELETE_SCRIPT = `if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end return 0`;
2610
+ }
2611
+ });
2555
2612
  var redis_exports = {};
2556
2613
  __export2(redis_exports, {
2557
- RedisStorageAdapter: () => RedisStorageAdapter
2614
+ RedisStorageAdapter: () => RedisStorageAdapter,
2615
+ createRedisClient: () => createRedisClient
2558
2616
  });
2559
2617
  function getRedisClass() {
2560
2618
  try {
@@ -2572,12 +2630,28 @@ function getRedisClass() {
2572
2630
  });
2573
2631
  }
2574
2632
  }
2633
+ function createRedisClient(options) {
2634
+ const RedisClass = getRedisClass();
2635
+ const baseOptions = { lazyConnect: false, maxRetriesPerRequest: 3 };
2636
+ const client = options.url ? new RedisClass(options.url, baseOptions) : new RedisClass({
2637
+ ...baseOptions,
2638
+ host: options.host ?? "localhost",
2639
+ port: options.port ?? 6379,
2640
+ password: options.password,
2641
+ db: options.db ?? 0,
2642
+ tls: options.tls ? {} : void 0
2643
+ });
2644
+ attachRedisErrorListener(client, { label: options.label ?? "redis", logger: options.logger });
2645
+ return client;
2646
+ }
2575
2647
  var RedisStorageAdapter;
2576
2648
  var init_redis = __esm({
2577
2649
  "libs/utils/src/storage/adapters/redis.ts"() {
2578
2650
  "use strict";
2579
2651
  init_errors();
2652
+ init_redis_error_listener();
2580
2653
  init_utils();
2654
+ init_compare_and_delete();
2581
2655
  init_base();
2582
2656
  RedisStorageAdapter = class extends BaseStorageAdapter {
2583
2657
  backendName = "redis";
@@ -2585,6 +2659,7 @@ var init_redis = __esm({
2585
2659
  subscriber;
2586
2660
  options;
2587
2661
  ownsClient;
2662
+ detachErrorListener;
2588
2663
  connecting;
2589
2664
  keyPrefix;
2590
2665
  subscriptionHandlers = /* @__PURE__ */ new Map();
@@ -2641,7 +2716,10 @@ var init_redis = __esm({
2641
2716
  await client.ping();
2642
2717
  this.client = client;
2643
2718
  this.connected = true;
2644
- if (this.ownsClient) client.removeListener("error", recordSocketError);
2719
+ if (this.ownsClient) {
2720
+ client.removeListener("error", recordSocketError);
2721
+ this.detachErrorListener = attachRedisErrorListener(client, { label: "RedisStorage" });
2722
+ }
2645
2723
  } catch (e) {
2646
2724
  if (this.ownsClient && client) {
2647
2725
  try {
@@ -2662,6 +2740,8 @@ var init_redis = __esm({
2662
2740
  if (this.ownsClient && this.client) {
2663
2741
  await this.client.quit();
2664
2742
  }
2743
+ this.detachErrorListener?.();
2744
+ this.detachErrorListener = void 0;
2665
2745
  this.client = void 0;
2666
2746
  this.connected = false;
2667
2747
  this.subscriptionHandlers.clear();
@@ -2726,6 +2806,15 @@ var init_redis = __esm({
2726
2806
  const result = await this.getConnectedClient().del(this.prefixKey(key));
2727
2807
  return result > 0;
2728
2808
  }
2809
+ async deleteIfEquals(key, expectedValue) {
2810
+ const deleted = await this.getConnectedClient().eval(
2811
+ COMPARE_AND_DELETE_SCRIPT,
2812
+ 1,
2813
+ this.prefixKey(key),
2814
+ expectedValue
2815
+ );
2816
+ return deleted === 1;
2817
+ }
2729
2818
  async exists(key) {
2730
2819
  const result = await this.getConnectedClient().exists(this.prefixKey(key));
2731
2820
  return result > 0;
@@ -2889,6 +2978,7 @@ var init_redis = __esm({
2889
2978
  } else {
2890
2979
  throw new StorageConfigError("redis", "Cannot create subscriber without url, config, or client");
2891
2980
  }
2981
+ attachRedisErrorListener(subscriber, { label: "RedisStorage:subscriber" });
2892
2982
  subscriber.on("message", (channel, message) => {
2893
2983
  const handlers = this.subscriptionHandlers.get(channel);
2894
2984
  if (handlers) {
@@ -2931,9 +3021,12 @@ var vercel_kv_exports = {};
2931
3021
  __export2(vercel_kv_exports, {
2932
3022
  VercelKvStorageAdapter: () => VercelKvStorageAdapter
2933
3023
  });
2934
- function getVercelKv() {
3024
+ async function loadVercelKv() {
2935
3025
  try {
2936
- return __require("@vercel/kv");
3026
+ const mod = await import("@vercel/kv");
3027
+ const resolved = typeof mod.createClient === "function" ? mod : mod.default;
3028
+ if (!resolved || typeof resolved.createClient !== "function") throw new Error("createClient missing");
3029
+ return resolved;
2937
3030
  } catch {
2938
3031
  throw new Error("@vercel/kv is required for Vercel KV storage adapter. Install it with: npm install @vercel/kv");
2939
3032
  }
@@ -2942,9 +3035,10 @@ var VercelKvStorageAdapter;
2942
3035
  var init_vercel_kv = __esm({
2943
3036
  "libs/utils/src/storage/adapters/vercel-kv.ts"() {
2944
3037
  "use strict";
2945
- init_base();
2946
3038
  init_errors();
3039
+ init_compare_and_delete();
2947
3040
  init_ttl();
3041
+ init_base();
2948
3042
  VercelKvStorageAdapter = class extends BaseStorageAdapter {
2949
3043
  backendName = "vercel-kv";
2950
3044
  client;
@@ -2969,17 +3063,13 @@ var init_vercel_kv = __esm({
2969
3063
  async connect() {
2970
3064
  if (this.connected) return;
2971
3065
  try {
2972
- const { createClient, kv } = getVercelKv();
2973
- if (this.options.url === process.env["KV_REST_API_URL"]) {
2974
- this.client = kv;
2975
- } else {
2976
- const url = this.options.url;
2977
- const token = this.options.token;
2978
- if (!url || !token) {
2979
- throw new StorageConfigError("vercel-kv", "URL and token are required");
2980
- }
2981
- this.client = createClient({ url, token });
3066
+ const { createClient } = await loadVercelKv();
3067
+ const url = this.options.url;
3068
+ const token = this.options.token;
3069
+ if (!url || !token) {
3070
+ throw new StorageConfigError("vercel-kv", "URL and token are required");
2982
3071
  }
3072
+ this.client = createClient({ url, token, cache: void 0 });
2983
3073
  await this.client.exists("__healthcheck__");
2984
3074
  this.connected = true;
2985
3075
  } catch (e) {
@@ -3041,6 +3131,14 @@ var init_vercel_kv = __esm({
3041
3131
  const result = await this.getConnectedClient().del(this.prefixKey(key));
3042
3132
  return result > 0;
3043
3133
  }
3134
+ async deleteIfEquals(key, expectedValue) {
3135
+ const deleted = await this.getConnectedClient().eval(
3136
+ COMPARE_AND_DELETE_SCRIPT,
3137
+ [this.prefixKey(key)],
3138
+ [expectedValue]
3139
+ );
3140
+ return deleted === 1;
3141
+ }
3044
3142
  async exists(key) {
3045
3143
  const result = await this.getConnectedClient().exists(this.prefixKey(key));
3046
3144
  return result > 0;
@@ -3157,9 +3255,10 @@ var UpstashStorageAdapter;
3157
3255
  var init_upstash = __esm({
3158
3256
  "libs/utils/src/storage/adapters/upstash.ts"() {
3159
3257
  "use strict";
3160
- init_base();
3161
3258
  init_errors();
3259
+ init_compare_and_delete();
3162
3260
  init_ttl();
3261
+ init_base();
3163
3262
  PUBSUB_POLL_INTERVAL_MS = 100;
3164
3263
  UpstashStorageAdapter = class extends BaseStorageAdapter {
3165
3264
  backendName = "upstash";
@@ -3264,6 +3363,14 @@ var init_upstash = __esm({
3264
3363
  const result = await this.getConnectedClient().del(this.prefixKey(key));
3265
3364
  return result > 0;
3266
3365
  }
3366
+ async deleteIfEquals(key, expectedValue) {
3367
+ const deleted = await this.getConnectedClient().eval(
3368
+ COMPARE_AND_DELETE_SCRIPT,
3369
+ [this.prefixKey(key)],
3370
+ [expectedValue]
3371
+ );
3372
+ return deleted === 1;
3373
+ }
3267
3374
  async exists(key) {
3268
3375
  const result = await this.getConnectedClient().exists(this.prefixKey(key));
3269
3376
  return result > 0;
@@ -3452,7 +3559,9 @@ var init_cloudflare_kv = __esm({
3452
3559
  constructor(options) {
3453
3560
  super();
3454
3561
  if (!options?.namespace) {
3455
- throw new Error("CloudflareKvStorageAdapter: a bound KV `namespace` is required (resolve it from the Worker `env`).");
3562
+ throw new Error(
3563
+ "CloudflareKvStorageAdapter: a bound KV `namespace` is required (resolve it from the Worker `env`)."
3564
+ );
3456
3565
  }
3457
3566
  this.kv = options.namespace;
3458
3567
  this.keyPrefix = options.keyPrefix ?? "";
@@ -3546,6 +3655,13 @@ var init_cloudflare_kv = __esm({
3546
3655
  "Cloudflare KV has no atomic increment (a get+put is racy under eventual consistency). Use a Durable Object for atomic counters."
3547
3656
  );
3548
3657
  }
3658
+ async deleteIfEquals(_key, _expectedValue) {
3659
+ throw new StorageNotSupportedError(
3660
+ "deleteIfEquals",
3661
+ this.backendName,
3662
+ "Cloudflare KV has no compare-and-set; use a Durable Object for an atomic compare-and-delete."
3663
+ );
3664
+ }
3549
3665
  // ── Pub/Sub (unsupported) ────────────────────────────────────────────────
3550
3666
  getPubSubSuggestion() {
3551
3667
  return "Cloudflare KV does not support pub/sub. Use a Durable Object (or Queues) for fan-out.";
@@ -3659,18 +3775,10 @@ function compileBlocks(entries, parseNetwork) {
3659
3775
  }
3660
3776
  init_fs2();
3661
3777
  init_crypto();
3662
- var entryAvailabilitySchema = import_lazy_zod3.z.object({
3663
- os: import_lazy_zod3.z.array(import_lazy_zod3.z.string().min(1)).optional(),
3664
- platform: import_lazy_zod3.z.array(import_lazy_zod3.z.string().min(1)).optional(),
3665
- runtime: import_lazy_zod3.z.array(import_lazy_zod3.z.string().min(1)).optional(),
3666
- deployment: import_lazy_zod3.z.array(import_lazy_zod3.z.string().min(1)).optional(),
3667
- provider: import_lazy_zod3.z.array(import_lazy_zod3.z.string().min(1)).optional(),
3668
- target: import_lazy_zod3.z.array(import_lazy_zod3.z.string().min(1)).optional(),
3669
- surface: import_lazy_zod3.z.array(import_lazy_zod3.z.enum(["mcp", "cli", "http-trigger", "job", "agent"])).optional(),
3670
- env: import_lazy_zod3.z.array(import_lazy_zod3.z.string().min(1)).optional()
3671
- }).strict();
3778
+ init_errors();
3672
3779
  init_errors();
3673
3780
  init_memory();
3781
+ init_redis_error_listener();
3674
3782
  init_errors();
3675
3783
  init_crypto();
3676
3784
  init_errors();
@@ -3687,6 +3795,14 @@ init_ttl();
3687
3795
  init_crypto();
3688
3796
  init_runtime();
3689
3797
 
3798
+ // plugins/plugin-cache/src/cache.errors.ts
3799
+ var CachePluginConfigurationError = class extends Error {
3800
+ constructor(message) {
3801
+ super(message);
3802
+ this.name = "CachePluginConfigurationError";
3803
+ }
3804
+ };
3805
+
3690
3806
  // plugins/plugin-cache/src/cache.symbol.ts
3691
3807
  var CacheStoreToken = /* @__PURE__ */ Symbol("plugin:cache:store");
3692
3808
 
@@ -3918,6 +4034,15 @@ CacheVercelKvProvider = __decorateClass([
3918
4034
 
3919
4035
  // plugins/plugin-cache/src/cache.plugin.ts
3920
4036
  var DEFAULT_BYPASS_HEADER = "x-frontmcp-disable-cache";
4037
+ var BYPASS_HEADER_PREFIX = "x-frontmcp-";
4038
+ function assertReadableBypassHeader(bypassHeader) {
4039
+ if (bypassHeader === void 0) return;
4040
+ const name = bypassHeader.toLowerCase();
4041
+ if (name.startsWith(BYPASS_HEADER_PREFIX) && name.length > BYPASS_HEADER_PREFIX.length) return;
4042
+ throw new CachePluginConfigurationError(
4043
+ `CachePlugin bypassHeader "${bypassHeader}" is never seen by the plugin: only request headers that start with "${BYPASS_HEADER_PREFIX}" reach it. Rename it, e.g. "${BYPASS_HEADER_PREFIX}no-cache".`
4044
+ );
4045
+ }
3921
4046
  function matchesToolPattern(toolName, patterns) {
3922
4047
  if (!patterns || patterns.length === 0) return false;
3923
4048
  return patterns.some((pattern) => {
@@ -3933,6 +4058,7 @@ var CachePlugin = class extends import_sdk4.DynamicPlugin {
3933
4058
  options;
3934
4059
  constructor(options = CachePlugin.defaultOptions) {
3935
4060
  super();
4061
+ assertReadableBypassHeader(options.bypassHeader);
3936
4062
  this.options = {
3937
4063
  defaultTTL: 60 * 60 * 24,
3938
4064
  ...options
@@ -3990,15 +4116,13 @@ var CachePlugin = class extends import_sdk4.DynamicPlugin {
3990
4116
  const hash = this.buildCacheKey(tool.fullName, toolContext);
3991
4117
  const cached = await cacheStore.getValue(hash);
3992
4118
  if (cached !== void 0 && cached !== null) {
3993
- const cacheConfig = typeof cache === "object" ? cache : void 0;
3994
- if (cache === true || cacheConfig?.ttl && cacheConfig?.slideWindow) {
3995
- const ttl = this.getTtl(cache);
3996
- await cacheStore.setValue(hash, cached, ttl);
3997
- }
3998
- if (!tool.safeParseOutput(cached).success) {
4119
+ if (isErrorResult(cached) || !tool.safeParseOutput(cached).success) {
3999
4120
  await cacheStore.delete(hash);
4000
4121
  return;
4001
4122
  }
4123
+ if (typeof cache === "object" && cache.slideWindow) {
4124
+ await cacheStore.setValue(hash, cached, this.getTtl(cache));
4125
+ }
4002
4126
  flowCtx.state.set("resultMeta", { ...flowCtx.state.resultMeta, cache: "hit" });
4003
4127
  flowCtx.state.set("rawOutput", cached);
4004
4128
  toolContext.respond(cached);
@@ -4015,6 +4139,9 @@ var CachePlugin = class extends import_sdk4.DynamicPlugin {
4015
4139
  if (!shouldCache || typeof toolContext.input === "undefined") {
4016
4140
  return;
4017
4141
  }
4142
+ if (isErrorResult(toolContext.output)) {
4143
+ return;
4144
+ }
4018
4145
  const cacheStore = this.get(CacheStoreToken);
4019
4146
  const ttl = this.getTtl(cache);
4020
4147
  const hash = this.buildCacheKey(tool.fullName, toolContext);
@@ -4139,6 +4266,11 @@ CachePlugin = __decorateClass([
4139
4266
  ]
4140
4267
  })
4141
4268
  ], CachePlugin);
4269
+ function isErrorResult(output) {
4270
+ if (typeof output !== "object" || output === null) return false;
4271
+ const result = output;
4272
+ return result.isError === true && Array.isArray(result.content);
4273
+ }
4142
4274
  function stableValue(value) {
4143
4275
  if (Array.isArray(value)) {
4144
4276
  return value.map(stableValue);
@@ -4154,5 +4286,6 @@ function stableValue(value) {
4154
4286
  }
4155
4287
  // Annotate the CommonJS export names for ESM import in node:
4156
4288
  0 && (module.exports = {
4157
- CachePlugin
4289
+ CachePlugin,
4290
+ CachePluginConfigurationError
4158
4291
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@frontmcp/plugin-cache",
3
- "version": "1.8.6",
3
+ "version": "1.9.0",
4
4
  "description": "Cache plugin for FrontMCP - Redis, Vercel KV, and in-memory caching with automatic tool result caching",
5
5
  "author": "AgentFront <info@agentfront.dev>",
6
6
  "license": "Apache-2.0",
@@ -48,8 +48,8 @@
48
48
  }
49
49
  },
50
50
  "dependencies": {
51
- "@frontmcp/sdk": "1.8.6",
52
- "@frontmcp/utils": "1.8.6",
51
+ "@frontmcp/sdk": "1.9.0",
52
+ "@frontmcp/utils": "1.9.0",
53
53
  "ioredis": "^5.8.0"
54
54
  },
55
55
  "peerDependencies": {