@frontmcp/plugin-cache 1.12.0 → 1.12.1

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/cache.plugin.d.ts CHANGED
@@ -41,7 +41,8 @@ export default class CachePlugin extends DynamicPlugin<CachePluginOptions> {
41
41
  *
42
42
  * Read and write both go through here. They used to build the key at two separate call
43
43
  * sites, and a key that differs between them silently disables the cache rather than
44
- * failing visibly.
44
+ * failing visibly. The call's surface is part of it: what a tool acting for the caller
45
+ * (CodeCall's search and describe) returns depends on it.
45
46
  */
46
47
  private buildCacheKey;
47
48
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"cache.plugin.d.ts","sourceRoot":"","sources":["../src/cache.plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,aAAa,EASb,KAAK,SAAS,EAEd,KAAK,oBAAoB,EACzB,KAAK,iBAAiB,EACtB,KAAK,YAAY,EAClB,MAAM,eAAe,CAAC;AAKvB,OAAO,EAAE,KAAK,kBAAkB,EAAsC,MAAM,eAAe,CAAC;AA4E5F,MAAM,CAAC,OAAO,OAAO,WAAY,SAAQ,aAAa,CAAC,kBAAkB,CAAC;IACxE,uGAAuG;IACvG,OAAgB,aAAa,GAAI,SAAS,kBAAkB,EAAE,QAAQ,iBAAiB,KAAG,oBAAoB,EAAE,CAQ9G;IAEF,OAAgB,gBAAgB,GAAI,SAAS,kBAAkB,oBA+D7D;IAEF,MAAM,CAAC,cAAc,EAAE,kBAAkB,CAEvC;IACF,OAAO,EAAE,kBAAkB,CAAC;gBAEhB,OAAO,GAAE,kBAA+C;IAUpE;;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;IAyDnD,cAAc,CAAC,OAAO,EAAE,SAAS,CAAC,iBAAiB,CAAC;IAgC1D;;;;;;;;;;;OAWG;IACH,OAAO,CAAC,qBAAqB;IAwB7B;;;;;;;OAOG;IACH,OAAO,CAAC,aAAa;IASrB;;;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,EAUb,KAAK,SAAS,EAEd,KAAK,oBAAoB,EACzB,KAAK,iBAAiB,EACtB,KAAK,YAAY,EAClB,MAAM,eAAe,CAAC;AAKvB,OAAO,EAAE,KAAK,kBAAkB,EAAsC,MAAM,eAAe,CAAC;AA4E5F,MAAM,CAAC,OAAO,OAAO,WAAY,SAAQ,aAAa,CAAC,kBAAkB,CAAC;IACxE,uGAAuG;IACvG,OAAgB,aAAa,GAAI,SAAS,kBAAkB,EAAE,QAAQ,iBAAiB,KAAG,oBAAoB,EAAE,CAQ9G;IAEF,OAAgB,gBAAgB,GAAI,SAAS,kBAAkB,oBAiE7D;IAEF,MAAM,CAAC,cAAc,EAAE,kBAAkB,CAEvC;IACF,OAAO,EAAE,kBAAkB,CAAC;gBAEhB,OAAO,GAAE,kBAA+C;IAUpE;;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;IAyDnD,cAAc,CAAC,OAAO,EAAE,SAAS,CAAC,iBAAiB,CAAC;IAgC1D;;;;;;;;;;;OAWG;IACH,OAAO,CAAC,qBAAqB;IAyB7B;;;;;;;;OAQG;IACH,OAAO,CAAC,aAAa;IAarB;;;OAGG;IACH,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO;CAGvC"}
package/cache.types.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Redis as RedisClient } from 'ioredis';
1
+ import type { Redis as RedisClient, RedisOptions } from 'ioredis';
2
2
  declare global {
3
3
  interface ExtendFrontMcpToolMetadata {
4
4
  cache?: CachePluginToolOptions | true;
@@ -81,6 +81,10 @@ export interface RedisCachePluginOptions extends BaseCachePluginOptions {
81
81
  port: number;
82
82
  password?: string;
83
83
  db?: number;
84
+ /** TLS options for the connection; `{}` connects over TLS with the default certificate checks. */
85
+ tls?: RedisOptions['tls'];
86
+ /** Prefix of every cache key, so servers that share one Redis database keep their entries apart. */
87
+ keyPrefix?: string;
84
88
  };
85
89
  }
86
90
  export type MemoryCachePluginOptions = BaseCachePluginOptions & {
@@ -1 +1 @@
1
- {"version":3,"file":"cache.types.d.ts","sourceRoot":"","sources":["../src/cache.types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,IAAI,WAAW,EAAE,MAAM,SAAS,CAAC;AAEpD,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"}
1
+ {"version":3,"file":"cache.types.d.ts","sourceRoot":"","sources":["../src/cache.types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,IAAI,WAAW,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAElE,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;QACZ,kGAAkG;QAClG,GAAG,CAAC,EAAE,YAAY,CAAC,KAAK,CAAC,CAAC;QAC1B,oGAAoG;QACpG,SAAS,CAAC,EAAE,MAAM,CAAC;KACpB,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,4 +1,4 @@
1
1
  var __frontmcpModule = typeof process !== "undefined" && typeof process.getBuiltinModule === "function" ? process.getBuiltinModule("module") : undefined;
2
2
  const require = __frontmcpModule ? __frontmcpModule.createRequire(import.meta.url || 'file:///') : undefined;
3
3
  // __frontmcpCreateRequire
4
- var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __require=(x=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x)(function(x){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var __decorateClass=(decorators,target,key,kind)=>{var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target;for(var i=decorators.length-1,decorator;i>=0;i--)if(decorator=decorators[i])result=(kind?decorator(target,key,result):decorator(result))||result;if(kind&&result)__defProp(target,key,result);return result};var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);import{DynamicPlugin,FrontMcpConfig,FrontMcpContextStorage,getGlobalStoreConfig,isAnonymousSubject,isVercelKvProvider,Plugin,storeProvider,ToolHook}from"@frontmcp/sdk";import{sha256Hex}from"@frontmcp/utils";var CachePluginConfigurationError=class extends Error{constructor(message){super(message);this.name="CachePluginConfigurationError"}};var CacheStoreToken=Symbol("plugin:cache:store");import{Provider,ProviderScope}from"@frontmcp/sdk";var MAX_TIMEOUT_MS=2**31-1;var CacheMemoryProvider=class{memory=new Map;sweeper;constructor(sweepIntervalTTL=60){this.sweeper=setInterval(()=>this.sweep(),sweepIntervalTTL*1e3);this.sweeper.unref?.()}async setValue(key,value,ttlSeconds){const strValue=typeof value==="string"?value:JSON.stringify(value);const existing=this.memory.get(key);if(existing?.timeout)clearTimeout(existing.timeout);const entry={value:strValue};if(ttlSeconds&&ttlSeconds>0){const ttlMs=ttlSeconds*1e3;entry.expiresAt=Date.now()+ttlMs;if(ttlMs<=MAX_TIMEOUT_MS){entry.timeout=setTimeout(()=>{const e=this.memory.get(key);if(e&&e.expiresAt&&e.expiresAt<=Date.now()){this.memory.delete(key)}},ttlMs);entry.timeout.unref?.()}}this.memory.set(key,entry)}async getValue(key,defaultValue){const entry=this.memory.get(key);if(!entry)return defaultValue;if(this.isExpired(entry)){await this.delete(key);return defaultValue}const raw=entry.value;try{return JSON.parse(raw)}catch{return raw}}async delete(key){const entry=this.memory.get(key);if(entry?.timeout)clearTimeout(entry.timeout);this.memory.delete(key)}async exists(key){const entry=this.memory.get(key);if(!entry)return false;if(this.isExpired(entry)){await this.delete(key);return false}return true}async close(){if(this.sweeper)clearInterval(this.sweeper);for(const[,entry]of this.memory){if(entry.timeout)clearTimeout(entry.timeout)}this.memory.clear()}isExpired(entry){return entry.expiresAt!==void 0&&entry.expiresAt<=Date.now()}sweep(){const now=Date.now();for(const[key,entry]of this.memory){if(entry.expiresAt!==void 0&&entry.expiresAt<=now){if(entry.timeout)clearTimeout(entry.timeout);this.memory.delete(key)}}}};CacheMemoryProvider=__decorateClass([Provider({name:"provider:cache:memory",description:"Memory-based cache provider",scope:ProviderScope.GLOBAL})],CacheMemoryProvider);import{Provider as Provider2,ProviderScope as ProviderScope2}from"@frontmcp/sdk";function createRedisClient(options){const ioredis=__require("ioredis");const Redis=ioredis.default??ioredis;return new Redis(options)}var CacheRedisProvider=class{client;constructor(options){if(options.type!=="redis"&&options.type!=="redis-client"){throw new Error("Invalid cache provider type")}if(options.type==="redis-client"){this.client=options.client;return}this.client=createRedisClient({lazyConnect:false,maxRetriesPerRequest:3,...options.config});this.client.on("connect",()=>console.log("[Redis] Connected"));this.client.on("error",err=>console.error("[Redis] Error:",err))}async setValue(key,value,ttlSeconds){const strValue=typeof value==="string"?value:JSON.stringify(value);if(ttlSeconds&&ttlSeconds>0){await this.client.set(key,strValue,"EX",ttlSeconds)}else{await this.client.set(key,strValue)}}async getValue(key,defaultValue){const raw=await this.client.get(key);if(raw===null)return defaultValue;try{return JSON.parse(raw)}catch{return raw}}async delete(key){await this.client.del(key)}async exists(key){return await this.client.exists(key)===1}async close(){await this.client.quit()}};CacheRedisProvider=__decorateClass([Provider2({name:"provider:cache:redis",description:"Redis-based cache provider",scope:ProviderScope2.GLOBAL})],CacheRedisProvider);import{Provider as Provider3,ProviderScope as ProviderScope3}from"@frontmcp/sdk";import{createVercelKvClient}from"@frontmcp/utils";var CacheVercelKvProvider=class{connection;client;keyPrefix;defaultTTL;constructor(options={}){const hasUrl=options.url!==void 0;const hasToken=options.token!==void 0;if(hasUrl!==hasToken){throw new Error(`CacheVercelKvProvider: Both 'url' and 'token' must be provided together, or neither. Received: url=${hasUrl?"provided":"missing"}, token=${hasToken?"provided":"missing"}`)}this.connection={url:options.url,token:options.token};this.keyPrefix=options.keyPrefix??"cache:";this.defaultTTL=options.defaultTTL??60*60*24}kv(){this.client??=createVercelKvClient(this.connection).catch(error=>{this.client=void 0;throw error});return this.client}prefixKey(key){return`${this.keyPrefix}${key}`}async setValue(key,value,ttlSeconds){const strValue=typeof value==="string"?value:JSON.stringify(value);const ttl=ttlSeconds??this.defaultTTL;const kv=await this.kv();if(ttl>0){await kv.set(this.prefixKey(key),strValue,{ex:ttl})}else{await kv.set(this.prefixKey(key),strValue)}}async getValue(key,defaultValue){const kv=await this.kv();const raw=await kv.get(this.prefixKey(key));if(raw===null||raw===void 0)return defaultValue;if(typeof raw==="string"){try{return JSON.parse(raw)}catch{return raw}}return raw}async delete(key){const kv=await this.kv();await kv.del(this.prefixKey(key))}async exists(key){const kv=await this.kv();return await kv.exists(this.prefixKey(key))===1}async close(){}};CacheVercelKvProvider=__decorateClass([Provider3({name:"provider:cache:vercel-kv",description:"Vercel KV-based cache provider",scope:ProviderScope3.GLOBAL})],CacheVercelKvProvider);var DEFAULT_BYPASS_HEADER="x-frontmcp-disable-cache";var BYPASS_HEADER_PREFIX="x-frontmcp-";function assertReadableBypassHeader(bypassHeader){if(bypassHeader===void 0)return;const name=bypassHeader.toLowerCase();if(name.startsWith(BYPASS_HEADER_PREFIX)&&name.length>BYPASS_HEADER_PREFIX.length)return;throw new CachePluginConfigurationError(`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".`)}var CACHE_TYPES=["memory","redis","redis-client","global-store"];function assertKnownCacheType(type){if(type===void 0||CACHE_TYPES.includes(type))return;throw new CachePluginConfigurationError(`CachePlugin type ${JSON.stringify(type)} is not supported. Supported types: ${CACHE_TYPES.map(name=>`"${name}"`).join(", ")}.`)}function matchesToolPattern(toolName,patterns){if(!patterns||patterns.length===0)return false;return patterns.some(pattern=>{if(pattern.includes("*")){const escaped=pattern.replace(/[.+?^${}()|[\]\\]/g,"\\$&");const regex=new RegExp("^"+escaped.replace(/\*/g,".*")+"$");return regex.test(toolName)}return pattern===toolName})}var CachePlugin=class extends DynamicPlugin{options;constructor(options=CachePlugin.defaultOptions){super();assertKnownCacheType(options.type);assertReadableBypassHeader(options.bypassHeader);this.options={defaultTTL:60*60*24,...options}}shouldCacheTool(toolName,cacheMetadata){if(typeof cacheMetadata==="object"&&cacheMetadata.ttl!==void 0&&cacheMetadata.ttl<=0){return false}if(cacheMetadata)return true;const patterns=this.options.toolPatterns??[];return matchesToolPattern(toolName,patterns)}shouldBypassCache(_flowCtx){const bypassHeader=this.options.bypassHeader??DEFAULT_BYPASS_HEADER;try{const contextStorage=this.get(FrontMcpContextStorage);const context=contextStorage?.getStore();const customHeaders=context?.metadata?.customHeaders;if(!customHeaders)return false;const headerKey=bypassHeader.toLowerCase();const headerValue=customHeaders[headerKey];return headerValue==="true"||headerValue==="1"}catch{return false}}getTtl(cacheMetadata){if(typeof cacheMetadata==="object"&&cacheMetadata.ttl!==void 0){return cacheMetadata.ttl}return this.options.defaultTTL??60*60*24}async willReadCache(flowCtx){const{tool,toolContext}=flowCtx.state;if(!tool||!toolContext)return;if(this.shouldBypassCache(flowCtx)){return}const{cache}=toolContext.metadata;if(!this.shouldCacheTool(tool.fullName,cache)&&!this.shouldCacheTool(tool.name,cache)||typeof toolContext.input==="undefined"){return}const hash=this.buildCacheKey(tool.fullName,toolContext);if(hash===void 0)return;const cacheStore=this.get(CacheStoreToken);const cached=await cacheStore.getValue(hash);if(cached!==void 0&&cached!==null){if(isErrorResult(cached)||!tool.safeParseOutput(cached).success){await cacheStore.delete(hash);return}if(typeof cache==="object"&&cache.slideWindow){await cacheStore.setValue(hash,cached,this.getTtl(cache))}flowCtx.state.set("resultMeta",{...flowCtx.state.resultMeta,cache:"hit"});toolContext.respond(cached)}}async willWriteCache(flowCtx){const{tool,toolContext}=flowCtx.state;if(!tool||!toolContext)return;if(this.shouldBypassCache(flowCtx)){return}const{cache}=toolContext.metadata;const shouldCache=this.shouldCacheTool(tool.fullName,cache)||this.shouldCacheTool(tool.name,cache);if(!shouldCache||typeof toolContext.input==="undefined"){return}if(isErrorResult(toolContext.output)){return}const hash=this.buildCacheKey(tool.fullName,toolContext);if(hash===void 0)return;const cacheStore=this.get(CacheStoreToken);await cacheStore.setValue(hash,toolContext.output,this.getTtl(cache))}resolveCallerIdentity(toolContext){const ctx=toolContext;const requestContext=ctx.tryGetContext?.();const authInfo=ctx.authInfo??requestContext?.authInfo;const subject=authInfo?.extra?.["sub"]??authInfo?.extra?.["userId"];if(!isAnonymousSubject(subject))return`user:${subject}`;if(!isAnonymousSubject(authInfo?.clientId))return`client:${authInfo?.clientId}`;const sessionId=requestContext?.verifiedSessionId;if(sessionId)return`session:${sessionId}`;return void 0}buildCacheKey(toolFullName,toolContext){const identity=this.options.keyByIdentity===false?"shared":this.resolveCallerIdentity(toolContext);if(identity===void 0)return void 0;return sha256Hex(JSON.stringify({identity,tool:toolFullName,input:stableValue(toolContext.input)}))}isCacheable(toolName){return matchesToolPattern(toolName,this.options.toolPatterns??[])}};__publicField(CachePlugin,"browserStores",(options,server)=>{const onRedis=options.type==="redis"||options.type==="redis-client"||options.type==="global-store"&&server.redis!==void 0&&!isVercelKvProvider(server.redis);return[{plugin:"CachePlugin",option:onRedis?`type: '${options.type}'`:void 0,memory:"type: 'memory'"}]});__publicField(CachePlugin,"dynamicProviders",options=>{const providers=[];switch(options.type){case"global-store":providers.push(storeProvider({name:"cache:global-store",provide:CacheStoreToken,inject:()=>[FrontMcpConfig],useFactory:config=>{const storeConfig=getGlobalStoreConfig("CachePlugin",config);const globalOptions=options;if(isVercelKvProvider(storeConfig)){return new CacheVercelKvProvider({url:storeConfig.url,token:storeConfig.token,keyPrefix:storeConfig.keyPrefix,defaultTTL:globalOptions.defaultTTL})}return new CacheRedisProvider({type:"redis",config:{host:storeConfig.host??"localhost",port:storeConfig.port??6379,password:storeConfig.password,db:storeConfig.db},defaultTTL:globalOptions.defaultTTL})}}));break;case"redis":case"redis-client":{let store;providers.push(storeProvider({name:"cache:redis",provide:CacheStoreToken,inject:()=>[],useFactory:()=>store??=new CacheRedisProvider(options)}));break}case"memory":providers.push({name:"cache:memory",provide:CacheStoreToken,inject:()=>[],useFactory:()=>new CacheMemoryProvider(options.defaultTTL)});break}return providers});__publicField(CachePlugin,"defaultOptions",{type:"memory"});__decorateClass([ToolHook.Will("execute",{priority:1e3})],CachePlugin.prototype,"willReadCache",1);__decorateClass([ToolHook.Did("execute",{priority:1e3})],CachePlugin.prototype,"willWriteCache",1);CachePlugin=__decorateClass([Plugin({name:"cache",description:"Cache plugin for caching tool results",providers:[{name:"cache:memory",provide:CacheStoreToken,inject:()=>[],useFactory:()=>new CacheMemoryProvider(60*60*24)}]})],CachePlugin);function isErrorResult(output){if(typeof output!=="object"||output===null)return false;const result=output;return result.isError===true&&Array.isArray(result.content)}function stableValue(value){if(Array.isArray(value)){return value.map(stableValue)}if(typeof value==="object"&&value!==null){const source=value;return Object.keys(source).sort().reduce((acc,key)=>{acc[key]=stableValue(source[key]);return acc},{})}return value}export{CachePlugin,CachePluginConfigurationError,CachePlugin as default};
4
+ var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __require=(x=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x)(function(x){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var __decorateClass=(decorators,target,key,kind)=>{var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target;for(var i=decorators.length-1,decorator;i>=0;i--)if(decorator=decorators[i])result=(kind?decorator(target,key,result):decorator(result))||result;if(kind&&result)__defProp(target,key,result);return result};var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);import{DynamicPlugin,FrontMcpConfig,FrontMcpContextStorage,getGlobalStoreConfig,isAnonymousSubject,isVercelKvProvider,Plugin,resolvePrincipal,storeProvider,ToolHook}from"@frontmcp/sdk";import{sha256Hex}from"@frontmcp/utils";var CachePluginConfigurationError=class extends Error{constructor(message){super(message);this.name="CachePluginConfigurationError"}};var CacheStoreToken=Symbol("plugin:cache:store");import{Provider,ProviderScope}from"@frontmcp/sdk";var MAX_TIMEOUT_MS=2**31-1;var CacheMemoryProvider=class{memory=new Map;sweeper;constructor(sweepIntervalTTL=60){this.sweeper=setInterval(()=>this.sweep(),sweepIntervalTTL*1e3);this.sweeper.unref?.()}async setValue(key,value,ttlSeconds){const strValue=typeof value==="string"?value:JSON.stringify(value);const existing=this.memory.get(key);if(existing?.timeout)clearTimeout(existing.timeout);const entry={value:strValue};if(ttlSeconds&&ttlSeconds>0){const ttlMs=ttlSeconds*1e3;entry.expiresAt=Date.now()+ttlMs;if(ttlMs<=MAX_TIMEOUT_MS){entry.timeout=setTimeout(()=>{const e=this.memory.get(key);if(e&&e.expiresAt&&e.expiresAt<=Date.now()){this.memory.delete(key)}},ttlMs);entry.timeout.unref?.()}}this.memory.set(key,entry)}async getValue(key,defaultValue){const entry=this.memory.get(key);if(!entry)return defaultValue;if(this.isExpired(entry)){await this.delete(key);return defaultValue}const raw=entry.value;try{return JSON.parse(raw)}catch{return raw}}async delete(key){const entry=this.memory.get(key);if(entry?.timeout)clearTimeout(entry.timeout);this.memory.delete(key)}async exists(key){const entry=this.memory.get(key);if(!entry)return false;if(this.isExpired(entry)){await this.delete(key);return false}return true}async close(){if(this.sweeper)clearInterval(this.sweeper);for(const[,entry]of this.memory){if(entry.timeout)clearTimeout(entry.timeout)}this.memory.clear()}isExpired(entry){return entry.expiresAt!==void 0&&entry.expiresAt<=Date.now()}sweep(){const now=Date.now();for(const[key,entry]of this.memory){if(entry.expiresAt!==void 0&&entry.expiresAt<=now){if(entry.timeout)clearTimeout(entry.timeout);this.memory.delete(key)}}}};CacheMemoryProvider=__decorateClass([Provider({name:"provider:cache:memory",description:"Memory-based cache provider",scope:ProviderScope.GLOBAL})],CacheMemoryProvider);import{Provider as Provider2,ProviderScope as ProviderScope2}from"@frontmcp/sdk";function createRedisClient(options){const ioredis=__require("ioredis");const Redis=ioredis.default??ioredis;return new Redis(options)}var CacheRedisProvider=class{client;constructor(options){if(options.type!=="redis"&&options.type!=="redis-client"){throw new Error("Invalid cache provider type")}if(options.type==="redis-client"){this.client=options.client;return}this.client=createRedisClient({lazyConnect:false,maxRetriesPerRequest:3,...options.config});this.client.on("connect",()=>console.log("[Redis] Connected"));this.client.on("error",err=>console.error("[Redis] Error:",err))}async setValue(key,value,ttlSeconds){const strValue=typeof value==="string"?value:JSON.stringify(value);if(ttlSeconds&&ttlSeconds>0){await this.client.set(key,strValue,"EX",ttlSeconds)}else{await this.client.set(key,strValue)}}async getValue(key,defaultValue){const raw=await this.client.get(key);if(raw===null)return defaultValue;try{return JSON.parse(raw)}catch{return raw}}async delete(key){await this.client.del(key)}async exists(key){return await this.client.exists(key)===1}async close(){await this.client.quit()}};CacheRedisProvider=__decorateClass([Provider2({name:"provider:cache:redis",description:"Redis-based cache provider",scope:ProviderScope2.GLOBAL})],CacheRedisProvider);import{Provider as Provider3,ProviderScope as ProviderScope3}from"@frontmcp/sdk";import{createVercelKvClient}from"@frontmcp/utils";var CacheVercelKvProvider=class{connection;client;keyPrefix;defaultTTL;constructor(options={}){const hasUrl=options.url!==void 0;const hasToken=options.token!==void 0;if(hasUrl!==hasToken){throw new Error(`CacheVercelKvProvider: Both 'url' and 'token' must be provided together, or neither. Received: url=${hasUrl?"provided":"missing"}, token=${hasToken?"provided":"missing"}`)}this.connection={url:options.url,token:options.token};this.keyPrefix=options.keyPrefix??"cache:";this.defaultTTL=options.defaultTTL??60*60*24}kv(){this.client??=createVercelKvClient(this.connection).catch(error=>{this.client=void 0;throw error});return this.client}prefixKey(key){return`${this.keyPrefix}${key}`}async setValue(key,value,ttlSeconds){const strValue=typeof value==="string"?value:JSON.stringify(value);const ttl=ttlSeconds??this.defaultTTL;const kv=await this.kv();if(ttl>0){await kv.set(this.prefixKey(key),strValue,{ex:ttl})}else{await kv.set(this.prefixKey(key),strValue)}}async getValue(key,defaultValue){const kv=await this.kv();const raw=await kv.get(this.prefixKey(key));if(raw===null||raw===void 0)return defaultValue;if(typeof raw==="string"){try{return JSON.parse(raw)}catch{return raw}}return raw}async delete(key){const kv=await this.kv();await kv.del(this.prefixKey(key))}async exists(key){const kv=await this.kv();return await kv.exists(this.prefixKey(key))===1}async close(){}};CacheVercelKvProvider=__decorateClass([Provider3({name:"provider:cache:vercel-kv",description:"Vercel KV-based cache provider",scope:ProviderScope3.GLOBAL})],CacheVercelKvProvider);var DEFAULT_BYPASS_HEADER="x-frontmcp-disable-cache";var BYPASS_HEADER_PREFIX="x-frontmcp-";function assertReadableBypassHeader(bypassHeader){if(bypassHeader===void 0)return;const name=bypassHeader.toLowerCase();if(name.startsWith(BYPASS_HEADER_PREFIX)&&name.length>BYPASS_HEADER_PREFIX.length)return;throw new CachePluginConfigurationError(`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".`)}var CACHE_TYPES=["memory","redis","redis-client","global-store"];function assertKnownCacheType(type){if(type===void 0||CACHE_TYPES.includes(type))return;throw new CachePluginConfigurationError(`CachePlugin type ${JSON.stringify(type)} is not supported. Supported types: ${CACHE_TYPES.map(name=>`"${name}"`).join(", ")}.`)}function matchesToolPattern(toolName,patterns){if(!patterns||patterns.length===0)return false;return patterns.some(pattern=>{if(pattern.includes("*")){const escaped=pattern.replace(/[.+?^${}()|[\]\\]/g,"\\$&");const regex=new RegExp("^"+escaped.replace(/\*/g,".*")+"$");return regex.test(toolName)}return pattern===toolName})}var CachePlugin=class extends DynamicPlugin{options;constructor(options=CachePlugin.defaultOptions){super();assertKnownCacheType(options.type);assertReadableBypassHeader(options.bypassHeader);this.options={defaultTTL:60*60*24,...options}}shouldCacheTool(toolName,cacheMetadata){if(typeof cacheMetadata==="object"&&cacheMetadata.ttl!==void 0&&cacheMetadata.ttl<=0){return false}if(cacheMetadata)return true;const patterns=this.options.toolPatterns??[];return matchesToolPattern(toolName,patterns)}shouldBypassCache(_flowCtx){const bypassHeader=this.options.bypassHeader??DEFAULT_BYPASS_HEADER;try{const contextStorage=this.get(FrontMcpContextStorage);const context=contextStorage?.getStore();const customHeaders=context?.metadata?.customHeaders;if(!customHeaders)return false;const headerKey=bypassHeader.toLowerCase();const headerValue=customHeaders[headerKey];return headerValue==="true"||headerValue==="1"}catch{return false}}getTtl(cacheMetadata){if(typeof cacheMetadata==="object"&&cacheMetadata.ttl!==void 0){return cacheMetadata.ttl}return this.options.defaultTTL??60*60*24}async willReadCache(flowCtx){const{tool,toolContext}=flowCtx.state;if(!tool||!toolContext)return;if(this.shouldBypassCache(flowCtx)){return}const{cache}=toolContext.metadata;if(!this.shouldCacheTool(tool.fullName,cache)&&!this.shouldCacheTool(tool.name,cache)||typeof toolContext.input==="undefined"){return}const hash=this.buildCacheKey(tool.fullName,toolContext,callSurfaceOf(flowCtx));if(hash===void 0)return;const cacheStore=this.get(CacheStoreToken);const cached=await cacheStore.getValue(hash);if(cached!==void 0&&cached!==null){if(isErrorResult(cached)||!tool.safeParseOutput(cached).success){await cacheStore.delete(hash);return}if(typeof cache==="object"&&cache.slideWindow){await cacheStore.setValue(hash,cached,this.getTtl(cache))}flowCtx.state.set("resultMeta",{...flowCtx.state.resultMeta,cache:"hit"});toolContext.respond(cached)}}async willWriteCache(flowCtx){const{tool,toolContext}=flowCtx.state;if(!tool||!toolContext)return;if(this.shouldBypassCache(flowCtx)){return}const{cache}=toolContext.metadata;const shouldCache=this.shouldCacheTool(tool.fullName,cache)||this.shouldCacheTool(tool.name,cache);if(!shouldCache||typeof toolContext.input==="undefined"){return}if(isErrorResult(toolContext.output)){return}const hash=this.buildCacheKey(tool.fullName,toolContext,callSurfaceOf(flowCtx));if(hash===void 0)return;const cacheStore=this.get(CacheStoreToken);await cacheStore.setValue(hash,toolContext.output,this.getTtl(cache))}resolveCallerIdentity(toolContext){const ctx=toolContext;const requestContext=ctx.tryGetContext?.();const authInfo=ctx.authInfo??requestContext?.authInfo;const issuer=verifiedIssuerOf(authInfo);const subject=authInfo?.extra?.["sub"]??authInfo?.extra?.["userId"];if(!isAnonymousSubject(subject))return subjectIdentity("user",subject,issuer);if(!isAnonymousSubject(authInfo?.clientId))return subjectIdentity("client",authInfo?.clientId,issuer);const sessionId=requestContext?.verifiedSessionId;if(sessionId)return`session:${sessionId}`;return void 0}buildCacheKey(toolFullName,toolContext,surface){const identity=this.options.keyByIdentity===false?"shared":this.resolveCallerIdentity(toolContext);if(identity===void 0)return void 0;return sha256Hex(JSON.stringify({identity,tool:toolFullName,input:stableValue(toolContext.input),surface}))}isCacheable(toolName){return matchesToolPattern(toolName,this.options.toolPatterns??[])}};__publicField(CachePlugin,"browserStores",(options,server)=>{const onRedis=options.type==="redis"||options.type==="redis-client"||options.type==="global-store"&&server.redis!==void 0&&!isVercelKvProvider(server.redis);return[{plugin:"CachePlugin",option:onRedis?`type: '${options.type}'`:void 0,memory:"type: 'memory'"}]});__publicField(CachePlugin,"dynamicProviders",options=>{const providers=[];switch(options.type){case"global-store":providers.push(storeProvider({name:"cache:global-store",provide:CacheStoreToken,inject:()=>[FrontMcpConfig],useFactory:config=>{const storeConfig=getGlobalStoreConfig("CachePlugin",config);const globalOptions=options;if(isVercelKvProvider(storeConfig)){return new CacheVercelKvProvider({url:storeConfig.url,token:storeConfig.token,keyPrefix:storeConfig.keyPrefix,defaultTTL:globalOptions.defaultTTL})}return new CacheRedisProvider({type:"redis",config:{host:storeConfig.host??"localhost",port:storeConfig.port??6379,password:storeConfig.password,db:storeConfig.db,tls:storeConfig.tls?{}:void 0,keyPrefix:storeConfig.keyPrefix},defaultTTL:globalOptions.defaultTTL})}}));break;case"redis":case"redis-client":{let store;providers.push(storeProvider({name:"cache:redis",provide:CacheStoreToken,inject:()=>[],useFactory:()=>store??=new CacheRedisProvider(options)}));break}case"memory":providers.push({name:"cache:memory",provide:CacheStoreToken,inject:()=>[],useFactory:()=>new CacheMemoryProvider(options.defaultTTL)});break}return providers});__publicField(CachePlugin,"defaultOptions",{type:"memory"});__decorateClass([ToolHook.Will("execute",{priority:1e3})],CachePlugin.prototype,"willReadCache",1);__decorateClass([ToolHook.Did("execute",{priority:1e3})],CachePlugin.prototype,"willWriteCache",1);CachePlugin=__decorateClass([Plugin({name:"cache",description:"Cache plugin for caching tool results",providers:[{name:"cache:memory",provide:CacheStoreToken,inject:()=>[],useFactory:()=>new CacheMemoryProvider(60*60*24)}]})],CachePlugin);function callSurfaceOf(flowCtx){const rawInput=flowCtx.rawInput;const surface=rawInput?.ctx?.surface;return typeof surface==="string"?surface:void 0}function verifiedIssuerOf(authInfo){const issuer=resolvePrincipal(authInfo).claims["iss"];return typeof issuer==="string"&&issuer.length>0?issuer:void 0}function subjectIdentity(kind,subject,issuer){const identity=`${kind}:${subject}`;return issuer===void 0?identity:JSON.stringify([issuer,identity])}function isErrorResult(output){if(typeof output!=="object"||output===null)return false;const result=output;return result.isError===true&&Array.isArray(result.content)}function stableValue(value){if(Array.isArray(value)){return value.map(stableValue)}if(typeof value==="object"&&value!==null){const source=value;return Object.keys(source).sort().reduce((acc,key)=>{acc[key]=stableValue(source[key]);return acc},{})}return value}export{CachePlugin,CachePluginConfigurationError,CachePlugin as default};
package/esm/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@frontmcp/plugin-cache",
3
- "version": "1.12.0",
3
+ "version": "1.12.1",
4
4
  "description": "Cache plugin for FrontMCP: answers repeated tool calls from memory, Redis or Vercel KV instead of running the tool again",
5
5
  "author": "AgentFront <info@agentfront.dev>",
6
6
  "license": "Apache-2.0",
@@ -49,8 +49,8 @@
49
49
  }
50
50
  },
51
51
  "dependencies": {
52
- "@frontmcp/sdk": "1.12.0",
53
- "@frontmcp/utils": "1.12.0",
52
+ "@frontmcp/sdk": "1.12.1",
53
+ "@frontmcp/utils": "1.12.1",
54
54
  "ioredis": "^5.8.0"
55
55
  },
56
56
  "peerDependencies": {
package/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var __decorateClass=(decorators,target,key,kind)=>{var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target;for(var i=decorators.length-1,decorator;i>=0;i--)if(decorator=decorators[i])result=(kind?decorator(target,key,result):decorator(result))||result;if(kind&&result)__defProp(target,key,result);return result};var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);var index_exports={};__export(index_exports,{CachePlugin:()=>CachePlugin,CachePluginConfigurationError:()=>CachePluginConfigurationError,default:()=>CachePlugin});module.exports=__toCommonJS(index_exports);var import_sdk4=require("@frontmcp/sdk");var import_utils2=require("@frontmcp/utils");var CachePluginConfigurationError=class extends Error{constructor(message){super(message);this.name="CachePluginConfigurationError"}};var CacheStoreToken=Symbol("plugin:cache:store");var import_sdk=require("@frontmcp/sdk");var MAX_TIMEOUT_MS=2**31-1;var CacheMemoryProvider=class{memory=new Map;sweeper;constructor(sweepIntervalTTL=60){this.sweeper=setInterval(()=>this.sweep(),sweepIntervalTTL*1e3);this.sweeper.unref?.()}async setValue(key,value,ttlSeconds){const strValue=typeof value==="string"?value:JSON.stringify(value);const existing=this.memory.get(key);if(existing?.timeout)clearTimeout(existing.timeout);const entry={value:strValue};if(ttlSeconds&&ttlSeconds>0){const ttlMs=ttlSeconds*1e3;entry.expiresAt=Date.now()+ttlMs;if(ttlMs<=MAX_TIMEOUT_MS){entry.timeout=setTimeout(()=>{const e=this.memory.get(key);if(e&&e.expiresAt&&e.expiresAt<=Date.now()){this.memory.delete(key)}},ttlMs);entry.timeout.unref?.()}}this.memory.set(key,entry)}async getValue(key,defaultValue){const entry=this.memory.get(key);if(!entry)return defaultValue;if(this.isExpired(entry)){await this.delete(key);return defaultValue}const raw=entry.value;try{return JSON.parse(raw)}catch{return raw}}async delete(key){const entry=this.memory.get(key);if(entry?.timeout)clearTimeout(entry.timeout);this.memory.delete(key)}async exists(key){const entry=this.memory.get(key);if(!entry)return false;if(this.isExpired(entry)){await this.delete(key);return false}return true}async close(){if(this.sweeper)clearInterval(this.sweeper);for(const[,entry]of this.memory){if(entry.timeout)clearTimeout(entry.timeout)}this.memory.clear()}isExpired(entry){return entry.expiresAt!==void 0&&entry.expiresAt<=Date.now()}sweep(){const now=Date.now();for(const[key,entry]of this.memory){if(entry.expiresAt!==void 0&&entry.expiresAt<=now){if(entry.timeout)clearTimeout(entry.timeout);this.memory.delete(key)}}}};CacheMemoryProvider=__decorateClass([(0,import_sdk.Provider)({name:"provider:cache:memory",description:"Memory-based cache provider",scope:import_sdk.ProviderScope.GLOBAL})],CacheMemoryProvider);var import_sdk2=require("@frontmcp/sdk");function createRedisClient(options){const ioredis=require("ioredis");const Redis=ioredis.default??ioredis;return new Redis(options)}var CacheRedisProvider=class{client;constructor(options){if(options.type!=="redis"&&options.type!=="redis-client"){throw new Error("Invalid cache provider type")}if(options.type==="redis-client"){this.client=options.client;return}this.client=createRedisClient({lazyConnect:false,maxRetriesPerRequest:3,...options.config});this.client.on("connect",()=>console.log("[Redis] Connected"));this.client.on("error",err=>console.error("[Redis] Error:",err))}async setValue(key,value,ttlSeconds){const strValue=typeof value==="string"?value:JSON.stringify(value);if(ttlSeconds&&ttlSeconds>0){await this.client.set(key,strValue,"EX",ttlSeconds)}else{await this.client.set(key,strValue)}}async getValue(key,defaultValue){const raw=await this.client.get(key);if(raw===null)return defaultValue;try{return JSON.parse(raw)}catch{return raw}}async delete(key){await this.client.del(key)}async exists(key){return await this.client.exists(key)===1}async close(){await this.client.quit()}};CacheRedisProvider=__decorateClass([(0,import_sdk2.Provider)({name:"provider:cache:redis",description:"Redis-based cache provider",scope:import_sdk2.ProviderScope.GLOBAL})],CacheRedisProvider);var import_sdk3=require("@frontmcp/sdk");var import_utils=require("@frontmcp/utils");var CacheVercelKvProvider=class{connection;client;keyPrefix;defaultTTL;constructor(options={}){const hasUrl=options.url!==void 0;const hasToken=options.token!==void 0;if(hasUrl!==hasToken){throw new Error(`CacheVercelKvProvider: Both 'url' and 'token' must be provided together, or neither. Received: url=${hasUrl?"provided":"missing"}, token=${hasToken?"provided":"missing"}`)}this.connection={url:options.url,token:options.token};this.keyPrefix=options.keyPrefix??"cache:";this.defaultTTL=options.defaultTTL??60*60*24}kv(){this.client??=(0,import_utils.createVercelKvClient)(this.connection).catch(error=>{this.client=void 0;throw error});return this.client}prefixKey(key){return`${this.keyPrefix}${key}`}async setValue(key,value,ttlSeconds){const strValue=typeof value==="string"?value:JSON.stringify(value);const ttl=ttlSeconds??this.defaultTTL;const kv=await this.kv();if(ttl>0){await kv.set(this.prefixKey(key),strValue,{ex:ttl})}else{await kv.set(this.prefixKey(key),strValue)}}async getValue(key,defaultValue){const kv=await this.kv();const raw=await kv.get(this.prefixKey(key));if(raw===null||raw===void 0)return defaultValue;if(typeof raw==="string"){try{return JSON.parse(raw)}catch{return raw}}return raw}async delete(key){const kv=await this.kv();await kv.del(this.prefixKey(key))}async exists(key){const kv=await this.kv();return await kv.exists(this.prefixKey(key))===1}async close(){}};CacheVercelKvProvider=__decorateClass([(0,import_sdk3.Provider)({name:"provider:cache:vercel-kv",description:"Vercel KV-based cache provider",scope:import_sdk3.ProviderScope.GLOBAL})],CacheVercelKvProvider);var DEFAULT_BYPASS_HEADER="x-frontmcp-disable-cache";var BYPASS_HEADER_PREFIX="x-frontmcp-";function assertReadableBypassHeader(bypassHeader){if(bypassHeader===void 0)return;const name=bypassHeader.toLowerCase();if(name.startsWith(BYPASS_HEADER_PREFIX)&&name.length>BYPASS_HEADER_PREFIX.length)return;throw new CachePluginConfigurationError(`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".`)}var CACHE_TYPES=["memory","redis","redis-client","global-store"];function assertKnownCacheType(type){if(type===void 0||CACHE_TYPES.includes(type))return;throw new CachePluginConfigurationError(`CachePlugin type ${JSON.stringify(type)} is not supported. Supported types: ${CACHE_TYPES.map(name=>`"${name}"`).join(", ")}.`)}function matchesToolPattern(toolName,patterns){if(!patterns||patterns.length===0)return false;return patterns.some(pattern=>{if(pattern.includes("*")){const escaped=pattern.replace(/[.+?^${}()|[\]\\]/g,"\\$&");const regex=new RegExp("^"+escaped.replace(/\*/g,".*")+"$");return regex.test(toolName)}return pattern===toolName})}var CachePlugin=class extends import_sdk4.DynamicPlugin{options;constructor(options=CachePlugin.defaultOptions){super();assertKnownCacheType(options.type);assertReadableBypassHeader(options.bypassHeader);this.options={defaultTTL:60*60*24,...options}}shouldCacheTool(toolName,cacheMetadata){if(typeof cacheMetadata==="object"&&cacheMetadata.ttl!==void 0&&cacheMetadata.ttl<=0){return false}if(cacheMetadata)return true;const patterns=this.options.toolPatterns??[];return matchesToolPattern(toolName,patterns)}shouldBypassCache(_flowCtx){const bypassHeader=this.options.bypassHeader??DEFAULT_BYPASS_HEADER;try{const contextStorage=this.get(import_sdk4.FrontMcpContextStorage);const context=contextStorage?.getStore();const customHeaders=context?.metadata?.customHeaders;if(!customHeaders)return false;const headerKey=bypassHeader.toLowerCase();const headerValue=customHeaders[headerKey];return headerValue==="true"||headerValue==="1"}catch{return false}}getTtl(cacheMetadata){if(typeof cacheMetadata==="object"&&cacheMetadata.ttl!==void 0){return cacheMetadata.ttl}return this.options.defaultTTL??60*60*24}async willReadCache(flowCtx){const{tool,toolContext}=flowCtx.state;if(!tool||!toolContext)return;if(this.shouldBypassCache(flowCtx)){return}const{cache}=toolContext.metadata;if(!this.shouldCacheTool(tool.fullName,cache)&&!this.shouldCacheTool(tool.name,cache)||typeof toolContext.input==="undefined"){return}const hash=this.buildCacheKey(tool.fullName,toolContext);if(hash===void 0)return;const cacheStore=this.get(CacheStoreToken);const cached=await cacheStore.getValue(hash);if(cached!==void 0&&cached!==null){if(isErrorResult(cached)||!tool.safeParseOutput(cached).success){await cacheStore.delete(hash);return}if(typeof cache==="object"&&cache.slideWindow){await cacheStore.setValue(hash,cached,this.getTtl(cache))}flowCtx.state.set("resultMeta",{...flowCtx.state.resultMeta,cache:"hit"});toolContext.respond(cached)}}async willWriteCache(flowCtx){const{tool,toolContext}=flowCtx.state;if(!tool||!toolContext)return;if(this.shouldBypassCache(flowCtx)){return}const{cache}=toolContext.metadata;const shouldCache=this.shouldCacheTool(tool.fullName,cache)||this.shouldCacheTool(tool.name,cache);if(!shouldCache||typeof toolContext.input==="undefined"){return}if(isErrorResult(toolContext.output)){return}const hash=this.buildCacheKey(tool.fullName,toolContext);if(hash===void 0)return;const cacheStore=this.get(CacheStoreToken);await cacheStore.setValue(hash,toolContext.output,this.getTtl(cache))}resolveCallerIdentity(toolContext){const ctx=toolContext;const requestContext=ctx.tryGetContext?.();const authInfo=ctx.authInfo??requestContext?.authInfo;const subject=authInfo?.extra?.["sub"]??authInfo?.extra?.["userId"];if(!(0,import_sdk4.isAnonymousSubject)(subject))return`user:${subject}`;if(!(0,import_sdk4.isAnonymousSubject)(authInfo?.clientId))return`client:${authInfo?.clientId}`;const sessionId=requestContext?.verifiedSessionId;if(sessionId)return`session:${sessionId}`;return void 0}buildCacheKey(toolFullName,toolContext){const identity=this.options.keyByIdentity===false?"shared":this.resolveCallerIdentity(toolContext);if(identity===void 0)return void 0;return(0,import_utils2.sha256Hex)(JSON.stringify({identity,tool:toolFullName,input:stableValue(toolContext.input)}))}isCacheable(toolName){return matchesToolPattern(toolName,this.options.toolPatterns??[])}};__publicField(CachePlugin,"browserStores",(options,server)=>{const onRedis=options.type==="redis"||options.type==="redis-client"||options.type==="global-store"&&server.redis!==void 0&&!(0,import_sdk4.isVercelKvProvider)(server.redis);return[{plugin:"CachePlugin",option:onRedis?`type: '${options.type}'`:void 0,memory:"type: 'memory'"}]});__publicField(CachePlugin,"dynamicProviders",options=>{const providers=[];switch(options.type){case"global-store":providers.push((0,import_sdk4.storeProvider)({name:"cache:global-store",provide:CacheStoreToken,inject:()=>[import_sdk4.FrontMcpConfig],useFactory:config=>{const storeConfig=(0,import_sdk4.getGlobalStoreConfig)("CachePlugin",config);const globalOptions=options;if((0,import_sdk4.isVercelKvProvider)(storeConfig)){return new CacheVercelKvProvider({url:storeConfig.url,token:storeConfig.token,keyPrefix:storeConfig.keyPrefix,defaultTTL:globalOptions.defaultTTL})}return new CacheRedisProvider({type:"redis",config:{host:storeConfig.host??"localhost",port:storeConfig.port??6379,password:storeConfig.password,db:storeConfig.db},defaultTTL:globalOptions.defaultTTL})}}));break;case"redis":case"redis-client":{let store;providers.push((0,import_sdk4.storeProvider)({name:"cache:redis",provide:CacheStoreToken,inject:()=>[],useFactory:()=>store??=new CacheRedisProvider(options)}));break}case"memory":providers.push({name:"cache:memory",provide:CacheStoreToken,inject:()=>[],useFactory:()=>new CacheMemoryProvider(options.defaultTTL)});break}return providers});__publicField(CachePlugin,"defaultOptions",{type:"memory"});__decorateClass([import_sdk4.ToolHook.Will("execute",{priority:1e3})],CachePlugin.prototype,"willReadCache",1);__decorateClass([import_sdk4.ToolHook.Did("execute",{priority:1e3})],CachePlugin.prototype,"willWriteCache",1);CachePlugin=__decorateClass([(0,import_sdk4.Plugin)({name:"cache",description:"Cache plugin for caching tool results",providers:[{name:"cache:memory",provide:CacheStoreToken,inject:()=>[],useFactory:()=>new CacheMemoryProvider(60*60*24)}]})],CachePlugin);function isErrorResult(output){if(typeof output!=="object"||output===null)return false;const result=output;return result.isError===true&&Array.isArray(result.content)}function stableValue(value){if(Array.isArray(value)){return value.map(stableValue)}if(typeof value==="object"&&value!==null){const source=value;return Object.keys(source).sort().reduce((acc,key)=>{acc[key]=stableValue(source[key]);return acc},{})}return value}0&&(module.exports={CachePlugin,CachePluginConfigurationError});
1
+ "use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var __decorateClass=(decorators,target,key,kind)=>{var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target;for(var i=decorators.length-1,decorator;i>=0;i--)if(decorator=decorators[i])result=(kind?decorator(target,key,result):decorator(result))||result;if(kind&&result)__defProp(target,key,result);return result};var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);var index_exports={};__export(index_exports,{CachePlugin:()=>CachePlugin,CachePluginConfigurationError:()=>CachePluginConfigurationError,default:()=>CachePlugin});module.exports=__toCommonJS(index_exports);var import_sdk4=require("@frontmcp/sdk");var import_utils2=require("@frontmcp/utils");var CachePluginConfigurationError=class extends Error{constructor(message){super(message);this.name="CachePluginConfigurationError"}};var CacheStoreToken=Symbol("plugin:cache:store");var import_sdk=require("@frontmcp/sdk");var MAX_TIMEOUT_MS=2**31-1;var CacheMemoryProvider=class{memory=new Map;sweeper;constructor(sweepIntervalTTL=60){this.sweeper=setInterval(()=>this.sweep(),sweepIntervalTTL*1e3);this.sweeper.unref?.()}async setValue(key,value,ttlSeconds){const strValue=typeof value==="string"?value:JSON.stringify(value);const existing=this.memory.get(key);if(existing?.timeout)clearTimeout(existing.timeout);const entry={value:strValue};if(ttlSeconds&&ttlSeconds>0){const ttlMs=ttlSeconds*1e3;entry.expiresAt=Date.now()+ttlMs;if(ttlMs<=MAX_TIMEOUT_MS){entry.timeout=setTimeout(()=>{const e=this.memory.get(key);if(e&&e.expiresAt&&e.expiresAt<=Date.now()){this.memory.delete(key)}},ttlMs);entry.timeout.unref?.()}}this.memory.set(key,entry)}async getValue(key,defaultValue){const entry=this.memory.get(key);if(!entry)return defaultValue;if(this.isExpired(entry)){await this.delete(key);return defaultValue}const raw=entry.value;try{return JSON.parse(raw)}catch{return raw}}async delete(key){const entry=this.memory.get(key);if(entry?.timeout)clearTimeout(entry.timeout);this.memory.delete(key)}async exists(key){const entry=this.memory.get(key);if(!entry)return false;if(this.isExpired(entry)){await this.delete(key);return false}return true}async close(){if(this.sweeper)clearInterval(this.sweeper);for(const[,entry]of this.memory){if(entry.timeout)clearTimeout(entry.timeout)}this.memory.clear()}isExpired(entry){return entry.expiresAt!==void 0&&entry.expiresAt<=Date.now()}sweep(){const now=Date.now();for(const[key,entry]of this.memory){if(entry.expiresAt!==void 0&&entry.expiresAt<=now){if(entry.timeout)clearTimeout(entry.timeout);this.memory.delete(key)}}}};CacheMemoryProvider=__decorateClass([(0,import_sdk.Provider)({name:"provider:cache:memory",description:"Memory-based cache provider",scope:import_sdk.ProviderScope.GLOBAL})],CacheMemoryProvider);var import_sdk2=require("@frontmcp/sdk");function createRedisClient(options){const ioredis=require("ioredis");const Redis=ioredis.default??ioredis;return new Redis(options)}var CacheRedisProvider=class{client;constructor(options){if(options.type!=="redis"&&options.type!=="redis-client"){throw new Error("Invalid cache provider type")}if(options.type==="redis-client"){this.client=options.client;return}this.client=createRedisClient({lazyConnect:false,maxRetriesPerRequest:3,...options.config});this.client.on("connect",()=>console.log("[Redis] Connected"));this.client.on("error",err=>console.error("[Redis] Error:",err))}async setValue(key,value,ttlSeconds){const strValue=typeof value==="string"?value:JSON.stringify(value);if(ttlSeconds&&ttlSeconds>0){await this.client.set(key,strValue,"EX",ttlSeconds)}else{await this.client.set(key,strValue)}}async getValue(key,defaultValue){const raw=await this.client.get(key);if(raw===null)return defaultValue;try{return JSON.parse(raw)}catch{return raw}}async delete(key){await this.client.del(key)}async exists(key){return await this.client.exists(key)===1}async close(){await this.client.quit()}};CacheRedisProvider=__decorateClass([(0,import_sdk2.Provider)({name:"provider:cache:redis",description:"Redis-based cache provider",scope:import_sdk2.ProviderScope.GLOBAL})],CacheRedisProvider);var import_sdk3=require("@frontmcp/sdk");var import_utils=require("@frontmcp/utils");var CacheVercelKvProvider=class{connection;client;keyPrefix;defaultTTL;constructor(options={}){const hasUrl=options.url!==void 0;const hasToken=options.token!==void 0;if(hasUrl!==hasToken){throw new Error(`CacheVercelKvProvider: Both 'url' and 'token' must be provided together, or neither. Received: url=${hasUrl?"provided":"missing"}, token=${hasToken?"provided":"missing"}`)}this.connection={url:options.url,token:options.token};this.keyPrefix=options.keyPrefix??"cache:";this.defaultTTL=options.defaultTTL??60*60*24}kv(){this.client??=(0,import_utils.createVercelKvClient)(this.connection).catch(error=>{this.client=void 0;throw error});return this.client}prefixKey(key){return`${this.keyPrefix}${key}`}async setValue(key,value,ttlSeconds){const strValue=typeof value==="string"?value:JSON.stringify(value);const ttl=ttlSeconds??this.defaultTTL;const kv=await this.kv();if(ttl>0){await kv.set(this.prefixKey(key),strValue,{ex:ttl})}else{await kv.set(this.prefixKey(key),strValue)}}async getValue(key,defaultValue){const kv=await this.kv();const raw=await kv.get(this.prefixKey(key));if(raw===null||raw===void 0)return defaultValue;if(typeof raw==="string"){try{return JSON.parse(raw)}catch{return raw}}return raw}async delete(key){const kv=await this.kv();await kv.del(this.prefixKey(key))}async exists(key){const kv=await this.kv();return await kv.exists(this.prefixKey(key))===1}async close(){}};CacheVercelKvProvider=__decorateClass([(0,import_sdk3.Provider)({name:"provider:cache:vercel-kv",description:"Vercel KV-based cache provider",scope:import_sdk3.ProviderScope.GLOBAL})],CacheVercelKvProvider);var DEFAULT_BYPASS_HEADER="x-frontmcp-disable-cache";var BYPASS_HEADER_PREFIX="x-frontmcp-";function assertReadableBypassHeader(bypassHeader){if(bypassHeader===void 0)return;const name=bypassHeader.toLowerCase();if(name.startsWith(BYPASS_HEADER_PREFIX)&&name.length>BYPASS_HEADER_PREFIX.length)return;throw new CachePluginConfigurationError(`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".`)}var CACHE_TYPES=["memory","redis","redis-client","global-store"];function assertKnownCacheType(type){if(type===void 0||CACHE_TYPES.includes(type))return;throw new CachePluginConfigurationError(`CachePlugin type ${JSON.stringify(type)} is not supported. Supported types: ${CACHE_TYPES.map(name=>`"${name}"`).join(", ")}.`)}function matchesToolPattern(toolName,patterns){if(!patterns||patterns.length===0)return false;return patterns.some(pattern=>{if(pattern.includes("*")){const escaped=pattern.replace(/[.+?^${}()|[\]\\]/g,"\\$&");const regex=new RegExp("^"+escaped.replace(/\*/g,".*")+"$");return regex.test(toolName)}return pattern===toolName})}var CachePlugin=class extends import_sdk4.DynamicPlugin{options;constructor(options=CachePlugin.defaultOptions){super();assertKnownCacheType(options.type);assertReadableBypassHeader(options.bypassHeader);this.options={defaultTTL:60*60*24,...options}}shouldCacheTool(toolName,cacheMetadata){if(typeof cacheMetadata==="object"&&cacheMetadata.ttl!==void 0&&cacheMetadata.ttl<=0){return false}if(cacheMetadata)return true;const patterns=this.options.toolPatterns??[];return matchesToolPattern(toolName,patterns)}shouldBypassCache(_flowCtx){const bypassHeader=this.options.bypassHeader??DEFAULT_BYPASS_HEADER;try{const contextStorage=this.get(import_sdk4.FrontMcpContextStorage);const context=contextStorage?.getStore();const customHeaders=context?.metadata?.customHeaders;if(!customHeaders)return false;const headerKey=bypassHeader.toLowerCase();const headerValue=customHeaders[headerKey];return headerValue==="true"||headerValue==="1"}catch{return false}}getTtl(cacheMetadata){if(typeof cacheMetadata==="object"&&cacheMetadata.ttl!==void 0){return cacheMetadata.ttl}return this.options.defaultTTL??60*60*24}async willReadCache(flowCtx){const{tool,toolContext}=flowCtx.state;if(!tool||!toolContext)return;if(this.shouldBypassCache(flowCtx)){return}const{cache}=toolContext.metadata;if(!this.shouldCacheTool(tool.fullName,cache)&&!this.shouldCacheTool(tool.name,cache)||typeof toolContext.input==="undefined"){return}const hash=this.buildCacheKey(tool.fullName,toolContext,callSurfaceOf(flowCtx));if(hash===void 0)return;const cacheStore=this.get(CacheStoreToken);const cached=await cacheStore.getValue(hash);if(cached!==void 0&&cached!==null){if(isErrorResult(cached)||!tool.safeParseOutput(cached).success){await cacheStore.delete(hash);return}if(typeof cache==="object"&&cache.slideWindow){await cacheStore.setValue(hash,cached,this.getTtl(cache))}flowCtx.state.set("resultMeta",{...flowCtx.state.resultMeta,cache:"hit"});toolContext.respond(cached)}}async willWriteCache(flowCtx){const{tool,toolContext}=flowCtx.state;if(!tool||!toolContext)return;if(this.shouldBypassCache(flowCtx)){return}const{cache}=toolContext.metadata;const shouldCache=this.shouldCacheTool(tool.fullName,cache)||this.shouldCacheTool(tool.name,cache);if(!shouldCache||typeof toolContext.input==="undefined"){return}if(isErrorResult(toolContext.output)){return}const hash=this.buildCacheKey(tool.fullName,toolContext,callSurfaceOf(flowCtx));if(hash===void 0)return;const cacheStore=this.get(CacheStoreToken);await cacheStore.setValue(hash,toolContext.output,this.getTtl(cache))}resolveCallerIdentity(toolContext){const ctx=toolContext;const requestContext=ctx.tryGetContext?.();const authInfo=ctx.authInfo??requestContext?.authInfo;const issuer=verifiedIssuerOf(authInfo);const subject=authInfo?.extra?.["sub"]??authInfo?.extra?.["userId"];if(!(0,import_sdk4.isAnonymousSubject)(subject))return subjectIdentity("user",subject,issuer);if(!(0,import_sdk4.isAnonymousSubject)(authInfo?.clientId))return subjectIdentity("client",authInfo?.clientId,issuer);const sessionId=requestContext?.verifiedSessionId;if(sessionId)return`session:${sessionId}`;return void 0}buildCacheKey(toolFullName,toolContext,surface){const identity=this.options.keyByIdentity===false?"shared":this.resolveCallerIdentity(toolContext);if(identity===void 0)return void 0;return(0,import_utils2.sha256Hex)(JSON.stringify({identity,tool:toolFullName,input:stableValue(toolContext.input),surface}))}isCacheable(toolName){return matchesToolPattern(toolName,this.options.toolPatterns??[])}};__publicField(CachePlugin,"browserStores",(options,server)=>{const onRedis=options.type==="redis"||options.type==="redis-client"||options.type==="global-store"&&server.redis!==void 0&&!(0,import_sdk4.isVercelKvProvider)(server.redis);return[{plugin:"CachePlugin",option:onRedis?`type: '${options.type}'`:void 0,memory:"type: 'memory'"}]});__publicField(CachePlugin,"dynamicProviders",options=>{const providers=[];switch(options.type){case"global-store":providers.push((0,import_sdk4.storeProvider)({name:"cache:global-store",provide:CacheStoreToken,inject:()=>[import_sdk4.FrontMcpConfig],useFactory:config=>{const storeConfig=(0,import_sdk4.getGlobalStoreConfig)("CachePlugin",config);const globalOptions=options;if((0,import_sdk4.isVercelKvProvider)(storeConfig)){return new CacheVercelKvProvider({url:storeConfig.url,token:storeConfig.token,keyPrefix:storeConfig.keyPrefix,defaultTTL:globalOptions.defaultTTL})}return new CacheRedisProvider({type:"redis",config:{host:storeConfig.host??"localhost",port:storeConfig.port??6379,password:storeConfig.password,db:storeConfig.db,tls:storeConfig.tls?{}:void 0,keyPrefix:storeConfig.keyPrefix},defaultTTL:globalOptions.defaultTTL})}}));break;case"redis":case"redis-client":{let store;providers.push((0,import_sdk4.storeProvider)({name:"cache:redis",provide:CacheStoreToken,inject:()=>[],useFactory:()=>store??=new CacheRedisProvider(options)}));break}case"memory":providers.push({name:"cache:memory",provide:CacheStoreToken,inject:()=>[],useFactory:()=>new CacheMemoryProvider(options.defaultTTL)});break}return providers});__publicField(CachePlugin,"defaultOptions",{type:"memory"});__decorateClass([import_sdk4.ToolHook.Will("execute",{priority:1e3})],CachePlugin.prototype,"willReadCache",1);__decorateClass([import_sdk4.ToolHook.Did("execute",{priority:1e3})],CachePlugin.prototype,"willWriteCache",1);CachePlugin=__decorateClass([(0,import_sdk4.Plugin)({name:"cache",description:"Cache plugin for caching tool results",providers:[{name:"cache:memory",provide:CacheStoreToken,inject:()=>[],useFactory:()=>new CacheMemoryProvider(60*60*24)}]})],CachePlugin);function callSurfaceOf(flowCtx){const rawInput=flowCtx.rawInput;const surface=rawInput?.ctx?.surface;return typeof surface==="string"?surface:void 0}function verifiedIssuerOf(authInfo){const issuer=(0,import_sdk4.resolvePrincipal)(authInfo).claims["iss"];return typeof issuer==="string"&&issuer.length>0?issuer:void 0}function subjectIdentity(kind,subject,issuer){const identity=`${kind}:${subject}`;return issuer===void 0?identity:JSON.stringify([issuer,identity])}function isErrorResult(output){if(typeof output!=="object"||output===null)return false;const result=output;return result.isError===true&&Array.isArray(result.content)}function stableValue(value){if(Array.isArray(value)){return value.map(stableValue)}if(typeof value==="object"&&value!==null){const source=value;return Object.keys(source).sort().reduce((acc,key)=>{acc[key]=stableValue(source[key]);return acc},{})}return value}0&&(module.exports={CachePlugin,CachePluginConfigurationError});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@frontmcp/plugin-cache",
3
- "version": "1.12.0",
3
+ "version": "1.12.1",
4
4
  "description": "Cache plugin for FrontMCP: answers repeated tool calls from memory, Redis or Vercel KV instead of running the tool again",
5
5
  "author": "AgentFront <info@agentfront.dev>",
6
6
  "license": "Apache-2.0",
@@ -49,8 +49,8 @@
49
49
  }
50
50
  },
51
51
  "dependencies": {
52
- "@frontmcp/sdk": "1.12.0",
53
- "@frontmcp/utils": "1.12.0",
52
+ "@frontmcp/sdk": "1.12.1",
53
+ "@frontmcp/utils": "1.12.1",
54
54
  "ioredis": "^5.8.0"
55
55
  },
56
56
  "peerDependencies": {