@frontmcp/plugin-cache 1.11.2 → 1.12.0-rc.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/README.md +9 -9
- package/cache.plugin.d.ts.map +1 -1
- package/cache.symbol.d.ts +1 -1
- package/cache.symbol.d.ts.map +1 -1
- package/esm/index.mjs +1 -1
- package/esm/package.json +3 -3
- package/index.js +1 -1
- package/package.json +3 -3
- package/providers/cache-memory.provider.d.ts.map +1 -1
package/README.md
CHANGED
|
@@ -79,15 +79,15 @@ subject, so one user never gets another user's cached answer.
|
|
|
79
79
|
|
|
80
80
|
## Options
|
|
81
81
|
|
|
82
|
-
| Option | Default | Description
|
|
83
|
-
| --------------- | ---------------------------- |
|
|
84
|
-
| `type` | `'memory'` | Where entries are kept: `'memory'`, `'redis'`, `'redis-client'` or `'global-store'`. Required when you pass options.
|
|
85
|
-
| `defaultTTL` | `86400` (a day) | Seconds an entry lives when the tool's `cache` gives no `ttl`, and for tools matched by `toolPatterns`.
|
|
86
|
-
| `keyByIdentity` | `true` | Keep separate entries per caller. See [Who gets which entry](#who-gets-which-entry).
|
|
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
|
-
| `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.
|
|
82
|
+
| Option | Default | Description |
|
|
83
|
+
| --------------- | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
84
|
+
| `type` | `'memory'` | Where entries are kept: `'memory'`, `'redis'`, `'redis-client'` or `'global-store'`. Required when you pass options. Any other value makes `init()` throw a `CachePluginConfigurationError`. |
|
|
85
|
+
| `defaultTTL` | `86400` (a day) | Seconds an entry lives when the tool's `cache` gives no `ttl`, and for tools matched by `toolPatterns`. |
|
|
86
|
+
| `keyByIdentity` | `true` | Keep separate entries per caller. See [Who gets which entry](#who-gets-which-entry). |
|
|
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
|
+
| `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. |
|
|
91
91
|
|
|
92
92
|
## Stores
|
|
93
93
|
|
package/cache.plugin.d.ts.map
CHANGED
|
@@ -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;
|
|
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"}
|
package/cache.symbol.d.ts
CHANGED
package/cache.symbol.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cache.symbol.d.ts","sourceRoot":"","sources":["../src/cache.symbol.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"cache.symbol.d.ts","sourceRoot":"","sources":["../src/cache.symbol.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AAEtC,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAEpD,eAAO,MAAM,eAAe,EAAE,KAAK,CAAC,mBAAmB,CAAgC,CAAC"}
|
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".`)}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();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"});flowCtx.state.set("rawOutput",cached);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,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};
|
package/esm/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@frontmcp/plugin-cache",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.12.0-rc.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.
|
|
53
|
-
"@frontmcp/utils": "1.
|
|
52
|
+
"@frontmcp/sdk": "1.12.0-rc.1",
|
|
53
|
+
"@frontmcp/utils": "1.12.0-rc.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".`)}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();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"});flowCtx.state.set("rawOutput",cached);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);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});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@frontmcp/plugin-cache",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.12.0-rc.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.
|
|
53
|
-
"@frontmcp/utils": "1.
|
|
52
|
+
"@frontmcp/sdk": "1.12.0-rc.1",
|
|
53
|
+
"@frontmcp/utils": "1.12.0-rc.1",
|
|
54
54
|
"ioredis": "^5.8.0"
|
|
55
55
|
},
|
|
56
56
|
"peerDependencies": {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cache-memory.provider.d.ts","sourceRoot":"","sources":["../../src/providers/cache-memory.provider.ts"],"names":[],"mappings":"
|
|
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;gBAErB,gBAAgB,SAAK;IAMjC,6CAA6C;IACvC,QAAQ,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IA6B/E,2DAA2D;IACrD,QAAQ,CAAC,CAAC,GAAG,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC;IAkBlF,mBAAmB;IACb,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAMxC,8CAA8C;IACxC,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAU3C,oCAAoC;IAC9B,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAU5B,OAAO,CAAC,SAAS;IAIjB,2DAA2D;IAC3D,OAAO,CAAC,KAAK;CASd"}
|