@frontmcp/sdk 1.10.10 → 1.10.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/browser/common/utils/decide-request-intent.utils.mjs +1 -1
- package/browser/index.cjs +1 -1
- package/esm/index.mjs +1 -1
- package/index.js +1 -1
- package/package.json +10 -10
package/index.js
CHANGED
|
@@ -89,7 +89,7 @@ ${yamlBlock}
|
|
|
89
89
|
---
|
|
90
90
|
|
|
91
91
|
${body}
|
|
92
|
-
`}var yaml3;var init_sep_2640_builders=__esm({"libs/sdk/src/skill/sep-2640/sep-2640.builders.ts"(){"use strict";yaml3=__toESM(require("#js-yaml"));init_sep_2640_constants();init_sep_2640_uri()}});function getSepVisibleSkills(scope){const registry=scope.skills;if(!registry||!registry.hasAny())return[];return registry.getSkills({visibility:"mcp"})}async function getExternalProviderSkills(scope){const registry=scope.skills;if(registry?.getExternalProvider()?.isReadOnly()!==true)return[];const{skills}=await registry.listSkills({limit:Number.MAX_SAFE_INTEGER});return skills.filter(metadata=>!registry.findByName(metadata.name))}async function loadExternalProviderSkill(scope,skillPath){const registry=scope.skills;if(registry?.getExternalProvider()?.isReadOnly()!==true)return void 0;if(skillPath.includes("/")||registry.findByName(skillPath))return void 0;return(await registry.loadSkill(skillPath))?.skill}function findSkillByPath(scope,skillPath){const registry=scope.skills;if(!registry||!registry.hasAny())return void 0;if(typeof skillPath!=="string"||skillPath.length===0)return void 0;const visible=getSepVisibleSkills(scope);const byPath=visible.find(s=>s.getSkillPath()===skillPath);if(byPath)return byPath;const segments=skillPath.split("/").filter(s=>s.length>0);if(segments.length===0)return void 0;const lastSegment=segments[segments.length-1];const byName=visible.find(s=>s.name===lastSegment&&s.getSkillPath()===lastSegment);if(byName)return byName;if(segments.length!==1)return void 0;return visible.find(s=>s.metadata.id===lastSegment&&s.getSkillPath()===s.metadata.name)}async function findAndLoadSkillByPath(scope,skillPath){const registry=scope.skills;if(!registry||!registry.hasAny()){throw new PublicMcpError("Skills are not available in this scope.","CAPABILITY_NOT_AVAILABLE",501)}const entry=findSkillByPath(scope,skillPath);if(!entry||!await isSkillServable(scope,entry)){throw new ResourceNotFoundError(`skill://${skillPath}/SKILL.md`)}const loadResult=await registry.loadSkill(entry.metadata.id??entry.name);if(!loadResult){throw new PublicMcpError(`Failed to load skill at "${skillPath}".`,"INTERNAL_ERROR",500)}return{loadResult,instance:entry}}function isTextMimeType(mimeType){if(mimeType.startsWith("text/"))return true;if(mimeType.startsWith("application/json"))return true;if(mimeType==="application/yaml")return true;if(mimeType==="application/x-sh")return true;if(mimeType==="image/svg+xml")return true;if(mimeType.startsWith("application/javascript"))return true;if(mimeType.startsWith("application/xml"))return true;return false}async function readSkillFileByPath(instance,filePath){if(!filePath||filePath.toLowerCase()==="skill.md"){throw new ResourceNotFoundError(`skill://${instance.getSkillPath()}/${filePath}`)}const rawSegments=filePath.split("/").filter(s=>s.length>0);const segments=[];for(const raw of rawSegments){let decoded;try{decoded=decodeURIComponent(raw)}catch{throw new PublicMcpError(`Invalid file path "${filePath}".`,"INVALID_PARAMS",400)}if(decoded.includes("/")||decoded.includes("\\")){throw new PublicMcpError(`Invalid file path "${filePath}".`,"INVALID_PARAMS",400)}if(decoded===".."||decoded==="."){throw new PublicMcpError(`Invalid file path "${filePath}".`,"INVALID_PARAMS",400)}if(decoded.toLowerCase()==="skill.md"){throw new ResourceNotFoundError(`skill://${instance.getSkillPath()}/${filePath}`)}segments.push(decoded)}if(segments[0]==="references"||segments[0]==="examples"){const tail=segments.slice(1).join("/");const resolved=await tryResolvedSubFile(instance,segments[0],tail);if(resolved!==void 0){return{kind:"text",content:resolved,mimeType:guessMimeType(filePath)}}}const baseDir=instance.getBaseDir();if(!baseDir){throw new ResourceNotFoundError(`skill://${instance.getSkillPath()}/${filePath}`)}const resources=instance.getResources();const candidateDirs=[["references",resources?.references],["examples",resources?.examples],["scripts",resources?.scripts],["assets",resources?.assets]];let candidatePath;for(const[subdir,configured]of candidateDirs){if(segments[0]!==subdir)continue;const dir=configured?(0,import_utils82.isAbsolute)(configured)?configured:(0,import_utils82.pathResolve)(baseDir,configured):(0,import_utils82.joinPath)(baseDir,subdir);candidatePath=(0,import_utils82.pathResolve)(dir,...segments.slice(1));if(!isInside(candidatePath,dir)){throw new PublicMcpError(`Invalid file path "${filePath}".`,"INVALID_PARAMS",400)}break}if(!candidatePath){candidatePath=(0,import_utils82.pathResolve)(baseDir,...segments);if(!isInside(candidatePath,baseDir)){throw new PublicMcpError(`Invalid file path "${filePath}".`,"INVALID_PARAMS",400)}}const mimeType=guessMimeType(filePath);let buffer;try{buffer=await(0,import_utils82.readFileBuffer)(candidatePath)}catch(err){if(isFileMissingError(err)){throw new ResourceNotFoundError(`skill://${instance.getSkillPath()}/${filePath}`)}throw err}if(!isTextMimeType(mimeType)){const buf2=Buffer.isBuffer(buffer)?buffer:Buffer.from(buffer);return{kind:"blob",blob:buf2.toString("base64"),mimeType}}const buf=Buffer.isBuffer(buffer)?buffer:Buffer.from(buffer);const content=buf.toString("utf-8");const isMarkdown=filePath.endsWith(".md")||filePath.endsWith(".markdown");const body=isMarkdown?parseSkillMdFrontmatter(content).body:content;return{kind:"text",content:body,mimeType}}async function tryResolvedSubFile(instance,kind,tail){if(!tail)return void 0;let content;try{content=await instance.load()}catch(err){if(!instance.getBaseDir()){throw err}return void 0}const entries=kind==="references"?content.resolvedReferences??[]:content.resolvedExamples??[];const tailNoExt=tail.replace(/\.(md|markdown)$/i,"");for(const entry of entries){const filename=entry.filename;const name48=entry.name;const matches=filename!==void 0&&(filename===tail||filename===tailNoExt)||name48!==void 0&&(name48===tail||name48===tailNoExt);if(!matches)continue;const inline=entry.content;if(inline!==void 0){return parseSkillMdFrontmatter(inline).body}const absolutePath=entry.path;const resolvedPath=resolveEntryPath2(instance,kind,absolutePath,filename);if(!resolvedPath)continue;try{const buf=await(0,import_utils82.readFileBuffer)(resolvedPath);const text=(Buffer.isBuffer(buf)?buf:Buffer.from(buf)).toString("utf-8");return parseSkillMdFrontmatter(text).body}catch(err){if(isFileMissingError(err)){continue}throw err}}return void 0}function resolveEntryPath2(instance,kind,absolutePath,filename){if(absolutePath&&(0,import_utils82.isAbsolute)(absolutePath))return absolutePath;if(!filename)return void 0;const baseDir=instance.getBaseDir();const configured=instance.getResources()?.[kind];let dir;if(configured&&(0,import_utils82.isAbsolute)(configured)){dir=configured}else if(baseDir){dir=configured?(0,import_utils82.pathResolve)(baseDir,configured):(0,import_utils82.joinPath)(baseDir,kind)}if(!dir)return void 0;const resolved=(0,import_utils82.pathResolve)(dir,filename);if(!isInside(resolved,dir))return void 0;return resolved}function isFileMissingError(err){if(typeof err!=="object"||err===null)return false;const code=err.code;return code==="ENOENT"||code==="ENOTDIR"}function guessMimeType(filePath){const lower=filePath.toLowerCase();if(lower.endsWith(".md")||lower.endsWith(".markdown"))return"text/markdown";if(lower.endsWith(".json"))return"application/json";if(lower.endsWith(".yaml")||lower.endsWith(".yml"))return"application/yaml";if(lower.endsWith(".txt"))return"text/plain";if(lower.endsWith(".py"))return"text/x-python";if(lower.endsWith(".js"))return"text/javascript";if(lower.endsWith(".ts"))return"text/x-typescript";if(lower.endsWith(".sh"))return"application/x-sh";if(lower.endsWith(".html"))return"text/html";if(lower.endsWith(".css"))return"text/css";if(lower.endsWith(".svg"))return"image/svg+xml";if(lower.endsWith(".png"))return"image/png";if(lower.endsWith(".jpg")||lower.endsWith(".jpeg"))return"image/jpeg";return"application/octet-stream"}function isInside(child,parent){const normChild=child.replace(/\\/g,"/");const normParent=parent.replace(/\\/g,"/");const parentPrefix=normParent.endsWith("/")?normParent:`${normParent}/`;return normChild===normParent||normChild.startsWith(parentPrefix)}var import_utils82;var init_sep_2640_resource_helpers=__esm({"libs/sdk/src/skill/sep-2640/sep-2640.resource-helpers.ts"(){"use strict";import_utils82=require("@frontmcp/utils");init_errors();init_skill_filter_helper();init_skill_md_parser()}});var sep_2640_per_skill_exports={};__export(sep_2640_per_skill_exports,{buildPerSkillResourceRecord:()=>buildPerSkillResourceRecord,registerPerSkillResources:()=>registerPerSkillResources});function skillExtensionMetadata(skill){const extensions={};for(const[key,value]of Object.entries(skill.metadata)){if(value===void 0||key in FrontMcpSkillTokens||key in FrontMcpResourceTokens)continue;extensions[key]=value}return extensions}function buildPerSkillResourceRecord(scope,skill,opts={}){const skillPathSegments=skill.getSkillPathSegments();const skillPath=skillPathSegments.join("/");const uri=buildSkillUri(skillPathSegments,"SKILL.md");const annotations={audience:["assistant"],priority:SKILL_MD_PRIORITY};if(opts.lastModified){annotations.lastModified=opts.lastModified}const meta={[`${SEP_2640_META_NAMESPACE}path`]:skillPath};const metadata={...skillExtensionMetadata(skill),uri,name:skill.metadata.name,description:skill.getDescription(),mimeType:SKILL_MD_MIME_TYPE,annotations,_meta:meta,...skill.metadata.availableWhen!==void 0&&{availableWhen:skill.metadata.availableWhen}};const handler=async()=>{const{loadResult}=await findAndLoadSkillByPath(scope,skillPath);return{contents:[{uri,mimeType:SKILL_MD_MIME_TYPE,text:serializeSkillMd(loadResult.skill)}]}};return{kind:"FUNCTION",provide:handler,metadata}}async function registerPerSkillResources(options){const{scope,skillRegistry,resourceRegistry,logger,resolveLastModified}=options;const registered=new Map;const register=skill=>{try{const record=buildPerSkillResourceRecord(scope,skill);resourceRegistry.registerDynamicResource(record);registered.set(skill.getSkillPath(),{token:record.provide,metadata:record.metadata,extensionKeys:Object.keys(skillExtensionMetadata(skill))});logger.verbose(`Registered SEP-2640 per-skill resource: ${record.metadata.uri}`);return resolveLastModified?addLastModified(record.metadata,skill,resolveLastModified,logger):Promise.resolve()}catch(err){logger.warn(`Failed to register SEP-2640 per-skill resource for "${skill.name}": ${err instanceof Error?err.message:String(err)}`);return Promise.resolve()}};const reconcile=()=>{const served=servedSkillsByPath(skillRegistry);for(const[skillPath,resource]of registered){if(served.has(skillPath))continue;resourceRegistry.unregisterResourceInstance(resource.token);registered.delete(skillPath)}const lastModifiedUpdates=[];for(const[skillPath,skill]of served){const resource=registered.get(skillPath);if(resource)refreshFromSkill(resource,skill);else lastModifiedUpdates.push(register(skill))}return lastModifiedUpdates};await Promise.all(reconcile());const unsubscribe=skillRegistry.subscribe({immediate:false},()=>{reconcile()});scope.onDispose(unsubscribe)}async function addLastModified(metadata,skill,resolveLastModified,logger){try{const lastModified=await resolveLastModified(skill);if(lastModified&&metadata.annotations)metadata.annotations.lastModified=lastModified}catch(err){logger.warn(`Failed to resolve SEP-2640 lastModified for "${skill.name}": ${err instanceof Error?err.message:String(err)}`)}}function servedSkillsByPath(skillRegistry){const served=new Map;for(const skill of skillRegistry.getSkills({visibility:"mcp"})){const skillPath=skill.getSkillPath();if(!served.has(skillPath))served.set(skillPath,skill)}return served}function refreshFromSkill(resource,skill){const extensions=skillExtensionMetadata(skill);for(const key of resource.extensionKeys){if(!(key in extensions))Reflect.deleteProperty(resource.metadata,key)}Object.assign(resource.metadata,extensions);resource.metadata["description"]=skill.getDescription();if(skill.metadata.availableWhen===void 0)Reflect.deleteProperty(resource.metadata,"availableWhen");else resource.metadata["availableWhen"]=skill.metadata.availableWhen;resource.extensionKeys=Object.keys(extensions)}var init_sep_2640_per_skill=__esm({"libs/sdk/src/skill/sep-2640/sep-2640.per-skill.ts"(){"use strict";init_common();init_sep_2640_builders();init_sep_2640_constants();init_sep_2640_resource_helpers();init_sep_2640_uri()}});var sep_2640_last_modified_exports={};__export(sep_2640_last_modified_exports,{resolveLastModifiedForSkill:()=>resolveLastModifiedForSkill});async function resolveLastModifiedForSkill(skill){const record=skill.record;if(!record||record.kind!=="FILE"||!record.filePath){return void 0}try{const s=await(0,import_utils83.stat)(record.filePath);return s.mtime instanceof Date?s.mtime.toISOString():void 0}catch{return void 0}}var import_utils83;var init_sep_2640_last_modified=__esm({"libs/sdk/src/skill/sep-2640/sep-2640.last-modified.ts"(){"use strict";import_utils83=require("@frontmcp/utils")}});var init_base_interface=__esm({"libs/sdk/src/common/interfaces/base.interface.ts"(){"use strict"}});var init_front_mcp_interface=__esm({"libs/sdk/src/common/interfaces/front-mcp.interface.ts"(){"use strict"}});var import_protocol49,ServerRequest,ServerResponse,FrontMcpServer;var init_server_interface=__esm({"libs/sdk/src/common/interfaces/server.interface.ts"(){"use strict";import_protocol49=require("@frontmcp/protocol");ServerRequest=class extends import_protocol49.IncomingMessage{path;query;params;body;authSession};ServerResponse=class extends import_protocol49.HttpServerResponse{};FrontMcpServer=class{async stop(){return}}}});var init_scope_interface=__esm({"libs/sdk/src/common/interfaces/scope.interface.ts"(){"use strict"}});var init_hook_interface=__esm({"libs/sdk/src/common/interfaces/hook.interface.ts"(){"use strict"}});var init_app_interface=__esm({"libs/sdk/src/common/interfaces/app.interface.ts"(){"use strict"}});function AsyncAuthProvider(cfg){return cfg}var init_auth_provider_interface=__esm({"libs/sdk/src/common/interfaces/auth-provider.interface.ts"(){"use strict"}});var init_adapter_interface=__esm({"libs/sdk/src/common/interfaces/adapter.interface.ts"(){"use strict"}});var init_plugin_interface=__esm({"libs/sdk/src/common/interfaces/plugin.interface.ts"(){"use strict"}});var ToolContext;var init_tool_interface=__esm({"libs/sdk/src/common/interfaces/tool.interface.ts"(){"use strict";init_helpers();init_execution_context_interface();init_flow_interface();ToolContext=class extends ExecutionContextBase{toolId;toolName;metadata;_toolNameInternal;_toolInputInternal;_jsonRpcRequestIdInternal;_rawInput;_input;_outputDraft;_output;_inputHistory=[];_outputHistory=[];_progressToken;signal;constructor(args){const{metadata,input,providers,logger,progressToken,signal}=args;super({providers,logger:logger.child(`tool:${metadata.id??metadata.name}`),authInfo:args.authInfo});this.toolName=metadata.name;this.toolId=metadata.id??metadata.name;this.metadata=metadata;this._input=input;this._progressToken=progressToken;this.signal=signal}get _progressTokenInternal(){return this._progressToken}fetch(input,init){const context=this.fetchContext(init);if(context&&this.signal)return context.fetch(input,init,this.signal);return super.fetch(input,init)}get input(){return this._input}set input(v){this._input=v;this._inputHistory.push({at:Date.now(),stage:this.activeStage,value:v})}get inputHistory(){return this._inputHistory}get output(){return this._output}set output(v){this._output=v;this._outputHistory.push({at:Date.now(),stage:this.activeStage,value:v})}get outputHistory(){return this._outputHistory}respond(value){this.output=value;FlowControl.respond(value)}async notify(message,level="info"){const data=typeof message==="string"?{message}:message;const sink=this.tryGetContext()?.getRequestNotificationSink?.();if(sink)return sink.log(level,this.toolName,data);const sessionId=this.authInfo.sessionId;if(!sessionId){this.logger.warn("Cannot send notification: no session ID");return false}return this.scope.notifications.sendLogMessageToSession(sessionId,level,this.toolName,data)}async progress(progress,total,message){const sink=this.tryGetContext()?.getRequestNotificationSink?.();if(sink)return sink.progress(progress,total,message);if(!this._progressToken){this.logger.debug("Cannot send progress: no progressToken in request");return false}const sessionId=this.authInfo.sessionId;if(!sessionId){this.logger.warn("Cannot send progress: no session ID");return false}return this.scope.notifications.sendProgressNotification(sessionId,this._progressToken,progress,total,message)}notifyResourceUpdated(uri){this.scope.resources.notifyContentChanged(uri)}notifyResourceListChanged(){this.scope.notifications.broadcastNotification("notifications/resources/list_changed")}async elicit(message,requestedSchema,options){return performElicit({sessionId:this.context.sessionId,getClientCapabilities:sid=>this.scope.notifications.getClientCapabilities(sid),tryGetContext:()=>this.tryGetContext(),entryName:this._toolNameInternal??this.toolName,entryInput:this._toolInputInternal??this.input,elicitationEnabled:this.scope.metadata.elicitation?.enabled===true},message,requestedSchema,options)}async sample(options){return performSample(this.tryGetContext(),options)}async listRoots(){return performListRoots(this.tryGetContext())}get platform(){const payloadPlatform=this.authInfo.sessionIdPayload?.platformType;if(payloadPlatform&&payloadPlatform!=="unknown"){return payloadPlatform}const requestPlatform=this.tryGetContext()?.platformType;if(requestPlatform&&requestPlatform!=="unknown"){return requestPlatform}const sessionId=this.authInfo.sessionId;if(!sessionId){return"unknown"}return this.scope.notifications.getPlatformType(sessionId)}get clientInfo(){const requestClientInfo=this.tryGetContext()?.clientInfo;if(requestClientInfo){return requestClientInfo}const sessionId=this.authInfo.sessionId;if(!sessionId){return void 0}return this.scope.notifications.getClientInfo(sessionId)}}}});var ResourceContext;var init_resource_interface=__esm({"libs/sdk/src/common/interfaces/resource.interface.ts"(){"use strict";init_execution_context_interface();init_flow_interface();ResourceContext=class extends ExecutionContextBase{resourceId;resourceName;metadata;uri;params;_output;_outputHistory=[];constructor(args){const{metadata,uri,params,providers,logger}=args;super({providers,logger:logger.child(`resource:${metadata.name}`),authInfo:args.authInfo});this.resourceName=metadata.name;this.resourceId=metadata.name;this.metadata=metadata;this.uri=uri;this.params=params}getArgumentCompleter(_argName){return null}get output(){return this._output}set output(v){this._output=v;this._outputHistory.push({at:Date.now(),stage:this.activeStage,value:v})}get outputHistory(){return this._outputHistory}notifyUpdated(uri){const targetUri=uri??this.uri;this.scope.resources.notifyContentChanged(targetUri)}respond(value){this.output=value;FlowControl.respond(value)}}}});var PromptContext;var init_prompt_interface=__esm({"libs/sdk/src/common/interfaces/prompt.interface.ts"(){"use strict";init_execution_context_interface();init_flow_interface();PromptContext=class extends ExecutionContextBase{promptId;promptName;metadata;args;_output;_outputHistory=[];constructor(ctorArgs){const{metadata,args,providers,logger,authInfo}=ctorArgs;super({providers,logger:logger.child(`prompt:${metadata.name}`),authInfo});this.promptName=metadata.name;this.promptId=metadata.name;this.metadata=metadata;this.args=args}get authInfo(){return super.authInfo}get output(){return this._output}set output(v){this._output=v;this._outputHistory.push({at:Date.now(),stage:this.activeStage,value:v})}get outputHistory(){return this._outputHistory}respond(value){this.output=value;FlowControl.respond(value)}get error(){return super.error}}}});var LogTransportInterface,FrontMcpLogger;var init_logger_interface=__esm({"libs/sdk/src/common/interfaces/logger.interface.ts"(){"use strict";LogTransportInterface=class{};FrontMcpLogger=class{}}});function definedFields(toolCall){return Object.fromEntries(Object.entries(toolCall).filter(([,value])=>value!==void 0))}var AgentExecutionLoop,AgentMaxIterationsError;var init_agent_execution_loop=__esm({"libs/sdk/src/agent/agent-execution-loop.ts"(){"use strict";init_common();AgentExecutionLoop=class{config;constructor(config){this.config={maxIterations:10,timeout:12e4,...config}}async run(userMessage,toolExecutor,existingMessages=[]){const startTime=Date.now();const messages=[...existingMessages,{role:"user",content:userMessage}];let iterations=0;let totalPromptTokens=0;let totalCompletionTokens=0;let timeout;try{const timeoutPromise=new Promise((_,reject)=>{timeout=setTimeout(()=>reject(new Error(`Agent execution timed out after ${this.config.timeout}ms`)),this.config.timeout)});const result=await Promise.race([this.executeLoop(messages,toolExecutor,{onIteration:(iter,msg)=>{iterations=iter;this.config.onIteration?.(iter,msg)},onUsage:(prompt,completion)=>{totalPromptTokens+=prompt;totalCompletionTokens+=completion}}),timeoutPromise]);return{content:result.content,messages,iterations,usage:{promptTokens:totalPromptTokens,completionTokens:totalCompletionTokens,totalTokens:totalPromptTokens+totalCompletionTokens},success:true,durationMs:Date.now()-startTime}}catch(error){return{content:null,messages,iterations,usage:{promptTokens:totalPromptTokens,completionTokens:totalCompletionTokens,totalTokens:totalPromptTokens+totalCompletionTokens},success:false,error,durationMs:Date.now()-startTime}}finally{clearTimeout(timeout)}}async*runStreaming(userMessage,toolExecutor,existingMessages=[]){const startTime=Date.now();const deadline=startTime+this.config.timeout;const messages=[...existingMessages,{role:"user",content:userMessage}];let iterations=0;let totalPromptTokens=0;let totalCompletionTokens=0;const result=(content,error)=>({content,messages,iterations,usage:{promptTokens:totalPromptTokens,completionTokens:totalCompletionTokens,totalTokens:totalPromptTokens+totalCompletionTokens},success:error===void 0,...error&&{error},durationMs:Date.now()-startTime});const events=this.executeLoopStreaming(messages,toolExecutor);try{for(;;){const step=await this.beforeDeadline(events.next(),deadline);if(step.done){const done=result(step.value.content);yield{type:"done",result:done};return done}const event=step.value;if(event.type==="iteration")iterations=event.iteration;if(event.type==="usage"){totalPromptTokens+=event.promptTokens;totalCompletionTokens+=event.completionTokens}yield event}}catch(caught){void events.return({content:null}).catch(()=>void 0);const error=caught;const failed=result(null,error);yield{type:"error",error};yield{type:"done",result:failed};return failed}}async beforeDeadline(step,deadline){let timer;const timeout=new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(`Agent execution timed out after ${this.config.timeout}ms`)),Math.max(0,deadline-Date.now()))});try{return await Promise.race([step,timeout])}finally{clearTimeout(timer)}}async executeLoop(messages,toolExecutor,callbacks){for(let iteration=1;iteration<=this.config.maxIterations;iteration++){this.config.logger?.debug(`Agent loop iteration ${iteration}/${this.config.maxIterations}`);this.config.onLlmStart?.(iteration,this.config.maxIterations);const prompt={system:this.config.systemInstructions,messages};const completion=await this.config.adapter.completion(prompt,this.config.tools.length>0?this.config.tools:void 0,this.config.completionOptions);this.config.onLlmComplete?.(iteration,completion.usage);if(completion.usage){callbacks.onUsage(completion.usage.promptTokens,completion.usage.completionTokens)}if(completion.finishReason==="tool_calls"&&completion.toolCalls?.length){this.config.onToolsIdentified?.(completion.toolCalls.length,completion.toolCalls.map(tc=>tc.name));const assistantMessage={role:"assistant",content:completion.content,toolCalls:completion.toolCalls};messages.push(assistantMessage);callbacks.onIteration(iteration,assistantMessage);const totalTools=completion.toolCalls.length;for(let toolIndex=0;toolIndex<totalTools;toolIndex++){const toolCall=completion.toolCalls[toolIndex];this.config.onToolStart?.(toolCall,toolIndex,totalTools);this.config.onToolCall?.(toolCall);let result;let error2;try{result=await toolExecutor(toolCall.name,toolCall.arguments)}catch(e){error2=e;result={error:error2.message}}this.config.onToolResult?.(toolCall,result,error2);const toolMessage={role:"tool",content:typeof result==="string"?result:JSON.stringify(result),toolCallId:toolCall.id,name:toolCall.name};messages.push(toolMessage)}}else{const assistantMessage={role:"assistant",content:completion.content};messages.push(assistantMessage);callbacks.onIteration(iteration,assistantMessage);this.config.onContent?.(completion.content??"");this.config.onComplete?.(completion.content,void 0);return{content:completion.content}}}const error=new AgentMaxIterationsError(`Agent reached maximum iterations (${this.config.maxIterations}) without completing`,this.config.maxIterations);this.config.onComplete?.(null,error);throw error}async*executeLoopStreaming(messages,toolExecutor){for(let iteration=1;iteration<=this.config.maxIterations;iteration++){this.config.logger?.debug(`Agent loop iteration ${iteration}/${this.config.maxIterations}`);this.config.onLlmStart?.(iteration,this.config.maxIterations);yield{type:"iteration",iteration};const prompt={system:this.config.systemInstructions,messages};const completion=yield*this.streamCompletion(prompt);this.config.onLlmComplete?.(iteration,completion.usage);if(completion.finishReason==="tool_calls"&&completion.toolCalls?.length){const toolCalls=completion.toolCalls;this.config.onToolsIdentified?.(toolCalls.length,toolCalls.map(tc=>tc.name));const assistantMessage={role:"assistant",content:completion.content,toolCalls};messages.push(assistantMessage);this.config.onIteration?.(iteration,assistantMessage);const totalTools=toolCalls.length;for(let toolIndex=0;toolIndex<totalTools;toolIndex++){const toolCall=toolCalls[toolIndex];this.config.onToolStart?.(toolCall,toolIndex,totalTools);this.config.onToolCall?.(toolCall);yield{type:"tool_start",toolCall};let result;let error2;try{result=await toolExecutor(toolCall.name,toolCall.arguments)}catch(e){error2=e;result={error:error2.message}}this.config.onToolResult?.(toolCall,result,error2);yield{type:"tool_end",toolCall,result,error:error2};const toolMessage={role:"tool",content:typeof result==="string"?result:JSON.stringify(result),toolCallId:toolCall.id,name:toolCall.name};messages.push(toolMessage)}}else{const assistantMessage={role:"assistant",content:completion.content};messages.push(assistantMessage);this.config.onIteration?.(iteration,assistantMessage);this.config.onComplete?.(completion.content,void 0);return{content:completion.content}}}const error=new AgentMaxIterationsError(`Agent reached maximum iterations (${this.config.maxIterations}) without completing`,this.config.maxIterations);this.config.onComplete?.(null,error);throw error}async*streamCompletion(prompt){const adapter=this.config.adapter;const tools=this.config.tools.length>0?this.config.tools:void 0;let streamedText="";let completion;if(supportsStreaming(adapter)){const announced=new Map;let done;for await(const chunk of adapter.streamCompletion(prompt,tools,this.config.completionOptions)){if(chunk.type==="content"&&chunk.content){streamedText+=chunk.content;yield{type:"content",content:chunk.content};this.config.onContent?.(chunk.content)}else if(chunk.type==="tool_call"&&chunk.toolCall){announced.set(chunk.toolCall.id,{...announced.get(chunk.toolCall.id),...definedFields(chunk.toolCall)});yield{type:"tool_call",toolCall:chunk.toolCall}}else if(chunk.type==="done"&&chunk.completion){done=chunk.completion}}const toolCalls=done?.toolCalls??[...announced.values()].map(call=>({id:call.id,name:call.name??"",arguments:call.arguments??{}}));completion={content:streamedText||(done?.content??null),finishReason:done?.finishReason??(toolCalls.length>0?"tool_calls":"stop"),...toolCalls.length>0&&{toolCalls},...done?.usage&&{usage:done.usage}}}else{completion=await adapter.completion(prompt,tools,this.config.completionOptions)}if(!streamedText&&completion.content){yield{type:"content",content:completion.content};this.config.onContent?.(completion.content)}if(completion.usage){yield{type:"usage",promptTokens:completion.usage.promptTokens,completionTokens:completion.usage.completionTokens}}return completion}};AgentMaxIterationsError=class extends Error{constructor(message,maxIterations){super(message);this.maxIterations=maxIterations;this.name="AgentMaxIterationsError"}maxIterations}}});var AgentContext;var init_agent_interface=__esm({"libs/sdk/src/common/interfaces/agent.interface.ts"(){"use strict";init_agent_execution_loop();init_frontmcp_context_storage();init_helpers();init_errors();init_tool_lookup_utils();init_execution_context_interface();init_flow_interface();AgentContext=class _AgentContext extends ExecutionContextBase{agentId;agentName;metadata;llmAdapter;agentScope;systemInstructions;toolDefinitions;toolExecutor;agentInvoker;privateScope;_agentNameInternal;_agentInputInternal;_rawInput;_input;_outputDraft;_output;_inputHistory=[];_outputHistory=[];_progressToken;constructor(args){const{metadata,input,providers,logger,llmAdapter,agentScope,toolDefinitions,toolExecutor,agentInvoker,privateScope,progressToken}=args;super({providers,logger:logger.child(`agent:${metadata.id??metadata.name}`),authInfo:args.authInfo});this.agentName=metadata.name;this.agentId=metadata.id??metadata.name;this.metadata=metadata;this._input=input;this.llmAdapter=llmAdapter;this.agentScope=agentScope;this.systemInstructions=metadata.systemInstructions??"";this.toolDefinitions=toolDefinitions??[];this.toolExecutor=toolExecutor;this.agentInvoker=agentInvoker;this.privateScope=privateScope;this._progressToken=progressToken}async execute(input){return this.runAgentLoop(input)}async runAgentLoop(input){const userMessage=this.buildUserMessage(input);const streaming=this.streamsReplies();const enableAutoProgress=this.metadata.execution?.enableAutoProgress===true&&this.metadata.execution?.enableNotifications!==false;const maxIterations=this.metadata.execution?.maxIterations??10;const notificationInterval=this.metadata.execution?.notificationInterval??1e3;const iterationShare=80/maxIterations;let iterationStart=0;let lastSentProgress=-1;let lastAutoProgressAt;const autoProgress=(progress,message,isFinal=false)=>{if(streaming)return;const now=Date.now();if(progress<=lastSentProgress)return;if(!isFinal&&lastAutoProgressAt!==void 0&&now-lastAutoProgressAt<notificationInterval)return;lastAutoProgressAt=now;lastSentProgress=progress;void this.progress(progress,100,message)};const loop=new AgentExecutionLoop({adapter:{completion:(prompt,tools,options)=>this.completion(prompt,tools,options),...streaming&&{streamCompletion:(prompt,tools,options)=>this.streamCompletion(prompt,tools,options)}},systemInstructions:this.systemInstructions,tools:this.toolDefinitions,maxIterations,timeout:this.metadata.execution?.timeout??12e4,logger:this.logger,completionOptions:this.completionOptions(),onLlmStart:enableAutoProgress?(iteration,maxIter)=>{iterationStart=(iteration-1)*iterationShare;autoProgress(Math.round(iterationStart),`Starting LLM call (iteration ${iteration}/${maxIter})`)}:void 0,onLlmComplete:enableAutoProgress?(iteration,usage)=>{const usageStr=usage?` (${usage.promptTokens??0}P + ${usage.completionTokens??0}C tokens)`:"";autoProgress(Math.round(iterationStart+iterationShare/2),`LLM response received${usageStr}`)}:void 0,onToolsIdentified:enableAutoProgress?(count,names)=>{this.notify(`Identified ${count} tool call(s): ${names.join(", ")}`,"info")}:void 0,onToolStart:enableAutoProgress?(toolCall,index,total)=>{const toolsDone=(index+1)/(total+1);const toolProgress=iterationStart+iterationShare/2*(1+toolsDone);autoProgress(Math.round(toolProgress),`Executing tool ${index+1}/${total}: ${toolCall.name}`)}:void 0,onComplete:enableAutoProgress?(content,error)=>{autoProgress(100,error?`Agent failed: ${toMcpError(error).getPublicMessage()}`:"Agent completed",true)}:void 0,onToolCall:toolCall=>{if(this.metadata.execution?.enableNotifications!==false){this.notify(`Calling tool: ${toolCall.name}`,"info")}this.logger.debug(`Tool call: ${toolCall.name}`,{args:toolCall.arguments})},onToolResult:(toolCall,result2,error)=>{if(error){const reported=toMcpError(error);if(this.metadata.execution?.enableNotifications!==false){this.notify(`Tool ${toolCall.name} failed: ${reported.getPublicMessage()}`,"error")}this.logger.error(`Tool ${toolCall.name} failed (${reported.errorId})`,error)}else{this.logger.debug(`Tool ${toolCall.name} completed`,{result:result2})}},onContent:content=>{if(this.metadata.execution?.enableNotifications!==false){this.logger.debug(`Content received: ${content.slice(0,100)}...`)}}});const executor=async(name48,args)=>this.executeTool(name48,args);const result=streaming?await this.streamAgentLoop(loop.runStreaming(userMessage,executor)):await loop.run(userMessage,executor);if(!result.success&&result.error){throw result.error}return this.parseAgentResponse(result.content)}streamsReplies(){if(this.metadata.execution?.enableStreaming!==true||this._progressToken===void 0)return false;const overridesCompletion=this.completion!==_AgentContext.prototype.completion;const overridesStreamCompletion=this.streamCompletion!==_AgentContext.prototype.streamCompletion;return overridesStreamCompletion||!overridesCompletion&&typeof this.llmAdapter.streamCompletion==="function"}async streamAgentLoop(events){let chunks=0;for(let step=await events.next();;step=await events.next()){if(step.done)return step.value;const event=step.value;if(event.type==="content"&&event.content){chunks+=1;await this.progress(chunks,void 0,event.content)}}}completionOptions(){const llm=this.metadata.llm;return{...llm?.temperature!==void 0&&{temperature:llm.temperature},...llm?.maxTokens!==void 0&&{maxTokens:llm.maxTokens}}}buildUserMessage(input){if(typeof input==="string"){return input}const inputObj=input;if(inputObj["query"])return String(inputObj["query"]);if(inputObj["message"])return String(inputObj["message"]);if(inputObj["prompt"])return String(inputObj["prompt"]);if(inputObj["input"])return String(inputObj["input"]);return JSON.stringify(input)}parseAgentResponse(content){if(content===null){return{response:""}}if(content.trim().startsWith("{")||content.trim().startsWith("[")){try{return JSON.parse(content)}catch{}}return{response:content}}get input(){return this._input}set input(v){this._input=v;this._inputHistory.push({at:Date.now(),stage:this.activeStage,value:v})}get inputHistory(){return this._inputHistory}get output(){return this._output}set output(v){this._output=v;this._outputHistory.push({at:Date.now(),stage:this.activeStage,value:v})}get outputHistory(){return this._outputHistory}async completion(prompt,tools,options){return this.llmAdapter.completion(prompt,tools,options)}async*streamCompletion(prompt,tools,options){if(!this.llmAdapter.streamCompletion){const result=await this.completion(prompt,tools,options);yield{type:"done",completion:result};return}yield*this.llmAdapter.streamCompletion(prompt,tools,options)}async executeTool(name48,args){if(!this.toolExecutor){throw new AgentMethodNotAvailableError("executeTool",this.agentName)}return this.toolExecutor(name48,args)}async invokeAgent(agentId,input){if(!this.agentInvoker){throw new AgentMethodNotAvailableError("invokeAgent",this.agentName)}return this.agentInvoker(agentId,input)}callToolSurface(){return"agent"}callToolScope(name48){const privateScope=this.privateScope;const isPrivateTool=privateScope&&lookupTool(privateScope,name48);return isPrivateTool?privateScope:super.callToolScope(name48)}async notify(message,level="info"){const logMessage=typeof message==="string"?message:JSON.stringify(message);if(level==="error"){this.logger.error(logMessage)}else if(level==="warning"){this.logger.warn(logMessage)}else{this.logger.info(logMessage)}const data=typeof message==="string"?{message}:message;const sink=this.requestNotificationSink();if(sink)return sink.log(level,this.agentName,data);const sessionId=this.authInfo.sessionId;if(!sessionId){return false}return this.scope.notifications.sendLogMessageToSession(sessionId,level,this.agentName,data)}async progress(progress,total,message){const sink=this.requestNotificationSink();if(sink)return sink.progress(progress,total,message);if(this._progressToken===void 0){this.logger.debug("Cannot send progress: no progressToken in request");return false}const sessionId=this.authInfo.sessionId;if(!sessionId){this.logger.warn("Cannot send progress: no session ID");return false}return this.scope.notifications.sendProgressNotification(sessionId,this._progressToken,progress,total,message)}async elicit(message,requestedSchema,options){return performElicit({sessionId:this.authInfo.sessionId,getClientCapabilities:sid=>this.scope.notifications.getClientCapabilities(sid),tryGetContext:()=>this.tryGetContext()??this.runningRequestContext(),entryName:this._agentNameInternal??this.agentName,entryInput:this._agentInputInternal??this.input,elicitationEnabled:this.scope.metadata.elicitation?.enabled===true},message,requestedSchema,options)}requestNotificationSink(){return(this.tryGetContext()??this.runningRequestContext())?.getRequestNotificationSink?.()}runningRequestContext(){try{return this.scope.providers.get(FrontMcpContextStorage).getStore()}catch{return void 0}}respond(value){this.output=value;FlowControl.respond(value)}get platform(){const payloadPlatform=this.authInfo.sessionIdPayload?.platformType;if(payloadPlatform&&payloadPlatform!=="unknown"){return payloadPlatform}const requestPlatform=this.tryGetContext()?.platformType;if(requestPlatform&&requestPlatform!=="unknown"){return requestPlatform}const sessionId=this.authInfo.sessionId;if(!sessionId){return"unknown"}return this.scope.notifications.getPlatformType(sessionId)}get clientInfo(){const requestClientInfo=this.tryGetContext()?.clientInfo;if(requestClientInfo){return requestClientInfo}const sessionId=this.authInfo.sessionId;if(!sessionId){return void 0}return this.scope.notifications.getClientInfo(sessionId)}}}});var SkillContext;var init_skill_interface=__esm({"libs/sdk/src/common/interfaces/skill.interface.ts"(){"use strict";init_sdk_errors();init_metadata();init_execution_context_interface();SkillContext=class extends ExecutionContextBase{skillId;skillName;metadata;defaults;constructor(args){const{metadata,providers,logger,defaults}=args;super({providers,logger:logger.child(`skill:${metadata.id??metadata.name}`),authInfo:args.authInfo});this.skillName=metadata.name;this.skillId=metadata.id??metadata.name;this.metadata=metadata;this.defaults=defaults}async loadInstructions(){if(!this.defaults)throw new SkillContextNotImplementedError(this.skillName,"loadInstructions");return this.defaults.loadInstructions()}async build(){if(!this.defaults)throw new SkillContextNotImplementedError(this.skillName,"build");return this.defaults.build()}getToolRefs(){if(!this.metadata.tools)return[];return this.metadata.tools.map(t=>normalizeToolRef(t))}getToolNames(){return this.getToolRefs().map(t=>t.name)}}}});var JobContext;var init_job_interface=__esm({"libs/sdk/src/common/interfaces/job.interface.ts"(){"use strict";init_execution_context_interface();init_flow_interface();JobContext=class extends ExecutionContextBase{jobId;jobName;metadata;_input;_output;_attempt;_logs=[];signal;constructor(args){const{metadata,input,providers,logger,attempt,signal}=args;super({providers,logger:logger.child(`job:${metadata.id??metadata.name}`),authInfo:args.authInfo});this.jobName=metadata.name;this.jobId=metadata.id??metadata.name;this.metadata=metadata;this._input=input;this._attempt=attempt;this.signal=signal}fetch(input,init){const context=this.fetchContext(init);if(context&&this.signal)return context.fetch(input,init,this.signal);return super.fetch(input,init)}get input(){return this._input}get output(){return this._output}set output(v){this._output=v}get attempt(){return this._attempt}log(message){this._logs.push(`[${new Date().toISOString()}] ${message}`);this.logger.info(message)}async progress(pct,total,msg){const sessionId=this.authInfo.sessionId;if(!sessionId){this.logger.debug("Cannot send progress: no session ID");return false}return this.scope.notifications.sendProgressNotification(sessionId,this.jobId,pct,total,msg)}respond(value){this._output=value;FlowControl.respond(value)}getLogs(){return this._logs}callToolSurface(){return"job"}}}});var WorkflowContext;var init_workflow_interface=__esm({"libs/sdk/src/common/interfaces/workflow.interface.ts"(){"use strict";init_execution_context_interface();WorkflowContext=class extends ExecutionContextBase{metadata;_stepResults=new Map;constructor(args){const{metadata,providers,logger}=args;super({providers,logger:logger.child(`workflow:${metadata.id??metadata.name}`),authInfo:args.authInfo});this.metadata=metadata}get workflowName(){return this.metadata.name}get workflowId(){return this.metadata.id??this.metadata.name}get stepResults(){return this._stepResults}_setStepResult(stepId,result){this._stepResults.set(stepId,result)}}}});var ChannelContext;var init_channel_interface=__esm({"libs/sdk/src/common/interfaces/channel.interface.ts"(){"use strict";init_call_surface();init_mcp_error();init_execution_context_interface();ChannelContext=class extends ExecutionContextBase{channelName;metadata;_pushIncoming;constructor(args){const{metadata,providers,logger}=args;super({providers,logger:logger.child(`channel:${metadata.name}`),authInfo:args.authInfo});this.channelName=metadata.name;this.metadata=metadata}async onReply(reply,meta){throw new PublicMcpError(`Channel "${this.channelName}" has twoWay: true but onReply() is not implemented. Override onReply() to forward replies to the external system.`,"CHANNEL_REPLY_NOT_IMPLEMENTED",501)}async onConnect(){}async onDisconnect(){}pushIncoming(payload){if(this._pushIncoming){this._pushIncoming(payload)}else{this.logger.warn(`Channel "${this.channelName}": pushIncoming called but no handler is wired`)}}callToolSurface(){return getCallSurface()==="http-trigger"?"http-trigger":void 0}}}});function sessionIdPresentedBy(request){const header=request.headers?.["mcp-session-id"];if(typeof header==="string"&&header.length>0)return header;const query=request.query?.["sessionId"];return typeof query==="string"&&query.length>0?query:void 0}function authInfoFromAuthorization(authorization,presentedSessionId){const{token,user,session}=authorization;const verifiedSession=session!==void 0&&presentedSessionId!==void 0&&session.id===presentedSessionId?session:void 0;return{token,clientId:user?.sub,scopes:(0,import_auth38.scopesFromClaims)(user),expiresAt:user?.exp?user.exp*1e3:void 0,user,extra:{user,sessionId:verifiedSession?.id,sessionPayload:verifiedSession?.payload}}}var import_auth38;var init_auth_info_utils=__esm({"libs/sdk/src/common/utils/auth-info.utils.ts"(){"use strict";import_auth38=require("@frontmcp/auth")}});function pathOf(req){const anyReq=req;const raw=anyReq.path??anyReq.pathname??anyReq.url??"/";try{const u=new URL(String(raw),"http://local");return u.pathname||"/"}catch{return String(raw).split("?")[0]||"/"}}function isLegacySsePath(path){return path==="/sse"||path.endsWith("/sse")}function tryDecodeTransportType(sessionId){if(!sessionId)return;try{const b64=sessionId.replace(/-/g,"+").replace(/_/g,"/");const json=Buffer.from(b64,"base64").toString("utf8");if(json.trimStart()[0]!=="{")return;const obj=JSON.parse(json);return obj?.transportType}catch{return}}function getQuerySessionId(req){const anyReq=req;const raw=anyReq.url??anyReq.path??"/";try{const u=new URL(String(raw),"http://local");return u.searchParams.get("sessionId")??void 0}catch{return void 0}}function computeBitmap(req,cfg){const method=req.method.toUpperCase();const accept=h(req,"accept");const path=pathOf(req);const postToMessage=method==="POST"&&(path==="/message"||path.endsWith("/message"));const headerSessionId=h(req,"mcp-session-id");const querySessionId=postToMessage?getQuerySessionId(req):void 0;const sessionId=headerSessionId??querySessionId;const legacyHeader=h(req,"x-legacy-sse")==="true";const transportType=tryDecodeTransportType(sessionId);const acceptSSE=wantsSSE(accept);const acceptJSON=wantsJSON(accept)||!accept&&cfg.tolerateMissingAccept;const init=method==="POST"&&isInitialize(req.body);const getToSsePath=method==="GET"&&isLegacySsePath(path);const channel2=method==="POST"&&postToMessage?CH_POST_MESSAGE:getToSsePath&&acceptSSE?CH_GET_SSE_PATH:method==="GET"&&acceptSSE?CH_GET_SSE:method==="POST"&&init&&acceptSSE?CH_POST_INIT_SSE:method==="POST"&&init&&acceptJSON?CH_POST_INIT_JSON:method==="POST"&&!init&&acceptSSE?CH_POST_SSE:method==="POST"&&!init&&acceptJSON?CH_POST_JSON:CH_OTHER;let flags=0;if(sessionId)flags|=B_HAS_SESSION;if(cfg.enableStatelessHttp)flags|=B_STATELESS_EN;if(cfg.requireSessionForStreamable)flags|=B_REQ_SESSION;if(legacyHeader||transportType==="legacy-sse")flags|=B_LEGACY_HINT;if(cfg.enableSseListener)flags|=B_SSE_LISTENER_EN;if(cfg.enableStreamableHttp)flags|=B_STREAMABLE_EN;if(cfg.enableStatefulHttp)flags|=B_STATEFUL_EN;if(cfg.enableLegacySSE)flags|=B_LEGACY_EN;return{key:channel2&CH_MASK|flags,channel:channel2,flags,init}}function decideIntent(req,cfg){const reasons=[];const method=req.method.toUpperCase();if(method==="DELETE"){const sessionId=h(req,"mcp-session-id");if(!sessionId){return{intent:"unknown",reasons:["DELETE requires Mcp-Session-Id header."],recommendation:{httpStatus:400,message:"Session ID required for DELETE"},debug:{key:0,channel:0,flags:0}}}return{intent:"delete-session",reasons:["DELETE with Mcp-Session-Id \u2192 session termination."],debug:{key:0,channel:0,flags:sessionId?B_HAS_SESSION:0}}}const{key,channel:channel2,flags,init}=computeBitmap(req,cfg);if(method==="POST"){const accept=h(req,"accept");const acceptsSSE=wantsSSE(accept);const acceptsJSON=wantsJSON(accept)||!accept&&cfg.tolerateMissingAccept;if(!acceptsSSE&&!acceptsJSON){return{intent:"unknown",reasons:["Client must accept application/json or text/event-stream."],recommendation:{httpStatus:406,message:"Not acceptable"},debug:{key,channel:channel2,flags}}}}for(const rule of RULES){if((key&rule.care)===rule.match){const{reason,...rest}=rule.outcome;reasons.push(reason);if(init)reasons.push("Initialize body detected.");return{...rest,reasons,debug:{key,channel:channel2,flags}}}}return{intent:"unknown",reasons:["No matching rule."],recommendation:{httpStatus:500,message:"Unroutable request"},debug:{key,channel:channel2,flags}}}function authorizeSessionTermination(verifyResult,requestedSessionId){if(!verifyResult||verifyResult.kind!=="authorized"||!verifyResult.authorization){return{kind:"unauthorized"}}const ownedSessionId=verifyResult.authorization.session?.id;if(!ownedSessionId||!requestedSessionId||requestedSessionId!==ownedSessionId){return{kind:"forbidden"}}return{kind:"ok",sessionId:ownedSessionId}}var import_lazy_zod71,intentSchema,decisionSchema,CH_OTHER,CH_GET_SSE,CH_POST_INIT_JSON,CH_POST_INIT_SSE,CH_POST_JSON,CH_POST_SSE,CH_POST_MESSAGE,CH_GET_SSE_PATH,CH_MASK,B_HAS_SESSION,B_STATELESS_EN,B_REQ_SESSION,B_LEGACY_HINT,B_SSE_LISTENER_EN,B_STREAMABLE_EN,B_STATEFUL_EN,B_LEGACY_EN,h,wantsSSE,wantsJSON,isInitialize,RULES;var init_decide_request_intent_utils=__esm({"libs/sdk/src/common/utils/decide-request-intent.utils.ts"(){"use strict";import_lazy_zod71=require("@frontmcp/lazy-zod");intentSchema=import_lazy_zod71.z.union([import_lazy_zod71.z.literal("legacy-sse"),import_lazy_zod71.z.literal("sse"),import_lazy_zod71.z.literal("streamable-http"),import_lazy_zod71.z.literal("stateful-http"),import_lazy_zod71.z.literal("stateless-http"),import_lazy_zod71.z.literal("delete-session"),import_lazy_zod71.z.literal("mcp-20260728"),import_lazy_zod71.z.literal("unknown")]);decisionSchema=import_lazy_zod71.z.object({intent:intentSchema,reasons:import_lazy_zod71.z.array(import_lazy_zod71.z.string()),recommendation:import_lazy_zod71.z.object({httpStatus:import_lazy_zod71.z.number(),message:import_lazy_zod71.z.string()}).optional(),debug:import_lazy_zod71.z.object({key:import_lazy_zod71.z.number(),channel:import_lazy_zod71.z.number(),flags:import_lazy_zod71.z.number()}).optional()});CH_OTHER=0;CH_GET_SSE=1;CH_POST_INIT_JSON=2;CH_POST_INIT_SSE=3;CH_POST_JSON=4;CH_POST_SSE=5;CH_POST_MESSAGE=6;CH_GET_SSE_PATH=7;CH_MASK=7;B_HAS_SESSION=1<<3;B_STATELESS_EN=1<<4;B_REQ_SESSION=1<<5;B_LEGACY_HINT=1<<6;B_SSE_LISTENER_EN=1<<7;B_STREAMABLE_EN=1<<8;B_STATEFUL_EN=1<<9;B_LEGACY_EN=1<<10;h=(req,name48)=>Object.entries(req.headers).find(([k])=>k.toLowerCase()===name48.toLowerCase())?.[1];wantsSSE=accept=>(accept??"").toLowerCase().includes("text/event-stream");wantsJSON=accept=>(accept??"").toLowerCase().includes("application/json");isInitialize=body=>!!body&&typeof body==="object"&&body.method==="initialize";RULES=[{care:CH_MASK|B_HAS_SESSION|B_LEGACY_EN,match:CH_GET_SSE_PATH|B_LEGACY_EN,outcome:{intent:"legacy-sse",reason:"GET /sse without Mcp-Session-Id \u2192 legacy SSE."}},{care:CH_MASK|B_HAS_SESSION|B_LEGACY_EN,match:CH_GET_SSE_PATH,outcome:{intent:"unknown",reason:"Legacy SSE disabled.",recommendation:{httpStatus:405,message:"Legacy SSE disabled"}}},{care:CH_MASK|B_HAS_SESSION|B_SSE_LISTENER_EN|B_STREAMABLE_EN,match:CH_GET_SSE|B_HAS_SESSION|B_SSE_LISTENER_EN|B_STREAMABLE_EN,outcome:{intent:"streamable-http",reason:"GET / with session ID \u2192 SSE listener for streamable-http."}},{care:CH_MASK|B_HAS_SESSION|B_SSE_LISTENER_EN,match:CH_GET_SSE|B_HAS_SESSION,outcome:{intent:"unknown",reason:"SSE listener disabled for GET / requests.",recommendation:{httpStatus:405,message:"SSE listener disabled"}}},{care:CH_MASK|B_HAS_SESSION,match:CH_GET_SSE,outcome:{intent:"unknown",reason:"GET / with SSE requires session for MCP transport."}},{care:CH_MASK|B_HAS_SESSION|B_LEGACY_EN,match:CH_POST_MESSAGE|B_HAS_SESSION|B_LEGACY_EN,outcome:{intent:"legacy-sse",reason:"POST /message with Mcp-Session-Id \u2192 legacy SSE bridge."}},{care:CH_MASK|B_HAS_SESSION|B_LEGACY_EN,match:CH_POST_MESSAGE|B_HAS_SESSION,outcome:{intent:"unknown",reason:"Legacy /message endpoint disabled.",recommendation:{httpStatus:405,message:"Legacy SSE disabled"}}},{care:CH_MASK|B_SSE_LISTENER_EN|B_HAS_SESSION,match:CH_GET_SSE_PATH|B_HAS_SESSION,outcome:{intent:"unknown",reason:"SSE listener disabled.",recommendation:{httpStatus:405,message:"SSE listener disabled"}}},{care:CH_MASK|B_SSE_LISTENER_EN|B_HAS_SESSION,match:CH_GET_SSE_PATH|B_SSE_LISTENER_EN|B_HAS_SESSION,outcome:{intent:"sse",reason:"GET /sse with Mcp-Session-Id."}},{care:CH_MASK|B_HAS_SESSION|B_STATELESS_EN|B_STREAMABLE_EN,match:CH_POST_INIT_SSE|B_STATELESS_EN,outcome:{intent:"stateless-http",reason:"Stateless initialize (no session)."}},{care:CH_MASK|B_STREAMABLE_EN,match:CH_POST_INIT_SSE,outcome:{intent:"unknown",reason:"Streamable HTTP disabled.",recommendation:{httpStatus:405,message:"Streamable HTTP disabled"}}},{care:CH_MASK|B_STREAMABLE_EN,match:CH_POST_INIT_SSE|B_STREAMABLE_EN,outcome:{intent:"streamable-http",reason:"Initialize with SSE."}},{care:CH_MASK|B_HAS_SESSION|B_STATELESS_EN|B_STREAMABLE_EN,match:CH_POST_INIT_JSON|B_STATELESS_EN,outcome:{intent:"stateless-http",reason:"Stateless initialize JSON (no session)."}},{care:CH_MASK|B_STREAMABLE_EN,match:CH_POST_INIT_JSON,outcome:{intent:"unknown",reason:"JSON mode disabled.",recommendation:{httpStatus:405,message:"JSON mode disabled"}}},{care:CH_MASK|B_STREAMABLE_EN,match:CH_POST_INIT_JSON|B_STREAMABLE_EN,outcome:{intent:"stateful-http",reason:"Initialize with JSON."}},{care:CH_MASK|B_REQ_SESSION|B_HAS_SESSION|B_STATELESS_EN,match:CH_POST_SSE|B_REQ_SESSION,outcome:{intent:"unknown",reason:"POST SSE requires session.",recommendation:{httpStatus:400,message:"Initialize required (no Mcp-Session-Id)"}}},{care:CH_MASK|B_STREAMABLE_EN|B_STATELESS_EN,match:CH_POST_SSE,outcome:{intent:"unknown",reason:"Streamable HTTP disabled.",recommendation:{httpStatus:405,message:"Streamable HTTP disabled"}}},{care:CH_MASK|B_HAS_SESSION|B_STATELESS_EN|B_STREAMABLE_EN,match:CH_POST_SSE|B_STATELESS_EN,outcome:{intent:"stateless-http",reason:"Stateless short-lived SSE."}},{care:CH_MASK,match:CH_POST_SSE,outcome:{intent:"streamable-http",reason:"Short-lived SSE for this request."}},{care:CH_MASK|B_REQ_SESSION|B_HAS_SESSION|B_STATELESS_EN,match:CH_POST_JSON|B_REQ_SESSION,outcome:{intent:"unknown",reason:"POST JSON requires session.",recommendation:{httpStatus:400,message:"Initialize required (no Mcp-Session-Id)"}}},{care:CH_MASK|B_STATEFUL_EN|B_STREAMABLE_EN|B_STATELESS_EN,match:CH_POST_JSON,outcome:{intent:"unknown",reason:"JSON mode disabled.",recommendation:{httpStatus:405,message:"JSON mode disabled"}}},{care:CH_MASK|B_HAS_SESSION|B_STATELESS_EN|B_STREAMABLE_EN,match:CH_POST_JSON|B_STATELESS_EN,outcome:{intent:"stateless-http",reason:"Stateless JSON request."}},{care:CH_MASK,match:CH_POST_JSON,outcome:{intent:"stateful-http",reason:"Aggregated JSON response."}},{care:CH_MASK,match:CH_OTHER,outcome:{intent:"unknown",reason:"Method/Accept not allowed.",recommendation:{httpStatus:405,message:"Method/Accept not allowed"}}}]}});function enforceIpFilter(scope,clientIp,buildRejection=()=>httpRespond.forbidden({body:{...IP_FILTER_REJECTION_BODY}})){const result=scope.rateLimitManager?.checkIpFilter(clientIp);if(!result||result.allowed)return;scope.logger.warn("request rejected by ipFilter",{reason:result.reason,hasClientIp:clientIp!==void 0});FlowControl.respond(buildRejection())}function buildPartitionContext(source){if(!source)return void 0;const clientId=source.authInfo?.clientId;const userId=(0,import_auth39.isAnonymousSubject)(clientId)?void 0:String(clientId);const callerKey=userId?`user:${userId}`:"anonymous";return{sessionId:verifiedSessionOf(source)??callerKey,clientIp:source.metadata?.clientIp,userId}}function verifiedSessionOf(source){if("verifiedSessionId"in source)return source.verifiedSessionId;const confirmed=source.authInfo?.sessionId??source.authInfo?.extra?.sessionId;return confirmed===source.sessionId?source.sessionId:void 0}function partitionsByIdentity(partitionBy){return partitionBy==="session"||partitionBy==="userId"||typeof partitionBy==="function"}async function enforceGlobalRateLimit(scope,context){const manager=scope.rateLimitManager;const globalConfig=manager?.config?.global;const partitionBy=globalConfig?.partitionBy;if(!manager||!globalConfig||partitionBy==="session"||partitionBy==="userId")return;let result;try{result=await manager.checkGlobalRateLimit(buildPartitionContext(context))}catch(error){if(!(error instanceof import_guard7.GuardStorageUnavailableError))throw error;FlowControl.respond(httpRespond.json({error:"service_unavailable",message:"Service temporarily unavailable: the rate-limit store cannot be reached",code:error.code},{status:error.statusCode,headers:{"Retry-After":"1"}}))}context?.set(GLOBAL_RATE_LIMIT_CHECKED,true);if(result.allowed)return;const retryAfter=Math.ceil((result.retryAfterMs??6e4)/1e3);FlowControl.respond(httpRespond.json({error:"rate_limited",message:`Rate limit exceeded. Retry after ${retryAfter} seconds`},{status:429,headers:{"Retry-After":String(retryAfter)}}))}async function acquireConcurrencySlots(manager,entityName,entityConfig,partitionContext,options={}){const globalConfig=options.skipGlobal?void 0:manager.config.globalConcurrency;const globalTicket=globalConfig?await manager.acquireGlobalSemaphore(partitionContext):null;if(globalConfig&&!globalTicket){throw new import_guard7.ConcurrencyLimitError("global",globalConfig.maxConcurrent)}const config=entityConfig??manager.config.defaultConcurrency;if(!config)return globalTicket??void 0;let entityTicket;try{entityTicket=await manager.acquireSemaphore(entityName,config,partitionContext)}catch(error){await globalTicket?.release();throw error}if(!entityTicket){await globalTicket?.release();throw new import_guard7.ConcurrencyLimitError(entityName,config.maxConcurrent)}if(!globalTicket)return entityTicket;const heldEntityTicket=entityTicket;return{ticket:heldEntityTicket.ticket,release:async()=>{try{await heldEntityTicket.release()}finally{await globalTicket.release()}}}}var import_auth39,import_guard7,IP_FILTER_REJECTION_BODY,GLOBAL_RATE_LIMIT_CHECKED;var init_guard_utils=__esm({"libs/sdk/src/common/utils/guard.utils.ts"(){"use strict";import_auth39=require("@frontmcp/auth");import_guard7=require("@frontmcp/guard");init_flow_interface();init_http_output_schema();IP_FILTER_REJECTION_BODY={error:"forbidden",message:"Client IP rejected by ipFilter"};GLOBAL_RATE_LIMIT_CHECKED=Symbol.for("frontmcp:guard:global-rate-limit-checked")}});function toStringArray(value){if(Array.isArray(value))return value.filter(v=>typeof v==="string");if(typeof value==="string"&&value.length>0)return value.split(" ").filter(Boolean);return[]}function asRecord(value){return value&&typeof value==="object"?value:void 0}function firstPresent(sources,convert){for(const source of sources){if(source!==void 0&&source!==null)return convert(source)}return[]}function resolvePrincipal2(authInfo,contextBuilder){const info=authInfo??{};const user=asRecord(info["user"])??{};const extraAuthorization=asRecord(asRecord(info["extra"])?.["authorization"]);const authInfoClaims=asRecord(info["claims"])??{};const authorizationClaims=asRecord(extraAuthorization?.["claims"])??{};const claims={...authorizationClaims,...authInfoClaims,...user};const scopes=toStringArray(info["scopes"]).length?toStringArray(info["scopes"]):firstPresent([extraAuthorization?.["scopes"],claims["scope"],claims["scopes"]],toStringArray);if(contextBuilder){const ctx=contextBuilder.build(info);return{sub:ctx.user.sub??"",roles:ctx.user.roles,permissions:ctx.user.permissions,scopes,claims:ctx.user.claims}}const roles=firstPresent([user["roles"],claims["roles"],extraAuthorization?.["scopes"]],toStringArray);const permissions=firstPresent([user["permissions"],claims["permissions"]],toStringArray);return{sub:typeof user["sub"]==="string"?user["sub"]:"",roles,permissions,scopes,claims}}var init_principal_utils=__esm({"libs/sdk/src/common/utils/principal.utils.ts"(){"use strict"}});function getGlobalStoreConfig(pluginName,config){if(!config.redis){throw new GlobalConfigNotFoundError(pluginName,"redis")}return config.redis}var init_global_config_utils=__esm({"libs/sdk/src/common/utils/global-config.utils.ts"(){"use strict";init_errors()}});var init_utils3=__esm({"libs/sdk/src/common/utils/index.ts"(){"use strict";init_auth_info_utils();init_caller_dir_utils();init_decide_request_intent_utils();init_guard_utils();init_path_utils();init_principal_utils();init_global_config_utils();init_primitive_filter();init_validate_remote_url()}});var FrontMcpAuth;var init_primary_auth_provider_interface=__esm({"libs/sdk/src/common/interfaces/internal/primary-auth-provider.interface.ts"(){"use strict";init_types();init_utils3();FrontMcpAuth=class{ready;options;id;constructor(options){this.options=options;this.id=this.deriveId(options)}deriveId(options){if((0,import_auth13.isPublicMode)(options)){return options.issuer??"public"}if((0,import_auth13.isTransparentMode)(options)){return options.providerConfig?.id??urlToSafeId(options.provider)}if((0,import_auth13.isOrchestratedMode)(options)){if((0,import_auth13.isOrchestratedRemote)(options)){return options.providerConfig?.id??urlToSafeId(options.provider)}return options.local?.issuer??"local"}return"unknown"}verifyGatewayToken(_token,_requestBaseUrl,_expectedAudience,_expectedIssuer){return Promise.resolve({ok:false,error:"gateway token verification is not supported by this auth mode"})}}}});var init_registry_interface=__esm({"libs/sdk/src/common/interfaces/internal/registry.interface.ts"(){"use strict"}});var init_internal=__esm({"libs/sdk/src/common/interfaces/internal/index.ts"(){"use strict";init_primary_auth_provider_interface();init_registry_interface()}});var init_interfaces2=__esm({"libs/sdk/src/common/interfaces/index.ts"(){"use strict";init_base_interface();init_execution_context_interface();init_front_mcp_interface();init_server_interface();init_scope_interface();init_flow_interface();init_hook_interface();init_app_interface();init_provider_interface();init_auth_provider_interface();init_adapter_interface();init_plugin_interface();init_tool_interface();init_resource_interface();init_prompt_interface();init_logger_interface();init_llm_adapter_interface();init_agent_interface();init_skill_interface();init_job_interface();init_workflow_interface();init_channel_interface();init_internal()}});var Sep2640SkillFileResource;var init_skill_file_resource=__esm({"libs/sdk/src/skill/sep-2640/resources/skill-file.resource.ts"(){"use strict";init_common();init_interfaces2();init_errors();init_skill_authorities_helper();init_skill_filter_helper();init_sep_2640_resource_helpers();Sep2640SkillFileResource=class extends ResourceContext{async skillPathCompleter(partial){const visible=getSepVisibleSkills(this.scope);const authorized=await filterSkillsByAuthorities(this.scope,visible,this.getAuthInfo());const skills=await filterServableSkills(this.scope,authorized);const paths=skills.map(s=>s.getSkillPath());const filtered=partial?paths.filter(p=>p.toLowerCase().startsWith(partial.toLowerCase())):paths;return{values:filtered,total:filtered.length}}async filePathCompleter(partial){const visible=getSepVisibleSkills(this.scope);const authorized=await filterSkillsByAuthorities(this.scope,visible,this.getAuthInfo());const skills=await filterServableSkills(this.scope,authorized);const seen=new Set;for(const skill of skills){try{const content=await skill.load();for(const ref of content.resolvedReferences??[]){if(ref.filename)seen.add(`references/${ref.filename}`)}for(const ex of content.resolvedExamples??[]){if(ex.filename)seen.add(`examples/${ex.filename}`)}}catch{}}const all=Array.from(seen).sort();const filtered=partial?all.filter(p=>p.toLowerCase().startsWith(partial.toLowerCase())):all;return{values:filtered,total:filtered.length}}async execute(uri,params){if(params.filePath==="SKILL.md"||params.filePath.endsWith("/SKILL.md")){throw new ResourceNotFoundError(uri)}const entry=findSkillByPath(this.scope,params.skillPath);if(!entry){await findAndLoadSkillByPath(this.scope,params.skillPath);throw new ResourceNotFoundError(uri)}if(!await isSkillServable(this.scope,entry)){throw new ResourceNotFoundError(uri)}const instance=entry;await assertSkillAuthorized(this.scope,instance,this.getAuthInfo());const result=await readSkillFileByPath(instance,params.filePath);return{contents:[result.kind==="text"?{uri,mimeType:result.mimeType,text:result.content}:{uri,mimeType:result.mimeType,blob:result.blob}]}}};Sep2640SkillFileResource=__decorateClass([_ResourceTemplate({name:"sep2640-skill-file",uriTemplate:"skill://{+skillPath}/{+filePath}",description:"Read any file inside a skill directory (references, examples, scripts, assets, top-level files) per MCP SEP-2640. Path traversal is rejected."})],Sep2640SkillFileResource)}});var Sep2640SkillIndexResource;var init_skill_index_resource=__esm({"libs/sdk/src/skill/sep-2640/resources/skill-index.resource.ts"(){"use strict";init_common();init_interfaces2();init_skill_authorities_helper();init_skill_filter_helper();init_sep_2640_builders();init_sep_2640_constants();init_sep_2640_resource_helpers();Sep2640SkillIndexResource=class extends ResourceContext{async execute(uri){const visible=getSepVisibleSkills(this.scope);const authorized=await filterSkillsByAuthorities(this.scope,visible,this.getAuthInfo());const skills=await filterServableSkills(this.scope,authorized);const entries=skills.map(skill=>buildSkillMdIndexEntry({name:skill.metadata.name,description:skill.getDescription(),skillPathSegments:skill.getSkillPathSegments()}));for(const metadata of await getExternalProviderSkills(this.scope)){entries.push(buildSkillMdIndexEntry({name:metadata.name,description:metadata.description}))}if(entries.length>0){entries.push(buildResourceTemplateIndexEntry("Read the raw SKILL.md (frontmatter + body) for any skill served by this MCP server.","skill://{+skillPath}/SKILL.md"))}const registry=this.scope.skills;const templates=registry?.getSep2640IndexTemplates?.()??[];for(const tpl of templates){entries.push(tpl)}const archives=registry?.getSep2640IndexArchives?.()??[];for(const arc of archives){entries.push(arc)}const document=buildSkillIndex(entries);return{contents:[{uri,mimeType:SKILL_INDEX_MIME_TYPE,text:JSON.stringify(document,null,2)}]}}};Sep2640SkillIndexResource=__decorateClass([Resource({name:"sep2640-skill-index",uri:SKILL_INDEX_URI,description:"SEP-2640 skill discovery index. Lists every MCP-visible skill with its name, description, and full skill:// URI. Resource templates and archive entries may also appear when configured.",mimeType:SKILL_INDEX_MIME_TYPE})],Sep2640SkillIndexResource)}});var Sep2640SkillMdResource;var init_skill_md_resource=__esm({"libs/sdk/src/skill/sep-2640/resources/skill-md.resource.ts"(){"use strict";init_common();init_interfaces2();init_skill_authorities_helper();init_skill_filter_helper();init_sep_2640_builders();init_sep_2640_constants();init_sep_2640_resource_helpers();Sep2640SkillMdResource=class extends ResourceContext{async skillPathCompleter(partial){const visible=getSepVisibleSkills(this.scope);const authorized=await filterSkillsByAuthorities(this.scope,visible,this.getAuthInfo());const skills=await filterServableSkills(this.scope,authorized);const paths=skills.map(s=>s.getSkillPath());const filtered=partial?paths.filter(p=>p.toLowerCase().startsWith(partial.toLowerCase())):paths;return{values:filtered,total:filtered.length}}async execute(uri,params){const raw=serializeSkillMd(await this.readSkill(params.skillPath));return{contents:[{uri,mimeType:SKILL_MD_MIME_TYPE,text:raw}]}}async readSkill(skillPath){if(!findSkillByPath(this.scope,skillPath)){const providerSkill=await loadExternalProviderSkill(this.scope,skillPath);if(providerSkill)return providerSkill}const{loadResult,instance}=await findAndLoadSkillByPath(this.scope,skillPath);await assertSkillAuthorized(this.scope,instance,this.getAuthInfo());return loadResult.skill}};Sep2640SkillMdResource=__decorateClass([_ResourceTemplate({name:"sep2640-skill-md",uriTemplate:"skill://{+skillPath}/SKILL.md",description:"Read a skill's SKILL.md (raw YAML frontmatter + markdown body) per MCP SEP-2640. Conformant clients parse the frontmatter identically to filesystem skills.",mimeType:SKILL_MD_MIME_TYPE})],Sep2640SkillMdResource)}});var resources_exports={};__export(resources_exports,{Sep2640SkillFileResource:()=>Sep2640SkillFileResource,Sep2640SkillIndexResource:()=>Sep2640SkillIndexResource,Sep2640SkillMdResource:()=>Sep2640SkillMdResource,getSep2640Resources:()=>getSep2640Resources});function getSep2640Resources(){return[Sep2640SkillIndexResource,Sep2640SkillMdResource,Sep2640SkillFileResource]}var init_resources=__esm({"libs/sdk/src/skill/sep-2640/resources/index.ts"(){"use strict";init_skill_file_resource();init_skill_index_resource();init_skill_md_resource()}});function declaresDynamicSkills(metadata){return metadata.dynamicSkills===true||(metadata.plugins??[]).some(plugin=>declaresDynamicSkills(normalizePlugin(plugin).metadata))}function pluginsRegisterDynamicSkills(plugins){for(const plugin of plugins){if(declaresDynamicSkills(normalizePlugin(plugin).metadata))return true}return false}async function registerSkillCapabilities(options){const{skillRegistry,flowRegistry,resourceRegistry,providers,skillsConfig,logger,dynamicSkills}=options;registerSkillAuditWriter({providers,audit:skillsConfig?.audit,logger});await flowRegistry.registryFlows([FilterSkillsFlow]);if(dynamicSkills){skillRegistry.expectDynamicSkills()}if(skillsConfig?.externalProvider){await skillsConfig.externalProvider.initialize();skillRegistry.setExternalProvider(skillsConfig.externalProvider)}if(!skillRegistry.servesSkills()){return}const{LlmFullTxtFlow:LlmFullTxtFlow2,LlmTxtFlow:LlmTxtFlow2,LoadSkillFlow:LoadSkillFlow2,SearchSkillsFlow:SearchSkillsFlow2,SkillsApiFlow:SkillsApiFlow2}=await Promise.resolve().then(()=>(init_flows(),flows_exports));await flowRegistry.registryFlows([SearchSkillsFlow2,LoadSkillFlow2]);const shouldRegisterResources=skillsConfig?.mcpResources!==false;if(shouldRegisterResources){await registerSep2640Resources({resourceRegistry,logger});const[{registerPerSkillResources:registerPerSkillResources2},{resolveLastModifiedForSkill:resolveLastModifiedForSkill2}]=await Promise.all([Promise.resolve().then(()=>(init_sep_2640_per_skill(),sep_2640_per_skill_exports)),Promise.resolve().then(()=>(init_sep_2640_last_modified(),sep_2640_last_modified_exports))]);await registerPerSkillResources2({scope:providers.getActiveScope(),skillRegistry,resourceRegistry,logger,resolveLastModified:resolveLastModifiedForSkill2})}else{logger.verbose("SEP-2640 skill:// resources disabled via skillsConfig.mcpResources=false")}if(skillsConfig?.enabled){await flowRegistry.registryFlows([LlmTxtFlow2,LlmFullTxtFlow2,SkillsApiFlow2]);logger.verbose("Registered skills HTTP flows (llm.txt, llm_full.txt, /skills API)")}}async function registerSep2640Resources(options){const{resourceRegistry,logger}=options;const{getSep2640Resources:getSep2640Resources2}=await Promise.resolve().then(()=>(init_resources(),resources_exports));const resources=getSep2640Resources2();for(const ResourceClass of resources){try{resourceRegistry.registerDynamicResource(ResourceClass);const resourceName=typeof ResourceClass==="function"?ResourceClass.name:"unknown";logger.verbose(`Registered SEP-2640 resource: ${resourceName}`)}catch(error){logger.warn(`Failed to register SEP-2640 resource: ${error instanceof Error?error.message:String(error)}`)}}}var init_skill_scope_helper=__esm({"libs/sdk/src/skill/skill-scope.helper.ts"(){"use strict";init_plugin_utils();init_filter_skills_flow();init_skill_audit_helper()}});function isExplicitStorage(storage){return Boolean(storage?.type&&storage.type!=="auto")}function resolvesToVercelKvTaskBackend(redis,storage){if(isExplicitStorage(storage))return storage.type==="vercel-kv";if(redis)return"provider"in redis&&redis.provider==="vercel-kv";return Boolean((0,import_utils85.getEnv)("KV_REST_API_URL"))}var import_utils85;var init_task_backend_utils=__esm({"libs/sdk/src/task/store/task-backend.utils.ts"(){"use strict";import_utils85=require("@frontmcp/utils")}});function describeMode(mode){return typeof mode==="function"?"a function":`'${String(mode)}'`}function protocolAdvice(protocol,remove){return protocol==="stateless-api"?`The server already serves without sessions (\`transport.protocol: 'stateless-api'\`); remove \`${remove}\`.`:`To serve without sessions, set \`transport.protocol: 'stateless-api'\` and remove \`${remove}\`.`}function warnIfSessionModeIgnored(options){const{logger,transport,session}=options;const mode=transport?.sessionMode;if(transport&&mode!==void 0&&mode!=="stateful"&&!warned.has(transport)){warned.add(transport);logger.warn(`transport.sessionMode (${describeMode(mode)}) ${REMOVAL}: sessions follow \`transport.protocol\`. `+protocolAdvice(transport.protocol,"sessionMode"))}if(!session||warned.has(session))return;const legacyMode=session.sessionMode;const ignored=[];if(legacyMode!==void 0&&legacyMode!=="stateful"){ignored.push(`session.sessionMode (${describeMode(legacyMode)}) ${REMOVAL}, with the rest of \`session\`: sessions follow \`transport.protocol\`, and provider tokens always stay server-side (\`auth.tokenStorage\`), never in the JWT. ${protocolAdvice(transport?.protocol,"session")}`)}if(session.platformDetection!==void 0){ignored.push(`session.platformDetection ${REMOVAL}, with the rest of \`session\`: move it to \`transport.platformDetection\`.`)}if(ignored.length===0)return;warned.add(session);for(const message of ignored)logger.warn(message)}var warned,REMOVAL;var init_session_mode_check=__esm({"libs/sdk/src/transport/session-mode.check.ts"(){"use strict";warned=new WeakSet;REMOVAL="is ignored and will be removed in the next major"}});async function registerServerEntries(providers,entries,appIds){if(!entries.tools?.length&&!entries.resources?.length)return;if(appIds.includes(serverEntryOwner.id))throw new ReservedAppIdError(serverEntryOwner.id);const registries=[];if(entries.tools?.length){registries.push(new ToolRegistry(providers,entries.tools,serverEntryOwner,{adopt:false}).ready)}if(entries.resources?.length){registries.push(new ResourceRegistry(providers,entries.resources,serverEntryOwner,{adopt:false}).ready)}await Promise.all(registries)}var init_server_entries_helper=__esm({"libs/sdk/src/scope/server-entries.helper.ts"(){"use strict";init_errors();init_resource_registry();init_tool_registry();init_lineage_utils()}});function reportStartup(plugins,report,logger){const installed=plugins?.getPlugins()??[];for(const plugin of installed){try{plugin.reportStartupTelemetry?.({...report,pluginsCount:installed.length})}catch(error){logger.warn("A plugin failed to report startup telemetry",{error:error instanceof Error?error.message:String(error)})}}}var init_startup_report_helper=__esm({"libs/sdk/src/scope/startup-report.helper.ts"(){"use strict"}});function constantTimeEquals(a,b){const encoder6=new TextEncoder;return(0,import_utils86.timingSafeEqual)((0,import_utils86.sha256)(encoder6.encode(a)),(0,import_utils86.sha256)(encoder6.encode(b)))}function quoteHeaderParam(value){return value.replace(/[^\x20-\x21\x23-\x7e]/g,"")}function buildStaticChallenge(options,description){const scheme=options.scheme.trim();if(!scheme)return"";const parts=[`${quoteHeaderParam(scheme)} realm="${quoteHeaderParam(options.realm)}"`];if(description){parts.push('error="invalid_token"',`error_description="${quoteHeaderParam(description)}"`)}return parts.join(", ")}var import_reflect_metadata19,import_auth40,import_lazy_zod72,import_utils86,inputSchema19,stateSchema19,UnauthorizedSchema,AuthorizedSchema,ForbiddenSchema,sessionVerifyOutputSchema,plan19,name19,Stage19,warnedUnpinnedAudience,SessionVerifyFlow;var init_session_verify_flow=__esm({"libs/sdk/src/auth/flows/session.verify.flow.ts"(){"use strict";init_common();import_reflect_metadata19=require("reflect-metadata");import_auth40=require("@frontmcp/auth");import_lazy_zod72=require("@frontmcp/lazy-zod");import_utils86=require("@frontmcp/utils");init_notification_service();init_skill_mode_utils();init_session_id_utils();inputSchema19=httpRequestInputSchema.extend({sessionless:import_lazy_zod72.z.boolean().optional()});stateSchema19=import_lazy_zod72.z.object({baseUrl:import_lazy_zod72.z.string().min(1),authorizationHeader:import_lazy_zod72.z.string().optional(),token:import_lazy_zod72.z.string().optional(),sessionIdHeader:import_lazy_zod72.z.string().optional(),sessionProtocol:import_lazy_zod72.z.string().optional(),userAgent:import_lazy_zod72.z.string().optional(),prmMetadataPath:import_lazy_zod72.z.string().optional(),prmMetadataHeader:import_lazy_zod72.z.string().optional(),prmUrl:import_lazy_zod72.z.string().optional(),jwtPayload:import_lazy_zod72.z.object({}).passthrough().optional(),user:import_auth5.userClaimSchema.optional(),session:sessionIdSchema.optional()});UnauthorizedSchema=import_lazy_zod72.z.object({kind:import_lazy_zod72.z.literal("unauthorized"),prmMetadataHeader:import_lazy_zod72.z.string().describe("Path to protected resource metadata")}).describe("401 Unauthorized with 'WWW-Authenticate' header for requesting authentication");AuthorizedSchema=import_lazy_zod72.z.object({kind:import_lazy_zod72.z.literal("authorized"),authorization:authorizationSchema.describe("Session information if session id is present")}).describe("Authorized session information");ForbiddenSchema=import_lazy_zod72.z.object({kind:import_lazy_zod72.z.literal("forbidden"),prmMetadataHeader:import_lazy_zod72.z.string().describe("WWW-Authenticate header with insufficient_scope error")}).describe("403 Forbidden \u2014 token valid but insufficient scope");sessionVerifyOutputSchema=import_lazy_zod72.z.union([UnauthorizedSchema,AuthorizedSchema,ForbiddenSchema]);plan19={pre:["parseInput","handleStaticToken","handlePublicMode","handleAnonymousFallback","requireAuthorizationHeader","verifyIfJwt"],execute:["deriveUser","parseSessionHeader","buildAuthorizedOutput"]};name19="session:verify";Stage19=StageHookOf(name19);warnedUnpinnedAudience=false;SessionVerifyFlow=class extends FlowBase{logger=this.scopeLogger.child("SessionVerifyFlow");maskSub(sub){if(!sub)return"***";if(sub.length<=10)return"***"+sub.slice(-4);return sub.slice(0,6)+"***"+sub.slice(-4)}createAnonymousSession(options){const{authMode,subject,sessionIdHeader}=options;this.logger.verbose("createAnonymousSession",{authMode,hasExistingSession:!!sessionIdHeader});if(this.rawInput.sessionless){this.respond({kind:"authorized",authorization:{token:"",user:(0,import_auth40.anonymousCallerClaims)(options,(0,import_utils86.randomUUID)())}});return}const machineId=(0,import_utils86.getMachineId)();const authSignature=subject?`${authMode}:${subject}`:authMode;if(sessionIdHeader){const body=this.rawInput.request.body;const isInitialize2=typeof body==="object"&&body!==null&&"method"in body&&body.method==="initialize";const decrypted=decryptPublicSession(sessionIdHeader,authSignature);const existingPayload=decrypted&&isInitialize2&&decrypted.nodeId!==machineId?void 0:decrypted;if(existingPayload){const anonId=existingPayload.uuid??`${existingPayload.iat*1e3}`;const user2=(0,import_auth40.anonymousCallerClaims)(options,anonId);this.respond({kind:"authorized",authorization:{token:"",user:user2,session:{id:sessionIdHeader,payload:existingPayload}}});return}this.logger.verbose("createAnonymousSession: ignoring unrecognized client session id; minting a fresh one")}const now=Date.now();const uuid=(0,import_utils86.randomUUID)();const user=(0,import_auth40.anonymousCallerClaims)(options,uuid);const platformDetectionConfig=this.scope.metadata.transport?.platformDetection;const platformType=detectPlatformFromUserAgent(this.state.userAgent,platformDetectionConfig);const payload={uuid,nodeId:machineId,authSig:authSignature,iat:Math.floor(now/1e3),isPublic:authMode==="public",authMode,...platformType!=="unknown"&&{platformType},...detectSkillsOnlyMode(this.rawInput.request.query)&&{skillsOnlyMode:true}};const sessionId=(0,import_auth40.encryptJson)(payload);this.respond({kind:"authorized",authorization:{token:"",user,session:{id:sessionId,payload}}})}async parseInput(){const{request}=this.rawInput;const entryPath=normalizeEntryPrefix(this.scope.entryPath);const routeBase=normalizeScopeBase(this.scope.routeBase);const baseUrl=getRequestBaseUrl(request,entryPath);const authorizationHeader=request.headers?.["authorization"]??void 0;const httpTransportHeader=request.headers?.["http-transport"];const sessionIdRawHeader=request.headers?.["mcp-session-id"];const sessionIdQuery=request.query["sessionId"];const sessionIdHeader=sessionIdRawHeader??sessionIdQuery??void 0;const sessionProtocol=httpTransportHeader?"http":sessionIdRawHeader?"streamable-http":sessionIdQuery?"sse":void 0;const token=(0,import_auth40.extractBearerToken)(authorizationHeader);const userAgent=request.headers?.["user-agent"]??void 0;const prmMetadataPath=`/.well-known/oauth-protected-resource${entryPath}${routeBase}`;const prmUrl=`${getRequestBaseUrl(request)}${prmMetadataPath}`;const prmMetadataHeader=(0,import_auth40.buildUnauthorizedHeader)(prmUrl);this.logger.verbose("parseInput",{hasAuthHeader:!!authorizationHeader,hasToken:!!token,sessionProtocol,hasSessionId:!!sessionIdHeader});this.state.set({baseUrl,authorizationHeader,token,sessionIdHeader,sessionProtocol,userAgent,prmMetadataPath,prmMetadataHeader,prmUrl})}async handleStaticToken(){const authOptions=this.scope.auth?.options;if(!authOptions||!(0,import_auth13.isStaticMode)(authOptions))return;const options=authOptions;const presented=this.readStaticCredential(options);if(!presented){this.logger.warn("handleStaticToken: no credential presented, returning 401");this.respond({kind:"unauthorized",prmMetadataHeader:buildStaticChallenge(options)});return}const matched=options.tokens.reduce((found,candidate)=>constantTimeEquals(candidate,presented)?candidate:found,void 0);if(!matched){this.logger.warn("handleStaticToken: credential did not match, returning 401");this.respond({kind:"unauthorized",prmMetadataHeader:buildStaticChallenge(options,"The access token is invalid")});return}this.logger.verbose("handleStaticToken: credential accepted");this.createAnonymousSession({authMode:"static",issuer:"static",scopes:options.scopes,subject:`static:${(0,import_utils86.sha256Hex)(matched).slice(0,12)}`,sessionIdHeader:this.state.sessionIdHeader})}readStaticCredential(options){const headers=this.rawInput.request.headers??{};const raw=headers[options.header.toLowerCase()];const value=(Array.isArray(raw)?raw[0]:raw)?.trim();if(!value)return void 0;const{scheme}=options;if(!scheme)return value;if(value.slice(0,scheme.length).toLowerCase()!==scheme.toLowerCase())return void 0;if(value[scheme.length]!==" ")return void 0;return value.slice(scheme.length+1).trim()||void 0}async handlePublicMode(){const authOptions=this.scope.auth?.options;if(!authOptions||!(0,import_auth13.isPublicMode)(authOptions)){return}if(this.state.token&&(0,import_auth40.isJwt)(this.state.token)){return}if(this.state.token){this.logger.verbose("handlePublicMode: ignoring non-JWT bearer token (public mode has nothing to verify it against)")}this.logger.verbose("handlePublicMode: allowing anonymous access (public mode)");this.createAnonymousSession({authMode:"public",issuer:"public",scopes:authOptions.anonymousScopes??["anonymous"],sessionIdHeader:this.state.sessionIdHeader})}async handleAnonymousFallback(){this.logger.verbose("handleAnonymousFallback: creating anonymous session (transparent-anon)");const authOptions=this.scope.auth?.options;const scopes=authOptions?.anonymousScopes??["anonymous"];this.createAnonymousSession({authMode:"transparent-anon",issuer:"transparent-anon",scopes,sessionIdHeader:this.state.sessionIdHeader})}async requireAuthorizationOrChallenge(){this.logger.verbose("requireAuthorizationOrChallenge: returning 401");this.respond({kind:"unauthorized",prmMetadataHeader:this.state.required.prmMetadataHeader})}async verifyIfJwt(){const jwks=this.get(import_auth40.JwksService);const token=this.state.token;if(!token){this.logger.warn("verifyIfJwt: missing or empty bearer token, returning 401");this.respond({kind:"unauthorized",prmMetadataHeader:this.state.required.prmMetadataHeader});return}if(!(0,import_auth40.isJwt)(token)){this.logger.warn("verifyIfJwt: token is not a JWT, returning 401");this.respond({kind:"unauthorized",prmMetadataHeader:(0,import_auth40.buildInvalidTokenHeader)(this.state.required.prmUrl,"Token is not a valid JWT")});return}const auth=this.scope.auth;if(!auth){this.logger.warn("verifyIfJwt: auth registry not available, returning 401");this.respond({kind:"unauthorized",prmMetadataHeader:this.state.required.prmMetadataHeader});return}let verify;const authOptions=auth.options;const mode=(0,import_auth13.isTransparentMode)(authOptions)?"transparent":"gateway";this.logger.verbose(`verifyIfJwt: verifying using ${mode} mode`);if((0,import_auth13.isTransparentMode)(authOptions)){const primary=authOptions;const issuer=auth.issuer;const providerRefs=[{id:primary.providerConfig?.id??"default",issuerUrl:issuer,additionalIssuers:primary.providerConfig?.additionalIssuers,verifyIssuer:primary.providerConfig?.verifyIssuer,jwks:primary.providerConfig?.jwks,jwksUri:primary.providerConfig?.jwksUri}];verify=jwks.verifyTransparentToken(token,providerRefs)}else{const configuredAudience=(0,import_auth13.isOrchestratedMode)(authOptions)?authOptions.expectedAudience:void 0;const resource=computeResource(this.rawInput.request,this.scope.entryPath,this.scope.routeBase);const issuer=auth.acceptedIssuersFor?.(this.rawInput.request);verify=auth.verifyGatewayToken(token,this.state.required.baseUrl,configuredAudience??resource,issuer)}const result=await verify;if(result.ok){this.state.set({jwtPayload:result.payload});if((0,import_auth13.isTransparentMode)(authOptions)){const configuredAudience=authOptions.expectedAudience;if(!configuredAudience&&!isPublicUrlPinned()&&!warnedUnpinnedAudience){warnedUnpinnedAudience=true;this.logger.warn("transparent audience validation is deriving the expected audience from the request Host: set auth.expectedAudience or FRONTMCP_PUBLIC_URL to bind tokens to a fixed resource. X-Forwarded-Host is ignored unless FRONTMCP_TRUST_PROXY is enabled.")}const expectedAudiences=configuredAudience?Array.isArray(configuredAudience)?configuredAudience:[configuredAudience]:(0,import_auth40.deriveExpectedAudience)(this.state.required.baseUrl);const audResult=(0,import_auth40.validateAudience)(result.payload?.["aud"],{expectedAudiences,allowNoAudience:authOptions.requireAudience!==true});if(!audResult.valid){this.logger.warn("verifyIfJwt: audience validation failed",{error:audResult.error});this.respond({kind:"unauthorized",prmMetadataHeader:(0,import_auth40.buildInvalidTokenHeader)(this.state.required.prmUrl,audResult.error??"Token audience is not valid for this resource")});return}}const requiredScopes=authOptions?.["requiredScopes"];if(requiredScopes&&requiredScopes.length>0){const tokenScopes=(0,import_auth40.scopesFromClaims)(result.payload);const hasAll=requiredScopes.every(s=>tokenScopes.includes(s));if(!hasAll){this.logger.warn("verifyIfJwt: insufficient scopes",{required:requiredScopes,actual:tokenScopes});this.respond({kind:"forbidden",prmMetadataHeader:(0,import_auth40.buildInsufficientScopeHeader)(this.state.required.prmUrl,requiredScopes)});return}}return}this.logger.warn("verifyIfJwt: JWT verification failed",{error:result.error});this.respond({kind:"unauthorized",prmMetadataHeader:(0,import_auth40.buildInvalidTokenHeader)(this.state.required.prmUrl,result.error??"Token verification failed")})}async deriveUser(){const user=(0,import_auth40.deriveTypedUser)(this.state.required.jwtPayload??{});if(!user.sub){this.logger.warn("deriveUser: verified token has no sub, client_id or azp claim, returning 401");this.respond({kind:"unauthorized",prmMetadataHeader:(0,import_auth40.buildInvalidTokenHeader)(this.state.required.prmUrl,"Token has no subject: the sub, client_id and azp claims are all missing")});return}this.state.set("user",user)}async parseSessionHeader(){const{sessionIdHeader,required:{token}}=this.state;const session=parseSessionHeader(sessionIdHeader,token);this.logger.verbose("parseSessionHeader",{hasSessionId:!!sessionIdHeader,parsed:!!session});if(session){this.state.set("session",session)}}async buildAuthorizedOutput(){const{required:{token,user},session}=this.state;this.logger.verbose("Session verified successfully",{sub:this.maskSub(user.sub),hasSession:!!session});this.respond({kind:"authorized",authorization:{token,user,session}})}};__decorateClass([Stage19("parseInput")],SessionVerifyFlow.prototype,"parseInput",1);__decorateClass([Stage19("handleStaticToken",{filter:({scope})=>{const authOptions=scope.auth?.options;return!!authOptions&&(0,import_auth13.isStaticMode)(authOptions)}})],SessionVerifyFlow.prototype,"handleStaticToken",1);__decorateClass([Stage19("handlePublicMode")],SessionVerifyFlow.prototype,"handlePublicMode",1);__decorateClass([Stage19("handleAnonymousFallback",{filter:({state,scope})=>{if(state.token)return false;const authOptions=scope.auth?.options;if(!authOptions||!(0,import_auth13.isTransparentMode)(authOptions))return false;return authOptions.allowAnonymous===true}})],SessionVerifyFlow.prototype,"handleAnonymousFallback",1);__decorateClass([Stage19("requireAuthorizationHeader",{filter:({state,scope})=>{if(state.authorizationHeader)return false;const authOptions=scope.auth?.options;if(authOptions&&(0,import_auth13.isPublicMode)(authOptions))return false;if(authOptions&&(0,import_auth13.isTransparentMode)(authOptions)){if(authOptions.allowAnonymous===true)return false}return true}})],SessionVerifyFlow.prototype,"requireAuthorizationOrChallenge",1);__decorateClass([Stage19("verifyIfJwt")],SessionVerifyFlow.prototype,"verifyIfJwt",1);__decorateClass([Stage19("deriveUser")],SessionVerifyFlow.prototype,"deriveUser",1);__decorateClass([Stage19("parseSessionHeader")],SessionVerifyFlow.prototype,"parseSessionHeader",1);__decorateClass([Stage19("buildAuthorizedOutput")],SessionVerifyFlow.prototype,"buildAuthorizedOutput",1);SessionVerifyFlow=__decorateClass([FrontMcpFlow({name:name19,plan:plan19,inputSchema:inputSchema19,outputSchema:sessionVerifyOutputSchema,access:"authorized"})],SessionVerifyFlow)}});var DEFAULT_FRONTMCP_NODE_COOKIE,DEFAULT_FRONTMCP_MACHINE_ID_HEADER;var init_ha_constants=__esm({"libs/sdk/src/ha/ha.constants.ts"(){"use strict";DEFAULT_FRONTMCP_NODE_COOKIE="__frontmcp_node";DEFAULT_FRONTMCP_MACHINE_ID_HEADER="X-FrontMCP-Machine-Id"}});function machineIdHeader(){if((0,import_utils87.getRuntimeContext)().deployment!=="distributed")return void 0;return[DEFAULT_FRONTMCP_MACHINE_ID_HEADER,(0,import_utils87.getMachineId)()]}function applyMachineIdHeader(response){const header=machineIdHeader();if(!header)return false;response.setHeader(header[0],header[1]);return true}function affinityCookieOptions(){const name48=(0,import_utils87.getEnv)("FRONTMCP_AFFINITY_COOKIE")?.trim()||DEFAULT_FRONTMCP_NODE_COOKIE;const domain=(0,import_utils87.getEnv)("FRONTMCP_AFFINITY_COOKIE_DOMAIN")?.trim()||void 0;const rawSameSite=(0,import_utils87.getEnv)("FRONTMCP_AFFINITY_COOKIE_SAMESITE")?.trim().toLowerCase();const sameSite=rawSameSite==="strict"?"Strict":rawSameSite==="lax"?"Lax":rawSameSite==="none"?"None":void 0;return{name:name48,...domain?{domain}:{},...sameSite?{sameSite}:{}}}function applyNodeAffinity(response,request){if(!applyMachineIdHeader(response))return;const cookie=(0,import_utils87.buildSetCookie)({...affinityCookieOptions(),value:(0,import_utils87.getMachineId)()},request);if(!cookie)return;const existing=response.getHeader("Set-Cookie");const existingArr=Array.isArray(existing)?existing:existing?[String(existing)]:[];response.setHeader("Set-Cookie",[...existingArr,cookie])}var import_utils87;var init_ha_headers=__esm({"libs/sdk/src/ha/ha-headers.ts"(){"use strict";import_utils87=require("@frontmcp/utils");init_ha_constants()}});function withoutQuery(url){const end=url.search(/[?#]/);return end===-1?url:`${url.slice(0,end)}?${REDACTED}`}function headerValueForLog(name48,value){const key=name48.toLowerCase();if(CREDENTIAL_HEADERS.has(key)||CREDENTIAL_HEADER_WORDS.test(key))return REDACTED;if(SESSION_ID_HEADER.test(key))return`${String(value).slice(0,8)}...`;if(REFERER_HEADERS.has(key)){return Array.isArray(value)?value.map(entry=>withoutQuery(String(entry))):withoutQuery(String(value))}return value}function headersForLog(headers){return Object.fromEntries(Object.entries(headers).map(([key,value])=>[key,headerValueForLog(key,value)]))}var REDACTED,CREDENTIAL_HEADERS,CREDENTIAL_HEADER_WORDS,SESSION_ID_HEADER,REFERER_HEADERS;var init_request_log_redaction=__esm({"libs/sdk/src/scope/flows/request-log.redaction.ts"(){"use strict";REDACTED="[REDACTED]";CREDENTIAL_HEADERS=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-api-key","x-frontmcp-dashboard-token"]);CREDENTIAL_HEADER_WORDS=/(?:^|-)(?:auth|authorization|token|secret|password|passwd|credential|credentials|key|apikey|signature|cookie)(?:-|$)/;SESSION_ID_HEADER=/(?:^|-)session-id$/;REFERER_HEADERS=new Set(["referer","referrer"])}});var persistent_session_owner_exports={};__export(persistent_session_owner_exports,{claimPersistentSession:()=>claimPersistentSession,persistentSessionCallerKey:()=>persistentSessionCallerKey});function persistentSessionCallerKey(authorization){const sub=authorization?.user?.sub;if(!(0,import_auth41.isAnonymousSubject)(sub)){const iss=authorization?.user?.iss;return`sub:${(0,import_utils88.sha256Hex)(JSON.stringify([typeof iss==="string"?iss:"",sub]))}`}if(authorization?.token)return`token:${(0,import_utils88.sha256Hex)(authorization.token)}`;return null}function claimPersistentSession(session,callerKey,store){if(!owners.has(session)&&store&&store.initial!==void 0){owners.set(session,store.initial)}if(!owners.has(session)){owners.set(session,callerKey);return"claimed"}return owners.get(session)===callerKey?"owner":"refused"}var import_auth41,import_utils88,owners;var init_persistent_session_owner=__esm({"libs/sdk/src/transport/persistent-session-owner.ts"(){"use strict";import_auth41=require("@frontmcp/auth");import_utils88=require("@frontmcp/utils");owners=new WeakMap}});function parseByteLimit(limit){if(typeof limit==="number"&&Number.isFinite(limit)&&limit>=0)return limit;if(typeof limit==="string"){const match=/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb)?$/i.exec(limit.trim());if(match)return Math.floor(Number(match[1])*BYTE_UNITS[(match[2]??"b").toLowerCase()])}return DEFAULT_BODY_LIMIT_BYTES}function mcpTransportBodyLimit(limit){return Math.max(1,parseByteLimit(limit))}var DEFAULT_BODY_LIMIT_BYTES,BYTE_UNITS;var init_body_limit=__esm({"libs/sdk/src/transport/body-limit.ts"(){"use strict";DEFAULT_BODY_LIMIT_BYTES=4*1024*1024;BYTE_UNITS={b:1,kb:1024,mb:1024**2,gb:1024**3}}});var web_standard_mcp_exports={};__export(web_standard_mcp_exports,{buildPersistentWebStandardMcp:()=>buildPersistentWebStandardMcp,runWebStandardMcp:()=>runWebStandardMcp});async function wireServer(scope,serverOptions,sessionId,sessionIdGenerator,enableJsonResponse){const{createMcpHandlers:createMcpHandlers2}=await Promise.resolve().then(()=>(init_mcp_handlers(),mcp_handlers_exports));const mcpServer=new import_protocol50.McpServer(scope.metadata.info,serverOptions);const composeInstructions=caller=>composeCallerInstructions(scope,{ctx:caller,skillUriHints:true});for(const handler of createMcpHandlers2({scope,serverOptions,composeInstructions})){const originalHandler=handler.handler;const wrappedHandler=async(req,ctx)=>{const existingAuthInfo=ctx?.["authInfo"]??{};const enrichedCtx={...ctx,authInfo:{...existingAuthInfo,sessionId}};return originalHandler(req,enrichedCtx)};mcpServer.setRequestHandler(handler.requestSchema,wrappedHandler)}const transport=new import_protocol50.WebStandardStreamableHTTPServerTransport({sessionIdGenerator,enableJsonResponse,maxRequestBodySize:mcpTransportBodyLimit(scope.metadata.http?.bodyLimit)});await mcpServer.connect(transport);return{mcpServer,transport}}async function buildPersistentWebStandardMcp(scope,options){const serverOptions=buildScopedServerOptions(scope);const pair=await wireServer(scope,serverOptions,options.sessionId,()=>options.sessionId,false);return options.owner?{...pair,owner:options.owner}:pair}async function runWebStandardMcp(scope,request,options){if(options.persistent){return options.persistent.transport.handleRequest(request,{authInfo:options.authInfo})}const sessionId=`web:${(0,import_utils89.randomUUID)()}`;const accept=request.headers.get("accept")??"";const wantsStream=request.method==="GET"||options.sse&&accept.includes("text/event-stream");const{mcpServer,transport}=await wireServer(scope,options.serverOptions,sessionId,void 0,!wantsStream);const response=await transport.handleRequest(request,{authInfo:options.authInfo});if(response.headers.get("content-type")?.includes("text/event-stream")){const closed=new Promise(resolve=>{const prev=transport.onclose;transport.onclose=()=>{prev?.();resolve()}});const teardown=closed.then(()=>mcpServer.close().catch(()=>void 0));if(options.ctx?.waitUntil)options.ctx.waitUntil(teardown);else void teardown}else{void mcpServer.close().catch(()=>void 0)}return response}var import_protocol50,import_utils89;var init_web_standard_mcp=__esm({"libs/sdk/src/transport/web-standard-mcp.ts"(){"use strict";import_protocol50=require("@frontmcp/protocol");import_utils89=require("@frontmcp/utils");init_skill_instructions_helper();init_body_limit();init_build_scoped_server_options()}});var import_auth42,import_guard8,import_lazy_zod73,import_utils90,plan20,httpRequestStateSchema,name20,Stage20,HttpRequestFlow;var init_http_request_flow=__esm({"libs/sdk/src/scope/flows/http.request.flow.ts"(){"use strict";import_auth42=require("@frontmcp/auth");import_guard8=require("@frontmcp/guard");import_lazy_zod73=require("@frontmcp/lazy-zod");import_utils90=require("@frontmcp/utils");init_session_verify_flow();init_common();init_schema7();init_errors();init_ha_headers();init_skill_mode_utils();init_mcp_20260728();init_request_log_redaction();plan20={pre:["traceRequest","checkIpFilter","relayToSessionOwner","acquireQuota","acquireSemaphore","checkAuthorization","acquireIdentityQuota","resolveSkillsOnlyMode","router"],execute:["checkPersistentSessionOwner","handleMcp2026","handleWebFetch","handleLegacySse","handleSse","handleStreamableHttp","handleStatefulHttp","handleStatelessHttp","applyDeleteNodeHeaders","handleDeleteSession"],finalize:["audit","metrics","releaseSemaphore","releaseQuota","finalize"],error:[]};httpRequestStateSchema=import_lazy_zod73.z.object({decision:decisionSchema,intent:intentSchema,verifyResult:sessionVerifyOutputSchema});name20="http:request";({Stage:Stage20}=FlowHooksOf("http:request"));HttpRequestFlow=class extends FlowBase{logger=this.scope.logger.child("HttpRequestFlow");requestStartTime=0;requestId="";static canActivate(request,scope){const requestPath=normalizeEntryPrefix(request.path);const prefix=normalizeEntryPrefix(scope.entryPath);const scopePath=normalizeScopeBase(scope.routeBase);const basePath=`${prefix}${scopePath}`;return requestPath===basePath||requestPath===`${basePath}/sse`||requestPath===`${basePath}/message`}async traceRequest(){const{request}=this.rawInput;this.requestStartTime=Date.now();const ctx=this.tryGetContext();this.requestId=ctx?.requestId??`req-${(0,import_utils90.randomUUID)()}`;const headers=request.headers??{};const body=request.body;const userAgent=headers["user-agent"];const contentType2=headers["content-type"];const accept=headers["accept"];const sessionId=ctx?.sessionId??headers["mcp-session-id"]??"no-session";this.logger.info(`[${this.requestId}] \u25B6 ${request.method} ${request.path}`,{requestId:this.requestId,traceId:ctx?.traceContext.traceId?.slice(0,16),method:request.method,path:request.path,userAgent:userAgent?.slice(0,50),sessionId:sessionId?.slice(0,20),contentType:contentType2,accept,hasBody:!!request.body,bodyMethod:body?.["method"]});this.logger.debug(`[${this.requestId}] HEADERS`,{headers:headersForLog(headers)})}async checkIpFilter(){enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp,()=>httpRespond.json({jsonrpc:"2.0",id:this.jsonRpcRequestId(),error:{code:-32001,message:"Forbidden: client IP rejected by ipFilter"}},{status:403}))}async relayToSessionOwner(){const transportService=this.scope.transportService;if(!transportService)return;const{request,response}=this.rawInput;const owner=await transportService.findRemoteSessionOwner(request);if(!owner)return;this.logger.verbose(`[${this.requestId}] relaying to session owner ${owner.nodeId}`);try{await transportService.relayToSessionOwner(owner,request,response)}catch(error){if(!(error instanceof SessionOwnerUnreachableError))throw error;this.logger.warn(`[${this.requestId}] session owner unreachable: ${error.reason}`,{owner:owner.nodeId});this.respond(httpRespond.json({jsonrpc:"2.0",id:this.jsonRpcRequestId(),error:{code:-32e3,message:error.getPublicMessage()}},{status:error.statusCode,headers:{"Retry-After":String(error.retryAfterSeconds)}}));return}this.handled()}async acquireQuota(){const manager=this.scope.rateLimitManager;const globalConfig=manager?.config?.global;if(!manager||!globalConfig||partitionsByIdentity(globalConfig.partitionBy))return;await this.enforceGlobalRateLimit(manager)}async acquireIdentityQuota(){const manager=this.scope.rateLimitManager;const globalConfig=manager?.config?.global;if(!manager||!globalConfig||!partitionsByIdentity(globalConfig.partitionBy))return;await this.enforceGlobalRateLimit(manager)}async enforceGlobalRateLimit(manager){const context=this.tryGetContext();let result;try{result=await manager.checkGlobalRateLimit(buildPartitionContext(context))}catch(error){if(!(error instanceof import_guard8.GuardStorageUnavailableError))throw error;this.logger.warn(`[${this.requestId}] acquireQuota: ${error.message}`);this.respond(httpRespond.json({jsonrpc:"2.0",id:this.jsonRpcRequestId(),error:{code:-32603,message:"Service temporarily unavailable: the rate-limit store cannot be reached",data:{code:error.code}}},{status:error.statusCode,headers:{"Retry-After":"1"}}));return}context?.set(GLOBAL_RATE_LIMIT_CHECKED,true);if(result.allowed)return;const retryAfter=Math.ceil((result.retryAfterMs??6e4)/1e3);this.respond(httpRespond.json({jsonrpc:"2.0",id:this.jsonRpcRequestId(),error:{code:-32029,message:`Rate limit exceeded. Retry after ${retryAfter} seconds`}},{status:429,headers:{"Retry-After":String(retryAfter)}}))}jsonRpcRequestId(){const requestBody=this.rawInput.request.body;return requestBody?.id??null}async checkAuthorization(){const{request}=this.rawInput;this.logger.verbose(`[${this.requestId}] checkAuthorization: verifying session`);try{const result=await this.scope.runFlow("session:verify",{request,sessionless:this.servesProtocol20260728()});if(!result){this.logger.error(`[${this.requestId}] failed to verify session`);throw new SessionVerificationFailedError}this.state.set({verifyResult:result});if(result.kind==="authorized"&&result.authorization){const ctx=this.tryGetContext();if(ctx){const{token,user}=result.authorization;const presentedSessionId=this.servesProtocol20260728()?void 0:sessionIdPresentedBy(request);ctx.updateAuthInfo(authInfoFromAuthorization(result.authorization,presentedSessionId));await this.bindOrchestrationAccessor(ctx,token,user)}}}catch(error){if(!(error instanceof FlowControl)){this.logError(error,"checkAuthorization")}throw error}}async bindOrchestrationAccessor(ctx,token,user){const auth=this.scope.auth;const mode=auth?.options?.mode;const isOrchestrated=mode==="local"||mode==="remote";if(!token||!auth?.orchestratedTokenStore||!isOrchestrated){return}const tokenStore=auth.orchestratedTokenStore;let providers;try{const authorizationId=(0,import_auth42.deriveAuthorizationId)(token);const providerIds=await tokenStore.getProviderIds(authorizationId);providers=Object.fromEntries(providerIds.map(id=>[id,{id}]))}catch(err){this.logger.warn(`[${this.requestId}] failed to load orchestrated providers: ${String(err)}`)}const authorization=import_auth42.OrchestratedAuthorization.create({token,user:{sub:user.sub??"unknown",name:user.name,email:user.email,picture:user.picture},expiresAt:user.exp?user.exp*1e3:void 0,tokenStore,onTokenRefresh:auth.providerTokenRefresher?.(),providers});ctx.setContextToken(import_auth42.ORCHESTRATED_AUTH_ACCESSOR,new import_auth42.OrchestratedAuthAccessorAdapter(authorization))}servesProtocol20260728(){const{request}=this.rawInput;const isWebMode=!!request[ServerRequestTokens.webRequest];const defaultProtocolVersion=this.scope.metadata.transport?.defaultProtocolVersion??(isWebMode?"2026-07-28":"legacy");return isProtocol20260728Request({headers:request.headers,body:request.body,defaultVersion:defaultProtocolVersion})}async resolveSkillsOnlyMode(){if(detectSkillsOnlyMode(this.rawInput.request.query))this.tryGetContext()?.set(SKILLS_ONLY_REQUEST,true)}async router(){try{const{request}=this.rawInput;this.logger.verbose(`[${this.requestId}] router: check request decision`);const transportConfig=this.scope.metadata.transport;if(!transportConfig){this.logger.error(`[${this.requestId}] transport config not found in scope metadata`);this.respond(httpRespond.json({error:"Internal Server Error",message:"Transport configuration missing"},{status:500}));return}const legacyFlags=toLegacyProtocolFlags(transportConfig.protocol);this.logger.debug(`[${this.requestId}] transport config`,{protocol:transportConfig.protocol,enableLegacySSE:legacyFlags.enableLegacySSE,enableStreamableHttp:legacyFlags.enableStreamableHttp,path:request.path,accept:request.headers?.["accept"]});const decision=decideIntent(request,{...legacyFlags,tolerateMissingAccept:true});const isWebMode=!!request[ServerRequestTokens.webRequest];if(isWebMode&&decision.intent==="unknown"){decision.intent="stateless-http"}this.logger.debug(`[${this.requestId}] decision result`,{intent:decision.intent,reasons:decision.reasons,debug:decision.debug});if(this.servesProtocol20260728()){const verify=this.state.required.verifyResult;if(verify.kind==="authorized"){request[ServerRequestTokens.auth]=verify.authorization}else if(verify.kind==="forbidden"){this.logger.warn(`[${this.requestId}] mcp-20260728: forbidden, insufficient scope`);this.respond(httpRespond.forbidden({headers:challengeHeaders(verify.prmMetadataHeader)}));return}else{this.logger.warn(`[${this.requestId}] mcp-20260728: unauthorized`);this.respond(httpRespond.unauthorized({headers:challengeHeaders(verify.prmMetadataHeader)}));return}this.logger.verbose(`[${this.requestId}] routing to mcp-20260728 pipeline`);this.state.set("intent","mcp-20260728");return}const routerBody=request.body;const isJsonRpcRequest=request.method.toUpperCase()!=="DELETE"&&routerBody&&typeof routerBody==="object"&&routerBody["jsonrpc"]==="2.0"&&typeof routerBody["method"]==="string"&&routerBody["method"]!=="initialize";const respondNoSession=()=>{const requestId=routerBody?.["id"]??null;return this.respond({kind:"json",status:200,contentType:"application/json; charset=utf-8",body:{jsonrpc:"2.0",id:requestId,error:{code:-32600,message:"Session not initialized \u2014 send `initialize` first",data:{transport:"streamable-http",expected:"initialize"}}}})};if(request.method.toUpperCase()==="DELETE"){this.logger.verbose(`[${this.requestId}] DELETE request, using decision intent: ${decision.intent}`);if(decision.intent==="unknown"){this.logger.verbose(`[${this.requestId}] DELETE with unknown intent, forwarding to next middleware`);this.next();return}const deleteVerify=this.state.required.verifyResult;const requestedSessionId=request[ServerRequestTokens.sessionId]??request.headers["mcp-session-id"]??request.query?.["sessionId"];const deleteAuthz=authorizeSessionTermination(deleteVerify,requestedSessionId);if(request[ServerRequestTokens.webTransport]&&deleteAuthz.kind!=="unauthorized"){request[ServerRequestTokens.auth]=deleteVerify.authorization;this.state.set("intent",decision.intent);return}if(deleteAuthz.kind==="unauthorized"){this.logger.warn(`[${this.requestId}] DELETE session denied: request is not authenticated`);this.respond(httpRespond.unauthorized({headers:challengeHeaders(deleteVerify.prmMetadataHeader??"Bearer")}));return}if(deleteAuthz.kind==="forbidden"){this.logger.warn(`[${this.requestId}] DELETE session denied: caller does not own the requested session id`);this.respond(httpRespond.notFound("Session not found"));return}request[ServerRequestTokens.auth]=deleteVerify.authorization;request[ServerRequestTokens.sessionId]=deleteAuthz.sessionId;this.state.set("intent",decision.intent);return}const{verifyResult}=this.state.required;if(verifyResult.kind==="authorized"){const{authorization}=verifyResult;request[ServerRequestTokens.auth]=authorization;if(authorization.session?.payload){const ctx=this.tryGetContext();if(ctx){ctx.updateSessionMetadata(authorization.session.payload)}}if(authorization.session){const sessionId=authorization.session.id;request[ServerRequestTokens.sessionId]=sessionId;if(this.scope.notifications.isSessionTerminated(sessionId)){const body=request.body;if(body?.method==="initialize"){this.logger.info(`[${this.requestId}] Initialize with terminated session ${sessionId.slice(0,20)}... - re-initializing`);this.scope.notifications.unmarkTerminated(sessionId);request[ServerRequestTokens.reinitialize]=true}else{this.logger.warn(`[${this.requestId}] Request to terminated session: ${sessionId.slice(0,20)}...`);this.respond(httpRespond.notFound("Session not found"));return}}const protocol=authorization.session?.payload?.protocol;if(protocol){this.logger.verbose(`[${this.requestId}] decision from session: ${protocol}`);this.state.set("intent",protocol);return}}if(decision.intent==="unknown"){if(isJsonRpcRequest){this.logger.info(`[${this.requestId}] no session, JSON-RPC body present \u2014 responding with structured error (#380)`);respondNoSession()}this.logger.verbose(`[${this.requestId}] decision is unknown, continue to next http middleware`);this.next();return}this.logger.verbose(`[${this.requestId}] decision is request info: ${decision.intent}`);this.state.set("intent",decision.intent)}else if(verifyResult.kind==="forbidden"){if(decision.intent==="unknown"){if(isJsonRpcRequest){respondNoSession()}this.logger.verbose(`[${this.requestId}] forbidden with unknown intent, continue to other public http middleware`);this.next();return}this.logger.warn(`[${this.requestId}] forbidden: insufficient scope`);this.respond(httpRespond.forbidden({headers:challengeHeaders(verifyResult.prmMetadataHeader)}))}else{this.logger.verbose(`[${this.requestId}] not authorized request, check decision intent: ${decision.intent}`);if(decision.intent==="unknown"){if(isJsonRpcRequest){respondNoSession()}this.logger.verbose(`[${this.requestId}] decision is unknown, continue to other public http middleware`);this.next();return}this.logger.warn(`[${this.requestId}] decision is ${decision.intent}, but not authorized, respond with 401`);this.respond(httpRespond.unauthorized({headers:challengeHeaders(verifyResult.prmMetadataHeader)}))}}catch(error){if(!(error instanceof FlowControl)){this.logError(error,"router")}throw error}}async checkPersistentSessionOwner(){const req=this.rawInput.request;const persistent=req[ServerRequestTokens.webTransport];if(!req[ServerRequestTokens.webRequest]||!persistent||typeof persistent!=="object")return;const{claimPersistentSession:claimPersistentSession2,persistentSessionCallerKey:persistentSessionCallerKey2}=await Promise.resolve().then(()=>(init_persistent_session_owner(),persistent_session_owner_exports));const authorization=req[ServerRequestTokens.auth];const callerKey=persistentSessionCallerKey2(authorization);const store=persistent.owner;const claim=claimPersistentSession2(persistent,callerKey,store);if(claim==="claimed"){await store?.save(callerKey);return}if(claim==="owner")return;this.logger.warn(`[${this.requestId}] Persistent session refused: it was opened by another caller`);this.respond(httpRespond.json({jsonrpc:"2.0",error:{code:-32001,message:"Session not found"},id:null},{status:404}))}async handleWebFetch(){const{request}=this.rawInput;const req=request;const webRequest=req[ServerRequestTokens.webRequest];if(!webRequest)return;try{const webCtx=req[ServerRequestTokens.webCtx];const{runWebStandardMcp:runWebStandardMcp2}=await Promise.resolve().then(()=>(init_web_standard_mcp(),web_standard_mcp_exports));const{buildScopedServerOptions:buildScopedServerOptions2}=await Promise.resolve().then(()=>(init_build_scoped_server_options(),build_scoped_server_options_exports));const{expandProtocolConfig:expandProtocolConfig2}=await Promise.resolve().then(()=>(init_schema7(),schema_exports));const scope=this.scope;const proto=expandProtocolConfig2(scope.metadata.transport?.protocol);const sse=proto.streamable&&!proto.json;const authorization=req[ServerRequestTokens.auth];const authInfo=authorization?authInfoFromAuthorization(authorization,sessionIdPresentedBy(request)):void 0;const persistent=req[ServerRequestTokens.webTransport];const response=await runWebStandardMcp2(scope,webRequest,{serverOptions:buildScopedServerOptions2(scope),authInfo,sse,ctx:webCtx,persistent});this.respond(httpRespond.webResponse(response))}catch(error){if(!(error instanceof FlowControl)){this.logError(error,"handleWebFetch")}throw error}}async handleMcp2026(){try{const response=await this.scope.runFlow("handle:mcp-202607280728",this.rawInput);if(response){this.respond(response)}this.handled()}catch(error){if(!(error instanceof FlowControl)){this.logError(error,"handleMcp2026")}throw error}}async handleLegacySse(){try{const response=await this.scope.runFlow("handle:legacy-sse",this.rawInput);if(response){this.respond(response)}this.handled()}catch(error){if(!(error instanceof FlowControl)){this.logError(error,"handleLegacySse")}throw error}}async handleSse(){try{const response=await this.scope.runFlow("handle:streamable-http",this.rawInput);if(response){this.respond(response)}this.next()}catch(error){if(!(error instanceof FlowControl)){this.logError(error,"handleSse")}throw error}}async handleStreamableHttp(){try{const response=await this.scope.runFlow("handle:streamable-http",this.rawInput);if(response){this.respond(response)}this.next()}catch(error){if(!(error instanceof FlowControl)){this.logError(error,"handleStreamableHttp")}throw error}}async handleStatefulHttp(){try{const response=await this.scope.runFlow("handle:streamable-http",this.rawInput);if(response){this.respond(response)}this.next()}catch(error){if(!(error instanceof FlowControl)){this.logError(error,"handleStatefulHttp")}throw error}}async handleStatelessHttp(){try{const response=await this.scope.runFlow("handle:stateless-http",this.rawInput);if(response){this.respond(response)}this.handled()}catch(error){if(!(error instanceof FlowControl)){this.logError(error,"handleStatelessHttp")}throw error}}async applyDeleteNodeHeaders(){applyMachineIdHeader(this.rawInput.response)}async handleDeleteSession(){try{const{request}=this.rawInput;const sessionId=request[ServerRequestTokens.sessionId]??request.headers["mcp-session-id"];if(!sessionId||typeof sessionId!=="string"){this.logger.warn(`[${this.requestId}] DELETE request without valid session ID`);this.respond(httpRespond.rpcError("No valid session ID provided"));return}this.logger.info(`[${this.requestId}] DELETE session: ${sessionId}`);this.scope.notifications.terminateSession(sessionId);const authorization=request[ServerRequestTokens.auth];const transportService=this.scope.transportService;if(authorization&&transportService){for(const protocol of["streamable-http","sse"]){try{await transportService.destroyTransporter(protocol,authorization.token??"",sessionId)}catch{}}await transportService.deleteStoredSession(sessionId)}this.logger.info(`[${this.requestId}] Session terminated: ${sessionId}`);this.respond(httpRespond.noContent())}catch(error){if(!(error instanceof FlowControl)){this.logError(error,"handleDeleteSession")}throw error}}async finalize(){const{request}=this.rawInput;const duration=Date.now()-this.requestStartTime;const intent=this.state.get("intent")??"unknown";this.logger.info(`[${this.requestId}] \u25C0 ${request.method} ${request.path} completed in ${duration}ms`,{requestId:this.requestId,method:request.method,path:request.path,duration,intent})}logError(error,context){const{request}=this.rawInput;const duration=Date.now()-this.requestStartTime;const errorMessage2=error instanceof Error?error.message:String(error);const errorName=error instanceof Error?error.name:"UnknownError";const errorStack=error instanceof Error?error.stack:void 0;const body=request.body;const errorCode=error?.code;const errorCause=error?.cause;this.logger.error(`[${this.requestId}] \u2716 ${request.method} ${request.path} failed${context?` in ${context}`:""} after ${duration}ms: ${errorMessage2||"(no message)"}`,{requestId:this.requestId,method:request.method,path:request.path,duration,context,error:{name:errorName,message:errorMessage2||"(no message)",code:errorCode,cause:errorCause instanceof Error?errorCause.message:errorCause,stack:errorStack},request:{userAgent:request.headers?.["user-agent"]?.slice(0,50),sessionId:request.headers?.["mcp-session-id"]?.slice(0,20),contentType:request.headers?.["content-type"],bodyMethod:body?.["method"],bodyId:body?.["id"]},state:{intent:this.state.get("intent"),hasVerifyResult:!!this.state.get("verifyResult")}})}};__decorateClass([Stage20("traceRequest")],HttpRequestFlow.prototype,"traceRequest",1);__decorateClass([Stage20("checkIpFilter")],HttpRequestFlow.prototype,"checkIpFilter",1);__decorateClass([Stage20("relayToSessionOwner")],HttpRequestFlow.prototype,"relayToSessionOwner",1);__decorateClass([Stage20("acquireQuota")],HttpRequestFlow.prototype,"acquireQuota",1);__decorateClass([Stage20("acquireIdentityQuota")],HttpRequestFlow.prototype,"acquireIdentityQuota",1);__decorateClass([Stage20("checkAuthorization")],HttpRequestFlow.prototype,"checkAuthorization",1);__decorateClass([Stage20("resolveSkillsOnlyMode")],HttpRequestFlow.prototype,"resolveSkillsOnlyMode",1);__decorateClass([Stage20("router")],HttpRequestFlow.prototype,"router",1);__decorateClass([Stage20("checkPersistentSessionOwner")],HttpRequestFlow.prototype,"checkPersistentSessionOwner",1);__decorateClass([Stage20("handleWebFetch")],HttpRequestFlow.prototype,"handleWebFetch",1);__decorateClass([Stage20("handleMcp2026",{filter:({state:{required:{intent}}})=>intent==="mcp-20260728"})],HttpRequestFlow.prototype,"handleMcp2026",1);__decorateClass([Stage20("handleLegacySse",{filter:({state:{required:{intent}}})=>intent==="legacy-sse"})],HttpRequestFlow.prototype,"handleLegacySse",1);__decorateClass([Stage20("handleSse",{filter:({state:{required:{intent}}})=>intent==="sse"})],HttpRequestFlow.prototype,"handleSse",1);__decorateClass([Stage20("handleStreamableHttp",{filter:({state:{required:{intent}}})=>intent==="streamable-http"})],HttpRequestFlow.prototype,"handleStreamableHttp",1);__decorateClass([Stage20("handleStatefulHttp",{filter:({state:{required:{intent}}})=>intent==="stateful-http"})],HttpRequestFlow.prototype,"handleStatefulHttp",1);__decorateClass([Stage20("handleStatelessHttp",{filter:({state:{required:{intent}}})=>intent==="stateless-http"})],HttpRequestFlow.prototype,"handleStatelessHttp",1);__decorateClass([Stage20("applyDeleteNodeHeaders",{filter:({state:{required:{intent}}})=>intent==="delete-session"})],HttpRequestFlow.prototype,"applyDeleteNodeHeaders",1);__decorateClass([Stage20("handleDeleteSession",{filter:({state:{required:{intent}}})=>intent==="delete-session"})],HttpRequestFlow.prototype,"handleDeleteSession",1);__decorateClass([Stage20("finalize")],HttpRequestFlow.prototype,"finalize",1);HttpRequestFlow=__decorateClass([FrontMcpFlow({name:name20,plan:plan20,access:"public",inputSchema:httpInputSchema,outputSchema:httpOutputSchema,middleware:{path:"/"}})],HttpRequestFlow)}});var plan21,name21,Stage21,HttpIpFilterFlow;var init_http_ip_filter_flow=__esm({"libs/sdk/src/scope/flows/http.ip-filter.flow.ts"(){"use strict";init_common();plan21={pre:["checkIpFilter"]};name21="http:ip-filter";({Stage:Stage21}=FlowHooksOf(name21));HttpIpFilterFlow=class extends FlowBase{async checkIpFilter(){enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp)}};__decorateClass([Stage21("checkIpFilter")],HttpIpFilterFlow.prototype,"checkIpFilter",1);HttpIpFilterFlow=__decorateClass([FrontMcpFlow({name:name21,plan:plan21,access:"public",inputSchema:httpInputSchema,outputSchema:httpOutputSchema})],HttpIpFilterFlow)}});var require_dist=__commonJS({"libs/storage-sqlite/dist/index.js"(exports2,module2){"use strict";var __defProp2=Object.defineProperty;var __getOwnPropDesc2=Object.getOwnPropertyDescriptor;var __getOwnPropNames2=Object.getOwnPropertyNames;var __hasOwnProp2=Object.prototype.hasOwnProperty;var __export2=(target,all)=>{for(var name48 in all)__defProp2(target,name48,{get:all[name48],enumerable:true})};var __copyProps2=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames2(from))if(!__hasOwnProp2.call(to,key)&&key!==except)__defProp2(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc2(from,key))||desc.enumerable})}return to};var __toCommonJS2=mod=>__copyProps2(__defProp2({},"__esModule",{value:true}),mod);var index_exports2={};__export2(index_exports2,{SqliteDecryptionError:()=>SqliteDecryptionError,SqliteElicitationStore:()=>SqliteElicitationStore,SqliteEventStore:()=>SqliteEventStore,SqliteKvStore:()=>SqliteKvStore,SqliteSessionStore:()=>SqliteSessionStore,SqliteStorageAdapter:()=>SqliteStorageAdapter,SqliteTaskStore:()=>SqliteTaskStore,decryptValue:()=>decryptValue,deriveEncryptionKey:()=>deriveEncryptionKey,encryptValue:()=>encryptValue,loadBetterSqlite3:()=>loadBetterSqlite3,openDatabase:()=>openDatabase,sqliteStorageOptionsSchema:()=>sqliteStorageOptionsSchema,withBusyRetry:()=>withBusyRetry});module2.exports=__toCommonJS2(index_exports2);var import_utils146=require("@frontmcp/utils");var SqliteDecryptionError=class extends Error{code="SQLITE_DECRYPTION_FAILED";constructor(){super("SqliteKvStore: failed to decrypt a stored value. The encryption secret differs from the one the database was written with (or the value is corrupted). Restore the original secret, or delete the database file to start empty.");this.name="SqliteDecryptionError"}};var HKDF_SALT=new TextEncoder().encode("frontmcp-sqlite-storage-v1");var HKDF_INFO=new TextEncoder().encode("aes-256-gcm-value-encryption");var KEY_LENGTH=32;function deriveEncryptionKey(secret){const ikm=new TextEncoder().encode(secret);return(0,import_utils146.hkdfSha256)(ikm,HKDF_SALT,HKDF_INFO,KEY_LENGTH)}var SEPARATOR=":";function encryptValue(key,plaintext){const iv=(0,import_utils146.randomBytes)(12);const plaintextBytes=new TextEncoder().encode(plaintext);const{ciphertext,tag}=(0,import_utils146.encryptAesGcm)(key,plaintextBytes,iv);return[(0,import_utils146.base64urlEncode)(iv),(0,import_utils146.base64urlEncode)(tag),(0,import_utils146.base64urlEncode)(ciphertext)].join(SEPARATOR)}function decryptValue(key,encrypted){const parts=encrypted.split(SEPARATOR);if(parts.length!==3){throw new Error("Invalid encrypted value format")}const iv=(0,import_utils146.base64urlDecode)(parts[0]);const tag=(0,import_utils146.base64urlDecode)(parts[1]);const ciphertext=(0,import_utils146.base64urlDecode)(parts[2]);try{return new TextDecoder().decode((0,import_utils146.decryptAesGcm)(key,ciphertext,iv,tag))}catch{throw new SqliteDecryptionError}}var import_utils210=require("@frontmcp/utils");var cached=null;function loadBetterSqlite3(){if(cached){return cached}const mod=require("better-sqlite3");cached=mod;return mod}var MEMORY_PATH=":memory:";var DEFAULT_BUSY_TIMEOUT_MS=5e3;function isBusyError(err){const code=err?.code;return code==="SQLITE_BUSY"||code==="SQLITE_BUSY_RECOVERY"||code==="SQLITE_BUSY_SNAPSHOT"}function sleepSync(ms){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}function withBusyRetry(operation,options={}){const attempts=options.attempts??5;const delayMs=options.delayMs??50;for(let attempt=1;;attempt++){try{return operation()}catch(err){if(!isBusyError(err)||attempt>=attempts)throw err;sleepSync(delayMs*attempt)}}}function openDatabase(path,storeName,options={}){const BetterSqlite3=loadBetterSqlite3();if(path!==MEMORY_PATH&&path!==""){const dir=(0,import_utils210.dirname)(path);if(dir&&dir!=="."){try{(0,import_utils210.ensureDirSync)(dir)}catch(err){const message=err instanceof Error?err.message:String(err);throw new Error(`${storeName}: failed to create directory "${dir}" for database "${path}": ${message}`,{cause:err})}}}let db;try{db=new BetterSqlite3(path)}catch(err){const message=err instanceof Error?err.message:String(err);throw new Error(`${storeName}: failed to open database at "${path}": ${message}`,{cause:err})}try{db.pragma(`busy_timeout = ${Math.max(0,Math.floor(options.busyTimeoutMs??DEFAULT_BUSY_TIMEOUT_MS))}`);if(options.walMode)withBusyRetry(()=>db.pragma("journal_mode = WAL"))}catch(err){db.close();const message=err instanceof Error?err.message:String(err);throw new Error(`${storeName}: failed to configure database at "${path}": ${message}`,{cause:err})}return db}var SqliteKvStore=class{db;encryptionKey=null;cleanupTimer=null;stmts=null;constructor(options){this.db=openDatabase(options.path,"SqliteKvStore",{busyTimeoutMs:options.busyTimeoutMs,walMode:options.walMode!==false});if(options.encryption?.secret){this.encryptionKey=deriveEncryptionKey(options.encryption.secret)}withBusyRetry(()=>this.initSchema());this.prepareStatements();const cleanupInterval=options.ttlCleanupIntervalMs??6e4;if(cleanupInterval>0){this.cleanupTimer=setInterval(()=>this.purgeExpired(),cleanupInterval);if(this.cleanupTimer.unref){this.cleanupTimer.unref()}}}initSchema(){this.db.exec(`
|
|
92
|
+
`}var yaml3;var init_sep_2640_builders=__esm({"libs/sdk/src/skill/sep-2640/sep-2640.builders.ts"(){"use strict";yaml3=__toESM(require("#js-yaml"));init_sep_2640_constants();init_sep_2640_uri()}});function getSepVisibleSkills(scope){const registry=scope.skills;if(!registry||!registry.hasAny())return[];return registry.getSkills({visibility:"mcp"})}async function getExternalProviderSkills(scope){const registry=scope.skills;if(registry?.getExternalProvider()?.isReadOnly()!==true)return[];const{skills}=await registry.listSkills({limit:Number.MAX_SAFE_INTEGER});return skills.filter(metadata=>!registry.findByName(metadata.name))}async function loadExternalProviderSkill(scope,skillPath){const registry=scope.skills;if(registry?.getExternalProvider()?.isReadOnly()!==true)return void 0;if(skillPath.includes("/")||registry.findByName(skillPath))return void 0;return(await registry.loadSkill(skillPath))?.skill}function findSkillByPath(scope,skillPath){const registry=scope.skills;if(!registry||!registry.hasAny())return void 0;if(typeof skillPath!=="string"||skillPath.length===0)return void 0;const visible=getSepVisibleSkills(scope);const byPath=visible.find(s=>s.getSkillPath()===skillPath);if(byPath)return byPath;const segments=skillPath.split("/").filter(s=>s.length>0);if(segments.length===0)return void 0;const lastSegment=segments[segments.length-1];const byName=visible.find(s=>s.name===lastSegment&&s.getSkillPath()===lastSegment);if(byName)return byName;if(segments.length!==1)return void 0;return visible.find(s=>s.metadata.id===lastSegment&&s.getSkillPath()===s.metadata.name)}async function findAndLoadSkillByPath(scope,skillPath){const registry=scope.skills;if(!registry||!registry.hasAny()){throw new PublicMcpError("Skills are not available in this scope.","CAPABILITY_NOT_AVAILABLE",501)}const entry=findSkillByPath(scope,skillPath);if(!entry||!await isSkillServable(scope,entry)){throw new ResourceNotFoundError(`skill://${skillPath}/SKILL.md`)}const loadResult=await registry.loadSkill(entry.metadata.id??entry.name);if(!loadResult){throw new PublicMcpError(`Failed to load skill at "${skillPath}".`,"INTERNAL_ERROR",500)}return{loadResult,instance:entry}}function isTextMimeType(mimeType){if(mimeType.startsWith("text/"))return true;if(mimeType.startsWith("application/json"))return true;if(mimeType==="application/yaml")return true;if(mimeType==="application/x-sh")return true;if(mimeType==="image/svg+xml")return true;if(mimeType.startsWith("application/javascript"))return true;if(mimeType.startsWith("application/xml"))return true;return false}async function readSkillFileByPath(instance,filePath){if(!filePath||filePath.toLowerCase()==="skill.md"){throw new ResourceNotFoundError(`skill://${instance.getSkillPath()}/${filePath}`)}const rawSegments=filePath.split("/").filter(s=>s.length>0);const segments=[];for(const raw of rawSegments){let decoded;try{decoded=decodeURIComponent(raw)}catch{throw new PublicMcpError(`Invalid file path "${filePath}".`,"INVALID_PARAMS",400)}if(decoded.includes("/")||decoded.includes("\\")){throw new PublicMcpError(`Invalid file path "${filePath}".`,"INVALID_PARAMS",400)}if(decoded===".."||decoded==="."){throw new PublicMcpError(`Invalid file path "${filePath}".`,"INVALID_PARAMS",400)}if(decoded.toLowerCase()==="skill.md"){throw new ResourceNotFoundError(`skill://${instance.getSkillPath()}/${filePath}`)}segments.push(decoded)}if(segments[0]==="references"||segments[0]==="examples"){const tail=segments.slice(1).join("/");const resolved=await tryResolvedSubFile(instance,segments[0],tail);if(resolved!==void 0){return{kind:"text",content:resolved,mimeType:guessMimeType(filePath)}}}const baseDir=instance.getBaseDir();if(!baseDir){throw new ResourceNotFoundError(`skill://${instance.getSkillPath()}/${filePath}`)}const resources=instance.getResources();const candidateDirs=[["references",resources?.references],["examples",resources?.examples],["scripts",resources?.scripts],["assets",resources?.assets]];let candidatePath;for(const[subdir,configured]of candidateDirs){if(segments[0]!==subdir)continue;const dir=configured?(0,import_utils82.isAbsolute)(configured)?configured:(0,import_utils82.pathResolve)(baseDir,configured):(0,import_utils82.joinPath)(baseDir,subdir);candidatePath=(0,import_utils82.pathResolve)(dir,...segments.slice(1));if(!isInside(candidatePath,dir)){throw new PublicMcpError(`Invalid file path "${filePath}".`,"INVALID_PARAMS",400)}break}if(!candidatePath){candidatePath=(0,import_utils82.pathResolve)(baseDir,...segments);if(!isInside(candidatePath,baseDir)){throw new PublicMcpError(`Invalid file path "${filePath}".`,"INVALID_PARAMS",400)}}const mimeType=guessMimeType(filePath);let buffer;try{buffer=await(0,import_utils82.readFileBuffer)(candidatePath)}catch(err){if(isFileMissingError(err)){throw new ResourceNotFoundError(`skill://${instance.getSkillPath()}/${filePath}`)}throw err}if(!isTextMimeType(mimeType)){const buf2=Buffer.isBuffer(buffer)?buffer:Buffer.from(buffer);return{kind:"blob",blob:buf2.toString("base64"),mimeType}}const buf=Buffer.isBuffer(buffer)?buffer:Buffer.from(buffer);const content=buf.toString("utf-8");const isMarkdown=filePath.endsWith(".md")||filePath.endsWith(".markdown");const body=isMarkdown?parseSkillMdFrontmatter(content).body:content;return{kind:"text",content:body,mimeType}}async function tryResolvedSubFile(instance,kind,tail){if(!tail)return void 0;let content;try{content=await instance.load()}catch(err){if(!instance.getBaseDir()){throw err}return void 0}const entries=kind==="references"?content.resolvedReferences??[]:content.resolvedExamples??[];const tailNoExt=tail.replace(/\.(md|markdown)$/i,"");for(const entry of entries){const filename=entry.filename;const name48=entry.name;const matches=filename!==void 0&&(filename===tail||filename===tailNoExt)||name48!==void 0&&(name48===tail||name48===tailNoExt);if(!matches)continue;const inline=entry.content;if(inline!==void 0){return parseSkillMdFrontmatter(inline).body}const absolutePath=entry.path;const resolvedPath=resolveEntryPath2(instance,kind,absolutePath,filename);if(!resolvedPath)continue;try{const buf=await(0,import_utils82.readFileBuffer)(resolvedPath);const text=(Buffer.isBuffer(buf)?buf:Buffer.from(buf)).toString("utf-8");return parseSkillMdFrontmatter(text).body}catch(err){if(isFileMissingError(err)){continue}throw err}}return void 0}function resolveEntryPath2(instance,kind,absolutePath,filename){if(absolutePath&&(0,import_utils82.isAbsolute)(absolutePath))return absolutePath;if(!filename)return void 0;const baseDir=instance.getBaseDir();const configured=instance.getResources()?.[kind];let dir;if(configured&&(0,import_utils82.isAbsolute)(configured)){dir=configured}else if(baseDir){dir=configured?(0,import_utils82.pathResolve)(baseDir,configured):(0,import_utils82.joinPath)(baseDir,kind)}if(!dir)return void 0;const resolved=(0,import_utils82.pathResolve)(dir,filename);if(!isInside(resolved,dir))return void 0;return resolved}function isFileMissingError(err){if(typeof err!=="object"||err===null)return false;const code=err.code;return code==="ENOENT"||code==="ENOTDIR"}function guessMimeType(filePath){const lower=filePath.toLowerCase();if(lower.endsWith(".md")||lower.endsWith(".markdown"))return"text/markdown";if(lower.endsWith(".json"))return"application/json";if(lower.endsWith(".yaml")||lower.endsWith(".yml"))return"application/yaml";if(lower.endsWith(".txt"))return"text/plain";if(lower.endsWith(".py"))return"text/x-python";if(lower.endsWith(".js"))return"text/javascript";if(lower.endsWith(".ts"))return"text/x-typescript";if(lower.endsWith(".sh"))return"application/x-sh";if(lower.endsWith(".html"))return"text/html";if(lower.endsWith(".css"))return"text/css";if(lower.endsWith(".svg"))return"image/svg+xml";if(lower.endsWith(".png"))return"image/png";if(lower.endsWith(".jpg")||lower.endsWith(".jpeg"))return"image/jpeg";return"application/octet-stream"}function isInside(child,parent){const normChild=child.replace(/\\/g,"/");const normParent=parent.replace(/\\/g,"/");const parentPrefix=normParent.endsWith("/")?normParent:`${normParent}/`;return normChild===normParent||normChild.startsWith(parentPrefix)}var import_utils82;var init_sep_2640_resource_helpers=__esm({"libs/sdk/src/skill/sep-2640/sep-2640.resource-helpers.ts"(){"use strict";import_utils82=require("@frontmcp/utils");init_errors();init_skill_filter_helper();init_skill_md_parser()}});var sep_2640_per_skill_exports={};__export(sep_2640_per_skill_exports,{buildPerSkillResourceRecord:()=>buildPerSkillResourceRecord,registerPerSkillResources:()=>registerPerSkillResources});function skillExtensionMetadata(skill){const extensions={};for(const[key,value]of Object.entries(skill.metadata)){if(value===void 0||key in FrontMcpSkillTokens||key in FrontMcpResourceTokens)continue;extensions[key]=value}return extensions}function buildPerSkillResourceRecord(scope,skill,opts={}){const skillPathSegments=skill.getSkillPathSegments();const skillPath=skillPathSegments.join("/");const uri=buildSkillUri(skillPathSegments,"SKILL.md");const annotations={audience:["assistant"],priority:SKILL_MD_PRIORITY};if(opts.lastModified){annotations.lastModified=opts.lastModified}const meta={[`${SEP_2640_META_NAMESPACE}path`]:skillPath};const metadata={...skillExtensionMetadata(skill),uri,name:skill.metadata.name,description:skill.getDescription(),mimeType:SKILL_MD_MIME_TYPE,annotations,_meta:meta,...skill.metadata.availableWhen!==void 0&&{availableWhen:skill.metadata.availableWhen}};const handler=async()=>{const{loadResult}=await findAndLoadSkillByPath(scope,skillPath);return{contents:[{uri,mimeType:SKILL_MD_MIME_TYPE,text:serializeSkillMd(loadResult.skill)}]}};return{kind:"FUNCTION",provide:handler,metadata}}async function registerPerSkillResources(options){const{scope,skillRegistry,resourceRegistry,logger,resolveLastModified}=options;const registered=new Map;const register=skill=>{try{const record=buildPerSkillResourceRecord(scope,skill);resourceRegistry.registerDynamicResource(record);registered.set(skill.getSkillPath(),{token:record.provide,metadata:record.metadata,extensionKeys:Object.keys(skillExtensionMetadata(skill))});logger.verbose(`Registered SEP-2640 per-skill resource: ${record.metadata.uri}`);return resolveLastModified?addLastModified(record.metadata,skill,resolveLastModified,logger):Promise.resolve()}catch(err){logger.warn(`Failed to register SEP-2640 per-skill resource for "${skill.name}": ${err instanceof Error?err.message:String(err)}`);return Promise.resolve()}};const reconcile=()=>{const served=servedSkillsByPath(skillRegistry);for(const[skillPath,resource]of registered){if(served.has(skillPath))continue;resourceRegistry.unregisterResourceInstance(resource.token);registered.delete(skillPath)}const lastModifiedUpdates=[];for(const[skillPath,skill]of served){const resource=registered.get(skillPath);if(resource)refreshFromSkill(resource,skill);else lastModifiedUpdates.push(register(skill))}return lastModifiedUpdates};await Promise.all(reconcile());const unsubscribe=skillRegistry.subscribe({immediate:false},()=>{reconcile()});scope.onDispose(unsubscribe)}async function addLastModified(metadata,skill,resolveLastModified,logger){try{const lastModified=await resolveLastModified(skill);if(lastModified&&metadata.annotations)metadata.annotations.lastModified=lastModified}catch(err){logger.warn(`Failed to resolve SEP-2640 lastModified for "${skill.name}": ${err instanceof Error?err.message:String(err)}`)}}function servedSkillsByPath(skillRegistry){const served=new Map;for(const skill of skillRegistry.getSkills({visibility:"mcp"})){const skillPath=skill.getSkillPath();if(!served.has(skillPath))served.set(skillPath,skill)}return served}function refreshFromSkill(resource,skill){const extensions=skillExtensionMetadata(skill);for(const key of resource.extensionKeys){if(!(key in extensions))Reflect.deleteProperty(resource.metadata,key)}Object.assign(resource.metadata,extensions);resource.metadata["description"]=skill.getDescription();if(skill.metadata.availableWhen===void 0)Reflect.deleteProperty(resource.metadata,"availableWhen");else resource.metadata["availableWhen"]=skill.metadata.availableWhen;resource.extensionKeys=Object.keys(extensions)}var init_sep_2640_per_skill=__esm({"libs/sdk/src/skill/sep-2640/sep-2640.per-skill.ts"(){"use strict";init_common();init_sep_2640_builders();init_sep_2640_constants();init_sep_2640_resource_helpers();init_sep_2640_uri()}});var sep_2640_last_modified_exports={};__export(sep_2640_last_modified_exports,{resolveLastModifiedForSkill:()=>resolveLastModifiedForSkill});async function resolveLastModifiedForSkill(skill){const record=skill.record;if(!record||record.kind!=="FILE"||!record.filePath){return void 0}try{const s=await(0,import_utils83.stat)(record.filePath);return s.mtime instanceof Date?s.mtime.toISOString():void 0}catch{return void 0}}var import_utils83;var init_sep_2640_last_modified=__esm({"libs/sdk/src/skill/sep-2640/sep-2640.last-modified.ts"(){"use strict";import_utils83=require("@frontmcp/utils")}});var init_base_interface=__esm({"libs/sdk/src/common/interfaces/base.interface.ts"(){"use strict"}});var init_front_mcp_interface=__esm({"libs/sdk/src/common/interfaces/front-mcp.interface.ts"(){"use strict"}});var import_protocol49,ServerRequest,ServerResponse,FrontMcpServer;var init_server_interface=__esm({"libs/sdk/src/common/interfaces/server.interface.ts"(){"use strict";import_protocol49=require("@frontmcp/protocol");ServerRequest=class extends import_protocol49.IncomingMessage{path;query;params;body;authSession};ServerResponse=class extends import_protocol49.HttpServerResponse{};FrontMcpServer=class{async stop(){return}}}});var init_scope_interface=__esm({"libs/sdk/src/common/interfaces/scope.interface.ts"(){"use strict"}});var init_hook_interface=__esm({"libs/sdk/src/common/interfaces/hook.interface.ts"(){"use strict"}});var init_app_interface=__esm({"libs/sdk/src/common/interfaces/app.interface.ts"(){"use strict"}});function AsyncAuthProvider(cfg){return cfg}var init_auth_provider_interface=__esm({"libs/sdk/src/common/interfaces/auth-provider.interface.ts"(){"use strict"}});var init_adapter_interface=__esm({"libs/sdk/src/common/interfaces/adapter.interface.ts"(){"use strict"}});var init_plugin_interface=__esm({"libs/sdk/src/common/interfaces/plugin.interface.ts"(){"use strict"}});var ToolContext;var init_tool_interface=__esm({"libs/sdk/src/common/interfaces/tool.interface.ts"(){"use strict";init_helpers();init_execution_context_interface();init_flow_interface();ToolContext=class extends ExecutionContextBase{toolId;toolName;metadata;_toolNameInternal;_toolInputInternal;_jsonRpcRequestIdInternal;_rawInput;_input;_outputDraft;_output;_inputHistory=[];_outputHistory=[];_progressToken;signal;constructor(args){const{metadata,input,providers,logger,progressToken,signal}=args;super({providers,logger:logger.child(`tool:${metadata.id??metadata.name}`),authInfo:args.authInfo});this.toolName=metadata.name;this.toolId=metadata.id??metadata.name;this.metadata=metadata;this._input=input;this._progressToken=progressToken;this.signal=signal}get _progressTokenInternal(){return this._progressToken}fetch(input,init){const context=this.fetchContext(init);if(context&&this.signal)return context.fetch(input,init,this.signal);return super.fetch(input,init)}get input(){return this._input}set input(v){this._input=v;this._inputHistory.push({at:Date.now(),stage:this.activeStage,value:v})}get inputHistory(){return this._inputHistory}get output(){return this._output}set output(v){this._output=v;this._outputHistory.push({at:Date.now(),stage:this.activeStage,value:v})}get outputHistory(){return this._outputHistory}respond(value){this.output=value;FlowControl.respond(value)}async notify(message,level="info"){const data=typeof message==="string"?{message}:message;const sink=this.tryGetContext()?.getRequestNotificationSink?.();if(sink)return sink.log(level,this.toolName,data);const sessionId=this.authInfo.sessionId;if(!sessionId){this.logger.warn("Cannot send notification: no session ID");return false}return this.scope.notifications.sendLogMessageToSession(sessionId,level,this.toolName,data)}async progress(progress,total,message){const sink=this.tryGetContext()?.getRequestNotificationSink?.();if(sink)return sink.progress(progress,total,message);if(!this._progressToken){this.logger.debug("Cannot send progress: no progressToken in request");return false}const sessionId=this.authInfo.sessionId;if(!sessionId){this.logger.warn("Cannot send progress: no session ID");return false}return this.scope.notifications.sendProgressNotification(sessionId,this._progressToken,progress,total,message)}notifyResourceUpdated(uri){this.scope.resources.notifyContentChanged(uri)}notifyResourceListChanged(){this.scope.notifications.broadcastNotification("notifications/resources/list_changed")}async elicit(message,requestedSchema,options){return performElicit({sessionId:this.context.sessionId,getClientCapabilities:sid=>this.scope.notifications.getClientCapabilities(sid),tryGetContext:()=>this.tryGetContext(),entryName:this._toolNameInternal??this.toolName,entryInput:this._toolInputInternal??this.input,elicitationEnabled:this.scope.metadata.elicitation?.enabled===true},message,requestedSchema,options)}async sample(options){return performSample(this.tryGetContext(),options)}async listRoots(){return performListRoots(this.tryGetContext())}get platform(){const payloadPlatform=this.authInfo.sessionIdPayload?.platformType;if(payloadPlatform&&payloadPlatform!=="unknown"){return payloadPlatform}const requestPlatform=this.tryGetContext()?.platformType;if(requestPlatform&&requestPlatform!=="unknown"){return requestPlatform}const sessionId=this.authInfo.sessionId;if(!sessionId){return"unknown"}return this.scope.notifications.getPlatformType(sessionId)}get clientInfo(){const requestClientInfo=this.tryGetContext()?.clientInfo;if(requestClientInfo){return requestClientInfo}const sessionId=this.authInfo.sessionId;if(!sessionId){return void 0}return this.scope.notifications.getClientInfo(sessionId)}}}});var ResourceContext;var init_resource_interface=__esm({"libs/sdk/src/common/interfaces/resource.interface.ts"(){"use strict";init_execution_context_interface();init_flow_interface();ResourceContext=class extends ExecutionContextBase{resourceId;resourceName;metadata;uri;params;_output;_outputHistory=[];constructor(args){const{metadata,uri,params,providers,logger}=args;super({providers,logger:logger.child(`resource:${metadata.name}`),authInfo:args.authInfo});this.resourceName=metadata.name;this.resourceId=metadata.name;this.metadata=metadata;this.uri=uri;this.params=params}getArgumentCompleter(_argName){return null}get output(){return this._output}set output(v){this._output=v;this._outputHistory.push({at:Date.now(),stage:this.activeStage,value:v})}get outputHistory(){return this._outputHistory}notifyUpdated(uri){const targetUri=uri??this.uri;this.scope.resources.notifyContentChanged(targetUri)}respond(value){this.output=value;FlowControl.respond(value)}}}});var PromptContext;var init_prompt_interface=__esm({"libs/sdk/src/common/interfaces/prompt.interface.ts"(){"use strict";init_execution_context_interface();init_flow_interface();PromptContext=class extends ExecutionContextBase{promptId;promptName;metadata;args;_output;_outputHistory=[];constructor(ctorArgs){const{metadata,args,providers,logger,authInfo}=ctorArgs;super({providers,logger:logger.child(`prompt:${metadata.name}`),authInfo});this.promptName=metadata.name;this.promptId=metadata.name;this.metadata=metadata;this.args=args}get authInfo(){return super.authInfo}get output(){return this._output}set output(v){this._output=v;this._outputHistory.push({at:Date.now(),stage:this.activeStage,value:v})}get outputHistory(){return this._outputHistory}respond(value){this.output=value;FlowControl.respond(value)}get error(){return super.error}}}});var LogTransportInterface,FrontMcpLogger;var init_logger_interface=__esm({"libs/sdk/src/common/interfaces/logger.interface.ts"(){"use strict";LogTransportInterface=class{};FrontMcpLogger=class{}}});function definedFields(toolCall){return Object.fromEntries(Object.entries(toolCall).filter(([,value])=>value!==void 0))}var AgentExecutionLoop,AgentMaxIterationsError;var init_agent_execution_loop=__esm({"libs/sdk/src/agent/agent-execution-loop.ts"(){"use strict";init_common();AgentExecutionLoop=class{config;constructor(config){this.config={maxIterations:10,timeout:12e4,...config}}async run(userMessage,toolExecutor,existingMessages=[]){const startTime=Date.now();const messages=[...existingMessages,{role:"user",content:userMessage}];let iterations=0;let totalPromptTokens=0;let totalCompletionTokens=0;let timeout;try{const timeoutPromise=new Promise((_,reject)=>{timeout=setTimeout(()=>reject(new Error(`Agent execution timed out after ${this.config.timeout}ms`)),this.config.timeout)});const result=await Promise.race([this.executeLoop(messages,toolExecutor,{onIteration:(iter,msg)=>{iterations=iter;this.config.onIteration?.(iter,msg)},onUsage:(prompt,completion)=>{totalPromptTokens+=prompt;totalCompletionTokens+=completion}}),timeoutPromise]);return{content:result.content,messages,iterations,usage:{promptTokens:totalPromptTokens,completionTokens:totalCompletionTokens,totalTokens:totalPromptTokens+totalCompletionTokens},success:true,durationMs:Date.now()-startTime}}catch(error){return{content:null,messages,iterations,usage:{promptTokens:totalPromptTokens,completionTokens:totalCompletionTokens,totalTokens:totalPromptTokens+totalCompletionTokens},success:false,error,durationMs:Date.now()-startTime}}finally{clearTimeout(timeout)}}async*runStreaming(userMessage,toolExecutor,existingMessages=[]){const startTime=Date.now();const deadline=startTime+this.config.timeout;const messages=[...existingMessages,{role:"user",content:userMessage}];let iterations=0;let totalPromptTokens=0;let totalCompletionTokens=0;const result=(content,error)=>({content,messages,iterations,usage:{promptTokens:totalPromptTokens,completionTokens:totalCompletionTokens,totalTokens:totalPromptTokens+totalCompletionTokens},success:error===void 0,...error&&{error},durationMs:Date.now()-startTime});const events=this.executeLoopStreaming(messages,toolExecutor);try{for(;;){const step=await this.beforeDeadline(events.next(),deadline);if(step.done){const done=result(step.value.content);yield{type:"done",result:done};return done}const event=step.value;if(event.type==="iteration")iterations=event.iteration;if(event.type==="usage"){totalPromptTokens+=event.promptTokens;totalCompletionTokens+=event.completionTokens}yield event}}catch(caught){void events.return({content:null}).catch(()=>void 0);const error=caught;const failed=result(null,error);yield{type:"error",error};yield{type:"done",result:failed};return failed}}async beforeDeadline(step,deadline){let timer;const timeout=new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(`Agent execution timed out after ${this.config.timeout}ms`)),Math.max(0,deadline-Date.now()))});try{return await Promise.race([step,timeout])}finally{clearTimeout(timer)}}async executeLoop(messages,toolExecutor,callbacks){for(let iteration=1;iteration<=this.config.maxIterations;iteration++){this.config.logger?.debug(`Agent loop iteration ${iteration}/${this.config.maxIterations}`);this.config.onLlmStart?.(iteration,this.config.maxIterations);const prompt={system:this.config.systemInstructions,messages};const completion=await this.config.adapter.completion(prompt,this.config.tools.length>0?this.config.tools:void 0,this.config.completionOptions);this.config.onLlmComplete?.(iteration,completion.usage);if(completion.usage){callbacks.onUsage(completion.usage.promptTokens,completion.usage.completionTokens)}if(completion.finishReason==="tool_calls"&&completion.toolCalls?.length){this.config.onToolsIdentified?.(completion.toolCalls.length,completion.toolCalls.map(tc=>tc.name));const assistantMessage={role:"assistant",content:completion.content,toolCalls:completion.toolCalls};messages.push(assistantMessage);callbacks.onIteration(iteration,assistantMessage);const totalTools=completion.toolCalls.length;for(let toolIndex=0;toolIndex<totalTools;toolIndex++){const toolCall=completion.toolCalls[toolIndex];this.config.onToolStart?.(toolCall,toolIndex,totalTools);this.config.onToolCall?.(toolCall);let result;let error2;try{result=await toolExecutor(toolCall.name,toolCall.arguments)}catch(e){error2=e;result={error:error2.message}}this.config.onToolResult?.(toolCall,result,error2);const toolMessage={role:"tool",content:typeof result==="string"?result:JSON.stringify(result),toolCallId:toolCall.id,name:toolCall.name};messages.push(toolMessage)}}else{const assistantMessage={role:"assistant",content:completion.content};messages.push(assistantMessage);callbacks.onIteration(iteration,assistantMessage);this.config.onContent?.(completion.content??"");this.config.onComplete?.(completion.content,void 0);return{content:completion.content}}}const error=new AgentMaxIterationsError(`Agent reached maximum iterations (${this.config.maxIterations}) without completing`,this.config.maxIterations);this.config.onComplete?.(null,error);throw error}async*executeLoopStreaming(messages,toolExecutor){for(let iteration=1;iteration<=this.config.maxIterations;iteration++){this.config.logger?.debug(`Agent loop iteration ${iteration}/${this.config.maxIterations}`);this.config.onLlmStart?.(iteration,this.config.maxIterations);yield{type:"iteration",iteration};const prompt={system:this.config.systemInstructions,messages};const completion=yield*this.streamCompletion(prompt);this.config.onLlmComplete?.(iteration,completion.usage);if(completion.finishReason==="tool_calls"&&completion.toolCalls?.length){const toolCalls=completion.toolCalls;this.config.onToolsIdentified?.(toolCalls.length,toolCalls.map(tc=>tc.name));const assistantMessage={role:"assistant",content:completion.content,toolCalls};messages.push(assistantMessage);this.config.onIteration?.(iteration,assistantMessage);const totalTools=toolCalls.length;for(let toolIndex=0;toolIndex<totalTools;toolIndex++){const toolCall=toolCalls[toolIndex];this.config.onToolStart?.(toolCall,toolIndex,totalTools);this.config.onToolCall?.(toolCall);yield{type:"tool_start",toolCall};let result;let error2;try{result=await toolExecutor(toolCall.name,toolCall.arguments)}catch(e){error2=e;result={error:error2.message}}this.config.onToolResult?.(toolCall,result,error2);yield{type:"tool_end",toolCall,result,error:error2};const toolMessage={role:"tool",content:typeof result==="string"?result:JSON.stringify(result),toolCallId:toolCall.id,name:toolCall.name};messages.push(toolMessage)}}else{const assistantMessage={role:"assistant",content:completion.content};messages.push(assistantMessage);this.config.onIteration?.(iteration,assistantMessage);this.config.onComplete?.(completion.content,void 0);return{content:completion.content}}}const error=new AgentMaxIterationsError(`Agent reached maximum iterations (${this.config.maxIterations}) without completing`,this.config.maxIterations);this.config.onComplete?.(null,error);throw error}async*streamCompletion(prompt){const adapter=this.config.adapter;const tools=this.config.tools.length>0?this.config.tools:void 0;let streamedText="";let completion;if(supportsStreaming(adapter)){const announced=new Map;let done;for await(const chunk of adapter.streamCompletion(prompt,tools,this.config.completionOptions)){if(chunk.type==="content"&&chunk.content){streamedText+=chunk.content;yield{type:"content",content:chunk.content};this.config.onContent?.(chunk.content)}else if(chunk.type==="tool_call"&&chunk.toolCall){announced.set(chunk.toolCall.id,{...announced.get(chunk.toolCall.id),...definedFields(chunk.toolCall)});yield{type:"tool_call",toolCall:chunk.toolCall}}else if(chunk.type==="done"&&chunk.completion){done=chunk.completion}}const toolCalls=done?.toolCalls??[...announced.values()].map(call=>({id:call.id,name:call.name??"",arguments:call.arguments??{}}));completion={content:streamedText||(done?.content??null),finishReason:done?.finishReason??(toolCalls.length>0?"tool_calls":"stop"),...toolCalls.length>0&&{toolCalls},...done?.usage&&{usage:done.usage}}}else{completion=await adapter.completion(prompt,tools,this.config.completionOptions)}if(!streamedText&&completion.content){yield{type:"content",content:completion.content};this.config.onContent?.(completion.content)}if(completion.usage){yield{type:"usage",promptTokens:completion.usage.promptTokens,completionTokens:completion.usage.completionTokens}}return completion}};AgentMaxIterationsError=class extends Error{constructor(message,maxIterations){super(message);this.maxIterations=maxIterations;this.name="AgentMaxIterationsError"}maxIterations}}});var AgentContext;var init_agent_interface=__esm({"libs/sdk/src/common/interfaces/agent.interface.ts"(){"use strict";init_agent_execution_loop();init_frontmcp_context_storage();init_helpers();init_errors();init_tool_lookup_utils();init_execution_context_interface();init_flow_interface();AgentContext=class _AgentContext extends ExecutionContextBase{agentId;agentName;metadata;llmAdapter;agentScope;systemInstructions;toolDefinitions;toolExecutor;agentInvoker;privateScope;_agentNameInternal;_agentInputInternal;_rawInput;_input;_outputDraft;_output;_inputHistory=[];_outputHistory=[];_progressToken;constructor(args){const{metadata,input,providers,logger,llmAdapter,agentScope,toolDefinitions,toolExecutor,agentInvoker,privateScope,progressToken}=args;super({providers,logger:logger.child(`agent:${metadata.id??metadata.name}`),authInfo:args.authInfo});this.agentName=metadata.name;this.agentId=metadata.id??metadata.name;this.metadata=metadata;this._input=input;this.llmAdapter=llmAdapter;this.agentScope=agentScope;this.systemInstructions=metadata.systemInstructions??"";this.toolDefinitions=toolDefinitions??[];this.toolExecutor=toolExecutor;this.agentInvoker=agentInvoker;this.privateScope=privateScope;this._progressToken=progressToken}async execute(input){return this.runAgentLoop(input)}async runAgentLoop(input){const userMessage=this.buildUserMessage(input);const streaming=this.streamsReplies();const enableAutoProgress=this.metadata.execution?.enableAutoProgress===true&&this.metadata.execution?.enableNotifications!==false;const maxIterations=this.metadata.execution?.maxIterations??10;const notificationInterval=this.metadata.execution?.notificationInterval??1e3;const iterationShare=80/maxIterations;let iterationStart=0;let lastSentProgress=-1;let lastAutoProgressAt;const autoProgress=(progress,message,isFinal=false)=>{if(streaming)return;const now=Date.now();if(progress<=lastSentProgress)return;if(!isFinal&&lastAutoProgressAt!==void 0&&now-lastAutoProgressAt<notificationInterval)return;lastAutoProgressAt=now;lastSentProgress=progress;void this.progress(progress,100,message)};const loop=new AgentExecutionLoop({adapter:{completion:(prompt,tools,options)=>this.completion(prompt,tools,options),...streaming&&{streamCompletion:(prompt,tools,options)=>this.streamCompletion(prompt,tools,options)}},systemInstructions:this.systemInstructions,tools:this.toolDefinitions,maxIterations,timeout:this.metadata.execution?.timeout??12e4,logger:this.logger,completionOptions:this.completionOptions(),onLlmStart:enableAutoProgress?(iteration,maxIter)=>{iterationStart=(iteration-1)*iterationShare;autoProgress(Math.round(iterationStart),`Starting LLM call (iteration ${iteration}/${maxIter})`)}:void 0,onLlmComplete:enableAutoProgress?(iteration,usage)=>{const usageStr=usage?` (${usage.promptTokens??0}P + ${usage.completionTokens??0}C tokens)`:"";autoProgress(Math.round(iterationStart+iterationShare/2),`LLM response received${usageStr}`)}:void 0,onToolsIdentified:enableAutoProgress?(count,names)=>{this.notify(`Identified ${count} tool call(s): ${names.join(", ")}`,"info")}:void 0,onToolStart:enableAutoProgress?(toolCall,index,total)=>{const toolsDone=(index+1)/(total+1);const toolProgress=iterationStart+iterationShare/2*(1+toolsDone);autoProgress(Math.round(toolProgress),`Executing tool ${index+1}/${total}: ${toolCall.name}`)}:void 0,onComplete:enableAutoProgress?(content,error)=>{autoProgress(100,error?`Agent failed: ${toMcpError(error).getPublicMessage()}`:"Agent completed",true)}:void 0,onToolCall:toolCall=>{if(this.metadata.execution?.enableNotifications!==false){this.notify(`Calling tool: ${toolCall.name}`,"info")}this.logger.debug(`Tool call: ${toolCall.name}`,{args:toolCall.arguments})},onToolResult:(toolCall,result2,error)=>{if(error){const reported=toMcpError(error);if(this.metadata.execution?.enableNotifications!==false){this.notify(`Tool ${toolCall.name} failed: ${reported.getPublicMessage()}`,"error")}this.logger.error(`Tool ${toolCall.name} failed (${reported.errorId})`,error)}else{this.logger.debug(`Tool ${toolCall.name} completed`,{result:result2})}},onContent:content=>{if(this.metadata.execution?.enableNotifications!==false){this.logger.debug(`Content received: ${content.slice(0,100)}...`)}}});const executor=async(name48,args)=>this.executeTool(name48,args);const result=streaming?await this.streamAgentLoop(loop.runStreaming(userMessage,executor)):await loop.run(userMessage,executor);if(!result.success&&result.error){throw result.error}return this.parseAgentResponse(result.content)}streamsReplies(){if(this.metadata.execution?.enableStreaming!==true||this._progressToken===void 0)return false;const overridesCompletion=this.completion!==_AgentContext.prototype.completion;const overridesStreamCompletion=this.streamCompletion!==_AgentContext.prototype.streamCompletion;return overridesStreamCompletion||!overridesCompletion&&typeof this.llmAdapter.streamCompletion==="function"}async streamAgentLoop(events){let chunks=0;for(let step=await events.next();;step=await events.next()){if(step.done)return step.value;const event=step.value;if(event.type==="content"&&event.content){chunks+=1;await this.progress(chunks,void 0,event.content)}}}completionOptions(){const llm=this.metadata.llm;return{...llm?.temperature!==void 0&&{temperature:llm.temperature},...llm?.maxTokens!==void 0&&{maxTokens:llm.maxTokens}}}buildUserMessage(input){if(typeof input==="string"){return input}const inputObj=input;if(inputObj["query"])return String(inputObj["query"]);if(inputObj["message"])return String(inputObj["message"]);if(inputObj["prompt"])return String(inputObj["prompt"]);if(inputObj["input"])return String(inputObj["input"]);return JSON.stringify(input)}parseAgentResponse(content){if(content===null){return{response:""}}if(content.trim().startsWith("{")||content.trim().startsWith("[")){try{return JSON.parse(content)}catch{}}return{response:content}}get input(){return this._input}set input(v){this._input=v;this._inputHistory.push({at:Date.now(),stage:this.activeStage,value:v})}get inputHistory(){return this._inputHistory}get output(){return this._output}set output(v){this._output=v;this._outputHistory.push({at:Date.now(),stage:this.activeStage,value:v})}get outputHistory(){return this._outputHistory}async completion(prompt,tools,options){return this.llmAdapter.completion(prompt,tools,options)}async*streamCompletion(prompt,tools,options){if(!this.llmAdapter.streamCompletion){const result=await this.completion(prompt,tools,options);yield{type:"done",completion:result};return}yield*this.llmAdapter.streamCompletion(prompt,tools,options)}async executeTool(name48,args){if(!this.toolExecutor){throw new AgentMethodNotAvailableError("executeTool",this.agentName)}return this.toolExecutor(name48,args)}async invokeAgent(agentId,input){if(!this.agentInvoker){throw new AgentMethodNotAvailableError("invokeAgent",this.agentName)}return this.agentInvoker(agentId,input)}callToolSurface(){return"agent"}callToolScope(name48){const privateScope=this.privateScope;const isPrivateTool=privateScope&&lookupTool(privateScope,name48);return isPrivateTool?privateScope:super.callToolScope(name48)}async notify(message,level="info"){const logMessage=typeof message==="string"?message:JSON.stringify(message);if(level==="error"){this.logger.error(logMessage)}else if(level==="warning"){this.logger.warn(logMessage)}else{this.logger.info(logMessage)}const data=typeof message==="string"?{message}:message;const sink=this.requestNotificationSink();if(sink)return sink.log(level,this.agentName,data);const sessionId=this.authInfo.sessionId;if(!sessionId){return false}return this.scope.notifications.sendLogMessageToSession(sessionId,level,this.agentName,data)}async progress(progress,total,message){const sink=this.requestNotificationSink();if(sink)return sink.progress(progress,total,message);if(this._progressToken===void 0){this.logger.debug("Cannot send progress: no progressToken in request");return false}const sessionId=this.authInfo.sessionId;if(!sessionId){this.logger.warn("Cannot send progress: no session ID");return false}return this.scope.notifications.sendProgressNotification(sessionId,this._progressToken,progress,total,message)}async elicit(message,requestedSchema,options){return performElicit({sessionId:this.authInfo.sessionId,getClientCapabilities:sid=>this.scope.notifications.getClientCapabilities(sid),tryGetContext:()=>this.tryGetContext()??this.runningRequestContext(),entryName:this._agentNameInternal??this.agentName,entryInput:this._agentInputInternal??this.input,elicitationEnabled:this.scope.metadata.elicitation?.enabled===true},message,requestedSchema,options)}requestNotificationSink(){return(this.tryGetContext()??this.runningRequestContext())?.getRequestNotificationSink?.()}runningRequestContext(){try{return this.scope.providers.get(FrontMcpContextStorage).getStore()}catch{return void 0}}respond(value){this.output=value;FlowControl.respond(value)}get platform(){const payloadPlatform=this.authInfo.sessionIdPayload?.platformType;if(payloadPlatform&&payloadPlatform!=="unknown"){return payloadPlatform}const requestPlatform=this.tryGetContext()?.platformType;if(requestPlatform&&requestPlatform!=="unknown"){return requestPlatform}const sessionId=this.authInfo.sessionId;if(!sessionId){return"unknown"}return this.scope.notifications.getPlatformType(sessionId)}get clientInfo(){const requestClientInfo=this.tryGetContext()?.clientInfo;if(requestClientInfo){return requestClientInfo}const sessionId=this.authInfo.sessionId;if(!sessionId){return void 0}return this.scope.notifications.getClientInfo(sessionId)}}}});var SkillContext;var init_skill_interface=__esm({"libs/sdk/src/common/interfaces/skill.interface.ts"(){"use strict";init_sdk_errors();init_metadata();init_execution_context_interface();SkillContext=class extends ExecutionContextBase{skillId;skillName;metadata;defaults;constructor(args){const{metadata,providers,logger,defaults}=args;super({providers,logger:logger.child(`skill:${metadata.id??metadata.name}`),authInfo:args.authInfo});this.skillName=metadata.name;this.skillId=metadata.id??metadata.name;this.metadata=metadata;this.defaults=defaults}async loadInstructions(){if(!this.defaults)throw new SkillContextNotImplementedError(this.skillName,"loadInstructions");return this.defaults.loadInstructions()}async build(){if(!this.defaults)throw new SkillContextNotImplementedError(this.skillName,"build");return this.defaults.build()}getToolRefs(){if(!this.metadata.tools)return[];return this.metadata.tools.map(t=>normalizeToolRef(t))}getToolNames(){return this.getToolRefs().map(t=>t.name)}}}});var JobContext;var init_job_interface=__esm({"libs/sdk/src/common/interfaces/job.interface.ts"(){"use strict";init_execution_context_interface();init_flow_interface();JobContext=class extends ExecutionContextBase{jobId;jobName;metadata;_input;_output;_attempt;_logs=[];signal;constructor(args){const{metadata,input,providers,logger,attempt,signal}=args;super({providers,logger:logger.child(`job:${metadata.id??metadata.name}`),authInfo:args.authInfo});this.jobName=metadata.name;this.jobId=metadata.id??metadata.name;this.metadata=metadata;this._input=input;this._attempt=attempt;this.signal=signal}fetch(input,init){const context=this.fetchContext(init);if(context&&this.signal)return context.fetch(input,init,this.signal);return super.fetch(input,init)}get input(){return this._input}get output(){return this._output}set output(v){this._output=v}get attempt(){return this._attempt}log(message){this._logs.push(`[${new Date().toISOString()}] ${message}`);this.logger.info(message)}async progress(pct,total,msg){const sessionId=this.authInfo.sessionId;if(!sessionId){this.logger.debug("Cannot send progress: no session ID");return false}return this.scope.notifications.sendProgressNotification(sessionId,this.jobId,pct,total,msg)}respond(value){this._output=value;FlowControl.respond(value)}getLogs(){return this._logs}callToolSurface(){return"job"}}}});var WorkflowContext;var init_workflow_interface=__esm({"libs/sdk/src/common/interfaces/workflow.interface.ts"(){"use strict";init_execution_context_interface();WorkflowContext=class extends ExecutionContextBase{metadata;_stepResults=new Map;constructor(args){const{metadata,providers,logger}=args;super({providers,logger:logger.child(`workflow:${metadata.id??metadata.name}`),authInfo:args.authInfo});this.metadata=metadata}get workflowName(){return this.metadata.name}get workflowId(){return this.metadata.id??this.metadata.name}get stepResults(){return this._stepResults}_setStepResult(stepId,result){this._stepResults.set(stepId,result)}}}});var ChannelContext;var init_channel_interface=__esm({"libs/sdk/src/common/interfaces/channel.interface.ts"(){"use strict";init_call_surface();init_mcp_error();init_execution_context_interface();ChannelContext=class extends ExecutionContextBase{channelName;metadata;_pushIncoming;constructor(args){const{metadata,providers,logger}=args;super({providers,logger:logger.child(`channel:${metadata.name}`),authInfo:args.authInfo});this.channelName=metadata.name;this.metadata=metadata}async onReply(reply,meta){throw new PublicMcpError(`Channel "${this.channelName}" has twoWay: true but onReply() is not implemented. Override onReply() to forward replies to the external system.`,"CHANNEL_REPLY_NOT_IMPLEMENTED",501)}async onConnect(){}async onDisconnect(){}pushIncoming(payload){if(this._pushIncoming){this._pushIncoming(payload)}else{this.logger.warn(`Channel "${this.channelName}": pushIncoming called but no handler is wired`)}}callToolSurface(){return getCallSurface()==="http-trigger"?"http-trigger":void 0}}}});function sessionIdPresentedBy(request){const header=request.headers?.["mcp-session-id"];if(typeof header==="string"&&header.length>0)return header;const query=request.query?.["sessionId"];return typeof query==="string"&&query.length>0?query:void 0}function authInfoFromAuthorization(authorization,presentedSessionId){const{token,user,session}=authorization;const verifiedSession=session!==void 0&&presentedSessionId!==void 0&&session.id===presentedSessionId?session:void 0;return{token,clientId:user?.sub,scopes:(0,import_auth38.scopesFromClaims)(user),expiresAt:user?.exp?user.exp*1e3:void 0,user,extra:{user,sessionId:verifiedSession?.id,sessionPayload:verifiedSession?.payload}}}var import_auth38;var init_auth_info_utils=__esm({"libs/sdk/src/common/utils/auth-info.utils.ts"(){"use strict";import_auth38=require("@frontmcp/auth")}});function pathOf(req){const anyReq=req;const raw=anyReq.path??anyReq.pathname??anyReq.url??"/";try{const u=new URL(String(raw),"http://local");return u.pathname||"/"}catch{return String(raw).split("?")[0]||"/"}}function isLegacySsePath(path){return path==="/sse"||path.endsWith("/sse")}function tryDecodeTransportType(sessionId){if(!sessionId)return;try{const b64=sessionId.replace(/-/g,"+").replace(/_/g,"/");const json=Buffer.from(b64,"base64").toString("utf8");if(json.trimStart()[0]!=="{")return;const obj=JSON.parse(json);return obj?.transportType}catch{return}}function getQuerySessionId(req){const anyReq=req;const raw=anyReq.url??anyReq.path??"/";try{const u=new URL(String(raw),"http://local");return u.searchParams.get("sessionId")??void 0}catch{return void 0}}function computeBitmap(req,cfg){const method=req.method.toUpperCase();const accept=h(req,"accept");const path=pathOf(req);const postToMessage=method==="POST"&&(path==="/message"||path.endsWith("/message"));const headerSessionId=h(req,"mcp-session-id");const querySessionId=postToMessage?getQuerySessionId(req):void 0;const sessionId=headerSessionId??querySessionId;const legacyHeader=h(req,"x-legacy-sse")==="true";const transportType=tryDecodeTransportType(sessionId);const acceptSSE=wantsSSE(accept);const acceptJSON=wantsJSON(accept)||!accept&&cfg.tolerateMissingAccept;const init=method==="POST"&&isInitialize(req.body);const getToSsePath=method==="GET"&&isLegacySsePath(path);const channel2=method==="POST"&&postToMessage?CH_POST_MESSAGE:getToSsePath&&acceptSSE?CH_GET_SSE_PATH:method==="GET"&&acceptSSE?CH_GET_SSE:method==="POST"&&init&&acceptSSE?CH_POST_INIT_SSE:method==="POST"&&init&&acceptJSON?CH_POST_INIT_JSON:method==="POST"&&!init&&acceptSSE?CH_POST_SSE:method==="POST"&&!init&&acceptJSON?CH_POST_JSON:CH_OTHER;let flags=0;if(sessionId)flags|=B_HAS_SESSION;if(cfg.enableStatelessHttp)flags|=B_STATELESS_EN;if(cfg.requireSessionForStreamable)flags|=B_REQ_SESSION;if(legacyHeader||transportType==="legacy-sse")flags|=B_LEGACY_HINT;if(cfg.enableSseListener)flags|=B_SSE_LISTENER_EN;if(cfg.enableStreamableHttp)flags|=B_STREAMABLE_EN;if(cfg.enableStatefulHttp)flags|=B_STATEFUL_EN;if(cfg.enableLegacySSE)flags|=B_LEGACY_EN;return{key:channel2&CH_MASK|flags,channel:channel2,flags,init}}function decideIntent(req,cfg){const reasons=[];const method=req.method.toUpperCase();if(method==="DELETE"){const sessionId=h(req,"mcp-session-id");if(!sessionId){return{intent:"unknown",reasons:["DELETE requires Mcp-Session-Id header."],recommendation:{httpStatus:400,message:"Session ID required for DELETE"},debug:{key:0,channel:0,flags:0}}}return{intent:"delete-session",reasons:["DELETE with Mcp-Session-Id \u2192 session termination."],debug:{key:0,channel:0,flags:sessionId?B_HAS_SESSION:0}}}const{key,channel:channel2,flags,init}=computeBitmap(req,cfg);if(method==="POST"&&channel2!==CH_POST_MESSAGE){const accept=h(req,"accept");const acceptsSSE=wantsSSE(accept);const acceptsJSON=wantsJSON(accept)||!accept&&cfg.tolerateMissingAccept;if(!acceptsSSE&&!acceptsJSON){return{intent:"unknown",reasons:["Client must accept application/json or text/event-stream."],recommendation:{httpStatus:406,message:"Not acceptable"},debug:{key,channel:channel2,flags}}}}for(const rule of RULES){if((key&rule.care)===rule.match){const{reason,...rest}=rule.outcome;reasons.push(reason);if(init)reasons.push("Initialize body detected.");return{...rest,reasons,debug:{key,channel:channel2,flags}}}}return{intent:"unknown",reasons:["No matching rule."],recommendation:{httpStatus:500,message:"Unroutable request"},debug:{key,channel:channel2,flags}}}function authorizeSessionTermination(verifyResult,requestedSessionId){if(!verifyResult||verifyResult.kind!=="authorized"||!verifyResult.authorization){return{kind:"unauthorized"}}const ownedSessionId=verifyResult.authorization.session?.id;if(!ownedSessionId||!requestedSessionId||requestedSessionId!==ownedSessionId){return{kind:"forbidden"}}return{kind:"ok",sessionId:ownedSessionId}}var import_lazy_zod71,intentSchema,decisionSchema,CH_OTHER,CH_GET_SSE,CH_POST_INIT_JSON,CH_POST_INIT_SSE,CH_POST_JSON,CH_POST_SSE,CH_POST_MESSAGE,CH_GET_SSE_PATH,CH_MASK,B_HAS_SESSION,B_STATELESS_EN,B_REQ_SESSION,B_LEGACY_HINT,B_SSE_LISTENER_EN,B_STREAMABLE_EN,B_STATEFUL_EN,B_LEGACY_EN,h,wantsSSE,wantsJSON,isInitialize,RULES;var init_decide_request_intent_utils=__esm({"libs/sdk/src/common/utils/decide-request-intent.utils.ts"(){"use strict";import_lazy_zod71=require("@frontmcp/lazy-zod");intentSchema=import_lazy_zod71.z.union([import_lazy_zod71.z.literal("legacy-sse"),import_lazy_zod71.z.literal("sse"),import_lazy_zod71.z.literal("streamable-http"),import_lazy_zod71.z.literal("stateful-http"),import_lazy_zod71.z.literal("stateless-http"),import_lazy_zod71.z.literal("delete-session"),import_lazy_zod71.z.literal("mcp-20260728"),import_lazy_zod71.z.literal("unknown")]);decisionSchema=import_lazy_zod71.z.object({intent:intentSchema,reasons:import_lazy_zod71.z.array(import_lazy_zod71.z.string()),recommendation:import_lazy_zod71.z.object({httpStatus:import_lazy_zod71.z.number(),message:import_lazy_zod71.z.string()}).optional(),debug:import_lazy_zod71.z.object({key:import_lazy_zod71.z.number(),channel:import_lazy_zod71.z.number(),flags:import_lazy_zod71.z.number()}).optional()});CH_OTHER=0;CH_GET_SSE=1;CH_POST_INIT_JSON=2;CH_POST_INIT_SSE=3;CH_POST_JSON=4;CH_POST_SSE=5;CH_POST_MESSAGE=6;CH_GET_SSE_PATH=7;CH_MASK=7;B_HAS_SESSION=1<<3;B_STATELESS_EN=1<<4;B_REQ_SESSION=1<<5;B_LEGACY_HINT=1<<6;B_SSE_LISTENER_EN=1<<7;B_STREAMABLE_EN=1<<8;B_STATEFUL_EN=1<<9;B_LEGACY_EN=1<<10;h=(req,name48)=>Object.entries(req.headers).find(([k])=>k.toLowerCase()===name48.toLowerCase())?.[1];wantsSSE=accept=>(accept??"").toLowerCase().includes("text/event-stream");wantsJSON=accept=>(accept??"").toLowerCase().includes("application/json");isInitialize=body=>!!body&&typeof body==="object"&&body.method==="initialize";RULES=[{care:CH_MASK|B_HAS_SESSION|B_LEGACY_EN,match:CH_GET_SSE_PATH|B_LEGACY_EN,outcome:{intent:"legacy-sse",reason:"GET /sse without Mcp-Session-Id \u2192 legacy SSE."}},{care:CH_MASK|B_HAS_SESSION|B_LEGACY_EN,match:CH_GET_SSE_PATH,outcome:{intent:"unknown",reason:"Legacy SSE disabled.",recommendation:{httpStatus:405,message:"Legacy SSE disabled"}}},{care:CH_MASK|B_HAS_SESSION|B_SSE_LISTENER_EN|B_STREAMABLE_EN,match:CH_GET_SSE|B_HAS_SESSION|B_SSE_LISTENER_EN|B_STREAMABLE_EN,outcome:{intent:"streamable-http",reason:"GET / with session ID \u2192 SSE listener for streamable-http."}},{care:CH_MASK|B_HAS_SESSION|B_SSE_LISTENER_EN,match:CH_GET_SSE|B_HAS_SESSION,outcome:{intent:"unknown",reason:"SSE listener disabled for GET / requests.",recommendation:{httpStatus:405,message:"SSE listener disabled"}}},{care:CH_MASK|B_HAS_SESSION,match:CH_GET_SSE,outcome:{intent:"unknown",reason:"GET / with SSE requires session for MCP transport."}},{care:CH_MASK|B_HAS_SESSION|B_LEGACY_EN,match:CH_POST_MESSAGE|B_HAS_SESSION|B_LEGACY_EN,outcome:{intent:"legacy-sse",reason:"POST /message with Mcp-Session-Id \u2192 legacy SSE bridge."}},{care:CH_MASK|B_HAS_SESSION|B_LEGACY_EN,match:CH_POST_MESSAGE|B_HAS_SESSION,outcome:{intent:"unknown",reason:"Legacy /message endpoint disabled.",recommendation:{httpStatus:405,message:"Legacy SSE disabled"}}},{care:CH_MASK|B_SSE_LISTENER_EN|B_HAS_SESSION,match:CH_GET_SSE_PATH|B_HAS_SESSION,outcome:{intent:"unknown",reason:"SSE listener disabled.",recommendation:{httpStatus:405,message:"SSE listener disabled"}}},{care:CH_MASK|B_SSE_LISTENER_EN|B_HAS_SESSION,match:CH_GET_SSE_PATH|B_SSE_LISTENER_EN|B_HAS_SESSION,outcome:{intent:"sse",reason:"GET /sse with Mcp-Session-Id."}},{care:CH_MASK|B_HAS_SESSION|B_STATELESS_EN|B_STREAMABLE_EN,match:CH_POST_INIT_SSE|B_STATELESS_EN,outcome:{intent:"stateless-http",reason:"Stateless initialize (no session)."}},{care:CH_MASK|B_STREAMABLE_EN,match:CH_POST_INIT_SSE,outcome:{intent:"unknown",reason:"Streamable HTTP disabled.",recommendation:{httpStatus:405,message:"Streamable HTTP disabled"}}},{care:CH_MASK|B_STREAMABLE_EN,match:CH_POST_INIT_SSE|B_STREAMABLE_EN,outcome:{intent:"streamable-http",reason:"Initialize with SSE."}},{care:CH_MASK|B_HAS_SESSION|B_STATELESS_EN|B_STREAMABLE_EN,match:CH_POST_INIT_JSON|B_STATELESS_EN,outcome:{intent:"stateless-http",reason:"Stateless initialize JSON (no session)."}},{care:CH_MASK|B_STREAMABLE_EN,match:CH_POST_INIT_JSON,outcome:{intent:"unknown",reason:"JSON mode disabled.",recommendation:{httpStatus:405,message:"JSON mode disabled"}}},{care:CH_MASK|B_STREAMABLE_EN,match:CH_POST_INIT_JSON|B_STREAMABLE_EN,outcome:{intent:"stateful-http",reason:"Initialize with JSON."}},{care:CH_MASK|B_REQ_SESSION|B_HAS_SESSION|B_STATELESS_EN,match:CH_POST_SSE|B_REQ_SESSION,outcome:{intent:"unknown",reason:"POST SSE requires session.",recommendation:{httpStatus:400,message:"Initialize required (no Mcp-Session-Id)"}}},{care:CH_MASK|B_STREAMABLE_EN|B_STATELESS_EN,match:CH_POST_SSE,outcome:{intent:"unknown",reason:"Streamable HTTP disabled.",recommendation:{httpStatus:405,message:"Streamable HTTP disabled"}}},{care:CH_MASK|B_HAS_SESSION|B_STATELESS_EN|B_STREAMABLE_EN,match:CH_POST_SSE|B_STATELESS_EN,outcome:{intent:"stateless-http",reason:"Stateless short-lived SSE."}},{care:CH_MASK,match:CH_POST_SSE,outcome:{intent:"streamable-http",reason:"Short-lived SSE for this request."}},{care:CH_MASK|B_REQ_SESSION|B_HAS_SESSION|B_STATELESS_EN,match:CH_POST_JSON|B_REQ_SESSION,outcome:{intent:"unknown",reason:"POST JSON requires session.",recommendation:{httpStatus:400,message:"Initialize required (no Mcp-Session-Id)"}}},{care:CH_MASK|B_STATEFUL_EN|B_STREAMABLE_EN|B_STATELESS_EN,match:CH_POST_JSON,outcome:{intent:"unknown",reason:"JSON mode disabled.",recommendation:{httpStatus:405,message:"JSON mode disabled"}}},{care:CH_MASK|B_HAS_SESSION|B_STATELESS_EN|B_STREAMABLE_EN,match:CH_POST_JSON|B_STATELESS_EN,outcome:{intent:"stateless-http",reason:"Stateless JSON request."}},{care:CH_MASK,match:CH_POST_JSON,outcome:{intent:"stateful-http",reason:"Aggregated JSON response."}},{care:CH_MASK,match:CH_OTHER,outcome:{intent:"unknown",reason:"Method/Accept not allowed.",recommendation:{httpStatus:405,message:"Method/Accept not allowed"}}}]}});function enforceIpFilter(scope,clientIp,buildRejection=()=>httpRespond.forbidden({body:{...IP_FILTER_REJECTION_BODY}})){const result=scope.rateLimitManager?.checkIpFilter(clientIp);if(!result||result.allowed)return;scope.logger.warn("request rejected by ipFilter",{reason:result.reason,hasClientIp:clientIp!==void 0});FlowControl.respond(buildRejection())}function buildPartitionContext(source){if(!source)return void 0;const clientId=source.authInfo?.clientId;const userId=(0,import_auth39.isAnonymousSubject)(clientId)?void 0:String(clientId);const callerKey=userId?`user:${userId}`:"anonymous";return{sessionId:verifiedSessionOf(source)??callerKey,clientIp:source.metadata?.clientIp,userId}}function verifiedSessionOf(source){if("verifiedSessionId"in source)return source.verifiedSessionId;const confirmed=source.authInfo?.sessionId??source.authInfo?.extra?.sessionId;return confirmed===source.sessionId?source.sessionId:void 0}function partitionsByIdentity(partitionBy){return partitionBy==="session"||partitionBy==="userId"||typeof partitionBy==="function"}async function enforceGlobalRateLimit(scope,context){const manager=scope.rateLimitManager;const globalConfig=manager?.config?.global;const partitionBy=globalConfig?.partitionBy;if(!manager||!globalConfig||partitionBy==="session"||partitionBy==="userId")return;let result;try{result=await manager.checkGlobalRateLimit(buildPartitionContext(context))}catch(error){if(!(error instanceof import_guard7.GuardStorageUnavailableError))throw error;FlowControl.respond(httpRespond.json({error:"service_unavailable",message:"Service temporarily unavailable: the rate-limit store cannot be reached",code:error.code},{status:error.statusCode,headers:{"Retry-After":"1"}}))}context?.set(GLOBAL_RATE_LIMIT_CHECKED,true);if(result.allowed)return;const retryAfter=Math.ceil((result.retryAfterMs??6e4)/1e3);FlowControl.respond(httpRespond.json({error:"rate_limited",message:`Rate limit exceeded. Retry after ${retryAfter} seconds`},{status:429,headers:{"Retry-After":String(retryAfter)}}))}async function acquireConcurrencySlots(manager,entityName,entityConfig,partitionContext,options={}){const globalConfig=options.skipGlobal?void 0:manager.config.globalConcurrency;const globalTicket=globalConfig?await manager.acquireGlobalSemaphore(partitionContext):null;if(globalConfig&&!globalTicket){throw new import_guard7.ConcurrencyLimitError("global",globalConfig.maxConcurrent)}const config=entityConfig??manager.config.defaultConcurrency;if(!config)return globalTicket??void 0;let entityTicket;try{entityTicket=await manager.acquireSemaphore(entityName,config,partitionContext)}catch(error){await globalTicket?.release();throw error}if(!entityTicket){await globalTicket?.release();throw new import_guard7.ConcurrencyLimitError(entityName,config.maxConcurrent)}if(!globalTicket)return entityTicket;const heldEntityTicket=entityTicket;return{ticket:heldEntityTicket.ticket,release:async()=>{try{await heldEntityTicket.release()}finally{await globalTicket.release()}}}}var import_auth39,import_guard7,IP_FILTER_REJECTION_BODY,GLOBAL_RATE_LIMIT_CHECKED;var init_guard_utils=__esm({"libs/sdk/src/common/utils/guard.utils.ts"(){"use strict";import_auth39=require("@frontmcp/auth");import_guard7=require("@frontmcp/guard");init_flow_interface();init_http_output_schema();IP_FILTER_REJECTION_BODY={error:"forbidden",message:"Client IP rejected by ipFilter"};GLOBAL_RATE_LIMIT_CHECKED=Symbol.for("frontmcp:guard:global-rate-limit-checked")}});function toStringArray(value){if(Array.isArray(value))return value.filter(v=>typeof v==="string");if(typeof value==="string"&&value.length>0)return value.split(" ").filter(Boolean);return[]}function asRecord(value){return value&&typeof value==="object"?value:void 0}function firstPresent(sources,convert){for(const source of sources){if(source!==void 0&&source!==null)return convert(source)}return[]}function resolvePrincipal2(authInfo,contextBuilder){const info=authInfo??{};const user=asRecord(info["user"])??{};const extraAuthorization=asRecord(asRecord(info["extra"])?.["authorization"]);const authInfoClaims=asRecord(info["claims"])??{};const authorizationClaims=asRecord(extraAuthorization?.["claims"])??{};const claims={...authorizationClaims,...authInfoClaims,...user};const scopes=toStringArray(info["scopes"]).length?toStringArray(info["scopes"]):firstPresent([extraAuthorization?.["scopes"],claims["scope"],claims["scopes"]],toStringArray);if(contextBuilder){const ctx=contextBuilder.build(info);return{sub:ctx.user.sub??"",roles:ctx.user.roles,permissions:ctx.user.permissions,scopes,claims:ctx.user.claims}}const roles=firstPresent([user["roles"],claims["roles"],extraAuthorization?.["scopes"]],toStringArray);const permissions=firstPresent([user["permissions"],claims["permissions"]],toStringArray);return{sub:typeof user["sub"]==="string"?user["sub"]:"",roles,permissions,scopes,claims}}var init_principal_utils=__esm({"libs/sdk/src/common/utils/principal.utils.ts"(){"use strict"}});function getGlobalStoreConfig(pluginName,config){if(!config.redis){throw new GlobalConfigNotFoundError(pluginName,"redis")}return config.redis}var init_global_config_utils=__esm({"libs/sdk/src/common/utils/global-config.utils.ts"(){"use strict";init_errors()}});var init_utils3=__esm({"libs/sdk/src/common/utils/index.ts"(){"use strict";init_auth_info_utils();init_caller_dir_utils();init_decide_request_intent_utils();init_guard_utils();init_path_utils();init_principal_utils();init_global_config_utils();init_primitive_filter();init_validate_remote_url()}});var FrontMcpAuth;var init_primary_auth_provider_interface=__esm({"libs/sdk/src/common/interfaces/internal/primary-auth-provider.interface.ts"(){"use strict";init_types();init_utils3();FrontMcpAuth=class{ready;options;id;constructor(options){this.options=options;this.id=this.deriveId(options)}deriveId(options){if((0,import_auth13.isPublicMode)(options)){return options.issuer??"public"}if((0,import_auth13.isTransparentMode)(options)){return options.providerConfig?.id??urlToSafeId(options.provider)}if((0,import_auth13.isOrchestratedMode)(options)){if((0,import_auth13.isOrchestratedRemote)(options)){return options.providerConfig?.id??urlToSafeId(options.provider)}return options.local?.issuer??"local"}return"unknown"}verifyGatewayToken(_token,_requestBaseUrl,_expectedAudience,_expectedIssuer){return Promise.resolve({ok:false,error:"gateway token verification is not supported by this auth mode"})}}}});var init_registry_interface=__esm({"libs/sdk/src/common/interfaces/internal/registry.interface.ts"(){"use strict"}});var init_internal=__esm({"libs/sdk/src/common/interfaces/internal/index.ts"(){"use strict";init_primary_auth_provider_interface();init_registry_interface()}});var init_interfaces2=__esm({"libs/sdk/src/common/interfaces/index.ts"(){"use strict";init_base_interface();init_execution_context_interface();init_front_mcp_interface();init_server_interface();init_scope_interface();init_flow_interface();init_hook_interface();init_app_interface();init_provider_interface();init_auth_provider_interface();init_adapter_interface();init_plugin_interface();init_tool_interface();init_resource_interface();init_prompt_interface();init_logger_interface();init_llm_adapter_interface();init_agent_interface();init_skill_interface();init_job_interface();init_workflow_interface();init_channel_interface();init_internal()}});var Sep2640SkillFileResource;var init_skill_file_resource=__esm({"libs/sdk/src/skill/sep-2640/resources/skill-file.resource.ts"(){"use strict";init_common();init_interfaces2();init_errors();init_skill_authorities_helper();init_skill_filter_helper();init_sep_2640_resource_helpers();Sep2640SkillFileResource=class extends ResourceContext{async skillPathCompleter(partial){const visible=getSepVisibleSkills(this.scope);const authorized=await filterSkillsByAuthorities(this.scope,visible,this.getAuthInfo());const skills=await filterServableSkills(this.scope,authorized);const paths=skills.map(s=>s.getSkillPath());const filtered=partial?paths.filter(p=>p.toLowerCase().startsWith(partial.toLowerCase())):paths;return{values:filtered,total:filtered.length}}async filePathCompleter(partial){const visible=getSepVisibleSkills(this.scope);const authorized=await filterSkillsByAuthorities(this.scope,visible,this.getAuthInfo());const skills=await filterServableSkills(this.scope,authorized);const seen=new Set;for(const skill of skills){try{const content=await skill.load();for(const ref of content.resolvedReferences??[]){if(ref.filename)seen.add(`references/${ref.filename}`)}for(const ex of content.resolvedExamples??[]){if(ex.filename)seen.add(`examples/${ex.filename}`)}}catch{}}const all=Array.from(seen).sort();const filtered=partial?all.filter(p=>p.toLowerCase().startsWith(partial.toLowerCase())):all;return{values:filtered,total:filtered.length}}async execute(uri,params){if(params.filePath==="SKILL.md"||params.filePath.endsWith("/SKILL.md")){throw new ResourceNotFoundError(uri)}const entry=findSkillByPath(this.scope,params.skillPath);if(!entry){await findAndLoadSkillByPath(this.scope,params.skillPath);throw new ResourceNotFoundError(uri)}if(!await isSkillServable(this.scope,entry)){throw new ResourceNotFoundError(uri)}const instance=entry;await assertSkillAuthorized(this.scope,instance,this.getAuthInfo());const result=await readSkillFileByPath(instance,params.filePath);return{contents:[result.kind==="text"?{uri,mimeType:result.mimeType,text:result.content}:{uri,mimeType:result.mimeType,blob:result.blob}]}}};Sep2640SkillFileResource=__decorateClass([_ResourceTemplate({name:"sep2640-skill-file",uriTemplate:"skill://{+skillPath}/{+filePath}",description:"Read any file inside a skill directory (references, examples, scripts, assets, top-level files) per MCP SEP-2640. Path traversal is rejected."})],Sep2640SkillFileResource)}});var Sep2640SkillIndexResource;var init_skill_index_resource=__esm({"libs/sdk/src/skill/sep-2640/resources/skill-index.resource.ts"(){"use strict";init_common();init_interfaces2();init_skill_authorities_helper();init_skill_filter_helper();init_sep_2640_builders();init_sep_2640_constants();init_sep_2640_resource_helpers();Sep2640SkillIndexResource=class extends ResourceContext{async execute(uri){const visible=getSepVisibleSkills(this.scope);const authorized=await filterSkillsByAuthorities(this.scope,visible,this.getAuthInfo());const skills=await filterServableSkills(this.scope,authorized);const entries=skills.map(skill=>buildSkillMdIndexEntry({name:skill.metadata.name,description:skill.getDescription(),skillPathSegments:skill.getSkillPathSegments()}));for(const metadata of await getExternalProviderSkills(this.scope)){entries.push(buildSkillMdIndexEntry({name:metadata.name,description:metadata.description}))}if(entries.length>0){entries.push(buildResourceTemplateIndexEntry("Read the raw SKILL.md (frontmatter + body) for any skill served by this MCP server.","skill://{+skillPath}/SKILL.md"))}const registry=this.scope.skills;const templates=registry?.getSep2640IndexTemplates?.()??[];for(const tpl of templates){entries.push(tpl)}const archives=registry?.getSep2640IndexArchives?.()??[];for(const arc of archives){entries.push(arc)}const document=buildSkillIndex(entries);return{contents:[{uri,mimeType:SKILL_INDEX_MIME_TYPE,text:JSON.stringify(document,null,2)}]}}};Sep2640SkillIndexResource=__decorateClass([Resource({name:"sep2640-skill-index",uri:SKILL_INDEX_URI,description:"SEP-2640 skill discovery index. Lists every MCP-visible skill with its name, description, and full skill:// URI. Resource templates and archive entries may also appear when configured.",mimeType:SKILL_INDEX_MIME_TYPE})],Sep2640SkillIndexResource)}});var Sep2640SkillMdResource;var init_skill_md_resource=__esm({"libs/sdk/src/skill/sep-2640/resources/skill-md.resource.ts"(){"use strict";init_common();init_interfaces2();init_skill_authorities_helper();init_skill_filter_helper();init_sep_2640_builders();init_sep_2640_constants();init_sep_2640_resource_helpers();Sep2640SkillMdResource=class extends ResourceContext{async skillPathCompleter(partial){const visible=getSepVisibleSkills(this.scope);const authorized=await filterSkillsByAuthorities(this.scope,visible,this.getAuthInfo());const skills=await filterServableSkills(this.scope,authorized);const paths=skills.map(s=>s.getSkillPath());const filtered=partial?paths.filter(p=>p.toLowerCase().startsWith(partial.toLowerCase())):paths;return{values:filtered,total:filtered.length}}async execute(uri,params){const raw=serializeSkillMd(await this.readSkill(params.skillPath));return{contents:[{uri,mimeType:SKILL_MD_MIME_TYPE,text:raw}]}}async readSkill(skillPath){if(!findSkillByPath(this.scope,skillPath)){const providerSkill=await loadExternalProviderSkill(this.scope,skillPath);if(providerSkill)return providerSkill}const{loadResult,instance}=await findAndLoadSkillByPath(this.scope,skillPath);await assertSkillAuthorized(this.scope,instance,this.getAuthInfo());return loadResult.skill}};Sep2640SkillMdResource=__decorateClass([_ResourceTemplate({name:"sep2640-skill-md",uriTemplate:"skill://{+skillPath}/SKILL.md",description:"Read a skill's SKILL.md (raw YAML frontmatter + markdown body) per MCP SEP-2640. Conformant clients parse the frontmatter identically to filesystem skills.",mimeType:SKILL_MD_MIME_TYPE})],Sep2640SkillMdResource)}});var resources_exports={};__export(resources_exports,{Sep2640SkillFileResource:()=>Sep2640SkillFileResource,Sep2640SkillIndexResource:()=>Sep2640SkillIndexResource,Sep2640SkillMdResource:()=>Sep2640SkillMdResource,getSep2640Resources:()=>getSep2640Resources});function getSep2640Resources(){return[Sep2640SkillIndexResource,Sep2640SkillMdResource,Sep2640SkillFileResource]}var init_resources=__esm({"libs/sdk/src/skill/sep-2640/resources/index.ts"(){"use strict";init_skill_file_resource();init_skill_index_resource();init_skill_md_resource()}});function declaresDynamicSkills(metadata){return metadata.dynamicSkills===true||(metadata.plugins??[]).some(plugin=>declaresDynamicSkills(normalizePlugin(plugin).metadata))}function pluginsRegisterDynamicSkills(plugins){for(const plugin of plugins){if(declaresDynamicSkills(normalizePlugin(plugin).metadata))return true}return false}async function registerSkillCapabilities(options){const{skillRegistry,flowRegistry,resourceRegistry,providers,skillsConfig,logger,dynamicSkills}=options;registerSkillAuditWriter({providers,audit:skillsConfig?.audit,logger});await flowRegistry.registryFlows([FilterSkillsFlow]);if(dynamicSkills){skillRegistry.expectDynamicSkills()}if(skillsConfig?.externalProvider){await skillsConfig.externalProvider.initialize();skillRegistry.setExternalProvider(skillsConfig.externalProvider)}if(!skillRegistry.servesSkills()){return}const{LlmFullTxtFlow:LlmFullTxtFlow2,LlmTxtFlow:LlmTxtFlow2,LoadSkillFlow:LoadSkillFlow2,SearchSkillsFlow:SearchSkillsFlow2,SkillsApiFlow:SkillsApiFlow2}=await Promise.resolve().then(()=>(init_flows(),flows_exports));await flowRegistry.registryFlows([SearchSkillsFlow2,LoadSkillFlow2]);const shouldRegisterResources=skillsConfig?.mcpResources!==false;if(shouldRegisterResources){await registerSep2640Resources({resourceRegistry,logger});const[{registerPerSkillResources:registerPerSkillResources2},{resolveLastModifiedForSkill:resolveLastModifiedForSkill2}]=await Promise.all([Promise.resolve().then(()=>(init_sep_2640_per_skill(),sep_2640_per_skill_exports)),Promise.resolve().then(()=>(init_sep_2640_last_modified(),sep_2640_last_modified_exports))]);await registerPerSkillResources2({scope:providers.getActiveScope(),skillRegistry,resourceRegistry,logger,resolveLastModified:resolveLastModifiedForSkill2})}else{logger.verbose("SEP-2640 skill:// resources disabled via skillsConfig.mcpResources=false")}if(skillsConfig?.enabled){await flowRegistry.registryFlows([LlmTxtFlow2,LlmFullTxtFlow2,SkillsApiFlow2]);logger.verbose("Registered skills HTTP flows (llm.txt, llm_full.txt, /skills API)")}}async function registerSep2640Resources(options){const{resourceRegistry,logger}=options;const{getSep2640Resources:getSep2640Resources2}=await Promise.resolve().then(()=>(init_resources(),resources_exports));const resources=getSep2640Resources2();for(const ResourceClass of resources){try{resourceRegistry.registerDynamicResource(ResourceClass);const resourceName=typeof ResourceClass==="function"?ResourceClass.name:"unknown";logger.verbose(`Registered SEP-2640 resource: ${resourceName}`)}catch(error){logger.warn(`Failed to register SEP-2640 resource: ${error instanceof Error?error.message:String(error)}`)}}}var init_skill_scope_helper=__esm({"libs/sdk/src/skill/skill-scope.helper.ts"(){"use strict";init_plugin_utils();init_filter_skills_flow();init_skill_audit_helper()}});function isExplicitStorage(storage){return Boolean(storage?.type&&storage.type!=="auto")}function resolvesToVercelKvTaskBackend(redis,storage){if(isExplicitStorage(storage))return storage.type==="vercel-kv";if(redis)return"provider"in redis&&redis.provider==="vercel-kv";return Boolean((0,import_utils85.getEnv)("KV_REST_API_URL"))}var import_utils85;var init_task_backend_utils=__esm({"libs/sdk/src/task/store/task-backend.utils.ts"(){"use strict";import_utils85=require("@frontmcp/utils")}});function describeMode(mode){return typeof mode==="function"?"a function":`'${String(mode)}'`}function protocolAdvice(protocol,remove){return protocol==="stateless-api"?`The server already serves without sessions (\`transport.protocol: 'stateless-api'\`); remove \`${remove}\`.`:`To serve without sessions, set \`transport.protocol: 'stateless-api'\` and remove \`${remove}\`.`}function warnIfSessionModeIgnored(options){const{logger,transport,session}=options;const mode=transport?.sessionMode;if(transport&&mode!==void 0&&mode!=="stateful"&&!warned.has(transport)){warned.add(transport);logger.warn(`transport.sessionMode (${describeMode(mode)}) ${REMOVAL}: sessions follow \`transport.protocol\`. `+protocolAdvice(transport.protocol,"sessionMode"))}if(!session||warned.has(session))return;const legacyMode=session.sessionMode;const ignored=[];if(legacyMode!==void 0&&legacyMode!=="stateful"){ignored.push(`session.sessionMode (${describeMode(legacyMode)}) ${REMOVAL}, with the rest of \`session\`: sessions follow \`transport.protocol\`, and provider tokens always stay server-side (\`auth.tokenStorage\`), never in the JWT. ${protocolAdvice(transport?.protocol,"session")}`)}if(session.platformDetection!==void 0){ignored.push(`session.platformDetection ${REMOVAL}, with the rest of \`session\`: move it to \`transport.platformDetection\`.`)}if(ignored.length===0)return;warned.add(session);for(const message of ignored)logger.warn(message)}var warned,REMOVAL;var init_session_mode_check=__esm({"libs/sdk/src/transport/session-mode.check.ts"(){"use strict";warned=new WeakSet;REMOVAL="is ignored and will be removed in the next major"}});async function registerServerEntries(providers,entries,appIds){if(!entries.tools?.length&&!entries.resources?.length)return;if(appIds.includes(serverEntryOwner.id))throw new ReservedAppIdError(serverEntryOwner.id);const registries=[];if(entries.tools?.length){registries.push(new ToolRegistry(providers,entries.tools,serverEntryOwner,{adopt:false}).ready)}if(entries.resources?.length){registries.push(new ResourceRegistry(providers,entries.resources,serverEntryOwner,{adopt:false}).ready)}await Promise.all(registries)}var init_server_entries_helper=__esm({"libs/sdk/src/scope/server-entries.helper.ts"(){"use strict";init_errors();init_resource_registry();init_tool_registry();init_lineage_utils()}});function reportStartup(plugins,report,logger){const installed=plugins?.getPlugins()??[];for(const plugin of installed){try{plugin.reportStartupTelemetry?.({...report,pluginsCount:installed.length})}catch(error){logger.warn("A plugin failed to report startup telemetry",{error:error instanceof Error?error.message:String(error)})}}}var init_startup_report_helper=__esm({"libs/sdk/src/scope/startup-report.helper.ts"(){"use strict"}});function constantTimeEquals(a,b){const encoder6=new TextEncoder;return(0,import_utils86.timingSafeEqual)((0,import_utils86.sha256)(encoder6.encode(a)),(0,import_utils86.sha256)(encoder6.encode(b)))}function quoteHeaderParam(value){return value.replace(/[^\x20-\x21\x23-\x7e]/g,"")}function buildStaticChallenge(options,description){const scheme=options.scheme.trim();if(!scheme)return"";const parts=[`${quoteHeaderParam(scheme)} realm="${quoteHeaderParam(options.realm)}"`];if(description){parts.push('error="invalid_token"',`error_description="${quoteHeaderParam(description)}"`)}return parts.join(", ")}var import_reflect_metadata19,import_auth40,import_lazy_zod72,import_utils86,inputSchema19,stateSchema19,UnauthorizedSchema,AuthorizedSchema,ForbiddenSchema,sessionVerifyOutputSchema,plan19,name19,Stage19,warnedUnpinnedAudience,SessionVerifyFlow;var init_session_verify_flow=__esm({"libs/sdk/src/auth/flows/session.verify.flow.ts"(){"use strict";init_common();import_reflect_metadata19=require("reflect-metadata");import_auth40=require("@frontmcp/auth");import_lazy_zod72=require("@frontmcp/lazy-zod");import_utils86=require("@frontmcp/utils");init_notification_service();init_skill_mode_utils();init_session_id_utils();inputSchema19=httpRequestInputSchema.extend({sessionless:import_lazy_zod72.z.boolean().optional()});stateSchema19=import_lazy_zod72.z.object({baseUrl:import_lazy_zod72.z.string().min(1),authorizationHeader:import_lazy_zod72.z.string().optional(),token:import_lazy_zod72.z.string().optional(),sessionIdHeader:import_lazy_zod72.z.string().optional(),sessionProtocol:import_lazy_zod72.z.string().optional(),userAgent:import_lazy_zod72.z.string().optional(),prmMetadataPath:import_lazy_zod72.z.string().optional(),prmMetadataHeader:import_lazy_zod72.z.string().optional(),prmUrl:import_lazy_zod72.z.string().optional(),jwtPayload:import_lazy_zod72.z.object({}).passthrough().optional(),user:import_auth5.userClaimSchema.optional(),session:sessionIdSchema.optional()});UnauthorizedSchema=import_lazy_zod72.z.object({kind:import_lazy_zod72.z.literal("unauthorized"),prmMetadataHeader:import_lazy_zod72.z.string().describe("Path to protected resource metadata")}).describe("401 Unauthorized with 'WWW-Authenticate' header for requesting authentication");AuthorizedSchema=import_lazy_zod72.z.object({kind:import_lazy_zod72.z.literal("authorized"),authorization:authorizationSchema.describe("Session information if session id is present")}).describe("Authorized session information");ForbiddenSchema=import_lazy_zod72.z.object({kind:import_lazy_zod72.z.literal("forbidden"),prmMetadataHeader:import_lazy_zod72.z.string().describe("WWW-Authenticate header with insufficient_scope error")}).describe("403 Forbidden \u2014 token valid but insufficient scope");sessionVerifyOutputSchema=import_lazy_zod72.z.union([UnauthorizedSchema,AuthorizedSchema,ForbiddenSchema]);plan19={pre:["parseInput","handleStaticToken","handlePublicMode","handleAnonymousFallback","requireAuthorizationHeader","verifyIfJwt"],execute:["deriveUser","parseSessionHeader","buildAuthorizedOutput"]};name19="session:verify";Stage19=StageHookOf(name19);warnedUnpinnedAudience=false;SessionVerifyFlow=class extends FlowBase{logger=this.scopeLogger.child("SessionVerifyFlow");maskSub(sub){if(!sub)return"***";if(sub.length<=10)return"***"+sub.slice(-4);return sub.slice(0,6)+"***"+sub.slice(-4)}createAnonymousSession(options){const{authMode,subject,sessionIdHeader}=options;this.logger.verbose("createAnonymousSession",{authMode,hasExistingSession:!!sessionIdHeader});if(this.rawInput.sessionless){this.respond({kind:"authorized",authorization:{token:"",user:(0,import_auth40.anonymousCallerClaims)(options,(0,import_utils86.randomUUID)())}});return}const machineId=(0,import_utils86.getMachineId)();const authSignature=subject?`${authMode}:${subject}`:authMode;if(sessionIdHeader){const body=this.rawInput.request.body;const isInitialize2=typeof body==="object"&&body!==null&&"method"in body&&body.method==="initialize";const decrypted=decryptPublicSession(sessionIdHeader,authSignature);const existingPayload=decrypted&&isInitialize2&&decrypted.nodeId!==machineId?void 0:decrypted;if(existingPayload){const anonId=existingPayload.uuid??`${existingPayload.iat*1e3}`;const user2=(0,import_auth40.anonymousCallerClaims)(options,anonId);this.respond({kind:"authorized",authorization:{token:"",user:user2,session:{id:sessionIdHeader,payload:existingPayload}}});return}this.logger.verbose("createAnonymousSession: ignoring unrecognized client session id; minting a fresh one")}const now=Date.now();const uuid=(0,import_utils86.randomUUID)();const user=(0,import_auth40.anonymousCallerClaims)(options,uuid);const platformDetectionConfig=this.scope.metadata.transport?.platformDetection;const platformType=detectPlatformFromUserAgent(this.state.userAgent,platformDetectionConfig);const payload={uuid,nodeId:machineId,authSig:authSignature,iat:Math.floor(now/1e3),isPublic:authMode==="public",authMode,...platformType!=="unknown"&&{platformType},...detectSkillsOnlyMode(this.rawInput.request.query)&&{skillsOnlyMode:true}};const sessionId=(0,import_auth40.encryptJson)(payload);this.respond({kind:"authorized",authorization:{token:"",user,session:{id:sessionId,payload}}})}async parseInput(){const{request}=this.rawInput;const entryPath=normalizeEntryPrefix(this.scope.entryPath);const routeBase=normalizeScopeBase(this.scope.routeBase);const baseUrl=getRequestBaseUrl(request,entryPath);const authorizationHeader=request.headers?.["authorization"]??void 0;const httpTransportHeader=request.headers?.["http-transport"];const sessionIdRawHeader=request.headers?.["mcp-session-id"];const sessionIdQuery=request.query["sessionId"];const sessionIdHeader=sessionIdRawHeader??sessionIdQuery??void 0;const sessionProtocol=httpTransportHeader?"http":sessionIdRawHeader?"streamable-http":sessionIdQuery?"sse":void 0;const token=(0,import_auth40.extractBearerToken)(authorizationHeader);const userAgent=request.headers?.["user-agent"]??void 0;const prmMetadataPath=`/.well-known/oauth-protected-resource${entryPath}${routeBase}`;const prmUrl=`${getRequestBaseUrl(request)}${prmMetadataPath}`;const prmMetadataHeader=(0,import_auth40.buildUnauthorizedHeader)(prmUrl);this.logger.verbose("parseInput",{hasAuthHeader:!!authorizationHeader,hasToken:!!token,sessionProtocol,hasSessionId:!!sessionIdHeader});this.state.set({baseUrl,authorizationHeader,token,sessionIdHeader,sessionProtocol,userAgent,prmMetadataPath,prmMetadataHeader,prmUrl})}async handleStaticToken(){const authOptions=this.scope.auth?.options;if(!authOptions||!(0,import_auth13.isStaticMode)(authOptions))return;const options=authOptions;const presented=this.readStaticCredential(options);if(!presented){this.logger.warn("handleStaticToken: no credential presented, returning 401");this.respond({kind:"unauthorized",prmMetadataHeader:buildStaticChallenge(options)});return}const matched=options.tokens.reduce((found,candidate)=>constantTimeEquals(candidate,presented)?candidate:found,void 0);if(!matched){this.logger.warn("handleStaticToken: credential did not match, returning 401");this.respond({kind:"unauthorized",prmMetadataHeader:buildStaticChallenge(options,"The access token is invalid")});return}this.logger.verbose("handleStaticToken: credential accepted");this.createAnonymousSession({authMode:"static",issuer:"static",scopes:options.scopes,subject:`static:${(0,import_utils86.sha256Hex)(matched).slice(0,12)}`,sessionIdHeader:this.state.sessionIdHeader})}readStaticCredential(options){const headers=this.rawInput.request.headers??{};const raw=headers[options.header.toLowerCase()];const value=(Array.isArray(raw)?raw[0]:raw)?.trim();if(!value)return void 0;const{scheme}=options;if(!scheme)return value;if(value.slice(0,scheme.length).toLowerCase()!==scheme.toLowerCase())return void 0;if(value[scheme.length]!==" ")return void 0;return value.slice(scheme.length+1).trim()||void 0}async handlePublicMode(){const authOptions=this.scope.auth?.options;if(!authOptions||!(0,import_auth13.isPublicMode)(authOptions)){return}if(this.state.token&&(0,import_auth40.isJwt)(this.state.token)){return}if(this.state.token){this.logger.verbose("handlePublicMode: ignoring non-JWT bearer token (public mode has nothing to verify it against)")}this.logger.verbose("handlePublicMode: allowing anonymous access (public mode)");this.createAnonymousSession({authMode:"public",issuer:"public",scopes:authOptions.anonymousScopes??["anonymous"],sessionIdHeader:this.state.sessionIdHeader})}async handleAnonymousFallback(){this.logger.verbose("handleAnonymousFallback: creating anonymous session (transparent-anon)");const authOptions=this.scope.auth?.options;const scopes=authOptions?.anonymousScopes??["anonymous"];this.createAnonymousSession({authMode:"transparent-anon",issuer:"transparent-anon",scopes,sessionIdHeader:this.state.sessionIdHeader})}async requireAuthorizationOrChallenge(){this.logger.verbose("requireAuthorizationOrChallenge: returning 401");this.respond({kind:"unauthorized",prmMetadataHeader:this.state.required.prmMetadataHeader})}async verifyIfJwt(){const jwks=this.get(import_auth40.JwksService);const token=this.state.token;if(!token){this.logger.warn("verifyIfJwt: missing or empty bearer token, returning 401");this.respond({kind:"unauthorized",prmMetadataHeader:this.state.required.prmMetadataHeader});return}if(!(0,import_auth40.isJwt)(token)){this.logger.warn("verifyIfJwt: token is not a JWT, returning 401");this.respond({kind:"unauthorized",prmMetadataHeader:(0,import_auth40.buildInvalidTokenHeader)(this.state.required.prmUrl,"Token is not a valid JWT")});return}const auth=this.scope.auth;if(!auth){this.logger.warn("verifyIfJwt: auth registry not available, returning 401");this.respond({kind:"unauthorized",prmMetadataHeader:this.state.required.prmMetadataHeader});return}let verify;const authOptions=auth.options;const mode=(0,import_auth13.isTransparentMode)(authOptions)?"transparent":"gateway";this.logger.verbose(`verifyIfJwt: verifying using ${mode} mode`);if((0,import_auth13.isTransparentMode)(authOptions)){const primary=authOptions;const issuer=auth.issuer;const providerRefs=[{id:primary.providerConfig?.id??"default",issuerUrl:issuer,additionalIssuers:primary.providerConfig?.additionalIssuers,verifyIssuer:primary.providerConfig?.verifyIssuer,jwks:primary.providerConfig?.jwks,jwksUri:primary.providerConfig?.jwksUri}];verify=jwks.verifyTransparentToken(token,providerRefs)}else{const configuredAudience=(0,import_auth13.isOrchestratedMode)(authOptions)?authOptions.expectedAudience:void 0;const resource=computeResource(this.rawInput.request,this.scope.entryPath,this.scope.routeBase);const issuer=auth.acceptedIssuersFor?.(this.rawInput.request);verify=auth.verifyGatewayToken(token,this.state.required.baseUrl,configuredAudience??resource,issuer)}const result=await verify;if(result.ok){this.state.set({jwtPayload:result.payload});if((0,import_auth13.isTransparentMode)(authOptions)){const configuredAudience=authOptions.expectedAudience;if(!configuredAudience&&!isPublicUrlPinned()&&!warnedUnpinnedAudience){warnedUnpinnedAudience=true;this.logger.warn("transparent audience validation is deriving the expected audience from the request Host: set auth.expectedAudience or FRONTMCP_PUBLIC_URL to bind tokens to a fixed resource. X-Forwarded-Host is ignored unless FRONTMCP_TRUST_PROXY is enabled.")}const expectedAudiences=configuredAudience?Array.isArray(configuredAudience)?configuredAudience:[configuredAudience]:(0,import_auth40.deriveExpectedAudience)(this.state.required.baseUrl);const audResult=(0,import_auth40.validateAudience)(result.payload?.["aud"],{expectedAudiences,allowNoAudience:authOptions.requireAudience!==true});if(!audResult.valid){this.logger.warn("verifyIfJwt: audience validation failed",{error:audResult.error});this.respond({kind:"unauthorized",prmMetadataHeader:(0,import_auth40.buildInvalidTokenHeader)(this.state.required.prmUrl,audResult.error??"Token audience is not valid for this resource")});return}}const requiredScopes=authOptions?.["requiredScopes"];if(requiredScopes&&requiredScopes.length>0){const tokenScopes=(0,import_auth40.scopesFromClaims)(result.payload);const hasAll=requiredScopes.every(s=>tokenScopes.includes(s));if(!hasAll){this.logger.warn("verifyIfJwt: insufficient scopes",{required:requiredScopes,actual:tokenScopes});this.respond({kind:"forbidden",prmMetadataHeader:(0,import_auth40.buildInsufficientScopeHeader)(this.state.required.prmUrl,requiredScopes)});return}}return}this.logger.warn("verifyIfJwt: JWT verification failed",{error:result.error});this.respond({kind:"unauthorized",prmMetadataHeader:(0,import_auth40.buildInvalidTokenHeader)(this.state.required.prmUrl,result.error??"Token verification failed")})}async deriveUser(){const user=(0,import_auth40.deriveTypedUser)(this.state.required.jwtPayload??{});if(!user.sub){this.logger.warn("deriveUser: verified token has no sub, client_id or azp claim, returning 401");this.respond({kind:"unauthorized",prmMetadataHeader:(0,import_auth40.buildInvalidTokenHeader)(this.state.required.prmUrl,"Token has no subject: the sub, client_id and azp claims are all missing")});return}this.state.set("user",user)}async parseSessionHeader(){const{sessionIdHeader,required:{token}}=this.state;const session=parseSessionHeader(sessionIdHeader,token);this.logger.verbose("parseSessionHeader",{hasSessionId:!!sessionIdHeader,parsed:!!session});if(session){this.state.set("session",session)}}async buildAuthorizedOutput(){const{required:{token,user},session}=this.state;this.logger.verbose("Session verified successfully",{sub:this.maskSub(user.sub),hasSession:!!session});this.respond({kind:"authorized",authorization:{token,user,session}})}};__decorateClass([Stage19("parseInput")],SessionVerifyFlow.prototype,"parseInput",1);__decorateClass([Stage19("handleStaticToken",{filter:({scope})=>{const authOptions=scope.auth?.options;return!!authOptions&&(0,import_auth13.isStaticMode)(authOptions)}})],SessionVerifyFlow.prototype,"handleStaticToken",1);__decorateClass([Stage19("handlePublicMode")],SessionVerifyFlow.prototype,"handlePublicMode",1);__decorateClass([Stage19("handleAnonymousFallback",{filter:({state,scope})=>{if(state.token)return false;const authOptions=scope.auth?.options;if(!authOptions||!(0,import_auth13.isTransparentMode)(authOptions))return false;return authOptions.allowAnonymous===true}})],SessionVerifyFlow.prototype,"handleAnonymousFallback",1);__decorateClass([Stage19("requireAuthorizationHeader",{filter:({state,scope})=>{if(state.authorizationHeader)return false;const authOptions=scope.auth?.options;if(authOptions&&(0,import_auth13.isPublicMode)(authOptions))return false;if(authOptions&&(0,import_auth13.isTransparentMode)(authOptions)){if(authOptions.allowAnonymous===true)return false}return true}})],SessionVerifyFlow.prototype,"requireAuthorizationOrChallenge",1);__decorateClass([Stage19("verifyIfJwt")],SessionVerifyFlow.prototype,"verifyIfJwt",1);__decorateClass([Stage19("deriveUser")],SessionVerifyFlow.prototype,"deriveUser",1);__decorateClass([Stage19("parseSessionHeader")],SessionVerifyFlow.prototype,"parseSessionHeader",1);__decorateClass([Stage19("buildAuthorizedOutput")],SessionVerifyFlow.prototype,"buildAuthorizedOutput",1);SessionVerifyFlow=__decorateClass([FrontMcpFlow({name:name19,plan:plan19,inputSchema:inputSchema19,outputSchema:sessionVerifyOutputSchema,access:"authorized"})],SessionVerifyFlow)}});var DEFAULT_FRONTMCP_NODE_COOKIE,DEFAULT_FRONTMCP_MACHINE_ID_HEADER;var init_ha_constants=__esm({"libs/sdk/src/ha/ha.constants.ts"(){"use strict";DEFAULT_FRONTMCP_NODE_COOKIE="__frontmcp_node";DEFAULT_FRONTMCP_MACHINE_ID_HEADER="X-FrontMCP-Machine-Id"}});function machineIdHeader(){if((0,import_utils87.getRuntimeContext)().deployment!=="distributed")return void 0;return[DEFAULT_FRONTMCP_MACHINE_ID_HEADER,(0,import_utils87.getMachineId)()]}function applyMachineIdHeader(response){const header=machineIdHeader();if(!header)return false;response.setHeader(header[0],header[1]);return true}function affinityCookieOptions(){const name48=(0,import_utils87.getEnv)("FRONTMCP_AFFINITY_COOKIE")?.trim()||DEFAULT_FRONTMCP_NODE_COOKIE;const domain=(0,import_utils87.getEnv)("FRONTMCP_AFFINITY_COOKIE_DOMAIN")?.trim()||void 0;const rawSameSite=(0,import_utils87.getEnv)("FRONTMCP_AFFINITY_COOKIE_SAMESITE")?.trim().toLowerCase();const sameSite=rawSameSite==="strict"?"Strict":rawSameSite==="lax"?"Lax":rawSameSite==="none"?"None":void 0;return{name:name48,...domain?{domain}:{},...sameSite?{sameSite}:{}}}function applyNodeAffinity(response,request){if(!applyMachineIdHeader(response))return;const cookie=(0,import_utils87.buildSetCookie)({...affinityCookieOptions(),value:(0,import_utils87.getMachineId)()},request);if(!cookie)return;const existing=response.getHeader("Set-Cookie");const existingArr=Array.isArray(existing)?existing:existing?[String(existing)]:[];response.setHeader("Set-Cookie",[...existingArr,cookie])}var import_utils87;var init_ha_headers=__esm({"libs/sdk/src/ha/ha-headers.ts"(){"use strict";import_utils87=require("@frontmcp/utils");init_ha_constants()}});function withoutQuery(url){const end=url.search(/[?#]/);return end===-1?url:`${url.slice(0,end)}?${REDACTED}`}function headerValueForLog(name48,value){const key=name48.toLowerCase();if(CREDENTIAL_HEADERS.has(key)||CREDENTIAL_HEADER_WORDS.test(key))return REDACTED;if(SESSION_ID_HEADER.test(key))return`${String(value).slice(0,8)}...`;if(REFERER_HEADERS.has(key)){return Array.isArray(value)?value.map(entry=>withoutQuery(String(entry))):withoutQuery(String(value))}return value}function headersForLog(headers){return Object.fromEntries(Object.entries(headers).map(([key,value])=>[key,headerValueForLog(key,value)]))}var REDACTED,CREDENTIAL_HEADERS,CREDENTIAL_HEADER_WORDS,SESSION_ID_HEADER,REFERER_HEADERS;var init_request_log_redaction=__esm({"libs/sdk/src/scope/flows/request-log.redaction.ts"(){"use strict";REDACTED="[REDACTED]";CREDENTIAL_HEADERS=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-api-key","x-frontmcp-dashboard-token"]);CREDENTIAL_HEADER_WORDS=/(?:^|-)(?:auth|authorization|token|secret|password|passwd|credential|credentials|key|apikey|signature|cookie)(?:-|$)/;SESSION_ID_HEADER=/(?:^|-)session-id$/;REFERER_HEADERS=new Set(["referer","referrer"])}});var persistent_session_owner_exports={};__export(persistent_session_owner_exports,{claimPersistentSession:()=>claimPersistentSession,persistentSessionCallerKey:()=>persistentSessionCallerKey});function persistentSessionCallerKey(authorization){const sub=authorization?.user?.sub;if(!(0,import_auth41.isAnonymousSubject)(sub)){const iss=authorization?.user?.iss;return`sub:${(0,import_utils88.sha256Hex)(JSON.stringify([typeof iss==="string"?iss:"",sub]))}`}if(authorization?.token)return`token:${(0,import_utils88.sha256Hex)(authorization.token)}`;return null}function claimPersistentSession(session,callerKey,store){if(!owners.has(session)&&store&&store.initial!==void 0){owners.set(session,store.initial)}if(!owners.has(session)){owners.set(session,callerKey);return"claimed"}return owners.get(session)===callerKey?"owner":"refused"}var import_auth41,import_utils88,owners;var init_persistent_session_owner=__esm({"libs/sdk/src/transport/persistent-session-owner.ts"(){"use strict";import_auth41=require("@frontmcp/auth");import_utils88=require("@frontmcp/utils");owners=new WeakMap}});function parseByteLimit(limit){if(typeof limit==="number"&&Number.isFinite(limit)&&limit>=0)return limit;if(typeof limit==="string"){const match=/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb)?$/i.exec(limit.trim());if(match)return Math.floor(Number(match[1])*BYTE_UNITS[(match[2]??"b").toLowerCase()])}return DEFAULT_BODY_LIMIT_BYTES}function mcpTransportBodyLimit(limit){return Math.max(1,parseByteLimit(limit))}var DEFAULT_BODY_LIMIT_BYTES,BYTE_UNITS;var init_body_limit=__esm({"libs/sdk/src/transport/body-limit.ts"(){"use strict";DEFAULT_BODY_LIMIT_BYTES=4*1024*1024;BYTE_UNITS={b:1,kb:1024,mb:1024**2,gb:1024**3}}});var web_standard_mcp_exports={};__export(web_standard_mcp_exports,{buildPersistentWebStandardMcp:()=>buildPersistentWebStandardMcp,runWebStandardMcp:()=>runWebStandardMcp});async function wireServer(scope,serverOptions,sessionId,sessionIdGenerator,enableJsonResponse){const{createMcpHandlers:createMcpHandlers2}=await Promise.resolve().then(()=>(init_mcp_handlers(),mcp_handlers_exports));const mcpServer=new import_protocol50.McpServer(scope.metadata.info,serverOptions);const composeInstructions=caller=>composeCallerInstructions(scope,{ctx:caller,skillUriHints:true});for(const handler of createMcpHandlers2({scope,serverOptions,composeInstructions})){const originalHandler=handler.handler;const wrappedHandler=async(req,ctx)=>{const existingAuthInfo=ctx?.["authInfo"]??{};const enrichedCtx={...ctx,authInfo:{...existingAuthInfo,sessionId}};return originalHandler(req,enrichedCtx)};mcpServer.setRequestHandler(handler.requestSchema,wrappedHandler)}const transport=new import_protocol50.WebStandardStreamableHTTPServerTransport({sessionIdGenerator,enableJsonResponse,maxRequestBodySize:mcpTransportBodyLimit(scope.metadata.http?.bodyLimit)});await mcpServer.connect(transport);return{mcpServer,transport}}async function buildPersistentWebStandardMcp(scope,options){const serverOptions=buildScopedServerOptions(scope);const pair=await wireServer(scope,serverOptions,options.sessionId,()=>options.sessionId,false);return options.owner?{...pair,owner:options.owner}:pair}async function runWebStandardMcp(scope,request,options){if(options.persistent){return options.persistent.transport.handleRequest(request,{authInfo:options.authInfo})}const sessionId=`web:${(0,import_utils89.randomUUID)()}`;const accept=request.headers.get("accept")??"";const wantsStream=request.method==="GET"||options.sse&&accept.includes("text/event-stream");const{mcpServer,transport}=await wireServer(scope,options.serverOptions,sessionId,void 0,!wantsStream);const response=await transport.handleRequest(request,{authInfo:options.authInfo});if(response.headers.get("content-type")?.includes("text/event-stream")){const closed=new Promise(resolve=>{const prev=transport.onclose;transport.onclose=()=>{prev?.();resolve()}});const teardown=closed.then(()=>mcpServer.close().catch(()=>void 0));if(options.ctx?.waitUntil)options.ctx.waitUntil(teardown);else void teardown}else{void mcpServer.close().catch(()=>void 0)}return response}var import_protocol50,import_utils89;var init_web_standard_mcp=__esm({"libs/sdk/src/transport/web-standard-mcp.ts"(){"use strict";import_protocol50=require("@frontmcp/protocol");import_utils89=require("@frontmcp/utils");init_skill_instructions_helper();init_body_limit();init_build_scoped_server_options()}});var import_auth42,import_guard8,import_lazy_zod73,import_utils90,plan20,httpRequestStateSchema,name20,Stage20,HttpRequestFlow;var init_http_request_flow=__esm({"libs/sdk/src/scope/flows/http.request.flow.ts"(){"use strict";import_auth42=require("@frontmcp/auth");import_guard8=require("@frontmcp/guard");import_lazy_zod73=require("@frontmcp/lazy-zod");import_utils90=require("@frontmcp/utils");init_session_verify_flow();init_common();init_schema7();init_errors();init_ha_headers();init_skill_mode_utils();init_mcp_20260728();init_request_log_redaction();plan20={pre:["traceRequest","checkIpFilter","relayToSessionOwner","acquireQuota","acquireSemaphore","checkAuthorization","acquireIdentityQuota","resolveSkillsOnlyMode","router"],execute:["checkPersistentSessionOwner","handleMcp2026","handleWebFetch","handleLegacySse","handleSse","handleStreamableHttp","handleStatefulHttp","handleStatelessHttp","applyDeleteNodeHeaders","handleDeleteSession"],finalize:["audit","metrics","releaseSemaphore","releaseQuota","finalize"],error:[]};httpRequestStateSchema=import_lazy_zod73.z.object({decision:decisionSchema,intent:intentSchema,verifyResult:sessionVerifyOutputSchema});name20="http:request";({Stage:Stage20}=FlowHooksOf("http:request"));HttpRequestFlow=class extends FlowBase{logger=this.scope.logger.child("HttpRequestFlow");requestStartTime=0;requestId="";static canActivate(request,scope){const requestPath=normalizeEntryPrefix(request.path);const prefix=normalizeEntryPrefix(scope.entryPath);const scopePath=normalizeScopeBase(scope.routeBase);const basePath=`${prefix}${scopePath}`;return requestPath===basePath||requestPath===`${basePath}/sse`||requestPath===`${basePath}/message`}async traceRequest(){const{request}=this.rawInput;this.requestStartTime=Date.now();const ctx=this.tryGetContext();this.requestId=ctx?.requestId??`req-${(0,import_utils90.randomUUID)()}`;const headers=request.headers??{};const body=request.body;const userAgent=headers["user-agent"];const contentType2=headers["content-type"];const accept=headers["accept"];const sessionId=ctx?.sessionId??headers["mcp-session-id"]??"no-session";this.logger.info(`[${this.requestId}] \u25B6 ${request.method} ${request.path}`,{requestId:this.requestId,traceId:ctx?.traceContext.traceId?.slice(0,16),method:request.method,path:request.path,userAgent:userAgent?.slice(0,50),sessionId:sessionId?.slice(0,20),contentType:contentType2,accept,hasBody:!!request.body,bodyMethod:body?.["method"]});this.logger.debug(`[${this.requestId}] HEADERS`,{headers:headersForLog(headers)})}async checkIpFilter(){enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp,()=>httpRespond.json({jsonrpc:"2.0",id:this.jsonRpcRequestId(),error:{code:-32001,message:"Forbidden: client IP rejected by ipFilter"}},{status:403}))}async relayToSessionOwner(){const transportService=this.scope.transportService;if(!transportService)return;const{request,response}=this.rawInput;const owner=await transportService.findRemoteSessionOwner(request);if(!owner)return;this.logger.verbose(`[${this.requestId}] relaying to session owner ${owner.nodeId}`);try{await transportService.relayToSessionOwner(owner,request,response)}catch(error){if(!(error instanceof SessionOwnerUnreachableError))throw error;this.logger.warn(`[${this.requestId}] session owner unreachable: ${error.reason}`,{owner:owner.nodeId});this.respond(httpRespond.json({jsonrpc:"2.0",id:this.jsonRpcRequestId(),error:{code:-32e3,message:error.getPublicMessage()}},{status:error.statusCode,headers:{"Retry-After":String(error.retryAfterSeconds)}}));return}this.handled()}async acquireQuota(){const manager=this.scope.rateLimitManager;const globalConfig=manager?.config?.global;if(!manager||!globalConfig||partitionsByIdentity(globalConfig.partitionBy))return;await this.enforceGlobalRateLimit(manager)}async acquireIdentityQuota(){const manager=this.scope.rateLimitManager;const globalConfig=manager?.config?.global;if(!manager||!globalConfig||!partitionsByIdentity(globalConfig.partitionBy))return;await this.enforceGlobalRateLimit(manager)}async enforceGlobalRateLimit(manager){const context=this.tryGetContext();let result;try{result=await manager.checkGlobalRateLimit(buildPartitionContext(context))}catch(error){if(!(error instanceof import_guard8.GuardStorageUnavailableError))throw error;this.logger.warn(`[${this.requestId}] acquireQuota: ${error.message}`);this.respond(httpRespond.json({jsonrpc:"2.0",id:this.jsonRpcRequestId(),error:{code:-32603,message:"Service temporarily unavailable: the rate-limit store cannot be reached",data:{code:error.code}}},{status:error.statusCode,headers:{"Retry-After":"1"}}));return}context?.set(GLOBAL_RATE_LIMIT_CHECKED,true);if(result.allowed)return;const retryAfter=Math.ceil((result.retryAfterMs??6e4)/1e3);this.respond(httpRespond.json({jsonrpc:"2.0",id:this.jsonRpcRequestId(),error:{code:-32029,message:`Rate limit exceeded. Retry after ${retryAfter} seconds`}},{status:429,headers:{"Retry-After":String(retryAfter)}}))}jsonRpcRequestId(){const requestBody=this.rawInput.request.body;return requestBody?.id??null}async checkAuthorization(){const{request}=this.rawInput;this.logger.verbose(`[${this.requestId}] checkAuthorization: verifying session`);try{const result=await this.scope.runFlow("session:verify",{request,sessionless:this.servesProtocol20260728()});if(!result){this.logger.error(`[${this.requestId}] failed to verify session`);throw new SessionVerificationFailedError}this.state.set({verifyResult:result});if(result.kind==="authorized"&&result.authorization){const ctx=this.tryGetContext();if(ctx){const{token,user}=result.authorization;const presentedSessionId=this.servesProtocol20260728()?void 0:sessionIdPresentedBy(request);ctx.updateAuthInfo(authInfoFromAuthorization(result.authorization,presentedSessionId));await this.bindOrchestrationAccessor(ctx,token,user)}}}catch(error){if(!(error instanceof FlowControl)){this.logError(error,"checkAuthorization")}throw error}}async bindOrchestrationAccessor(ctx,token,user){const auth=this.scope.auth;const mode=auth?.options?.mode;const isOrchestrated=mode==="local"||mode==="remote";if(!token||!auth?.orchestratedTokenStore||!isOrchestrated){return}const tokenStore=auth.orchestratedTokenStore;let providers;try{const authorizationId=(0,import_auth42.deriveAuthorizationId)(token);const providerIds=await tokenStore.getProviderIds(authorizationId);providers=Object.fromEntries(providerIds.map(id=>[id,{id}]))}catch(err){this.logger.warn(`[${this.requestId}] failed to load orchestrated providers: ${String(err)}`)}const authorization=import_auth42.OrchestratedAuthorization.create({token,user:{sub:user.sub??"unknown",name:user.name,email:user.email,picture:user.picture},expiresAt:user.exp?user.exp*1e3:void 0,tokenStore,onTokenRefresh:auth.providerTokenRefresher?.(),providers});ctx.setContextToken(import_auth42.ORCHESTRATED_AUTH_ACCESSOR,new import_auth42.OrchestratedAuthAccessorAdapter(authorization))}servesProtocol20260728(){const{request}=this.rawInput;const isWebMode=!!request[ServerRequestTokens.webRequest];const defaultProtocolVersion=this.scope.metadata.transport?.defaultProtocolVersion??(isWebMode?"2026-07-28":"legacy");return isProtocol20260728Request({headers:request.headers,body:request.body,defaultVersion:defaultProtocolVersion})}async resolveSkillsOnlyMode(){if(detectSkillsOnlyMode(this.rawInput.request.query))this.tryGetContext()?.set(SKILLS_ONLY_REQUEST,true)}async router(){try{const{request}=this.rawInput;this.logger.verbose(`[${this.requestId}] router: check request decision`);const transportConfig=this.scope.metadata.transport;if(!transportConfig){this.logger.error(`[${this.requestId}] transport config not found in scope metadata`);this.respond(httpRespond.json({error:"Internal Server Error",message:"Transport configuration missing"},{status:500}));return}const legacyFlags=toLegacyProtocolFlags(transportConfig.protocol);this.logger.debug(`[${this.requestId}] transport config`,{protocol:transportConfig.protocol,enableLegacySSE:legacyFlags.enableLegacySSE,enableStreamableHttp:legacyFlags.enableStreamableHttp,path:request.path,accept:request.headers?.["accept"]});const decision=decideIntent(request,{...legacyFlags,tolerateMissingAccept:true});const isWebMode=!!request[ServerRequestTokens.webRequest];if(isWebMode&&decision.intent==="unknown"){decision.intent="stateless-http"}this.logger.debug(`[${this.requestId}] decision result`,{intent:decision.intent,reasons:decision.reasons,debug:decision.debug});if(this.servesProtocol20260728()){const verify=this.state.required.verifyResult;if(verify.kind==="authorized"){request[ServerRequestTokens.auth]=verify.authorization}else if(verify.kind==="forbidden"){this.logger.warn(`[${this.requestId}] mcp-20260728: forbidden, insufficient scope`);this.respond(httpRespond.forbidden({headers:challengeHeaders(verify.prmMetadataHeader)}));return}else{this.logger.warn(`[${this.requestId}] mcp-20260728: unauthorized`);this.respond(httpRespond.unauthorized({headers:challengeHeaders(verify.prmMetadataHeader)}));return}this.logger.verbose(`[${this.requestId}] routing to mcp-20260728 pipeline`);this.state.set("intent","mcp-20260728");return}const routerBody=request.body;const isJsonRpcRequest=request.method.toUpperCase()!=="DELETE"&&routerBody&&typeof routerBody==="object"&&routerBody["jsonrpc"]==="2.0"&&typeof routerBody["method"]==="string"&&routerBody["method"]!=="initialize";const respondNoSession=()=>{const requestId=routerBody?.["id"]??null;return this.respond({kind:"json",status:200,contentType:"application/json; charset=utf-8",body:{jsonrpc:"2.0",id:requestId,error:{code:-32600,message:"Session not initialized \u2014 send `initialize` first",data:{transport:"streamable-http",expected:"initialize"}}}})};if(request.method.toUpperCase()==="DELETE"){this.logger.verbose(`[${this.requestId}] DELETE request, using decision intent: ${decision.intent}`);if(decision.intent==="unknown"){this.logger.verbose(`[${this.requestId}] DELETE with unknown intent, forwarding to next middleware`);this.next();return}const deleteVerify=this.state.required.verifyResult;const requestedSessionId=request[ServerRequestTokens.sessionId]??request.headers["mcp-session-id"]??request.query?.["sessionId"];const deleteAuthz=authorizeSessionTermination(deleteVerify,requestedSessionId);if(request[ServerRequestTokens.webTransport]&&deleteAuthz.kind!=="unauthorized"){request[ServerRequestTokens.auth]=deleteVerify.authorization;this.state.set("intent",decision.intent);return}if(deleteAuthz.kind==="unauthorized"){this.logger.warn(`[${this.requestId}] DELETE session denied: request is not authenticated`);this.respond(httpRespond.unauthorized({headers:challengeHeaders(deleteVerify.prmMetadataHeader??"Bearer")}));return}if(deleteAuthz.kind==="forbidden"){this.logger.warn(`[${this.requestId}] DELETE session denied: caller does not own the requested session id`);this.respond(httpRespond.notFound("Session not found"));return}request[ServerRequestTokens.auth]=deleteVerify.authorization;request[ServerRequestTokens.sessionId]=deleteAuthz.sessionId;this.state.set("intent",decision.intent);return}const{verifyResult}=this.state.required;if(verifyResult.kind==="authorized"){const{authorization}=verifyResult;request[ServerRequestTokens.auth]=authorization;if(authorization.session?.payload){const ctx=this.tryGetContext();if(ctx){ctx.updateSessionMetadata(authorization.session.payload)}}if(authorization.session){const sessionId=authorization.session.id;request[ServerRequestTokens.sessionId]=sessionId;if(this.scope.notifications.isSessionTerminated(sessionId)){const body=request.body;if(body?.method==="initialize"){this.logger.info(`[${this.requestId}] Initialize with terminated session ${sessionId.slice(0,20)}... - re-initializing`);this.scope.notifications.unmarkTerminated(sessionId);request[ServerRequestTokens.reinitialize]=true}else{this.logger.warn(`[${this.requestId}] Request to terminated session: ${sessionId.slice(0,20)}...`);this.respond(httpRespond.notFound("Session not found"));return}}const protocol=authorization.session?.payload?.protocol;if(protocol){this.logger.verbose(`[${this.requestId}] decision from session: ${protocol}`);this.state.set("intent",protocol);return}}if(decision.intent==="unknown"){if(isJsonRpcRequest){this.logger.info(`[${this.requestId}] no session, JSON-RPC body present \u2014 responding with structured error (#380)`);respondNoSession()}this.logger.verbose(`[${this.requestId}] decision is unknown, continue to next http middleware`);this.next();return}this.logger.verbose(`[${this.requestId}] decision is request info: ${decision.intent}`);this.state.set("intent",decision.intent)}else if(verifyResult.kind==="forbidden"){if(decision.intent==="unknown"){if(isJsonRpcRequest){respondNoSession()}this.logger.verbose(`[${this.requestId}] forbidden with unknown intent, continue to other public http middleware`);this.next();return}this.logger.warn(`[${this.requestId}] forbidden: insufficient scope`);this.respond(httpRespond.forbidden({headers:challengeHeaders(verifyResult.prmMetadataHeader)}))}else{this.logger.verbose(`[${this.requestId}] not authorized request, check decision intent: ${decision.intent}`);if(decision.intent==="unknown"){if(isJsonRpcRequest){respondNoSession()}this.logger.verbose(`[${this.requestId}] decision is unknown, continue to other public http middleware`);this.next();return}this.logger.warn(`[${this.requestId}] decision is ${decision.intent}, but not authorized, respond with 401`);this.respond(httpRespond.unauthorized({headers:challengeHeaders(verifyResult.prmMetadataHeader)}))}}catch(error){if(!(error instanceof FlowControl)){this.logError(error,"router")}throw error}}async checkPersistentSessionOwner(){const req=this.rawInput.request;const persistent=req[ServerRequestTokens.webTransport];if(!req[ServerRequestTokens.webRequest]||!persistent||typeof persistent!=="object")return;const{claimPersistentSession:claimPersistentSession2,persistentSessionCallerKey:persistentSessionCallerKey2}=await Promise.resolve().then(()=>(init_persistent_session_owner(),persistent_session_owner_exports));const authorization=req[ServerRequestTokens.auth];const callerKey=persistentSessionCallerKey2(authorization);const store=persistent.owner;const claim=claimPersistentSession2(persistent,callerKey,store);if(claim==="claimed"){await store?.save(callerKey);return}if(claim==="owner")return;this.logger.warn(`[${this.requestId}] Persistent session refused: it was opened by another caller`);this.respond(httpRespond.json({jsonrpc:"2.0",error:{code:-32001,message:"Session not found"},id:null},{status:404}))}async handleWebFetch(){const{request}=this.rawInput;const req=request;const webRequest=req[ServerRequestTokens.webRequest];if(!webRequest)return;try{const webCtx=req[ServerRequestTokens.webCtx];const{runWebStandardMcp:runWebStandardMcp2}=await Promise.resolve().then(()=>(init_web_standard_mcp(),web_standard_mcp_exports));const{buildScopedServerOptions:buildScopedServerOptions2}=await Promise.resolve().then(()=>(init_build_scoped_server_options(),build_scoped_server_options_exports));const{expandProtocolConfig:expandProtocolConfig2}=await Promise.resolve().then(()=>(init_schema7(),schema_exports));const scope=this.scope;const proto=expandProtocolConfig2(scope.metadata.transport?.protocol);const sse=proto.streamable&&!proto.json;const authorization=req[ServerRequestTokens.auth];const authInfo=authorization?authInfoFromAuthorization(authorization,sessionIdPresentedBy(request)):void 0;const persistent=req[ServerRequestTokens.webTransport];const response=await runWebStandardMcp2(scope,webRequest,{serverOptions:buildScopedServerOptions2(scope),authInfo,sse,ctx:webCtx,persistent});this.respond(httpRespond.webResponse(response))}catch(error){if(!(error instanceof FlowControl)){this.logError(error,"handleWebFetch")}throw error}}async handleMcp2026(){try{const response=await this.scope.runFlow("handle:mcp-202607280728",this.rawInput);if(response){this.respond(response)}this.handled()}catch(error){if(!(error instanceof FlowControl)){this.logError(error,"handleMcp2026")}throw error}}async handleLegacySse(){try{const response=await this.scope.runFlow("handle:legacy-sse",this.rawInput);if(response){this.respond(response)}this.handled()}catch(error){if(!(error instanceof FlowControl)){this.logError(error,"handleLegacySse")}throw error}}async handleSse(){try{const response=await this.scope.runFlow("handle:streamable-http",this.rawInput);if(response){this.respond(response)}this.next()}catch(error){if(!(error instanceof FlowControl)){this.logError(error,"handleSse")}throw error}}async handleStreamableHttp(){try{const response=await this.scope.runFlow("handle:streamable-http",this.rawInput);if(response){this.respond(response)}this.next()}catch(error){if(!(error instanceof FlowControl)){this.logError(error,"handleStreamableHttp")}throw error}}async handleStatefulHttp(){try{const response=await this.scope.runFlow("handle:streamable-http",this.rawInput);if(response){this.respond(response)}this.next()}catch(error){if(!(error instanceof FlowControl)){this.logError(error,"handleStatefulHttp")}throw error}}async handleStatelessHttp(){try{const response=await this.scope.runFlow("handle:stateless-http",this.rawInput);if(response){this.respond(response)}this.handled()}catch(error){if(!(error instanceof FlowControl)){this.logError(error,"handleStatelessHttp")}throw error}}async applyDeleteNodeHeaders(){applyMachineIdHeader(this.rawInput.response)}async handleDeleteSession(){try{const{request}=this.rawInput;const sessionId=request[ServerRequestTokens.sessionId]??request.headers["mcp-session-id"];if(!sessionId||typeof sessionId!=="string"){this.logger.warn(`[${this.requestId}] DELETE request without valid session ID`);this.respond(httpRespond.rpcError("No valid session ID provided"));return}this.logger.info(`[${this.requestId}] DELETE session: ${sessionId}`);this.scope.notifications.terminateSession(sessionId);const authorization=request[ServerRequestTokens.auth];const transportService=this.scope.transportService;if(authorization&&transportService){for(const protocol of["streamable-http","sse"]){try{await transportService.destroyTransporter(protocol,authorization.token??"",sessionId)}catch{}}await transportService.deleteStoredSession(sessionId)}this.logger.info(`[${this.requestId}] Session terminated: ${sessionId}`);this.respond(httpRespond.noContent())}catch(error){if(!(error instanceof FlowControl)){this.logError(error,"handleDeleteSession")}throw error}}async finalize(){const{request}=this.rawInput;const duration=Date.now()-this.requestStartTime;const intent=this.state.get("intent")??"unknown";this.logger.info(`[${this.requestId}] \u25C0 ${request.method} ${request.path} completed in ${duration}ms`,{requestId:this.requestId,method:request.method,path:request.path,duration,intent})}logError(error,context){const{request}=this.rawInput;const duration=Date.now()-this.requestStartTime;const errorMessage2=error instanceof Error?error.message:String(error);const errorName=error instanceof Error?error.name:"UnknownError";const errorStack=error instanceof Error?error.stack:void 0;const body=request.body;const errorCode=error?.code;const errorCause=error?.cause;this.logger.error(`[${this.requestId}] \u2716 ${request.method} ${request.path} failed${context?` in ${context}`:""} after ${duration}ms: ${errorMessage2||"(no message)"}`,{requestId:this.requestId,method:request.method,path:request.path,duration,context,error:{name:errorName,message:errorMessage2||"(no message)",code:errorCode,cause:errorCause instanceof Error?errorCause.message:errorCause,stack:errorStack},request:{userAgent:request.headers?.["user-agent"]?.slice(0,50),sessionId:request.headers?.["mcp-session-id"]?.slice(0,20),contentType:request.headers?.["content-type"],bodyMethod:body?.["method"],bodyId:body?.["id"]},state:{intent:this.state.get("intent"),hasVerifyResult:!!this.state.get("verifyResult")}})}};__decorateClass([Stage20("traceRequest")],HttpRequestFlow.prototype,"traceRequest",1);__decorateClass([Stage20("checkIpFilter")],HttpRequestFlow.prototype,"checkIpFilter",1);__decorateClass([Stage20("relayToSessionOwner")],HttpRequestFlow.prototype,"relayToSessionOwner",1);__decorateClass([Stage20("acquireQuota")],HttpRequestFlow.prototype,"acquireQuota",1);__decorateClass([Stage20("acquireIdentityQuota")],HttpRequestFlow.prototype,"acquireIdentityQuota",1);__decorateClass([Stage20("checkAuthorization")],HttpRequestFlow.prototype,"checkAuthorization",1);__decorateClass([Stage20("resolveSkillsOnlyMode")],HttpRequestFlow.prototype,"resolveSkillsOnlyMode",1);__decorateClass([Stage20("router")],HttpRequestFlow.prototype,"router",1);__decorateClass([Stage20("checkPersistentSessionOwner")],HttpRequestFlow.prototype,"checkPersistentSessionOwner",1);__decorateClass([Stage20("handleWebFetch")],HttpRequestFlow.prototype,"handleWebFetch",1);__decorateClass([Stage20("handleMcp2026",{filter:({state:{required:{intent}}})=>intent==="mcp-20260728"})],HttpRequestFlow.prototype,"handleMcp2026",1);__decorateClass([Stage20("handleLegacySse",{filter:({state:{required:{intent}}})=>intent==="legacy-sse"})],HttpRequestFlow.prototype,"handleLegacySse",1);__decorateClass([Stage20("handleSse",{filter:({state:{required:{intent}}})=>intent==="sse"})],HttpRequestFlow.prototype,"handleSse",1);__decorateClass([Stage20("handleStreamableHttp",{filter:({state:{required:{intent}}})=>intent==="streamable-http"})],HttpRequestFlow.prototype,"handleStreamableHttp",1);__decorateClass([Stage20("handleStatefulHttp",{filter:({state:{required:{intent}}})=>intent==="stateful-http"})],HttpRequestFlow.prototype,"handleStatefulHttp",1);__decorateClass([Stage20("handleStatelessHttp",{filter:({state:{required:{intent}}})=>intent==="stateless-http"})],HttpRequestFlow.prototype,"handleStatelessHttp",1);__decorateClass([Stage20("applyDeleteNodeHeaders",{filter:({state:{required:{intent}}})=>intent==="delete-session"})],HttpRequestFlow.prototype,"applyDeleteNodeHeaders",1);__decorateClass([Stage20("handleDeleteSession",{filter:({state:{required:{intent}}})=>intent==="delete-session"})],HttpRequestFlow.prototype,"handleDeleteSession",1);__decorateClass([Stage20("finalize")],HttpRequestFlow.prototype,"finalize",1);HttpRequestFlow=__decorateClass([FrontMcpFlow({name:name20,plan:plan20,access:"public",inputSchema:httpInputSchema,outputSchema:httpOutputSchema,middleware:{path:"/"}})],HttpRequestFlow)}});var plan21,name21,Stage21,HttpIpFilterFlow;var init_http_ip_filter_flow=__esm({"libs/sdk/src/scope/flows/http.ip-filter.flow.ts"(){"use strict";init_common();plan21={pre:["checkIpFilter"]};name21="http:ip-filter";({Stage:Stage21}=FlowHooksOf(name21));HttpIpFilterFlow=class extends FlowBase{async checkIpFilter(){enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp)}};__decorateClass([Stage21("checkIpFilter")],HttpIpFilterFlow.prototype,"checkIpFilter",1);HttpIpFilterFlow=__decorateClass([FrontMcpFlow({name:name21,plan:plan21,access:"public",inputSchema:httpInputSchema,outputSchema:httpOutputSchema})],HttpIpFilterFlow)}});var require_dist=__commonJS({"libs/storage-sqlite/dist/index.js"(exports2,module2){"use strict";var __defProp2=Object.defineProperty;var __getOwnPropDesc2=Object.getOwnPropertyDescriptor;var __getOwnPropNames2=Object.getOwnPropertyNames;var __hasOwnProp2=Object.prototype.hasOwnProperty;var __export2=(target,all)=>{for(var name48 in all)__defProp2(target,name48,{get:all[name48],enumerable:true})};var __copyProps2=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames2(from))if(!__hasOwnProp2.call(to,key)&&key!==except)__defProp2(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc2(from,key))||desc.enumerable})}return to};var __toCommonJS2=mod=>__copyProps2(__defProp2({},"__esModule",{value:true}),mod);var index_exports2={};__export2(index_exports2,{SqliteDecryptionError:()=>SqliteDecryptionError,SqliteElicitationStore:()=>SqliteElicitationStore,SqliteEventStore:()=>SqliteEventStore,SqliteKvStore:()=>SqliteKvStore,SqliteSessionStore:()=>SqliteSessionStore,SqliteStorageAdapter:()=>SqliteStorageAdapter,SqliteTaskStore:()=>SqliteTaskStore,decryptValue:()=>decryptValue,deriveEncryptionKey:()=>deriveEncryptionKey,encryptValue:()=>encryptValue,loadBetterSqlite3:()=>loadBetterSqlite3,openDatabase:()=>openDatabase,sqliteStorageOptionsSchema:()=>sqliteStorageOptionsSchema,withBusyRetry:()=>withBusyRetry});module2.exports=__toCommonJS2(index_exports2);var import_utils146=require("@frontmcp/utils");var SqliteDecryptionError=class extends Error{code="SQLITE_DECRYPTION_FAILED";constructor(){super("SqliteKvStore: failed to decrypt a stored value. The encryption secret differs from the one the database was written with (or the value is corrupted). Restore the original secret, or delete the database file to start empty.");this.name="SqliteDecryptionError"}};var HKDF_SALT=new TextEncoder().encode("frontmcp-sqlite-storage-v1");var HKDF_INFO=new TextEncoder().encode("aes-256-gcm-value-encryption");var KEY_LENGTH=32;function deriveEncryptionKey(secret){const ikm=new TextEncoder().encode(secret);return(0,import_utils146.hkdfSha256)(ikm,HKDF_SALT,HKDF_INFO,KEY_LENGTH)}var SEPARATOR=":";function encryptValue(key,plaintext){const iv=(0,import_utils146.randomBytes)(12);const plaintextBytes=new TextEncoder().encode(plaintext);const{ciphertext,tag}=(0,import_utils146.encryptAesGcm)(key,plaintextBytes,iv);return[(0,import_utils146.base64urlEncode)(iv),(0,import_utils146.base64urlEncode)(tag),(0,import_utils146.base64urlEncode)(ciphertext)].join(SEPARATOR)}function decryptValue(key,encrypted){const parts=encrypted.split(SEPARATOR);if(parts.length!==3){throw new Error("Invalid encrypted value format")}const iv=(0,import_utils146.base64urlDecode)(parts[0]);const tag=(0,import_utils146.base64urlDecode)(parts[1]);const ciphertext=(0,import_utils146.base64urlDecode)(parts[2]);try{return new TextDecoder().decode((0,import_utils146.decryptAesGcm)(key,ciphertext,iv,tag))}catch{throw new SqliteDecryptionError}}var import_utils210=require("@frontmcp/utils");var cached=null;function loadBetterSqlite3(){if(cached){return cached}const mod=require("better-sqlite3");cached=mod;return mod}var MEMORY_PATH=":memory:";var DEFAULT_BUSY_TIMEOUT_MS=5e3;function isBusyError(err){const code=err?.code;return code==="SQLITE_BUSY"||code==="SQLITE_BUSY_RECOVERY"||code==="SQLITE_BUSY_SNAPSHOT"}function sleepSync(ms){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}function withBusyRetry(operation,options={}){const attempts=options.attempts??5;const delayMs=options.delayMs??50;for(let attempt=1;;attempt++){try{return operation()}catch(err){if(!isBusyError(err)||attempt>=attempts)throw err;sleepSync(delayMs*attempt)}}}function openDatabase(path,storeName,options={}){const BetterSqlite3=loadBetterSqlite3();if(path!==MEMORY_PATH&&path!==""){const dir=(0,import_utils210.dirname)(path);if(dir&&dir!=="."){try{(0,import_utils210.ensureDirSync)(dir)}catch(err){const message=err instanceof Error?err.message:String(err);throw new Error(`${storeName}: failed to create directory "${dir}" for database "${path}": ${message}`,{cause:err})}}}let db;try{db=new BetterSqlite3(path)}catch(err){const message=err instanceof Error?err.message:String(err);throw new Error(`${storeName}: failed to open database at "${path}": ${message}`,{cause:err})}try{db.pragma(`busy_timeout = ${Math.max(0,Math.floor(options.busyTimeoutMs??DEFAULT_BUSY_TIMEOUT_MS))}`);if(options.walMode)withBusyRetry(()=>db.pragma("journal_mode = WAL"))}catch(err){db.close();const message=err instanceof Error?err.message:String(err);throw new Error(`${storeName}: failed to configure database at "${path}": ${message}`,{cause:err})}return db}var SqliteKvStore=class{db;encryptionKey=null;cleanupTimer=null;stmts=null;constructor(options){this.db=openDatabase(options.path,"SqliteKvStore",{busyTimeoutMs:options.busyTimeoutMs,walMode:options.walMode!==false});if(options.encryption?.secret){this.encryptionKey=deriveEncryptionKey(options.encryption.secret)}withBusyRetry(()=>this.initSchema());this.prepareStatements();const cleanupInterval=options.ttlCleanupIntervalMs??6e4;if(cleanupInterval>0){this.cleanupTimer=setInterval(()=>this.purgeExpired(),cleanupInterval);if(this.cleanupTimer.unref){this.cleanupTimer.unref()}}}initSchema(){this.db.exec(`
|
|
93
93
|
CREATE TABLE IF NOT EXISTS kv (
|
|
94
94
|
key TEXT PRIMARY KEY,
|
|
95
95
|
value TEXT NOT NULL,
|