@frontmcp/plugin-cache 1.13.2 → 1.14.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -86,13 +86,17 @@ subject, so one user never gets another user's cached answer.
86
86
  | `keyByIdentity` | `true` | Keep separate entries per caller. See [Who gets which entry](#who-gets-which-entry). |
87
87
  | `toolPatterns` | `[]` | Cache these tools too, without `cache` in their metadata. A tool name or `<app id>:<tool name>`, where `*` matches anything: `'catalog:*'`, `'get_*'`. |
88
88
  | `bypassHeader` | `'x-frontmcp-disable-cache'` | A request header that skips the cache for that call when its value is `true` or `1`. It must start with `x-frontmcp-`, or `init()` throws a `CachePluginConfigurationError`. |
89
- | `config` | | With `type: 'redis'`: `{ host, port, password?, db? }`. |
90
- | `client` | | With `type: 'redis-client'`: an `ioredis` client you created. |
89
+ | `maxEntries` | `10000` | With `type: 'memory'`: the most entries kept. Past it, the least recently used entry is removed. `0` keeps any number. |
90
+ | `maxBytes` | `67108864` (64 MiB) | With `type: 'memory'`: the most bytes of keys and values kept, as UTF-8. Past it, the least recently used entries are removed. `0` keeps any size. |
91
+ | `config` | | With `type: 'redis'`: `{ host, port, password?, db?, tls?, keyPrefix?, cluster? }`. `cluster: true` makes the host a Redis Cluster endpoint. |
92
+ | `client` | | With `type: 'redis-client'`: a client you created: ioredis `Redis` or `Cluster`, or a node-redis client or cluster. The plugin never closes it. |
93
+ | `keyPrefix` | | With `type: 'redis-client'`: put on every cache key, so servers that share one Redis keep their entries apart. `'global-store'` takes the server's `redis.keyPrefix` in every form. |
91
94
 
92
95
  ## Stores
93
96
 
94
- `'memory'` keeps entries in the server's process: they're lost on restart and aren't shared between instances. For
95
- Redis, let the plugin connect:
97
+ `'memory'` keeps entries in the server's process: they're lost on restart and aren't shared between instances. It
98
+ keeps at most 10,000 entries and 64 MiB; set `maxEntries` and `maxBytes` to change that. For Redis, let the plugin
99
+ connect:
96
100
 
97
101
  ```ts
98
102
  CachePlugin.init({
@@ -102,7 +106,17 @@ CachePlugin.init({
102
106
  });
103
107
  ```
104
108
 
105
- Or pass a client you already have:
109
+ On a Redis Cluster (AWS ElastiCache with cluster mode on), add `cluster: true`:
110
+
111
+ ```ts
112
+ CachePlugin.init({
113
+ type: 'redis',
114
+ config: { host: process.env.REDIS_HOST, port: 6379, password: process.env.REDIS_AUTH_TOKEN, tls: {}, cluster: true },
115
+ });
116
+ ```
117
+
118
+ Or pass a client you already have (ioredis or node-redis, single node or cluster). It stays yours: `close()` leaves it
119
+ open, so close it yourself after the server stops.
106
120
 
107
121
  ```ts
108
122
  import { Redis } from 'ioredis';
@@ -1 +1 @@
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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Redis as RedisClient, RedisOptions } from 'ioredis';
2
+ import type { RedisClientInput, RedisClusterOption } from '@frontmcp/utils';
2
3
  declare global {
3
4
  interface ExtendFrontMcpToolMetadata {
4
5
  cache?: CachePluginToolOptions | true;
@@ -72,7 +73,13 @@ export interface BaseCachePluginOptions {
72
73
  }
73
74
  export interface RedisClientCachePluginOptions extends BaseCachePluginOptions {
74
75
  type: 'redis-client';
75
- client: RedisClient;
76
+ /**
77
+ * A Redis client you made: an ioredis `Redis` or `Cluster`, a node-redis client or cluster, or a
78
+ * FrontMcpRedisClient. The plugin never closes it; you do, after the server stops.
79
+ */
80
+ client: RedisClient | RedisClientInput;
81
+ /** Prefix of every cache key, so servers that share one Redis database keep their entries apart. */
82
+ keyPrefix?: string;
76
83
  }
77
84
  export interface RedisCachePluginOptions extends BaseCachePluginOptions {
78
85
  type: 'redis';
@@ -85,10 +92,28 @@ export interface RedisCachePluginOptions extends BaseCachePluginOptions {
85
92
  tls?: RedisOptions['tls'];
86
93
  /** Prefix of every cache key, so servers that share one Redis database keep their entries apart. */
87
94
  keyPrefix?: string;
95
+ /**
96
+ * The host is a Redis Cluster endpoint (`true`, e.g. an AWS ElastiCache configuration endpoint),
97
+ * or `{ nodes, options }` with seed nodes and ioredis ClusterOptions. A cluster has database 0 only.
98
+ */
99
+ cluster?: RedisClusterOption;
88
100
  };
89
101
  }
90
102
  export type MemoryCachePluginOptions = BaseCachePluginOptions & {
91
103
  type: 'memory';
104
+ /**
105
+ * Most entries the store keeps. When a new entry goes past it, the least recently used entry is
106
+ * removed. `0` keeps any number of entries.
107
+ * @default 10000
108
+ */
109
+ maxEntries?: number;
110
+ /**
111
+ * Most bytes (UTF-8 length of keys and values) the store keeps. When a new entry goes past it,
112
+ * the least recently used entries are removed; a single entry larger than this is not stored.
113
+ * `0` keeps any size.
114
+ * @default 67108864 (64 MiB)
115
+ */
116
+ maxBytes?: number;
92
117
  };
93
118
  /**
94
119
  * Use global store configuration from @FrontMcp decorator.
@@ -1 +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AAkB,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 @@
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
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};
1
+ 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 __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 DEFAULT_MEMORY_CACHE_MAX_ENTRIES=1e4;var DEFAULT_MEMORY_CACHE_MAX_BYTES=64*1024*1024;var MAX_TIMEOUT_MS=2**31-1;function isLowSurrogate(code){return code>=56320&&code<=57343}function utf8Length(text){let bytes=0;for(let index=0;index<text.length;index+=1){const code=text.charCodeAt(index);if(code<128)bytes+=1;else if(code<2048)bytes+=2;else if(code>=55296&&code<=56319&&isLowSurrogate(text.charCodeAt(index+1))){bytes+=4;index+=1}else bytes+=3}return bytes}function readLimit(name,value,fallback){if(value===void 0)return fallback;if(!Number.isInteger(value)||value<0){throw new TypeError(`CacheMemoryProvider ${name} must be a whole number of 0 or more, got ${String(value)}.`)}return value}var CacheMemoryProvider=class{memory=new Map;maxEntries;maxBytes;totalBytes=0;sweeper;constructor(options={}){const resolved=typeof options==="number"?{sweepIntervalSeconds:options}:options;this.maxEntries=readLimit("maxEntries",resolved.maxEntries,DEFAULT_MEMORY_CACHE_MAX_ENTRIES);this.maxBytes=readLimit("maxBytes",resolved.maxBytes,DEFAULT_MEMORY_CACHE_MAX_BYTES);this.sweeper=setInterval(()=>this.sweep(),(resolved.sweepIntervalSeconds??60)*1e3);this.sweeper.unref?.()}async setValue(key,value,ttlSeconds){const strValue=typeof value==="string"?value:JSON.stringify(value);this.remove(key);if(strValue===void 0)return;const entry={value:strValue,bytes:utf8Length(key)+utf8Length(strValue)};if(this.maxBytes>0&&entry.bytes>this.maxBytes)return;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.remove(key)}},ttlMs);entry.timeout.unref?.()}}this.memory.set(key,entry);this.totalBytes+=entry.bytes;this.evictOverLimits()}async getValue(key,defaultValue){const entry=this.memory.get(key);if(!entry)return defaultValue;if(this.isExpired(entry)){await this.delete(key);return defaultValue}this.markUsed(key,entry);const raw=entry.value;try{return JSON.parse(raw)}catch{return raw}}async delete(key){this.remove(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();this.totalBytes=0}getStats(){return{entries:this.memory.size,bytes:this.totalBytes,maxEntries:this.maxEntries,maxBytes:this.maxBytes}}isExpired(entry){return entry.expiresAt!==void 0&&entry.expiresAt<=Date.now()}remove(key){const entry=this.memory.get(key);if(!entry)return;if(entry.timeout)clearTimeout(entry.timeout);this.memory.delete(key);this.totalBytes-=entry.bytes}markUsed(key,entry){this.memory.delete(key);this.memory.set(key,entry)}evictOverLimits(){while(this.maxEntries>0&&this.memory.size>this.maxEntries||this.maxBytes>0&&this.totalBytes>this.maxBytes){const oldest=this.memory.keys().next();if(oldest.done)return;this.remove(oldest.value)}}sweep(){const now=Date.now();for(const[key,entry]of this.memory){if(entry.expiresAt!==void 0&&entry.expiresAt<=now){this.remove(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";import{adoptRedisClient,createRedisConnection}from"@frontmcp/utils";var CacheRedisProvider=class{client;keyPrefix;constructor(options){if(options.type!=="redis"&&options.type!=="redis-client"){throw new Error("Invalid cache provider type")}if(options.type==="redis-client"){this.client=adoptRedisClient(options.client).client;this.keyPrefix=options.keyPrefix??"";return}this.keyPrefix="";const{host,port,password,db,cluster,...ioredisOptions}=options.config;this.client=createRedisConnection({host,port,password,db,cluster,ioredisOptions,noErrorListener:true}).client;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(this.keyPrefix+key,strValue,"EX",ttlSeconds)}else{await this.client.set(this.keyPrefix+key,strValue)}}async getValue(key,defaultValue){const raw=await this.client.get(this.keyPrefix+key);if(raw===null)return defaultValue;try{return JSON.parse(raw)}catch{return raw}}async delete(key){await this.client.del(this.keyPrefix+key)}async exists(key){return await this.client.exists(this.keyPrefix+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 assertMemoryLimits(options){if(options.type!=="memory")return;for(const name of["maxEntries","maxBytes"]){const value=options[name];if(value===void 0||Number.isInteger(value)&&value>=0)continue;throw new CachePluginConfigurationError(`CachePlugin ${name} must be a whole number of 0 or more (0 keeps no limit), got ${String(value)}.`)}}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);assertMemoryLimits(options);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"||toolContext.output===void 0){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})}const{client,keyPrefix}=storeConfig;if(client!==void 0){return new CacheRedisProvider({type:"redis-client",client,keyPrefix,defaultTTL:globalOptions.defaultTTL})}const redis=storeConfig;return new CacheRedisProvider({type:"redis",config:{host:redis.host??"localhost",port:redis.port??6379,password:redis.password,db:redis.db,...redis.tls?{tls:{}}:{},keyPrefix:redis.keyPrefix,...redis.cluster!==void 0?{cluster:redis.cluster}:{}},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({maxEntries:options.maxEntries,maxBytes:options.maxBytes})});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}]})],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.13.2",
3
+ "version": "1.14.0-rc.2",
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.13.2",
53
- "@frontmcp/utils": "1.13.2",
52
+ "@frontmcp/sdk": "1.14.0-rc.2",
53
+ "@frontmcp/utils": "1.14.0-rc.2",
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,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});
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_utils3=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 DEFAULT_MEMORY_CACHE_MAX_ENTRIES=1e4;var DEFAULT_MEMORY_CACHE_MAX_BYTES=64*1024*1024;var MAX_TIMEOUT_MS=2**31-1;function isLowSurrogate(code){return code>=56320&&code<=57343}function utf8Length(text){let bytes=0;for(let index=0;index<text.length;index+=1){const code=text.charCodeAt(index);if(code<128)bytes+=1;else if(code<2048)bytes+=2;else if(code>=55296&&code<=56319&&isLowSurrogate(text.charCodeAt(index+1))){bytes+=4;index+=1}else bytes+=3}return bytes}function readLimit(name,value,fallback){if(value===void 0)return fallback;if(!Number.isInteger(value)||value<0){throw new TypeError(`CacheMemoryProvider ${name} must be a whole number of 0 or more, got ${String(value)}.`)}return value}var CacheMemoryProvider=class{memory=new Map;maxEntries;maxBytes;totalBytes=0;sweeper;constructor(options={}){const resolved=typeof options==="number"?{sweepIntervalSeconds:options}:options;this.maxEntries=readLimit("maxEntries",resolved.maxEntries,DEFAULT_MEMORY_CACHE_MAX_ENTRIES);this.maxBytes=readLimit("maxBytes",resolved.maxBytes,DEFAULT_MEMORY_CACHE_MAX_BYTES);this.sweeper=setInterval(()=>this.sweep(),(resolved.sweepIntervalSeconds??60)*1e3);this.sweeper.unref?.()}async setValue(key,value,ttlSeconds){const strValue=typeof value==="string"?value:JSON.stringify(value);this.remove(key);if(strValue===void 0)return;const entry={value:strValue,bytes:utf8Length(key)+utf8Length(strValue)};if(this.maxBytes>0&&entry.bytes>this.maxBytes)return;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.remove(key)}},ttlMs);entry.timeout.unref?.()}}this.memory.set(key,entry);this.totalBytes+=entry.bytes;this.evictOverLimits()}async getValue(key,defaultValue){const entry=this.memory.get(key);if(!entry)return defaultValue;if(this.isExpired(entry)){await this.delete(key);return defaultValue}this.markUsed(key,entry);const raw=entry.value;try{return JSON.parse(raw)}catch{return raw}}async delete(key){this.remove(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();this.totalBytes=0}getStats(){return{entries:this.memory.size,bytes:this.totalBytes,maxEntries:this.maxEntries,maxBytes:this.maxBytes}}isExpired(entry){return entry.expiresAt!==void 0&&entry.expiresAt<=Date.now()}remove(key){const entry=this.memory.get(key);if(!entry)return;if(entry.timeout)clearTimeout(entry.timeout);this.memory.delete(key);this.totalBytes-=entry.bytes}markUsed(key,entry){this.memory.delete(key);this.memory.set(key,entry)}evictOverLimits(){while(this.maxEntries>0&&this.memory.size>this.maxEntries||this.maxBytes>0&&this.totalBytes>this.maxBytes){const oldest=this.memory.keys().next();if(oldest.done)return;this.remove(oldest.value)}}sweep(){const now=Date.now();for(const[key,entry]of this.memory){if(entry.expiresAt!==void 0&&entry.expiresAt<=now){this.remove(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");var import_utils=require("@frontmcp/utils");var CacheRedisProvider=class{client;keyPrefix;constructor(options){if(options.type!=="redis"&&options.type!=="redis-client"){throw new Error("Invalid cache provider type")}if(options.type==="redis-client"){this.client=(0,import_utils.adoptRedisClient)(options.client).client;this.keyPrefix=options.keyPrefix??"";return}this.keyPrefix="";const{host,port,password,db,cluster,...ioredisOptions}=options.config;this.client=(0,import_utils.createRedisConnection)({host,port,password,db,cluster,ioredisOptions,noErrorListener:true}).client;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(this.keyPrefix+key,strValue,"EX",ttlSeconds)}else{await this.client.set(this.keyPrefix+key,strValue)}}async getValue(key,defaultValue){const raw=await this.client.get(this.keyPrefix+key);if(raw===null)return defaultValue;try{return JSON.parse(raw)}catch{return raw}}async delete(key){await this.client.del(this.keyPrefix+key)}async exists(key){return await this.client.exists(this.keyPrefix+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_utils2=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_utils2.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 assertMemoryLimits(options){if(options.type!=="memory")return;for(const name of["maxEntries","maxBytes"]){const value=options[name];if(value===void 0||Number.isInteger(value)&&value>=0)continue;throw new CachePluginConfigurationError(`CachePlugin ${name} must be a whole number of 0 or more (0 keeps no limit), got ${String(value)}.`)}}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);assertMemoryLimits(options);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"||toolContext.output===void 0){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_utils3.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})}const{client,keyPrefix}=storeConfig;if(client!==void 0){return new CacheRedisProvider({type:"redis-client",client,keyPrefix,defaultTTL:globalOptions.defaultTTL})}const redis=storeConfig;return new CacheRedisProvider({type:"redis",config:{host:redis.host??"localhost",port:redis.port??6379,password:redis.password,db:redis.db,...redis.tls?{tls:{}}:{},keyPrefix:redis.keyPrefix,...redis.cluster!==void 0?{cluster:redis.cluster}:{}},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({maxEntries:options.maxEntries,maxBytes:options.maxBytes})});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}]})],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.13.2",
3
+ "version": "1.14.0-rc.2",
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.13.2",
53
- "@frontmcp/utils": "1.13.2",
52
+ "@frontmcp/sdk": "1.14.0-rc.2",
53
+ "@frontmcp/utils": "1.14.0-rc.2",
54
54
  "ioredis": "^5.8.0"
55
55
  },
56
56
  "peerDependencies": {
@@ -1,8 +1,23 @@
1
- import { CacheStoreInterface } from '../cache.types';
1
+ import type { CacheStoreInterface } from '../cache.types';
2
+ export interface CacheMemoryProviderOptions {
3
+ /** Seconds between sweeps that remove expired entries. Default 60. */
4
+ sweepIntervalSeconds?: number;
5
+ /** Most entries kept; the least recently used goes first. `0` keeps any number. Default 10,000. */
6
+ maxEntries?: number;
7
+ /** Most UTF-8 bytes of keys and values kept; the least recently used goes first. `0` keeps any size. Default 64 MiB. */
8
+ maxBytes?: number;
9
+ }
10
+ export declare const DEFAULT_MEMORY_CACHE_MAX_ENTRIES = 10000;
11
+ export declare const DEFAULT_MEMORY_CACHE_MAX_BYTES: number;
2
12
  export default class CacheMemoryProvider implements CacheStoreInterface {
13
+ /** Kept in least recently used order: the first key is the next to evict. */
3
14
  private readonly memory;
15
+ private readonly maxEntries;
16
+ private readonly maxBytes;
17
+ private totalBytes;
4
18
  private sweeper?;
5
- constructor(sweepIntervalTTL?: number);
19
+ /** Takes the options, or the sweep interval in seconds. */
20
+ constructor(options?: CacheMemoryProviderOptions | number);
6
21
  /** Set a value (auto-stringifies objects) */
7
22
  setValue(key: string, value: unknown, ttlSeconds?: number): Promise<void>;
8
23
  /** Get a value and automatically parse JSON if possible */
@@ -13,7 +28,17 @@ export default class CacheMemoryProvider implements CacheStoreInterface {
13
28
  exists(key: string): Promise<boolean>;
14
29
  /** Gracefully close the provider */
15
30
  close(): Promise<void>;
31
+ /** The number of entries and their size in UTF-8 bytes. */
32
+ getStats(): {
33
+ entries: number;
34
+ bytes: number;
35
+ maxEntries: number;
36
+ maxBytes: number;
37
+ };
16
38
  private isExpired;
39
+ private remove;
40
+ private markUsed;
41
+ private evictOverLimits;
17
42
  /** Periodically remove expired keys to keep memory tidy */
18
43
  private sweep;
19
44
  }
@@ -1 +1 @@
1
- {"version":3,"file":"cache-memory.provider.d.ts","sourceRoot":"","sources":["../../src/providers/cache-memory.provider.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAiBrD,MAAM,CAAC,OAAO,OAAO,mBAAoB,YAAW,mBAAmB;IACrE,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA4B;IACnD,OAAO,CAAC,OAAO,CAAC,CAAiB;gBAEr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C,UAAU,CAAK;IACvB,OAAO,CAAC,OAAO,CAAC,CAAiB;IAEjC,2DAA2D;gBAC/C,OAAO,GAAE,0BAA0B,GAAG,MAAW;IAS7D,6CAA6C;IACvC,QAAQ,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAiC/E,2DAA2D;IACrD,QAAQ,CAAC,CAAC,GAAG,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC;IAmBlF,mBAAmB;IACb,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAIxC,8CAA8C;IACxC,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAU3C,oCAAoC;IAC9B,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAS5B,2DAA2D;IAC3D,QAAQ,IAAI;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE;IAMpF,OAAO,CAAC,SAAS;IAIjB,OAAO,CAAC,MAAM;IAQd,OAAO,CAAC,QAAQ;IAKhB,OAAO,CAAC,eAAe;IAWvB,2DAA2D;IAC3D,OAAO,CAAC,KAAK;CAQd"}
@@ -1,6 +1,8 @@
1
1
  import { type CacheStoreInterface, type RedisCacheOptions } from '../cache.types';
2
2
  export default class CacheRedisProvider implements CacheStoreInterface {
3
3
  private readonly client;
4
+ /** Put on every key here for a client the app made; ioredis puts the `redis` type's own on its commands. */
5
+ private readonly keyPrefix;
4
6
  constructor(options: RedisCacheOptions);
5
7
  /** Set a value (auto-stringifies objects) */
6
8
  setValue(key: string, value: unknown, ttlSeconds?: number): Promise<void>;
@@ -10,7 +12,7 @@ export default class CacheRedisProvider implements CacheStoreInterface {
10
12
  delete(key: string): Promise<void>;
11
13
  /** Check if a key exists */
12
14
  exists(key: string): Promise<boolean>;
13
- /** Gracefully close the Redis connection */
15
+ /** Gracefully close the Redis connection (a client you passed in stays open: it is yours) */
14
16
  close(): Promise<void>;
15
17
  }
16
18
  //# sourceMappingURL=cache-redis.provider.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"cache-redis.provider.d.ts","sourceRoot":"","sources":["../../src/providers/cache-redis.provider.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,mBAAmB,EAAE,KAAK,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAgBlF,MAAM,CAAC,OAAO,OAAO,kBAAmB,YAAW,mBAAmB;IACpE,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAc;gBAEzB,OAAO,EAAE,iBAAiB;IAoBtC,6CAA6C;IACvC,QAAQ,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAS/E,2DAA2D;IACrD,QAAQ,CAAC,CAAC,GAAG,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC;IAYlF,mBAAmB;IACb,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAIxC,4BAA4B;IACtB,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAI3C,4CAA4C;IACtC,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAG7B"}
1
+ {"version":3,"file":"cache-redis.provider.d.ts","sourceRoot":"","sources":["../../src/providers/cache-redis.provider.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,mBAAmB,EAAE,KAAK,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAOlF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