@frontmcp/plugin-codecall 1.12.0-rc.1 → 1.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -52,7 +52,10 @@ export default class CodeCallPlugin extends DynamicPlugin<CodeCallPluginOptions,
52
52
  * (`visibility: 'hidden'`) also opts in with `visibleInListTools: true`, in every mode.
53
53
  */
54
54
  private isDirectlyCallable;
55
- /** Whether the tool's app is one `appIds` puts under `codecall_only`; every app is, without `appIds`. */
55
+ /**
56
+ * Whether the tool's app, found anywhere in its lineage (an app's adapter or plugin owns the tools it
57
+ * provides), is one `appIds` puts under `codecall_only`; every app is, without `appIds`.
58
+ */
56
59
  private managesApp;
57
60
  /** Whether this instance's direct-call gate runs for the tool, so the listing hides only what that gate refuses. */
58
61
  private judges;
@@ -1 +1 @@
1
- {"version":3,"file":"codecall.plugin.d.ts","sourceRoot":"","sources":["../src/codecall.plugin.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,aAAa,EAUb,KAAK,SAAS,EAEd,KAAK,YAAY,EAEjB,KAAK,QAAQ,EACd,MAAM,eAAe,CAAC;AAEvB,OAAO,EAGL,KAAK,qBAAqB,EAC1B,KAAK,0BAA0B,EAEhC,MAAM,kBAAkB,CAAC;AAuC1B,MAAM,CAAC,OAAO,OAAO,cAAe,SAAQ,aAAa,CAAC,qBAAqB,EAAE,0BAA0B,CAAC;IAC1G,OAAO,EAAE,qBAAqB,CAAC;IAC/B,OAAO,CAAC,YAAY,CAAC,CAAiB;IAEtC,OAAO,CAAC,SAAS;gBAOL,OAAO,GAAE,0BAA+B;IAMpD;;;OAGG;WACa,gBAAgB,CAAC,OAAO,EAAE,0BAA0B,GAAG,YAAY,EAAE;IAuDrF;;;OAGG;WACa,YAAY,CAAC,OAAO,EAAE,0BAA0B,GAAG,QAAQ,EAAE;IAwB7E;;;;;;;;;;;;;OAaG;IAEG,eAAe,CAAC,OAAO,EAAE,SAAS,CAAC,kBAAkB,CAAC;IAsB5D;;;;;;;;;;;;;;;OAeG;IAEG,4BAA4B,CAAC,OAAO,EAAE,SAAS,CAAC,iBAAiB,CAAC;IAUxE;;;OAGG;IACH,OAAO,CAAC,kBAAkB;IAO1B,yGAAyG;IACzG,OAAO,CAAC,UAAU;IAOlB,oHAAoH;IACpH,OAAO,CAAC,MAAM;IAId,OAAO,CAAC,WAAW;IAQnB;;;;;;;;;OASG;IAEH,OAAO,CAAC,qBAAqB;IAyB7B;;;OAGG;IAEH,OAAO,CAAC,cAAc;IAStB;;OAEG;IAEH,OAAO,CAAC,mBAAmB;CAG5B"}
1
+ {"version":3,"file":"codecall.plugin.d.ts","sourceRoot":"","sources":["../src/codecall.plugin.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,aAAa,EAUb,KAAK,SAAS,EAEd,KAAK,YAAY,EAEjB,KAAK,QAAQ,EACd,MAAM,eAAe,CAAC;AAEvB,OAAO,EAGL,KAAK,qBAAqB,EAC1B,KAAK,0BAA0B,EAEhC,MAAM,kBAAkB,CAAC;AAuC1B,MAAM,CAAC,OAAO,OAAO,cAAe,SAAQ,aAAa,CAAC,qBAAqB,EAAE,0BAA0B,CAAC;IAC1G,OAAO,EAAE,qBAAqB,CAAC;IAC/B,OAAO,CAAC,YAAY,CAAC,CAAiB;IAEtC,OAAO,CAAC,SAAS;gBAOL,OAAO,GAAE,0BAA+B;IAMpD;;;OAGG;WACa,gBAAgB,CAAC,OAAO,EAAE,0BAA0B,GAAG,YAAY,EAAE;IAuDrF;;;OAGG;WACa,YAAY,CAAC,OAAO,EAAE,0BAA0B,GAAG,QAAQ,EAAE;IAwB7E;;;;;;;;;;;;;OAaG;IAEG,eAAe,CAAC,OAAO,EAAE,SAAS,CAAC,kBAAkB,CAAC;IAsB5D;;;;;;;;;;;;;;;OAeG;IAEG,4BAA4B,CAAC,OAAO,EAAE,SAAS,CAAC,iBAAiB,CAAC;IAUxE;;;OAGG;IACH,OAAO,CAAC,kBAAkB;IAO1B;;;OAGG;IACH,OAAO,CAAC,UAAU;IAOlB,oHAAoH;IACpH,OAAO,CAAC,MAAM;IAId,OAAO,CAAC,WAAW;IAQnB;;;;;;;;;OASG;IAEH,OAAO,CAAC,qBAAqB;IAyB7B;;;OAGG;IAEH,OAAO,CAAC,cAAc;IAStB;;OAEG;IAEH,OAAO,CAAC,mBAAmB;CAG5B"}
package/esm/index.mjs CHANGED
@@ -1,9 +1,9 @@
1
- var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;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};import CachePlugin from"@frontmcp/plugin-cache";import{DynamicPlugin,FrontMcpLogger,FrontMcpToolTokens,isEntryGatedBy,ListToolsHook,Plugin,resolveToolVisibility,ScopeEntry,ToolHook,ToolNotFoundError}from"@frontmcp/sdk";import{z}from"@frontmcp/lazy-zod";var directCallsFilterSchema=z.custom(val=>typeof val==="function",{message:"filter must be a function with signature (tool: DirectCallsFilterToolInfo) => boolean"});var includeToolsFilterSchema=z.custom(val=>typeof val==="function",{message:"includeTools must be a function with signature (tool: IncludeToolsFilterToolInfo) => boolean"});var codeCallModeSchema=z.enum(["codecall_only","codecall_opt_in","metadata_driven"]).default("codecall_only");var codeCallVmPresetSchema=z.enum(["locked_down","secure","balanced","experimental"]).default("secure");var DEFAULT_VM_OPTIONS={preset:"secure"};var codeCallVmOptionsSchema=z.object({preset:codeCallVmPresetSchema,timeoutMs:z.number().positive().optional(),allowLoops:z.boolean().optional(),maxSteps:z.number().positive().optional(),disabledBuiltins:z.array(z.string()).optional(),disabledGlobals:z.array(z.string()).optional(),allowConsole:z.boolean().optional(),maxSanitizeDepth:z.number().positive().optional(),maxSanitizeProperties:z.number().positive().optional(),rapidEnumerationThreshold:z.number().int().positive().optional(),rapidEnumerationOverrides:z.record(z.string(),z.number().int().positive()).optional()}).default(()=>DEFAULT_VM_OPTIONS);var codeCallDirectCallsOptionsSchema=z.object({enabled:z.boolean(),allowedTools:z.array(z.string()).optional(),filter:directCallsFilterSchema.optional()});var embeddingStrategySchema=z.enum(["tfidf","ml"]).default("tfidf");var synonymExpansionConfigSchema=z.object({enabled:z.boolean().default(true),additionalSynonyms:z.array(z.array(z.string())).optional(),replaceDefaults:z.boolean().default(false),maxExpansionsPerTerm:z.number().positive().default(5)}).default({enabled:true,replaceDefaults:false,maxExpansionsPerTerm:5});var DEFAULT_EMBEDDING_OPTIONS={strategy:"tfidf",modelName:"Xenova/all-MiniLM-L6-v2",cacheDir:"./.cache/transformers",useHNSW:false,synonymExpansion:{enabled:true,replaceDefaults:false,maxExpansionsPerTerm:5}};var codeCallEmbeddingOptionsSchema=z.object({strategy:embeddingStrategySchema.optional(),modelName:z.string().optional(),cacheDir:z.string().optional(),useHNSW:z.boolean().optional(),synonymExpansion:z.union([z.literal(false),synonymExpansionConfigSchema]).optional()}).optional().transform(opts=>({strategy:opts?.strategy??DEFAULT_EMBEDDING_OPTIONS.strategy,modelName:opts?.modelName??DEFAULT_EMBEDDING_OPTIONS.modelName,cacheDir:opts?.cacheDir??DEFAULT_EMBEDDING_OPTIONS.cacheDir,useHNSW:opts?.useHNSW??DEFAULT_EMBEDDING_OPTIONS.useHNSW,synonymExpansion:opts?.synonymExpansion??DEFAULT_EMBEDDING_OPTIONS.synonymExpansion}));var codeCallSidecarOptionsSchema=z.object({enabled:z.boolean().default(false),maxTotalSize:z.number().positive().optional(),maxReferenceSize:z.number().positive().optional(),extractionThreshold:z.number().positive().optional(),maxResolvedSize:z.number().positive().optional(),allowComposites:z.boolean().optional(),maxScriptLengthWhenDisabled:z.number().positive().nullable().default(64*1024)}).default(()=>({enabled:false,maxScriptLengthWhenDisabled:64*1024}));var codeCallPluginOptionsObjectSchema=z.object({mode:codeCallModeSchema,appIds:z.array(z.string()).optional(),topK:z.number().positive().default(8),maxDefinitions:z.number().int().positive().default(8),includeTools:includeToolsFilterSchema.optional(),directCalls:codeCallDirectCallsOptionsSchema.optional(),vm:codeCallVmOptionsSchema,embedding:codeCallEmbeddingOptionsSchema,sidecar:codeCallSidecarOptionsSchema});var DEFAULT_PLUGIN_OPTIONS={mode:"codecall_only",topK:8,maxDefinitions:8,vm:DEFAULT_VM_OPTIONS,embedding:DEFAULT_EMBEDDING_OPTIONS,sidecar:{enabled:false,maxScriptLengthWhenDisabled:64*1024}};var codeCallPluginOptionsSchema=codeCallPluginOptionsObjectSchema.prefault(DEFAULT_PLUGIN_OPTIONS);import{BaseConfig,Provider,ProviderScope}from"@frontmcp/sdk";var CodeCallConfig=class extends BaseConfig{constructor(options={}){const parsedConfig=codeCallPluginOptionsSchema.parse(options);const resolvedVm=resolveVmOptions(parsedConfig.vm);super({...parsedConfig,resolvedVm})}};CodeCallConfig=__decorateClass([Provider({name:"codecall:config",description:"CodeCall plugin configuration with validated defaults",scope:ProviderScope.GLOBAL})],CodeCallConfig);var MAX_ITERATIONS_PER_LOOP=1e4;function maxToolCallsOf(vmOptions){return vmOptions.maxSteps||100}var SANDBOX_RAPID_ENUMERATION_THRESHOLD=30;function rapidEnumerationThresholdOf(vmOptions){return vmOptions.rapidEnumerationThreshold??SANDBOX_RAPID_ENUMERATION_THRESHOLD}function resolveVmOptions(vmOptions){const preset=vmOptions?.preset??"secure";const base=presetDefaults(preset);return{...base,...vmOptions,disabledBuiltins:vmOptions?.disabledBuiltins??base.disabledBuiltins,disabledGlobals:vmOptions?.disabledGlobals??base.disabledGlobals,allowConsole:vmOptions?.allowConsole===true}}function presetDefaults(preset){switch(preset){case"locked_down":return{preset,timeoutMs:2e3,allowLoops:false,allowConsole:false,maxSteps:2e3,disabledBuiltins:["eval","Function","AsyncFunction"],disabledGlobals:["require","process","fetch","setTimeout","setInterval","setImmediate","global","globalThis"],maxSanitizeDepth:10,maxSanitizeProperties:1e3};case"balanced":return{preset,timeoutMs:5e3,allowLoops:true,allowConsole:false,maxSteps:1e4,disabledBuiltins:["eval","Function","AsyncFunction"],disabledGlobals:["require","process","fetch"],maxSanitizeDepth:50,maxSanitizeProperties:5e3};case"experimental":return{preset,timeoutMs:1e4,allowLoops:true,allowConsole:false,maxSteps:2e4,disabledBuiltins:["eval","Function","AsyncFunction"],disabledGlobals:["require","process"],maxSanitizeDepth:100,maxSanitizeProperties:2e4};case"secure":default:return{preset:"secure",timeoutMs:3500,allowLoops:false,allowConsole:false,maxSteps:5e3,disabledBuiltins:["eval","Function","AsyncFunction"],disabledGlobals:["require","process","fetch","setTimeout","setInterval","setImmediate","global","globalThis"],maxSanitizeDepth:50,maxSanitizeProperties:2e3}}}import{getRunningTool}from"@frontmcp/sdk";var CODECALL_DISPATCH=Symbol("frontmcp.codecall.dispatch");function asCodeCallDispatch(ctx){return Object.defineProperty(ctx,CODECALL_DISPATCH,{value:true,enumerable:false})}function isInProcessDispatch(ctx){if(getRunningTool())return true;if(typeof ctx!=="object"||ctx===null)return false;const marks=ctx;return marks[CODECALL_DISPATCH]===true||marks.internalCall===true}var BLOCKED_NAMESPACE_PATTERNS=Object.freeze([/^system:/,/^internal:/,/^__/]);function isOfferedToCaller(availableWhen,surface){const offered=availableWhen?.surface;return offered===void 0||surface===void 0||offered.includes(surface)}var ALLOWED={allowed:true};function deny(reason){return{allowed:false,reason}}function codeCallAppIdOf(scope,entry){const lineage=scope?.tools?.lineageOf?.(entry)??[];const owners=entry.owner?[...lineage,entry.owner]:lineage;return owners.find(owner=>owner.kind==="app")?.id}function toCodeCallPolicyTool(entry,requestedName,scope){const{metadata}=entry;return{name:entry.name||entry.fullName,fullName:entry.fullName,aliases:requestedName?[requestedName]:void 0,appId:codeCallAppIdOf(scope,entry),description:metadata?.description,tags:metadata?.tags,hidden:metadata?.hideFromDiscovery===true||metadata?.visibility==="hidden"||metadata?.visibility==="internal",codecall:metadata?.codecall,annotations:metadata?.annotations,metadata}}function isPlainData(value){if(Array.isArray(value))return true;const proto=Object.getPrototypeOf(value);return proto===Object.prototype||proto===null}function readOnlyCopy(value,copies){if(typeof value!=="object"||value===null||!isPlainData(value))return value;const existing=copies.get(value);if(existing!==void 0)return existing;const copy=Array.isArray(value)?[]:Object.create(Object.getPrototypeOf(value));copies.set(value,copy);for(const key of Reflect.ownKeys(value)){if(!Object.prototype.propertyIsEnumerable.call(value,key))continue;Object.defineProperty(copy,key,{value:readOnlyCopy(Reflect.get(value,key),copies),enumerable:true,writable:true,configurable:true})}return Object.freeze(copy)}function toToolFilterInfo(tool){const copies=new WeakMap;const annotations=readOnlyCopy(tool.annotations,copies);const metadata=tool.metadata?readOnlyCopy({...tool.metadata,...annotations?{annotations:tool.annotations}:{}},copies):void 0;return{name:tool.name,fullName:tool.fullName,appId:tool.appId,source:tool.codecall?.source,description:tool.description,tags:readOnlyCopy(tool.codecall?.tags??tool.tags,copies),annotations,metadata}}function ownNamesOf(tool){return[tool.name,tool.fullName].filter(candidate=>!!candidate)}function checkCodeCallToolPolicy(tool,config){const{name}=tool;const spellings=[...ownNamesOf(tool),...tool.aliases??[]];if(spellings.some(candidate=>candidate.startsWith("codecall:"))){return deny("CodeCall meta-tools are not callable from CodeCall")}for(const candidate of spellings){if(BLOCKED_NAMESPACE_PATTERNS.some(pattern=>pattern.test(candidate))){return deny(`Tool "${candidate}" is in a namespace CodeCall never calls`)}}if(tool.hidden===true){return deny(`Tool "${name}" is hidden from discovery`)}const enabled=tool.codecall?.enabledInCodeCall;switch(config.mode){case"codecall_only":case"metadata_driven":if(enabled===false){return deny(`Tool "${name}" sets enabledInCodeCall: false`)}break;case"codecall_opt_in":if(enabled!==true){return deny(`Tool "${name}" has not opted in to CodeCall`)}break;default:return deny(`Unknown CodeCall mode: ${String(config.mode)}`)}if(config.includeTools&&!config.includeTools(toToolFilterInfo(tool))){return deny(`Tool "${name}" is excluded by the includeTools filter`)}return ALLOWED}function denyUnknownTool(name){return deny(`Tool "${name}" is not available through CodeCall`)}function resolveCodeCallTool(scope,name){const otherSpelling=/[-_]/.test(name)?name.includes("_")?name.replace(/_/g,"-"):name.replace(/-/g,"_"):void 0;const candidates=otherSpelling?[name,otherSpelling]:[name];const declaresAlias=entry=>entry.metadata?.aliases?.includes(name)===true;const matches=entry=>candidates.includes(entry.fullName)||candidates.includes(entry.name);return findResolvableTool(scope,declaresAlias)??findResolvableTool(scope,matches)}function findResolvableTool(scope,matches){const typedScope=scope;const local=typedScope.tools?.getTools(true)?.find(matches);if(local)return local;const registries=typedScope.providers?.getRegistries?.("AppRegistry")??[];for(const registry of registries){for(const app of registry.getApps()){if(!app.isRemote)continue;const remote=app.tools.getTools(true).find(matches);if(remote)return remote}}return void 0}function checkDirectCallPolicy(tool,directCalls){if(!directCalls)return ALLOWED;if(directCalls.enabled===false){return deny("Direct tool invocation is disabled")}const{allowedTools}=directCalls;if(allowedTools&&!ownNamesOf(tool).some(ownName=>allowedTools.includes(ownName))){return deny(`Tool "${tool.name}" is not in the direct-call allowlist`)}if(directCalls.filter&&!directCalls.filter(toToolFilterInfo(tool))){return deny(`Tool "${tool.name}" is excluded by the directCalls filter`)}return ALLOWED}function readCodeCallPolicyConfig(config){return{mode:config.get("mode")??"codecall_only",includeTools:config.get("includeTools")}}function checkCodeCallToolAccess(scope,config,name,options={}){const entry=resolveCodeCallTool(scope,name);if(!entry)return denyUnknownTool(name);if(!isOfferedToCaller(entry.metadata?.availableWhen,options.surface)){return deny(`Tool "${name}" is not offered on the caller's surface "${options.surface}"`)}const policyTool=toCodeCallPolicyTool(entry,name,scope);const baseDecision=checkCodeCallToolPolicy(policyTool,readCodeCallPolicyConfig(config));if(!baseDecision.allowed)return baseDecision;if(options.directCall){const directDecision=checkDirectCallPolicy(policyTool,config.get("directCalls"));if(!directDecision.allowed)return directDecision}return{allowed:true,entry}}var EMBEDDED_STACK_FRAME_RE=/\n[ \t]*at\s[^\n]*/g;var QUOTED_PATH_RE=/(['"`])((?:~?\/|[A-Za-z]:[\\/]|\\\\)[^\s'"`\\/][^'"`\n]*)\1/g;var URL_RE=/\b[A-Za-z][A-Za-z0-9+.-]{1,31}:\/\/(?:[^\s'"`<>,;]|[,;](?!~?\/|[A-Za-z]:[\\/]|\\\\))*/g;var QUERY_PATH_VALUE_RE=/([?&][^=&#]*=)(?:~?\/|[A-Za-z]:[\\/]|\\\\)[^&#]*/g;var POSIX_SEGMENT=String.raw`[^\s/\\'"\x60<>|,;:()\[\]{}]+`;var WINDOWS_SEGMENT=String.raw`[^\s/\\'"\x60<>|,;:*?]+`;function segments(segment,separator){const spaced=`${segment}(?: ${segment}){0,2}`;return`(?:(?:${spaced}${separator})+(?:${segment})?|${segment})`}var UNQUOTED_PATH_RE=new RegExp([String.raw`(?<![\w.~/\\)\]-])~?/+${segments(POSIX_SEGMENT,"/+")}`,String.raw`(?<![\w\\/])[A-Za-z]:[\\/]+${segments(WINDOWS_SEGMENT,String.raw`[\\/]+`)}?`,String.raw`(?<![\w\\])\\\\${segments(WINDOWS_SEGMENT,String.raw`[\\/]+`)}`].join("|"),"g");function redactPaths(text){return text.replace(QUOTED_PATH_RE,"$1[path]$1").replace(UNQUOTED_PATH_RE,"[path]")}function toClientErrorMessage(message){if(!message)return"";return redactAbsolutePaths(message.replace(EMBEDDED_STACK_FRAME_RE,""))}function redactAbsolutePaths(text){let result="";let last=0;for(const match of text.matchAll(URL_RE)){const start=match.index??0;result+=redactPaths(text.slice(last,start));result+=/^file:/i.test(match[0])?"[path]":match[0].replace(QUERY_PATH_VALUE_RE,"$1[path]");last=start+match[0].length}return result+redactPaths(text.slice(last))}var TOOL_CALL_ERROR_CODES={NOT_FOUND:"NOT_FOUND",VALIDATION:"VALIDATION",EXECUTION:"EXECUTION",TIMEOUT:"TIMEOUT",ACCESS_DENIED:"ACCESS_DENIED",RATE_LIMITED:"RATE_LIMITED",SELF_REFERENCE:"SELF_REFERENCE"};function createToolCallError(code,toolName,rawMessage){const sanitizedMessage=getSanitizedMessage(code,toolName,rawMessage);return Object.freeze({code,message:sanitizedMessage,toolName})}function createPublicToolCallError(code,toolName,publicMessage){return Object.freeze({code,message:toClientErrorMessage(publicMessage).trim()||getSanitizedMessage(code,toolName),toolName})}function getSanitizedMessage(code,toolName,rawMessage){switch(code){case TOOL_CALL_ERROR_CODES.NOT_FOUND:return`Tool "${toolName}" was not found`;case TOOL_CALL_ERROR_CODES.VALIDATION:return rawMessage?sanitizeValidationMessage(rawMessage):`Input validation failed for tool "${toolName}"`;case TOOL_CALL_ERROR_CODES.EXECUTION:return`Tool "${toolName}" execution failed`;case TOOL_CALL_ERROR_CODES.TIMEOUT:return`Tool "${toolName}" execution timed out`;case TOOL_CALL_ERROR_CODES.ACCESS_DENIED:return`Access denied for tool "${toolName}"`;case TOOL_CALL_ERROR_CODES.RATE_LIMITED:return`Tool "${toolName}" was rate limited`;case TOOL_CALL_ERROR_CODES.SELF_REFERENCE:return`Cannot call CodeCall tools from within AgentScript`;default:return`An error occurred while calling "${toolName}"`}}function sanitizeValidationMessage(message){let sanitized=toClientErrorMessage(message);sanitized=sanitized.replace(/\bat line \d+/gi,"");sanitized=sanitized.replace(/\bline \d+/gi,"");sanitized=sanitized.replace(/:\d+:\d+/g,"");if(sanitized.length>200){sanitized=sanitized.substring(0,200)+"..."}return sanitized.trim()}var SelfReferenceError=class extends Error{code=TOOL_CALL_ERROR_CODES.SELF_REFERENCE;toolName;constructor(toolName){super(`Self-reference attack: Attempted to call CodeCall tool "${toolName}" from within AgentScript`);this.name="SelfReferenceError";this.toolName=toolName;Object.freeze(this)}};var CODECALL_TOOL_PREFIX="codecall:";var BLOCKED_CODECALL_TOOLS=Object.freeze(new Set(["codecall:search","codecall:describe","codecall:execute","codecall:invoke"]));function isBlockedSelfReference(toolName){const normalizedName=toolName.toLowerCase().trim();if(normalizedName.startsWith(CODECALL_TOOL_PREFIX)){return true}if(BLOCKED_CODECALL_TOOLS.has(toolName)){return true}return false}function assertNotSelfReference(toolName){if(isBlockedSelfReference(toolName)){throw new SelfReferenceError(toolName)}}import{Provider as Provider2,ProviderScope as ProviderScope2}from"@frontmcp/sdk";var AUDIT_EVENT_TYPES={EXECUTION_START:"codecall:execution:start",EXECUTION_SUCCESS:"codecall:execution:success",EXECUTION_FAILURE:"codecall:execution:failure",EXECUTION_TIMEOUT:"codecall:execution:timeout",TOOL_CALL_START:"codecall:tool:call:start",TOOL_CALL_SUCCESS:"codecall:tool:call:success",TOOL_CALL_FAILURE:"codecall:tool:call:failure",SECURITY_SELF_REFERENCE:"codecall:security:self-reference",SECURITY_ACCESS_DENIED:"codecall:security:access-denied",SECURITY_AST_BLOCKED:"codecall:security:ast-blocked",SEARCH_PERFORMED:"codecall:search:performed",DESCRIBE_PERFORMED:"codecall:describe:performed",INVOKE_PERFORMED:"codecall:invoke:performed"};var AuditLoggerService=class{listeners=new Set;executionCounter=0;subscribe(listener){this.listeners.add(listener);return()=>{this.listeners.delete(listener)}}generateExecutionId(){const timestamp=Date.now().toString(36);const counter=(++this.executionCounter).toString(36).padStart(4,"0");const random=Math.random().toString(36).substring(2,8);return`exec_${timestamp}_${counter}_${random}`}logExecutionStart(executionId,script){this.emit({type:AUDIT_EVENT_TYPES.EXECUTION_START,timestamp:new Date().toISOString(),executionId,data:{scriptHash:this.hashScript(script),scriptLength:script.length}})}logExecutionSuccess(executionId,script,durationMs,toolCallCount){this.emit({type:AUDIT_EVENT_TYPES.EXECUTION_SUCCESS,timestamp:new Date().toISOString(),executionId,durationMs,data:{scriptHash:this.hashScript(script),scriptLength:script.length,toolCallCount}})}logExecutionFailure(executionId,script,durationMs,error){this.emit({type:AUDIT_EVENT_TYPES.EXECUTION_FAILURE,timestamp:new Date().toISOString(),executionId,durationMs,data:{scriptHash:this.hashScript(script),scriptLength:script.length,error:this.sanitizeError(error)}})}logExecutionTimeout(executionId,script,durationMs){this.emit({type:AUDIT_EVENT_TYPES.EXECUTION_TIMEOUT,timestamp:new Date().toISOString(),executionId,durationMs,data:{scriptHash:this.hashScript(script),scriptLength:script.length}})}logToolCallStart(executionId,toolName,callDepth){this.emit({type:AUDIT_EVENT_TYPES.TOOL_CALL_START,timestamp:new Date().toISOString(),executionId,data:{toolName,callDepth}})}logToolCallSuccess(executionId,toolName,callDepth,durationMs){this.emit({type:AUDIT_EVENT_TYPES.TOOL_CALL_SUCCESS,timestamp:new Date().toISOString(),executionId,durationMs,data:{toolName,callDepth}})}logToolCallFailure(executionId,toolName,callDepth,durationMs,errorCode){this.emit({type:AUDIT_EVENT_TYPES.TOOL_CALL_FAILURE,timestamp:new Date().toISOString(),executionId,durationMs,data:{toolName,callDepth,errorCode}})}logSecuritySelfReference(executionId,toolName){this.emit({type:AUDIT_EVENT_TYPES.SECURITY_SELF_REFERENCE,timestamp:new Date().toISOString(),executionId,data:{blocked:toolName,reason:"Self-reference attack: attempted to call CodeCall tool from within AgentScript"}})}logSecurityAccessDenied(executionId,toolName,reason){this.emit({type:AUDIT_EVENT_TYPES.SECURITY_ACCESS_DENIED,timestamp:new Date().toISOString(),executionId,data:{blocked:toolName,reason:this.sanitizeError(reason)}})}logSecurityAstBlocked(executionId,pattern,reason){this.emit({type:AUDIT_EVENT_TYPES.SECURITY_AST_BLOCKED,timestamp:new Date().toISOString(),executionId,data:{blocked:pattern,reason:this.sanitizeError(reason)}})}logSearch(executionId,query,resultCount,durationMs){this.emit({type:AUDIT_EVENT_TYPES.SEARCH_PERFORMED,timestamp:new Date().toISOString(),executionId,durationMs,data:{queryLength:query.length,resultCount}})}logDescribe(executionId,toolNames,durationMs){this.emit({type:AUDIT_EVENT_TYPES.DESCRIBE_PERFORMED,timestamp:new Date().toISOString(),executionId,durationMs,data:{toolCount:toolNames.length,toolNames:toolNames.slice(0,10)}})}logInvoke(executionId,toolName,success,durationMs){this.emit({type:AUDIT_EVENT_TYPES.INVOKE_PERFORMED,timestamp:new Date().toISOString(),executionId,durationMs,data:{toolName,success}})}emit(event){const frozenEvent=Object.freeze({...event,data:Object.freeze({...event.data})});for(const listener of this.listeners){try{listener(frozenEvent)}catch{}}}hashScript(script){let hash=0;for(let i=0;i<script.length;i++){const char=script.charCodeAt(i);hash=(hash<<5)-hash+char;hash=hash&hash}return`sh_${(hash>>>0).toString(16).padStart(8,"0")}`}sanitizeError(error){if(!error)return"Unknown error";let sanitized=toClientErrorMessage(error);sanitized=sanitized.replace(/:\d+:\d+/g,"");if(sanitized.length>200){sanitized=sanitized.substring(0,200)+"..."}return sanitized.trim()}};AuditLoggerService=__decorateClass([Provider2({name:"codecall:audit-logger",scope:ProviderScope2.GLOBAL})],AuditLoggerService);import{VectoriaDB}from"vectoriadb";var DEFAULT_SYNONYM_GROUPS=[["create","add","new","insert","make","append","register","generate","produce","build","construct","provision","instantiate","define","compose","draft"],["delete","remove","destroy","drop","erase","clear","purge","discard","eliminate","nuke","unbind","unregister"],["get","fetch","retrieve","read","obtain","load","pull","access","grab","snag","receive"],["update","edit","modify","change","patch","alter","revise","refresh","correct","amend","adjust","tweak","rectify","refine"],["list","show","display","enumerate","browse","view","peek","index","catalog","survey","inspect","ls","dir"],["find","search","lookup","query","locate","filter","scan","explore","investigate","detect","scout","seek"],["archive","shelve","retire","hide","suppress","mute"],["unarchive","restore","recover","undelete","unhide"],["enable","activate","start","turn on","switch on","boot","init","initialize","setup","spin up","resume","unpause"],["disable","deactivate","stop","turn off","switch off","shutdown","halt","kill","terminate","suspend","pause","cease"],["run","execute","invoke","trigger","launch","call","perform","operate","handle","process","fire"],["restart","reboot","reset","reload","bounce","recycle","refresh"],["validate","verify","check","confirm","assert","test","audit","assess","healthcheck","ping"],["analyze","interpret","diagnose","evaluate","review","summarize","count","calculate","compute","measure","aggregate","summarise"],["copy","duplicate","clone","replicate","mirror","fork","repro"],["move","transfer","migrate","relocate","rename","shift","mv","slide"],["save","store","write","persist","commit","stash","record","log"],["sync","synchronize","resync","reconcile","align","pair"],["import","ingest","upload","push","feed"],["export","download","dump","backup","extract"],["connect","link","bind","attach","join","bridge","associate","mount","map"],["disconnect","unlink","unbind","detach","leave","dissociate","unmount","unmap"],["login","log in","sign in","authenticate","auth"],["logout","log out","sign out","disconnect"],["approve","authorize","grant","permit","allow","sanction","whitelist"],["deny","reject","revoke","forbid","block","ban","blacklist"],["encrypt","secure","lock","seal","protect","scramble","hash"],["decrypt","unlock","unseal","reveal","decode"],["deploy","release","ship","publish","roll out","promote","distribute","install"],["debug","troubleshoot","fix","repair","resolve","trace"],["compile","transpile","build","assemble","package","bundle","minify"],["buy","purchase","order","pay","checkout","spend"],["sell","refund","reimburse","charge","invoice","bill"],["subscribe","upgrade","upsell"],["unsubscribe","cancel","downgrade"],["schedule","book","appoint","reserve","plan","calendar"],["reschedule","postpone","delay","defer"],["send","dispatch","deliver","transmit","post","broadcast","notify","alert","email","text","message","chat"],["reply","respond","answer","retort"],["share","forward","retweet","repost"],["like","favorite","star","upvote","heart"],["dislike","downvote"],["follow","watch","track"],["unfollow","ignore","mute"],["user","account","member","profile","identity","customer","principal","admin","operator","client","employee","staff"],["role","group","team","squad","unit","department"],["file","document","attachment","blob","asset","object","resource","content","media"],["image","picture","photo","screenshot"],["video","clip","recording","footage"],["message","notification","alert","event","signal","webhook","ping"],["log","trace","metric","telemetry","audit trail","history"],["settings","config","configuration","preferences","options","params","env","environment","variables"],["permission","privilege","access right","policy","rule","scope"],["organization","company","tenant","workspace","org","project","repo","repository"],["product","item","sku","inventory","stock"],["task","ticket","issue","bug","story","epic","todo","job","workitem"],["id","identifier","key","uuid","guid","token","hash","fingerprint"]];var SynonymExpansionService=class{synonymMap;maxExpansions;constructor(config={}){this.maxExpansions=config.maxExpansionsPerTerm??5;const groups=config.replaceDefaults?config.additionalSynonyms||[]:[...DEFAULT_SYNONYM_GROUPS,...config.additionalSynonyms||[]];this.synonymMap=this.buildSynonymMap(groups)}buildSynonymMap(groups){const map=new Map;for(const group of groups){const normalizedGroup=group.map(term=>term.toLowerCase());for(const term of normalizedGroup){if(!map.has(term)){map.set(term,new Set)}const synonyms=map.get(term);for(const synonym of normalizedGroup){if(synonym!==term){synonyms.add(synonym)}}}}return map}getSynonyms(term){const normalized=term.toLowerCase();const synonyms=this.synonymMap.get(normalized);if(!synonyms){return[]}return Array.from(synonyms).slice(0,this.maxExpansions)}expandQuery(query){const terms=query.toLowerCase().split(/\s+/).filter(term=>term.length>1);const expandedTerms=[];for(const term of terms){expandedTerms.push(term);const synonyms=this.getSynonyms(term);expandedTerms.push(...synonyms)}return expandedTerms.join(" ")}hasExpansions(query){const terms=query.toLowerCase().split(/\s+/);return terms.some(term=>this.synonymMap.has(term))}getStats(){const termCount=this.synonymMap.size;let totalSynonyms=0;for(const synonyms of this.synonymMap.values()){totalSynonyms+=synonyms.size}return{termCount,avgSynonymsPerTerm:termCount>0?totalSynonyms/termCount:0}}};import{defaultTokenizer}from"vectoriadb";function stemTerm(term){if(term.length<=3)return term;if(term.endsWith("ies"))return`${term.slice(0,-3)}y`;if(/(?:x|ch|sh|ss)es$/.test(term))return term.slice(0,-2);if(!term.endsWith("s")||/(?:ss|us|is)$/.test(term))return term;return term.slice(0,-1)}function dotProduct(left,right){let sum=0;for(const[term,weight]of left){sum+=weight*(right.get(term)??0)}return sum}var ToolTfidfIndex=class{constructor(documents=[],stopWords=new Set){this.stopWords=stopWords;const termsOf=documents.map(document=>this.tokenize(document.text));const documentFrequency=new Map;for(const terms of termsOf){for(const term of new Set(terms)){documentFrequency.set(term,(documentFrequency.get(term)??0)+1)}}for(const[term,frequency]of documentFrequency){this.idf.set(term,Math.log((1+documents.length)/(1+frequency))+1)}documents.forEach((document,index)=>{this.vectors.set(document.id,{metadata:document.metadata,vector:this.vectorOf(termsOf[index])})})}stopWords;idf=new Map;vectors=new Map;search(query,{topK,threshold,filter}){const queryVector=this.vectorOf(this.tokenize(query));const results=[];for(const[id,{metadata,vector}]of this.vectors){if(filter&&!filter(metadata))continue;const score=dotProduct(queryVector,vector);if(score>=threshold)results.push({id,metadata,score})}return results.sort((left,right)=>right.score-left.score).slice(0,topK)}getAllDocumentIds(){return[...this.vectors.keys()]}getDocumentCount(){return this.vectors.size}hasDocument(id){return this.vectors.has(id)}tokenize(text){return defaultTokenizer(text).filter(term=>!this.stopWords.has(term)).map(stemTerm)}vectorOf(terms){const vector=new Map;for(const term of terms){const idf=this.idf.get(term);if(idf!==void 0)vector.set(term,(vector.get(term)??0)+idf)}const norm=Math.sqrt([...vector.values()].reduce((sum,weight)=>sum+weight*weight,0));if(norm===0)return vector;for(const[term,weight]of vector){vector.set(term,weight/norm)}return vector}};var STOP_WORDS=new Set(["the","a","an","this","that","these","those","in","on","at","to","for","of","with","by","from","into","over","after","before","between","under","about","against","during","through","and","or","but","nor","so","yet","as","than","if","because","while","when","where","unless","i","me","my","mine","myself","you","your","yours","yourself","he","him","his","himself","she","her","hers","herself","it","its","itself","we","us","our","ours","ourselves","they","them","their","theirs","themselves","who","whom","whose","which","what","is","was","are","were","been","be","being","have","has","had","having","do","does","did","doing","will","would","shall","should","can","could","may","might","must","all","any","both","each","few","more","most","other","some","such","no","nor","not","only","own","same","too","very","just","even","please","pls","plz","thanks","thank","thx","hello","hi","hey","ok","okay","yes","no","actually","basically","literally","maybe","perhaps","now","then","here","there","again","once","back","example","context","optionally","optional","etc","ie","eg"]);var DEFAULT_EMBEDDING_MODEL="Xenova/all-MiniLM-L6-v2";function messageOf(error){return error instanceof Error?error.message:String(error)}var ToolSearchService=class _ToolSearchService{static MAX_SUBSCRIPTION_RETRIES=100;static INITIAL_RETRY_DELAY_MS=10;static MAX_RETRY_DELAY_MS=1e3;vectorDB;strategy;initialized=false;mlInitialized=false;config;scope;unsubscribe;synonymService=null;synonymExpansion;indexing;subscriptionPromise;subscriptionResolved=false;subscriptionResolve=null;subscriptionReject=null;retryTimeoutId=null;disposed=false;availabilityByTool=new Map;constructor(config={},scope){this.scope=scope;const embeddingOptions=config.embeddingOptions||{strategy:"tfidf",modelName:DEFAULT_EMBEDDING_MODEL,cacheDir:"./.cache/transformers",useHNSW:false,synonymExpansion:{enabled:true,replaceDefaults:false,maxExpansionsPerTerm:5}};this.strategy=config.strategy||embeddingOptions.strategy||"tfidf";this.config={strategy:this.strategy,embeddingOptions,defaultTopK:config.defaultTopK??8,defaultSimilarityThreshold:config.defaultSimilarityThreshold??0,mode:config.mode??"codecall_only",includeTools:config.includeTools};const validModes=["codecall_only","codecall_opt_in","metadata_driven"];if(!validModes.includes(this.config.mode)){throw new Error(`Invalid CodeCall mode: ${this.config.mode}. Valid modes: ${validModes.join(", ")}`)}if(this.strategy==="ml"){this.vectorDB=new VectoriaDB({modelName:embeddingOptions.modelName||DEFAULT_EMBEDDING_MODEL,cacheDir:embeddingOptions.cacheDir||"./.cache/transformers",defaultTopK:this.config.defaultTopK,defaultSimilarityThreshold:this.config.defaultSimilarityThreshold,useHNSW:embeddingOptions.useHNSW||false})}else{this.vectorDB=this.createTfidfIndex()}this.synonymExpansion=config.synonymExpansion??embeddingOptions.synonymExpansion;if(this.strategy==="tfidf"){this.synonymService=this.createSynonymService()}this.subscriptionPromise=new Promise((resolve,reject)=>{this.subscriptionResolve=resolve;this.subscriptionReject=reject});this.setupSubscription()}createTfidfIndex(documents=[]){return new ToolTfidfIndex(documents,STOP_WORDS)}createSynonymService(){const synonymExpansion=this.synonymExpansion;if(synonymExpansion===false||synonymExpansion?.enabled===false)return null;return new SynonymExpansionService(synonymExpansion??{})}async ensureSubscribed(){if(this.subscriptionResolved){return}await this.subscriptionPromise}setupSubscription(retryCount=0,delayMs=_ToolSearchService.INITIAL_RETRY_DELAY_MS){if(this.scope.tools){this.subscribeToToolChanges();return}if(retryCount>=_ToolSearchService.MAX_SUBSCRIPTION_RETRIES){this.scope.logger.warn("ToolSearchService: scope.tools not available after max retries. Tool search will return incomplete results until tools are registered.");this.markSubscribed();return}const nextDelay=Math.min(delayMs*2,_ToolSearchService.MAX_RETRY_DELAY_MS);this.retryTimeoutId=setTimeout(()=>{this.retryTimeoutId=null;if(this.disposed){return}this.setupSubscription(retryCount+1,nextDelay)},delayMs)}subscribeToToolChanges(){this.unsubscribe=this.scope.tools.subscribe({immediate:true},event=>{this.queueReindex(event.snapshot)});this.markSubscribed()}queueReindex(tools){const reindex=()=>this.handleToolChange(tools);const run=(this.indexing?this.indexing.then(reindex):reindex()).catch(error=>{this.scope.logger.warn(`CodeCall tool search could not index the tools: ${messageOf(error)}`)});this.indexing=run;void run.then(()=>{if(this.indexing===run)this.indexing=void 0})}markSubscribed(){this.subscriptionResolved=true;if(this.subscriptionResolve){this.subscriptionResolve();this.subscriptionResolve=null}}async handleToolChange(tools){if(tools.length>0&&!this.mlInitialized&&this.strategy==="ml"&&this.vectorDB instanceof VectoriaDB){try{await this.vectorDB.initialize();this.mlInitialized=true}catch(error){this.fallBackToTfidf(error)}}const availabilityByTool=new Map;const documents=tools.flatMap(tool=>this.toDocuments(tool,availabilityByTool));await this.replaceIndex(documents);this.availabilityByTool=availabilityByTool;this.initialized=true}toDocuments(tool,availabilityByTool){try{if(!this.shouldIndexTool(tool))return[];const toolName=tool.name;const document={id:toolName,text:this.extractSearchableText(tool),metadata:{id:toolName,toolName,qualifiedName:tool.fullName||toolName,appId:this.extractAppId(tool),toolInstance:tool}};availabilityByTool.set(toolName,tool.metadata.availableWhen);return[document]}catch(error){this.scope.logger.warn(`CodeCall tool search skipped tool "${tool.name}": ${messageOf(error)}`);return[]}}async replaceIndex(documents){if(this.vectorDB instanceof VectoriaDB){try{this.vectorDB.clear();if(documents.length>0)await this.vectorDB.addMany(documents);return}catch(error){this.fallBackToTfidf(error)}}this.vectorDB=this.createTfidfIndex(documents)}fallBackToTfidf(error){const modelName=this.config.embeddingOptions.modelName||DEFAULT_EMBEDDING_MODEL;this.scope.logger.warn(`CodeCall could not use embedding model "${modelName}" (${messageOf(error)}); tool search uses TF-IDF instead`);this.strategy="tfidf";this.vectorDB=this.createTfidfIndex();this.synonymService=this.createSynonymService()}shouldIndexTool(tool){return checkCodeCallToolPolicy(toCodeCallPolicyTool(tool,void 0,this.scope),this.config).allowed}async initialize(){}dispose(){this.disposed=true;if(this.retryTimeoutId){clearTimeout(this.retryTimeoutId);this.retryTimeoutId=null}if(this.subscriptionReject){this.subscriptionReject(new Error("ToolSearchService disposed before subscription completed"));this.subscriptionReject=null;this.subscriptionResolve=null}if(this.unsubscribe){this.unsubscribe();this.unsubscribe=void 0}}extractSearchableText(tool){const parts=[];if(tool.name){const nameParts=tool.name.split(/[:\-_.]/).filter(Boolean);for(const part of nameParts){parts.push(part,part)}}if(tool.metadata.description){const description=tool.metadata.description;parts.push(description,description,description);const keyTerms=description.toLowerCase().split(/\s+/).filter(word=>word.length>=4&&!this.isStopWord(word));parts.push(...keyTerms)}if(tool.metadata.tags&&tool.metadata.tags.length>0){for(const tag of tool.metadata.tags){parts.push(tag,tag)}}if(tool.rawInputSchema&&typeof tool.rawInputSchema==="object"){const schema=tool.rawInputSchema;if(schema.properties){parts.push(...Object.keys(schema.properties))}}const examples=tool.metadata?.examples;if(examples&&Array.isArray(examples)){for(const ex of examples){if(ex.description){parts.push(ex.description,ex.description)}if(ex.input&&typeof ex.input==="object"){for(const[key,value]of Object.entries(ex.input)){parts.push(key);if(typeof value==="string"){parts.push(value)}}}}}return parts.join(" ")}isStopWord(word){return STOP_WORDS.has(word)}extractAppId(tool){return codeCallAppIdOf(this.scope,tool)}async search(query,options={}){await this.ensureSubscribed();await this.indexing;const{topK=this.config.defaultTopK,appIds,excludeToolNames=[],surface}=options;const minScore=this.config.defaultSimilarityThreshold;const filter=metadata=>{if(excludeToolNames.includes(metadata.toolName)){return false}if(!isOfferedToCaller(metadata.toolInstance.metadata.availableWhen,surface)){return false}if(appIds&&appIds.length>0){if(!metadata.appId||!appIds.includes(metadata.appId)){return false}}return true};const effectiveQuery=this.synonymService?this.synonymService.expandQuery(query):query;const results=await this.vectorDB.search(effectiveQuery,{topK,threshold:minScore,filter});return results.map(result=>({toolName:result.metadata.toolName,appId:result.metadata.appId,description:result.metadata.toolInstance.metadata.description||"",relevanceScore:result.score}))}getAllToolNames(){if(this.vectorDB instanceof VectoriaDB){return this.vectorDB.getAll().map(doc=>doc.id)}else{return this.vectorDB.getAllDocumentIds()}}getTotalCount(surface){if(surface!==void 0){return this.getAllToolNames().filter(toolName=>this.hasTool(toolName,surface)).length}if(this.vectorDB instanceof VectoriaDB){return this.vectorDB.size()}else{return this.vectorDB.getDocumentCount()}}hasTool(toolName,surface){const indexed=this.vectorDB instanceof VectoriaDB?this.vectorDB.has(toolName):this.vectorDB.hasDocument(toolName);return indexed&&isOfferedToCaller(this.availabilityByTool.get(toolName),surface)}clear(){if(this.vectorDB instanceof VectoriaDB){this.vectorDB.clear()}else{this.vectorDB=this.createTfidfIndex()}this.availabilityByTool=new Map;this.initialized=false}getStrategy(){return this.strategy}isInitialized(){return this.initialized}};import{Enclave}from"@enclave-vm/core";import{Provider as Provider3,ProviderScope as ProviderScope3}from"@frontmcp/sdk";import{ForbiddenLoopRule,JSAstValidator,ValidationSeverity}from"@enclave-vm/ast";var AGENTSCRIPT_PARSE_OPTIONS={ecmaVersion:"latest",sourceType:"script",allowReturnOutsideFunction:true,allowAwaitOutsideFunction:true};var PARSE_ATTEMPTS=[{wrap:code=>code,parseOptions:AGENTSCRIPT_PARSE_OPTIONS,lineOffset:0},{wrap:code=>code,parseOptions:{...AGENTSCRIPT_PARSE_OPTIONS,sourceType:"module"},lineOffset:0},{wrap:code=>`async function __temp__() {
1
+ var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;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};import CachePlugin from"@frontmcp/plugin-cache";import{DynamicPlugin,FrontMcpLogger,FrontMcpToolTokens,isEntryGatedBy,ListToolsHook,Plugin,resolveToolVisibility,ScopeEntry,ToolHook,ToolNotFoundError}from"@frontmcp/sdk";import{z}from"@frontmcp/lazy-zod";var directCallsFilterSchema=z.custom(val=>typeof val==="function",{message:"filter must be a function with signature (tool: DirectCallsFilterToolInfo) => boolean"});var includeToolsFilterSchema=z.custom(val=>typeof val==="function",{message:"includeTools must be a function with signature (tool: IncludeToolsFilterToolInfo) => boolean"});var codeCallModeSchema=z.enum(["codecall_only","codecall_opt_in","metadata_driven"]).default("codecall_only");var codeCallVmPresetSchema=z.enum(["locked_down","secure","balanced","experimental"]).default("secure");var DEFAULT_VM_OPTIONS={preset:"secure"};var codeCallVmOptionsSchema=z.object({preset:codeCallVmPresetSchema,timeoutMs:z.number().positive().optional(),allowLoops:z.boolean().optional(),maxSteps:z.number().positive().optional(),disabledBuiltins:z.array(z.string()).optional(),disabledGlobals:z.array(z.string()).optional(),allowConsole:z.boolean().optional(),maxSanitizeDepth:z.number().positive().optional(),maxSanitizeProperties:z.number().positive().optional(),rapidEnumerationThreshold:z.number().int().positive().optional(),rapidEnumerationOverrides:z.record(z.string(),z.number().int().positive()).optional()}).default(()=>DEFAULT_VM_OPTIONS);var codeCallDirectCallsOptionsSchema=z.object({enabled:z.boolean(),allowedTools:z.array(z.string()).optional(),filter:directCallsFilterSchema.optional()});var embeddingStrategySchema=z.enum(["tfidf","ml"]).default("tfidf");var synonymExpansionConfigSchema=z.object({enabled:z.boolean().default(true),additionalSynonyms:z.array(z.array(z.string())).optional(),replaceDefaults:z.boolean().default(false),maxExpansionsPerTerm:z.number().positive().default(5)}).default({enabled:true,replaceDefaults:false,maxExpansionsPerTerm:5});var DEFAULT_EMBEDDING_OPTIONS={strategy:"tfidf",modelName:"Xenova/all-MiniLM-L6-v2",cacheDir:"./.cache/transformers",useHNSW:false,synonymExpansion:{enabled:true,replaceDefaults:false,maxExpansionsPerTerm:5}};var codeCallEmbeddingOptionsSchema=z.object({strategy:embeddingStrategySchema.optional(),modelName:z.string().optional(),cacheDir:z.string().optional(),useHNSW:z.boolean().optional(),synonymExpansion:z.union([z.literal(false),synonymExpansionConfigSchema]).optional()}).optional().transform(opts=>({strategy:opts?.strategy??DEFAULT_EMBEDDING_OPTIONS.strategy,modelName:opts?.modelName??DEFAULT_EMBEDDING_OPTIONS.modelName,cacheDir:opts?.cacheDir??DEFAULT_EMBEDDING_OPTIONS.cacheDir,useHNSW:opts?.useHNSW??DEFAULT_EMBEDDING_OPTIONS.useHNSW,synonymExpansion:opts?.synonymExpansion??DEFAULT_EMBEDDING_OPTIONS.synonymExpansion}));var codeCallSidecarOptionsSchema=z.object({enabled:z.boolean().default(false),maxTotalSize:z.number().positive().optional(),maxReferenceSize:z.number().positive().optional(),extractionThreshold:z.number().positive().optional(),maxResolvedSize:z.number().positive().optional(),allowComposites:z.boolean().optional(),maxScriptLengthWhenDisabled:z.number().positive().nullable().default(64*1024)}).default(()=>({enabled:false,maxScriptLengthWhenDisabled:64*1024}));var codeCallPluginOptionsObjectSchema=z.object({mode:codeCallModeSchema,appIds:z.array(z.string()).optional(),topK:z.number().positive().default(8),maxDefinitions:z.number().int().positive().default(8),includeTools:includeToolsFilterSchema.optional(),directCalls:codeCallDirectCallsOptionsSchema.optional(),vm:codeCallVmOptionsSchema,embedding:codeCallEmbeddingOptionsSchema,sidecar:codeCallSidecarOptionsSchema});var DEFAULT_PLUGIN_OPTIONS={mode:"codecall_only",topK:8,maxDefinitions:8,vm:DEFAULT_VM_OPTIONS,embedding:DEFAULT_EMBEDDING_OPTIONS,sidecar:{enabled:false,maxScriptLengthWhenDisabled:64*1024}};var codeCallPluginOptionsSchema=codeCallPluginOptionsObjectSchema.prefault(DEFAULT_PLUGIN_OPTIONS);import{BaseConfig,Provider,ProviderScope}from"@frontmcp/sdk";var CodeCallConfig=class extends BaseConfig{constructor(options={}){const parsedConfig=codeCallPluginOptionsSchema.parse(options);const resolvedVm=resolveVmOptions(parsedConfig.vm);super({...parsedConfig,resolvedVm})}};CodeCallConfig=__decorateClass([Provider({name:"codecall:config",description:"CodeCall plugin configuration with validated defaults",scope:ProviderScope.GLOBAL})],CodeCallConfig);var MAX_ITERATIONS_PER_LOOP=1e4;function maxToolCallsOf(vmOptions){return vmOptions.maxSteps||100}var SANDBOX_RAPID_ENUMERATION_THRESHOLD=30;function rapidEnumerationThresholdOf(vmOptions){return vmOptions.rapidEnumerationThreshold??SANDBOX_RAPID_ENUMERATION_THRESHOLD}function resolveVmOptions(vmOptions){const preset=vmOptions?.preset??"secure";const base=presetDefaults(preset);return{...base,...vmOptions,disabledBuiltins:vmOptions?.disabledBuiltins??base.disabledBuiltins,disabledGlobals:vmOptions?.disabledGlobals??base.disabledGlobals,allowConsole:vmOptions?.allowConsole===true}}function presetDefaults(preset){switch(preset){case"locked_down":return{preset,timeoutMs:2e3,allowLoops:false,allowConsole:false,maxSteps:2e3,disabledBuiltins:["eval","Function","AsyncFunction"],disabledGlobals:["require","process","fetch","setTimeout","setInterval","setImmediate","global","globalThis"],maxSanitizeDepth:10,maxSanitizeProperties:1e3};case"balanced":return{preset,timeoutMs:5e3,allowLoops:true,allowConsole:false,maxSteps:1e4,disabledBuiltins:["eval","Function","AsyncFunction"],disabledGlobals:["require","process","fetch"],maxSanitizeDepth:50,maxSanitizeProperties:5e3};case"experimental":return{preset,timeoutMs:1e4,allowLoops:true,allowConsole:false,maxSteps:2e4,disabledBuiltins:["eval","Function","AsyncFunction"],disabledGlobals:["require","process"],maxSanitizeDepth:100,maxSanitizeProperties:2e4};case"secure":default:return{preset:"secure",timeoutMs:3500,allowLoops:false,allowConsole:false,maxSteps:5e3,disabledBuiltins:["eval","Function","AsyncFunction"],disabledGlobals:["require","process","fetch","setTimeout","setInterval","setImmediate","global","globalThis"],maxSanitizeDepth:50,maxSanitizeProperties:2e3}}}import{getRunningTool}from"@frontmcp/sdk";var CODECALL_DISPATCH=Symbol("frontmcp.codecall.dispatch");function asCodeCallDispatch(ctx){return Object.defineProperty(ctx,CODECALL_DISPATCH,{value:true,enumerable:false})}function isInProcessDispatch(ctx){if(getRunningTool())return true;if(typeof ctx!=="object"||ctx===null)return false;const marks=ctx;return marks[CODECALL_DISPATCH]===true||marks.internalCall===true}var BLOCKED_NAMESPACE_PATTERNS=Object.freeze([/^system:/,/^internal:/,/^__/]);function isOfferedToCaller(availableWhen,surface){const offered=availableWhen?.surface;return offered===void 0||surface===void 0||offered.includes(surface)}var ALLOWED={allowed:true};function deny(reason){return{allowed:false,reason}}function codeCallAppIdOf(scope,entry){const lineage=scope?.tools?.lineageOf?.(entry)??[];const owners=entry.owner?[...lineage,entry.owner]:lineage;return owners.find(owner=>owner.kind==="app")?.id}function toCodeCallPolicyTool(entry,requestedName,scope){const{metadata}=entry;return{name:entry.name||entry.fullName,fullName:entry.fullName,aliases:requestedName?[requestedName]:void 0,appId:codeCallAppIdOf(scope,entry),description:metadata?.description,tags:metadata?.tags,hidden:metadata?.hideFromDiscovery===true||metadata?.visibility==="hidden"||metadata?.visibility==="internal",codecall:metadata?.codecall,annotations:metadata?.annotations,metadata}}function isPlainData(value){if(Array.isArray(value))return true;const proto=Object.getPrototypeOf(value);return proto===Object.prototype||proto===null}function readOnlyCopy(value,copies){if(typeof value!=="object"||value===null||!isPlainData(value))return value;const existing=copies.get(value);if(existing!==void 0)return existing;const copy=Array.isArray(value)?[]:Object.create(Object.getPrototypeOf(value));copies.set(value,copy);for(const key of Reflect.ownKeys(value)){if(!Object.prototype.propertyIsEnumerable.call(value,key))continue;Object.defineProperty(copy,key,{value:readOnlyCopy(Reflect.get(value,key),copies),enumerable:true,writable:true,configurable:true})}return Object.freeze(copy)}function toToolFilterInfo(tool){const copies=new WeakMap;const annotations=readOnlyCopy(tool.annotations,copies);const metadata=tool.metadata?readOnlyCopy({...tool.metadata,...annotations?{annotations:tool.annotations}:{}},copies):void 0;return{name:tool.name,fullName:tool.fullName,appId:tool.appId,source:tool.codecall?.source,description:tool.description,tags:readOnlyCopy(tool.codecall?.tags??tool.tags,copies),annotations,metadata}}function ownNamesOf(tool){return[tool.name,tool.fullName].filter(candidate=>!!candidate)}function checkCodeCallToolPolicy(tool,config){const{name}=tool;const spellings=[...ownNamesOf(tool),...tool.aliases??[]];if(spellings.some(candidate=>candidate.startsWith("codecall:"))){return deny("CodeCall meta-tools are not callable from CodeCall")}for(const candidate of spellings){if(BLOCKED_NAMESPACE_PATTERNS.some(pattern=>pattern.test(candidate))){return deny(`Tool "${candidate}" is in a namespace CodeCall never calls`)}}if(tool.hidden===true){return deny(`Tool "${name}" is hidden from discovery`)}const enabled=tool.codecall?.enabledInCodeCall;switch(config.mode){case"codecall_only":case"metadata_driven":if(enabled===false){return deny(`Tool "${name}" sets enabledInCodeCall: false`)}break;case"codecall_opt_in":if(enabled!==true){return deny(`Tool "${name}" has not opted in to CodeCall`)}break;default:return deny(`Unknown CodeCall mode: ${String(config.mode)}`)}if(config.includeTools&&!config.includeTools(toToolFilterInfo(tool))){return deny(`Tool "${name}" is excluded by the includeTools filter`)}return ALLOWED}function denyUnknownTool(name){return deny(`Tool "${name}" is not available through CodeCall`)}function resolveCodeCallTool(scope,name){const otherSpelling=/[-_]/.test(name)?name.includes("_")?name.replace(/_/g,"-"):name.replace(/-/g,"_"):void 0;const candidates=otherSpelling?[name,otherSpelling]:[name];const declaresAlias=entry=>entry.metadata?.aliases?.includes(name)===true;const matches=entry=>candidates.includes(entry.fullName)||candidates.includes(entry.name);return findResolvableTool(scope,declaresAlias)??findResolvableTool(scope,matches)}function findResolvableTool(scope,matches){const typedScope=scope;const local=typedScope.tools?.getTools(true)?.find(matches);if(local)return local;const registries=typedScope.providers?.getRegistries?.("AppRegistry")??[];for(const registry of registries){for(const app of registry.getApps()){if(!app.isRemote)continue;const remote=app.tools.getTools(true).find(matches);if(remote)return remote}}return void 0}function checkDirectCallPolicy(tool,directCalls){if(!directCalls)return ALLOWED;if(directCalls.enabled===false){return deny("Direct tool invocation is disabled")}const{allowedTools}=directCalls;if(allowedTools&&!ownNamesOf(tool).some(ownName=>allowedTools.includes(ownName))){return deny(`Tool "${tool.name}" is not in the direct-call allowlist`)}if(directCalls.filter&&!directCalls.filter(toToolFilterInfo(tool))){return deny(`Tool "${tool.name}" is excluded by the directCalls filter`)}return ALLOWED}function readCodeCallPolicyConfig(config){return{mode:config.get("mode")??"codecall_only",includeTools:config.get("includeTools")}}function checkCodeCallToolAccess(scope,config,name,options={}){const entry=resolveCodeCallTool(scope,name);if(!entry)return denyUnknownTool(name);if(!isOfferedToCaller(entry.metadata?.availableWhen,options.surface)){return deny(`Tool "${name}" is not offered on the caller's surface "${options.surface}"`)}const policyTool=toCodeCallPolicyTool(entry,name,scope);const baseDecision=checkCodeCallToolPolicy(policyTool,readCodeCallPolicyConfig(config));if(!baseDecision.allowed)return baseDecision;if(options.directCall){const directDecision=checkDirectCallPolicy(policyTool,config.get("directCalls"));if(!directDecision.allowed)return directDecision}return{allowed:true,entry}}var EMBEDDED_STACK_FRAME_RE=/\n[ \t]*at\s[^\n]*/g;var QUOTED_PATH_RE=/(['"`])((?:~?\/|[A-Za-z]:[\\/]|\\\\)[^\s'"`\\/][^'"`\n]*)\1/g;var URL_RE=/\b[A-Za-z][A-Za-z0-9+.-]{1,31}:\/\/(?:[^\s'"`<>,;]|[,;](?!~?\/|[A-Za-z]:[\\/]|\\\\))*/g;var QUERY_PATH_VALUE_RE=/([?&][^=&#?]*=)(?:~?\/|[A-Za-z]:[\\/]|\\\\)[^&#]*/g;var POSIX_SEGMENT=String.raw`[^\s/\\'"\x60<>|,;:()\[\]{}]+`;var WINDOWS_SEGMENT=String.raw`[^\s/\\'"\x60<>|,;:*?]+`;function segments(segment,separator){const spaced=`${segment}(?: ${segment}){0,2}`;return`(?:(?:${spaced}${separator})+(?:${segment})?|${segment})`}var UNQUOTED_PATH_RE=new RegExp([String.raw`(?<![\w.~/\\)\]-])~?/+${segments(POSIX_SEGMENT,"/+")}`,String.raw`(?<![\w\\/])[A-Za-z]:[\\/]+${segments(WINDOWS_SEGMENT,String.raw`[\\/]+`)}?`,String.raw`(?<![\w\\])\\\\${segments(WINDOWS_SEGMENT,String.raw`[\\/]+`)}`].join("|"),"g");function redactPaths(text){return text.replace(QUOTED_PATH_RE,"$1[path]$1").replace(UNQUOTED_PATH_RE,"[path]")}function toClientErrorMessage(message){if(!message)return"";return redactAbsolutePaths(message.replace(EMBEDDED_STACK_FRAME_RE,""))}function redactAbsolutePaths(text){let result="";let last=0;for(const match of text.matchAll(URL_RE)){const start=match.index??0;result+=redactPaths(text.slice(last,start));result+=/^file:/i.test(match[0])?"[path]":match[0].replace(QUERY_PATH_VALUE_RE,"$1[path]");last=start+match[0].length}return result+redactPaths(text.slice(last))}var TOOL_CALL_ERROR_CODES={NOT_FOUND:"NOT_FOUND",VALIDATION:"VALIDATION",EXECUTION:"EXECUTION",TIMEOUT:"TIMEOUT",ACCESS_DENIED:"ACCESS_DENIED",RATE_LIMITED:"RATE_LIMITED",SELF_REFERENCE:"SELF_REFERENCE"};function createToolCallError(code,toolName,rawMessage){const sanitizedMessage=getSanitizedMessage(code,toolName,rawMessage);return Object.freeze({code,message:sanitizedMessage,toolName})}function createPublicToolCallError(code,toolName,publicMessage){return Object.freeze({code,message:toClientErrorMessage(publicMessage).trim()||getSanitizedMessage(code,toolName),toolName})}function getSanitizedMessage(code,toolName,rawMessage){switch(code){case TOOL_CALL_ERROR_CODES.NOT_FOUND:return`Tool "${toolName}" was not found`;case TOOL_CALL_ERROR_CODES.VALIDATION:return rawMessage?sanitizeValidationMessage(rawMessage):`Input validation failed for tool "${toolName}"`;case TOOL_CALL_ERROR_CODES.EXECUTION:return`Tool "${toolName}" execution failed`;case TOOL_CALL_ERROR_CODES.TIMEOUT:return`Tool "${toolName}" execution timed out`;case TOOL_CALL_ERROR_CODES.ACCESS_DENIED:return`Access denied for tool "${toolName}"`;case TOOL_CALL_ERROR_CODES.RATE_LIMITED:return`Tool "${toolName}" was rate limited`;case TOOL_CALL_ERROR_CODES.SELF_REFERENCE:return`Cannot call CodeCall tools from within AgentScript`;default:return`An error occurred while calling "${toolName}"`}}function sanitizeValidationMessage(message){let sanitized=toClientErrorMessage(message);sanitized=sanitized.replace(/\bat line \d+/gi,"");sanitized=sanitized.replace(/\bline \d+/gi,"");sanitized=sanitized.replace(/:\d+:\d+/g,"");if(sanitized.length>200){sanitized=sanitized.substring(0,200)+"..."}return sanitized.trim()}var SelfReferenceError=class extends Error{code=TOOL_CALL_ERROR_CODES.SELF_REFERENCE;toolName;constructor(toolName){super(`Self-reference attack: Attempted to call CodeCall tool "${toolName}" from within AgentScript`);this.name="SelfReferenceError";this.toolName=toolName;Object.freeze(this)}};var CODECALL_TOOL_PREFIX="codecall:";var BLOCKED_CODECALL_TOOLS=Object.freeze(new Set(["codecall:search","codecall:describe","codecall:execute","codecall:invoke"]));function isBlockedSelfReference(toolName){const normalizedName=toolName.toLowerCase().trim();if(normalizedName.startsWith(CODECALL_TOOL_PREFIX)){return true}if(BLOCKED_CODECALL_TOOLS.has(toolName)){return true}return false}function assertNotSelfReference(toolName){if(isBlockedSelfReference(toolName)){throw new SelfReferenceError(toolName)}}import{Provider as Provider2,ProviderScope as ProviderScope2}from"@frontmcp/sdk";var AUDIT_EVENT_TYPES={EXECUTION_START:"codecall:execution:start",EXECUTION_SUCCESS:"codecall:execution:success",EXECUTION_FAILURE:"codecall:execution:failure",EXECUTION_TIMEOUT:"codecall:execution:timeout",TOOL_CALL_START:"codecall:tool:call:start",TOOL_CALL_SUCCESS:"codecall:tool:call:success",TOOL_CALL_FAILURE:"codecall:tool:call:failure",SECURITY_SELF_REFERENCE:"codecall:security:self-reference",SECURITY_ACCESS_DENIED:"codecall:security:access-denied",SECURITY_AST_BLOCKED:"codecall:security:ast-blocked",SEARCH_PERFORMED:"codecall:search:performed",DESCRIBE_PERFORMED:"codecall:describe:performed",INVOKE_PERFORMED:"codecall:invoke:performed"};var AuditLoggerService=class{listeners=new Set;executionCounter=0;subscribe(listener){this.listeners.add(listener);return()=>{this.listeners.delete(listener)}}generateExecutionId(){const timestamp=Date.now().toString(36);const counter=(++this.executionCounter).toString(36).padStart(4,"0");const random=Math.random().toString(36).substring(2,8);return`exec_${timestamp}_${counter}_${random}`}logExecutionStart(executionId,script){this.emit({type:AUDIT_EVENT_TYPES.EXECUTION_START,timestamp:new Date().toISOString(),executionId,data:{scriptHash:this.hashScript(script),scriptLength:script.length}})}logExecutionSuccess(executionId,script,durationMs,toolCallCount){this.emit({type:AUDIT_EVENT_TYPES.EXECUTION_SUCCESS,timestamp:new Date().toISOString(),executionId,durationMs,data:{scriptHash:this.hashScript(script),scriptLength:script.length,toolCallCount}})}logExecutionFailure(executionId,script,durationMs,error){this.emit({type:AUDIT_EVENT_TYPES.EXECUTION_FAILURE,timestamp:new Date().toISOString(),executionId,durationMs,data:{scriptHash:this.hashScript(script),scriptLength:script.length,error:this.sanitizeError(error)}})}logExecutionTimeout(executionId,script,durationMs){this.emit({type:AUDIT_EVENT_TYPES.EXECUTION_TIMEOUT,timestamp:new Date().toISOString(),executionId,durationMs,data:{scriptHash:this.hashScript(script),scriptLength:script.length}})}logToolCallStart(executionId,toolName,callDepth){this.emit({type:AUDIT_EVENT_TYPES.TOOL_CALL_START,timestamp:new Date().toISOString(),executionId,data:{toolName,callDepth}})}logToolCallSuccess(executionId,toolName,callDepth,durationMs){this.emit({type:AUDIT_EVENT_TYPES.TOOL_CALL_SUCCESS,timestamp:new Date().toISOString(),executionId,durationMs,data:{toolName,callDepth}})}logToolCallFailure(executionId,toolName,callDepth,durationMs,errorCode){this.emit({type:AUDIT_EVENT_TYPES.TOOL_CALL_FAILURE,timestamp:new Date().toISOString(),executionId,durationMs,data:{toolName,callDepth,errorCode}})}logSecuritySelfReference(executionId,toolName){this.emit({type:AUDIT_EVENT_TYPES.SECURITY_SELF_REFERENCE,timestamp:new Date().toISOString(),executionId,data:{blocked:toolName,reason:"Self-reference attack: attempted to call CodeCall tool from within AgentScript"}})}logSecurityAccessDenied(executionId,toolName,reason){this.emit({type:AUDIT_EVENT_TYPES.SECURITY_ACCESS_DENIED,timestamp:new Date().toISOString(),executionId,data:{blocked:toolName,reason:this.sanitizeError(reason)}})}logSecurityAstBlocked(executionId,pattern,reason){this.emit({type:AUDIT_EVENT_TYPES.SECURITY_AST_BLOCKED,timestamp:new Date().toISOString(),executionId,data:{blocked:pattern,reason:this.sanitizeError(reason)}})}logSearch(executionId,query,resultCount,durationMs){this.emit({type:AUDIT_EVENT_TYPES.SEARCH_PERFORMED,timestamp:new Date().toISOString(),executionId,durationMs,data:{queryLength:query.length,resultCount}})}logDescribe(executionId,toolNames,durationMs){this.emit({type:AUDIT_EVENT_TYPES.DESCRIBE_PERFORMED,timestamp:new Date().toISOString(),executionId,durationMs,data:{toolCount:toolNames.length,toolNames:toolNames.slice(0,10)}})}logInvoke(executionId,toolName,success,durationMs){this.emit({type:AUDIT_EVENT_TYPES.INVOKE_PERFORMED,timestamp:new Date().toISOString(),executionId,durationMs,data:{toolName,success}})}emit(event){const frozenEvent=Object.freeze({...event,data:Object.freeze({...event.data})});for(const listener of this.listeners){try{listener(frozenEvent)}catch{}}}hashScript(script){let hash=0;for(let i=0;i<script.length;i++){const char=script.charCodeAt(i);hash=(hash<<5)-hash+char;hash=hash&hash}return`sh_${(hash>>>0).toString(16).padStart(8,"0")}`}sanitizeError(error){if(!error)return"Unknown error";let sanitized=toClientErrorMessage(error);sanitized=sanitized.replace(/:\d+:\d+/g,"");if(sanitized.length>200){sanitized=sanitized.substring(0,200)+"..."}return sanitized.trim()}};AuditLoggerService=__decorateClass([Provider2({name:"codecall:audit-logger",scope:ProviderScope2.GLOBAL})],AuditLoggerService);import{VectoriaDB}from"vectoriadb";var DEFAULT_SYNONYM_GROUPS=[["create","add","new","insert","make","append","register","generate","produce","build","construct","provision","instantiate","define","compose","draft"],["delete","remove","destroy","drop","erase","clear","purge","discard","eliminate","nuke","unbind","unregister"],["get","fetch","retrieve","read","obtain","load","pull","access","grab","snag","receive"],["update","edit","modify","change","patch","alter","revise","refresh","correct","amend","adjust","tweak","rectify","refine"],["list","show","display","enumerate","browse","view","peek","index","catalog","survey","inspect","ls","dir"],["find","search","lookup","query","locate","filter","scan","explore","investigate","detect","scout","seek"],["archive","shelve","retire","hide","suppress","mute"],["unarchive","restore","recover","undelete","unhide"],["enable","activate","start","turn on","switch on","boot","init","initialize","setup","spin up","resume","unpause"],["disable","deactivate","stop","turn off","switch off","shutdown","halt","kill","terminate","suspend","pause","cease"],["run","execute","invoke","trigger","launch","call","perform","operate","handle","process","fire"],["restart","reboot","reset","reload","bounce","recycle","refresh"],["validate","verify","check","confirm","assert","test","audit","assess","healthcheck","ping"],["analyze","interpret","diagnose","evaluate","review","summarize","count","calculate","compute","measure","aggregate","summarise"],["copy","duplicate","clone","replicate","mirror","fork","repro"],["move","transfer","migrate","relocate","rename","shift","mv","slide"],["save","store","write","persist","commit","stash","record","log"],["sync","synchronize","resync","reconcile","align","pair"],["import","ingest","upload","push","feed"],["export","download","dump","backup","extract"],["connect","link","bind","attach","join","bridge","associate","mount","map"],["disconnect","unlink","unbind","detach","leave","dissociate","unmount","unmap"],["login","log in","sign in","authenticate","auth"],["logout","log out","sign out","disconnect"],["approve","authorize","grant","permit","allow","sanction","whitelist"],["deny","reject","revoke","forbid","block","ban","blacklist"],["encrypt","secure","lock","seal","protect","scramble","hash"],["decrypt","unlock","unseal","reveal","decode"],["deploy","release","ship","publish","roll out","promote","distribute","install"],["debug","troubleshoot","fix","repair","resolve","trace"],["compile","transpile","build","assemble","package","bundle","minify"],["buy","purchase","order","pay","checkout","spend"],["sell","refund","reimburse","charge","invoice","bill"],["subscribe","upgrade","upsell"],["unsubscribe","cancel","downgrade"],["schedule","book","appoint","reserve","plan","calendar"],["reschedule","postpone","delay","defer"],["send","dispatch","deliver","transmit","post","broadcast","notify","alert","email","text","message","chat"],["reply","respond","answer","retort"],["share","forward","retweet","repost"],["like","favorite","star","upvote","heart"],["dislike","downvote"],["follow","watch","track"],["unfollow","ignore","mute"],["user","account","member","profile","identity","customer","principal","admin","operator","client","employee","staff"],["role","group","team","squad","unit","department"],["file","document","attachment","blob","asset","object","resource","content","media"],["image","picture","photo","screenshot"],["video","clip","recording","footage"],["message","notification","alert","event","signal","webhook","ping"],["log","trace","metric","telemetry","audit trail","history"],["settings","config","configuration","preferences","options","params","env","environment","variables"],["permission","privilege","access right","policy","rule","scope"],["organization","company","tenant","workspace","org","project","repo","repository"],["product","item","sku","inventory","stock"],["task","ticket","issue","bug","story","epic","todo","job","workitem"],["id","identifier","key","uuid","guid","token","hash","fingerprint"]];var SynonymExpansionService=class{synonymMap;maxExpansions;constructor(config={}){this.maxExpansions=config.maxExpansionsPerTerm??5;const groups=config.replaceDefaults?config.additionalSynonyms||[]:[...DEFAULT_SYNONYM_GROUPS,...config.additionalSynonyms||[]];this.synonymMap=this.buildSynonymMap(groups)}buildSynonymMap(groups){const map=new Map;for(const group of groups){const normalizedGroup=group.map(term=>term.toLowerCase());for(const term of normalizedGroup){if(!map.has(term)){map.set(term,new Set)}const synonyms=map.get(term);for(const synonym of normalizedGroup){if(synonym!==term){synonyms.add(synonym)}}}}return map}getSynonyms(term){const normalized=term.toLowerCase();const synonyms=this.synonymMap.get(normalized);if(!synonyms){return[]}return Array.from(synonyms).slice(0,this.maxExpansions)}expandQuery(query){const terms=query.toLowerCase().split(/\s+/).filter(term=>term.length>1);const expandedTerms=[];for(const term of terms){expandedTerms.push(term);const synonyms=this.getSynonyms(term);expandedTerms.push(...synonyms)}return expandedTerms.join(" ")}hasExpansions(query){const terms=query.toLowerCase().split(/\s+/);return terms.some(term=>this.synonymMap.has(term))}getStats(){const termCount=this.synonymMap.size;let totalSynonyms=0;for(const synonyms of this.synonymMap.values()){totalSynonyms+=synonyms.size}return{termCount,avgSynonymsPerTerm:termCount>0?totalSynonyms/termCount:0}}};import{defaultTokenizer}from"vectoriadb";function stemTerm(term){if(term.length<=3)return term;if(term.endsWith("ies"))return`${term.slice(0,-3)}y`;if(/(?:x|ch|sh|ss)es$/.test(term))return term.slice(0,-2);if(!term.endsWith("s")||/(?:ss|us|is)$/.test(term))return term;return term.slice(0,-1)}function dotProduct(left,right){let sum=0;for(const[term,weight]of left){sum+=weight*(right.get(term)??0)}return sum}var ToolTfidfIndex=class{constructor(documents=[],stopWords=new Set){this.stopWords=stopWords;const termsOf=documents.map(document=>this.tokenize(document.text));const documentFrequency=new Map;for(const terms of termsOf){for(const term of new Set(terms)){documentFrequency.set(term,(documentFrequency.get(term)??0)+1)}}for(const[term,frequency]of documentFrequency){this.idf.set(term,Math.log((1+documents.length)/(1+frequency))+1)}documents.forEach((document,index)=>{this.vectors.set(document.id,{metadata:document.metadata,vector:this.vectorOf(termsOf[index])})})}stopWords;idf=new Map;vectors=new Map;search(query,{topK,threshold,filter}){const queryVector=this.vectorOf(this.tokenize(query));const results=[];for(const[id,{metadata,vector}]of this.vectors){if(filter&&!filter(metadata))continue;const score=dotProduct(queryVector,vector);if(score>=threshold)results.push({id,metadata,score})}return results.sort((left,right)=>right.score-left.score).slice(0,topK)}getAllDocumentIds(){return[...this.vectors.keys()]}getDocumentCount(){return this.vectors.size}hasDocument(id){return this.vectors.has(id)}tokenize(text){return defaultTokenizer(text).filter(term=>!this.stopWords.has(term)).map(stemTerm)}vectorOf(terms){const vector=new Map;for(const term of terms){const idf=this.idf.get(term);if(idf!==void 0)vector.set(term,(vector.get(term)??0)+idf)}const norm=Math.sqrt([...vector.values()].reduce((sum,weight)=>sum+weight*weight,0));if(norm===0)return vector;for(const[term,weight]of vector){vector.set(term,weight/norm)}return vector}};var STOP_WORDS=new Set(["the","a","an","this","that","these","those","in","on","at","to","for","of","with","by","from","into","over","after","before","between","under","about","against","during","through","and","or","but","nor","so","yet","as","than","if","because","while","when","where","unless","i","me","my","mine","myself","you","your","yours","yourself","he","him","his","himself","she","her","hers","herself","it","its","itself","we","us","our","ours","ourselves","they","them","their","theirs","themselves","who","whom","whose","which","what","is","was","are","were","been","be","being","have","has","had","having","do","does","did","doing","will","would","shall","should","can","could","may","might","must","all","any","both","each","few","more","most","other","some","such","no","nor","not","only","own","same","too","very","just","even","please","pls","plz","thanks","thank","thx","hello","hi","hey","ok","okay","yes","no","actually","basically","literally","maybe","perhaps","now","then","here","there","again","once","back","example","context","optionally","optional","etc","ie","eg"]);var DEFAULT_EMBEDDING_MODEL="Xenova/all-MiniLM-L6-v2";function messageOf(error){return error instanceof Error?error.message:String(error)}var ToolSearchService=class _ToolSearchService{static MAX_SUBSCRIPTION_RETRIES=100;static INITIAL_RETRY_DELAY_MS=10;static MAX_RETRY_DELAY_MS=1e3;vectorDB;strategy;initialized=false;mlInitialized=false;config;scope;unsubscribe;synonymService=null;synonymExpansion;indexing;subscriptionPromise;subscriptionResolved=false;subscriptionResolve=null;subscriptionReject=null;retryTimeoutId=null;disposed=false;availabilityByTool=new Map;constructor(config={},scope){this.scope=scope;const embeddingOptions=config.embeddingOptions||{strategy:"tfidf",modelName:DEFAULT_EMBEDDING_MODEL,cacheDir:"./.cache/transformers",useHNSW:false,synonymExpansion:{enabled:true,replaceDefaults:false,maxExpansionsPerTerm:5}};this.strategy=config.strategy||embeddingOptions.strategy||"tfidf";this.config={strategy:this.strategy,embeddingOptions,defaultTopK:config.defaultTopK??8,defaultSimilarityThreshold:config.defaultSimilarityThreshold??0,mode:config.mode??"codecall_only",includeTools:config.includeTools};const validModes=["codecall_only","codecall_opt_in","metadata_driven"];if(!validModes.includes(this.config.mode)){throw new Error(`Invalid CodeCall mode: ${this.config.mode}. Valid modes: ${validModes.join(", ")}`)}if(this.strategy==="ml"){this.vectorDB=new VectoriaDB({modelName:embeddingOptions.modelName||DEFAULT_EMBEDDING_MODEL,cacheDir:embeddingOptions.cacheDir||"./.cache/transformers",defaultTopK:this.config.defaultTopK,defaultSimilarityThreshold:this.config.defaultSimilarityThreshold,useHNSW:embeddingOptions.useHNSW||false})}else{this.vectorDB=this.createTfidfIndex()}this.synonymExpansion=config.synonymExpansion??embeddingOptions.synonymExpansion;if(this.strategy==="tfidf"){this.synonymService=this.createSynonymService()}this.subscriptionPromise=new Promise((resolve,reject)=>{this.subscriptionResolve=resolve;this.subscriptionReject=reject});this.setupSubscription()}createTfidfIndex(documents=[]){return new ToolTfidfIndex(documents,STOP_WORDS)}createSynonymService(){const synonymExpansion=this.synonymExpansion;if(synonymExpansion===false||synonymExpansion?.enabled===false)return null;return new SynonymExpansionService(synonymExpansion??{})}async ensureSubscribed(){if(this.subscriptionResolved){return}await this.subscriptionPromise}setupSubscription(retryCount=0,delayMs=_ToolSearchService.INITIAL_RETRY_DELAY_MS){if(this.scope.tools){this.subscribeToToolChanges();return}if(retryCount>=_ToolSearchService.MAX_SUBSCRIPTION_RETRIES){this.scope.logger.warn("ToolSearchService: scope.tools not available after max retries. Tool search will return incomplete results until tools are registered.");this.markSubscribed();return}const nextDelay=Math.min(delayMs*2,_ToolSearchService.MAX_RETRY_DELAY_MS);this.retryTimeoutId=setTimeout(()=>{this.retryTimeoutId=null;if(this.disposed){return}this.setupSubscription(retryCount+1,nextDelay)},delayMs)}subscribeToToolChanges(){this.unsubscribe=this.scope.tools.subscribe({immediate:true},event=>{this.queueReindex(event.snapshot)});this.markSubscribed()}queueReindex(tools){const reindex=()=>this.handleToolChange(tools);const run=(this.indexing?this.indexing.then(reindex):reindex()).catch(error=>{this.scope.logger.warn(`CodeCall tool search could not index the tools: ${messageOf(error)}`)});this.indexing=run;void run.then(()=>{if(this.indexing===run)this.indexing=void 0})}markSubscribed(){this.subscriptionResolved=true;if(this.subscriptionResolve){this.subscriptionResolve();this.subscriptionResolve=null}}async handleToolChange(tools){if(tools.length>0&&!this.mlInitialized&&this.strategy==="ml"&&this.vectorDB instanceof VectoriaDB){try{await this.vectorDB.initialize();this.mlInitialized=true}catch(error){this.fallBackToTfidf(error)}}const availabilityByTool=new Map;const documents=tools.flatMap(tool=>this.toDocuments(tool,availabilityByTool));await this.replaceIndex(documents);this.availabilityByTool=availabilityByTool;this.initialized=true}toDocuments(tool,availabilityByTool){try{if(!this.shouldIndexTool(tool))return[];const toolName=tool.name;const document={id:toolName,text:this.extractSearchableText(tool),metadata:{id:toolName,toolName,qualifiedName:tool.fullName||toolName,appId:this.extractAppId(tool),toolInstance:tool}};availabilityByTool.set(toolName,tool.metadata.availableWhen);return[document]}catch(error){this.scope.logger.warn(`CodeCall tool search skipped tool "${tool.name}": ${messageOf(error)}`);return[]}}async replaceIndex(documents){if(this.vectorDB instanceof VectoriaDB){try{this.vectorDB.clear();if(documents.length>0)await this.vectorDB.addMany(documents);return}catch(error){this.fallBackToTfidf(error)}}this.vectorDB=this.createTfidfIndex(documents)}fallBackToTfidf(error){const modelName=this.config.embeddingOptions.modelName||DEFAULT_EMBEDDING_MODEL;this.scope.logger.warn(`CodeCall could not use embedding model "${modelName}" (${messageOf(error)}); tool search uses TF-IDF instead`);this.strategy="tfidf";this.vectorDB=this.createTfidfIndex();this.synonymService=this.createSynonymService()}shouldIndexTool(tool){return checkCodeCallToolPolicy(toCodeCallPolicyTool(tool,void 0,this.scope),this.config).allowed}async initialize(){}dispose(){this.disposed=true;if(this.retryTimeoutId){clearTimeout(this.retryTimeoutId);this.retryTimeoutId=null}if(this.subscriptionReject){this.subscriptionReject(new Error("ToolSearchService disposed before subscription completed"));this.subscriptionReject=null;this.subscriptionResolve=null}if(this.unsubscribe){this.unsubscribe();this.unsubscribe=void 0}}extractSearchableText(tool){const parts=[];if(tool.name){const nameParts=tool.name.split(/[:\-_.]/).filter(Boolean);for(const part of nameParts){parts.push(part,part)}}if(tool.metadata.description){const description=tool.metadata.description;parts.push(description,description,description);const keyTerms=description.toLowerCase().split(/\s+/).filter(word=>word.length>=4&&!this.isStopWord(word));parts.push(...keyTerms)}if(tool.metadata.tags&&tool.metadata.tags.length>0){for(const tag of tool.metadata.tags){parts.push(tag,tag)}}if(tool.rawInputSchema&&typeof tool.rawInputSchema==="object"){const schema=tool.rawInputSchema;if(schema.properties){parts.push(...Object.keys(schema.properties))}}const examples=tool.metadata?.examples;if(examples&&Array.isArray(examples)){for(const ex of examples){if(ex.description){parts.push(ex.description,ex.description)}if(ex.input&&typeof ex.input==="object"){for(const[key,value]of Object.entries(ex.input)){parts.push(key);if(typeof value==="string"){parts.push(value)}}}}}return parts.join(" ")}isStopWord(word){return STOP_WORDS.has(word)}extractAppId(tool){return codeCallAppIdOf(this.scope,tool)}async search(query,options={}){await this.ensureSubscribed();await this.indexing;const{topK=this.config.defaultTopK,appIds,excludeToolNames=[],surface}=options;const minScore=this.config.defaultSimilarityThreshold;const filter=metadata=>{if(excludeToolNames.includes(metadata.toolName)){return false}if(!isOfferedToCaller(metadata.toolInstance.metadata.availableWhen,surface)){return false}if(appIds&&appIds.length>0){if(!metadata.appId||!appIds.includes(metadata.appId)){return false}}return true};const effectiveQuery=this.synonymService?this.synonymService.expandQuery(query):query;const results=await this.vectorDB.search(effectiveQuery,{topK,threshold:minScore,filter});return results.map(result=>({toolName:result.metadata.toolName,appId:result.metadata.appId,description:result.metadata.toolInstance.metadata.description||"",relevanceScore:result.score}))}getAllToolNames(){if(this.vectorDB instanceof VectoriaDB){return this.vectorDB.getAll().map(doc=>doc.id)}else{return this.vectorDB.getAllDocumentIds()}}getTotalCount(surface){if(surface!==void 0){return this.getAllToolNames().filter(toolName=>this.hasTool(toolName,surface)).length}if(this.vectorDB instanceof VectoriaDB){return this.vectorDB.size()}else{return this.vectorDB.getDocumentCount()}}hasTool(toolName,surface){const indexed=this.vectorDB instanceof VectoriaDB?this.vectorDB.has(toolName):this.vectorDB.hasDocument(toolName);return indexed&&isOfferedToCaller(this.availabilityByTool.get(toolName),surface)}clear(){if(this.vectorDB instanceof VectoriaDB){this.vectorDB.clear()}else{this.vectorDB=this.createTfidfIndex()}this.availabilityByTool=new Map;this.initialized=false}getStrategy(){return this.strategy}isInitialized(){return this.initialized}};import{Enclave}from"@enclave-vm/core";import{Provider as Provider3,ProviderScope as ProviderScope3}from"@frontmcp/sdk";import{ForbiddenLoopRule,JSAstValidator,ValidationSeverity}from"@enclave-vm/ast";var AGENTSCRIPT_PARSE_OPTIONS={ecmaVersion:"latest",sourceType:"script",allowReturnOutsideFunction:true,allowAwaitOutsideFunction:true};var PARSE_ATTEMPTS=[{wrap:code=>code,parseOptions:AGENTSCRIPT_PARSE_OPTIONS,lineOffset:0},{wrap:code=>code,parseOptions:{...AGENTSCRIPT_PARSE_OPTIONS,sourceType:"module"},lineOffset:0},{wrap:code=>`async function __temp__() {
2
2
  ${code}
3
3
  }`,parseOptions:AGENTSCRIPT_PARSE_OPTIONS,lineOffset:1}];var NON_REFERENCE_KEYS=new Set(["type","loc","start","end","range","label"]);function isAstNode(value){return typeof value==="object"&&value!==null&&typeof value.type==="string"}function isPropertyName(parent,key){if(!parent||parent["computed"])return false;if(parent.type==="MemberExpression")return key==="property";return key==="key"&&["Property","MethodDefinition","PropertyDefinition"].includes(parent.type)}function visitIdentifierReferences(node,visit,parent,key=""){if(node.type==="Identifier"){if(!isPropertyName(parent,key))visit(node);return}for(const[childKey,child]of Object.entries(node)){if(NON_REFERENCE_KEYS.has(childKey))continue;const children=Array.isArray(child)?child:[child];for(const childNode of children){if(isAstNode(childNode))visitIdentifierReferences(childNode,visit,node,childKey)}}}var DisallowedGlobalsRule=class{constructor(messages){this.messages=messages}messages;name="codecall-disallowed-globals";description="Globals CodeCall scripts may not use";defaultSeverity=ValidationSeverity.ERROR;enabledByDefault=true;validate(context){visitIdentifierReferences(context.ast,identifier=>{const message=identifier.name===void 0?void 0:this.messages.get(identifier.name);if(message===void 0)return;context.report({code:"DISALLOWED_IDENTIFIER",message,location:identifier.loc?{line:identifier.loc.start.line,column:identifier.loc.start.column}:void 0,data:{identifier:identifier.name}})})}};function disallowedGlobalMessages({disabledBuiltins,disabledGlobals,allowConsole}){const messages=new Map([...disabledBuiltins.map(name=>[name,`${name} is disabled by vm.disabledBuiltins`]),...disabledGlobals.map(name=>[name,`${name} is disabled by vm.disabledGlobals`])]);if(!allowConsole){messages.set("console","console is not available in CodeCall scripts unless vm.allowConsole is true; use mcpLog(level, message)")}return messages}function scriptPolicyRules(options){const rules=[new DisallowedGlobalsRule(disallowedGlobalMessages(options))];if(!options.allowLoops){rules.push(new ForbiddenLoopRule({allowFor:false,allowForOf:true,allowWhile:false,allowDoWhile:false,allowForIn:false,message:"Only for-of loops are allowed (vm.allowLoops is false)"}))}return rules}async function findScriptPolicyIssues(code,options){const validator=new JSAstValidator(scriptPolicyRules(options));for(const attempt of PARSE_ATTEMPTS){const result=await validator.validate(attempt.wrap(code),{parseOptions:attempt.parseOptions,preScan:{enabled:false}});if(result.parseError)continue;return result.issues.map(issue=>issue.location&&attempt.lineOffset>0?{...issue,location:{...issue.location,line:issue.location.line-attempt.lineOffset}}:issue)}return[]}var IDENT_RE=/^[A-Za-z_$][A-Za-z0-9_$]*$/;var PROTOTYPE_KEYS=new Set(["__proto__","constructor","prototype"]);var RESERVED_NAMESPACES=new Set(["console","Math","JSON","Object","Array","String","Number","Boolean","Promise","Symbol","Map","Set","WeakMap","WeakSet","Date","Error","RegExp","globalThis","global","window","self","undefined","null","true","false","callTool","getTool","mcpLog","mcpNotify"]);var UNBINDABLE_NAMESPACES=new Set(["break case catch class const continue debugger default delete do else enum export extends finally for","function if import in instanceof new return super switch this throw try typeof var void while with yield","let static implements interface package private protected public await eval arguments NaN Infinity","parallel isNaN isFinite parseInt parseFloat encodeURI encodeURIComponent decodeURI decodeURIComponent","process require module exports Buffer Function AsyncFunction GeneratorFunction Reflect Proxy TypeError","ReferenceError SyntaxError RangeError URIError EvalError AggregateError fetch XMLHttpRequest WebSocket","localStorage sessionStorage indexedDB crypto performance structuredClone AbortController AbortSignal","MessageChannel MessagePort BroadcastChannel TextEncoder TextDecoder Intl setTimeout setInterval","setImmediate clearTimeout clearInterval clearImmediate queueMicrotask WebAssembly Worker SharedWorker","ServiceWorker WeakRef FinalizationRegistry BigInt Atomics SharedArrayBuffer ArrayBuffer DataView","importScripts ShadowRealm Iterator AsyncIterator"].join(" ").split(" "));var UNCALLABLE_METHODS=new Set(["process require module exports Buffer eval Function AsyncFunction GeneratorFunction arguments RegExp","Promise Symbol Proxy Reflect Error TypeError ReferenceError SyntaxError RangeError URIError EvalError","AggregateError fetch XMLHttpRequest WebSocket localStorage sessionStorage indexedDB crypto performance","structuredClone AbortController AbortSignal MessageChannel MessagePort BroadcastChannel TextEncoder","TextDecoder Intl setTimeout setInterval setImmediate clearTimeout clearInterval clearImmediate","queueMicrotask WebAssembly Worker SharedWorker ServiceWorker WeakMap WeakSet WeakRef FinalizationRegistry","Map Set Atomics SharedArrayBuffer importScripts ShadowRealm Iterator AsyncIterator"].join(" ").split(" "));var SANDBOX_TOOL_NAME_RE=/^[a-zA-Z][a-zA-Z0-9:._-]*$/;var MAX_SANDBOX_TOOL_NAME_LENGTH=256;function isBindableNamespace(ns,reservedGlobals){return IDENT_RE.test(ns)&&!PROTOTYPE_KEYS.has(ns)&&!ns.startsWith("__")&&!RESERVED_NAMESPACES.has(ns)&&!UNBINDABLE_NAMESPACES.has(ns)&&!reservedGlobals.has(ns)}function isBindableMethod(ns,method,toolName){return IDENT_RE.test(method)&&!PROTOTYPE_KEYS.has(method)&&!method.startsWith("__")&&!UNCALLABLE_METHODS.has(method)&&toolName===`${ns}.${method}`&&toolName.length<=MAX_SANDBOX_TOOL_NAME_LENGTH&&SANDBOX_TOOL_NAME_RE.test(toolName)}function buildToolNamespaces(tools){const namespaces=Object.create(null);const skipped=[];for(const tool of tools){const name=tool?.name;if(typeof name!=="string"||name.length===0)continue;const dot=name.indexOf(".");if(dot<=0||dot===name.length-1){skipped.push({name,reason:"no-namespace-prefix"});continue}const ns=name.slice(0,dot);const method=name.slice(dot+1);if(!IDENT_RE.test(ns)||!IDENT_RE.test(method)){skipped.push({name,reason:"invalid-identifier"});continue}if(PROTOTYPE_KEYS.has(ns)||PROTOTYPE_KEYS.has(method)){skipped.push({name,reason:"prototype-key"});continue}if(RESERVED_NAMESPACES.has(ns)||UNBINDABLE_NAMESPACES.has(ns)||ns.startsWith("__")){skipped.push({name,reason:"reserved-namespace"});continue}if(!isBindableMethod(ns,method,name)){skipped.push({name,reason:"unsupported-name"});continue}const bucket=namespaces[ns]??(namespaces[ns]=Object.create(null));if(Object.prototype.hasOwnProperty.call(bucket,method)){skipped.push({name,reason:"duplicate-method"});continue}bucket[method]=name}return{namespaces,skipped}}function toSandboxToolNamespaces(namespaces,reservedGlobals=[]){if(!namespaces)return void 0;const reserved=new Set(reservedGlobals);const bindable=Object.create(null);let count=0;for(const ns of Object.keys(namespaces)){if(!isBindableNamespace(ns,reserved))continue;const methods=namespaces[ns];const bucket=Object.create(null);let methodCount=0;for(const method of Object.keys(methods)){const toolName=methods[method];if(typeof toolName!=="string"||!isBindableMethod(ns,method,toolName))continue;bucket[method]=toolName;methodCount+=1}if(methodCount>0){bindable[ns]=bucket;count+=1}}return count>0?bindable:void 0}import{isWrappedInMain,transformAgentScript}from"@enclave-vm/ast";import*as acorn from"acorn";var PARSE_OPTIONS={ecmaVersion:"latest",locations:true};var NON_CHILD_KEYS=new Set(["type","loc","start","end","range"]);function isNode(value){return typeof value==="object"&&value!==null&&typeof value.type==="string"}function isAddedByTransform(node){if(node.type==="VariableDeclaration"){const[declaration]=node["declarations"]??[];const id=declaration?.["id"];return typeof id?.["name"]==="string"&&id["name"].startsWith("__iter_")}if(node.type==="IfStatement"){const right=node["test"]?.["right"];return right?.type==="Identifier"&&right["name"]==="__maxIterations"}return false}function parseScript(script){try{return{body:parseBody(script,"script"),offset:0}}catch{try{return{body:parseBody(script,"module"),offset:0}}catch{const wrapped=parseBody(`async function __temp__() {
4
4
  ${script}
5
5
  }`,"script");const fn=wrapped[0];const block=fn?.["body"];return{body:block?.["body"]??[],offset:1}}}}function parseBody(code,sourceType){const program=acorn.parse(code,{...PARSE_OPTIONS,sourceType});return program["body"]??[]}function treesOf(script){try{const wrap=!isWrappedInMain(script);const printed=parseBody(transformAgentScript(script,{wrapInMain:wrap}),"script");const{body,offset}=parseScript(script);if(!wrap)return{printed,script:body,offset};const main=printed[0]?.["body"];return{printed:main?.["body"]??[],script:body,offset}}catch{return void 0}}function pairLists(printed,script,depth,out,offset){const kept=printed.filter(node=>!(isNode(node)&&isAddedByTransform(node)));if(kept.length!==script.length)return;kept.forEach((node,index)=>{const own=script[index];if(isNode(node)&&isNode(own))pairNodes(node,own,depth,out,offset)})}function pairNodes(printed,script,depth,out,offset){if(printed.type==="ReturnStatement"&&script.type==="ExpressionStatement"){record(printed,script,depth,out,offset);const argument=printed["argument"];const expression=script["expression"];if(isNode(argument)&&isNode(expression))pairNodes(argument,expression,depth+1,out,offset);return}if(printed.type!==script.type)return;record(printed,script,depth,out,offset);for(const key of Object.keys(printed)){if(NON_CHILD_KEYS.has(key))continue;const printedChild=printed[key];const scriptChild=script[key];if(Array.isArray(printedChild)&&Array.isArray(scriptChild)){pairLists(printedChild,scriptChild,depth+1,out,offset)}else if(isNode(printedChild)&&isNode(scriptChild)){pairNodes(printedChild,scriptChild,depth+1,out,offset)}}}function record(printed,script,depth,out,offset){if(!printed.loc||!script.loc)return;out.push({printedStart:printed.loc.start.line,printedEnd:printed.loc.end.line,scriptLine:script.loc.start.line-offset,depth})}function validatedLineMapper(script){const trees=treesOf(script);if(!trees)return()=>void 0;const pairs=[];pairLists(trees.printed,trees.script,0,pairs,trees.offset);return printedLine=>{const starting=pairs.filter(pair=>pair.printedStart===printedLine);const candidates=starting.length>0?starting:pairs.filter(pair=>pair.printedStart<=printedLine&&printedLine<=pair.printedEnd);const best=candidates.reduce((deepest,pair)=>!deepest||pair.depth>deepest.depth?pair:deepest,void 0);return best&&best.scriptLine>=1?best.scriptLine:void 0}}var ISSUE_LINE_RE=/ \(line (\d+)\)/g;function withScriptLines(message,script){if(!message.includes("(line "))return message;const lineOf=validatedLineMapper(script);return message.replace(ISSUE_LINE_RE,(_match,printed)=>{const line=lineOf(Number(printed));return line===void 0?"":` (line ${line})`})}var SCRIPT_CONSOLE_LINES_PER_SECOND=50;var WINDOW_MS=1e3;var LOGGER_LEVEL={log:"info",info:"info",warn:"warn",error:"error",debug:"debug"};var ScriptConsoleLog=class{constructor(logger,linesPerSecond=SCRIPT_CONSOLE_LINES_PER_SECOND,now=Date.now){this.logger=logger;this.linesPerSecond=linesPerSecond;this.now=now}logger;linesPerSecond;now;windowStart=Number.NEGATIVE_INFINITY;written=0;dropped=0;write=(level,message)=>{const now=this.now();if(now-this.windowStart>=WINDOW_MS){this.windowStart=now;this.written=0;this.dropped=0}if(this.written>=this.linesPerSecond){this.dropped++;if(this.dropped===1){this.logger.warn(`Dropping script console output: more than ${this.linesPerSecond} lines a second`)}return}this.written++;this.logger[LOGGER_LEVEL[level]](message)}};function toolFailureMessage(error,toolName){if(typeof error==="string"&&error)return error;const message=error?.message;return typeof message==="string"&&message?message:`Tool call failed: ${toolName}`}function toolFailureName(error){const name=error&&typeof error==="object"?error.name:void 0;return typeof name==="string"&&name?name.slice(0,128):"ToolError"}var ITERATION_LIMIT_PREFIX="Maximum iteration limit exceeded";var ITERATION_LIMIT_ERROR={name:"Error",message:`${ITERATION_LIMIT_PREFIX} (${MAX_ITERATIONS_PER_LOOP}). This limit prevents infinite loops.`};var PARSE_FAILURE_PREFIX="Failed to parse AgentScript code: ";var PARSE_POSITION_RE=/\((\d+):(\d+)\)$/;function parseFailureOf(message){const match=PARSE_POSITION_RE.exec(message);const line=match?Number(match[1])-1:0;if(!match||line<1)return{message};const column=Number(match[2]);return{message:`${message.slice(0,match.index)}(${line}:${column})`,location:{line,column}}}var ScriptTooLargeError=class extends Error{code="SCRIPT_TOO_LARGE";scriptLength;maxLength;constructor(scriptLength,maxLength){super(`Script length (${scriptLength} characters) exceeds maximum allowed length (${maxLength} characters). Enable sidecar to handle large data, or reduce script size.`);this.name="ScriptTooLargeError";this.scriptLength=scriptLength;this.maxLength=maxLength}};var EnclaveService=class{vmOptions;sidecarOptions;consoleHandler;constructor(config,scriptLogger){const all=config.getAll();this.vmOptions=all.resolvedVm;this.sidecarOptions=all.sidecar;if(this.vmOptions.allowConsole&&scriptLogger){this.consoleHandler=new ScriptConsoleLog(scriptLogger).write}}async execute(code,environment){const logs=[];if(!this.sidecarOptions.enabled&&this.sidecarOptions.maxScriptLengthWhenDisabled!==null){const maxLength=this.sidecarOptions.maxScriptLengthWhenDisabled;if(code.length>maxLength){throw new ScriptTooLargeError(code.length,maxLength)}}const policyIssues=await findScriptPolicyIssues(code,{...this.vmOptions,allowConsole:this.consoleHandler!==void 0});if(policyIssues.length>0){return{success:false,error:{message:`AgentScript validation failed:
6
- ${policyIssues.map(issue=>`${issue.code}${issue.location?` (line ${issue.location.line})`:""}: ${issue.message}`).join("\n")}`,name:"ValidationError",code:"VALIDATION_ERROR",blockedPatterns:[...new Set(policyIssues.map(issue=>issue.code))]},logs,timedOut:false,stats:{duration:0,toolCallCount:0,iterationCount:0}}}const toolFailures=[];const toolHandler=async(toolName,args)=>{try{return await environment.callTool(toolName,args)}catch(error){const code2=error?.code;toolFailures.push({toolName,name:toolFailureName(error),message:toolFailureMessage(error,toolName),...typeof code2==="string"?{code:code2}:{}});throw error}};const sidecar=this.sidecarOptions.enabled?{enabled:true,maxTotalSize:this.sidecarOptions.maxTotalSize,maxReferenceSize:this.sidecarOptions.maxReferenceSize,extractionThreshold:this.sidecarOptions.extractionThreshold,maxResolvedSize:this.sidecarOptions.maxResolvedSize,allowComposites:this.sidecarOptions.allowComposites}:void 0;const{mcpLog,mcpNotify}=environment;const globals={getTool:environment.getTool,...mcpLog?{mcpLog:(level,message,metadata)=>{mcpLog(level,message,metadata);logs.push(`[mcp:${level}] ${message}`)}}:{},...mcpNotify?{mcpNotify:(event,payload)=>{mcpNotify(event,payload);logs.push(`[notify] ${event}`)}}:{}};const{rapidEnumerationThreshold,rapidEnumerationOverrides}=this.vmOptions;const options={timeout:this.vmOptions.timeoutMs,maxToolCalls:maxToolCallsOf(this.vmOptions),maxIterations:MAX_ITERATIONS_PER_LOOP,maxSanitizeDepth:this.vmOptions.maxSanitizeDepth,maxSanitizeProperties:this.vmOptions.maxSanitizeProperties,toolHandler,validate:true,transform:true,sidecar,sanitizeStackTraces:true,allowFunctionsInGlobals:true,consoleHandler:this.consoleHandler,globals,toolNamespaces:toSandboxToolNamespaces(environment.toolNamespaces,Object.keys(globals)),doubleVm:{parentValidation:{...rapidEnumerationThreshold!==void 0&&{rapidEnumerationThreshold},...rapidEnumerationOverrides!==void 0&&{rapidEnumerationOverrides}}}};const enclave=createEnclave(options);try{const result=await enclave.run(code);return this.mapEnclaveResult(result,logs,toolFailures,code)}finally{enclave.dispose()}}mapEnclaveResult(result,logs,toolFailures=[],script=""){const stats={duration:result.stats.duration,toolCallCount:result.stats.toolCallCount,iterationCount:result.stats.iterationCount};if(result.success){return{success:true,result:result.value,logs,timedOut:false,stats}}const reportedError=result.error??{name:"Error",message:"Script execution failed"};const toolFailure=[...toolFailures].reverse().find(failure=>failure.message===reportedError.message&&failure.name===reportedError.name);const error=!toolFailure&&reportedError.message?.startsWith(ITERATION_LIMIT_PREFIX)?{...reportedError,...ITERATION_LIMIT_ERROR}:reportedError;if(error.code==="ENCLAVE_ERROR"&&error.message?.startsWith(PARSE_FAILURE_PREFIX)){const{message,location}=parseFailureOf(error.message);return{success:false,error:{message,name:"SyntaxError",code:"SYNTAX_ERROR",...location?{location}:{}},logs,timedOut:false,stats}}if(toolFailure){return{success:false,error:{message:error.message,name:error.name,...toolFailure.code?{code:toolFailure.code}:{},toolName:toolFailure.toolName},logs,timedOut:false,stats}}const timedOut=error.message?.includes("timed out")||error.code==="TIMEOUT";if(error.code==="VALIDATION_ERROR"){const issues=error.data?.issues??[];const blockedPatterns=[...new Set(issues.map(issue=>issue.code).filter(code=>!!code))];return{success:false,error:{message:withScriptLines(error.message,script),name:"ValidationError",code:error.code,...blockedPatterns.length>0?{blockedPatterns}:{}},logs,timedOut:false,stats}}return{success:false,error:{message:error.message,name:error.name,stack:error.stack,code:error.code},logs,timedOut,stats}}};EnclaveService=__decorateClass([Provider3({name:"codecall:enclave",description:"Executes AgentScript code in a secure enclave",scope:ProviderScope3.GLOBAL})],EnclaveService);function createEnclave(options){try{return new Enclave(options)}catch(error){if(!options.toolNamespaces||!(error instanceof TypeError)||!error.message.startsWith("Invalid toolNamespaces")){throw error}return new Enclave({...options,toolNamespaces:void 0})}}import{getCallSurface,Tool,ToolContext}from"@frontmcp/sdk";import{z as z2}from"@frontmcp/lazy-zod";var DEFAULT_MIN_RELEVANCE_SCORE=.1;function buildSearchToolDescription(topK){return`Find tools by splitting user request into atomic actions.
6
+ ${policyIssues.map(issue=>`${issue.code}${issue.location?` (line ${issue.location.line})`:""}: ${issue.message}`).join("\n")}`,name:"ValidationError",code:"VALIDATION_ERROR",blockedPatterns:[...new Set(policyIssues.map(issue=>issue.code))]},logs,timedOut:false,stats:{duration:0,toolCallCount:0,iterationCount:0}}}const toolFailures=[];const toolHandler=async(toolName,args)=>{try{return await environment.callTool(toolName,args)}catch(error){const code2=error?.code;toolFailures.push({toolName,name:toolFailureName(error),message:toolFailureMessage(error,toolName),...typeof code2==="string"?{code:code2}:{}});throw error}};const sidecar=this.sidecarOptions.enabled?{enabled:true,maxTotalSize:this.sidecarOptions.maxTotalSize,maxReferenceSize:this.sidecarOptions.maxReferenceSize,extractionThreshold:this.sidecarOptions.extractionThreshold,maxResolvedSize:this.sidecarOptions.maxResolvedSize,allowComposites:this.sidecarOptions.allowComposites}:void 0;const{mcpLog,mcpNotify}=environment;const globals={getTool:environment.getTool,...mcpLog?{mcpLog:(level,message,metadata)=>{mcpLog(level,message,metadata);logs.push(`[mcp:${level}] ${message}`)}}:{},...mcpNotify?{mcpNotify:(event,payload)=>{mcpNotify(event,payload);logs.push(`[notify] ${event}`)}}:{}};const{rapidEnumerationThreshold,rapidEnumerationOverrides}=this.vmOptions;const options={timeout:this.vmOptions.timeoutMs,maxToolCalls:maxToolCallsOf(this.vmOptions),maxIterations:MAX_ITERATIONS_PER_LOOP,maxSanitizeDepth:this.vmOptions.maxSanitizeDepth,maxSanitizeProperties:this.vmOptions.maxSanitizeProperties,toolHandler,validate:true,transform:true,sidecar,sanitizeStackTraces:true,allowFunctionsInGlobals:true,consoleHandler:this.consoleHandler,globals,toolNamespaces:toSandboxToolNamespaces(environment.toolNamespaces,Object.keys(globals)),doubleVm:{parentValidation:{...rapidEnumerationThreshold!==void 0&&{rapidEnumerationThreshold},...rapidEnumerationOverrides!==void 0&&{rapidEnumerationOverrides}}}};const enclave=createEnclave(options);try{const result=await enclave.run(code);return this.mapEnclaveResult(result,logs,toolFailures,code)}finally{enclave.dispose()}}mapEnclaveResult(result,logs,toolFailures=[],script=""){const stats={duration:result.stats.duration,toolCallCount:result.stats.toolCallCount,iterationCount:result.stats.iterationCount};if(result.success){return{success:true,result:result.value,logs,timedOut:false,stats}}const reportedError=result.error??{name:"Error",message:"Script execution failed"};const toolFailure=[...toolFailures].reverse().find(failure=>failure.message===reportedError.message&&failure.name===reportedError.name);const error=!toolFailure&&reportedError.message?.startsWith(ITERATION_LIMIT_PREFIX)?{...reportedError,...ITERATION_LIMIT_ERROR}:reportedError;if(error.code==="ENCLAVE_ERROR"&&error.message?.startsWith(PARSE_FAILURE_PREFIX)){const{message,location}=parseFailureOf(error.message);return{success:false,error:{message,name:"SyntaxError",code:"SYNTAX_ERROR",...location?{location}:{}},logs,timedOut:false,stats}}if(toolFailure){return{success:false,error:{message:error.message,name:error.name,...toolFailure.code?{code:toolFailure.code}:{},toolName:toolFailure.toolName},logs,timedOut:false,stats}}const timedOut=error.message?.includes("timed out")||error.code==="TIMEOUT";if(error.code==="VALIDATION_ERROR"){const issues=error.data?.issues??[];const blockedPatterns=[...new Set(issues.map(issue=>issue.code).filter(code=>!!code))];return{success:false,error:{message:withScriptLines(error.message,script),name:"ValidationError",code:error.code,...blockedPatterns.length>0?{blockedPatterns}:{}},logs,timedOut:false,stats}}return{success:false,error:{message:error.message,name:error.name,stack:error.stack,code:error.code},logs,timedOut,stats}}};EnclaveService=__decorateClass([Provider3({name:"codecall:enclave",description:"Executes AgentScript code in a secure enclave",scope:ProviderScope3.GLOBAL})],EnclaveService);function createEnclave(options){try{return new Enclave(options)}catch(error){if(!options.toolNamespaces||!(error instanceof TypeError)||!error.message.startsWith("Invalid toolNamespaces")){throw error}return new Enclave({...options,toolNamespaces:void 0})}}import{getCallSurface,Tool,ToolContext}from"@frontmcp/sdk";async function isDiscoverable(scope,metadata,authInfo){const authorities=metadata?.authorities;const engine=scope.authoritiesEngine;const contextBuilder=scope.authoritiesContextBuilder;if(!authorities||!engine||!contextBuilder)return true;try{return(await engine.evaluate(authorities,contextBuilder.build(authInfo))).granted}catch{return false}}async function toolsWithheldByAuthorities(scope,authInfo){const authoritiesScope=scope??{};const withheld=new Set;if(!authoritiesScope.authoritiesEngine||!authoritiesScope.authoritiesContextBuilder)return withheld;const callerAuthInfo=authInfo??{};for(const tool of authoritiesScope.tools?.getTools?.(true)??[]){if(await isDiscoverable(authoritiesScope,tool.metadata,callerAuthInfo))continue;withheld.add(tool.name);withheld.add(tool.fullName)}return withheld}async function skillsDiscoverableByAuthorities(scope,skills,authInfo){const callerAuthInfo=authInfo??{};const extraUser=callerAuthInfo["extra"]?.["user"];const normalized=callerAuthInfo["user"]||!extraUser?callerAuthInfo:{...callerAuthInfo,user:extraUser};const grants=await Promise.all(skills.map(skill=>isDiscoverable(scope??{},skill.metadata,normalized)));return skills.filter((_skill,index)=>grants[index])}import{z as z2}from"@frontmcp/lazy-zod";var DEFAULT_MIN_RELEVANCE_SCORE=.1;function buildSearchToolDescription(topK){return`Find tools by splitting user request into atomic actions.
7
7
 
8
8
  DECOMPOSE: "delete users and send email" \u2192 queries: ["delete user", "send email"]
9
9
  DECOMPOSE: "get order and refund" \u2192 queries: ["get order", "calculate refund"]
@@ -20,7 +20,7 @@ INPUT:
20
20
 
21
21
  OUTPUT: Flat deduplicated tool list. relevanceScore: 0.5+=good, 0.7+=strong match.
22
22
 
23
- FLOW: search \u2192 describe \u2192 execute/invoke`}var searchToolDescription=buildSearchToolDescription(codeCallPluginOptionsSchema.parse({}).topK);var searchToolInputSchema={queries:z2.array(z2.string().min(2).max(256)).min(1).max(10).describe("Atomic action queries. Split complex requests into simple actions."),appIds:z2.array(z2.string()).max(10).optional().describe("Filter by app IDs"),excludeToolNames:z2.array(z2.string()).max(50).optional().describe("Skip already-known tool names"),topK:z2.number().int().positive().max(50).optional().describe("Results per query (defaults to the server's CodeCall topK, 8 unless configured)"),minRelevanceScore:z2.number().min(0).max(1).optional().default(DEFAULT_MIN_RELEVANCE_SCORE).describe(`Minimum relevance threshold (default ${DEFAULT_MIN_RELEVANCE_SCORE})`)};var searchToolOutputSchema=z2.object({tools:z2.array(z2.object({name:z2.string().describe('Tool name (e.g., "users:list")'),appId:z2.string().optional().describe("App ID"),description:z2.string().describe("What this tool does"),relevanceScore:z2.number().min(0).max(1).describe("Match score (0-1)"),matchedQueries:z2.array(z2.string()).describe("Which queries matched this tool")})).describe("Deduplicated tools sorted by relevance"),warnings:z2.array(z2.object({type:z2.enum(["excluded_tool_not_found","no_results","low_relevance"]).describe("Warning type"),message:z2.string().describe("Warning message"),affectedTools:z2.array(z2.string()).optional().describe("Affected tool names")})).describe("Search warnings"),totalAvailableTools:z2.number().int().nonnegative().describe("Total tools in index")});var SearchTool=class extends ToolContext{async execute(input){const{queries,appIds,excludeToolNames=[],topK,minRelevanceScore=DEFAULT_MIN_RELEVANCE_SCORE}=input;const searchService=this.get(ToolSearchService);const warnings=[];const audit=this.tryGet(AuditLoggerService);const executionId=audit?audit.generateExecutionId():"";const startedAt=Date.now();const surface=getCallSurface();const nonExistentExcludedTools=excludeToolNames.filter(toolName=>!searchService.hasTool(toolName,surface));if(nonExistentExcludedTools.length>0){warnings.push({type:"excluded_tool_not_found",message:`Excluded tools not found: ${nonExistentExcludedTools.join(", ")}`,affectedTools:nonExistentExcludedTools})}const toolMap=new Map;let lowRelevanceCount=0;for(const query of queries){const searchResults=await searchService.search(query,{topK,appIds,excludeToolNames,surface});for(const result of searchResults){if(result.relevanceScore<minRelevanceScore){lowRelevanceCount++;continue}const existing=toolMap.get(result.toolName);if(existing){existing.matchedQueries.push(query);existing.relevanceScore=Math.max(existing.relevanceScore,result.relevanceScore)}else{toolMap.set(result.toolName,{name:result.toolName,appId:result.appId,description:result.description,relevanceScore:result.relevanceScore,matchedQueries:[query]})}}}const tools=Array.from(toolMap.values()).sort((a,b)=>b.relevanceScore-a.relevanceScore).map(tool=>({name:tool.name,appId:tool.appId,description:tool.description,relevanceScore:tool.relevanceScore,matchedQueries:tool.matchedQueries}));if(tools.length===0){warnings.push({type:"no_results",message:`No tools found for queries: ${queries.join(", ")}${appIds?.length?` in apps: ${appIds.join(", ")}`:""}`})}if(lowRelevanceCount>0&&tools.length>0){warnings.push({type:"low_relevance",message:`${lowRelevanceCount} result(s) filtered due to relevance below ${minRelevanceScore}`})}audit?.logSearch(executionId,queries.join(" "),tools.length,Date.now()-startedAt);return{tools,warnings,totalAvailableTools:searchService.getTotalCount(surface)}}};SearchTool=__decorateClass([Tool({name:"codecall:search",cache:{ttl:60,slideWindow:false},codecall:{enabledInCodeCall:false,visibleInListTools:true},description:searchToolDescription,inputSchema:searchToolInputSchema,outputSchema:searchToolOutputSchema,annotations:{readOnlyHint:true,openWorldHint:true}})],SearchTool);import{filterServableSkills,Tool as Tool2,ToolContext as ToolContext2}from"@frontmcp/sdk";import{z as z3}from"@frontmcp/lazy-zod";var searchSkillsToolDescription=`Search for EXECUTABLE skills. Each result returns the skill's description, tags, and the openapi operation IDs it can call from within AgentScript.
23
+ FLOW: search \u2192 describe \u2192 execute/invoke`}var searchToolDescription=buildSearchToolDescription(codeCallPluginOptionsSchema.parse({}).topK);var searchToolInputSchema={queries:z2.array(z2.string().min(2).max(256)).min(1).max(10).describe("Atomic action queries. Split complex requests into simple actions."),appIds:z2.array(z2.string()).max(10).optional().describe("Filter by app IDs"),excludeToolNames:z2.array(z2.string()).max(50).optional().describe("Skip already-known tool names"),topK:z2.number().int().positive().max(50).optional().describe("Results per query (defaults to the server's CodeCall topK, 8 unless configured)"),minRelevanceScore:z2.number().min(0).max(1).optional().default(DEFAULT_MIN_RELEVANCE_SCORE).describe(`Minimum relevance threshold (default ${DEFAULT_MIN_RELEVANCE_SCORE})`)};var searchToolOutputSchema=z2.object({tools:z2.array(z2.object({name:z2.string().describe('Tool name (e.g., "users:list")'),appId:z2.string().optional().describe("App ID"),description:z2.string().describe("What this tool does"),relevanceScore:z2.number().min(0).max(1).describe("Match score (0-1)"),matchedQueries:z2.array(z2.string()).describe("Which queries matched this tool")})).describe("Deduplicated tools sorted by relevance"),warnings:z2.array(z2.object({type:z2.enum(["excluded_tool_not_found","no_results","low_relevance"]).describe("Warning type"),message:z2.string().describe("Warning message"),affectedTools:z2.array(z2.string()).optional().describe("Affected tool names")})).describe("Search warnings"),totalAvailableTools:z2.number().int().nonnegative().describe("Total tools in index")});var SearchTool=class extends ToolContext{async execute(input){const{queries,appIds,excludeToolNames=[],topK,minRelevanceScore=DEFAULT_MIN_RELEVANCE_SCORE}=input;const searchService=this.get(ToolSearchService);const warnings=[];const audit=this.tryGet(AuditLoggerService);const executionId=audit?audit.generateExecutionId():"";const startedAt=Date.now();const surface=getCallSurface();const withheld=await toolsWithheldByAuthorities(this.scope,this.authInfo);const isReachable=toolName=>searchService.hasTool(toolName,surface)&&!withheld.has(toolName);const nonExistentExcludedTools=excludeToolNames.filter(toolName=>!isReachable(toolName));if(nonExistentExcludedTools.length>0){warnings.push({type:"excluded_tool_not_found",message:`Excluded tools not found: ${nonExistentExcludedTools.join(", ")}`,affectedTools:nonExistentExcludedTools})}const toolMap=new Map;let lowRelevanceCount=0;for(const query of queries){const searchResults=await searchService.search(query,{topK,appIds,excludeToolNames:[...excludeToolNames,...withheld],surface});for(const result of searchResults){if(result.relevanceScore<minRelevanceScore){lowRelevanceCount++;continue}const existing=toolMap.get(result.toolName);if(existing){existing.matchedQueries.push(query);existing.relevanceScore=Math.max(existing.relevanceScore,result.relevanceScore)}else{toolMap.set(result.toolName,{name:result.toolName,appId:result.appId,description:result.description,relevanceScore:result.relevanceScore,matchedQueries:[query]})}}}const tools=Array.from(toolMap.values()).sort((a,b)=>b.relevanceScore-a.relevanceScore).map(tool=>({name:tool.name,appId:tool.appId,description:tool.description,relevanceScore:tool.relevanceScore,matchedQueries:tool.matchedQueries}));if(tools.length===0){warnings.push({type:"no_results",message:`No tools found for queries: ${queries.join(", ")}${appIds?.length?` in apps: ${appIds.join(", ")}`:""}`})}if(lowRelevanceCount>0&&tools.length>0){warnings.push({type:"low_relevance",message:`${lowRelevanceCount} result(s) filtered due to relevance below ${minRelevanceScore}`})}audit?.logSearch(executionId,queries.join(" "),tools.length,Date.now()-startedAt);return{tools,warnings,totalAvailableTools:withheld.size===0?searchService.getTotalCount(surface):searchService.getAllToolNames().filter(isReachable).length}}};SearchTool=__decorateClass([Tool({name:"codecall:search",cache:{ttl:60,slideWindow:false},codecall:{enabledInCodeCall:false,visibleInListTools:true},description:searchToolDescription,inputSchema:searchToolInputSchema,outputSchema:searchToolOutputSchema,annotations:{readOnlyHint:true,openWorldHint:true}})],SearchTool);import{filterServableSkills,Tool as Tool2,ToolContext as ToolContext2}from"@frontmcp/sdk";import{z as z3}from"@frontmcp/lazy-zod";var searchSkillsToolDescription=`Search for EXECUTABLE skills. Each result returns the skill's description, tags, and the openapi operation IDs it can call from within AgentScript.
24
24
 
25
25
  DECOMPOSE complex requests into atomic queries. AVOID re-searching: use excludeSkillNames.
26
26
 
@@ -33,7 +33,7 @@ INPUT:
33
33
 
34
34
  OUTPUT: Flat deduplicated executable skill list. Each entry includes the operationIds the skill is allowed to call (via the markdown harvester). The agent can use those operationIds directly in execute() AgentScript via the generated namespaces (e.g. acme.getOrder({...})).
35
35
 
36
- FLOW: searchSkills \u2192 describe \u2192 execute`;var searchSkillsToolInputSchema={queries:z3.array(z3.string().min(2).max(256)).min(1).max(10).describe("Atomic skill queries. Split complex requests into simple actions."),tags:z3.array(z3.string().min(1).max(64)).max(16).optional().describe("Filter to skills with any of these tags"),excludeSkillNames:z3.array(z3.string()).max(50).optional().describe("Skip already-known skill names"),topK:z3.number().int().positive().max(50).optional().default(5).describe("Results per query (default 5)"),minRelevanceScore:z3.number().min(0).max(1).optional().default(.1).describe("Minimum relevance threshold (default 0.1)")};var referencedOperationSchema=z3.object({spec:z3.string().describe('OpenAPI spec id (e.g. "acme")'),operationId:z3.string().describe('OpenAPI operation id (e.g. "getOrder")')});var skillSearchHitSchema=z3.object({name:z3.string().describe("Skill name"),description:z3.string().describe("Short description of what the skill does"),tags:z3.array(z3.string()).describe("Tags carried by the skill"),operations:z3.array(referencedOperationSchema).describe("OpenAPI operations the skill can call"),tools:z3.array(z3.string()).describe("Tool names the skill declares (if any)"),relevanceScore:z3.number().min(0).max(1).describe("Match score (0-1)"),matchedQueries:z3.array(z3.string()).describe("Which queries matched this skill"),source:z3.enum(["local","external"]).describe("Where the skill was loaded from")});var searchSkillsToolOutputSchema=z3.object({skills:z3.array(skillSearchHitSchema).describe("Deduplicated executable skills, sorted by relevance"),warnings:z3.array(z3.object({type:z3.enum(["no_results","low_relevance","excluded_skill_not_found"]).describe("Warning type"),message:z3.string().describe("Warning message"),affectedSkills:z3.array(z3.string()).optional().describe("Affected skill names")})).describe("Search warnings"),totalExecutableSkills:z3.number().int().nonnegative().describe("Total executable skills available")});var SearchSkillsTool=class extends ToolContext2{async execute(input){const{queries,tags,excludeSkillNames=[],topK=5,minRelevanceScore=.1}=input;const skillRegistry=this.scope.skills;const executableSkills=await filterServableSkills(this.scope,skillRegistry.getExecutableSkills());const executableSet=new Set(executableSkills.map(s=>s.name));const totalExecutableSkills=executableSkills.length;const warnings=[];const nonExistentExcluded=excludeSkillNames.filter(n=>!executableSet.has(n));if(nonExistentExcluded.length>0){warnings.push({type:"excluded_skill_not_found",message:`Excluded skills not found: ${nonExistentExcluded.join(", ")}`,affectedSkills:nonExistentExcluded})}const matches=new Map;let lowRelevanceCount=0;const excludedSet=new Set(excludeSkillNames);const perQueryResults=await Promise.all(queries.map(query=>skillRegistry.search(query,{topK,tags,minScore:minRelevanceScore}).then(results=>({query,results}))));for(const{query,results}of perQueryResults){for(const result of results){const name=result.metadata.name;if(!executableSet.has(name))continue;if(excludedSet.has(name))continue;if(result.score<minRelevanceScore){lowRelevanceCount++;continue}const existing=matches.get(name);if(existing){existing.matchedQueries.push(query);existing.relevanceScore=Math.max(existing.relevanceScore,result.score)}else{const ops=result.metadata.referencedOperations??[];const toolNames=(result.metadata.tools??[]).map(t=>{if(typeof t==="string")return t;if(typeof t==="object"&&t!==null&&"name"in t)return t.name;return null}).filter(n=>typeof n==="string");matches.set(name,{name,description:result.metadata.description,tags:result.metadata.tags??[],operations:ops.map(op=>({spec:op.spec,operationId:op.operationId})),tools:toolNames,relevanceScore:result.score,matchedQueries:[query],source:result.source})}}}const skills=Array.from(matches.values()).sort((a,b)=>b.relevanceScore-a.relevanceScore);if(skills.length===0){warnings.push({type:"no_results",message:`No executable skills found for queries: ${queries.join(", ")}${tags?.length?` with tags: ${tags.join(", ")}`:""}`})}if(lowRelevanceCount>0&&skills.length>0){warnings.push({type:"low_relevance",message:`${lowRelevanceCount} result(s) filtered due to relevance below ${minRelevanceScore}`})}return{skills,warnings,totalExecutableSkills}}};SearchSkillsTool=__decorateClass([Tool2({name:"codecall:searchSkills",cache:{ttl:60,slideWindow:false},codecall:{enabledInCodeCall:false,visibleInListTools:true},description:searchSkillsToolDescription,inputSchema:searchSkillsToolInputSchema,outputSchema:searchSkillsToolOutputSchema,annotations:{readOnlyHint:true,openWorldHint:true}})],SearchSkillsTool);import{filterServableSkills as filterServableSkills2,Tool as Tool3,ToolContext as ToolContext3}from"@frontmcp/sdk";import{z as z4}from"@frontmcp/lazy-zod";var searchKnowledgeToolDescription=`Search for KNOWLEDGE-ONLY skills \u2014 domain context the agent should read before deciding what to do. These skills have no tools and no openapi operation refs; they are pure prose / references / examples.
36
+ FLOW: searchSkills \u2192 describe \u2192 execute`;var searchSkillsToolInputSchema={queries:z3.array(z3.string().min(2).max(256)).min(1).max(10).describe("Atomic skill queries. Split complex requests into simple actions."),tags:z3.array(z3.string().min(1).max(64)).max(16).optional().describe("Filter to skills with any of these tags"),excludeSkillNames:z3.array(z3.string()).max(50).optional().describe("Skip already-known skill names"),topK:z3.number().int().positive().max(50).optional().default(5).describe("Results per query (default 5)"),minRelevanceScore:z3.number().min(0).max(1).optional().default(.1).describe("Minimum relevance threshold (default 0.1)")};var referencedOperationSchema=z3.object({spec:z3.string().describe('OpenAPI spec id (e.g. "acme")'),operationId:z3.string().describe('OpenAPI operation id (e.g. "getOrder")')});var skillSearchHitSchema=z3.object({name:z3.string().describe("Skill name"),description:z3.string().describe("Short description of what the skill does"),tags:z3.array(z3.string()).describe("Tags carried by the skill"),operations:z3.array(referencedOperationSchema).describe("OpenAPI operations the skill can call"),tools:z3.array(z3.string()).describe("Tool names the skill declares (if any)"),relevanceScore:z3.number().min(0).max(1).describe("Match score (0-1)"),matchedQueries:z3.array(z3.string()).describe("Which queries matched this skill"),source:z3.enum(["local","external"]).describe("Where the skill was loaded from")});var searchSkillsToolOutputSchema=z3.object({skills:z3.array(skillSearchHitSchema).describe("Deduplicated executable skills, sorted by relevance"),warnings:z3.array(z3.object({type:z3.enum(["no_results","low_relevance","excluded_skill_not_found"]).describe("Warning type"),message:z3.string().describe("Warning message"),affectedSkills:z3.array(z3.string()).optional().describe("Affected skill names")})).describe("Search warnings"),totalExecutableSkills:z3.number().int().nonnegative().describe("Total executable skills available")});var SearchSkillsTool=class extends ToolContext2{async execute(input){const{queries,tags,excludeSkillNames=[],topK=5,minRelevanceScore=.1}=input;const skillRegistry=this.scope.skills;const executableSkills=await filterServableSkills(this.scope,await skillsDiscoverableByAuthorities(this.scope,skillRegistry.getExecutableSkills(),this.authInfo));const executableSet=new Set(executableSkills.map(s=>s.name));const totalExecutableSkills=executableSkills.length;const warnings=[];const nonExistentExcluded=excludeSkillNames.filter(n=>!executableSet.has(n));if(nonExistentExcluded.length>0){warnings.push({type:"excluded_skill_not_found",message:`Excluded skills not found: ${nonExistentExcluded.join(", ")}`,affectedSkills:nonExistentExcluded})}const matches=new Map;let lowRelevanceCount=0;const excludedSet=new Set(excludeSkillNames);const perQueryResults=await Promise.all(queries.map(query=>skillRegistry.search(query,{topK,tags,minScore:minRelevanceScore}).then(results=>({query,results}))));for(const{query,results}of perQueryResults){for(const result of results){const name=result.metadata.name;if(!executableSet.has(name))continue;if(excludedSet.has(name))continue;if(result.score<minRelevanceScore){lowRelevanceCount++;continue}const existing=matches.get(name);if(existing){existing.matchedQueries.push(query);existing.relevanceScore=Math.max(existing.relevanceScore,result.score)}else{const ops=result.metadata.referencedOperations??[];const toolNames=(result.metadata.tools??[]).map(t=>{if(typeof t==="string")return t;if(typeof t==="object"&&t!==null&&"name"in t)return t.name;return null}).filter(n=>typeof n==="string");matches.set(name,{name,description:result.metadata.description,tags:result.metadata.tags??[],operations:ops.map(op=>({spec:op.spec,operationId:op.operationId})),tools:toolNames,relevanceScore:result.score,matchedQueries:[query],source:result.source})}}}const skills=Array.from(matches.values()).sort((a,b)=>b.relevanceScore-a.relevanceScore);if(skills.length===0){warnings.push({type:"no_results",message:`No executable skills found for queries: ${queries.join(", ")}${tags?.length?` with tags: ${tags.join(", ")}`:""}`})}if(lowRelevanceCount>0&&skills.length>0){warnings.push({type:"low_relevance",message:`${lowRelevanceCount} result(s) filtered due to relevance below ${minRelevanceScore}`})}return{skills,warnings,totalExecutableSkills}}};SearchSkillsTool=__decorateClass([Tool2({name:"codecall:searchSkills",cache:{ttl:60,slideWindow:false},codecall:{enabledInCodeCall:false,visibleInListTools:true},description:searchSkillsToolDescription,inputSchema:searchSkillsToolInputSchema,outputSchema:searchSkillsToolOutputSchema,annotations:{readOnlyHint:true,openWorldHint:true}})],SearchSkillsTool);import{filterServableSkills as filterServableSkills2,Tool as Tool3,ToolContext as ToolContext3}from"@frontmcp/sdk";import{z as z4}from"@frontmcp/lazy-zod";var searchKnowledgeToolDescription=`Search for KNOWLEDGE-ONLY skills \u2014 domain context the agent should read before deciding what to do. These skills have no tools and no openapi operation refs; they are pure prose / references / examples.
37
37
 
38
38
  USE WHEN: the agent needs background to interpret a request, validate eligibility, or recall a procedure that isn't yet executable.
39
39
 
@@ -46,8 +46,8 @@ INPUT:
46
46
 
47
47
  OUTPUT: Deduplicated knowledge skill list with description + tags. To read the body, follow up with describe(skillName) or the skill:// resource URI.
48
48
 
49
- FLOW: searchKnowledge \u2192 describe (for body) \u2192 continue with searchSkills`;var searchKnowledgeToolInputSchema={queries:z4.array(z4.string().min(2).max(256)).min(1).max(10).describe("Atomic context queries."),tags:z4.array(z4.string().min(1).max(64)).max(16).optional().describe("Filter to skills with any of these tags"),excludeSkillNames:z4.array(z4.string()).max(50).optional().describe("Skip already-loaded knowledge skill names"),topK:z4.number().int().positive().max(50).optional().default(5).describe("Results per query (default 5)"),minRelevanceScore:z4.number().min(0).max(1).optional().default(.1).describe("Minimum relevance threshold (default 0.1)")};var knowledgeHitSchema=z4.object({name:z4.string().describe("Skill name"),description:z4.string().describe("Short description of what the knowledge covers"),tags:z4.array(z4.string()).describe("Tags carried by the skill"),relevanceScore:z4.number().min(0).max(1).describe("Match score (0-1)"),matchedQueries:z4.array(z4.string()).describe("Which queries matched this knowledge"),source:z4.enum(["local","external"]).describe("Where the skill was loaded from")});var searchKnowledgeToolOutputSchema=z4.object({knowledge:z4.array(knowledgeHitSchema).describe("Deduplicated knowledge skills, sorted by relevance"),warnings:z4.array(z4.object({type:z4.enum(["no_results","low_relevance","excluded_skill_not_found"]).describe("Warning type"),message:z4.string().describe("Warning message"),affectedSkills:z4.array(z4.string()).optional().describe("Affected skill names")})).describe("Search warnings"),totalKnowledgeSkills:z4.number().int().nonnegative().describe("Total knowledge-only skills available")});var SearchKnowledgeTool=class extends ToolContext3{async execute(input){const{queries,tags,excludeSkillNames=[],topK=5,minRelevanceScore=.1}=input;const skillRegistry=this.scope.skills;const knowledgeSkills=await filterServableSkills2(this.scope,skillRegistry.getKnowledgeOnlySkills());const knowledgeSet=new Set(knowledgeSkills.map(s=>s.name));const totalKnowledgeSkills=knowledgeSkills.length;const warnings=[];const nonExistentExcluded=excludeSkillNames.filter(n=>!knowledgeSet.has(n));if(nonExistentExcluded.length>0){warnings.push({type:"excluded_skill_not_found",message:`Excluded knowledge skills not found: ${nonExistentExcluded.join(", ")}`,affectedSkills:nonExistentExcluded})}const matches=new Map;let lowRelevanceCount=0;const excludedSet=new Set(excludeSkillNames);const perQueryResults=await Promise.all(queries.map(query=>skillRegistry.search(query,{topK,tags,minScore:minRelevanceScore}).then(results=>({query,results}))));for(const{query,results}of perQueryResults){for(const result of results){const name=result.metadata.name;if(!knowledgeSet.has(name))continue;if(excludedSet.has(name))continue;if(result.score<minRelevanceScore){lowRelevanceCount++;continue}const existing=matches.get(name);if(existing){existing.matchedQueries.push(query);existing.relevanceScore=Math.max(existing.relevanceScore,result.score)}else{matches.set(name,{name,description:result.metadata.description,tags:result.metadata.tags??[],relevanceScore:result.score,matchedQueries:[query],source:result.source})}}}const knowledge=Array.from(matches.values()).sort((a,b)=>b.relevanceScore-a.relevanceScore);if(knowledge.length===0){warnings.push({type:"no_results",message:`No knowledge skills found for queries: ${queries.join(", ")}${tags?.length?` with tags: ${tags.join(", ")}`:""}`})}if(lowRelevanceCount>0&&knowledge.length>0){warnings.push({type:"low_relevance",message:`${lowRelevanceCount} result(s) filtered due to relevance below ${minRelevanceScore}`})}return{knowledge,warnings,totalKnowledgeSkills}}};SearchKnowledgeTool=__decorateClass([Tool3({name:"codecall:searchKnowledge",cache:{ttl:60,slideWindow:false},codecall:{enabledInCodeCall:false,visibleInListTools:true},description:searchKnowledgeToolDescription,inputSchema:searchKnowledgeToolInputSchema,outputSchema:searchKnowledgeToolOutputSchema,annotations:{readOnlyHint:true,openWorldHint:true}})],SearchKnowledgeTool);import{toJSONSchema,z as z6,ZodType}from"@frontmcp/lazy-zod";import{getCallSurface as getCallSurface2,InvalidInputError,Tool as Tool4,ToolContext as ToolContext4}from"@frontmcp/sdk";var INTENT_PATTERNS={create:/^(create|add|new|insert|make|append|register|generate|produce|build|construct|provision|instantiate|define|compose|draft)/i,delete:/^(delete|remove|destroy|drop|erase|clear|purge|discard|eliminate|unbind|unregister)/i,get:/^(get|fetch|retrieve|read|obtain|load|pull|access|grab|receive)/i,update:/^(update|edit|modify|change|patch|set|alter|revise|adjust|amend|correct|fix|refresh|sync|upgrade|downgrade)/i,list:/^(list|all|index|enumerate|show|display|view|browse|scan|inventory)/i,search:/^(search|find|query|lookup|locate|discover|explore|seek|match|filter)/i};function detectToolIntent(toolName,description){const parts=toolName.split(":");const actionPart=parts.length>1?parts[parts.length-1]:toolName;for(const[intent,pattern]of Object.entries(INTENT_PATTERNS)){if(pattern.test(actionPart)){return intent}}if(description){const descLower=description.toLowerCase();if(/creates?\s|adding\s|inserts?/i.test(descLower))return"create";if(/deletes?\s|removes?\s|destroys?/i.test(descLower))return"delete";if(/gets?\s|fetche?s?\s|retrieves?/i.test(descLower))return"get";if(/updates?\s|modif(?:y|ies)\s|edits?/i.test(descLower))return"update";if(/lists?\s|shows?\s|displays?/i.test(descLower))return"list";if(/search(?:es)?\s|find(?:s)?\s|quer(?:y|ies)/i.test(descLower))return"search"}return"unknown"}function generateBasicExample(toolName,inputSchema){const params=generateSampleParams(inputSchema);const paramsStr=params?JSON.stringify(params,null,2):"{}";return{description:`Basic usage of ${toolName}`,code:`const result = await callTool('${toolName}', ${paramsStr});
50
- return result;`}}function generateSampleParams(schema){if(!schema||schema.type!=="object"||!schema.properties){return null}const params={};const required=new Set(schema.required||[]);for(const[key,propSchema]of Object.entries(schema.properties)){if(typeof propSchema==="boolean")continue;if(!required.has(key))continue;params[key]=getSampleValue(propSchema,key)}return Object.keys(params).length>0?params:null}function fitString(schema,value){let fitted=value;if(schema.maxLength!==void 0&&fitted.length>schema.maxLength){fitted=fitted.slice(0,Math.max(0,schema.maxLength))}if(schema.minLength!==void 0&&fitted.length<schema.minLength){fitted=fitted.padEnd(schema.minLength,"x")}return fitted}function isFreeTextString(schema){return schema?.type==="string"&&schema.enum===void 0&&schema.const===void 0&&schema.default===void 0&&schema.pattern===void 0&&schema.format===void 0}function acceptsNumber(schema,value){if(schema.const!==void 0)return schema.const===value;if(schema.enum!==void 0)return schema.enum.includes(value);if(schema.minimum!==void 0&&value<schema.minimum)return false;if(schema.maximum!==void 0&&value>schema.maximum)return false;return true}function pickNumber(schema,preferred){const accepted=preferred.find(value=>acceptsNumber(schema,value));if(accepted!==void 0)return accepted;const named=[schema.const,schema.enum?.[0],schema.minimum,schema.maximum].find(value=>typeof value==="number"&&acceptsNumber(schema,value));return named}function formatInlineArgs(args){const entries=Object.entries(args).map(([key,value])=>{const name=/^[A-Za-z_$][\w$]*$/.test(key)?key:JSON.stringify(key);const plain=typeof value==="string"&&[...value].every(ch=>ch!=="'"&&ch!=="\\"&&ch>=" ");const literal=plain?`'${value}'`:JSON.stringify(value);return`${name}: ${literal}`});return entries.length>0?`{ ${entries.join(", ")} }`:"{}"}function getSampleValue(schema,key){if(schema.default!==void 0){return schema.default}if(schema.enum&&schema.enum.length>0){return schema.enum[0]}if(schema.const!==void 0){return schema.const}const type=Array.isArray(schema.type)?schema.type[0]:schema.type;switch(type){case"string":if(key.toLowerCase().includes("id"))return fitString(schema,"abc123");if(key.toLowerCase().includes("email"))return fitString(schema,"user@example.com");if(key.toLowerCase().includes("name"))return fitString(schema,"Example");if(key.toLowerCase().includes("url"))return fitString(schema,"https://example.com");return fitString(schema,"string");case"number":case"integer":if(key.toLowerCase().includes("limit"))return 10;if(key.toLowerCase().includes("offset"))return 0;if(key.toLowerCase().includes("page"))return 1;return 0;case"boolean":return true;case"array":return[];case"object":return{};default:return null}}var PAGINATION_PROPERTIES=["limit","offset","page","pagesize","cursor"];function isPaginationProperty(name){return PAGINATION_PROPERTIES.includes(name.toLowerCase())}function hasPaginationParams(schema){if(!schema||schema.type!=="object"||!schema.properties){return false}return Object.keys(schema.properties).some(isPaginationProperty)}function inputProperties(schema){if(!schema||schema.type!=="object"||!schema.properties){return{}}const properties={};for(const[key,propSchema]of Object.entries(schema.properties)){if(typeof propSchema!=="boolean")properties[key]=propSchema}return properties}function buildExampleArgs(schema,keys,values={}){const properties=inputProperties(schema);const args={};for(const key of[...keys,...schema?.required??[]]){const propSchema=properties[key];if(!propSchema||key in args)continue;args[key]=key in values?values[key]:getSampleValue(propSchema,key)}return args}function formatExampleArgs(args){return Object.keys(args).length>0?JSON.stringify(args,null,2):"{}"}function getFilterProperties(schema){if(!schema||schema.type!=="object"||!schema.properties){return[]}return Object.keys(schema.properties).filter(p=>p.toLowerCase().includes("filter")||p.toLowerCase().includes("query")||p.toLowerCase().includes("search")||p.toLowerCase()==="status"||p.toLowerCase()==="type"||p.toLowerCase()==="role")}function generatePaginationExample(toolName,inputSchema){const description=`Pagination example for ${toolName}`;const props=Object.keys(inputProperties(inputSchema));const limitKey=props.find(p=>p.toLowerCase()==="limit");const offsetKey=props.find(p=>p.toLowerCase()==="offset");if(limitKey&&offsetKey){const properties=inputProperties(inputSchema);const limit=pickNumber(properties[limitKey],[10]);const firstOffset=pickNumber(properties[offsetKey],[0]);const values={};if(limit!==void 0)values[limitKey]=limit;if(firstOffset!==void 0)values[offsetKey]=firstOffset;const firstPage=buildExampleArgs(inputSchema,[limitKey,offsetKey],values);const nextOffset=[limit??10,10,20,...properties[offsetKey].enum??[]].find(value=>typeof value==="number"&&value!==firstPage[offsetKey]&&acceptsNumber(properties[offsetKey],value));if(nextOffset!==void 0){const secondPage={...firstPage,[offsetKey]:nextOffset};return{description,code:`// Fetch first page
49
+ FLOW: searchKnowledge \u2192 describe (for body) \u2192 continue with searchSkills`;var searchKnowledgeToolInputSchema={queries:z4.array(z4.string().min(2).max(256)).min(1).max(10).describe("Atomic context queries."),tags:z4.array(z4.string().min(1).max(64)).max(16).optional().describe("Filter to skills with any of these tags"),excludeSkillNames:z4.array(z4.string()).max(50).optional().describe("Skip already-loaded knowledge skill names"),topK:z4.number().int().positive().max(50).optional().default(5).describe("Results per query (default 5)"),minRelevanceScore:z4.number().min(0).max(1).optional().default(.1).describe("Minimum relevance threshold (default 0.1)")};var knowledgeHitSchema=z4.object({name:z4.string().describe("Skill name"),description:z4.string().describe("Short description of what the knowledge covers"),tags:z4.array(z4.string()).describe("Tags carried by the skill"),relevanceScore:z4.number().min(0).max(1).describe("Match score (0-1)"),matchedQueries:z4.array(z4.string()).describe("Which queries matched this knowledge"),source:z4.enum(["local","external"]).describe("Where the skill was loaded from")});var searchKnowledgeToolOutputSchema=z4.object({knowledge:z4.array(knowledgeHitSchema).describe("Deduplicated knowledge skills, sorted by relevance"),warnings:z4.array(z4.object({type:z4.enum(["no_results","low_relevance","excluded_skill_not_found"]).describe("Warning type"),message:z4.string().describe("Warning message"),affectedSkills:z4.array(z4.string()).optional().describe("Affected skill names")})).describe("Search warnings"),totalKnowledgeSkills:z4.number().int().nonnegative().describe("Total knowledge-only skills available")});var SearchKnowledgeTool=class extends ToolContext3{async execute(input){const{queries,tags,excludeSkillNames=[],topK=5,minRelevanceScore=.1}=input;const skillRegistry=this.scope.skills;const knowledgeSkills=await filterServableSkills2(this.scope,await skillsDiscoverableByAuthorities(this.scope,skillRegistry.getKnowledgeOnlySkills(),this.authInfo));const knowledgeSet=new Set(knowledgeSkills.map(s=>s.name));const totalKnowledgeSkills=knowledgeSkills.length;const warnings=[];const nonExistentExcluded=excludeSkillNames.filter(n=>!knowledgeSet.has(n));if(nonExistentExcluded.length>0){warnings.push({type:"excluded_skill_not_found",message:`Excluded knowledge skills not found: ${nonExistentExcluded.join(", ")}`,affectedSkills:nonExistentExcluded})}const matches=new Map;let lowRelevanceCount=0;const excludedSet=new Set(excludeSkillNames);const perQueryResults=await Promise.all(queries.map(query=>skillRegistry.search(query,{topK,tags,minScore:minRelevanceScore}).then(results=>({query,results}))));for(const{query,results}of perQueryResults){for(const result of results){const name=result.metadata.name;if(!knowledgeSet.has(name))continue;if(excludedSet.has(name))continue;if(result.score<minRelevanceScore){lowRelevanceCount++;continue}const existing=matches.get(name);if(existing){existing.matchedQueries.push(query);existing.relevanceScore=Math.max(existing.relevanceScore,result.score)}else{matches.set(name,{name,description:result.metadata.description,tags:result.metadata.tags??[],relevanceScore:result.score,matchedQueries:[query],source:result.source})}}}const knowledge=Array.from(matches.values()).sort((a,b)=>b.relevanceScore-a.relevanceScore);if(knowledge.length===0){warnings.push({type:"no_results",message:`No knowledge skills found for queries: ${queries.join(", ")}${tags?.length?` with tags: ${tags.join(", ")}`:""}`})}if(lowRelevanceCount>0&&knowledge.length>0){warnings.push({type:"low_relevance",message:`${lowRelevanceCount} result(s) filtered due to relevance below ${minRelevanceScore}`})}return{knowledge,warnings,totalKnowledgeSkills}}};SearchKnowledgeTool=__decorateClass([Tool3({name:"codecall:searchKnowledge",cache:{ttl:60,slideWindow:false},codecall:{enabledInCodeCall:false,visibleInListTools:true},description:searchKnowledgeToolDescription,inputSchema:searchKnowledgeToolInputSchema,outputSchema:searchKnowledgeToolOutputSchema,annotations:{readOnlyHint:true,openWorldHint:true}})],SearchKnowledgeTool);import{toJSONSchema,z as z6,ZodType}from"@frontmcp/lazy-zod";import{getCallSurface as getCallSurface2,InvalidInputError,Tool as Tool4,ToolContext as ToolContext4}from"@frontmcp/sdk";var INTENT_PATTERNS={create:/^(create|add|new|insert|make|append|register|generate|produce|build|construct|provision|instantiate|define|compose|draft)/i,delete:/^(delete|remove|destroy|drop|erase|clear|purge|discard|eliminate|unbind|unregister)/i,get:/^(get|fetch|retrieve|read|obtain|load|pull|access|grab|receive)/i,update:/^(update|edit|modify|change|patch|set|alter|revise|adjust|amend|correct|fix|refresh|sync|upgrade|downgrade)/i,list:/^(list|all|index|enumerate|show|display|view|browse|scan|inventory)/i,search:/^(search|find|query|lookup|locate|discover|explore|seek|match|filter)/i};function detectToolIntent(toolName,description){const parts=toolName.split(":");const actionPart=parts.length>1?parts[parts.length-1]:toolName;for(const[intent,pattern]of Object.entries(INTENT_PATTERNS)){if(pattern.test(actionPart)){return intent}}if(description){const descLower=description.toLowerCase();if(/creates?\s|adding\s|inserts?/i.test(descLower))return"create";if(/deletes?\s|removes?\s|destroys?/i.test(descLower))return"delete";if(/gets?\s|fetche?s?\s|retrieves?/i.test(descLower))return"get";if(/updates?\s|modif(?:y|ies)\s|edits?/i.test(descLower))return"update";if(/lists?\s|shows?\s|displays?/i.test(descLower))return"list";if(/search(?:es)?\s|find(?:s)?\s|quer(?:y|ies)/i.test(descLower))return"search"}return"unknown"}function generateBasicExample(toolName,inputSchema){const params=generateSampleParams(inputSchema);const paramsStr=params?JSON.stringify(params,null,2):"{}";return{description:`Basic usage of ${toolName}`,code:`const result = await callTool('${toolName}', ${paramsStr});
50
+ return result;`}}function generateSampleParams(schema){if(!schema||schema.type!=="object"||!schema.properties){return null}const params={};const required=new Set(schema.required||[]);for(const[key,propSchema]of Object.entries(schema.properties)){if(typeof propSchema==="boolean")continue;if(!required.has(key))continue;params[key]=getSampleValue(propSchema,key)}return Object.keys(params).length>0?params:null}var MAX_PADDED_EXAMPLE_LENGTH=256;function fitString(schema,value){let fitted=value;if(schema.maxLength!==void 0&&fitted.length>schema.maxLength){fitted=fitted.slice(0,Math.max(0,schema.maxLength))}if(schema.minLength!==void 0&&fitted.length<schema.minLength){fitted=fitted.padEnd(Math.min(schema.minLength,MAX_PADDED_EXAMPLE_LENGTH),"x")}return fitted}function isFreeTextString(schema){return schema?.type==="string"&&schema.enum===void 0&&schema.const===void 0&&schema.default===void 0&&schema.pattern===void 0&&schema.format===void 0}function acceptsNumber(schema,value){if(schema.const!==void 0)return schema.const===value;if(schema.enum!==void 0)return schema.enum.includes(value);if(schema.minimum!==void 0&&value<schema.minimum)return false;if(schema.maximum!==void 0&&value>schema.maximum)return false;return true}function pickNumber(schema,preferred){const accepted=preferred.find(value=>acceptsNumber(schema,value));if(accepted!==void 0)return accepted;const named=[schema.const,schema.enum?.[0],schema.minimum,schema.maximum].find(value=>typeof value==="number"&&acceptsNumber(schema,value));return named}function formatInlineArgs(args){const entries=Object.entries(args).map(([key,value])=>{const name=/^[A-Za-z_$][\w$]*$/.test(key)?key:JSON.stringify(key);const plain=typeof value==="string"&&[...value].every(ch=>ch!=="'"&&ch!=="\\"&&ch>=" ");const literal=plain?`'${value}'`:JSON.stringify(value);return`${name}: ${literal}`});return entries.length>0?`{ ${entries.join(", ")} }`:"{}"}function getSampleValue(schema,key){if(schema.default!==void 0){return schema.default}if(schema.enum&&schema.enum.length>0){return schema.enum[0]}if(schema.const!==void 0){return schema.const}const type=Array.isArray(schema.type)?schema.type[0]:schema.type;switch(type){case"string":if(key.toLowerCase().includes("id"))return fitString(schema,"abc123");if(key.toLowerCase().includes("email"))return fitString(schema,"user@example.com");if(key.toLowerCase().includes("name"))return fitString(schema,"Example");if(key.toLowerCase().includes("url"))return fitString(schema,"https://example.com");return fitString(schema,"string");case"number":case"integer":if(key.toLowerCase().includes("limit"))return 10;if(key.toLowerCase().includes("offset"))return 0;if(key.toLowerCase().includes("page"))return 1;return 0;case"boolean":return true;case"array":return[];case"object":return{};default:return null}}var PAGINATION_PROPERTIES=["limit","offset","page","pagesize","cursor"];function isPaginationProperty(name){return PAGINATION_PROPERTIES.includes(name.toLowerCase())}function hasPaginationParams(schema){if(!schema||schema.type!=="object"||!schema.properties){return false}return Object.keys(schema.properties).some(isPaginationProperty)}function inputProperties(schema){if(!schema||schema.type!=="object"||!schema.properties){return{}}const properties={};for(const[key,propSchema]of Object.entries(schema.properties)){if(typeof propSchema!=="boolean")properties[key]=propSchema}return properties}function buildExampleArgs(schema,keys,values={}){const properties=inputProperties(schema);const args={};for(const key of[...keys,...schema?.required??[]]){const propSchema=properties[key];if(!propSchema||key in args)continue;args[key]=key in values?values[key]:getSampleValue(propSchema,key)}return args}function formatExampleArgs(args){return Object.keys(args).length>0?JSON.stringify(args,null,2):"{}"}function getFilterProperties(schema){if(!schema||schema.type!=="object"||!schema.properties){return[]}return Object.keys(schema.properties).filter(p=>p.toLowerCase().includes("filter")||p.toLowerCase().includes("query")||p.toLowerCase().includes("search")||p.toLowerCase()==="status"||p.toLowerCase()==="type"||p.toLowerCase()==="role")}function generatePaginationExample(toolName,inputSchema){const description=`Pagination example for ${toolName}`;const props=Object.keys(inputProperties(inputSchema));const limitKey=props.find(p=>p.toLowerCase()==="limit");const offsetKey=props.find(p=>p.toLowerCase()==="offset");if(limitKey&&offsetKey){const properties=inputProperties(inputSchema);const limit=pickNumber(properties[limitKey],[10]);const firstOffset=pickNumber(properties[offsetKey],[0]);const values={};if(limit!==void 0)values[limitKey]=limit;if(firstOffset!==void 0)values[offsetKey]=firstOffset;const firstPage=buildExampleArgs(inputSchema,[limitKey,offsetKey],values);const nextOffset=[limit??10,10,20,...properties[offsetKey].enum??[]].find(value=>typeof value==="number"&&value!==firstPage[offsetKey]&&acceptsNumber(properties[offsetKey],value));if(nextOffset!==void 0){const secondPage={...firstPage,[offsetKey]:nextOffset};return{description,code:`// Fetch first page
51
51
  const page1 = await callTool('${toolName}', ${formatExampleArgs(firstPage)});
52
52
 
53
53
  // Fetch second page
@@ -74,8 +74,8 @@ INPUT: toolNames: string[] - tool names from search, at most the server's maxDef
74
74
  OUTPUT per tool: inputSchema (JSON Schema), outputSchema (JSON Schema), usageExamples (up to 5 callTool examples)
75
75
 
76
76
  IMPORTANT: If notFound array is non-empty \u2192 re-search with corrected queries.
77
- FLOW: search \u2192 describe \u2192 execute/invoke`;var describeToolInputSchema={toolNames:z5.array(z5.string()).min(1).superRefine((toolNames,ctx)=>{const seen=new Set;const duplicates=new Set;for(const name of toolNames){if(seen.has(name)){duplicates.add(name)}seen.add(name)}if(duplicates.size>0){ctx.addIssue({code:z5.ZodIssueCode.custom,message:`Duplicate tool names are not allowed: ${Array.from(duplicates).join(", ")}`})}}).describe('Array of unique tool names (from codecall:search results) to fetch their detailed schemas and usage examples. Example: ["users:list", "billing:getInvoice"]')};var describeToolOutputSchema=z5.object({tools:z5.array(z5.object({name:z5.string().describe("Tool name to be used in callTool() within codecall:execute scripts"),appId:z5.string().describe("The app ID this tool belongs to"),description:z5.string().describe("Detailed description of what this tool does"),inputSchema:z5.record(z5.string(),z5.unknown()).nullable().describe("JSON Schema object describing the tool input parameters"),outputSchema:z5.record(z5.string(),z5.unknown()).nullable().describe("JSON Schema object describing the tool output structure"),annotations:ToolAnnotationsSchema.optional().describe("MCP tool annotations (metadata)"),usageExamples:z5.array(z5.object({description:z5.string().describe("Description of what this example demonstrates"),code:z5.string().describe('JavaScript code example showing how to call this tool using callTool(). Format: const result = await callTool("tool:name", { ...params });')})).max(5).describe("Up to 5 practical examples of how to use this tool in a codecall:execute script")})).describe("Array of tool descriptions with schemas and usage examples"),notFound:z5.array(z5.string()).optional().describe("Tool names that were requested but not found in the index. Check these for typos.")});var DescribeTool=class extends ToolContext4{async execute(input){const{toolNames}=input;const audit=this.tryGet(AuditLoggerService);const executionId=audit?audit.generateExecutionId():"";const startedAt=Date.now();const config=this.get(CodeCallConfig);const maxDefinitions=config.get("maxDefinitions");const tools=[];const notFound=[];const surface=getCallSurface2();for(const toolName of toolNames){if(isBlockedSelfReference(toolName)){notFound.push(toolName);continue}const access=checkCodeCallToolAccess(this.scope,config,toolName,{surface});if(!access.allowed){audit?.logSecurityAccessDenied(executionId,toolName,access.reason);notFound.push(toolName);continue}const tool=access.entry;if(tools.length>=maxDefinitions){throw new InvalidInputError(`codecall:describe describes at most ${maxDefinitions} tools per call; describe the rest in another call`)}const appId=this.extractAppId(tool);const inputSchema=this.getInputSchema(tool);const outputSchema=this.toJsonSchema(tool.rawOutputSchema??tool.outputSchema);const usageExamples=this.generateExamples(tool,inputSchema??void 0);tools.push({name:tool.name,appId,description:tool.metadata?.description||`Tool: ${tool.name}`,inputSchema:inputSchema||null,outputSchema:outputSchema||null,annotations:tool.metadata?.annotations,usageExamples})}audit?.logDescribe(executionId,toolNames,Date.now()-startedAt);return{tools,notFound:notFound.length>0?notFound:void 0}}getInputSchema(tool){if(tool.inputSchema&&typeof tool.inputSchema==="object"&&Object.keys(tool.inputSchema).length>0){try{const firstValue=Object.values(tool.inputSchema)[0];if(firstValue instanceof ZodType){return toJSONSchema(z6.object(tool.inputSchema))}}catch{}}if(tool.rawInputSchema){return tool.rawInputSchema}return null}toJsonSchema(schema){if(!schema){return null}if(schema instanceof ZodType){try{return toJSONSchema(schema)}catch{return null}}if(typeof schema==="object"&&schema!==null&&!Array.isArray(schema)){const obj=schema;const firstValue=Object.values(obj)[0];if(firstValue instanceof ZodType){try{return toJSONSchema(z6.object(obj))}catch{return null}}if("type"in obj||"properties"in obj||"$schema"in obj){return schema}}if(typeof schema==="string"){return null}if(Array.isArray(schema)){return null}return null}extractAppId(tool){if(tool.metadata?.codecall?.appId){return tool.metadata.codecall.appId}if(tool.metadata?.source){return tool.metadata.source}if(tool.owner?.id){return tool.owner.id}const nameParts=tool.name?.split(":");if(nameParts&&nameParts.length>1){return nameParts[0]}return"unknown"}generateExamples(tool,inputSchema){const result=[];const examples=tool.metadata?.examples;if(examples&&Array.isArray(examples)){for(const ex of examples.slice(0,5)){result.push({description:ex.description||"Example usage",code:`const result = await callTool('${tool.name}', ${JSON.stringify(ex.input,null,2)});
78
- return result;`})}}if(result.length===0){result.push(generateSmartExample(tool.name,inputSchema,tool.metadata?.description))}return result.slice(0,5)}};DescribeTool=__decorateClass([Tool4({name:"codecall:describe",cache:{ttl:60,slideWindow:false},codecall:{enabledInCodeCall:false,visibleInListTools:true},description:describeToolDescription,inputSchema:describeToolInputSchema,outputSchema:describeToolOutputSchema,annotations:{readOnlyHint:true,openWorldHint:true}})],DescribeTool);import{getCallSurface as getCallSurface3,toMcpError,Tool as Tool5,ToolContext as ToolContext5}from"@frontmcp/sdk";import{z as z7}from"@frontmcp/lazy-zod";var MIN_EXECUTE_SCRIPT_LENGTH='return callTool("a",{})'.length;var ALWAYS_BLOCKED_NAMES=["eval","require","fetch","setTimeout","process","globalThis"];function buildExecuteToolDescription(vmOptions){const loops=vmOptions.allowLoops?"for, for-of":"for-of";const blockedLoops=vmOptions.allowLoops?"while, do-while":"while, do-while, for";const blockedNames=new Set([...ALWAYS_BLOCKED_NAMES,...vmOptions.disabledBuiltins,...vmOptions.disabledGlobals]);const namespaces=["Math","JSON"].filter(name=>!blockedNames.has(name)).map(name=>`${name}.*, `);const timeoutSeconds=vmOptions.timeoutMs/1e3;const maxToolCalls=maxToolCallsOf(vmOptions);const callsPerTool=rapidEnumerationThresholdOf(vmOptions);const blockedConsole=vmOptions.allowConsole?"":"console (use mcpLog), ";const consoleLine=vmOptions.allowConsole?"\nLOGGING: console.log/info/warn/error/debug or mcpLog(level, message)":"";return`Execute AgentScript (safe JS subset) for multi-tool orchestration.
77
+ FLOW: search \u2192 describe \u2192 execute/invoke`;var describeToolInputSchema={toolNames:z5.array(z5.string()).min(1).superRefine((toolNames,ctx)=>{const seen=new Set;const duplicates=new Set;for(const name of toolNames){if(seen.has(name)){duplicates.add(name)}seen.add(name)}if(duplicates.size>0){ctx.addIssue({code:z5.ZodIssueCode.custom,message:`Duplicate tool names are not allowed: ${Array.from(duplicates).join(", ")}`})}}).describe('Array of unique tool names (from codecall:search results) to fetch their detailed schemas and usage examples. Example: ["users:list", "billing:getInvoice"]')};var describeToolOutputSchema=z5.object({tools:z5.array(z5.object({name:z5.string().describe("Tool name to be used in callTool() within codecall:execute scripts"),appId:z5.string().describe("The app ID this tool belongs to"),description:z5.string().describe("Detailed description of what this tool does"),inputSchema:z5.record(z5.string(),z5.unknown()).nullable().describe("JSON Schema object describing the tool input parameters"),outputSchema:z5.record(z5.string(),z5.unknown()).nullable().describe("JSON Schema object describing the tool output structure"),annotations:ToolAnnotationsSchema.optional().describe("MCP tool annotations (metadata)"),usageExamples:z5.array(z5.object({description:z5.string().describe("Description of what this example demonstrates"),code:z5.string().describe('JavaScript code example showing how to call this tool using callTool(). Format: const result = await callTool("tool:name", { ...params });')})).max(5).describe("Up to 5 practical examples of how to use this tool in a codecall:execute script")})).describe("Array of tool descriptions with schemas and usage examples"),notFound:z5.array(z5.string()).optional().describe("Tool names that were requested but not found in the index. Check these for typos.")});var DescribeTool=class extends ToolContext4{async execute(input){const{toolNames}=input;const audit=this.tryGet(AuditLoggerService);const executionId=audit?audit.generateExecutionId():"";const startedAt=Date.now();const config=this.get(CodeCallConfig);const maxDefinitions=config.get("maxDefinitions");const tools=[];const notFound=[];const surface=getCallSurface2();const withheld=await toolsWithheldByAuthorities(this.scope,this.authInfo);for(const toolName of toolNames){if(isBlockedSelfReference(toolName)){notFound.push(toolName);continue}const access=checkCodeCallToolAccess(this.scope,config,toolName,{surface});if(!access.allowed){audit?.logSecurityAccessDenied(executionId,toolName,access.reason);notFound.push(toolName);continue}const tool=access.entry;if(withheld.has(tool.fullName)){audit?.logSecurityAccessDenied(executionId,toolName,"withheld by the tool's authorities");notFound.push(toolName);continue}if(tools.length>=maxDefinitions){throw new InvalidInputError(`codecall:describe describes at most ${maxDefinitions} tools per call; describe the rest in another call`)}const appId=this.extractAppId(tool);const inputSchema=this.getInputSchema(tool);const outputSchema=this.toJsonSchema(tool.rawOutputSchema??tool.outputSchema);const usageExamples=this.generateExamples(tool,inputSchema??void 0);tools.push({name:tool.name,appId,description:tool.metadata?.description||`Tool: ${tool.name}`,inputSchema:inputSchema||null,outputSchema:outputSchema||null,annotations:tool.metadata?.annotations,usageExamples})}audit?.logDescribe(executionId,toolNames,Date.now()-startedAt);return{tools,notFound:notFound.length>0?notFound:void 0}}getInputSchema(tool){if(tool.inputSchema&&typeof tool.inputSchema==="object"&&Object.keys(tool.inputSchema).length>0){try{const firstValue=Object.values(tool.inputSchema)[0];if(firstValue instanceof ZodType){return toJSONSchema(z6.object(tool.inputSchema))}}catch{}}if(tool.rawInputSchema){return tool.rawInputSchema}return null}toJsonSchema(schema){if(!schema){return null}if(schema instanceof ZodType){try{return toJSONSchema(schema)}catch{return null}}if(typeof schema==="object"&&schema!==null&&!Array.isArray(schema)){const obj=schema;const firstValue=Object.values(obj)[0];if(firstValue instanceof ZodType){try{return toJSONSchema(z6.object(obj))}catch{return null}}if("type"in obj||"properties"in obj||"$schema"in obj){return schema}}if(typeof schema==="string"){return null}if(Array.isArray(schema)){return null}return null}extractAppId(tool){if(tool.metadata?.codecall?.appId){return tool.metadata.codecall.appId}if(tool.metadata?.source){return tool.metadata.source}if(tool.owner?.id){return tool.owner.id}const nameParts=tool.name?.split(":");if(nameParts&&nameParts.length>1){return nameParts[0]}return"unknown"}generateExamples(tool,inputSchema){const result=[];const examples=tool.metadata?.examples;if(examples&&Array.isArray(examples)){for(const ex of examples.slice(0,5)){result.push({description:ex.description||"Example usage",code:`const result = await callTool('${tool.name}', ${JSON.stringify(ex.input,null,2)});
78
+ return result;`})}}if(result.length===0){result.push(generateSmartExample(tool.name,inputSchema,tool.metadata?.description))}return result.slice(0,5)}};DescribeTool=__decorateClass([Tool4({name:"codecall:describe",cache:{ttl:60,slideWindow:false},codecall:{enabledInCodeCall:false,visibleInListTools:true},description:describeToolDescription,inputSchema:describeToolInputSchema,outputSchema:describeToolOutputSchema,annotations:{readOnlyHint:true,openWorldHint:true}})],DescribeTool);import{getCallSurface as getCallSurface3,toMcpError,Tool as Tool5,ToolContext as ToolContext5}from"@frontmcp/sdk";import{escapeControlCharacters}from"@frontmcp/utils";import{z as z7}from"@frontmcp/lazy-zod";var MIN_EXECUTE_SCRIPT_LENGTH='return callTool("a",{})'.length;var ALWAYS_BLOCKED_NAMES=["eval","require","fetch","setTimeout","process","globalThis"];function buildExecuteToolDescription(vmOptions){const loops=vmOptions.allowLoops?"for, for-of":"for-of";const blockedLoops=vmOptions.allowLoops?"while, do-while":"while, do-while, for";const blockedNames=new Set([...ALWAYS_BLOCKED_NAMES,...vmOptions.disabledBuiltins,...vmOptions.disabledGlobals]);const namespaces=["Math","JSON"].filter(name=>!blockedNames.has(name)).map(name=>`${name}.*, `);const timeoutSeconds=vmOptions.timeoutMs/1e3;const maxToolCalls=maxToolCallsOf(vmOptions);const callsPerTool=rapidEnumerationThresholdOf(vmOptions);const blockedConsole=vmOptions.allowConsole?"":"console (use mcpLog), ";const consoleLine=vmOptions.allowConsole?"\nLOGGING: console.log/info/warn/error/debug or mcpLog(level, message)":"";return`Execute AgentScript (safe JS subset) for multi-tool orchestration.
79
79
 
80
80
  API: await callTool(name, args, opts?)
81
81
  - Default: throws on error
@@ -95,7 +95,7 @@ BLOCKED: ${blockedLoops}, ${blockedConsole}function decl, ${[...blockedNames].jo
95
95
 
96
96
  ERRORS: NOT_FOUND | VALIDATION | EXECUTION | TIMEOUT | ACCESS_DENIED | RATE_LIMITED
97
97
  STATUS: ok | syntax_error | illegal_access | runtime_error | tool_error | timeout
98
- LIMITS: ${MAX_ITERATIONS_PER_LOOP} iterations per loop, ${timeoutSeconds}s timeout, ${maxToolCalls} tool calls, ${callsPerTool} calls to one tool per 2s (parallel() included)`}var executeToolDescription=buildExecuteToolDescription(resolveVmOptions());var executeToolInputSchema={script:z7.string().min(MIN_EXECUTE_SCRIPT_LENGTH).max(100*1024).describe("JavaScript code to execute in the sandbox. Must return a value (implicitly or via explicit return). Use callTool(name, input) to invoke tools."),allowedTools:z7.array(z7.string()).optional().describe('Optional whitelist of tool names that can be called from this script. If not provided, all indexed tools are available. Example: ["users:list", "billing:getInvoice"]')};var syntaxErrorPayloadSchema=z7.object({message:z7.string(),location:z7.object({line:z7.number(),column:z7.number()}).optional()});var illegalAccessErrorPayloadSchema=z7.object({message:z7.string(),kind:z7.union([z7.literal("IllegalBuiltinAccess"),z7.literal("DisallowedGlobal"),z7.string()])});var runtimeErrorPayloadSchema=z7.object({source:z7.literal("script"),message:z7.string(),name:z7.string().optional(),stack:z7.string().optional()});var toolErrorPayloadSchema=z7.object({source:z7.literal("tool"),toolName:z7.string(),toolInput:z7.unknown().optional(),message:z7.string(),code:z7.string().optional(),details:z7.unknown().optional()});var timeoutErrorPayloadSchema=z7.object({message:z7.string()});var codeCallOkResultSchema=z7.object({status:z7.literal("ok"),result:z7.unknown(),logs:z7.array(z7.string()).optional()});var codeCallSyntaxErrorResultSchema=z7.object({status:z7.literal("syntax_error"),error:syntaxErrorPayloadSchema});var codeCallIllegalAccessResultSchema=z7.object({status:z7.literal("illegal_access"),error:illegalAccessErrorPayloadSchema});var codeCallRuntimeErrorResultSchema=z7.object({status:z7.literal("runtime_error"),error:runtimeErrorPayloadSchema});var codeCallToolErrorResultSchema=z7.object({status:z7.literal("tool_error"),error:toolErrorPayloadSchema});var codeCallTimeoutResultSchema=z7.object({status:z7.literal("timeout"),error:timeoutErrorPayloadSchema});var executeToolOutputSchema=z7.discriminatedUnion("status",[codeCallOkResultSchema,codeCallSyntaxErrorResultSchema,codeCallIllegalAccessResultSchema,codeCallRuntimeErrorResultSchema,codeCallToolErrorResultSchema,codeCallTimeoutResultSchema]);function getErrorCode(error,clientError){if(error instanceof Error&&error.name==="ZodError"){return TOOL_CALL_ERROR_CODES.VALIDATION}switch(clientError.code){case"INVALID_INPUT":return TOOL_CALL_ERROR_CODES.VALIDATION;case"TOOL_NOT_FOUND":return TOOL_CALL_ERROR_CODES.NOT_FOUND;case"EXECUTION_TIMEOUT":return TOOL_CALL_ERROR_CODES.TIMEOUT;case"RATE_LIMIT_EXCEEDED":case"QUOTA_EXCEEDED":case"CONCURRENCY_LIMIT":case"QUEUE_TIMEOUT":return TOOL_CALL_ERROR_CODES.RATE_LIMITED}return clientError.statusCode===429?TOOL_CALL_ERROR_CODES.RATE_LIMITED:TOOL_CALL_ERROR_CODES.EXECUTION}function toolCallErrorOf(error,toolName){const clientError=toMcpError(error);const code=getErrorCode(error,clientError);return clientError.isPublic?createPublicToolCallError(code,toolName,clientError.getPublicMessage()):createToolCallError(code,toolName)}var ExecuteTool=class extends ToolContext5{checkToolPolicy(name,surface){return checkCodeCallToolAccess(this.scope,this.get(CodeCallConfig),name,{surface})}async execute(input){const{script,allowedTools}=input;const callerSurface=getCallSurface3();const audit=this.tryGet(AuditLoggerService);const executionId=audit?audit.generateExecutionId():"";const callDepth=1;let toolCallCount=0;const allowedToolSet=allowedTools?new Set(allowedTools):null;const environment={callTool:async(name,toolInput,options)=>{const throwOnError=options?.throwOnError!==false;if(isBlockedSelfReference(name)){audit?.logSecuritySelfReference(executionId,name)}assertNotSelfReference(name);const decision=this.checkToolPolicy(name,callerSurface);if(!decision.allowed){audit?.logSecurityAccessDenied(executionId,name,decision.reason);const error=createToolCallError(TOOL_CALL_ERROR_CODES.ACCESS_DENIED,name,decision.reason);if(throwOnError){throw error}return{success:false,error}}if(allowedToolSet&&!allowedToolSet.has(name)){audit?.logSecurityAccessDenied(executionId,name,"not in the caller-supplied allowedTools list");const error=createToolCallError(TOOL_CALL_ERROR_CODES.ACCESS_DENIED,name);if(throwOnError){throw error}return{success:false,error}}toolCallCount+=1;audit?.logToolCallStart(executionId,name,callDepth);const toolCallStartedAt=Date.now();try{const request={method:"tools/call",params:{name,arguments:toolInput}};const ctx=asCodeCallDispatch({authInfo:this.authInfo,surface:callerSurface});const mcpResult=await this.scope.runFlow("tools:call-tool",{request,ctx});if(!mcpResult){audit?.logToolCallFailure(executionId,name,callDepth,Date.now()-toolCallStartedAt,TOOL_CALL_ERROR_CODES.EXECUTION);const error=createToolCallError(TOOL_CALL_ERROR_CODES.EXECUTION,name,"Flow returned no result");if(throwOnError){throw error}return{success:false,error}}const result=extractResultFromCallToolResult(mcpResult);audit?.logToolCallSuccess(executionId,name,callDepth,Date.now()-toolCallStartedAt);if(throwOnError){return result}return{success:true,data:result}}catch(error){const sanitizedError=toolCallErrorOf(error,name);audit?.logToolCallFailure(executionId,name,callDepth,Date.now()-toolCallStartedAt,sanitizedError.code);if(throwOnError){throw sanitizedError}return{success:false,error:sanitizedError}}},getTool:name=>{try{if(isBlockedSelfReference(name)){audit?.logSecuritySelfReference(executionId,name);return void 0}const introspectionAccess=this.checkToolPolicy(name,callerSurface);if(!introspectionAccess.allowed){audit?.logSecurityAccessDenied(executionId,name,introspectionAccess.reason);return void 0}if(allowedToolSet&&!allowedToolSet.has(name))return void 0;const tool=introspectionAccess.entry;return toPlainJson({name:tool.name,description:tool.metadata?.description,inputSchema:tool.getInputJsonSchema?.()??null,outputSchema:tool.getOutputJsonSchema?.()??null})}catch{return void 0}},mcpLog:(level,message,metadata)=>{this.logger?.[level](message,metadata)},mcpNotify:(event,payload)=>{this.logger?.debug("Notification sent",{event,payload})}};try{const policyConfig=readCodeCallPolicyConfig(this.get(CodeCallConfig));const callableTools=this.scope.tools.getTools(true).filter(tool=>checkCodeCallToolPolicy(toCodeCallPolicyTool(tool,void 0,this.scope),policyConfig).allowed);const{namespaces,skipped}=buildToolNamespaces(callableTools);environment.toolNamespaces=namespaces;if(skipped.length>0){this.logger?.debug?.("codecall: tools skipped during namespace generation",{count:skipped.length,sample:skipped.slice(0,25)})}}catch(error){this.logger?.warn?.("codecall: failed to build tool namespaces",{error:error instanceof Error?error.message:String(error)})}const enclaveService=this.get(EnclaveService);const config=this.get(CodeCallConfig);const startedAt=Date.now();const elapsed=reported=>reported??Date.now()-startedAt;audit?.logExecutionStart(executionId,script);try{const executionResult=await enclaveService.execute(script,environment);const durationMs=elapsed(executionResult.stats?.duration);if(executionResult.timedOut){audit?.logExecutionTimeout(executionId,script,durationMs);return{status:"timeout",error:{message:`Script execution timed out after ${config.getAll().resolvedVm.timeoutMs}ms`}}}if(!executionResult.success){const error=executionResult.error;if(error.code==="SYNTAX_ERROR"){audit?.logExecutionFailure(executionId,script,durationMs,error.message);return{status:"syntax_error",error:{message:toClientErrorMessage(error.message)||"Syntax error in script",...error.location?{location:error.location}:{}}}}if(error.code==="VALIDATION_ERROR"||error.name==="ValidationError"){audit?.logSecurityAstBlocked(executionId,error.blockedPatterns?.join(", ")??"UNKNOWN",error.message);audit?.logExecutionFailure(executionId,script,durationMs,error.message);return{status:"illegal_access",error:{kind:"IllegalBuiltinAccess",message:error.message}}}if(error.toolName){audit?.logExecutionFailure(executionId,script,durationMs,error.message);return{status:"tool_error",error:{source:"tool",toolName:error.toolName,message:toClientErrorMessage(error.message),code:error.code}}}audit?.logExecutionFailure(executionId,script,durationMs,error.message);return{status:"runtime_error",error:{source:"script",message:toClientErrorMessage(error.message),name:error.name}}}audit?.logExecutionSuccess(executionId,script,durationMs,toolCallCount);return{status:"ok",result:executionResult.result,logs:executionResult.logs.length>0?executionResult.logs:void 0}}catch(error){const errorName=error instanceof Error?error.name:"Error";const errorMessage=error instanceof Error?error.message:String(error);audit?.logExecutionFailure(executionId,script,elapsed(),errorMessage);const errorLoc=error.loc;if(errorName==="SyntaxError"||errorMessage?.includes("syntax")){return{status:"syntax_error",error:{message:toClientErrorMessage(errorMessage)||"Syntax error in script",location:errorLoc?{line:errorLoc.line,column:errorLoc.column}:void 0}}}return{status:"runtime_error",error:{source:"script",message:toClientErrorMessage(errorMessage)||"An unexpected error occurred during script execution",name:errorName}}}}};ExecuteTool=__decorateClass([Tool5({name:"codecall:execute",cache:{ttl:0,slideWindow:false},codecall:{enabledInCodeCall:false,visibleInListTools:true},description:executeToolDescription,inputSchema:executeToolInputSchema,outputSchema:executeToolOutputSchema})],ExecuteTool);import{getCallSurface as getCallSurface4,Tool as Tool6,ToolContext as ToolContext6}from"@frontmcp/sdk";import{z as z8}from"@frontmcp/lazy-zod";var invokeToolDescription=`Call ONE tool directly. Returns standard MCP CallToolResult.
98
+ LIMITS: ${MAX_ITERATIONS_PER_LOOP} iterations per loop, ${timeoutSeconds}s timeout, ${maxToolCalls} tool calls, ${callsPerTool} calls to one tool per 2s (parallel() included)`}var executeToolDescription=buildExecuteToolDescription(resolveVmOptions());var executeToolInputSchema={script:z7.string().min(MIN_EXECUTE_SCRIPT_LENGTH).max(100*1024).describe("JavaScript code to execute in the sandbox. Must return a value (implicitly or via explicit return). Use callTool(name, input) to invoke tools."),allowedTools:z7.array(z7.string()).optional().describe('Optional whitelist of tool names that can be called from this script. If not provided, all indexed tools are available. Example: ["users:list", "billing:getInvoice"]')};var syntaxErrorPayloadSchema=z7.object({message:z7.string(),location:z7.object({line:z7.number(),column:z7.number()}).optional()});var illegalAccessErrorPayloadSchema=z7.object({message:z7.string(),kind:z7.union([z7.literal("IllegalBuiltinAccess"),z7.literal("DisallowedGlobal"),z7.string()])});var runtimeErrorPayloadSchema=z7.object({source:z7.literal("script"),message:z7.string(),name:z7.string().optional(),stack:z7.string().optional()});var toolErrorPayloadSchema=z7.object({source:z7.literal("tool"),toolName:z7.string(),toolInput:z7.unknown().optional(),message:z7.string(),code:z7.string().optional(),details:z7.unknown().optional()});var timeoutErrorPayloadSchema=z7.object({message:z7.string()});var codeCallOkResultSchema=z7.object({status:z7.literal("ok"),result:z7.unknown(),logs:z7.array(z7.string()).optional()});var codeCallSyntaxErrorResultSchema=z7.object({status:z7.literal("syntax_error"),error:syntaxErrorPayloadSchema});var codeCallIllegalAccessResultSchema=z7.object({status:z7.literal("illegal_access"),error:illegalAccessErrorPayloadSchema});var codeCallRuntimeErrorResultSchema=z7.object({status:z7.literal("runtime_error"),error:runtimeErrorPayloadSchema});var codeCallToolErrorResultSchema=z7.object({status:z7.literal("tool_error"),error:toolErrorPayloadSchema});var codeCallTimeoutResultSchema=z7.object({status:z7.literal("timeout"),error:timeoutErrorPayloadSchema});var executeToolOutputSchema=z7.discriminatedUnion("status",[codeCallOkResultSchema,codeCallSyntaxErrorResultSchema,codeCallIllegalAccessResultSchema,codeCallRuntimeErrorResultSchema,codeCallToolErrorResultSchema,codeCallTimeoutResultSchema]);function getErrorCode(error,clientError){if(error instanceof Error&&error.name==="ZodError"){return TOOL_CALL_ERROR_CODES.VALIDATION}switch(clientError.code){case"INVALID_INPUT":return TOOL_CALL_ERROR_CODES.VALIDATION;case"TOOL_NOT_FOUND":return TOOL_CALL_ERROR_CODES.NOT_FOUND;case"EXECUTION_TIMEOUT":return TOOL_CALL_ERROR_CODES.TIMEOUT;case"RATE_LIMIT_EXCEEDED":case"QUOTA_EXCEEDED":case"CONCURRENCY_LIMIT":case"QUEUE_TIMEOUT":return TOOL_CALL_ERROR_CODES.RATE_LIMITED}return clientError.statusCode===429?TOOL_CALL_ERROR_CODES.RATE_LIMITED:TOOL_CALL_ERROR_CODES.EXECUTION}function toolCallErrorOf(error,toolName){const clientError=toMcpError(error);const code=getErrorCode(error,clientError);return clientError.isPublic?createPublicToolCallError(code,toolName,clientError.getPublicMessage()):createToolCallError(code,toolName)}var ExecuteTool=class extends ToolContext5{checkToolPolicy(name,surface){return checkCodeCallToolAccess(this.scope,this.get(CodeCallConfig),name,{surface})}async execute(input){const{script,allowedTools}=input;const callerSurface=getCallSurface3();const audit=this.tryGet(AuditLoggerService);const executionId=audit?audit.generateExecutionId():"";const callDepth=1;let toolCallCount=0;const allowedToolSet=allowedTools?new Set(allowedTools):null;const withheld=await toolsWithheldByAuthorities(this.scope,this.authInfo);const environment={callTool:async(name,toolInput,options)=>{const throwOnError=options?.throwOnError!==false;if(isBlockedSelfReference(name)){audit?.logSecuritySelfReference(executionId,name)}assertNotSelfReference(name);const decision=this.checkToolPolicy(name,callerSurface);if(!decision.allowed){audit?.logSecurityAccessDenied(executionId,name,decision.reason);const error=createToolCallError(TOOL_CALL_ERROR_CODES.ACCESS_DENIED,name,decision.reason);if(throwOnError){throw error}return{success:false,error}}if(allowedToolSet&&!allowedToolSet.has(name)){audit?.logSecurityAccessDenied(executionId,name,"not in the caller-supplied allowedTools list");const error=createToolCallError(TOOL_CALL_ERROR_CODES.ACCESS_DENIED,name);if(throwOnError){throw error}return{success:false,error}}toolCallCount+=1;audit?.logToolCallStart(executionId,name,callDepth);const toolCallStartedAt=Date.now();try{const request={method:"tools/call",params:{name,arguments:toolInput}};const ctx=asCodeCallDispatch({authInfo:this.authInfo,surface:callerSurface});const mcpResult=await this.scope.runFlow("tools:call-tool",{request,ctx});if(!mcpResult){audit?.logToolCallFailure(executionId,name,callDepth,Date.now()-toolCallStartedAt,TOOL_CALL_ERROR_CODES.EXECUTION);const error=createToolCallError(TOOL_CALL_ERROR_CODES.EXECUTION,name,"Flow returned no result");if(throwOnError){throw error}return{success:false,error}}const result=extractResultFromCallToolResult(mcpResult);audit?.logToolCallSuccess(executionId,name,callDepth,Date.now()-toolCallStartedAt);if(throwOnError){return result}return{success:true,data:result}}catch(error){const sanitizedError=toolCallErrorOf(error,name);audit?.logToolCallFailure(executionId,name,callDepth,Date.now()-toolCallStartedAt,sanitizedError.code);if(throwOnError){throw sanitizedError}return{success:false,error:sanitizedError}}},getTool:name=>{try{if(isBlockedSelfReference(name)){audit?.logSecuritySelfReference(executionId,name);return void 0}const introspectionAccess=this.checkToolPolicy(name,callerSurface);if(!introspectionAccess.allowed){audit?.logSecurityAccessDenied(executionId,name,introspectionAccess.reason);return void 0}if(allowedToolSet&&!allowedToolSet.has(name))return void 0;const tool=introspectionAccess.entry;if(withheld.has(tool.fullName)){audit?.logSecurityAccessDenied(executionId,name,"withheld by the tool's authorities");return void 0}return toPlainJson({name:tool.name,description:tool.metadata?.description,inputSchema:tool.getInputJsonSchema?.()??null,outputSchema:tool.getOutputJsonSchema?.()??null})}catch{return void 0}},mcpLog:(level,message,metadata)=>{this.logger?.[level](escapeControlCharacters(String(message)),metadata)},mcpNotify:(event,payload)=>{this.logger?.debug("Notification sent",{event,payload})}};try{const policyConfig=readCodeCallPolicyConfig(this.get(CodeCallConfig));const callableTools=this.scope.tools.getTools(true).filter(tool=>checkCodeCallToolPolicy(toCodeCallPolicyTool(tool,void 0,this.scope),policyConfig).allowed);const{namespaces,skipped}=buildToolNamespaces(callableTools);environment.toolNamespaces=namespaces;if(skipped.length>0){this.logger?.debug?.("codecall: tools skipped during namespace generation",{count:skipped.length,sample:skipped.slice(0,25)})}}catch(error){this.logger?.warn?.("codecall: failed to build tool namespaces",{error:error instanceof Error?error.message:String(error)})}const enclaveService=this.get(EnclaveService);const config=this.get(CodeCallConfig);const startedAt=Date.now();const elapsed=reported=>reported??Date.now()-startedAt;audit?.logExecutionStart(executionId,script);try{const executionResult=await enclaveService.execute(script,environment);const durationMs=elapsed(executionResult.stats?.duration);if(executionResult.timedOut){audit?.logExecutionTimeout(executionId,script,durationMs);return{status:"timeout",error:{message:`Script execution timed out after ${config.getAll().resolvedVm.timeoutMs}ms`}}}if(!executionResult.success){const error=executionResult.error;if(error.code==="SYNTAX_ERROR"){audit?.logExecutionFailure(executionId,script,durationMs,error.message);return{status:"syntax_error",error:{message:toClientErrorMessage(error.message)||"Syntax error in script",...error.location?{location:error.location}:{}}}}if(error.code==="VALIDATION_ERROR"||error.name==="ValidationError"){audit?.logSecurityAstBlocked(executionId,error.blockedPatterns?.join(", ")??"UNKNOWN",error.message);audit?.logExecutionFailure(executionId,script,durationMs,error.message);return{status:"illegal_access",error:{kind:"IllegalBuiltinAccess",message:error.message}}}if(error.toolName){audit?.logExecutionFailure(executionId,script,durationMs,error.message);return{status:"tool_error",error:{source:"tool",toolName:error.toolName,message:toClientErrorMessage(error.message),code:error.code}}}audit?.logExecutionFailure(executionId,script,durationMs,error.message);return{status:"runtime_error",error:{source:"script",message:toClientErrorMessage(error.message),name:error.name}}}audit?.logExecutionSuccess(executionId,script,durationMs,toolCallCount);return{status:"ok",result:executionResult.result,logs:executionResult.logs.length>0?executionResult.logs:void 0}}catch(error){const errorName=error instanceof Error?error.name:"Error";const errorMessage=error instanceof Error?error.message:String(error);audit?.logExecutionFailure(executionId,script,elapsed(),errorMessage);const errorLoc=error.loc;if(errorName==="SyntaxError"||errorMessage?.includes("syntax")){return{status:"syntax_error",error:{message:toClientErrorMessage(errorMessage)||"Syntax error in script",location:errorLoc?{line:errorLoc.line,column:errorLoc.column}:void 0}}}return{status:"runtime_error",error:{source:"script",message:toClientErrorMessage(errorMessage)||"An unexpected error occurred during script execution",name:errorName}}}}};ExecuteTool=__decorateClass([Tool5({name:"codecall:execute",cache:{ttl:0,slideWindow:false},codecall:{enabledInCodeCall:false,visibleInListTools:true},description:executeToolDescription,inputSchema:executeToolInputSchema,outputSchema:executeToolOutputSchema})],ExecuteTool);import{getCallSurface as getCallSurface4,Tool as Tool6,ToolContext as ToolContext6}from"@frontmcp/sdk";import{z as z8}from"@frontmcp/lazy-zod";var invokeToolDescription=`Call ONE tool directly. Returns standard MCP CallToolResult.
99
99
 
100
100
  USE invoke: single tool, no transformation
101
101
  USE execute: multiple tools, loops, filtering, joining
@@ -104,4 +104,4 @@ INPUT: tool (string), input (object matching tool schema)
104
104
  OUTPUT: MCP CallToolResult (same as standard tool call)
105
105
  ERRORS: tool_not_found (\u2192 re-search) | validation_error | execution_error | permission_denied
106
106
 
107
- FLOW: search \u2192 describe \u2192 invoke`;var invokeToolInputSchema={tool:z8.string().describe('The name of the tool to invoke (e.g., "users:getById", "billing:getInvoice"). Must be a tool you discovered via codecall:search.'),input:z8.record(z8.string(),z8.unknown()).describe("The input parameters for the tool. Structure must match the tool's input schema (check codecall:describe for schema details).")};function buildErrorResult(message){return{content:[{type:"text",text:message}],isError:true}}var InvokeTool=class extends ToolContext6{async execute(input){const{tool:toolName,input:toolInput}=input;const audit=this.tryGet(AuditLoggerService);const executionId=audit?audit.generateExecutionId():"";const startedAt=Date.now();if(isBlockedSelfReference(toolName)){audit?.logSecuritySelfReference(executionId,toolName);return buildErrorResult(`Tool "${toolName}" cannot be invoked directly. CodeCall tools are internal and not accessible via codecall:invoke.`)}const surface=getCallSurface4();const decision=checkCodeCallToolAccess(this.scope,this.get(CodeCallConfig),toolName,{directCall:true,surface});if(!decision.allowed){audit?.logSecurityAccessDenied(executionId,toolName,decision.reason);return buildErrorResult(`Tool "${toolName}" is not available. Use codecall:search to discover available tools.`)}const request={method:"tools/call",params:{name:toolName,arguments:toolInput}};const ctx=asCodeCallDispatch({authInfo:this.authInfo,surface});const result=await this.scope.runFlow("tools:call-tool",{request,ctx});if(!result){audit?.logInvoke(executionId,toolName,false,Date.now()-startedAt);return buildErrorResult(`Tool "${toolName}" not found. Use codecall:search to discover available tools.`)}audit?.logInvoke(executionId,toolName,true,Date.now()-startedAt);return result}};InvokeTool=__decorateClass([Tool6({name:"codecall:invoke",cache:{ttl:0,slideWindow:false},codecall:{enabledInCodeCall:false,visibleInListTools:true},description:invokeToolDescription,inputSchema:invokeToolInputSchema})],InvokeTool);function auditLogFields(event){const{executionId,durationMs,data}=event;return durationMs===void 0?{executionId,...data}:{executionId,durationMs,...data}}function callContextOf(flowCtx){const rawInput=flowCtx.rawInput;return typeof rawInput==="object"&&rawInput!==null?rawInput.ctx:void 0}var CodeCallPlugin=class extends DynamicPlugin{options;cachedLogger;getLogger(){if(!this.cachedLogger){this.cachedLogger=this.get(FrontMcpLogger).child("CodeCall")}return this.cachedLogger}constructor(options={}){super();this.options=codeCallPluginOptionsSchema.parse(options)}static dynamicProviders(options){const parsedOptions=codeCallPluginOptionsSchema.parse(options);const config=new CodeCallConfig(parsedOptions);return[{name:"codecall:config",provide:CodeCallConfig,useValue:config},{name:"codecall:enclave",provide:EnclaveService,inject:()=>[CodeCallConfig,ScopeEntry],useFactory:async(cfg,scope)=>{return new EnclaveService(cfg,scope.logger.child("CodeCall:script"))}},{name:"codecall:audit-logger",provide:AuditLoggerService,inject:()=>[ScopeEntry],useFactory:scope=>{const audit=new AuditLoggerService;const logger=scope.logger.child("codecall:audit");audit.subscribe(event=>logger.info(event.type,auditLogFields(event)));return audit}},{name:"codecall:tool-search",provide:ToolSearchService,inject:()=>[ScopeEntry],useFactory:async scope=>{return new ToolSearchService({embeddingOptions:parsedOptions.embedding,defaultTopK:parsedOptions.topK,mode:parsedOptions.mode,includeTools:parsedOptions["includeTools"]},scope)}}]}static dynamicTools(options){const config=new CodeCallConfig(codeCallPluginOptionsSchema.parse(options)).getAll();class ConfiguredSearchTool extends SearchTool{}class ConfiguredExecuteTool extends ExecuteTool{}Reflect.defineMetadata(FrontMcpToolTokens.description,buildSearchToolDescription(config.topK),ConfiguredSearchTool);Reflect.defineMetadata(FrontMcpToolTokens.description,buildExecuteToolDescription(config.resolvedVm),ConfiguredExecuteTool);return[ConfiguredSearchTool,SearchSkillsTool,SearchKnowledgeTool,DescribeTool,ConfiguredExecuteTool,InvokeTool]}async adjustListTools(flowCtx){const logger=this.getLogger();const{resolvedTools}=flowCtx.state;logger.verbose("adjustListTools hook called",{mode:this.options.mode});logger.verbose("adjustListTools: tools before filter",{count:resolvedTools?.length??0});if(!resolvedTools||resolvedTools.length===0){logger.verbose("adjustListTools: no tools to filter, returning early");return}const scope=this.tryGetScope();const filteredTools=resolvedTools.filter(({tool})=>!this.judges(scope,{tool})||this.shouldShowInListTools(tool,this.options.mode));logger.verbose("adjustListTools: tools after filter",{count:filteredTools.length});flowCtx.state.set("resolvedTools",filteredTools)}async refuseDirectCallOfHiddenTool(flowCtx){const{tool}=flowCtx.state;if(!tool||tool.owner?.kind==="scope")return;if(this.isDirectlyCallable(tool))return;if(isInProcessDispatch(callContextOf(flowCtx)))return;this.getLogger().verbose("refused a direct tools/call of a tool CodeCall hides",{tool:tool.fullName});throw new ToolNotFoundError(flowCtx.state.input?.name??tool.name)}isDirectlyCallable(tool){if(!this.managesApp(tool))return true;if(!this.shouldShowInListTools(tool,this.options.mode))return false;if(resolveToolVisibility(tool.metadata)!=="hidden")return true;return this.getCodeCallMetadata(tool)?.visibleInListTools===true}managesApp(tool){const managedAppIds=this.options.appIds;if(this.options.mode!=="codecall_only"||!managedAppIds||managedAppIds.length===0)return true;const toolOwnerAppId=tool.owner?.kind==="app"?tool.owner.id:void 0;return toolOwnerAppId!==void 0&&managedAppIds.includes(toolOwnerAppId)}judges(scope,entry){return!scope?.hooks||isEntryGatedBy(scope,entry,this)}tryGetScope(){try{return this.get(ScopeEntry)}catch{return void 0}}shouldShowInListTools(tool,mode){if(this.isCodeCallTool(tool)){return true}const codecallMeta=this.getCodeCallMetadata(tool);switch(mode){case"codecall_only":return!this.managesApp(tool)||codecallMeta?.visibleInListTools===true;case"codecall_opt_in":case"metadata_driven":return codecallMeta?.visibleInListTools!==false;default:return true}}isCodeCallTool(tool){const name=tool.name||tool.fullName;return typeof name==="string"&&name.startsWith("codecall:")}getCodeCallMetadata(tool){return tool.metadata?.["codecall"]}};__decorateClass([ListToolsHook.Did("resolveConflicts",{priority:1e3})],CodeCallPlugin.prototype,"adjustListTools",1);__decorateClass([ToolHook.Did("findTool",{priority:10,appliesTo:"uncovered-apps"})],CodeCallPlugin.prototype,"refuseDirectCallOfHiddenTool",1);CodeCallPlugin=__decorateClass([Plugin({name:"codecall",description:"CodeCall plugin: AgentScript-based meta-tools for orchestrating MCP tools",providers:[],plugins:[CachePlugin]})],CodeCallPlugin);export{AUDIT_EVENT_TYPES,AuditLoggerService,CodeCallPlugin,codeCallDirectCallsOptionsSchema,codeCallEmbeddingOptionsSchema,codeCallModeSchema,codeCallPluginOptionsSchema,codeCallSidecarOptionsSchema,codeCallVmOptionsSchema,codeCallVmPresetSchema,CodeCallPlugin as default,embeddingStrategySchema,synonymExpansionConfigSchema};
107
+ FLOW: search \u2192 describe \u2192 invoke`;var invokeToolInputSchema={tool:z8.string().describe('The name of the tool to invoke (e.g., "users:getById", "billing:getInvoice"). Must be a tool you discovered via codecall:search.'),input:z8.record(z8.string(),z8.unknown()).describe("The input parameters for the tool. Structure must match the tool's input schema (check codecall:describe for schema details).")};function buildErrorResult(message){return{content:[{type:"text",text:message}],isError:true}}var InvokeTool=class extends ToolContext6{async execute(input){const{tool:toolName,input:toolInput}=input;const audit=this.tryGet(AuditLoggerService);const executionId=audit?audit.generateExecutionId():"";const startedAt=Date.now();if(isBlockedSelfReference(toolName)){audit?.logSecuritySelfReference(executionId,toolName);return buildErrorResult(`Tool "${toolName}" cannot be invoked directly. CodeCall tools are internal and not accessible via codecall:invoke.`)}const surface=getCallSurface4();const decision=checkCodeCallToolAccess(this.scope,this.get(CodeCallConfig),toolName,{directCall:true,surface});if(!decision.allowed){audit?.logSecurityAccessDenied(executionId,toolName,decision.reason);return buildErrorResult(`Tool "${toolName}" is not available. Use codecall:search to discover available tools.`)}const request={method:"tools/call",params:{name:toolName,arguments:toolInput}};const ctx=asCodeCallDispatch({authInfo:this.authInfo,surface});const result=await this.scope.runFlow("tools:call-tool",{request,ctx});if(!result){audit?.logInvoke(executionId,toolName,false,Date.now()-startedAt);return buildErrorResult(`Tool "${toolName}" not found. Use codecall:search to discover available tools.`)}audit?.logInvoke(executionId,toolName,true,Date.now()-startedAt);return result}};InvokeTool=__decorateClass([Tool6({name:"codecall:invoke",cache:{ttl:0,slideWindow:false},codecall:{enabledInCodeCall:false,visibleInListTools:true},description:invokeToolDescription,inputSchema:invokeToolInputSchema})],InvokeTool);function auditLogFields(event){const{executionId,durationMs,data}=event;return durationMs===void 0?{executionId,...data}:{executionId,durationMs,...data}}function callContextOf(flowCtx){const rawInput=flowCtx.rawInput;return typeof rawInput==="object"&&rawInput!==null?rawInput.ctx:void 0}var CodeCallPlugin=class extends DynamicPlugin{options;cachedLogger;getLogger(){if(!this.cachedLogger){this.cachedLogger=this.get(FrontMcpLogger).child("CodeCall")}return this.cachedLogger}constructor(options={}){super();this.options=codeCallPluginOptionsSchema.parse(options)}static dynamicProviders(options){const parsedOptions=codeCallPluginOptionsSchema.parse(options);const config=new CodeCallConfig(parsedOptions);return[{name:"codecall:config",provide:CodeCallConfig,useValue:config},{name:"codecall:enclave",provide:EnclaveService,inject:()=>[CodeCallConfig,ScopeEntry],useFactory:async(cfg,scope)=>{return new EnclaveService(cfg,scope.logger.child("CodeCall:script"))}},{name:"codecall:audit-logger",provide:AuditLoggerService,inject:()=>[ScopeEntry],useFactory:scope=>{const audit=new AuditLoggerService;const logger=scope.logger.child("codecall:audit");audit.subscribe(event=>logger.info(event.type,auditLogFields(event)));return audit}},{name:"codecall:tool-search",provide:ToolSearchService,inject:()=>[ScopeEntry],useFactory:async scope=>{return new ToolSearchService({embeddingOptions:parsedOptions.embedding,defaultTopK:parsedOptions.topK,mode:parsedOptions.mode,includeTools:parsedOptions["includeTools"]},scope)}}]}static dynamicTools(options){const config=new CodeCallConfig(codeCallPluginOptionsSchema.parse(options)).getAll();class ConfiguredSearchTool extends SearchTool{}class ConfiguredExecuteTool extends ExecuteTool{}Reflect.defineMetadata(FrontMcpToolTokens.description,buildSearchToolDescription(config.topK),ConfiguredSearchTool);Reflect.defineMetadata(FrontMcpToolTokens.description,buildExecuteToolDescription(config.resolvedVm),ConfiguredExecuteTool);return[ConfiguredSearchTool,SearchSkillsTool,SearchKnowledgeTool,DescribeTool,ConfiguredExecuteTool,InvokeTool]}async adjustListTools(flowCtx){const logger=this.getLogger();const{resolvedTools}=flowCtx.state;logger.verbose("adjustListTools hook called",{mode:this.options.mode});logger.verbose("adjustListTools: tools before filter",{count:resolvedTools?.length??0});if(!resolvedTools||resolvedTools.length===0){logger.verbose("adjustListTools: no tools to filter, returning early");return}const scope=this.tryGetScope();const filteredTools=resolvedTools.filter(({tool})=>!this.judges(scope,{tool})||this.shouldShowInListTools(tool,this.options.mode));logger.verbose("adjustListTools: tools after filter",{count:filteredTools.length});flowCtx.state.set("resolvedTools",filteredTools)}async refuseDirectCallOfHiddenTool(flowCtx){const{tool}=flowCtx.state;if(!tool||tool.owner?.kind==="scope")return;if(this.isDirectlyCallable(tool))return;if(isInProcessDispatch(callContextOf(flowCtx)))return;this.getLogger().verbose("refused a direct tools/call of a tool CodeCall hides",{tool:tool.fullName});throw new ToolNotFoundError(flowCtx.state.input?.name??tool.name)}isDirectlyCallable(tool){if(!this.managesApp(tool))return true;if(!this.shouldShowInListTools(tool,this.options.mode))return false;if(resolveToolVisibility(tool.metadata)!=="hidden")return true;return this.getCodeCallMetadata(tool)?.visibleInListTools===true}managesApp(tool){const managedAppIds=this.options.appIds;if(this.options.mode!=="codecall_only"||!managedAppIds||managedAppIds.length===0)return true;const toolAppId=codeCallAppIdOf(this.tryGetScope(),tool);return toolAppId!==void 0&&managedAppIds.includes(toolAppId)}judges(scope,entry){return!scope?.hooks||isEntryGatedBy(scope,entry,this)}tryGetScope(){try{return this.get(ScopeEntry)}catch{return void 0}}shouldShowInListTools(tool,mode){if(this.isCodeCallTool(tool)){return true}const codecallMeta=this.getCodeCallMetadata(tool);switch(mode){case"codecall_only":return!this.managesApp(tool)||codecallMeta?.visibleInListTools===true;case"codecall_opt_in":case"metadata_driven":return codecallMeta?.visibleInListTools!==false;default:return true}}isCodeCallTool(tool){const name=tool.name||tool.fullName;return typeof name==="string"&&name.startsWith("codecall:")}getCodeCallMetadata(tool){return tool.metadata?.["codecall"]}};__decorateClass([ListToolsHook.Did("resolveConflicts",{priority:1e3})],CodeCallPlugin.prototype,"adjustListTools",1);__decorateClass([ToolHook.Did("findTool",{priority:10,appliesTo:"uncovered-apps"})],CodeCallPlugin.prototype,"refuseDirectCallOfHiddenTool",1);CodeCallPlugin=__decorateClass([Plugin({name:"codecall",description:"CodeCall plugin: AgentScript-based meta-tools for orchestrating MCP tools",providers:[],plugins:[CachePlugin]})],CodeCallPlugin);export{AUDIT_EVENT_TYPES,AuditLoggerService,CodeCallPlugin,codeCallDirectCallsOptionsSchema,codeCallEmbeddingOptionsSchema,codeCallModeSchema,codeCallPluginOptionsSchema,codeCallSidecarOptionsSchema,codeCallVmOptionsSchema,codeCallVmPresetSchema,CodeCallPlugin as default,embeddingStrategySchema,synonymExpansionConfigSchema};