mcp-use 2.7.3 → 2.8.0-canary.0
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/dist/bin.js +1 -1
- package/dist/branding.d.ts +4 -4
- package/dist/chunk-BNLXCMPL.js +11 -0
- package/dist/chunk-EI7MMDWY.js +1 -0
- package/dist/chunk-HAV435PF.js +1 -0
- package/dist/chunk-LPMFXLNI.js +1 -0
- package/dist/chunk-TCIRBQPM.js +1 -0
- package/dist/{chunk-FRVJVG2A.js → chunk-TTX5MUYW.js} +1 -1
- package/dist/chunk-YI27EOFM.js +1 -0
- package/dist/gate-GHSM72MD.js +1 -0
- package/dist/index-node.js +7 -7
- package/dist/index.d.ts +2 -1
- package/dist/index.js +22 -19
- package/dist/internal/buffered-response.js +1 -0
- package/dist/internal/resource-completion.js +1 -1
- package/dist/internal/usage.js +2 -1
- package/dist/{chunk-Z6ROXYBJ.js → landing-handler-3ZBRKAI2.js} +41 -41
- package/dist/landing.js +666 -1
- package/dist/mcp-proxy-YSI2UFBY.js +2 -0
- package/dist/mcp-proxy.d.ts +2 -0
- package/dist/node-bridge.js +1 -1
- package/dist/oauth/auth0.js +1 -1
- package/dist/oauth/better-auth.js +1 -1
- package/dist/oauth/clerk.js +1 -1
- package/dist/oauth/convex.js +1 -1
- package/dist/oauth/index.js +1 -1
- package/dist/oauth/keycloak.js +1 -1
- package/dist/oauth/scalekit.js +1 -1
- package/dist/oauth/supabase.js +1 -1
- package/dist/oauth/workos.js +1 -1
- package/dist/openapi/index.js +3 -1
- package/dist/public-route-AVKCGJDQ.js +1 -0
- package/dist/react/hooks/use-deep-link.d.ts +31 -0
- package/dist/react/hooks/use-model-context.d.ts +28 -0
- package/dist/react/index.d.ts +3 -0
- package/dist/react/index.js +1209 -73
- package/dist/react/public-assets.d.ts +1 -2
- package/dist/react/runtime/bootstrap-view.d.ts +2 -1
- package/dist/react/runtime/model-context-image.d.ts +7 -0
- package/dist/react/runtime/model-context-store.d.ts +29 -12
- package/dist/react/runtime/model-context-wire.d.ts +34 -0
- package/dist/react/runtime/model-context.d.ts +46 -0
- package/dist/react/runtime/view-config.d.ts +13 -2
- package/dist/react/types/model-context.d.ts +64 -0
- package/dist/server.d.ts +13 -0
- package/dist/settings.d.ts +86 -0
- package/dist/tanstack-start/vite.js +1 -1
- package/dist/tools.d.ts +41 -1
- package/dist/views/entrypoints.d.ts +6 -0
- package/dist/views/types.d.ts +10 -0
- package/dist/views/wire.d.ts +2 -1
- package/dist/vite/index.js +1 -1
- package/package.json +4 -3
- package/dist/chunk-4TEUYGHH.js +0 -1
- package/dist/chunk-6KY574WV.js +0 -1
- package/dist/chunk-72EUVURD.js +0 -1
- package/dist/chunk-HQWSVX2E.js +0 -2
- package/dist/chunk-I46MEN5X.js +0 -1
- package/dist/chunk-M7NVJNT3.js +0 -11
- package/dist/chunk-OJF6B5EU.js +0 -1
- package/dist/chunk-PZTPSQGD.js +0 -1
- package/dist/chunk-Y26DNVWA.js +0 -3
- package/dist/chunk-YU52DKNS.js +0 -1
- package/dist/gate-GK4EU23Q.js +0 -1
- package/dist/landing-handler-UNCJYWGL.js +0 -1
- package/dist/mcp-proxy-VRA6MTY6.js +0 -2
- package/dist/public-route-7PHP6P3A.js +0 -1
package/dist/index-node.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __defProp=Object.defineProperty;var __getOwnPropNames=Object.getOwnPropertyNames;var __esm=(fn,res)=>function(){return fn&&(res=(0,fn[__getOwnPropNames(fn)[0]])(fn=0)),res};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})};var __create,__defProp2,__getOwnPropDesc,__getOwnPropNames2,__getProtoOf,__hasOwnProp,__commonJSMin,__exportAll,__copyProps,__toESM,init_chunk_Br0eD_fh=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0_patch_hash=2a5f5402571efdc40802e9603a3dd09e22588b4aacad710814c204d79568091e/node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs"(){"use strict";__create=Object.create,__defProp2=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames2=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__commonJSMin=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports),__exportAll=(all,symbols)=>{let target={};for(var name in all)__defProp2(target,name,{get:all[name],enumerable:!0});return symbols&&__defProp2(target,Symbol.toStringTag,{value:"Module"}),target},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(var keys=__getOwnPropNames2(from),i=0,n=keys.length,key;i<n;i++)key=keys[i],!__hasOwnProp.call(to,key)&&key!==except&&__defProp2(to,key,{get:(k=>from[k]).bind(null,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp2(target,"default",{value:mod,enumerable:!0}):target,mod))}});function declares2019Dialect($schema){return typeof $schema=="string"&&DRAFT_2019_09_URIS.has($schema.replace(/#$/,""))}function declaredDialect(schema2,remedy){if(!("$schema"in schema2)||typeof schema2.$schema!="string")return"2020-12";let declared=schema2.$schema.replace(/#$/,"");if(DRAFT_2020_12_URIS.has(declared))return"2020-12";if(DRAFT_2019_09_URIS.has(declared))return"2019-09";if(DRAFT_07_URIS.has(declared)||DRAFT_06_URIS.has(declared))return"draft-7";throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${schema2.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${remedy}`)}var DRAFT_2020_12_URIS,DRAFT_2019_09_URIS,DRAFT_07_URIS,DRAFT_06_URIS,init_dialects_DoSzNhcb=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0_patch_hash=2a5f5402571efdc40802e9603a3dd09e22588b4aacad710814c204d79568091e/node_modules/@modelcontextprotocol/server/dist/dialects-DoSzNhcb.mjs"(){"use strict";DRAFT_2020_12_URIS=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),DRAFT_2019_09_URIS=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),DRAFT_07_URIS=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),DRAFT_06_URIS=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"])}});function $constructor(name,initializer3,params){function init(inst,def){if(inst._zod||Object.defineProperty(inst,"_zod",{value:{def,constr:_,traits:new Set},enumerable:!1}),inst._zod.traits.has(name))return;inst._zod.traits.add(name),initializer3(inst,def);let proto=_.prototype,keys=Object.keys(proto);for(let i=0;i<keys.length;i++){let k=keys[i];k in inst||(inst[k]=proto[k].bind(inst))}}let Parent=params?.Parent??Object;class Definition extends Parent{}Object.defineProperty(Definition,"name",{value:name});function _(def){var _a3;let inst=params?.Parent?new Definition:this;init(inst,def),(_a3=inst._zod).deferred??(_a3.deferred=[]);for(let fn of inst._zod.deferred)fn();return inst}return Object.defineProperty(_,"init",{value:init}),Object.defineProperty(_,Symbol.hasInstance,{value:inst=>params?.Parent&&inst instanceof params.Parent?!0:inst?._zod?.traits?.has(name)}),Object.defineProperty(_,"name",{value:name}),_}function config(newConfig){return newConfig&&Object.assign(globalConfig,newConfig),globalConfig}var _a,NEVER,$ZodAsyncError,$ZodEncodeError,globalConfig,init_core=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js"(){"use strict";NEVER=Object.freeze({status:"aborted"});$ZodAsyncError=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},$ZodEncodeError=class extends Error{constructor(name){super(`Encountered unidirectional transform during encode: ${name}`),this.name="ZodEncodeError"}};(_a=globalThis).__zod_globalConfig??(_a.__zod_globalConfig={});globalConfig=globalThis.__zod_globalConfig}});var util_exports={};__export(util_exports,{BIGINT_FORMAT_RANGES:()=>BIGINT_FORMAT_RANGES,Class:()=>Class,NUMBER_FORMAT_RANGES:()=>NUMBER_FORMAT_RANGES,aborted:()=>aborted,allowsEval:()=>allowsEval,assert:()=>assert,assertEqual:()=>assertEqual,assertIs:()=>assertIs,assertNever:()=>assertNever,assertNotEqual:()=>assertNotEqual,assignProp:()=>assignProp,base64ToUint8Array:()=>base64ToUint8Array,base64urlToUint8Array:()=>base64urlToUint8Array,cached:()=>cached,captureStackTrace:()=>captureStackTrace,cleanEnum:()=>cleanEnum,cleanRegex:()=>cleanRegex,clone:()=>clone,cloneDef:()=>cloneDef,createTransparentProxy:()=>createTransparentProxy,defineLazy:()=>defineLazy,esc:()=>esc,escapeRegex:()=>escapeRegex,explicitlyAborted:()=>explicitlyAborted,extend:()=>extend,finalizeIssue:()=>finalizeIssue,floatSafeRemainder:()=>floatSafeRemainder,getElementAtPath:()=>getElementAtPath,getEnumValues:()=>getEnumValues,getLengthableOrigin:()=>getLengthableOrigin,getParsedType:()=>getParsedType,getSizableOrigin:()=>getSizableOrigin,hexToUint8Array:()=>hexToUint8Array,isObject:()=>isObject,isPlainObject:()=>isPlainObject,issue:()=>issue,joinValues:()=>joinValues,jsonStringifyReplacer:()=>jsonStringifyReplacer,merge:()=>merge,mergeDefs:()=>mergeDefs,normalizeParams:()=>normalizeParams,nullish:()=>nullish,numKeys:()=>numKeys,objectClone:()=>objectClone,omit:()=>omit,optionalKeys:()=>optionalKeys,parsedType:()=>parsedType,partial:()=>partial,pick:()=>pick,prefixIssues:()=>prefixIssues,primitiveTypes:()=>primitiveTypes,promiseAllObject:()=>promiseAllObject,propertyKeyTypes:()=>propertyKeyTypes,randomString:()=>randomString,required:()=>required,safeExtend:()=>safeExtend,shallowClone:()=>shallowClone,slugify:()=>slugify,stringifyPrimitive:()=>stringifyPrimitive,uint8ArrayToBase64:()=>uint8ArrayToBase64,uint8ArrayToBase64url:()=>uint8ArrayToBase64url,uint8ArrayToHex:()=>uint8ArrayToHex,unwrapMessage:()=>unwrapMessage});function assertEqual(val){return val}function assertNotEqual(val){return val}function assertIs(_arg){}function assertNever(_x){throw new Error("Unexpected value in exhaustive check")}function assert(_){}function getEnumValues(entries){let numericValues=Object.values(entries).filter(v=>typeof v=="number");return Object.entries(entries).filter(([k,_])=>numericValues.indexOf(+k)===-1).map(([_,v])=>v)}function joinValues(array3,separator="|"){return array3.map(val=>stringifyPrimitive(val)).join(separator)}function jsonStringifyReplacer(_,value){return typeof value=="bigint"?value.toString():value}function cached(getter){return{get value(){{let value=getter();return Object.defineProperty(this,"value",{value}),value}throw new Error("cached value already set")}}}function nullish(input){return input==null}function cleanRegex(source){let start=source.startsWith("^")?1:0,end=source.endsWith("$")?source.length-1:source.length;return source.slice(start,end)}function floatSafeRemainder(val,step){let ratio=val/step,roundedRatio=Math.round(ratio),tolerance=Number.EPSILON*Math.max(Math.abs(ratio),1);return Math.abs(ratio-roundedRatio)<tolerance?0:ratio-roundedRatio}function defineLazy(object4,key,getter){let value;Object.defineProperty(object4,key,{get(){if(value!==EVALUATING)return value===void 0&&(value=EVALUATING,value=getter()),value},set(v){Object.defineProperty(object4,key,{value:v})},configurable:!0})}function objectClone(obj){return Object.create(Object.getPrototypeOf(obj),Object.getOwnPropertyDescriptors(obj))}function assignProp(target,prop,value){Object.defineProperty(target,prop,{value,writable:!0,enumerable:!0,configurable:!0})}function mergeDefs(...defs){let mergedDescriptors={};for(let def of defs){let descriptors=Object.getOwnPropertyDescriptors(def);Object.assign(mergedDescriptors,descriptors)}return Object.defineProperties({},mergedDescriptors)}function cloneDef(schema2){return mergeDefs(schema2._zod.def)}function getElementAtPath(obj,path){return path?path.reduce((acc,key)=>acc?.[key],obj):obj}function promiseAllObject(promisesObj){let keys=Object.keys(promisesObj),promises=keys.map(key=>promisesObj[key]);return Promise.all(promises).then(results=>{let resolvedObj={};for(let i=0;i<keys.length;i++)resolvedObj[keys[i]]=results[i];return resolvedObj})}function randomString(length=10){let chars="abcdefghijklmnopqrstuvwxyz",str="";for(let i=0;i<length;i++)str+=chars[Math.floor(Math.random()*chars.length)];return str}function esc(str){return JSON.stringify(str)}function slugify(input){return input.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function isObject(data){return typeof data=="object"&&data!==null&&!Array.isArray(data)}function isPlainObject(o){if(isObject(o)===!1)return!1;let ctor=o.constructor;if(ctor===void 0||typeof ctor!="function")return!0;let prot=ctor.prototype;return!(isObject(prot)===!1||Object.prototype.hasOwnProperty.call(prot,"isPrototypeOf")===!1)}function shallowClone(o){return isPlainObject(o)?{...o}:Array.isArray(o)?[...o]:o instanceof Map?new Map(o):o instanceof Set?new Set(o):o}function numKeys(data){let keyCount=0;for(let key in data)Object.prototype.hasOwnProperty.call(data,key)&&keyCount++;return keyCount}function escapeRegex(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function clone(inst,def,params){let cl=new inst._zod.constr(def??inst._zod.def);return(!def||params?.parent)&&(cl._zod.parent=inst),cl}function normalizeParams(_params){let params=_params;if(!params)return{};if(typeof params=="string")return{error:()=>params};if(params?.message!==void 0){if(params?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");params.error=params.message}return delete params.message,typeof params.error=="string"?{...params,error:()=>params.error}:params}function createTransparentProxy(getter){let target;return new Proxy({},{get(_,prop,receiver){return target??(target=getter()),Reflect.get(target,prop,receiver)},set(_,prop,value,receiver){return target??(target=getter()),Reflect.set(target,prop,value,receiver)},has(_,prop){return target??(target=getter()),Reflect.has(target,prop)},deleteProperty(_,prop){return target??(target=getter()),Reflect.deleteProperty(target,prop)},ownKeys(_){return target??(target=getter()),Reflect.ownKeys(target)},getOwnPropertyDescriptor(_,prop){return target??(target=getter()),Reflect.getOwnPropertyDescriptor(target,prop)},defineProperty(_,prop,descriptor){return target??(target=getter()),Reflect.defineProperty(target,prop,descriptor)}})}function stringifyPrimitive(value){return typeof value=="bigint"?value.toString()+"n":typeof value=="string"?`"${value}"`:`${value}`}function optionalKeys(shape){return Object.keys(shape).filter(k=>shape[k]._zod.optin==="optional"&&shape[k]._zod.optout==="optional")}function pick(schema2,mask){let currDef=schema2._zod.def,checks=currDef.checks;if(checks&&checks.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let def=mergeDefs(schema2._zod.def,{get shape(){let newShape={};for(let key in mask){if(!(key in currDef.shape))throw new Error(`Unrecognized key: "${key}"`);mask[key]&&(newShape[key]=currDef.shape[key])}return assignProp(this,"shape",newShape),newShape},checks:[]});return clone(schema2,def)}function omit(schema2,mask){let currDef=schema2._zod.def,checks=currDef.checks;if(checks&&checks.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let def=mergeDefs(schema2._zod.def,{get shape(){let newShape={...schema2._zod.def.shape};for(let key in mask){if(!(key in currDef.shape))throw new Error(`Unrecognized key: "${key}"`);mask[key]&&delete newShape[key]}return assignProp(this,"shape",newShape),newShape},checks:[]});return clone(schema2,def)}function extend(schema2,shape){if(!isPlainObject(shape))throw new Error("Invalid input to extend: expected a plain object");let checks=schema2._zod.def.checks;if(checks&&checks.length>0){let existingShape=schema2._zod.def.shape;for(let key in shape)if(Object.getOwnPropertyDescriptor(existingShape,key)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let def=mergeDefs(schema2._zod.def,{get shape(){let _shape={...schema2._zod.def.shape,...shape};return assignProp(this,"shape",_shape),_shape}});return clone(schema2,def)}function safeExtend(schema2,shape){if(!isPlainObject(shape))throw new Error("Invalid input to safeExtend: expected a plain object");let def=mergeDefs(schema2._zod.def,{get shape(){let _shape={...schema2._zod.def.shape,...shape};return assignProp(this,"shape",_shape),_shape}});return clone(schema2,def)}function merge(a,b){if(a._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let def=mergeDefs(a._zod.def,{get shape(){let _shape={...a._zod.def.shape,...b._zod.def.shape};return assignProp(this,"shape",_shape),_shape},get catchall(){return b._zod.def.catchall},checks:b._zod.def.checks??[]});return clone(a,def)}function partial(Class2,schema2,mask){let checks=schema2._zod.def.checks;if(checks&&checks.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let def=mergeDefs(schema2._zod.def,{get shape(){let oldShape=schema2._zod.def.shape,shape={...oldShape};if(mask)for(let key in mask){if(!(key in oldShape))throw new Error(`Unrecognized key: "${key}"`);mask[key]&&(shape[key]=Class2?new Class2({type:"optional",innerType:oldShape[key]}):oldShape[key])}else for(let key in oldShape)shape[key]=Class2?new Class2({type:"optional",innerType:oldShape[key]}):oldShape[key];return assignProp(this,"shape",shape),shape},checks:[]});return clone(schema2,def)}function required(Class2,schema2,mask){let def=mergeDefs(schema2._zod.def,{get shape(){let oldShape=schema2._zod.def.shape,shape={...oldShape};if(mask)for(let key in mask){if(!(key in shape))throw new Error(`Unrecognized key: "${key}"`);mask[key]&&(shape[key]=new Class2({type:"nonoptional",innerType:oldShape[key]}))}else for(let key in oldShape)shape[key]=new Class2({type:"nonoptional",innerType:oldShape[key]});return assignProp(this,"shape",shape),shape}});return clone(schema2,def)}function aborted(x,startIndex=0){if(x.aborted===!0)return!0;for(let i=startIndex;i<x.issues.length;i++)if(x.issues[i]?.continue!==!0)return!0;return!1}function explicitlyAborted(x,startIndex=0){if(x.aborted===!0)return!0;for(let i=startIndex;i<x.issues.length;i++)if(x.issues[i]?.continue===!1)return!0;return!1}function prefixIssues(path,issues){return issues.map(iss=>{var _a3;return(_a3=iss).path??(_a3.path=[]),iss.path.unshift(path),iss})}function unwrapMessage(message){return typeof message=="string"?message:message?.message}function finalizeIssue(iss,ctx,config2){let message=iss.message?iss.message:unwrapMessage(iss.inst?._zod.def?.error?.(iss))??unwrapMessage(ctx?.error?.(iss))??unwrapMessage(config2.customError?.(iss))??unwrapMessage(config2.localeError?.(iss))??"Invalid input",{inst:_inst,continue:_continue,input:_input,...rest}=iss;return rest.path??(rest.path=[]),rest.message=message,ctx?.reportInput&&(rest.input=_input),rest}function getSizableOrigin(input){return input instanceof Set?"set":input instanceof Map?"map":input instanceof File?"file":"unknown"}function getLengthableOrigin(input){return Array.isArray(input)?"array":typeof input=="string"?"string":"unknown"}function parsedType(data){let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"nan":"number";case"object":{if(data===null)return"null";if(Array.isArray(data))return"array";let obj=data;if(obj&&Object.getPrototypeOf(obj)!==Object.prototype&&"constructor"in obj&&obj.constructor)return obj.constructor.name}}return t}function issue(...args){let[iss,input,inst]=args;return typeof iss=="string"?{message:iss,code:"custom",input,inst}:{...iss}}function cleanEnum(obj){return Object.entries(obj).filter(([k,_])=>Number.isNaN(Number.parseInt(k,10))).map(el=>el[1])}function base64ToUint8Array(base642){let binaryString=atob(base642),bytes=new Uint8Array(binaryString.length);for(let i=0;i<binaryString.length;i++)bytes[i]=binaryString.charCodeAt(i);return bytes}function uint8ArrayToBase64(bytes){let binaryString="";for(let i=0;i<bytes.length;i++)binaryString+=String.fromCharCode(bytes[i]);return btoa(binaryString)}function base64urlToUint8Array(base64url2){let base642=base64url2.replace(/-/g,"+").replace(/_/g,"/"),padding="=".repeat((4-base642.length%4)%4);return base64ToUint8Array(base642+padding)}function uint8ArrayToBase64url(bytes){return uint8ArrayToBase64(bytes).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function hexToUint8Array(hex){let cleanHex=hex.replace(/^0x/,"");if(cleanHex.length%2!==0)throw new Error("Invalid hex string length");let bytes=new Uint8Array(cleanHex.length/2);for(let i=0;i<cleanHex.length;i+=2)bytes[i/2]=Number.parseInt(cleanHex.slice(i,i+2),16);return bytes}function uint8ArrayToHex(bytes){return Array.from(bytes).map(b=>b.toString(16).padStart(2,"0")).join("")}var EVALUATING,captureStackTrace,allowsEval,getParsedType,propertyKeyTypes,primitiveTypes,NUMBER_FORMAT_RANGES,BIGINT_FORMAT_RANGES,Class,init_util=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/util.js"(){"use strict";init_core();EVALUATING=Symbol("evaluating");captureStackTrace="captureStackTrace"in Error?Error.captureStackTrace:(..._args)=>{};allowsEval=cached(()=>{if(globalConfig.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let F=Function;return new F(""),!0}catch{return!1}});getParsedType=data=>{let t=typeof data;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(data)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(data)?"array":data===null?"null":data.then&&typeof data.then=="function"&&data.catch&&typeof data.catch=="function"?"promise":typeof Map<"u"&&data instanceof Map?"map":typeof Set<"u"&&data instanceof Set?"set":typeof Date<"u"&&data instanceof Date?"date":typeof File<"u"&&data instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},propertyKeyTypes=new Set(["string","number","symbol"]),primitiveTypes=new Set(["string","number","bigint","boolean","symbol","undefined"]);NUMBER_FORMAT_RANGES={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},BIGINT_FORMAT_RANGES={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Class=class{constructor(..._args){}}}});function flattenError(error3,mapper=issue2=>issue2.message){let fieldErrors={},formErrors=[];for(let sub of error3.issues)sub.path.length>0?(fieldErrors[sub.path[0]]=fieldErrors[sub.path[0]]||[],fieldErrors[sub.path[0]].push(mapper(sub))):formErrors.push(mapper(sub));return{formErrors,fieldErrors}}function formatError(error3,mapper=issue2=>issue2.message){let fieldErrors={_errors:[]},processError=(error4,path=[])=>{for(let issue2 of error4.issues)if(issue2.code==="invalid_union"&&issue2.errors.length)issue2.errors.map(issues=>processError({issues},[...path,...issue2.path]));else if(issue2.code==="invalid_key")processError({issues:issue2.issues},[...path,...issue2.path]);else if(issue2.code==="invalid_element")processError({issues:issue2.issues},[...path,...issue2.path]);else{let fullpath=[...path,...issue2.path];if(fullpath.length===0)fieldErrors._errors.push(mapper(issue2));else{let curr=fieldErrors,i=0;for(;i<fullpath.length;){let el=fullpath[i];i===fullpath.length-1?(curr[el]=curr[el]||{_errors:[]},curr[el]._errors.push(mapper(issue2))):curr[el]=curr[el]||{_errors:[]},curr=curr[el],i++}}}};return processError(error3),fieldErrors}var initializer,$ZodError,$ZodRealError,init_errors=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/errors.js"(){"use strict";init_core();init_util();initializer=(inst,def)=>{inst.name="$ZodError",Object.defineProperty(inst,"_zod",{value:inst._zod,enumerable:!1}),Object.defineProperty(inst,"issues",{value:def,enumerable:!1}),inst.message=JSON.stringify(def,jsonStringifyReplacer,2),Object.defineProperty(inst,"toString",{value:()=>inst.message,enumerable:!1})},$ZodError=$constructor("$ZodError",initializer),$ZodRealError=$constructor("$ZodError",initializer,{Parent:Error})}});var _parse,_parseAsync,_safeParse,safeParse,_safeParseAsync,safeParseAsync,_encode,_decode,_encodeAsync,_decodeAsync,_safeEncode,_safeDecode,_safeEncodeAsync,_safeDecodeAsync,init_parse=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/parse.js"(){"use strict";init_core();init_errors();init_util();_parse=_Err=>(schema2,value,_ctx,_params)=>{let ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema2._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError;if(result.issues.length){let e=new(_params?.Err??_Err)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())));throw captureStackTrace(e,_params?.callee),e}return result.value},_parseAsync=_Err=>async(schema2,value,_ctx,params)=>{let ctx=_ctx?{..._ctx,async:!0}:{async:!0},result=schema2._zod.run({value,issues:[]},ctx);if(result instanceof Promise&&(result=await result),result.issues.length){let e=new(params?.Err??_Err)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())));throw captureStackTrace(e,params?.callee),e}return result.value},_safeParse=_Err=>(schema2,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema2._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError;return result.issues.length?{success:!1,error:new(_Err??$ZodError)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}:{success:!0,data:result.value}},safeParse=_safeParse($ZodRealError),_safeParseAsync=_Err=>async(schema2,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!0}:{async:!0},result=schema2._zod.run({value,issues:[]},ctx);return result instanceof Promise&&(result=await result),result.issues.length?{success:!1,error:new _Err(result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}:{success:!0,data:result.value}},safeParseAsync=_safeParseAsync($ZodRealError),_encode=_Err=>(schema2,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _parse(_Err)(schema2,value,ctx)},_decode=_Err=>(schema2,value,_ctx)=>_parse(_Err)(schema2,value,_ctx),_encodeAsync=_Err=>async(schema2,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _parseAsync(_Err)(schema2,value,ctx)},_decodeAsync=_Err=>async(schema2,value,_ctx)=>_parseAsync(_Err)(schema2,value,_ctx),_safeEncode=_Err=>(schema2,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _safeParse(_Err)(schema2,value,ctx)},_safeDecode=_Err=>(schema2,value,_ctx)=>_safeParse(_Err)(schema2,value,_ctx),_safeEncodeAsync=_Err=>async(schema2,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _safeParseAsync(_Err)(schema2,value,ctx)},_safeDecodeAsync=_Err=>async(schema2,value,_ctx)=>_safeParseAsync(_Err)(schema2,value,_ctx)}});function emoji(){return new RegExp(_emoji,"u")}function timeSource(args){let hhmm="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof args.precision=="number"?args.precision===-1?`${hhmm}`:args.precision===0?`${hhmm}:[0-5]\\d`:`${hhmm}:[0-5]\\d\\.\\d{${args.precision}}`:`${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`}function time(args){return new RegExp(`^${timeSource(args)}$`)}function datetime(args){let time3=timeSource({precision:args.precision}),opts=["Z"];args.local&&opts.push(""),args.offset&&opts.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let timeRegex=`${time3}(?:${opts.join("|")})`;return new RegExp(`^${dateSource}T(?:${timeRegex})$`)}var cuid,cuid2,ulid,xid,ksuid,nanoid,duration,guid,uuid,email,_emoji,ipv4,ipv6,cidrv4,cidrv6,base64,base64url,httpProtocol,e164,dateSource,date,string,bigint,integer,number,boolean,_null,lowercase,uppercase,init_regexes=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/regexes.js"(){"use strict";cuid=/^[cC][0-9a-z]{6,}$/,cuid2=/^[0-9a-z]+$/,ulid=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,xid=/^[0-9a-vA-V]{20}$/,ksuid=/^[A-Za-z0-9]{27}$/,nanoid=/^[a-zA-Z0-9_-]{21}$/,duration=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,guid=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,uuid=version2=>version2?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,email=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,_emoji="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";ipv4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,cidrv4=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,cidrv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,base64url=/^[A-Za-z0-9_-]*$/,httpProtocol=/^https?$/,e164=/^\+[1-9]\d{6,14}$/,dateSource="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",date=new RegExp(`^${dateSource}$`);string=params=>{let regex=params?`[\\s\\S]{${params?.minimum??0},${params?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${regex}$`)},bigint=/^-?\d+n?$/,integer=/^-?\d+$/,number=/^-?\d+(?:\.\d+)?$/,boolean=/^(?:true|false)$/i,_null=/^null$/i,lowercase=/^[^A-Z]*$/,uppercase=/^[^a-z]*$/}});var $ZodCheck,numericOriginMap,$ZodCheckLessThan,$ZodCheckGreaterThan,$ZodCheckMultipleOf,$ZodCheckNumberFormat,$ZodCheckMaxLength,$ZodCheckMinLength,$ZodCheckLengthEquals,$ZodCheckStringFormat,$ZodCheckRegex,$ZodCheckLowerCase,$ZodCheckUpperCase,$ZodCheckIncludes,$ZodCheckStartsWith,$ZodCheckEndsWith,$ZodCheckOverwrite,init_checks=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/checks.js"(){"use strict";init_core();init_regexes();init_util();$ZodCheck=$constructor("$ZodCheck",(inst,def)=>{var _a3;inst._zod??(inst._zod={}),inst._zod.def=def,(_a3=inst._zod).onattach??(_a3.onattach=[])}),numericOriginMap={number:"number",bigint:"bigint",object:"date"},$ZodCheckLessThan=$constructor("$ZodCheckLessThan",(inst,def)=>{$ZodCheck.init(inst,def);let origin=numericOriginMap[typeof def.value];inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag,curr=(def.inclusive?bag.maximum:bag.exclusiveMaximum)??Number.POSITIVE_INFINITY;def.value<curr&&(def.inclusive?bag.maximum=def.value:bag.exclusiveMaximum=def.value)}),inst._zod.check=payload=>{(def.inclusive?payload.value<=def.value:payload.value<def.value)||payload.issues.push({origin,code:"too_big",maximum:typeof def.value=="object"?def.value.getTime():def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}}),$ZodCheckGreaterThan=$constructor("$ZodCheckGreaterThan",(inst,def)=>{$ZodCheck.init(inst,def);let origin=numericOriginMap[typeof def.value];inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag,curr=(def.inclusive?bag.minimum:bag.exclusiveMinimum)??Number.NEGATIVE_INFINITY;def.value>curr&&(def.inclusive?bag.minimum=def.value:bag.exclusiveMinimum=def.value)}),inst._zod.check=payload=>{(def.inclusive?payload.value>=def.value:payload.value>def.value)||payload.issues.push({origin,code:"too_small",minimum:typeof def.value=="object"?def.value.getTime():def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}}),$ZodCheckMultipleOf=$constructor("$ZodCheckMultipleOf",(inst,def)=>{$ZodCheck.init(inst,def),inst._zod.onattach.push(inst2=>{var _a3;(_a3=inst2._zod.bag).multipleOf??(_a3.multipleOf=def.value)}),inst._zod.check=payload=>{if(typeof payload.value!=typeof def.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof payload.value=="bigint"?payload.value%def.value===BigInt(0):floatSafeRemainder(payload.value,def.value)===0)||payload.issues.push({origin:typeof payload.value,code:"not_multiple_of",divisor:def.value,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckNumberFormat=$constructor("$ZodCheckNumberFormat",(inst,def)=>{$ZodCheck.init(inst,def),def.format=def.format||"float64";let isInt=def.format?.includes("int"),origin=isInt?"int":"number",[minimum,maximum]=NUMBER_FORMAT_RANGES[def.format];inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.format=def.format,bag.minimum=minimum,bag.maximum=maximum,isInt&&(bag.pattern=integer)}),inst._zod.check=payload=>{let input=payload.value;if(isInt){if(!Number.isInteger(input)){payload.issues.push({expected:origin,format:def.format,code:"invalid_type",continue:!1,input,inst});return}if(!Number.isSafeInteger(input)){input>0?payload.issues.push({input,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,inclusive:!0,continue:!def.abort}):payload.issues.push({input,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,inclusive:!0,continue:!def.abort});return}}input<minimum&&payload.issues.push({origin:"number",input,code:"too_small",minimum,inclusive:!0,inst,continue:!def.abort}),input>maximum&&payload.issues.push({origin:"number",input,code:"too_big",maximum,inclusive:!0,inst,continue:!def.abort})}}),$ZodCheckMaxLength=$constructor("$ZodCheckMaxLength",(inst,def)=>{var _a3;$ZodCheck.init(inst,def),(_a3=inst._zod.def).when??(_a3.when=payload=>{let val=payload.value;return!nullish(val)&&val.length!==void 0}),inst._zod.onattach.push(inst2=>{let curr=inst2._zod.bag.maximum??Number.POSITIVE_INFINITY;def.maximum<curr&&(inst2._zod.bag.maximum=def.maximum)}),inst._zod.check=payload=>{let input=payload.value;if(input.length<=def.maximum)return;let origin=getLengthableOrigin(input);payload.issues.push({origin,code:"too_big",maximum:def.maximum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckMinLength=$constructor("$ZodCheckMinLength",(inst,def)=>{var _a3;$ZodCheck.init(inst,def),(_a3=inst._zod.def).when??(_a3.when=payload=>{let val=payload.value;return!nullish(val)&&val.length!==void 0}),inst._zod.onattach.push(inst2=>{let curr=inst2._zod.bag.minimum??Number.NEGATIVE_INFINITY;def.minimum>curr&&(inst2._zod.bag.minimum=def.minimum)}),inst._zod.check=payload=>{let input=payload.value;if(input.length>=def.minimum)return;let origin=getLengthableOrigin(input);payload.issues.push({origin,code:"too_small",minimum:def.minimum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckLengthEquals=$constructor("$ZodCheckLengthEquals",(inst,def)=>{var _a3;$ZodCheck.init(inst,def),(_a3=inst._zod.def).when??(_a3.when=payload=>{let val=payload.value;return!nullish(val)&&val.length!==void 0}),inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.minimum=def.length,bag.maximum=def.length,bag.length=def.length}),inst._zod.check=payload=>{let input=payload.value,length=input.length;if(length===def.length)return;let origin=getLengthableOrigin(input),tooBig=length>def.length;payload.issues.push({origin,...tooBig?{code:"too_big",maximum:def.length}:{code:"too_small",minimum:def.length},inclusive:!0,exact:!0,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckStringFormat=$constructor("$ZodCheckStringFormat",(inst,def)=>{var _a3,_b;$ZodCheck.init(inst,def),inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.format=def.format,def.pattern&&(bag.patterns??(bag.patterns=new Set),bag.patterns.add(def.pattern))}),def.pattern?(_a3=inst._zod).check??(_a3.check=payload=>{def.pattern.lastIndex=0,!def.pattern.test(payload.value)&&payload.issues.push({origin:"string",code:"invalid_format",format:def.format,input:payload.value,...def.pattern?{pattern:def.pattern.toString()}:{},inst,continue:!def.abort})}):(_b=inst._zod).check??(_b.check=()=>{})}),$ZodCheckRegex=$constructor("$ZodCheckRegex",(inst,def)=>{$ZodCheckStringFormat.init(inst,def),inst._zod.check=payload=>{def.pattern.lastIndex=0,!def.pattern.test(payload.value)&&payload.issues.push({origin:"string",code:"invalid_format",format:"regex",input:payload.value,pattern:def.pattern.toString(),inst,continue:!def.abort})}}),$ZodCheckLowerCase=$constructor("$ZodCheckLowerCase",(inst,def)=>{def.pattern??(def.pattern=lowercase),$ZodCheckStringFormat.init(inst,def)}),$ZodCheckUpperCase=$constructor("$ZodCheckUpperCase",(inst,def)=>{def.pattern??(def.pattern=uppercase),$ZodCheckStringFormat.init(inst,def)}),$ZodCheckIncludes=$constructor("$ZodCheckIncludes",(inst,def)=>{$ZodCheck.init(inst,def);let escapedRegex=escapeRegex(def.includes),pattern=new RegExp(typeof def.position=="number"?`^.{${def.position}}${escapedRegex}`:escapedRegex);def.pattern=pattern,inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set),bag.patterns.add(pattern)}),inst._zod.check=payload=>{payload.value.includes(def.includes,def.position)||payload.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:def.includes,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckStartsWith=$constructor("$ZodCheckStartsWith",(inst,def)=>{$ZodCheck.init(inst,def);let pattern=new RegExp(`^${escapeRegex(def.prefix)}.*`);def.pattern??(def.pattern=pattern),inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set),bag.patterns.add(pattern)}),inst._zod.check=payload=>{payload.value.startsWith(def.prefix)||payload.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:def.prefix,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckEndsWith=$constructor("$ZodCheckEndsWith",(inst,def)=>{$ZodCheck.init(inst,def);let pattern=new RegExp(`.*${escapeRegex(def.suffix)}$`);def.pattern??(def.pattern=pattern),inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set),bag.patterns.add(pattern)}),inst._zod.check=payload=>{payload.value.endsWith(def.suffix)||payload.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:def.suffix,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckOverwrite=$constructor("$ZodCheckOverwrite",(inst,def)=>{$ZodCheck.init(inst,def),inst._zod.check=payload=>{payload.value=def.tx(payload.value)}})}});var Doc,init_doc=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/doc.js"(){"use strict";Doc=class{constructor(args=[]){this.content=[],this.indent=0,this&&(this.args=args)}indented(fn){this.indent+=1,fn(this),this.indent-=1}write(arg){if(typeof arg=="function"){arg(this,{execution:"sync"}),arg(this,{execution:"async"});return}let lines=arg.split(`
|
|
1
|
+
var __defProp=Object.defineProperty;var __getOwnPropNames=Object.getOwnPropertyNames;var __esm=(fn,res)=>function(){return fn&&(res=(0,fn[__getOwnPropNames(fn)[0]])(fn=0)),res};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})};var __create,__defProp2,__getOwnPropDesc,__getOwnPropNames2,__getProtoOf,__hasOwnProp,__commonJSMin,__exportAll,__copyProps,__toESM,init_chunk_Br0eD_fh=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0_patch_hash=2a5f5402571efdc40802e9603a3dd09e22588b4aacad710814c204d79568091e/node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs"(){"use strict";__create=Object.create,__defProp2=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames2=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__commonJSMin=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports),__exportAll=(all,symbols)=>{let target={};for(var name in all)__defProp2(target,name,{get:all[name],enumerable:!0});return symbols&&__defProp2(target,Symbol.toStringTag,{value:"Module"}),target},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(var keys=__getOwnPropNames2(from),i=0,n=keys.length,key;i<n;i++)key=keys[i],!__hasOwnProp.call(to,key)&&key!==except&&__defProp2(to,key,{get:(k=>from[k]).bind(null,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp2(target,"default",{value:mod,enumerable:!0}):target,mod))}});function declares2019Dialect($schema){return typeof $schema=="string"&&DRAFT_2019_09_URIS.has($schema.replace(/#$/,""))}function declaredDialect(schema2,remedy){if(!("$schema"in schema2)||typeof schema2.$schema!="string")return"2020-12";let declared=schema2.$schema.replace(/#$/,"");if(DRAFT_2020_12_URIS.has(declared))return"2020-12";if(DRAFT_2019_09_URIS.has(declared))return"2019-09";if(DRAFT_07_URIS.has(declared)||DRAFT_06_URIS.has(declared))return"draft-7";throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${schema2.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${remedy}`)}var DRAFT_2020_12_URIS,DRAFT_2019_09_URIS,DRAFT_07_URIS,DRAFT_06_URIS,init_dialects_DoSzNhcb=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0_patch_hash=2a5f5402571efdc40802e9603a3dd09e22588b4aacad710814c204d79568091e/node_modules/@modelcontextprotocol/server/dist/dialects-DoSzNhcb.mjs"(){"use strict";DRAFT_2020_12_URIS=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),DRAFT_2019_09_URIS=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),DRAFT_07_URIS=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),DRAFT_06_URIS=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"])}});function $constructor(name,initializer3,params){function init(inst,def){if(inst._zod||Object.defineProperty(inst,"_zod",{value:{def,constr:_,traits:new Set},enumerable:!1}),inst._zod.traits.has(name))return;inst._zod.traits.add(name),initializer3(inst,def);let proto=_.prototype,keys=Object.keys(proto);for(let i=0;i<keys.length;i++){let k=keys[i];k in inst||(inst[k]=proto[k].bind(inst))}}let Parent=params?.Parent??Object;class Definition extends Parent{}Object.defineProperty(Definition,"name",{value:name});function _(def){var _a3;let inst=params?.Parent?new Definition:this;init(inst,def),(_a3=inst._zod).deferred??(_a3.deferred=[]);for(let fn of inst._zod.deferred)fn();return inst}return Object.defineProperty(_,"init",{value:init}),Object.defineProperty(_,Symbol.hasInstance,{value:inst=>params?.Parent&&inst instanceof params.Parent?!0:inst?._zod?.traits?.has(name)}),Object.defineProperty(_,"name",{value:name}),_}function config(newConfig){return newConfig&&Object.assign(globalConfig,newConfig),globalConfig}var _a,NEVER,$ZodAsyncError,$ZodEncodeError,globalConfig,init_core=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js"(){"use strict";NEVER=Object.freeze({status:"aborted"});$ZodAsyncError=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},$ZodEncodeError=class extends Error{constructor(name){super(`Encountered unidirectional transform during encode: ${name}`),this.name="ZodEncodeError"}};(_a=globalThis).__zod_globalConfig??(_a.__zod_globalConfig={});globalConfig=globalThis.__zod_globalConfig}});var util_exports={};__export(util_exports,{BIGINT_FORMAT_RANGES:()=>BIGINT_FORMAT_RANGES,Class:()=>Class,NUMBER_FORMAT_RANGES:()=>NUMBER_FORMAT_RANGES,aborted:()=>aborted,allowsEval:()=>allowsEval,assert:()=>assert,assertEqual:()=>assertEqual,assertIs:()=>assertIs,assertNever:()=>assertNever,assertNotEqual:()=>assertNotEqual,assignProp:()=>assignProp,base64ToUint8Array:()=>base64ToUint8Array,base64urlToUint8Array:()=>base64urlToUint8Array,cached:()=>cached,captureStackTrace:()=>captureStackTrace,cleanEnum:()=>cleanEnum,cleanRegex:()=>cleanRegex,clone:()=>clone,cloneDef:()=>cloneDef,createTransparentProxy:()=>createTransparentProxy,defineLazy:()=>defineLazy,esc:()=>esc,escapeRegex:()=>escapeRegex,explicitlyAborted:()=>explicitlyAborted,extend:()=>extend,finalizeIssue:()=>finalizeIssue,floatSafeRemainder:()=>floatSafeRemainder,getElementAtPath:()=>getElementAtPath,getEnumValues:()=>getEnumValues,getLengthableOrigin:()=>getLengthableOrigin,getParsedType:()=>getParsedType,getSizableOrigin:()=>getSizableOrigin,hexToUint8Array:()=>hexToUint8Array,isObject:()=>isObject,isPlainObject:()=>isPlainObject,issue:()=>issue,joinValues:()=>joinValues,jsonStringifyReplacer:()=>jsonStringifyReplacer,merge:()=>merge,mergeDefs:()=>mergeDefs,normalizeParams:()=>normalizeParams,nullish:()=>nullish,numKeys:()=>numKeys,objectClone:()=>objectClone,omit:()=>omit,optionalKeys:()=>optionalKeys,parsedType:()=>parsedType,partial:()=>partial,pick:()=>pick,prefixIssues:()=>prefixIssues,primitiveTypes:()=>primitiveTypes,promiseAllObject:()=>promiseAllObject,propertyKeyTypes:()=>propertyKeyTypes,randomString:()=>randomString,required:()=>required,safeExtend:()=>safeExtend,shallowClone:()=>shallowClone,slugify:()=>slugify,stringifyPrimitive:()=>stringifyPrimitive,uint8ArrayToBase64:()=>uint8ArrayToBase64,uint8ArrayToBase64url:()=>uint8ArrayToBase64url,uint8ArrayToHex:()=>uint8ArrayToHex,unwrapMessage:()=>unwrapMessage});function assertEqual(val){return val}function assertNotEqual(val){return val}function assertIs(_arg){}function assertNever(_x){throw new Error("Unexpected value in exhaustive check")}function assert(_){}function getEnumValues(entries){let numericValues=Object.values(entries).filter(v=>typeof v=="number");return Object.entries(entries).filter(([k,_])=>numericValues.indexOf(+k)===-1).map(([_,v])=>v)}function joinValues(array4,separator="|"){return array4.map(val=>stringifyPrimitive(val)).join(separator)}function jsonStringifyReplacer(_,value){return typeof value=="bigint"?value.toString():value}function cached(getter){return{get value(){{let value=getter();return Object.defineProperty(this,"value",{value}),value}throw new Error("cached value already set")}}}function nullish(input){return input==null}function cleanRegex(source){let start=source.startsWith("^")?1:0,end=source.endsWith("$")?source.length-1:source.length;return source.slice(start,end)}function floatSafeRemainder(val,step){let ratio=val/step,roundedRatio=Math.round(ratio),tolerance=Number.EPSILON*Math.max(Math.abs(ratio),1);return Math.abs(ratio-roundedRatio)<tolerance?0:ratio-roundedRatio}function defineLazy(object5,key,getter){let value;Object.defineProperty(object5,key,{get(){if(value!==EVALUATING)return value===void 0&&(value=EVALUATING,value=getter()),value},set(v){Object.defineProperty(object5,key,{value:v})},configurable:!0})}function objectClone(obj){return Object.create(Object.getPrototypeOf(obj),Object.getOwnPropertyDescriptors(obj))}function assignProp(target,prop,value){Object.defineProperty(target,prop,{value,writable:!0,enumerable:!0,configurable:!0})}function mergeDefs(...defs){let mergedDescriptors={};for(let def of defs){let descriptors=Object.getOwnPropertyDescriptors(def);Object.assign(mergedDescriptors,descriptors)}return Object.defineProperties({},mergedDescriptors)}function cloneDef(schema2){return mergeDefs(schema2._zod.def)}function getElementAtPath(obj,path){return path?path.reduce((acc,key)=>acc?.[key],obj):obj}function promiseAllObject(promisesObj){let keys=Object.keys(promisesObj),promises=keys.map(key=>promisesObj[key]);return Promise.all(promises).then(results=>{let resolvedObj={};for(let i=0;i<keys.length;i++)resolvedObj[keys[i]]=results[i];return resolvedObj})}function randomString(length=10){let chars="abcdefghijklmnopqrstuvwxyz",str="";for(let i=0;i<length;i++)str+=chars[Math.floor(Math.random()*chars.length)];return str}function esc(str){return JSON.stringify(str)}function slugify(input){return input.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function isObject(data){return typeof data=="object"&&data!==null&&!Array.isArray(data)}function isPlainObject(o){if(isObject(o)===!1)return!1;let ctor=o.constructor;if(ctor===void 0||typeof ctor!="function")return!0;let prot=ctor.prototype;return!(isObject(prot)===!1||Object.prototype.hasOwnProperty.call(prot,"isPrototypeOf")===!1)}function shallowClone(o){return isPlainObject(o)?{...o}:Array.isArray(o)?[...o]:o instanceof Map?new Map(o):o instanceof Set?new Set(o):o}function numKeys(data){let keyCount=0;for(let key in data)Object.prototype.hasOwnProperty.call(data,key)&&keyCount++;return keyCount}function escapeRegex(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function clone(inst,def,params){let cl=new inst._zod.constr(def??inst._zod.def);return(!def||params?.parent)&&(cl._zod.parent=inst),cl}function normalizeParams(_params){let params=_params;if(!params)return{};if(typeof params=="string")return{error:()=>params};if(params?.message!==void 0){if(params?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");params.error=params.message}return delete params.message,typeof params.error=="string"?{...params,error:()=>params.error}:params}function createTransparentProxy(getter){let target;return new Proxy({},{get(_,prop,receiver){return target??(target=getter()),Reflect.get(target,prop,receiver)},set(_,prop,value,receiver){return target??(target=getter()),Reflect.set(target,prop,value,receiver)},has(_,prop){return target??(target=getter()),Reflect.has(target,prop)},deleteProperty(_,prop){return target??(target=getter()),Reflect.deleteProperty(target,prop)},ownKeys(_){return target??(target=getter()),Reflect.ownKeys(target)},getOwnPropertyDescriptor(_,prop){return target??(target=getter()),Reflect.getOwnPropertyDescriptor(target,prop)},defineProperty(_,prop,descriptor){return target??(target=getter()),Reflect.defineProperty(target,prop,descriptor)}})}function stringifyPrimitive(value){return typeof value=="bigint"?value.toString()+"n":typeof value=="string"?`"${value}"`:`${value}`}function optionalKeys(shape){return Object.keys(shape).filter(k=>shape[k]._zod.optin==="optional"&&shape[k]._zod.optout==="optional")}function pick(schema2,mask){let currDef=schema2._zod.def,checks=currDef.checks;if(checks&&checks.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let def=mergeDefs(schema2._zod.def,{get shape(){let newShape={};for(let key in mask){if(!(key in currDef.shape))throw new Error(`Unrecognized key: "${key}"`);mask[key]&&(newShape[key]=currDef.shape[key])}return assignProp(this,"shape",newShape),newShape},checks:[]});return clone(schema2,def)}function omit(schema2,mask){let currDef=schema2._zod.def,checks=currDef.checks;if(checks&&checks.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let def=mergeDefs(schema2._zod.def,{get shape(){let newShape={...schema2._zod.def.shape};for(let key in mask){if(!(key in currDef.shape))throw new Error(`Unrecognized key: "${key}"`);mask[key]&&delete newShape[key]}return assignProp(this,"shape",newShape),newShape},checks:[]});return clone(schema2,def)}function extend(schema2,shape){if(!isPlainObject(shape))throw new Error("Invalid input to extend: expected a plain object");let checks=schema2._zod.def.checks;if(checks&&checks.length>0){let existingShape=schema2._zod.def.shape;for(let key in shape)if(Object.getOwnPropertyDescriptor(existingShape,key)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let def=mergeDefs(schema2._zod.def,{get shape(){let _shape={...schema2._zod.def.shape,...shape};return assignProp(this,"shape",_shape),_shape}});return clone(schema2,def)}function safeExtend(schema2,shape){if(!isPlainObject(shape))throw new Error("Invalid input to safeExtend: expected a plain object");let def=mergeDefs(schema2._zod.def,{get shape(){let _shape={...schema2._zod.def.shape,...shape};return assignProp(this,"shape",_shape),_shape}});return clone(schema2,def)}function merge(a,b){if(a._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let def=mergeDefs(a._zod.def,{get shape(){let _shape={...a._zod.def.shape,...b._zod.def.shape};return assignProp(this,"shape",_shape),_shape},get catchall(){return b._zod.def.catchall},checks:b._zod.def.checks??[]});return clone(a,def)}function partial(Class2,schema2,mask){let checks=schema2._zod.def.checks;if(checks&&checks.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let def=mergeDefs(schema2._zod.def,{get shape(){let oldShape=schema2._zod.def.shape,shape={...oldShape};if(mask)for(let key in mask){if(!(key in oldShape))throw new Error(`Unrecognized key: "${key}"`);mask[key]&&(shape[key]=Class2?new Class2({type:"optional",innerType:oldShape[key]}):oldShape[key])}else for(let key in oldShape)shape[key]=Class2?new Class2({type:"optional",innerType:oldShape[key]}):oldShape[key];return assignProp(this,"shape",shape),shape},checks:[]});return clone(schema2,def)}function required(Class2,schema2,mask){let def=mergeDefs(schema2._zod.def,{get shape(){let oldShape=schema2._zod.def.shape,shape={...oldShape};if(mask)for(let key in mask){if(!(key in shape))throw new Error(`Unrecognized key: "${key}"`);mask[key]&&(shape[key]=new Class2({type:"nonoptional",innerType:oldShape[key]}))}else for(let key in oldShape)shape[key]=new Class2({type:"nonoptional",innerType:oldShape[key]});return assignProp(this,"shape",shape),shape}});return clone(schema2,def)}function aborted(x,startIndex=0){if(x.aborted===!0)return!0;for(let i=startIndex;i<x.issues.length;i++)if(x.issues[i]?.continue!==!0)return!0;return!1}function explicitlyAborted(x,startIndex=0){if(x.aborted===!0)return!0;for(let i=startIndex;i<x.issues.length;i++)if(x.issues[i]?.continue===!1)return!0;return!1}function prefixIssues(path,issues){return issues.map(iss=>{var _a3;return(_a3=iss).path??(_a3.path=[]),iss.path.unshift(path),iss})}function unwrapMessage(message){return typeof message=="string"?message:message?.message}function finalizeIssue(iss,ctx,config2){let message=iss.message?iss.message:unwrapMessage(iss.inst?._zod.def?.error?.(iss))??unwrapMessage(ctx?.error?.(iss))??unwrapMessage(config2.customError?.(iss))??unwrapMessage(config2.localeError?.(iss))??"Invalid input",{inst:_inst,continue:_continue,input:_input,...rest}=iss;return rest.path??(rest.path=[]),rest.message=message,ctx?.reportInput&&(rest.input=_input),rest}function getSizableOrigin(input){return input instanceof Set?"set":input instanceof Map?"map":input instanceof File?"file":"unknown"}function getLengthableOrigin(input){return Array.isArray(input)?"array":typeof input=="string"?"string":"unknown"}function parsedType(data){let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"nan":"number";case"object":{if(data===null)return"null";if(Array.isArray(data))return"array";let obj=data;if(obj&&Object.getPrototypeOf(obj)!==Object.prototype&&"constructor"in obj&&obj.constructor)return obj.constructor.name}}return t}function issue(...args){let[iss,input,inst]=args;return typeof iss=="string"?{message:iss,code:"custom",input,inst}:{...iss}}function cleanEnum(obj){return Object.entries(obj).filter(([k,_])=>Number.isNaN(Number.parseInt(k,10))).map(el=>el[1])}function base64ToUint8Array(base642){let binaryString=atob(base642),bytes=new Uint8Array(binaryString.length);for(let i=0;i<binaryString.length;i++)bytes[i]=binaryString.charCodeAt(i);return bytes}function uint8ArrayToBase64(bytes){let binaryString="";for(let i=0;i<bytes.length;i++)binaryString+=String.fromCharCode(bytes[i]);return btoa(binaryString)}function base64urlToUint8Array(base64url2){let base642=base64url2.replace(/-/g,"+").replace(/_/g,"/"),padding="=".repeat((4-base642.length%4)%4);return base64ToUint8Array(base642+padding)}function uint8ArrayToBase64url(bytes){return uint8ArrayToBase64(bytes).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function hexToUint8Array(hex){let cleanHex=hex.replace(/^0x/,"");if(cleanHex.length%2!==0)throw new Error("Invalid hex string length");let bytes=new Uint8Array(cleanHex.length/2);for(let i=0;i<cleanHex.length;i+=2)bytes[i/2]=Number.parseInt(cleanHex.slice(i,i+2),16);return bytes}function uint8ArrayToHex(bytes){return Array.from(bytes).map(b=>b.toString(16).padStart(2,"0")).join("")}var EVALUATING,captureStackTrace,allowsEval,getParsedType,propertyKeyTypes,primitiveTypes,NUMBER_FORMAT_RANGES,BIGINT_FORMAT_RANGES,Class,init_util=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/util.js"(){"use strict";init_core();EVALUATING=Symbol("evaluating");captureStackTrace="captureStackTrace"in Error?Error.captureStackTrace:(..._args)=>{};allowsEval=cached(()=>{if(globalConfig.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let F=Function;return new F(""),!0}catch{return!1}});getParsedType=data=>{let t=typeof data;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(data)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(data)?"array":data===null?"null":data.then&&typeof data.then=="function"&&data.catch&&typeof data.catch=="function"?"promise":typeof Map<"u"&&data instanceof Map?"map":typeof Set<"u"&&data instanceof Set?"set":typeof Date<"u"&&data instanceof Date?"date":typeof File<"u"&&data instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},propertyKeyTypes=new Set(["string","number","symbol"]),primitiveTypes=new Set(["string","number","bigint","boolean","symbol","undefined"]);NUMBER_FORMAT_RANGES={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},BIGINT_FORMAT_RANGES={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Class=class{constructor(..._args){}}}});function flattenError(error3,mapper=issue2=>issue2.message){let fieldErrors={},formErrors=[];for(let sub of error3.issues)sub.path.length>0?(fieldErrors[sub.path[0]]=fieldErrors[sub.path[0]]||[],fieldErrors[sub.path[0]].push(mapper(sub))):formErrors.push(mapper(sub));return{formErrors,fieldErrors}}function formatError(error3,mapper=issue2=>issue2.message){let fieldErrors={_errors:[]},processError=(error4,path=[])=>{for(let issue2 of error4.issues)if(issue2.code==="invalid_union"&&issue2.errors.length)issue2.errors.map(issues=>processError({issues},[...path,...issue2.path]));else if(issue2.code==="invalid_key")processError({issues:issue2.issues},[...path,...issue2.path]);else if(issue2.code==="invalid_element")processError({issues:issue2.issues},[...path,...issue2.path]);else{let fullpath=[...path,...issue2.path];if(fullpath.length===0)fieldErrors._errors.push(mapper(issue2));else{let curr=fieldErrors,i=0;for(;i<fullpath.length;){let el=fullpath[i];i===fullpath.length-1?(curr[el]=curr[el]||{_errors:[]},curr[el]._errors.push(mapper(issue2))):curr[el]=curr[el]||{_errors:[]},curr=curr[el],i++}}}};return processError(error3),fieldErrors}var initializer,$ZodError,$ZodRealError,init_errors=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/errors.js"(){"use strict";init_core();init_util();initializer=(inst,def)=>{inst.name="$ZodError",Object.defineProperty(inst,"_zod",{value:inst._zod,enumerable:!1}),Object.defineProperty(inst,"issues",{value:def,enumerable:!1}),inst.message=JSON.stringify(def,jsonStringifyReplacer,2),Object.defineProperty(inst,"toString",{value:()=>inst.message,enumerable:!1})},$ZodError=$constructor("$ZodError",initializer),$ZodRealError=$constructor("$ZodError",initializer,{Parent:Error})}});var _parse,_parseAsync,_safeParse,safeParse,_safeParseAsync,safeParseAsync,_encode,_decode,_encodeAsync,_decodeAsync,_safeEncode,_safeDecode,_safeEncodeAsync,_safeDecodeAsync,init_parse=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/parse.js"(){"use strict";init_core();init_errors();init_util();_parse=_Err=>(schema2,value,_ctx,_params)=>{let ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema2._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError;if(result.issues.length){let e=new(_params?.Err??_Err)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())));throw captureStackTrace(e,_params?.callee),e}return result.value},_parseAsync=_Err=>async(schema2,value,_ctx,params)=>{let ctx=_ctx?{..._ctx,async:!0}:{async:!0},result=schema2._zod.run({value,issues:[]},ctx);if(result instanceof Promise&&(result=await result),result.issues.length){let e=new(params?.Err??_Err)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())));throw captureStackTrace(e,params?.callee),e}return result.value},_safeParse=_Err=>(schema2,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema2._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError;return result.issues.length?{success:!1,error:new(_Err??$ZodError)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}:{success:!0,data:result.value}},safeParse=_safeParse($ZodRealError),_safeParseAsync=_Err=>async(schema2,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!0}:{async:!0},result=schema2._zod.run({value,issues:[]},ctx);return result instanceof Promise&&(result=await result),result.issues.length?{success:!1,error:new _Err(result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}:{success:!0,data:result.value}},safeParseAsync=_safeParseAsync($ZodRealError),_encode=_Err=>(schema2,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _parse(_Err)(schema2,value,ctx)},_decode=_Err=>(schema2,value,_ctx)=>_parse(_Err)(schema2,value,_ctx),_encodeAsync=_Err=>async(schema2,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _parseAsync(_Err)(schema2,value,ctx)},_decodeAsync=_Err=>async(schema2,value,_ctx)=>_parseAsync(_Err)(schema2,value,_ctx),_safeEncode=_Err=>(schema2,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _safeParse(_Err)(schema2,value,ctx)},_safeDecode=_Err=>(schema2,value,_ctx)=>_safeParse(_Err)(schema2,value,_ctx),_safeEncodeAsync=_Err=>async(schema2,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _safeParseAsync(_Err)(schema2,value,ctx)},_safeDecodeAsync=_Err=>async(schema2,value,_ctx)=>_safeParseAsync(_Err)(schema2,value,_ctx)}});function emoji(){return new RegExp(_emoji,"u")}function timeSource(args){let hhmm="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof args.precision=="number"?args.precision===-1?`${hhmm}`:args.precision===0?`${hhmm}:[0-5]\\d`:`${hhmm}:[0-5]\\d\\.\\d{${args.precision}}`:`${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`}function time(args){return new RegExp(`^${timeSource(args)}$`)}function datetime(args){let time3=timeSource({precision:args.precision}),opts=["Z"];args.local&&opts.push(""),args.offset&&opts.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let timeRegex=`${time3}(?:${opts.join("|")})`;return new RegExp(`^${dateSource}T(?:${timeRegex})$`)}var cuid,cuid2,ulid,xid,ksuid,nanoid,duration,guid,uuid,email,_emoji,ipv4,ipv6,cidrv4,cidrv6,base64,base64url,httpProtocol,e164,dateSource,date,string,bigint,integer,number,boolean,_null,lowercase,uppercase,init_regexes=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/regexes.js"(){"use strict";cuid=/^[cC][0-9a-z]{6,}$/,cuid2=/^[0-9a-z]+$/,ulid=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,xid=/^[0-9a-vA-V]{20}$/,ksuid=/^[A-Za-z0-9]{27}$/,nanoid=/^[a-zA-Z0-9_-]{21}$/,duration=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,guid=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,uuid=version2=>version2?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,email=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,_emoji="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";ipv4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,cidrv4=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,cidrv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,base64url=/^[A-Za-z0-9_-]*$/,httpProtocol=/^https?$/,e164=/^\+[1-9]\d{6,14}$/,dateSource="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",date=new RegExp(`^${dateSource}$`);string=params=>{let regex=params?`[\\s\\S]{${params?.minimum??0},${params?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${regex}$`)},bigint=/^-?\d+n?$/,integer=/^-?\d+$/,number=/^-?\d+(?:\.\d+)?$/,boolean=/^(?:true|false)$/i,_null=/^null$/i,lowercase=/^[^A-Z]*$/,uppercase=/^[^a-z]*$/}});var $ZodCheck,numericOriginMap,$ZodCheckLessThan,$ZodCheckGreaterThan,$ZodCheckMultipleOf,$ZodCheckNumberFormat,$ZodCheckMaxLength,$ZodCheckMinLength,$ZodCheckLengthEquals,$ZodCheckStringFormat,$ZodCheckRegex,$ZodCheckLowerCase,$ZodCheckUpperCase,$ZodCheckIncludes,$ZodCheckStartsWith,$ZodCheckEndsWith,$ZodCheckOverwrite,init_checks=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/checks.js"(){"use strict";init_core();init_regexes();init_util();$ZodCheck=$constructor("$ZodCheck",(inst,def)=>{var _a3;inst._zod??(inst._zod={}),inst._zod.def=def,(_a3=inst._zod).onattach??(_a3.onattach=[])}),numericOriginMap={number:"number",bigint:"bigint",object:"date"},$ZodCheckLessThan=$constructor("$ZodCheckLessThan",(inst,def)=>{$ZodCheck.init(inst,def);let origin=numericOriginMap[typeof def.value];inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag,curr=(def.inclusive?bag.maximum:bag.exclusiveMaximum)??Number.POSITIVE_INFINITY;def.value<curr&&(def.inclusive?bag.maximum=def.value:bag.exclusiveMaximum=def.value)}),inst._zod.check=payload=>{(def.inclusive?payload.value<=def.value:payload.value<def.value)||payload.issues.push({origin,code:"too_big",maximum:typeof def.value=="object"?def.value.getTime():def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}}),$ZodCheckGreaterThan=$constructor("$ZodCheckGreaterThan",(inst,def)=>{$ZodCheck.init(inst,def);let origin=numericOriginMap[typeof def.value];inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag,curr=(def.inclusive?bag.minimum:bag.exclusiveMinimum)??Number.NEGATIVE_INFINITY;def.value>curr&&(def.inclusive?bag.minimum=def.value:bag.exclusiveMinimum=def.value)}),inst._zod.check=payload=>{(def.inclusive?payload.value>=def.value:payload.value>def.value)||payload.issues.push({origin,code:"too_small",minimum:typeof def.value=="object"?def.value.getTime():def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}}),$ZodCheckMultipleOf=$constructor("$ZodCheckMultipleOf",(inst,def)=>{$ZodCheck.init(inst,def),inst._zod.onattach.push(inst2=>{var _a3;(_a3=inst2._zod.bag).multipleOf??(_a3.multipleOf=def.value)}),inst._zod.check=payload=>{if(typeof payload.value!=typeof def.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof payload.value=="bigint"?payload.value%def.value===BigInt(0):floatSafeRemainder(payload.value,def.value)===0)||payload.issues.push({origin:typeof payload.value,code:"not_multiple_of",divisor:def.value,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckNumberFormat=$constructor("$ZodCheckNumberFormat",(inst,def)=>{$ZodCheck.init(inst,def),def.format=def.format||"float64";let isInt=def.format?.includes("int"),origin=isInt?"int":"number",[minimum,maximum]=NUMBER_FORMAT_RANGES[def.format];inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.format=def.format,bag.minimum=minimum,bag.maximum=maximum,isInt&&(bag.pattern=integer)}),inst._zod.check=payload=>{let input=payload.value;if(isInt){if(!Number.isInteger(input)){payload.issues.push({expected:origin,format:def.format,code:"invalid_type",continue:!1,input,inst});return}if(!Number.isSafeInteger(input)){input>0?payload.issues.push({input,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,inclusive:!0,continue:!def.abort}):payload.issues.push({input,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,inclusive:!0,continue:!def.abort});return}}input<minimum&&payload.issues.push({origin:"number",input,code:"too_small",minimum,inclusive:!0,inst,continue:!def.abort}),input>maximum&&payload.issues.push({origin:"number",input,code:"too_big",maximum,inclusive:!0,inst,continue:!def.abort})}}),$ZodCheckMaxLength=$constructor("$ZodCheckMaxLength",(inst,def)=>{var _a3;$ZodCheck.init(inst,def),(_a3=inst._zod.def).when??(_a3.when=payload=>{let val=payload.value;return!nullish(val)&&val.length!==void 0}),inst._zod.onattach.push(inst2=>{let curr=inst2._zod.bag.maximum??Number.POSITIVE_INFINITY;def.maximum<curr&&(inst2._zod.bag.maximum=def.maximum)}),inst._zod.check=payload=>{let input=payload.value;if(input.length<=def.maximum)return;let origin=getLengthableOrigin(input);payload.issues.push({origin,code:"too_big",maximum:def.maximum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckMinLength=$constructor("$ZodCheckMinLength",(inst,def)=>{var _a3;$ZodCheck.init(inst,def),(_a3=inst._zod.def).when??(_a3.when=payload=>{let val=payload.value;return!nullish(val)&&val.length!==void 0}),inst._zod.onattach.push(inst2=>{let curr=inst2._zod.bag.minimum??Number.NEGATIVE_INFINITY;def.minimum>curr&&(inst2._zod.bag.minimum=def.minimum)}),inst._zod.check=payload=>{let input=payload.value;if(input.length>=def.minimum)return;let origin=getLengthableOrigin(input);payload.issues.push({origin,code:"too_small",minimum:def.minimum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckLengthEquals=$constructor("$ZodCheckLengthEquals",(inst,def)=>{var _a3;$ZodCheck.init(inst,def),(_a3=inst._zod.def).when??(_a3.when=payload=>{let val=payload.value;return!nullish(val)&&val.length!==void 0}),inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.minimum=def.length,bag.maximum=def.length,bag.length=def.length}),inst._zod.check=payload=>{let input=payload.value,length=input.length;if(length===def.length)return;let origin=getLengthableOrigin(input),tooBig=length>def.length;payload.issues.push({origin,...tooBig?{code:"too_big",maximum:def.length}:{code:"too_small",minimum:def.length},inclusive:!0,exact:!0,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckStringFormat=$constructor("$ZodCheckStringFormat",(inst,def)=>{var _a3,_b;$ZodCheck.init(inst,def),inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.format=def.format,def.pattern&&(bag.patterns??(bag.patterns=new Set),bag.patterns.add(def.pattern))}),def.pattern?(_a3=inst._zod).check??(_a3.check=payload=>{def.pattern.lastIndex=0,!def.pattern.test(payload.value)&&payload.issues.push({origin:"string",code:"invalid_format",format:def.format,input:payload.value,...def.pattern?{pattern:def.pattern.toString()}:{},inst,continue:!def.abort})}):(_b=inst._zod).check??(_b.check=()=>{})}),$ZodCheckRegex=$constructor("$ZodCheckRegex",(inst,def)=>{$ZodCheckStringFormat.init(inst,def),inst._zod.check=payload=>{def.pattern.lastIndex=0,!def.pattern.test(payload.value)&&payload.issues.push({origin:"string",code:"invalid_format",format:"regex",input:payload.value,pattern:def.pattern.toString(),inst,continue:!def.abort})}}),$ZodCheckLowerCase=$constructor("$ZodCheckLowerCase",(inst,def)=>{def.pattern??(def.pattern=lowercase),$ZodCheckStringFormat.init(inst,def)}),$ZodCheckUpperCase=$constructor("$ZodCheckUpperCase",(inst,def)=>{def.pattern??(def.pattern=uppercase),$ZodCheckStringFormat.init(inst,def)}),$ZodCheckIncludes=$constructor("$ZodCheckIncludes",(inst,def)=>{$ZodCheck.init(inst,def);let escapedRegex=escapeRegex(def.includes),pattern=new RegExp(typeof def.position=="number"?`^.{${def.position}}${escapedRegex}`:escapedRegex);def.pattern=pattern,inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set),bag.patterns.add(pattern)}),inst._zod.check=payload=>{payload.value.includes(def.includes,def.position)||payload.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:def.includes,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckStartsWith=$constructor("$ZodCheckStartsWith",(inst,def)=>{$ZodCheck.init(inst,def);let pattern=new RegExp(`^${escapeRegex(def.prefix)}.*`);def.pattern??(def.pattern=pattern),inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set),bag.patterns.add(pattern)}),inst._zod.check=payload=>{payload.value.startsWith(def.prefix)||payload.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:def.prefix,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckEndsWith=$constructor("$ZodCheckEndsWith",(inst,def)=>{$ZodCheck.init(inst,def);let pattern=new RegExp(`.*${escapeRegex(def.suffix)}$`);def.pattern??(def.pattern=pattern),inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set),bag.patterns.add(pattern)}),inst._zod.check=payload=>{payload.value.endsWith(def.suffix)||payload.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:def.suffix,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckOverwrite=$constructor("$ZodCheckOverwrite",(inst,def)=>{$ZodCheck.init(inst,def),inst._zod.check=payload=>{payload.value=def.tx(payload.value)}})}});var Doc,init_doc=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/doc.js"(){"use strict";Doc=class{constructor(args=[]){this.content=[],this.indent=0,this&&(this.args=args)}indented(fn){this.indent+=1,fn(this),this.indent-=1}write(arg){if(typeof arg=="function"){arg(this,{execution:"sync"}),arg(this,{execution:"async"});return}let lines=arg.split(`
|
|
2
2
|
`).filter(x=>x),minIndent=Math.min(...lines.map(x=>x.length-x.trimStart().length)),dedented=lines.map(x=>x.slice(minIndent)).map(x=>" ".repeat(this.indent*2)+x);for(let line of dedented)this.content.push(line)}compile(){let F=Function,args=this?.args,lines=[...(this?.content??[""]).map(x=>` ${x}`)];return new F(...args,lines.join(`
|
|
3
3
|
`))}}}});var version,init_versions=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/versions.js"(){"use strict";version={major:4,minor:4,patch:3}}});function isValidBase64(data){if(data==="")return!0;if(/\s/.test(data)||data.length%4!==0)return!1;try{return atob(data),!0}catch{return!1}}function isValidBase64URL(data){if(!base64url.test(data))return!1;let base642=data.replace(/[-_]/g,c=>c==="-"?"+":"/"),padded=base642.padEnd(Math.ceil(base642.length/4)*4,"=");return isValidBase64(padded)}function isValidJWT(token,algorithm=null){try{let tokensParts=token.split(".");if(tokensParts.length!==3)return!1;let[header]=tokensParts;if(!header)return!1;let parsedHeader=JSON.parse(atob(header));return!("typ"in parsedHeader&&parsedHeader?.typ!=="JWT"||!parsedHeader.alg||algorithm&&(!("alg"in parsedHeader)||parsedHeader.alg!==algorithm))}catch{return!1}}function handleArrayResult(result,final,index){result.issues.length&&final.issues.push(...prefixIssues(index,result.issues)),final.value[index]=result.value}function handlePropertyResult(result,final,key,input,isOptionalIn,isOptionalOut){let isPresent=key in input;if(result.issues.length){if(isOptionalIn&&isOptionalOut&&!isPresent)return;final.issues.push(...prefixIssues(key,result.issues))}if(!isPresent&&!isOptionalIn){result.issues.length||final.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[key]});return}result.value===void 0?isPresent&&(final.value[key]=void 0):final.value[key]=result.value}function normalizeDef(def){let keys=Object.keys(def.shape);for(let k of keys)if(!def.shape?.[k]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${k}": expected a Zod schema`);let okeys=optionalKeys(def.shape);return{...def,keys,keySet:new Set(keys),numKeys:keys.length,optionalKeys:new Set(okeys)}}function handleCatchall(proms,input,payload,ctx,def,inst){let unrecognized=[],keySet=def.keySet,_catchall=def.catchall._zod,t=_catchall.def.type,isOptionalIn=_catchall.optin==="optional",isOptionalOut=_catchall.optout==="optional";for(let key in input){if(key==="__proto__"||keySet.has(key))continue;if(t==="never"){unrecognized.push(key);continue}let r=_catchall.run({value:input[key],issues:[]},ctx);r instanceof Promise?proms.push(r.then(r2=>handlePropertyResult(r2,payload,key,input,isOptionalIn,isOptionalOut))):handlePropertyResult(r,payload,key,input,isOptionalIn,isOptionalOut)}return unrecognized.length&&payload.issues.push({code:"unrecognized_keys",keys:unrecognized,input,inst}),proms.length?Promise.all(proms).then(()=>payload):payload}function handleUnionResults(results,final,inst,ctx){for(let result of results)if(result.issues.length===0)return final.value=result.value,final;let nonaborted=results.filter(r=>!aborted(r));return nonaborted.length===1?(final.value=nonaborted[0].value,nonaborted[0]):(final.issues.push({code:"invalid_union",input:final.value,inst,errors:results.map(result=>result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}),final)}function mergeValues(a,b){if(a===b)return{valid:!0,data:a};if(a instanceof Date&&b instanceof Date&&+a==+b)return{valid:!0,data:a};if(isPlainObject(a)&&isPlainObject(b)){let bKeys=Object.keys(b),sharedKeys=Object.keys(a).filter(key=>bKeys.indexOf(key)!==-1),newObj={...a,...b};for(let key of sharedKeys){let sharedValue=mergeValues(a[key],b[key]);if(!sharedValue.valid)return{valid:!1,mergeErrorPath:[key,...sharedValue.mergeErrorPath]};newObj[key]=sharedValue.data}return{valid:!0,data:newObj}}if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)return{valid:!1,mergeErrorPath:[]};let newArray=[];for(let index=0;index<a.length;index++){let itemA=a[index],itemB=b[index],sharedValue=mergeValues(itemA,itemB);if(!sharedValue.valid)return{valid:!1,mergeErrorPath:[index,...sharedValue.mergeErrorPath]};newArray.push(sharedValue.data)}return{valid:!0,data:newArray}}return{valid:!1,mergeErrorPath:[]}}function handleIntersectionResults(result,left,right){let unrecKeys=new Map,unrecIssue;for(let iss of left.issues)if(iss.code==="unrecognized_keys"){unrecIssue??(unrecIssue=iss);for(let k of iss.keys)unrecKeys.has(k)||unrecKeys.set(k,{}),unrecKeys.get(k).l=!0}else result.issues.push(iss);for(let iss of right.issues)if(iss.code==="unrecognized_keys")for(let k of iss.keys)unrecKeys.has(k)||unrecKeys.set(k,{}),unrecKeys.get(k).r=!0;else result.issues.push(iss);let bothKeys=[...unrecKeys].filter(([,f])=>f.l&&f.r).map(([k])=>k);if(bothKeys.length&&unrecIssue&&result.issues.push({...unrecIssue,keys:bothKeys}),aborted(result))return result;let merged=mergeValues(left.value,right.value);if(!merged.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);return result.value=merged.data,result}function handleOptionalResult(result,input){return input===void 0&&(result.issues.length||result.fallback)?{issues:[],value:void 0}:result}function handleDefaultResult(payload,def){return payload.value===void 0&&(payload.value=def.defaultValue),payload}function handleNonOptionalResult(payload,inst){return!payload.issues.length&&payload.value===void 0&&payload.issues.push({code:"invalid_type",expected:"nonoptional",input:payload.value,inst}),payload}function handlePipeResult(left,next,ctx){return left.issues.length?(left.aborted=!0,left):next._zod.run({value:left.value,issues:left.issues,fallback:left.fallback},ctx)}function handleReadonlyResult(payload){return payload.value=Object.freeze(payload.value),payload}function handleRefineResult(result,payload,input,inst){if(!result){let _iss={code:"custom",input,inst,path:[...inst._zod.def.path??[]],continue:!inst._zod.def.abort};inst._zod.def.params&&(_iss.params=inst._zod.def.params),payload.issues.push(issue(_iss))}}var $ZodType,$ZodString,$ZodStringFormat,$ZodGUID,$ZodUUID,$ZodEmail,$ZodURL,$ZodEmoji,$ZodNanoID,$ZodCUID,$ZodCUID2,$ZodULID,$ZodXID,$ZodKSUID,$ZodISODateTime,$ZodISODate,$ZodISOTime,$ZodISODuration,$ZodIPv4,$ZodIPv6,$ZodCIDRv4,$ZodCIDRv6,$ZodBase64,$ZodBase64URL,$ZodE164,$ZodJWT,$ZodNumber,$ZodNumberFormat,$ZodBoolean,$ZodBigInt,$ZodNull,$ZodAny,$ZodUnknown,$ZodNever,$ZodDate,$ZodArray,$ZodObject,$ZodObjectJIT,$ZodUnion,$ZodDiscriminatedUnion,$ZodIntersection,$ZodRecord,$ZodEnum,$ZodLiteral,$ZodTransform,$ZodOptional,$ZodExactOptional,$ZodNullable,$ZodDefault,$ZodPrefault,$ZodNonOptional,$ZodCatch,$ZodPipe,$ZodPreprocess,$ZodReadonly,$ZodLazy,$ZodCustom,init_schemas=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/schemas.js"(){"use strict";init_checks();init_core();init_doc();init_parse();init_regexes();init_util();init_versions();init_util();$ZodType=$constructor("$ZodType",(inst,def)=>{var _a3;inst??(inst={}),inst._zod.def=def,inst._zod.bag=inst._zod.bag||{},inst._zod.version=version;let checks=[...inst._zod.def.checks??[]];inst._zod.traits.has("$ZodCheck")&&checks.unshift(inst);for(let ch of checks)for(let fn of ch._zod.onattach)fn(inst);if(checks.length===0)(_a3=inst._zod).deferred??(_a3.deferred=[]),inst._zod.deferred?.push(()=>{inst._zod.run=inst._zod.parse});else{let runChecks=(payload,checks2,ctx)=>{let isAborted=aborted(payload),asyncResult;for(let ch of checks2){if(ch._zod.def.when){if(explicitlyAborted(payload)||!ch._zod.def.when(payload))continue}else if(isAborted)continue;let currLen=payload.issues.length,_=ch._zod.check(payload);if(_ instanceof Promise&&ctx?.async===!1)throw new $ZodAsyncError;if(asyncResult||_ instanceof Promise)asyncResult=(asyncResult??Promise.resolve()).then(async()=>{await _,payload.issues.length!==currLen&&(isAborted||(isAborted=aborted(payload,currLen)))});else{if(payload.issues.length===currLen)continue;isAborted||(isAborted=aborted(payload,currLen))}}return asyncResult?asyncResult.then(()=>payload):payload},handleCanaryResult=(canary,payload,ctx)=>{if(aborted(canary))return canary.aborted=!0,canary;let checkResult=runChecks(payload,checks,ctx);if(checkResult instanceof Promise){if(ctx.async===!1)throw new $ZodAsyncError;return checkResult.then(checkResult2=>inst._zod.parse(checkResult2,ctx))}return inst._zod.parse(checkResult,ctx)};inst._zod.run=(payload,ctx)=>{if(ctx.skipChecks)return inst._zod.parse(payload,ctx);if(ctx.direction==="backward"){let canary=inst._zod.parse({value:payload.value,issues:[]},{...ctx,skipChecks:!0});return canary instanceof Promise?canary.then(canary2=>handleCanaryResult(canary2,payload,ctx)):handleCanaryResult(canary,payload,ctx)}let result=inst._zod.parse(payload,ctx);if(result instanceof Promise){if(ctx.async===!1)throw new $ZodAsyncError;return result.then(result2=>runChecks(result2,checks,ctx))}return runChecks(result,checks,ctx)}}defineLazy(inst,"~standard",()=>({validate:value=>{try{let r=safeParse(inst,value);return r.success?{value:r.data}:{issues:r.error?.issues}}catch{return safeParseAsync(inst,value).then(r=>r.success?{value:r.data}:{issues:r.error?.issues})}},vendor:"zod",version:1}))}),$ZodString=$constructor("$ZodString",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=[...inst?._zod.bag?.patterns??[]].pop()??string(inst._zod.bag),inst._zod.parse=(payload,_)=>{if(def.coerce)try{payload.value=String(payload.value)}catch{}return typeof payload.value=="string"||payload.issues.push({expected:"string",code:"invalid_type",input:payload.value,inst}),payload}}),$ZodStringFormat=$constructor("$ZodStringFormat",(inst,def)=>{$ZodCheckStringFormat.init(inst,def),$ZodString.init(inst,def)}),$ZodGUID=$constructor("$ZodGUID",(inst,def)=>{def.pattern??(def.pattern=guid),$ZodStringFormat.init(inst,def)}),$ZodUUID=$constructor("$ZodUUID",(inst,def)=>{if(def.version){let v={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[def.version];if(v===void 0)throw new Error(`Invalid UUID version: "${def.version}"`);def.pattern??(def.pattern=uuid(v))}else def.pattern??(def.pattern=uuid());$ZodStringFormat.init(inst,def)}),$ZodEmail=$constructor("$ZodEmail",(inst,def)=>{def.pattern??(def.pattern=email),$ZodStringFormat.init(inst,def)}),$ZodURL=$constructor("$ZodURL",(inst,def)=>{$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{try{let trimmed=payload.value.trim();if(!def.normalize&&def.protocol?.source===httpProtocol.source&&!/^https?:\/\//i.test(trimmed)){payload.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:payload.value,inst,continue:!def.abort});return}let url2=new URL(trimmed);def.hostname&&(def.hostname.lastIndex=0,def.hostname.test(url2.hostname)||payload.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:def.hostname.source,input:payload.value,inst,continue:!def.abort})),def.protocol&&(def.protocol.lastIndex=0,def.protocol.test(url2.protocol.endsWith(":")?url2.protocol.slice(0,-1):url2.protocol)||payload.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:def.protocol.source,input:payload.value,inst,continue:!def.abort})),def.normalize?payload.value=url2.href:payload.value=trimmed;return}catch{payload.issues.push({code:"invalid_format",format:"url",input:payload.value,inst,continue:!def.abort})}}}),$ZodEmoji=$constructor("$ZodEmoji",(inst,def)=>{def.pattern??(def.pattern=emoji()),$ZodStringFormat.init(inst,def)}),$ZodNanoID=$constructor("$ZodNanoID",(inst,def)=>{def.pattern??(def.pattern=nanoid),$ZodStringFormat.init(inst,def)}),$ZodCUID=$constructor("$ZodCUID",(inst,def)=>{def.pattern??(def.pattern=cuid),$ZodStringFormat.init(inst,def)}),$ZodCUID2=$constructor("$ZodCUID2",(inst,def)=>{def.pattern??(def.pattern=cuid2),$ZodStringFormat.init(inst,def)}),$ZodULID=$constructor("$ZodULID",(inst,def)=>{def.pattern??(def.pattern=ulid),$ZodStringFormat.init(inst,def)}),$ZodXID=$constructor("$ZodXID",(inst,def)=>{def.pattern??(def.pattern=xid),$ZodStringFormat.init(inst,def)}),$ZodKSUID=$constructor("$ZodKSUID",(inst,def)=>{def.pattern??(def.pattern=ksuid),$ZodStringFormat.init(inst,def)}),$ZodISODateTime=$constructor("$ZodISODateTime",(inst,def)=>{def.pattern??(def.pattern=datetime(def)),$ZodStringFormat.init(inst,def)}),$ZodISODate=$constructor("$ZodISODate",(inst,def)=>{def.pattern??(def.pattern=date),$ZodStringFormat.init(inst,def)}),$ZodISOTime=$constructor("$ZodISOTime",(inst,def)=>{def.pattern??(def.pattern=time(def)),$ZodStringFormat.init(inst,def)}),$ZodISODuration=$constructor("$ZodISODuration",(inst,def)=>{def.pattern??(def.pattern=duration),$ZodStringFormat.init(inst,def)}),$ZodIPv4=$constructor("$ZodIPv4",(inst,def)=>{def.pattern??(def.pattern=ipv4),$ZodStringFormat.init(inst,def),inst._zod.bag.format="ipv4"}),$ZodIPv6=$constructor("$ZodIPv6",(inst,def)=>{def.pattern??(def.pattern=ipv6),$ZodStringFormat.init(inst,def),inst._zod.bag.format="ipv6",inst._zod.check=payload=>{try{new URL(`http://[${payload.value}]`)}catch{payload.issues.push({code:"invalid_format",format:"ipv6",input:payload.value,inst,continue:!def.abort})}}}),$ZodCIDRv4=$constructor("$ZodCIDRv4",(inst,def)=>{def.pattern??(def.pattern=cidrv4),$ZodStringFormat.init(inst,def)}),$ZodCIDRv6=$constructor("$ZodCIDRv6",(inst,def)=>{def.pattern??(def.pattern=cidrv6),$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{let parts=payload.value.split("/");try{if(parts.length!==2)throw new Error;let[address,prefix]=parts;if(!prefix)throw new Error;let prefixNum=Number(prefix);if(`${prefixNum}`!==prefix)throw new Error;if(prefixNum<0||prefixNum>128)throw new Error;new URL(`http://[${address}]`)}catch{payload.issues.push({code:"invalid_format",format:"cidrv6",input:payload.value,inst,continue:!def.abort})}}});$ZodBase64=$constructor("$ZodBase64",(inst,def)=>{def.pattern??(def.pattern=base64),$ZodStringFormat.init(inst,def),inst._zod.bag.contentEncoding="base64",inst._zod.check=payload=>{isValidBase64(payload.value)||payload.issues.push({code:"invalid_format",format:"base64",input:payload.value,inst,continue:!def.abort})}});$ZodBase64URL=$constructor("$ZodBase64URL",(inst,def)=>{def.pattern??(def.pattern=base64url),$ZodStringFormat.init(inst,def),inst._zod.bag.contentEncoding="base64url",inst._zod.check=payload=>{isValidBase64URL(payload.value)||payload.issues.push({code:"invalid_format",format:"base64url",input:payload.value,inst,continue:!def.abort})}}),$ZodE164=$constructor("$ZodE164",(inst,def)=>{def.pattern??(def.pattern=e164),$ZodStringFormat.init(inst,def)});$ZodJWT=$constructor("$ZodJWT",(inst,def)=>{$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{isValidJWT(payload.value,def.alg)||payload.issues.push({code:"invalid_format",format:"jwt",input:payload.value,inst,continue:!def.abort})}}),$ZodNumber=$constructor("$ZodNumber",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=inst._zod.bag.pattern??number,inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=Number(payload.value)}catch{}let input=payload.value;if(typeof input=="number"&&!Number.isNaN(input)&&Number.isFinite(input))return payload;let received=typeof input=="number"?Number.isNaN(input)?"NaN":Number.isFinite(input)?void 0:"Infinity":void 0;return payload.issues.push({expected:"number",code:"invalid_type",input,inst,...received?{received}:{}}),payload}}),$ZodNumberFormat=$constructor("$ZodNumberFormat",(inst,def)=>{$ZodCheckNumberFormat.init(inst,def),$ZodNumber.init(inst,def)}),$ZodBoolean=$constructor("$ZodBoolean",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=boolean,inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=!!payload.value}catch{}let input=payload.value;return typeof input=="boolean"||payload.issues.push({expected:"boolean",code:"invalid_type",input,inst}),payload}}),$ZodBigInt=$constructor("$ZodBigInt",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=bigint,inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=BigInt(payload.value)}catch{}return typeof payload.value=="bigint"||payload.issues.push({expected:"bigint",code:"invalid_type",input:payload.value,inst}),payload}}),$ZodNull=$constructor("$ZodNull",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=_null,inst._zod.values=new Set([null]),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;return input===null||payload.issues.push({expected:"null",code:"invalid_type",input,inst}),payload}}),$ZodAny=$constructor("$ZodAny",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=payload=>payload}),$ZodUnknown=$constructor("$ZodUnknown",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=payload=>payload}),$ZodNever=$constructor("$ZodNever",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>(payload.issues.push({expected:"never",code:"invalid_type",input:payload.value,inst}),payload)}),$ZodDate=$constructor("$ZodDate",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=new Date(payload.value)}catch{}let input=payload.value,isDate=input instanceof Date;return isDate&&!Number.isNaN(input.getTime())||payload.issues.push({expected:"date",code:"invalid_type",input,...isDate?{received:"Invalid Date"}:{},inst}),payload}});$ZodArray=$constructor("$ZodArray",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!Array.isArray(input))return payload.issues.push({expected:"array",code:"invalid_type",input,inst}),payload;payload.value=Array(input.length);let proms=[];for(let i=0;i<input.length;i++){let item=input[i],result=def.element._zod.run({value:item,issues:[]},ctx);result instanceof Promise?proms.push(result.then(result2=>handleArrayResult(result2,payload,i))):handleArrayResult(result,payload,i)}return proms.length?Promise.all(proms).then(()=>payload):payload}});$ZodObject=$constructor("$ZodObject",(inst,def)=>{if($ZodType.init(inst,def),!Object.getOwnPropertyDescriptor(def,"shape")?.get){let sh=def.shape;Object.defineProperty(def,"shape",{get:()=>{let newSh={...sh};return Object.defineProperty(def,"shape",{value:newSh}),newSh}})}let _normalized=cached(()=>normalizeDef(def));defineLazy(inst._zod,"propValues",()=>{let shape=def.shape,propValues={};for(let key in shape){let field=shape[key]._zod;if(field.values){propValues[key]??(propValues[key]=new Set);for(let v of field.values)propValues[key].add(v)}}return propValues});let isObject2=isObject,catchall=def.catchall,value;inst._zod.parse=(payload,ctx)=>{value??(value=_normalized.value);let input=payload.value;if(!isObject2(input))return payload.issues.push({expected:"object",code:"invalid_type",input,inst}),payload;payload.value={};let proms=[],shape=value.shape;for(let key of value.keys){let el=shape[key],isOptionalIn=el._zod.optin==="optional",isOptionalOut=el._zod.optout==="optional",r=el._zod.run({value:input[key],issues:[]},ctx);r instanceof Promise?proms.push(r.then(r2=>handlePropertyResult(r2,payload,key,input,isOptionalIn,isOptionalOut))):handlePropertyResult(r,payload,key,input,isOptionalIn,isOptionalOut)}return catchall?handleCatchall(proms,input,payload,ctx,_normalized.value,inst):proms.length?Promise.all(proms).then(()=>payload):payload}}),$ZodObjectJIT=$constructor("$ZodObjectJIT",(inst,def)=>{$ZodObject.init(inst,def);let superParse=inst._zod.parse,_normalized=cached(()=>normalizeDef(def)),generateFastpass=shape=>{let doc=new Doc(["shape","payload","ctx"]),normalized=_normalized.value,parseStr=key=>{let k=esc(key);return`shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`};doc.write("const input = payload.value;");let ids=Object.create(null),counter=0;for(let key of normalized.keys)ids[key]=`key_${counter++}`;doc.write("const newResult = {};");for(let key of normalized.keys){let id=ids[key],k=esc(key),schema2=shape[key],isOptionalIn=schema2?._zod?.optin==="optional",isOptionalOut=schema2?._zod?.optout==="optional";doc.write(`const ${id} = ${parseStr(key)};`),isOptionalIn&&isOptionalOut?doc.write(`
|
|
4
4
|
if (${id}.issues.length) {
|
|
@@ -96,7 +96,7 @@ data:
|
|
|
96
96
|
`;return eventId&&(eventData+=`id: ${eventId}
|
|
97
97
|
`),eventData+=`data: ${JSON.stringify(message)}
|
|
98
98
|
|
|
99
|
-
`,controller.enqueue(encoder.encode(eventData)),!0}catch(error3){return this.onerror?.(error3),!1}}handleUnsupportedRequest(){return this.onerror?.(new Error("Method not allowed.")),Response.json({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null},{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(req,options){try{let acceptHeader=req.headers.get("accept");if(!acceptHeader?.includes("application/json")||!acceptHeader.includes("text/event-stream"))return this.onerror?.(new Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");if(!isJsonContentType(req.headers.get("content-type")))return this.onerror?.(new Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let request=req,rawMessage;if(options?.parsedBody===void 0)try{rawMessage=await req.json()}catch(error3){return this.onerror?.(error3),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}else rawMessage=options.parsedBody;let messages;try{messages=Array.isArray(rawMessage)?rawMessage.map(msg=>JSONRPCMessageSchema.parse(msg)):[JSONRPCMessageSchema.parse(rawMessage)]}catch(error3){return this.onerror?.(error3),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let isInitializationRequest=messages.some(element=>isInitializeRequest(element));if(isInitializationRequest){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(new Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(messages.length>1)return this.onerror?.(new Error("Invalid Request: Only one initialization request is allowed")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!isInitializationRequest){let sessionError=this.validateSession(req);if(sessionError)return sessionError;let protocolError=this.validateProtocolVersion(req);if(protocolError)return protocolError}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");if(!messages.some(element=>isJSONRPCRequest(element))){for(let message of messages)this.onmessage?.(message,{authInfo:options?.authInfo,request});return new Response(null,{status:202})}let streamId=crypto.randomUUID(),initRequest=messages.find(m=>isInitializeRequest(m)),clientProtocolVersion=initRequest?initRequest.params.protocolVersion:req.headers.get("mcp-protocol-version")??DEFAULT_NEGOTIATED_PROTOCOL_VERSION;if(this._enableJsonResponse)return new Promise(resolve=>{this._streamMapping.set(streamId,{resolveJson:resolve,cleanup:()=>{this._streamMapping.delete(streamId)}});for(let message of messages)isJSONRPCRequest(message)&&this._requestToStreamMapping.set(message.id,streamId);for(let message of messages)this.onmessage?.(message,{authInfo:options?.authInfo,request})});let encoder=new TextEncoder,streamController,keepAliveTimer,readable=new ReadableStream({start:controller=>{streamController=controller},cancel:()=>{keepAliveTimer!==void 0&&clearInterval(keepAliveTimer),this._streamMapping.get(streamId)?.controller===streamController&&this._streamMapping.delete(streamId)}}),headers={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};this.sessionId!==void 0&&(headers["mcp-session-id"]=this.sessionId);for(let message of messages)isJSONRPCRequest(message)&&(this._streamMapping.set(streamId,{controller:streamController,encoder,cleanup:()=>{keepAliveTimer!==void 0&&clearInterval(keepAliveTimer),this._streamMapping.delete(streamId);try{streamController.close()}catch{}}}),this._requestToStreamMapping.set(message.id,streamId));await this.writePrimingEvent(streamController,encoder,streamId,clientProtocolVersion);for(let message of messages){let closeSSEStream,closeStandaloneSSEStream;isJSONRPCRequest(message)&&this._eventStore&&this.supportsEmptySSEData(clientProtocolVersion)&&(closeSSEStream=()=>{this.closeSSEStream(message.id)},closeStandaloneSSEStream=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(message,{authInfo:options?.authInfo,request,closeSSEStream,closeStandaloneSSEStream})}return this._streamMapping.get(streamId)?.controller===streamController&&(keepAliveTimer=this.startKeepAlive(streamController,encoder)),new Response(readable,{status:200,headers})}catch(error3){return this.onerror?.(error3),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(error3)})}}async handleDeleteRequest(req){let sessionError=this.validateSession(req);if(sessionError)return sessionError;let protocolError=this.validateProtocolVersion(req);if(protocolError)return protocolError;try{return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),new Response(null,{status:200})}finally{await this.close()}}validateSession(req){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(new Error("Bad Request: Server not initialized")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let sessionId=req.headers.get("mcp-session-id");if(!sessionId)return this.onerror?.(new Error("Bad Request: Mcp-Session-Id header is required")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required");if(sessionId!==this.sessionId)return this.onerror?.(new Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found")}validateProtocolVersion(req){let protocolVersion=req.headers.get("mcp-protocol-version");if(protocolVersion!==null&&!this._supportedProtocolVersions.includes(protocolVersion)){let error3=`Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${this._supportedProtocolVersions.join(", ")})`;return this.onerror?.(new Error(error3)),this.createJsonErrorResponse(400,-32e3,error3)}}async close(){if(!this._closed){this._closed=!0;for(let{cleanup}of this._streamMapping.values())cleanup();this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}}closeSSEStream(requestId){let streamId=this._requestToStreamMapping.get(requestId);if(!streamId)return;let stream=this._streamMapping.get(streamId);stream&&stream.cleanup()}closeStandaloneSSEStream(){let stream=this._streamMapping.get(this._standaloneSseStreamId);stream&&stream.cleanup()}async send(message,options){let requestId=options?.relatedRequestId;if((isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message))&&(requestId=message.id),requestId===void 0){if(isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message))throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let eventId;this._eventStore&&(eventId=await this._eventStore.storeEvent(this._standaloneSseStreamId,message));let standaloneSse=this._streamMapping.get(this._standaloneSseStreamId);if(standaloneSse===void 0)return;standaloneSse.controller&&standaloneSse.encoder&&(eventId===void 0||!standaloneSse.replayedEventIds?.has(eventId))&&this.writeSSEEvent(standaloneSse.controller,standaloneSse.encoder,message,eventId);return}let streamId=this._requestToStreamMapping.get(requestId);if(!streamId)throw new Error(`No connection established for request ID: ${String(requestId)}`);let stream=this._streamMapping.get(streamId);if(!this._enableJsonResponse){let eventId;this._eventStore&&(eventId=await this._eventStore.storeEvent(streamId,message),stream=this._streamMapping.get(streamId)),stream?.controller&&stream?.encoder&&(eventId===void 0||!stream.replayedEventIds?.has(eventId))&&this.writeSSEEvent(stream.controller,stream.encoder,message,eventId)}if(isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message)){this._requestResponseMap.set(requestId,message);let relatedIds=[...this._requestToStreamMapping.entries()].filter(([_,sid])=>sid===streamId).map(([id])=>id);if(relatedIds.every(id=>this._requestResponseMap.has(id))){if(!stream){if(this._enableJsonResponse)throw new Error(`No connection established for request ID: ${String(requestId)}`);if(!this._eventStore){this.onerror?.(new Error(`Response for request ID ${String(requestId)} is undeliverable: per-request stream is disconnected and no eventStore is configured`));for(let id of relatedIds)this._requestResponseMap.delete(id),this._requestToStreamMapping.delete(id);return}for(let id of relatedIds)this._requestResponseMap.delete(id),this._requestToStreamMapping.delete(id);return}if(this._enableJsonResponse&&stream.resolveJson){let headers={"Content-Type":"application/json"};this.sessionId!==void 0&&(headers["mcp-session-id"]=this.sessionId);let responses=relatedIds.map(id=>this._requestResponseMap.get(id));responses.length===1?stream.resolveJson(Response.json(responses[0],{status:200,headers})):stream.resolveJson(Response.json(responses,{status:200,headers})),stream.cleanup()}else stream.cleanup();for(let id of relatedIds)this._requestResponseMap.delete(id),this._requestToStreamMapping.delete(id)}}}};ALLOWED_METHODS="GET, HEAD, OPTIONS";PREFIX="v1."}});function stripTrailingSlashes(value){return value.replace(/\/+$/,"")}function readEnv(name){if(typeof process>"u")return;let value=process.env[name];return value!==void 0&&value!==""?value:void 0}function parseForwardedHeader(header){for(let part of header.split(",")){let params=new Map;for(let token of part.split(";")){let[key,...rest]=token.trim().split("=");key===void 0||rest.length===0||params.set(key.toLowerCase(),rest.join("=").replace(/^"|"$/g,""))}let proto=params.get("proto"),host=params.get("host");if(proto!==void 0&&host!==void 0)return`${proto}://${host}`}}function resolveRequestOriginFromHeaders(request){let forwarded=request.headers.get("forwarded");if(forwarded!==null){let fromForwarded=parseForwardedHeader(forwarded);if(fromForwarded!==void 0)return fromForwarded}let proto=request.headers.get("x-forwarded-proto"),host=request.headers.get("x-forwarded-host");if(proto!==null&&host!==null){let firstHost=host.split(",")[0]?.trim(),firstProto=proto.split(",")[0]?.trim();if(firstHost!==void 0&&firstProto!==void 0&&firstHost!=="")return`${firstProto}://${firstHost}`}return new URL(request.url).origin}function resolveServerOrigin(request){let mcpUrl=readEnv("MCP_URL");if(mcpUrl!==void 0)try{return new URL(mcpUrl).origin}catch{}return resolveRequestOriginFromHeaders(request)}function originFromAssetsBase(assetsBase){try{return new URL(assetsBase).origin}catch{return assetsBase}}function normalizeAssetsBaseUrl(value){return stripTrailingSlashes(value)}function resolveAssetsBase(request){let assetsUrl=readEnv("MCP_ASSETS_URL");if(assetsUrl!==void 0)try{return normalizeAssetsBaseUrl(new URL(assetsUrl).href.replace(/\/$/,""))}catch{}return resolveServerOrigin(request)}function hasExplicitAssetsBase(){let assetsUrl=readEnv("MCP_ASSETS_URL");if(assetsUrl===void 0)return!1;try{return new URL(assetsUrl),!0}catch{return!1}}var init_origin=__esm({"src/views/origin.ts"(){"use strict"}});var public_route_exports={};__export(public_route_exports,{publicContentType:()=>publicContentType,resolvePublicFilePath:()=>resolvePublicFilePath,servePublicFile:()=>servePublicFile});function publicContentType(filename){let extension=filename.slice(filename.lastIndexOf(".")).toLowerCase();return PUBLIC_CONTENT_TYPES[extension]??"application/octet-stream"}async function resolvePublicFilePath(publicRoot,subpath){let{stat}=await import("fs/promises"),{resolve,sep}=await import("path");if(subpath===""||subpath.includes("\\")||subpath.split("/").some(segment=>segment===".."))return null;let clean2=subpath.replace(/^\/+/,"");if(clean2===""||clean2.endsWith("/"))return null;let root=resolve(publicRoot),abs=resolve(root,clean2);if(abs!==root&&!abs.startsWith(root+sep))return null;try{if(!(await stat(abs)).isFile())return null}catch{return null}return abs}async function servePublicFile(diskPath,options={}){let{readFile}=await import("fs/promises"),contentType=publicContentType(diskPath),body=options.head===!0?null:new Uint8Array(await readFile(diskPath));return new Response(body,{status:200,headers:{"Content-Type":contentType,"Cache-Control":"public, max-age=0, must-revalidate",...options.deferCors!==!0&&{"Access-Control-Allow-Origin":"*"}}})}var PUBLIC_CONTENT_TYPES,init_public_route=__esm({"src/views/public-route.ts"(){"use strict";PUBLIC_CONTENT_TYPES={".css":"text/css",".gif":"image/gif",".html":"text/html",".ico":"image/x-icon",".jpeg":"image/jpeg",".jpg":"image/jpeg",".js":"application/javascript",".json":"application/json",".map":"application/json",".png":"image/png",".svg":"image/svg+xml",".txt":"text/plain",".webp":"image/webp",".woff":"font/woff",".woff2":"font/woff2"}}});function getRequestBag(request){let bag=requestBags.get(request);return bag===void 0&&(bag={},requestBags.set(request,bag)),bag}function composeFetch(terminal,...middlewares){return async request=>{let index=0,dispatch=async()=>{if(index<middlewares.length){let middleware=middlewares[index];return index+=1,middleware(request,dispatch)}return terminal(request)};return dispatch()}}function pathnameOf(request){return new URL(request.url).pathname}function matchesPath(request,path){return pathnameOf(request)===path}function matchesPathPrefix(request,prefix){let pathname=pathnameOf(request);return pathname===prefix||pathname.startsWith(`${prefix}/`)}function pathUnderBase(basePath,childPath){let child=childPath.replace(/^\/+/,"");return basePath==="/"?`/${child}`:`${basePath}/${child}`}function isHtmlNavigationRequest(request){if(request.method!=="GET"&&request.method!=="HEAD")return!1;let accept=request.headers.get("accept");return accept===null?!1:accept.split(",").some(range=>{let[mediaType,...parameters]=range.split(";");return mediaType?.trim().toLowerCase()!=="text/html"?!1:!parameters.some(parameter=>{let[name,value]=parameter.trim().toLowerCase().split("=");return name==="q"&&Number(value)===0})})}function jsonBodyMiddleware(){return async(request,next)=>{let bag=getRequestBag(request);if(bag.parsedBody!==void 0||!(request.headers.get("content-type")??"").includes("application/json"))return next();try{bag.parsedBody=await request.clone().json()}catch{return new Response("Invalid JSON",{status:400})}return next()}}function hostValidationMiddleware(hosts){return async(request,next)=>hostHeaderValidationResponse(request,hosts)??next()}function originValidationMiddleware(origins,skipSafeMethods=!0){return async(request,next)=>skipSafeMethods&&(request.method==="GET"||request.method==="HEAD")?next():originValidationResponse(request,origins)??next()}var requestBags,init_fetch_app=__esm({"src/fetch-app.ts"(){"use strict";init_dist();requestBags=new WeakMap}});function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function unionScopes(baseline,extra){return[...new Set([...baseline,...extra])]}function resolveSecuritySchemes(name,declared,options){let fail=detail=>{throw new TypeError(`Tool "${name}": ${detail}`)};if(declared===void 0)return[{type:"oauth2",scopes:[...options.baselineScopes]}];(!Array.isArray(declared)||declared.length===0)&&fail("securitySchemes must be a non-empty array; omit it to require sign-in with the provider's requiredScopes");let noAuth=!1,oauth2Scopes;for(let scheme of declared){isRecord2(scheme)||fail(SCHEME_SHAPE);let{type}=scheme,allowed=type==="oauth2"?["type","scopes"]:["type"];for(let key of Object.keys(scheme))allowed.includes(key)||fail(`unknown security scheme field ${JSON.stringify(key)}; ${SCHEME_SHAPE}`);if(type==="noauth")noAuth&&fail("declares more than one noauth scheme"),noAuth=!0;else if(type==="oauth2"){oauth2Scopes!==void 0&&fail("declares more than one oauth2 scheme; a sign-in challenge can only ask for one scope set");let{scopes}=scheme;Array.isArray(scopes)||fail("oauth2 scopes must be an array of scope strings");for(let scope of scopes)(typeof scope!="string"||!SCOPE_TOKEN.test(scope))&&fail(`invalid oauth2 scope ${JSON.stringify(scope)}; each scope must be one non-empty token without whitespace, ", or \\`);oauth2Scopes=scopes}else fail(`unsupported security scheme type ${JSON.stringify(type)}; use "noauth" or "oauth2"`)}noAuth&&!options.mixedAuth&&fail(options.hasOAuth?"noauth requires mixedAuth: true on the server. Without it, every request needs a token, so signed-out callers could never use it":"noauth requires an OAuth provider with mixedAuth: true. A server without OAuth serves every tool signed out, so remove securitySchemes"),oauth2Scopes!==void 0&&!options.hasOAuth&&fail("oauth2 requires an OAuth provider to verify tokens"),oauth2Scopes!==void 0&&oauth2Scopes.length===0&&options.baselineScopes.length===0&&fail("oauth2 scopes are empty and the OAuth provider has no requiredScopes. ChatGPT ignores an oauth2 scheme without scopes and would never offer sign-in; list at least one scope");let resolved=[];return noAuth&&resolved.push({type:"noauth"}),oauth2Scopes!==void 0&&resolved.push({type:"oauth2",scopes:unionScopes(options.baselineScopes,oauth2Scopes)}),resolved}function requiresSignIn(schemes){return!schemes.some(scheme=>scheme.type==="noauth")}function schemeScopes(schemes){for(let scheme of schemes)if(scheme.type==="oauth2")return scheme.scopes;return[]}function handWrittenSecuritySchemesWarning(name,definition,options){let handWritten=definition._meta?.[SECURITY_SCHEMES_META_KEY];if(handWritten!==void 0){if(definition.securitySchemes!==void 0)return JSON.stringify(handWritten)===JSON.stringify(definition.securitySchemes)?void 0:`[mcp-use] Tool "${name}": _meta.securitySchemes is replaced by the top-level securitySchemes. Remove the _meta entry.`;if(options.mixedAuth)return`[mcp-use] Tool "${name}": _meta.securitySchemes is advertised but not enforced, so the tool requires sign-in. Move it to the top-level securitySchemes field.`}}var SECURITY_SCHEMES_META_KEY,SCHEME_SHAPE,SCOPE_TOKEN,init_policy=__esm({"src/oauth/policy.ts"(){"use strict";SECURITY_SCHEMES_META_KEY="securitySchemes",SCHEME_SHAPE='each security scheme must be { type: "noauth" } or { type: "oauth2", scopes: string[] }',SCOPE_TOKEN=/^[\x21\x23-\x5B\x5D-\x7E]+$/}});var mcp_proxy_exports={};__export(mcp_proxy_exports,{isProxyConnection:()=>isProxyConnection,mountProxyConnection:()=>mountProxyConnection,mountProxyServers:()=>mountProxyServers,proxyClientInstallError:()=>proxyClientInstallError});function passthroughJsonSchema(schema2){return{"~standard":{version:1,vendor:"mcp-use-proxy",validate(value){return{value}},jsonSchema:{input:()=>schema2,output:()=>schema2}}}}function promptArgsToJsonSchema(args){let properties=Object.create(null),required2=[];for(let arg of args??[])properties[arg.name]={type:"string",...arg.description!==void 0&&{description:arg.description}},arg.required===!0&&required2.push(arg.name);return{type:"object",properties,...required2.length>0&&{required:required2}}}function prefixedName(namespace,name){return`${namespace}_${name}`}function proxiedResourceUri(namespace,uri){return`mcp-use-proxy:///${encodeURIComponent(namespace)}/${encodeURIComponent(uri)}`}function isConnection(value){if(value===null||typeof value!="object")return!1;let candidate=value;return typeof candidate.listTools=="function"&&typeof candidate.callTool=="function"&&typeof candidate.readResource=="function"&&typeof candidate.listPrompts=="function"&&typeof candidate.getPrompt=="function"}function isClientPackageMissing(error3){if(!(error3 instanceof Error))return!1;let code=error3.code;return(code==="ERR_MODULE_NOT_FOUND"||code==="MODULE_NOT_FOUND")&&error3.message.includes("@mcp-use/client")}function proxyDiagnostic(message,error3){if(error3===void 0){console.error(`[mcp-use] ${message}`);return}let detail=error3 instanceof Error?error3.message:String(error3);console.error(`[mcp-use] ${message}: ${detail}`)}function proxyClientInstallError(error3){return isClientPackageMissing(error3)?new Error(PROXY_CLIENT_INSTALL_HINT,{cause:error3}):void 0}async function loadProxyClient(importer=()=>import("@mcp-use/client")){try{return await importer()}catch(error3){let installError=proxyClientInstallError(error3);throw installError!==void 0?installError:error3}}function supports(connection,capability){return connection.supports?.(capability)!==!1}async function introspect(namespace,connection){let tools=[];if(supports(connection,"tools"))try{tools=await connection.listTools()}catch(error3){proxyDiagnostic(`Failed to introspect tools from upstream MCP server "${namespace}"`,error3)}let resources=[];if(supports(connection,"resources"))try{connection.listAllResources!==void 0?resources=(await connection.listAllResources()).resources:connection.listResources!==void 0&&(resources=(await connection.listResources()).resources)}catch(error3){proxyDiagnostic(`Failed to introspect resources from upstream MCP server "${namespace}"`,error3)}let prompts=[];if(supports(connection,"prompts"))try{prompts=(await connection.listPrompts()).prompts}catch(error3){proxyDiagnostic(`Failed to introspect prompts from upstream MCP server "${namespace}"`,error3)}return{namespace,connection,tools,resources,prompts}}function mountPlan(host,plan){host.trackNamespace?.({tools:plan.tools.length,resources:plan.resources.length,prompts:plan.prompts.length});for(let tool of plan.tools){let name=prefixedName(plan.namespace,tool.name);if(host.hasTool(name)){proxyDiagnostic(`Skipping proxied tool "${name}" from upstream "${plan.namespace}" because that name is already registered`);continue}let definition={name,...tool.title!==void 0&&{title:tool.title},...tool.description!==void 0&&{description:tool.description},...tool.annotations!==void 0&&{annotations:tool.annotations},...tool.inputSchema!==void 0&&{inputSchema:passthroughJsonSchema(tool.inputSchema)},...tool.outputSchema!==void 0&&{outputSchema:passthroughJsonSchema(tool.outputSchema)}},upstreamName=tool.name,callback=async(params,ctx)=>{let progressForwarding=Promise.resolve();try{return await plan.connection.callTool(upstreamName,params,{signal:ctx.signal,onprogress:progress=>{progressForwarding=progressForwarding.then(async()=>{try{await ctx.reportProgress(progress.progress,progress.total,progress.message)}catch(error3){proxyDiagnostic(`Failed to forward progress for proxied tool "${definition.name}"`,error3)}})}})}finally{await progressForwarding}};host.registerTool(definition,callback)}for(let resource2 of plan.resources){let name=prefixedName(plan.namespace,resource2.name);if(host.hasResource(name)){proxyDiagnostic(`Skipping proxied resource "${name}" from upstream "${plan.namespace}" because that name is already registered`);continue}let upstreamUri=resource2.uri;host.registerResource({name,uri:proxiedResourceUri(plan.namespace,upstreamUri),...resource2.title!==void 0&&{title:resource2.title},...resource2.description!==void 0&&{description:resource2.description},...resource2.mimeType!==void 0&&{mimeType:resource2.mimeType},...resource2.annotations!==void 0&&{annotations:resource2.annotations},...resource2._meta!==void 0&&{_meta:resource2._meta}},async(_uri,ctx)=>plan.connection.readResource(upstreamUri,{signal:ctx.signal}))}for(let prompt of plan.prompts){let name=prefixedName(plan.namespace,prompt.name);if(host.hasPrompt(name)){proxyDiagnostic(`Skipping proxied prompt "${name}" from upstream "${plan.namespace}" because that name is already registered`);continue}let upstreamName=prompt.name;host.registerPrompt({name,...prompt.title!==void 0&&{title:prompt.title},...prompt.description!==void 0&&{description:prompt.description},schema:passthroughJsonSchema(promptArgsToJsonSchema(prompt.arguments))},async(params,ctx)=>plan.connection.getPrompt(upstreamName,params,{signal:ctx.signal}))}}async function mountProxyConnection(host,connection){if(host.isStarted())throw new Error("Cannot call proxy() after the server has started: register upstream servers before listen()/server.fetch.");let namespace=connection.info.server?.name;if(!namespace)throw new Error("Cannot proxy an anonymous MCP connection directly: the upstream server did not report a name for namespace generation.");let plan=await introspect(namespace,connection);mountPlan(host,plan)}function toClientConfig(config2){return{url:config2.url,...config2.headers!==void 0&&{headers:config2.headers},...config2.authToken!==void 0&&{authToken:config2.authToken},...config2.timeout!==void 0&&{timeout:config2.timeout},...config2.fetch!==void 0&&{fetch:config2.fetch},...config2.protocolNegotiation!==void 0&&{protocolNegotiation:config2.protocolNegotiation},oauth:!1}}async function mountProxyServers(host,servers){if(host.isStarted())throw new Error("Cannot call proxy() after the server has started: register upstream servers before listen()/server.fetch.");let{MCPClient}=await loadProxyClient(),clientServers=Object.fromEntries(Object.entries(servers).map(([name,config2])=>[name,toClientConfig(config2)])),owner=new MCPClient({mcpServers:clientServers});try{let plans=[];for(let namespace of Object.keys(clientServers)){let connection;try{connection=await owner.connect(namespace)}catch(error3){proxyDiagnostic(`Failed to connect to upstream MCP server "${namespace}"`,error3);continue}plans.push(await introspect(namespace,connection))}for(let plan of plans)mountPlan(host,plan);host.trackOwner(owner)}catch(error3){throw await owner.close().catch(()=>{}),error3}}function isProxyConnection(value){return isConnection(value)}var PROXY_CLIENT_INSTALL_HINT,init_mcp_proxy=__esm({"src/mcp-proxy.ts"(){"use strict";PROXY_CLIENT_INSTALL_HINT=["[mcp-use] server.proxy() requires the optional @mcp-use/client package.","Install it in your project:",""," npm install @mcp-use/client"].join(`
|
|
99
|
+
`,controller.enqueue(encoder.encode(eventData)),!0}catch(error3){return this.onerror?.(error3),!1}}handleUnsupportedRequest(){return this.onerror?.(new Error("Method not allowed.")),Response.json({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null},{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(req,options){try{let acceptHeader=req.headers.get("accept");if(!acceptHeader?.includes("application/json")||!acceptHeader.includes("text/event-stream"))return this.onerror?.(new Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");if(!isJsonContentType(req.headers.get("content-type")))return this.onerror?.(new Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let request=req,rawMessage;if(options?.parsedBody===void 0)try{rawMessage=await req.json()}catch(error3){return this.onerror?.(error3),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}else rawMessage=options.parsedBody;let messages;try{messages=Array.isArray(rawMessage)?rawMessage.map(msg=>JSONRPCMessageSchema.parse(msg)):[JSONRPCMessageSchema.parse(rawMessage)]}catch(error3){return this.onerror?.(error3),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let isInitializationRequest=messages.some(element=>isInitializeRequest(element));if(isInitializationRequest){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(new Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(messages.length>1)return this.onerror?.(new Error("Invalid Request: Only one initialization request is allowed")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!isInitializationRequest){let sessionError=this.validateSession(req);if(sessionError)return sessionError;let protocolError=this.validateProtocolVersion(req);if(protocolError)return protocolError}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");if(!messages.some(element=>isJSONRPCRequest(element))){for(let message of messages)this.onmessage?.(message,{authInfo:options?.authInfo,request});return new Response(null,{status:202})}let streamId=crypto.randomUUID(),initRequest=messages.find(m=>isInitializeRequest(m)),clientProtocolVersion=initRequest?initRequest.params.protocolVersion:req.headers.get("mcp-protocol-version")??DEFAULT_NEGOTIATED_PROTOCOL_VERSION;if(this._enableJsonResponse)return new Promise(resolve=>{this._streamMapping.set(streamId,{resolveJson:resolve,cleanup:()=>{this._streamMapping.delete(streamId)}});for(let message of messages)isJSONRPCRequest(message)&&this._requestToStreamMapping.set(message.id,streamId);for(let message of messages)this.onmessage?.(message,{authInfo:options?.authInfo,request})});let encoder=new TextEncoder,streamController,keepAliveTimer,readable=new ReadableStream({start:controller=>{streamController=controller},cancel:()=>{keepAliveTimer!==void 0&&clearInterval(keepAliveTimer),this._streamMapping.get(streamId)?.controller===streamController&&this._streamMapping.delete(streamId)}}),headers={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};this.sessionId!==void 0&&(headers["mcp-session-id"]=this.sessionId);for(let message of messages)isJSONRPCRequest(message)&&(this._streamMapping.set(streamId,{controller:streamController,encoder,cleanup:()=>{keepAliveTimer!==void 0&&clearInterval(keepAliveTimer),this._streamMapping.delete(streamId);try{streamController.close()}catch{}}}),this._requestToStreamMapping.set(message.id,streamId));await this.writePrimingEvent(streamController,encoder,streamId,clientProtocolVersion);for(let message of messages){let closeSSEStream,closeStandaloneSSEStream;isJSONRPCRequest(message)&&this._eventStore&&this.supportsEmptySSEData(clientProtocolVersion)&&(closeSSEStream=()=>{this.closeSSEStream(message.id)},closeStandaloneSSEStream=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(message,{authInfo:options?.authInfo,request,closeSSEStream,closeStandaloneSSEStream})}return this._streamMapping.get(streamId)?.controller===streamController&&(keepAliveTimer=this.startKeepAlive(streamController,encoder)),new Response(readable,{status:200,headers})}catch(error3){return this.onerror?.(error3),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(error3)})}}async handleDeleteRequest(req){let sessionError=this.validateSession(req);if(sessionError)return sessionError;let protocolError=this.validateProtocolVersion(req);if(protocolError)return protocolError;try{return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),new Response(null,{status:200})}finally{await this.close()}}validateSession(req){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(new Error("Bad Request: Server not initialized")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let sessionId=req.headers.get("mcp-session-id");if(!sessionId)return this.onerror?.(new Error("Bad Request: Mcp-Session-Id header is required")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required");if(sessionId!==this.sessionId)return this.onerror?.(new Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found")}validateProtocolVersion(req){let protocolVersion=req.headers.get("mcp-protocol-version");if(protocolVersion!==null&&!this._supportedProtocolVersions.includes(protocolVersion)){let error3=`Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${this._supportedProtocolVersions.join(", ")})`;return this.onerror?.(new Error(error3)),this.createJsonErrorResponse(400,-32e3,error3)}}async close(){if(!this._closed){this._closed=!0;for(let{cleanup}of this._streamMapping.values())cleanup();this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}}closeSSEStream(requestId){let streamId=this._requestToStreamMapping.get(requestId);if(!streamId)return;let stream=this._streamMapping.get(streamId);stream&&stream.cleanup()}closeStandaloneSSEStream(){let stream=this._streamMapping.get(this._standaloneSseStreamId);stream&&stream.cleanup()}async send(message,options){let requestId=options?.relatedRequestId;if((isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message))&&(requestId=message.id),requestId===void 0){if(isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message))throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let eventId;this._eventStore&&(eventId=await this._eventStore.storeEvent(this._standaloneSseStreamId,message));let standaloneSse=this._streamMapping.get(this._standaloneSseStreamId);if(standaloneSse===void 0)return;standaloneSse.controller&&standaloneSse.encoder&&(eventId===void 0||!standaloneSse.replayedEventIds?.has(eventId))&&this.writeSSEEvent(standaloneSse.controller,standaloneSse.encoder,message,eventId);return}let streamId=this._requestToStreamMapping.get(requestId);if(!streamId)throw new Error(`No connection established for request ID: ${String(requestId)}`);let stream=this._streamMapping.get(streamId);if(!this._enableJsonResponse){let eventId;this._eventStore&&(eventId=await this._eventStore.storeEvent(streamId,message),stream=this._streamMapping.get(streamId)),stream?.controller&&stream?.encoder&&(eventId===void 0||!stream.replayedEventIds?.has(eventId))&&this.writeSSEEvent(stream.controller,stream.encoder,message,eventId)}if(isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message)){this._requestResponseMap.set(requestId,message);let relatedIds=[...this._requestToStreamMapping.entries()].filter(([_,sid])=>sid===streamId).map(([id])=>id);if(relatedIds.every(id=>this._requestResponseMap.has(id))){if(!stream){if(this._enableJsonResponse)throw new Error(`No connection established for request ID: ${String(requestId)}`);if(!this._eventStore){this.onerror?.(new Error(`Response for request ID ${String(requestId)} is undeliverable: per-request stream is disconnected and no eventStore is configured`));for(let id of relatedIds)this._requestResponseMap.delete(id),this._requestToStreamMapping.delete(id);return}for(let id of relatedIds)this._requestResponseMap.delete(id),this._requestToStreamMapping.delete(id);return}if(this._enableJsonResponse&&stream.resolveJson){let headers={"Content-Type":"application/json"};this.sessionId!==void 0&&(headers["mcp-session-id"]=this.sessionId);let responses=relatedIds.map(id=>this._requestResponseMap.get(id));responses.length===1?stream.resolveJson(Response.json(responses[0],{status:200,headers})):stream.resolveJson(Response.json(responses,{status:200,headers})),stream.cleanup()}else stream.cleanup();for(let id of relatedIds)this._requestResponseMap.delete(id),this._requestToStreamMapping.delete(id)}}}};ALLOWED_METHODS="GET, HEAD, OPTIONS";PREFIX="v1."}});function stripTrailingSlashes(value){return value.replace(/\/+$/,"")}function readEnv(name){if(typeof process>"u")return;let value=process.env[name];return value!==void 0&&value!==""?value:void 0}function parseForwardedHeader(header){for(let part of header.split(",")){let params=new Map;for(let token of part.split(";")){let[key,...rest]=token.trim().split("=");key===void 0||rest.length===0||params.set(key.toLowerCase(),rest.join("=").replace(/^"|"$/g,""))}let proto=params.get("proto"),host=params.get("host");if(proto!==void 0&&host!==void 0)return`${proto}://${host}`}}function resolveRequestOriginFromHeaders(request){let forwarded=request.headers.get("forwarded");if(forwarded!==null){let fromForwarded=parseForwardedHeader(forwarded);if(fromForwarded!==void 0)return fromForwarded}let proto=request.headers.get("x-forwarded-proto"),host=request.headers.get("x-forwarded-host");if(proto!==null&&host!==null){let firstHost=host.split(",")[0]?.trim(),firstProto=proto.split(",")[0]?.trim();if(firstHost!==void 0&&firstProto!==void 0&&firstHost!=="")return`${firstProto}://${firstHost}`}return new URL(request.url).origin}function resolveServerOrigin(request){let mcpUrl=readEnv("MCP_URL");if(mcpUrl!==void 0)try{return new URL(mcpUrl).origin}catch{}return resolveRequestOriginFromHeaders(request)}function originFromAssetsBase(assetsBase){try{return new URL(assetsBase).origin}catch{return assetsBase}}function normalizeAssetsBaseUrl(value){return stripTrailingSlashes(value)}function resolveAssetsBase(request){let assetsUrl=readEnv("MCP_ASSETS_URL");if(assetsUrl!==void 0)try{return normalizeAssetsBaseUrl(new URL(assetsUrl).href.replace(/\/$/,""))}catch{}return resolveServerOrigin(request)}function hasExplicitAssetsBase(){let assetsUrl=readEnv("MCP_ASSETS_URL");if(assetsUrl===void 0)return!1;try{return new URL(assetsUrl),!0}catch{return!1}}var init_origin=__esm({"src/views/origin.ts"(){"use strict"}});var public_route_exports={};__export(public_route_exports,{publicContentType:()=>publicContentType,resolvePublicFilePath:()=>resolvePublicFilePath,servePublicFile:()=>servePublicFile});function publicContentType(filename){let extension=filename.slice(filename.lastIndexOf(".")).toLowerCase();return PUBLIC_CONTENT_TYPES[extension]??"application/octet-stream"}async function resolvePublicFilePath(publicRoot,subpath){let{stat}=await import("fs/promises"),{resolve,sep}=await import("path");if(subpath===""||subpath.includes("\\")||subpath.split("/").some(segment=>segment===".."))return null;let clean2=subpath.replace(/^\/+/,"");if(clean2===""||clean2.endsWith("/"))return null;let root=resolve(publicRoot),abs=resolve(root,clean2);if(abs!==root&&!abs.startsWith(root+sep))return null;try{if(!(await stat(abs)).isFile())return null}catch{return null}return abs}async function servePublicFile(diskPath,options={}){let{readFile}=await import("fs/promises"),contentType=publicContentType(diskPath),body=options.head===!0?null:new Uint8Array(await readFile(diskPath));return new Response(body,{status:200,headers:{"Content-Type":contentType,"Cache-Control":"public, max-age=0, must-revalidate",...options.deferCors!==!0&&{"Access-Control-Allow-Origin":"*"}}})}var PUBLIC_CONTENT_TYPES,init_public_route=__esm({"src/views/public-route.ts"(){"use strict";PUBLIC_CONTENT_TYPES={".css":"text/css",".gif":"image/gif",".html":"text/html",".ico":"image/x-icon",".jpeg":"image/jpeg",".jpg":"image/jpeg",".js":"application/javascript",".json":"application/json",".map":"application/json",".png":"image/png",".svg":"image/svg+xml",".txt":"text/plain",".webp":"image/webp",".woff":"font/woff",".woff2":"font/woff2"}}});function getRequestBag(request){let bag=requestBags.get(request);return bag===void 0&&(bag={},requestBags.set(request,bag)),bag}function composeFetch(terminal,...middlewares){return async request=>{let index=0,dispatch=async()=>{if(index<middlewares.length){let middleware=middlewares[index];return index+=1,middleware(request,dispatch)}return terminal(request)};return dispatch()}}function pathnameOf(request){return new URL(request.url).pathname}function matchesPath(request,path){return pathnameOf(request)===path}function matchesPathPrefix(request,prefix){let pathname=pathnameOf(request);return pathname===prefix||pathname.startsWith(`${prefix}/`)}function pathUnderBase(basePath,childPath){let child=childPath.replace(/^\/+/,"");return basePath==="/"?`/${child}`:`${basePath}/${child}`}function isHtmlNavigationRequest(request){if(request.method!=="GET"&&request.method!=="HEAD")return!1;let accept=request.headers.get("accept");return accept===null?!1:accept.split(",").some(range=>{let[mediaType,...parameters]=range.split(";");return mediaType?.trim().toLowerCase()!=="text/html"?!1:!parameters.some(parameter=>{let[name,value]=parameter.trim().toLowerCase().split("=");return name==="q"&&Number(value)===0})})}function jsonBodyMiddleware(){return async(request,next)=>{let bag=getRequestBag(request);if(bag.parsedBody!==void 0||!(request.headers.get("content-type")??"").includes("application/json"))return next();try{bag.parsedBody=await request.clone().json()}catch{return new Response("Invalid JSON",{status:400})}return next()}}function hostValidationMiddleware(hosts){return async(request,next)=>hostHeaderValidationResponse(request,hosts)??next()}function originValidationMiddleware(origins,skipSafeMethods=!0){return async(request,next)=>skipSafeMethods&&(request.method==="GET"||request.method==="HEAD")?next():originValidationResponse(request,origins)??next()}var requestBags,init_fetch_app=__esm({"src/fetch-app.ts"(){"use strict";init_dist();requestBags=new WeakMap}});function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function unionScopes(baseline,extra){return[...new Set([...baseline,...extra])]}function resolveSecuritySchemes(name,declared,options){let fail=detail=>{throw new TypeError(`Tool "${name}": ${detail}`)};if(declared===void 0)return[{type:"oauth2",scopes:[...options.baselineScopes]}];(!Array.isArray(declared)||declared.length===0)&&fail("securitySchemes must be a non-empty array; omit it to require sign-in with the provider's requiredScopes");let noAuth=!1,oauth2Scopes;for(let scheme of declared){isRecord2(scheme)||fail(SCHEME_SHAPE);let{type}=scheme,allowed=type==="oauth2"?["type","scopes"]:["type"];for(let key of Object.keys(scheme))allowed.includes(key)||fail(`unknown security scheme field ${JSON.stringify(key)}; ${SCHEME_SHAPE}`);if(type==="noauth")noAuth&&fail("declares more than one noauth scheme"),noAuth=!0;else if(type==="oauth2"){oauth2Scopes!==void 0&&fail("declares more than one oauth2 scheme; a sign-in challenge can only ask for one scope set");let{scopes}=scheme;Array.isArray(scopes)||fail("oauth2 scopes must be an array of scope strings");for(let scope of scopes)(typeof scope!="string"||!SCOPE_TOKEN.test(scope))&&fail(`invalid oauth2 scope ${JSON.stringify(scope)}; each scope must be one non-empty token without whitespace, ", or \\`);oauth2Scopes=scopes}else fail(`unsupported security scheme type ${JSON.stringify(type)}; use "noauth" or "oauth2"`)}noAuth&&!options.mixedAuth&&fail(options.hasOAuth?"noauth requires mixedAuth: true on the server. Without it, every request needs a token, so signed-out callers could never use it":"noauth requires an OAuth provider with mixedAuth: true. A server without OAuth serves every tool signed out, so remove securitySchemes"),oauth2Scopes!==void 0&&!options.hasOAuth&&fail("oauth2 requires an OAuth provider to verify tokens"),oauth2Scopes!==void 0&&oauth2Scopes.length===0&&options.baselineScopes.length===0&&fail("oauth2 scopes are empty and the OAuth provider has no requiredScopes. ChatGPT ignores an oauth2 scheme without scopes and would never offer sign-in; list at least one scope");let resolved=[];return noAuth&&resolved.push({type:"noauth"}),oauth2Scopes!==void 0&&resolved.push({type:"oauth2",scopes:unionScopes(options.baselineScopes,oauth2Scopes)}),resolved}function requiresSignIn(schemes){return!schemes.some(scheme=>scheme.type==="noauth")}function schemeScopes(schemes){for(let scheme of schemes)if(scheme.type==="oauth2")return scheme.scopes;return[]}function handWrittenSecuritySchemesWarning(name,definition,options){let handWritten=definition._meta?.[SECURITY_SCHEMES_META_KEY];if(handWritten!==void 0){if(definition.securitySchemes!==void 0)return JSON.stringify(handWritten)===JSON.stringify(definition.securitySchemes)?void 0:`[mcp-use] Tool "${name}": _meta.securitySchemes is replaced by the top-level securitySchemes. Remove the _meta entry.`;if(options.mixedAuth)return`[mcp-use] Tool "${name}": _meta.securitySchemes is advertised but not enforced, so the tool requires sign-in. Move it to the top-level securitySchemes field.`}}var SECURITY_SCHEMES_META_KEY,SCHEME_SHAPE,SCOPE_TOKEN,init_policy=__esm({"src/oauth/policy.ts"(){"use strict";SECURITY_SCHEMES_META_KEY="securitySchemes",SCHEME_SHAPE='each security scheme must be { type: "noauth" } or { type: "oauth2", scopes: string[] }',SCOPE_TOKEN=/^[\x21\x23-\x5B\x5D-\x7E]+$/}});var mcp_proxy_exports={};__export(mcp_proxy_exports,{isProxyConnection:()=>isProxyConnection,mountProxyConnection:()=>mountProxyConnection,mountProxyServers:()=>mountProxyServers,proxyClientInstallError:()=>proxyClientInstallError});function passthroughJsonSchema(schema2){return{"~standard":{version:1,vendor:"mcp-use-proxy",validate(value){return{value}},jsonSchema:{input:()=>schema2,output:()=>schema2}}}}function promptArgsToJsonSchema(args){let properties=Object.create(null),required2=[];for(let arg of args??[])properties[arg.name]={type:"string",...arg.description!==void 0&&{description:arg.description}},arg.required===!0&&required2.push(arg.name);return{type:"object",properties,...required2.length>0&&{required:required2}}}function prefixedName(namespace,name){return`${namespace}_${name}`}function proxiedResourceUri(namespace,uri){return`mcp-use-proxy:///${encodeURIComponent(namespace)}/${encodeURIComponent(uri)}`}function isConnection(value){if(value===null||typeof value!="object")return!1;let candidate=value;return typeof candidate.listTools=="function"&&typeof candidate.callTool=="function"&&typeof candidate.readResource=="function"&&typeof candidate.listPrompts=="function"&&typeof candidate.getPrompt=="function"}function isClientPackageMissing(error3){if(!(error3 instanceof Error))return!1;let code=error3.code;return(code==="ERR_MODULE_NOT_FOUND"||code==="MODULE_NOT_FOUND")&&error3.message.includes("@mcp-use/client")}function proxyDiagnostic(message,error3){if(error3===void 0){console.error(`[mcp-use] ${message}`);return}let detail=error3 instanceof Error?error3.message:String(error3);console.error(`[mcp-use] ${message}: ${detail}`)}function proxyClientInstallError(error3){return isClientPackageMissing(error3)?new Error(PROXY_CLIENT_INSTALL_HINT,{cause:error3}):void 0}async function loadProxyClient(importer=()=>import("@mcp-use/client")){try{return await importer()}catch(error3){let installError=proxyClientInstallError(error3);throw installError!==void 0?installError:error3}}function supports(connection,capability){return connection.supports?.(capability)!==!1}async function introspect(namespace,connection){let tools=[];if(supports(connection,"tools"))try{tools=await connection.listTools()}catch(error3){proxyDiagnostic(`Failed to introspect tools from upstream MCP server "${namespace}"`,error3)}let resources=[];if(supports(connection,"resources"))try{connection.listAllResources!==void 0?resources=(await connection.listAllResources()).resources:connection.listResources!==void 0&&(resources=(await connection.listResources()).resources)}catch(error3){proxyDiagnostic(`Failed to introspect resources from upstream MCP server "${namespace}"`,error3)}let prompts=[];if(supports(connection,"prompts"))try{prompts=(await connection.listPrompts()).prompts}catch(error3){proxyDiagnostic(`Failed to introspect prompts from upstream MCP server "${namespace}"`,error3)}return{namespace,connection,tools,resources,prompts}}function mountPlan(host,plan){host.trackNamespace?.({tools:plan.tools.length,resources:plan.resources.length,prompts:plan.prompts.length});for(let tool of plan.tools){let name=prefixedName(plan.namespace,tool.name);if(host.hasTool(name)){proxyDiagnostic(`Skipping proxied tool "${name}" from upstream "${plan.namespace}" because that name is already registered`);continue}let definition={name,...tool.title!==void 0&&{title:tool.title},...tool.icons!==void 0&&{icons:tool.icons},...tool.description!==void 0&&{description:tool.description},...tool.annotations!==void 0&&{annotations:tool.annotations},...tool.inputSchema!==void 0&&{inputSchema:passthroughJsonSchema(tool.inputSchema)},...tool.outputSchema!==void 0&&{outputSchema:passthroughJsonSchema(tool.outputSchema)}},upstreamName=tool.name,callback=async(params,ctx)=>{let progressForwarding=Promise.resolve();try{return await plan.connection.callTool(upstreamName,params,{signal:ctx.signal,onprogress:progress=>{progressForwarding=progressForwarding.then(async()=>{try{await ctx.reportProgress(progress.progress,progress.total,progress.message)}catch(error3){proxyDiagnostic(`Failed to forward progress for proxied tool "${definition.name}"`,error3)}})}})}finally{await progressForwarding}};host.registerTool(definition,callback)}for(let resource2 of plan.resources){let name=prefixedName(plan.namespace,resource2.name);if(host.hasResource(name)){proxyDiagnostic(`Skipping proxied resource "${name}" from upstream "${plan.namespace}" because that name is already registered`);continue}let upstreamUri=resource2.uri;host.registerResource({name,uri:proxiedResourceUri(plan.namespace,upstreamUri),...resource2.title!==void 0&&{title:resource2.title},...resource2.description!==void 0&&{description:resource2.description},...resource2.mimeType!==void 0&&{mimeType:resource2.mimeType},...resource2.annotations!==void 0&&{annotations:resource2.annotations},...resource2._meta!==void 0&&{_meta:resource2._meta}},async(_uri,ctx)=>plan.connection.readResource(upstreamUri,{signal:ctx.signal}))}for(let prompt of plan.prompts){let name=prefixedName(plan.namespace,prompt.name);if(host.hasPrompt(name)){proxyDiagnostic(`Skipping proxied prompt "${name}" from upstream "${plan.namespace}" because that name is already registered`);continue}let upstreamName=prompt.name;host.registerPrompt({name,...prompt.title!==void 0&&{title:prompt.title},...prompt.description!==void 0&&{description:prompt.description},schema:passthroughJsonSchema(promptArgsToJsonSchema(prompt.arguments))},async(params,ctx)=>plan.connection.getPrompt(upstreamName,params,{signal:ctx.signal}))}}async function mountProxyConnection(host,connection){if(host.isStarted())throw new Error("Cannot call proxy() after the server has started: register upstream servers before listen()/server.fetch.");let namespace=connection.info.server?.name;if(!namespace)throw new Error("Cannot proxy an anonymous MCP connection directly: the upstream server did not report a name for namespace generation.");let plan=await introspect(namespace,connection);mountPlan(host,plan)}function toClientConfig(config2){return{url:config2.url,...config2.headers!==void 0&&{headers:config2.headers},...config2.authToken!==void 0&&{authToken:config2.authToken},...config2.timeout!==void 0&&{timeout:config2.timeout},...config2.fetch!==void 0&&{fetch:config2.fetch},...config2.protocolNegotiation!==void 0&&{protocolNegotiation:config2.protocolNegotiation},oauth:!1}}async function mountProxyServers(host,servers){if(host.isStarted())throw new Error("Cannot call proxy() after the server has started: register upstream servers before listen()/server.fetch.");let{MCPClient}=await loadProxyClient(),clientServers=Object.fromEntries(Object.entries(servers).map(([name,config2])=>[name,toClientConfig(config2)])),owner=new MCPClient({mcpServers:clientServers});try{let plans=[];for(let namespace of Object.keys(clientServers)){let connection;try{connection=await owner.connect(namespace)}catch(error3){proxyDiagnostic(`Failed to connect to upstream MCP server "${namespace}"`,error3);continue}plans.push(await introspect(namespace,connection))}for(let plan of plans)mountPlan(host,plan);host.trackOwner(owner)}catch(error3){throw await owner.close().catch(()=>{}),error3}}function isProxyConnection(value){return isConnection(value)}var PROXY_CLIENT_INSTALL_HINT,init_mcp_proxy=__esm({"src/mcp-proxy.ts"(){"use strict";PROXY_CLIENT_INSTALL_HINT=["[mcp-use] server.proxy() requires the optional @mcp-use/client package.","Install it in your project:",""," npm install @mcp-use/client"].join(`
|
|
100
100
|
`)}});function defaultDescription(reason,missingScopes){return reason==="missing_token"?"Authentication is required for this request.":reason==="invalid_token"?"The access token is invalid or expired.":missingScopes.length>0?`Additional permissions are required: ${missingScopes.join(" ")}.`:"Additional permissions are required."}function createAuthChallenge(options){return{reason:options.reason,description:options.description??defaultDescription(options.reason,options.missingScopes??[]),scopes:[...options.scopes],resourceMetadataUrl:options.resourceMetadataUrl}}function authChallengeHttpResponse(challenge){return bearerAuthChallengeResponse(new OAuthError(challenge.reason==="insufficient_scope"?OAuthErrorCode.InsufficientScope:OAuthErrorCode.InvalidToken,challenge.description),{requiredScopes:[...challenge.scopes],resourceMetadataUrl:challenge.resourceMetadataUrl})}function authChallengeToolResult(challenge){let header=authChallengeHttpResponse(challenge).headers.get("WWW-Authenticate");return{content:[{type:"text",text:challenge.description}],isError:!0,_meta:{[WWW_AUTHENTICATE_META_KEY]:header===null?[]:[header]}}}function prefersToolResultChallenge(request){return TOOL_RESULT_CHALLENGE_USER_AGENT.test(request.headers.get("user-agent")??"")}var WWW_AUTHENTICATE_META_KEY,TOOL_RESULT_CHALLENGE_USER_AGENT,init_challenge=__esm({"src/oauth/challenge.ts"(){"use strict";init_dist();WWW_AUTHENTICATE_META_KEY="mcp/www_authenticate",TOOL_RESULT_CHALLENGE_USER_AGENT=/chatgpt|openai/i}});var gate_exports={};__export(gate_exports,{createOAuthGate:()=>createOAuthGate});function isRecord3(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function parseMessage(body){if(!isRecord3(body)||typeof body.method!="string")return;let id=body.id,params=body.params;return{method:body.method,id:typeof id=="string"||typeof id=="number"?id:void 0,params:isRecord3(params)?params:void 0}}function isModernEnvelope(message){let meta2=message.params?._meta;return isRecord3(meta2)&&meta2[PROTOCOL_VERSION_META_KEY]!==void 0}function normalizeResourceUri(uri){try{return new URL(uri).toString()}catch{return uri}}function stringParam(params,key){let value=params?.[key];return typeof value=="string"?value:void 0}function isSignInMethod(message){if(SIGNED_OUT_METHODS.has(message.method)||message.id===void 0&&message.method.startsWith("notifications/"))return!1;if(message.method==="subscriptions/listen"){let filter=message.params?.notifications,uris=isRecord3(filter)?filter.resourceSubscriptions:void 0;return uris!==void 0&&(!Array.isArray(uris)||uris.length>0)}return!0}function createOAuthGate(options){let{verifier,resourceMetadataUrl,baselineScopes,mixedAuth,toolSchemes}=options,openResources=new Set([...options.openResourceUris].map(normalizeResourceUri)),open={required:!1,scopes:[]},signIn=(extra=[])=>({required:!0,scopes:[...new Set([...baselineScopes,...extra])]}),requirementFor=message=>{if(message===void 0)return mixedAuth?open:signIn();if(message.method==="tools/call"){let name=stringParam(message.params,"name"),schemes=name===void 0?void 0:toolSchemes(name);return schemes===void 0?signIn():mixedAuth&&!requiresSignIn(schemes)?open:signIn(schemeScopes(schemes))}if(!mixedAuth)return signIn();if(message.method==="resources/read"){let uri=stringParam(message.params,"uri");if(uri!==void 0&&openResources.has(normalizeResourceUri(uri)))return open}return isSignInMethod(message)?signIn():open},requirementForBody=body=>{if(!Array.isArray(body))return requirementFor(parseMessage(body));let scopes=new Set,required2=!1;for(let element of body){let requirement=requirementFor(parseMessage(element));if(requirement.required){required2=!0;for(let scope of requirement.scopes)scopes.add(scope)}}return{required:required2,scopes:[...scopes]}},refuse=(request,message,reason,requirement,details={})=>{let challenge=createAuthChallenge({reason,scopes:requirement.required?requirement.scopes:baselineScopes,resourceMetadataUrl,...details});return message===void 0||message.method!=="tools/call"||message.id===void 0||!prefersToolResultChallenge(request)?authChallengeHttpResponse(challenge):Response.json({jsonrpc:"2.0",id:message.id,result:{...isModernEnvelope(message)&&{resultType:"complete"},...authChallengeToolResult(challenge)}})};return async(request,next)=>{let bag=getRequestBag(request),body=bag.parsedBody;if(body===void 0&&request.method.toUpperCase()==="POST")try{body=await request.clone().json()}catch{}let message=Array.isArray(body)?void 0:parseMessage(body),requirement=requirementForBody(body),authInfo,authorization=request.headers.get("authorization");if(authorization!==null||requirement.required)try{authInfo=await verifyBearerToken(authorization,{verifier})}catch(error3){return!(error3 instanceof OAuthError)||error3.code!==OAuthErrorCode.InvalidToken&&error3.code!==OAuthErrorCode.InsufficientScope?bearerAuthChallengeResponse(error3,{resourceMetadataUrl}):error3.code===OAuthErrorCode.InsufficientScope?refuse(request,message,"insufficient_scope",requirement,{description:error3.message}):authorization===null?refuse(request,message,"missing_token",requirement):refuse(request,message,"invalid_token",requirement,{description:error3.message})}if(requirement.required&&authInfo!==void 0){let granted=new Set(authInfo.scopes),missingScopes=requirement.scopes.filter(scope=>!granted.has(scope));if(missingScopes.length>0)return refuse(request,message,"insufficient_scope",requirement,{missingScopes})}return authInfo!==void 0&&(bag.authInfo=authInfo),next()}}var SIGNED_OUT_METHODS,init_gate=__esm({"src/oauth/gate.ts"(){"use strict";init_dist();init_fetch_app();init_challenge();init_policy();SIGNED_OUT_METHODS=new Set(["initialize","server/discover","ping","tools/list","resources/list","resources/templates/list","prompts/list","logging/setLevel"])}});function escapeHtml2(text2){return text2.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function serializeScriptJson(value){return JSON.stringify(value).replace(/</g,"\\u003c").replace(/>/g,"\\u003e")}function sanitizeServerName(name){return name.replace(/[^a-zA-Z0-9-_]/g,"_").toLowerCase()}function generateCursorDeepLink(url2,name){let configJson=JSON.stringify({url:url2}),base64Config=typeof Buffer<"u"?Buffer.from(configJson).toString("base64"):btoa(configJson),sanitizedName=sanitizeServerName(name);return`cursor://anysphere.cursor-deeplink/mcp/install?config=${encodeURIComponent(base64Config)}&name=${encodeURIComponent(sanitizedName)}`}function generateVSCodeDeepLink(url2,name){let config2={url:url2,name:sanitizeServerName(name),type:"http"},configJson=JSON.stringify(config2);return`vscode:mcp/install?${encodeURIComponent(configJson)}`}function generateVSCodeInsidersDeepLink(url2,name){let config2={url:url2,name:sanitizeServerName(name),type:"http"},configJson=JSON.stringify(config2);return`vscode-insiders:mcp/install?${encodeURIComponent(configJson)}`}function generateClaudeCommand(url2,name){let sanitizedName=sanitizeServerName(name),quotedUrl=`'${url2.replace(/'/g,"'\\''")}'`;return`claude mcp add --transport http "${sanitizedName}" ${quotedUrl}`}function getManufactInspectorUrl(serverUrl){let params=new URLSearchParams({autoConnect:serverUrl,tab:"chat"});return`${MANUFACT_INSPECTOR_ORIGIN}/inspector?${params.toString()}`}function getPublicChatUrls(serverUrl){let origin=new URL(serverUrl).origin;return{chatUrl:new URL("/chat",origin).href,readyUrl:new URL("/chat/ready",origin).href}}function getMeshGradientScript(){return`(function(){
|
|
101
101
|
var c=document.getElementById('mesh-bg');
|
|
102
102
|
if(!c)return;
|
|
@@ -762,13 +762,13 @@ a:hover { text-decoration: underline; }
|
|
|
762
762
|
})();
|
|
763
763
|
</script>
|
|
764
764
|
</body>
|
|
765
|
-
</html>`}var MANUFACT_INSPECTOR_ORIGIN,LOGO_SVG_PATHS,LINE_INTERSECTION_PATH,init_landing=__esm({"src/landing.ts"(){"use strict";MANUFACT_INSPECTOR_ORIGIN="https://inspector.manufact.com";LOGO_SVG_PATHS={path1:"M105.933 0C164.437 0.000115889 211.865 47.607 211.865 106.333C211.865 131.828 210.494 158.401 221.068 181.6L228.976 198.947C243.585 230.997 269.266 256.7 301.304 271.336L316.156 278.121C340.143 289.079 367.695 287.335 394.067 287.335C452.572 287.335 500 334.942 500 393.668C500 452.394 452.572 500.001 394.067 500.001C335.563 500.001 288.135 452.394 288.135 393.668C288.135 368.974 289.241 343.275 278.992 320.807L270.587 302.38C255.949 270.289 230.214 244.565 198.118 229.939L180.164 221.758C157.282 211.331 131.078 212.666 105.933 212.666C47.4278 212.666 4.92992e-05 165.059 0 106.333C0 47.607 47.4278 0 105.933 0Z",circle:{cx:100.426,cy:399.575,r:100.426},path2:"M500 100.426C500 155.889 455.037 200.851 399.574 200.851C344.11 200.851 299.148 155.889 299.148 100.426C299.148 44.962 344.11 0 399.574 0C455.037 0 500 44.962 500 100.426Z"},LINE_INTERSECTION_PATH="M10.5 4C10.5 7.31371 7.81371 10 4.5 10H0.5V11H4.5C7.81371 11 10.5 13.6863 10.5 17V21H11.5V17C11.5 13.6863 14.1863 11 17.5 11H21.5V10H17.5C14.1863 10 11.5 7.31371 11.5 4V0H10.5V4Z"}});var landing_handler_exports={};__export(landing_handler_exports,{createLandingPageResponse:()=>createLandingPageResponse});function createLandingPageResponse(request,basePath,config2,branding,tools,prompts,resources){let origin=resolveServerOrigin(request),url2=new URL(basePath,`${origin}/`).href,html2=generateLandingPage({...config2,url:url2,...branding.favicon!==void 0&&{iconUrl:new URL("/favicon.ico",`${origin}/`).href,...branding.faviconMimeType!==void 0&&{iconType:branding.faviconMimeType}},tools:Array.from(tools,entry=>entry.definition),prompts:Array.from(prompts,entry=>entry.definition),resources:Array.from(resources,entry=>entry.definition)});return new Response(request.method==="HEAD"?null:html2,{status:200,headers:{"cache-control":"no-store","content-type":"text/html; charset=utf-8","x-content-type-options":"nosniff"}})}var init_landing_handler=__esm({"src/landing-handler.ts"(){"use strict";init_landing();init_origin()}});init_dist();import{createServer as createNodeHttpServer}from"node:http";var GET_MATCH_RESULT=Symbol();var bufferToFormData=(arrayBuffer,contentType)=>new Response(arrayBuffer,{headers:{"Content-Type":contentType.replace(/^[^;]+/,mediaType=>mediaType.toLowerCase())}}).formData();var MAX_NESTED_OBJECTS=1e4,isRawRequest=request=>"headers"in request,parseBody=async(request,options=Object.create(null))=>{let{all=!1,dot=!1}=options,mediaType=(isRawRequest(request)?request.headers:request.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return mediaType==="multipart/form-data"||mediaType==="application/x-www-form-urlencoded"?parseFormData(request,{all,dot}):{}};async function parseFormData(request,options){if(!isRawRequest(request)&&request.bodyCache.formData)return convertFormDataToBodyData(await request.bodyCache.formData,options);let headers=isRawRequest(request)?request.headers:request.raw.headers,arrayBuffer=await request.arrayBuffer(),formDataPromise=bufferToFormData(arrayBuffer,headers.get("Content-Type")||"");isRawRequest(request)||(request.bodyCache.formData=formDataPromise);let formData=await formDataPromise;return formData?convertFormDataToBodyData(formData,options):{}}function convertFormDataToBodyData(formData,options){let form=Object.create(null),nestingState={count:0};return formData.forEach((value,key)=>{options.all||key.endsWith("[]")?handleParsingAllValues(form,key,value):form[key]=value}),options.dot&&Object.entries(form).forEach(([key,value])=>{key.includes(".")&&(handleParsingNestedValues(form,key,value,nestingState),delete form[key])}),form}var handleParsingAllValues=(form,key,value)=>{form[key]!==void 0?Array.isArray(form[key])?form[key].push(value):form[key]=[form[key],value]:key.endsWith("[]")?form[key]=[value]:form[key]=value},handleParsingNestedValues=(form,key,value,state)=>{if(/(?:^|\.)__proto__\./.test(key))return;let nestedForm=form,keys=key.split(".",34);keys.length>33&&throwNestingLimitExceeded(),keys.forEach((key2,index)=>{index===keys.length-1?nestedForm[key2]=value:((!nestedForm[key2]||typeof nestedForm[key2]!="object"||Array.isArray(nestedForm[key2])||nestedForm[key2]instanceof File)&&(state.count++>=MAX_NESTED_OBJECTS&&throwNestingLimitExceeded(),nestedForm[key2]=Object.create(null)),nestedForm=nestedForm[key2])})},throwNestingLimitExceeded=()=>{throw new Error("Nesting limit exceeded")};var splitPath=path=>{let paths=path.split("/");return paths[0]===""&&paths.shift(),paths},splitRoutingPath=routePath=>{let{groups,path}=extractGroupsFromPath(routePath),paths=splitPath(path);return replaceGroupMarks(paths,groups)},extractGroupsFromPath=path=>{let groups=[];return path=path.replace(/\{[^}]+\}/g,(match2,index)=>{let mark=`@${index}`;return groups.push([mark,match2]),mark}),{groups,path}},replaceGroupMarks=(paths,groups)=>{for(let i=groups.length-1;i>=0;i--){let[mark]=groups[i];for(let j=paths.length-1;j>=0;j--)if(paths[j].includes(mark)){paths[j]=paths[j].replace(mark,groups[i][1]);break}}return paths},patternCache={},getPattern=(label,next)=>{if(label==="*")return"*";let match2=label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(match2){let cacheKey=`${label}#${next}`;return patternCache[cacheKey]||(match2[2]?patternCache[cacheKey]=next&&next[0]!==":"&&next[0]!=="*"?[cacheKey,match2[1],new RegExp(`^${match2[2]}(?=/${next})`)]:[label,match2[1],new RegExp(`^${match2[2]}$`)]:patternCache[cacheKey]=[label,match2[1],!0]),patternCache[cacheKey]}return null},tryDecode=(str,decoder)=>{try{return decoder(str)}catch{return str.replace(/(?:%[0-9A-Fa-f]{2})+/g,match2=>{try{return decoder(match2)}catch{return match2}})}},tryDecodeURI=str=>tryDecode(str,decodeURI),getPath=request=>{let url2=request.url,start=url2.indexOf("/",url2.indexOf(":")+4),i=start;for(;i<url2.length;i++){let charCode=url2.charCodeAt(i);if(charCode===37){let queryIndex=url2.indexOf("?",i),hashIndex=url2.indexOf("#",i),end=queryIndex===-1?hashIndex===-1?void 0:hashIndex:hashIndex===-1?queryIndex:Math.min(queryIndex,hashIndex),path=url2.slice(start,end);return tryDecodeURI(path.includes("%25")?path.replace(/%25/g,"%2525"):path)}else if(charCode===63||charCode===35)break}return url2.slice(start,i)};var getPathNoStrict=request=>{let result=getPath(request);return result.length>1&&result.at(-1)==="/"?result.slice(0,-1):result},mergePath=(base,sub,...rest)=>(rest.length&&(sub=mergePath(sub,...rest)),`${base?.[0]==="/"?"":"/"}${base}${sub==="/"?"":`${base?.at(-1)==="/"?"":"/"}${sub?.[0]==="/"?sub.slice(1):sub}`}`),checkOptionalParameter=path=>{if(path.charCodeAt(path.length-1)!==63||!path.includes(":"))return null;let segments=path.split("/"),results=[],basePath="";return segments.forEach(segment=>{if(segment!==""&&!/\:/.test(segment))basePath+="/"+segment;else if(/\:/.test(segment))if(segment.charCodeAt(segment.length-1)===63){results.length===0&&basePath===""?results.push("/"):results.push(basePath);let optionalSegment=segment.slice(0,-1);basePath+="/"+optionalSegment,results.push(basePath)}else basePath+="/"+segment}),results.filter((v,i,a)=>a.indexOf(v)===i)},tryDecodeURIComponent=str=>str.indexOf("%")!==-1?tryDecode(str,decodeURIComponent_):str,_decodeURI=value=>(value.indexOf("+")!==-1&&(value=value.replace(/\+/g," ")),tryDecodeURIComponent(value)),_getQueryParam=(url2,key,multiple)=>{let hashIndex=url2.indexOf("#",8);hashIndex!==-1&&(url2=url2.slice(0,hashIndex));let encoded;if(!multiple&&key&&key.indexOf("%")===-1&&key.indexOf("+")===-1){let keyIndex2=url2.indexOf("?",8);if(keyIndex2===-1)return;for(url2.startsWith(key,keyIndex2+1)||(keyIndex2=url2.indexOf(`&${key}`,keyIndex2+1));keyIndex2!==-1;){let trailingKeyCode=url2.charCodeAt(keyIndex2+key.length+1);if(trailingKeyCode===61){let valueIndex=keyIndex2+key.length+2,endIndex=url2.indexOf("&",valueIndex);return _decodeURI(url2.slice(valueIndex,endIndex===-1?void 0:endIndex))}else if(trailingKeyCode==38||isNaN(trailingKeyCode))return"";keyIndex2=url2.indexOf(`&${key}`,keyIndex2+1)}if(encoded=/[%+]/.test(url2),!encoded)return}let results=Object.create(null);encoded??=/[%+]/.test(url2);let keyIndex=url2.indexOf("?",8);for(;keyIndex!==-1;){let nextKeyIndex=url2.indexOf("&",keyIndex+1),valueIndex=url2.indexOf("=",keyIndex);valueIndex>nextKeyIndex&&nextKeyIndex!==-1&&(valueIndex=-1);let name=url2.slice(keyIndex+1,valueIndex===-1?nextKeyIndex===-1?void 0:nextKeyIndex:valueIndex);if(encoded&&(name=_decodeURI(name)),keyIndex=nextKeyIndex,name==="")continue;let value;valueIndex===-1?value="":(value=url2.slice(valueIndex+1,nextKeyIndex===-1?void 0:nextKeyIndex),encoded&&(value=_decodeURI(value))),multiple?(results[name]&&Array.isArray(results[name])||(results[name]=[]),results[name].push(value)):results[name]??=value}return key?results[key]:results},getQueryParam=_getQueryParam,getQueryParams=(url2,key)=>_getQueryParam(url2,key,!0),decodeURIComponent_=decodeURIComponent;var HonoRequest=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(request,path="/",matchResult=[[]]){this.raw=request,this.path=path,this.#matchResult=matchResult}param(key){return key?this.#getDecodedParam(key):this.#getAllDecodedParams()}#getDecodedParam(key){let paramKey=this.#matchResult[0][this.routeIndex]?.[1][key],param=this.#getParamValue(paramKey);return param&&tryDecodeURIComponent(param)}#getAllDecodedParams(){let decoded={},keys=Object.keys(this.#matchResult[0][this.routeIndex]?.[1]??{});for(let key of keys){let value=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);value!==void 0&&(decoded[key]=tryDecodeURIComponent(value))}return decoded}#getParamValue(paramKey){return this.#matchResult[1]?this.#matchResult[1][paramKey]:paramKey}query(key){return getQueryParam(this.url,key)}queries(key){return getQueryParams(this.url,key)}header(name){if(name)return this.raw.headers.get(name)??void 0;let headerData=Object.create(null);return this.raw.headers.forEach((value,key)=>{headerData[key]=value}),headerData}async parseBody(options){return parseBody(this,options)}#cachedBody=key=>{let{bodyCache,raw:raw2}=this,cachedBody=bodyCache[key];if(cachedBody)return cachedBody;for(let anyCachedKey in bodyCache)return bodyCache[anyCachedKey].then(body=>{anyCachedKey==="json"&&(body=JSON.stringify(body));let contentType=anyCachedKey==="formData"?void 0:raw2.headers.get("content-type");return new Response(body,{headers:contentType?{"Content-Type":contentType}:void 0})[key]()});return bodyCache[key]=raw2[key]()};json(){return this.#cachedBody("text").then(text2=>JSON.parse(text2))}text(){return this.#cachedBody("text")}arrayBuffer(){return this.#cachedBody("arrayBuffer")}bytes(){return this.#cachedBody("arrayBuffer").then(buffer=>new Uint8Array(buffer))}blob(){return this.#cachedBody("blob")}formData(){return this.#cachedBody("formData")}addValidatedData(target,data){(this.#validatedData??={})[target]=data}valid(target){return this.#validatedData?.[target]}get url(){return this.raw.url}get method(){return this.raw.method}get[GET_MATCH_RESULT](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,route]])=>route)}get routePath(){return this.#matchResult[0].map(([[,route]])=>route)[this.routeIndex].path}};var HtmlEscapedCallbackPhase={Stringify:1,BeforeStream:2,Stream:3},raw=(value,callbacks)=>{let escapedString=new String(value);return escapedString.isEscaped=!0,escapedString.callbacks=callbacks,escapedString};var resolveCallback=async(str,phase,preserveCallbacks,context,buffer)=>{typeof str=="object"&&!(str instanceof String)&&(str instanceof Promise||(str=str.toString()),str instanceof Promise&&(str=await str));let callbacks=str.callbacks;if(!callbacks?.length)return Promise.resolve(str);buffer?buffer[0]+=str:buffer=[str];let resStr=Promise.all(callbacks.map(c=>c({phase,buffer,context}))).then(res=>Promise.all(res.filter(Boolean).map(str2=>resolveCallback(str2,phase,!1,context,buffer))).then(()=>buffer[0]));return preserveCallbacks?raw(await resStr,callbacks):resStr};var TEXT_PLAIN="text/plain; charset=UTF-8",setDefaultContentType=(contentType,headers)=>({"Content-Type":contentType,...headers}),createResponseInstance=(body,init)=>new Response(body,init),Context=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(req,options){this.#rawRequest=req,options&&(this.#executionCtx=options.executionCtx,this.env=options.env,this.#notFoundHandler=options.notFoundHandler,this.#path=options.path,this.#matchResult=options.matchResult)}get req(){return this.#req??=new HonoRequest(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&"respondWith"in this.#executionCtx)return this.#executionCtx;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error("This context has no ExecutionContext")}get res(){return this.#res||=createResponseInstance(null,{headers:this.#preparedHeaders??=new Headers})}set res(_res){if(this.#res&&_res){_res=createResponseInstance(_res.body,_res);for(let[k,v]of this.#res.headers.entries())if(k!=="content-type")if(k==="set-cookie"){let cookies=this.#res.headers.getSetCookie();_res.headers.delete("set-cookie");for(let cookie of cookies)_res.headers.append("set-cookie",cookie)}else _res.headers.set(k,v)}this.#res=_res,this.finalized=!0}render=(...args)=>(this.#renderer??=content=>this.html(content),this.#renderer(...args));setLayout=layout=>this.#layout=layout;getLayout=()=>this.#layout;setRenderer=renderer=>{this.#renderer=renderer};header=(name,value,options)=>{this.finalized&&(this.#res=createResponseInstance(this.#res.body,this.#res));let headers=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;value===void 0?headers.delete(name):options?.append?headers.append(name,value):headers.set(name,value)};status=status=>{this.#status=status};set=(key,value)=>{this.#var??=new Map,this.#var.set(key,value)};get=key=>this.#var?this.#var.get(key):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(data,arg,headers){let responseHeaders=this.#res?new Headers(this.#res.headers):this.#preparedHeaders;if(typeof arg=="object"&&arg.headers){responseHeaders??=new Headers;for(let[key,value]of new Headers(arg.headers))key==="set-cookie"?responseHeaders.append(key,value):responseHeaders.set(key,value)}if(headers){if(!responseHeaders){let count=0;for(let k in headers)if(++count>1||typeof headers[k]!="string"){responseHeaders=new Headers;break}}if(responseHeaders)for(let k in headers){let v=headers[k];if(typeof v=="string")responseHeaders.set(k,v);else{responseHeaders.delete(k);for(let v2 of v)responseHeaders.append(k,v2)}}}let status=typeof arg=="number"?arg:arg?.status??this.#status;return createResponseInstance(data,{status,headers:responseHeaders??headers})}newResponse=(...args)=>this.#newResponse(...args);body=(data,arg,headers)=>this.#newResponse(data,arg,headers);text=(text2,arg,headers)=>!this.#preparedHeaders&&!this.#status&&!arg&&!headers&&!this.finalized?new Response(text2):this.#newResponse(text2,arg,setDefaultContentType(TEXT_PLAIN,headers));json=(object4,arg,headers)=>this.#newResponse(JSON.stringify(object4),arg,setDefaultContentType("application/json",headers));html=(html2,arg,headers)=>{let res=html3=>this.#newResponse(html3,arg,setDefaultContentType("text/html; charset=UTF-8",headers));return typeof html2=="object"?resolveCallback(html2,HtmlEscapedCallbackPhase.Stringify,!1,{}).then(res):res(html2)};redirect=(location,status)=>{let locationString=String(location);return this.header("Location",/[^\x00-\xFF]/.test(locationString)?encodeURI(locationString):locationString),this.newResponse(null,status??302)};notFound=()=>(this.#notFoundHandler??=()=>createResponseInstance(),this.#notFoundHandler(this))};var compose=(middleware,onError,onNotFound)=>(context,next)=>{let index=-1;return dispatch(0);async function dispatch(i){if(i<=index)throw new Error("next() called multiple times");index=i;let res,isError=!1,handler;if(middleware[i]?(handler=middleware[i][0][0],context.req.routeIndex=i):handler=i===middleware.length&&next||void 0,handler)try{res=await handler(context,()=>dispatch(i+1))}catch(err){if(err instanceof Error&&onError)context.error=err,res=await onError(err,context),isError=!0;else throw err}else context.finalized===!1&&onNotFound&&(res=await onNotFound(context));return res&&(context.finalized===!1||isError)&&(context.res=res),context}};var METHODS=["get","post","put","delete","options","patch","query"],MESSAGE_MATCHER_IS_ALREADY_BUILT="Can not add a route since the matcher is already built.",UnsupportedPathError=class extends Error{};var COMPOSED_HANDLER="__COMPOSED_HANDLER";var notFoundHandler=c=>c.text("404 Not Found",404),errorHandler=(err,c)=>{if("getResponse"in err){let res=err.getResponse();return c.newResponse(res.body,res)}return console.error(err),c.text("Internal Server Error",500)},Hono=class Hono2{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#path="/";routes=[];constructor(options={}){[...METHODS,"all"].forEach(method=>{this[method]=(args1,...args)=>{let methodName=method.toUpperCase();return typeof args1=="string"?this.#path=args1:this.#addRoute(methodName,this.#path,args1),args.forEach(handler=>{this.#addRoute(methodName,this.#path,handler)}),this}}),this.on=(method,path,...handlers)=>{for(let p of[path].flat()){this.#path=p;for(let m of[method].flat()){let methodName=m.toUpperCase();for(let handler of handlers)this.#addRoute(methodName,this.#path,handler)}}return this},this.use=(arg1,...handlers)=>(typeof arg1=="string"?this.#path=arg1:(this.#path="*",handlers.unshift(arg1)),handlers.forEach(handler=>{this.#addRoute("ALL",this.#path,handler)}),this);let{strict,...optionsWithoutStrict}=options;Object.assign(this,optionsWithoutStrict),this.getPath=strict??!0?options.getPath??getPath:getPathNoStrict}#clone(){let clone2=new Hono2({router:this.router,getPath:this.getPath});return clone2.errorHandler=this.errorHandler,clone2.#notFoundHandler=this.#notFoundHandler,clone2.routes=this.routes,clone2}#notFoundHandler=notFoundHandler;errorHandler=errorHandler;route(path,app){let subApp=this.basePath(path);return app.routes.map(r=>{let handler;app.errorHandler===errorHandler?handler=r.handler:(handler=async(c,next)=>(await compose([],app.errorHandler)(c,()=>r.handler(c,next))).res,handler[COMPOSED_HANDLER]=r.handler),subApp.#addRoute(r.method,r.path,handler,r.basePath)}),this}basePath(path){let subApp=this.#clone();return subApp._basePath=mergePath(this._basePath,path),subApp}onError=handler=>(this.errorHandler=handler,this);notFound=handler=>(this.#notFoundHandler=handler,this);mount(path,applicationHandler,options){let replaceRequest,optionHandler;options&&(typeof options=="function"?optionHandler=options:(optionHandler=options.optionHandler,options.replaceRequest===!1?replaceRequest=request=>request:replaceRequest=options.replaceRequest));let getOptions=optionHandler?c=>{let options2=optionHandler(c);return Array.isArray(options2)?options2:[options2]}:c=>{let executionContext;try{executionContext=c.executionCtx}catch{}return[c.env,executionContext]};replaceRequest||=(()=>{let mergedPath=mergePath(this._basePath,path),pathPrefixLength=mergedPath==="/"?0:mergedPath.length;return request=>{let url2=new URL(request.url);return url2.pathname=this.getPath(request).slice(pathPrefixLength)||"/",new Request(url2,request)}})();let handler=async(c,next)=>{let res=await applicationHandler(replaceRequest(c.req.raw),...getOptions(c));if(res)return res;await next()};return this.#addRoute("ALL",mergePath(path,"*"),handler),this}#addRoute(method,path,handler,baseRoutePath){path=mergePath(this._basePath,path);let r={basePath:baseRoutePath!==void 0?mergePath(this._basePath,baseRoutePath):this._basePath,path,method,handler};this.router.add(method,path,[handler,r]),this.routes.push(r)}#handleError(err,c){if(err instanceof Error)return this.errorHandler(err,c);throw err}#dispatch(request,executionCtx,env2,method){if(method==="HEAD")return(async()=>new Response(null,await this.#dispatch(request,executionCtx,env2,"GET")))();let path=this.getPath(request,{env:env2}),matchResult=this.router.match(method,path),c=new Context(request,{path,matchResult,env:env2,executionCtx,notFoundHandler:this.#notFoundHandler});if(matchResult[0].length===1){let res;try{res=matchResult[0][0][0][0](c,async()=>{c.res=await this.#notFoundHandler(c)})}catch(err){return this.#handleError(err,c)}return res instanceof Promise?res.then(resolved=>resolved||(c.finalized?c.res:this.#notFoundHandler(c))).catch(err=>this.#handleError(err,c)):res??this.#notFoundHandler(c)}let composed=compose(matchResult[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let context=await composed(c);if(!context.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return context.res}catch(err){return this.#handleError(err,c)}})()}fetch=(request,...rest)=>this.#dispatch(request,rest[1],rest[0],request.method);request=(input,requestInit,Env,executionCtx)=>input instanceof Request?this.fetch(requestInit?new Request(input,requestInit):input,Env,executionCtx):(input=input.toString(),this.fetch(new Request(/^https?:\/\//.test(input)?input:`http://localhost${mergePath("/",input)}`,requestInit),Env,executionCtx));fire=()=>{addEventListener("fetch",event=>{event.respondWith(this.#dispatch(event.request,event,void 0,event.request.method))})}};var createNullObject=()=>Object.create(null);var emptyParam=[];function match(method,path){let matchers=this.buildAllMatchers(),match2=((method2,path2)=>{let matcher=matchers[method2]||matchers.ALL,staticMatch=matcher[2][path2];if(staticMatch)return staticMatch;let match3=path2.match(matcher[0]);if(!match3)return[[],emptyParam];let index=match3.indexOf("",1);return[matcher[1][index],match3]});return this.match=match2,match2(method,path)}var LABEL_REG_EXP_STR="[^/]+";var TAIL_WILDCARD_REG_EXP_STR="(?:|/.*)",PATH_ERROR=Symbol(),regExpMetaChars=new Set(".\\+*[^]$()");function compareKey(a,b){return a.length===1?b.length===1?a<b?-1:1:-1:b.length===1?1:a===".*"||a==="(?:|/.*)"?b==="(?:|/.*)"?-1:1:b===".*"||b==="(?:|/.*)"?-1:a==="[^/]+"?1:b==="[^/]+"?-1:a.length===b.length?a<b?-1:1:b.length-a.length}var Node=class Node2{#index;#varIndex;#children=createNullObject();insert(tokens,index,paramMap,context,isStatic){let node=this;for(let i=0,len=tokens.length;i<len;i++){let token=tokens[i],pattern=token.length===1?token==="*"?i===len-1?["","",".*"]:["","",LABEL_REG_EXP_STR]:null:token==="/*"?["","",TAIL_WILDCARD_REG_EXP_STR]:token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),nextNode;if(pattern){let name=pattern[1],regexpStr=pattern[2]||"[^/]+";if(name&&pattern[2]&&(regexpStr===".*"||(regexpStr=regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(regexpStr))||regexpStr.length===1&®ExpMetaChars.has(regexpStr)))throw PATH_ERROR;if(nextNode=node.#children[regexpStr],!nextNode){if(regexpStr!==".*"&®expStr!=="(?:|/.*)"){for(let k in node.#children)if((regexpStr.length>1||k.length>1)&&k!==".*"&&k!=="(?:|/.*)")throw PATH_ERROR}nextNode=node.#children[regexpStr]=new Node2}name!==""&&(nextNode.#varIndex??=context.varIndex++,paramMap.push([name,nextNode.#varIndex]))}else if(nextNode=node.#children[token],!nextNode){for(let k in node.#children)if(k.length>1&&k!==".*"&&k!=="(?:|/.*)")throw PATH_ERROR;nextNode=node.#children[token]=new Node2}node=nextNode}if(node.#index!==void 0)throw PATH_ERROR;node.#index=isStatic?-1:index}buildRegExpStr(){let strList=Object.keys(this.#children).sort(compareKey).map(k=>{let c=this.#children[k],childStr=c.buildRegExpStr();return childStr===""?"":(typeof c.#varIndex=="number"?`(${k})@${c.#varIndex}`:regExpMetaChars.has(k)?`\\${k}`:k)+childStr}).filter(Boolean);return typeof this.#index=="number"&&this.#index!==-1&&strList.unshift(`#${this.#index}`),strList.length===0?"":strList.length===1?strList[0]:"(?:"+strList.join("|")+")"}};var Trie=class{#context={varIndex:0};#root=new Node;#index=0;paths=createNullObject();insert(path,isStatic){if(isStatic){this.#root.insert(path.split(""),0,[],this.#context,!0);return}let paramAssoc=[],groups=[],markedPath=path;for(let i=0;;){let replaced=!1;if(markedPath=markedPath.replace(/\{[^}]+\}/g,m=>{let mark=`@\\${i}`;return groups[i]=[mark,m],i++,replaced=!0,mark}),!replaced)break}let tokens=markedPath.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=groups.length-1;i>=0;i--){let[mark]=groups[i];for(let j=tokens.length-1;j>=0;j--)if(tokens[j].indexOf(mark)!==-1){tokens[j]=tokens[j].replace(mark,groups[i][1]);break}}this.#root.insert(tokens,this.#index,paramAssoc,this.#context,!1),this.paths[path]=[this.#index++,paramAssoc]}buildRegExp(){let regexp=this.#root.buildRegExpStr();if(regexp==="")return[/^$/,[],[]];let captureIndex=0,indexReplacementMap=[],paramReplacementMap=[];return regexp=regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g,(_,handlerIndex,paramIndex)=>handlerIndex!==void 0?(indexReplacementMap[++captureIndex]=Number(handlerIndex),"$()"):(paramIndex!==void 0&&(paramReplacementMap[Number(paramIndex)]=++captureIndex),"")),[new RegExp(`^${regexp}`),indexReplacementMap,paramReplacementMap]}};var wildcardRegExpCache=createNullObject();function buildWildcardRegExp(path){return wildcardRegExpCache[path]??=new RegExp(`^${path.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(match2,metaChar)=>metaChar?`\\${metaChar}`:match2==="/*"?TAIL_WILDCARD_REG_EXP_STR:match2==="*"?".*":`/:${LABEL_REG_EXP_STR}`)}$`)}function findMiddleware(middleware,path){for(let k of Object.keys(middleware).sort((a,b)=>b.length-a.length))if(buildWildcardRegExp(k).test(path))return[...middleware[k]]}var RegExpRouter=class{name="RegExpRouter";#middleware;#routes;#tries;constructor(){this.#middleware={ALL:createNullObject()},this.#routes={ALL:createNullObject()},this.#tries={ALL:new Trie}}#insertPath(method,path){try{this.#tries[method].insert(path,!/\*|\/:/.test(path))}catch(e){throw e===PATH_ERROR?new UnsupportedPathError(path):e}}add(method,path,handler){let middleware=this.#middleware,routes=this.#routes;if(!middleware)throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);if(!middleware[method]){this.#tries[method]=new Trie;for(let handlerMap of[middleware,routes]){handlerMap[method]=createNullObject();for(let p in handlerMap.ALL)handlerMap[method][p]=[...handlerMap.ALL[p]],this.#insertPath(method,p)}}path==="/*"&&(path="*");let methods=method==="ALL"?Object.keys(middleware):[method];if(/\*$/.test(path)){let re=buildWildcardRegExp(path);for(let m of methods)middleware[m][path]||(this.#insertPath(m,path),middleware[m][path]=findMiddleware(middleware[m],path)||findMiddleware(middleware.ALL,path)||[]);for(let handlerMap of[middleware,routes])for(let m of methods)for(let p in handlerMap[m])re.test(p)&&handlerMap[m][p].push([handler,path]);return}let paths=checkOptionalParameter(path)||[path];for(let path2 of paths)for(let m of methods)routes[m][path2]||(this.#insertPath(m,path2),routes[m][path2]=findMiddleware(middleware[m],path2)||findMiddleware(middleware.ALL,path2)||[]),routes[m][path2].push([handler,path2])}match=match;buildAllMatchers(){let matchers=createNullObject();for(let method of Object.keys(this.#routes))matchers[method]=this.#buildMatcher(method);return this.#middleware=this.#routes=this.#tries=void 0,wildcardRegExpCache=createNullObject(),matchers}#buildMatcher(method){let middleware=this.#middleware[method],routes=this.#routes[method],trie=this.#tries[method],staticMap=createNullObject(),handlerData=[],[regexp,indexReplacementMap,paramReplacementMap]=trie.buildRegExp();for(let r of[middleware,routes])for(let path in r){let handlers=r[path],pathData=trie.paths[path];if(!pathData){staticMap[path]=[handlers.map(([h])=>[h,createNullObject()]),emptyParam];continue}handlerData[pathData[0]]=handlers.map(([h,handlerPath])=>[h,trie.paths[handlerPath][1].reduceRight((map,[key],i)=>(map[key]=paramReplacementMap[pathData[1][i][1]],map),createNullObject())])}return[regexp,indexReplacementMap.map(i=>handlerData[i]),staticMap]}};var SmartRouter=class{name="SmartRouter";#routers=[];#routes=[];constructor(init){this.#routers=init.routers}add(method,path,handler){if(!this.#routes)throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);this.#routes.push([method,path,handler])}match(method,path){if(!this.#routes)throw new Error("Fatal error");let routers=this.#routers,routes=this.#routes,len=routers.length,i=0,res;for(;i<len;i++){let router=routers[i];try{for(let i2=0,len2=routes.length;i2<len2;i2++)router.add(...routes[i2]);res=router.match(method,path)}catch(e){if(e instanceof UnsupportedPathError)continue;throw e}this.match=router.match.bind(router),this.#routers=[router],this.#routes=void 0;break}if(i===len)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,res}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw new Error("No active router has been determined yet.");return this.#routers[0]}};var emptyParams=createNullObject(),order=0,Node3=class Node4{#methods=[];#children=createNullObject();#patterns=[];#pattern;#params=emptyParams;insert(method,path,handler){let curNode=this,parts=splitRoutingPath(path),possibleKeys=new Set,i=0;for(let p of parts){let nextP=parts[++i],pattern=getPattern(p,nextP)||(nextP===void 0&&p&&p.indexOf("*")===p.length-1?p:null),isParam=Array.isArray(pattern),key=isParam?pattern[0]:pattern||p,child=curNode.#children[key]||=new Node4;pattern&&!child.#pattern&&(child.#pattern=pattern,curNode.#patterns.push(child)),curNode=child,isParam&&possibleKeys.add(pattern[1])}curNode.#methods.push({[method]:{handler,possibleKeys:[...possibleKeys],score:++order}})}#pushHandlerSets(handlerSets,node,method,nodeParams,params){for(let i=0,len=node.#methods.length;i<len;i++){let m=node.#methods[i],handlerSet=m[method]||m.ALL;if(handlerSet){handlerSet.params=createNullObject(),handlerSets.push(handlerSet);for(let i2=0,len2=handlerSet.possibleKeys.length;i2<len2;i2++){let key=handlerSet.possibleKeys[i2];handlerSet.params[key]=params?.[key]&&!i2?params[key]:nodeParams[key]??params?.[key]}}}}search(method,path){let handlerSets=[];this.#params=emptyParams;let curNodes=[this],parts=splitPath(path),curNodesQueue=[],len=parts.length,partOffsets=null;for(let i=0;i<len;i++){let part=parts[i],isLast=i===len-1,tempNodes=[];for(let j=0,len2=curNodes.length;j<len2;j++){let node=curNodes[j],nextNode=node.#children[part];nextNode&&(nextNode.#params=node.#params,isLast?(nextNode.#children["*"]&&this.#pushHandlerSets(handlerSets,nextNode.#children["*"],method,node.#params),this.#pushHandlerSets(handlerSets,nextNode,method,node.#params)):tempNodes.push(nextNode));for(let child of node.#patterns){let pattern=child.#pattern,params=node.#params===emptyParams?{}:{...node.#params};if(typeof pattern=="string"){(pattern==="*"||part.startsWith(pattern.slice(0,-1)))&&(this.#pushHandlerSets(handlerSets,child,method,node.#params),pattern==="*"&&(child.#params=params,tempNodes.push(child)));continue}let[,name,matcher]=pattern;if(!(!part&&matcher===!0)){if(matcher!==!0){if(!partOffsets){partOffsets=[];let offset=path[0]==="/"?1:0;for(let p=0;p<len;p++)partOffsets[p]=offset,offset+=parts[p].length+1}let restPathString=path.slice(partOffsets[i]),m=matcher.exec(restPathString);if(m){params[name]=m[0],this.#pushHandlerSets(handlerSets,child,method,node.#params,params),m[0].length===restPathString.length&&child.#children["*"]&&this.#pushHandlerSets(handlerSets,child.#children["*"],method,node.#params,params);for(let _ in child.#children){child.#params=params;let componentCount=m[0].match(/\//g)?.length??0;(curNodesQueue[componentCount]||=[]).push(child);break}continue}}(matcher===!0||matcher.test(part))&&(params[name]=part,isLast?(this.#pushHandlerSets(handlerSets,child,method,params,node.#params),child.#children["*"]&&this.#pushHandlerSets(handlerSets,child.#children["*"],method,params,node.#params)):(child.#params=params,tempNodes.push(child)))}}}let shifted=curNodesQueue.shift();curNodes=shifted?tempNodes.concat(shifted):tempNodes}return handlerSets[1]&&handlerSets.sort((a,b)=>a.score-b.score),[handlerSets.map(({handler,params})=>[handler,params])]}};var TrieRouter=class{name="TrieRouter";#node=new Node3;add(method,path,handler){for(let result of checkOptionalParameter(path)||[path])this.#node.insert(method,result,handler)}match(method,path){return this.#node.search(method,path)}};var Hono3=class extends Hono{constructor(options={}){super(options),this.router=options.router??new SmartRouter({routers:[new RegExpRouter,new TrieRouter]})}};init_origin();init_public_route();var FAVICON_CACHE_CONTROL="public, max-age=31536000, immutable",FAVICON_REDIRECT_CACHE_CONTROL="public, max-age=300";function protocolOf(value){return/^([a-z][a-z\d+.-]*):/i.exec(value)?.[1]?.toLowerCase()}function publicAssetPath(basePath,source){return`${basePath==="/"?"":basePath}/_mcp-use/public/${source.split("/").map(segment=>encodeURIComponent(segment)).join("/")}`}function isLocalPublicSource(source){return protocolOf(source)===void 0}function selectFaviconFromIcons(icons){return icons[0]}function assertLocalPublicSource(source,field){if(source.startsWith("/")||source.includes("\\")||source.includes("?")||source.includes("#")||source.split("/").some(segment=>segment===""||segment===".."))throw new TypeError(`${field} must be an http(s) URL, image data URL, or safe path relative to public/`)}function parseDataImage(source,field){let comma=source.indexOf(",");if(comma<0)throw new TypeError(`${field} must be a valid image data URL`);let metadata=source.slice(5,comma),payload=source.slice(comma+1),parts=metadata.split(";"),mimeType=parts[0]?.toLowerCase()??"";if(!mimeType.startsWith("image/"))throw new TypeError(`${field} data URL must use an image MIME type`);try{if(parts.includes("base64")){let binary2=atob(payload);return{mimeType,bytes:Uint8Array.from(binary2,character=>character.charCodeAt(0))}}return{mimeType,bytes:new TextEncoder().encode(decodeURIComponent(payload))}}catch{throw new TypeError(`${field} must be a valid image data URL`)}}function assertBrandingSource(source,field){if(typeof source!="string"||source.length===0)throw new TypeError(`${field} must be a non-empty string`);let protocol=protocolOf(source);if(protocol===void 0)return assertLocalPublicSource(source,field),source;if(protocol==="data")return parseDataImage(source,field),source;if(protocol!=="http"&&protocol!=="https")throw new TypeError(`${field} must be an http(s) URL, image data URL, or safe path relative to public/`);try{new URL(source)}catch{throw new TypeError(`${field} must be a valid absolute http(s) URL`)}return source}function normalizeServerBranding(config2){let websiteUrl;if(config2.websiteUrl!==void 0){if(typeof config2.websiteUrl!="string"||config2.websiteUrl.length===0)throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL");let parsed;try{parsed=new URL(config2.websiteUrl)}catch{throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL")}if(parsed.protocol!=="http:"&&parsed.protocol!=="https:")throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL");websiteUrl=config2.websiteUrl}let icons;if(config2.icons!==void 0){if(!Array.isArray(config2.icons))throw new TypeError("icons must be an array of MCP Icon objects");icons=Object.freeze(config2.icons.map((value,index)=>{if(typeof value!="object"||value===null)throw new TypeError(`icons[${index}] must be an MCP Icon object`);let icon=value,src=assertBrandingSource(icon.src,`icons[${index}].src`),mimeType=icon.mimeType;if(mimeType!==void 0&&(typeof mimeType!="string"||!mimeType.toLowerCase().startsWith("image/")))throw new TypeError(`icons[${index}].mimeType must be an image MIME type when provided`);let sizes=icon.sizes;if(sizes!==void 0&&(!Array.isArray(sizes)||sizes.some(size=>typeof size!="string"||size.length===0)))throw new TypeError(`icons[${index}].sizes must be an array of non-empty strings when provided`);let normalizedSizes=sizes===void 0?void 0:sizes.map(size=>size),theme=icon.theme;if(theme!==void 0&&theme!=="light"&&theme!=="dark")throw new TypeError(`icons[${index}].theme must be "light" or "dark" when provided`);return Object.freeze({src,...mimeType!==void 0&&{mimeType},...normalizedSizes!==void 0&&{sizes:Object.freeze(normalizedSizes)},...theme!==void 0&&{theme}})}))}let explicitFavicon=config2.favicon===void 0?void 0:assertBrandingSource(config2.favicon,"favicon"),inferred=explicitFavicon===void 0?selectFaviconFromIcons(icons??[]):void 0,favicon=explicitFavicon??inferred?.src,faviconMimeType=inferred?.mimeType??icons?.find(icon=>icon.src===explicitFavicon)?.mimeType;return Object.freeze({...favicon!==void 0&&{favicon},...faviconMimeType!==void 0&&{faviconMimeType},...icons!==void 0&&{icons},...websiteUrl!==void 0&&{websiteUrl}})}function resolveImplementationIcons(icons,request,basePath){if(icons!==void 0)return icons.map(icon=>({...icon,src:request!==void 0&&isLocalPublicSource(icon.src)?`${resolveAssetsBase(request)}${publicAssetPath(basePath,icon.src)}`:icon.src,...icon.sizes!==void 0&&{sizes:[...icon.sizes]}}))}function hasLocalBrandingAsset(branding){return branding.favicon!==void 0&&isLocalPublicSource(branding.favicon)||branding.icons?.some(icon=>isLocalPublicSource(icon.src))===!0}function createFaviconHandler(branding,options){let source=branding.favicon;if(source!==void 0)return async request=>{if(request.method!=="GET"&&request.method!=="HEAD")return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});if(new URL(request.url).pathname!=="/favicon.ico")return new Response("Not Found",{status:404});let protocol=protocolOf(source);if(protocol==="http"||protocol==="https")return new Response(null,{status:307,headers:{Location:source,"Cache-Control":FAVICON_REDIRECT_CACHE_CONTROL}});if(protocol==="data"){let data=parseDataImage(source,"favicon");return new Response(request.method==="HEAD"?null:data.bytes.buffer,{status:200,headers:{"Content-Type":branding.faviconMimeType??data.mimeType,"Cache-Control":FAVICON_CACHE_CONTROL,"X-Content-Type-Options":"nosniff"}})}let{join}=await import("path"),publicRoot=options.dev?join(options.projectRoot,"public"):join(options.projectRoot,".mcp-use/build/views/public"),diskPath=await resolvePublicFilePath(publicRoot,source);if(diskPath===null)return new Response("Not Found",{status:404,headers:{"Cache-Control":"no-store"}});let response=await servePublicFile(diskPath,{...options.deferCors===!0&&{deferCors:!0},...request.method==="HEAD"&&{head:!0}});return response.headers.set("Cache-Control",FAVICON_CACHE_CONTROL),response.headers.set("X-Content-Type-Options","nosniff"),branding.faviconMimeType!==void 0&&response.headers.set("Content-Type",branding.faviconMimeType),response}}function isOAuthProviderLike(value){if(typeof value!="object"||value===null)return!1;let provider=value;return typeof provider.createTokenVerifier=="function"&&typeof provider.mapAuthInfo=="function"&&typeof provider.oauthMetadata=="object"&&provider.oauthMetadata!==null}function assertServerConfig(config2){if(config2.mixedAuth!==void 0&&typeof config2.mixedAuth!="boolean")throw new TypeError("mixedAuth must be a boolean");if(config2.mixedAuth===!0&&!isOAuthProviderLike(config2.oauth))throw new TypeError("mixedAuth requires an OAuth provider; set oauth on the server");if(config2.basePath!==void 0){if(typeof config2.basePath!="string")throw new TypeError("basePath must be an absolute URL pathname without empty segments, trailing slash, query, fragment, or whitespace");let{basePath}=config2;if(!basePath.startsWith("/")||basePath.includes("?")||basePath.includes("#")||/\s/.test(basePath)||basePath.includes("//")||basePath.length>1&&basePath.endsWith("/"))throw new TypeError("basePath must be an absolute URL pathname without empty segments, trailing slash, query, fragment, or whitespace")}if(config2.port!==void 0&&(typeof config2.port!="number"||!Number.isInteger(config2.port)||config2.port<0||config2.port>65535))throw new TypeError("port must be an integer between 0 and 65535");if(config2.skills!==void 0&&typeof config2.skills!="boolean"){if(typeof config2.skills!="object"||config2.skills===null||Array.isArray(config2.skills))throw new TypeError("skills must be a boolean or configuration object");let directory=config2.skills.directory;if(directory!==void 0&&typeof directory!="string")throw new TypeError("skills.directory must be a string when provided")}}var DEFAULT_LISTEN_HOST="127.0.0.1";function resolveListenHost(explicitHost,configuredHost,env2=process.env){if(explicitHost!==void 0)return explicitHost;let envHost=env2.HOST?.trim();return envHost!==void 0&&envHost!==""?envHost:configuredHost??DEFAULT_LISTEN_HOST}function resolveListenPort(explicitPort,configuredPort,env2=process.env){if(explicitPort!==void 0)return explicitPort;let envPort=parsePort(env2.PORT);return envPort!==void 0?envPort:configuredPort??3e3}function parsePort(value){if(value===void 0||value.trim()==="")return;let port=Number(value);return Number.isInteger(port)&&port>=0&&port<=65535?port:void 0}var bufferedResponses=new WeakSet,bufferedSources=new WeakMap;function markBufferedResponse(response){return response.body!==null&&bufferedResponses.add(response),response}function trackBufferedResponse(request,response){return markBufferedResponse(response),bufferedSources.set(request,response),response}function isBufferedResponse(response,request){if(response.body===null)return!1;if(bufferedResponses.has(response))return!0;let source=request===void 0?void 0:bufferedSources.get(request);return source!==void 0&&source.body!==null&&source.body===response.body}function inheritBufferedResponse(source,target){return isBufferedResponse(source)?markBufferedResponse(target):target}function toNodeHandler(handler,opts){return async(req,res,parsedBody)=>{typeof parsedBody=="function"&&(parsedBody=void 0);let finished=!1,abort=new AbortController;res.on("close",()=>{finished||abort.abort()}),res.destroyed===!0&&abort.abort();let request,response;try{request=await toWebRequest(req,parsedBody,{signal:abort.signal}),response=await handler.fetch(request,{...req.auth!==void 0&&{authInfo:req.auth},...parsedBody!==void 0&&{parsedBody}})}catch(error3){try{opts?.onerror?.(error3 instanceof Error?error3:new Error(String(error3)))}catch{}response=internalServerErrorResponse2(echoableRequestId2(parsedBody))}let headers={},setCookies=response.headers.getSetCookie?.();for(let[name,value]of response.headers){if(name==="set-cookie"&&setCookies?.length){headers[name]=setCookies;continue}headers[name]=value}if(res.writeHead(response.status,headers),response.body===null){finished=!0,res.end();return}if(isBufferedResponse(response,request)){try{let bytes=new Uint8Array(await response.arrayBuffer());finished=!0,res.end(bytes)}catch{finished=!0,res.end()}return}let drainResolve,releaseDrainWait=()=>{drainResolve?.(),drainResolve=void 0},waitForDrain=()=>new Promise(resolve=>{drainResolve=resolve});res.on("drain",releaseDrainWait);let closed=new Promise(resolve=>{abort.signal.addEventListener("abort",()=>resolve(),{once:!0})});try{for await(let chunk of response.body){if(abort.signal.aborted)break;let bytes=chunk instanceof Uint8Array?chunk:new Uint8Array(chunk);res.write(bytes)===!1&&await Promise.race([waitForDrain(),closed])}}catch{}finished=!0,res.end()}}async function toWebRequest(req,parsedBody,options){let method=(req.method??"GET").toUpperCase(),url2=`http://${singleHeaderValue(req.headers.host)??singleHeaderValue(req.headers[":authority"])??"localhost"}${req.url??"/"}`,headers=new Headers;for(let[name,value]of Object.entries(req.headers))if(!(value===void 0||name.startsWith(":")))if(Array.isArray(value))for(let item of value)headers.append(name,item);else headers.set(name,value);let body;if(method!=="GET"&&method!=="HEAD")if(parsedBody===void 0){let decoder=new TextDecoder,collected="";for await(let chunk of req)collected+=typeof chunk=="string"?chunk:decoder.decode(chunk,{stream:!0});collected+=decoder.decode(),collected.length>0&&(body=collected)}else{let serialized=JSON.stringify(parsedBody);headers.delete("content-encoding"),headers.delete("transfer-encoding"),serialized===void 0?headers.delete("content-length"):(body=serialized,headers.set("content-length",String(new TextEncoder().encode(serialized).byteLength)))}return new Request(url2,{method,headers,...options?.signal!==void 0&&{signal:options.signal},...body!==void 0&&{body}})}function singleHeaderValue(value){return Array.isArray(value)?value[0]:value}function echoableRequestId2(body){if(body===null||typeof body!="object"||Array.isArray(body))return null;let{method,id}=body;return typeof method!="string"?null:typeof id=="string"||typeof id=="number"?id:null}function internalServerErrorResponse2(id){return Response.json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id},{status:500})}init_dist();init_fetch_app();init_dist();var UI_EXTENSION_ID="io.modelcontextprotocol/ui",UI_MIME_TYPE="text/html;profile=mcp-app",UI_RESOURCE_URI_PREFIX="ui://views/";var UI_RESOURCE_URI_META_KEY="ui/resourceUri";function viewResourceUri(viewName){return`${UI_RESOURCE_URI_PREFIX}${viewName}.html`}var clientCapabilitiesByRequest=new WeakMap;function stashClientCapabilities(request,capabilities){clientCapabilitiesByRequest.set(request,capabilities)}function extractClientCapabilitiesFromBody(body){if(typeof body!="object"||body===null)return;let params=body.params;if(typeof params!="object"||params===null)return;let meta2=params._meta;if(typeof meta2!="object"||meta2===null)return;let capabilities=meta2[CLIENT_CAPABILITIES_META_KEY];if(!(typeof capabilities!="object"||capabilities===null))return capabilities}function supportsViews(capabilities){let extensions=capabilities?.extensions;if(extensions===void 0)return!1;let uiExtension=extensions[UI_EXTENSION_ID];if(typeof uiExtension!="object"||uiExtension===null)return!1;let mimeTypes=uiExtension.mimeTypes;return Array.isArray(mimeTypes)?mimeTypes.includes(UI_MIME_TYPE):!1}function requireOAuthAuthInfo(authInfo){if(authInfo===void 0||authInfo.extra===void 0||authInfo.expiresAt===void 0)throw new Error("OAuth callback did not receive mapped AuthInfo.extra")}function stringValue(value){return typeof value=="string"?value:void 0}function coordinateValue(value){return typeof value=="string"||typeof value=="number"&&Number.isFinite(value)?value:void 0}function normalizeUserContext(meta2){if(meta2===void 0)return;let locale=stringValue(meta2["openai/locale"])??stringValue(meta2["webplus/i18n"]),userAgent=stringValue(meta2["openai/userAgent"]),subject=stringValue(meta2["openai/subject"]),conversationId=stringValue(meta2["openai/session"]),organizationId=stringValue(meta2["openai/organization"]),rawLocation=meta2["openai/userLocation"],location;if(typeof rawLocation=="object"&&rawLocation!==null&&!Array.isArray(rawLocation)){let values=rawLocation,normalized={city:stringValue(values.city),region:stringValue(values.region),country:stringValue(values.country),timezone:stringValue(values.timezone),latitude:coordinateValue(values.latitude),longitude:coordinateValue(values.longitude)},entries=Object.entries(normalized).filter(entry=>entry[1]!==void 0);entries.length>0&&(location=Object.fromEntries(entries))}if(!(locale===void 0&&userAgent===void 0&&location===void 0&&subject===void 0&&conversationId===void 0&&organizationId===void 0))return{...locale!==void 0&&{locale},...userAgent!==void 0&&{userAgent},...location!==void 0&&{location},...subject!==void 0&&{subject},...conversationId!==void 0&&{conversationId},...organizationId!==void 0&&{organizationId}}}function requestEnvelope(ctx){return ctx.mcpReq.envelope}function requestClientInfo(ctx){return{...requestEnvelope(ctx)?.[CLIENT_INFO_META_KEY]??{}}}function toClientContext(ctx){let capabilities={...requestEnvelope(ctx)?.[CLIENT_CAPABILITIES_META_KEY]??{}},info=requestClientInfo(ctx),user=normalizeUserContext(ctx.mcpReq._meta);return{can(capability){return Object.hasOwn(capabilities,capability)},capabilities(){return{...capabilities}},extension(id){let settings=capabilities.extensions?.[id];return settings===void 0?void 0:{...settings}},info(){return{...info}},user(){return user===void 0?void 0:{...user,...user.location!==void 0&&{location:{...user.location}}}},supportsViews(){return supportsViews(capabilities)}}}function toRequestContext(ctx){let rawRequest=ctx.http?.req,http=rawRequest===void 0?void 0:getRequestBag(rawRequest).honoContext,request=http?.req??(rawRequest===void 0?void 0:new HonoRequest(rawRequest)),additions={signal:ctx.mcpReq.signal,...request!==void 0&&{request},...ctx.mcpReq.inputResponses!==void 0&&{inputResponses:ctx.mcpReq.inputResponses},client:toClientContext(ctx),requestState:()=>ctx.mcpReq.requestState(),async sendNotification(method,params){await ctx.mcpReq.notify({method,...params!==void 0&&{params}})},async reportProgress(progress,total,message){let progressToken=ctx.mcpReq._meta?.progressToken;return progressToken===void 0?!1:(await ctx.mcpReq.notify({method:"notifications/progress",params:{progressToken,progress,...total!==void 0&&{total},...message!==void 0&&{message}}}),!0)},async sendLog(level,data,logger){await ctx.mcpReq.notify({method:"notifications/message",params:{level,data,...logger!==void 0&&{logger}}})}};return http!==void 0?Object.assign(http,additions):{...additions,...request!==void 0&&{req:request}}}function toAuthenticatedRequestContext(ctx){let authInfo=ctx.http?.authInfo;return requireOAuthAuthInfo(authInfo),Object.assign(toRequestContext(ctx),{auth:{user:authInfo.extra.user,payload:authInfo.extra.payload,accessToken:authInfo.token,scopes:[...authInfo.scopes],permissions:[...authInfo.extra.permissions],...authInfo.clientId.length>0&&{clientId:authInfo.clientId},expiresAt:authInfo.expiresAt,...authInfo.resource!==void 0&&{resource:authInfo.resource}}})}init_dist();function isReadResourceResult(result){return"contents"in result&&Array.isArray(result.contents)}function isGetPromptResult(result){return"messages"in result&&Array.isArray(result.messages)}function toResourceResult(result,uri){if(isReadResourceResult(result))return result;let mime=result._meta&&typeof result._meta=="object"&&typeof result._meta.mimeType=="string"?result._meta.mimeType:void 0,contents=[];for(let block of result.content??[]){let mapped=contentBlockToResourceContents(block,uri,mime);mapped!==void 0&&contents.push(mapped)}return contents.length===0&&result.structuredContent!==void 0&&contents.push({uri,mimeType:"application/json",text:JSON.stringify(result.structuredContent)}),contents.length===0&&contents.push({uri,mimeType:"text/plain",text:""}),{contents}}function contentBlockToResourceContents(block,uri,mimeHint){if(block.type==="text")return{uri,mimeType:mimeHint??"text/plain",text:block.text};if(block.type==="image"||block.type==="audio")return{uri,mimeType:block.mimeType,blob:block.data};if(block.type==="resource")return{...block.resource}}function toPromptResult(result){if(isInputRequiredResult(result)||isGetPromptResult(result))return result;let messages=(result.content??[]).map(content=>({role:"user",content}));return messages.length===0&&result.structuredContent!==void 0&&messages.push({role:"user",content:{type:"text",text:JSON.stringify(result.structuredContent)}}),messages.length===0&&messages.push({role:"user",content:{type:"text",text:""}}),{messages}}init_fetch_app();var DEFAULT_METHODS=["GET","HEAD","POST","OPTIONS"],DEFAULT_ALLOWED_HEADERS=["Content-Type","Authorization","mcp-protocol-version","mcp-method","mcp-name"];function resolveAllowedOrigin(origin,requestOrigin){return origin===void 0?requestOrigin:typeof origin=="function"?origin(requestOrigin):origin==="*"?"*":Array.isArray(origin)?requestOrigin!==null&&origin.includes(requestOrigin)?requestOrigin:null:origin}function corsHeaders(options,request){if(request.headers.has("Access-Control-Allow-Origin"))return;let requestOrigin=request.headers.get("Origin"),allowedOrigin=resolveAllowedOrigin(options.origin,requestOrigin);if(allowedOrigin===null)return;let headers={"Access-Control-Allow-Origin":allowedOrigin,"Access-Control-Allow-Methods":options.methods.join(", "),"Access-Control-Allow-Headers":options.allowedHeaders.join(", ")};return options.credentials&&(headers["Access-Control-Allow-Credentials"]="true"),allowedOrigin!=="*"&&(headers.Vary="Origin"),headers}function mergeCorsHeaders(response,headers){if(response.headers.has("Access-Control-Allow-Origin"))return response;let merged=new Headers(response.headers);return new Headers(headers).forEach((value,key)=>{merged.set(key,value)}),inheritBufferedResponse(response,new Response(response.body,{status:response.status,statusText:response.statusText,headers:merged}))}function corsFetchMiddleware(options){if(!(options.enabled!==!1))return async(_request,next)=>next();let resolved={...options.origin!==void 0&&{origin:options.origin},methods:options.methods??DEFAULT_METHODS,allowedHeaders:options.allowedHeaders??DEFAULT_ALLOWED_HEADERS,credentials:options.credentials??!1};return async(request,next)=>{let headers=corsHeaders(resolved,request);if(headers===void 0)return next();if(request.method==="OPTIONS")return new Response(null,{status:204,headers});let response=await next();return mergeCorsHeaders(response,headers)}}function isGlobalCorsEnabled(cors){return cors!==void 0&&cors.enabled!==!1}init_auth_CUe6YdwF();init_dist();var MCP_MIDDLEWARE_METHODS=["tools/call","tools/list","resources/read","resources/list","prompts/get","prompts/list"];function withMcpMiddlewareParams(request,params){if(typeof request!="object"||request===null||Array.isArray(request))throw new TypeError("[mcp-use] MCP middleware received an invalid downstream request");return{...request,params}}function createMcpMiddlewareEntry(pattern,handler){let normalizedPattern=normalizeMcpMiddlewarePattern(pattern),invoke2=handler;if(normalizedPattern!=="*"&&!isMcpMiddlewareMethod(normalizedPattern))throw new TypeError(`Unsupported MCP middleware pattern "${pattern}". Use an exact MCP method or "mcp:*".`);return normalizedPattern==="*"?{pattern:normalizedPattern,handler:async(ctx,next)=>{let downstreamCalled=!1,downstreamResult;if(await invoke2(ctx,async()=>{downstreamResult=await next(),downstreamCalled=!0}),!downstreamCalled)throw new Error(`Wildcard MCP middleware "${normalizedPattern}" must call next()`);return downstreamResult}}:{pattern:normalizedPattern,handler:(ctx,next)=>invoke2(ctx,next)}}function createMcpEventListenerEntry(pattern,handler){let{pattern:normalizedPattern,phase}=parseMcpPattern(pattern),invoke2=handler;return{pattern:normalizedPattern,phase,handler:(ctx,result)=>invoke2(ctx,result)}}function matchesPattern(pattern,method){if(pattern==="*")return!0;if(pattern.endsWith("/*")){let prefix=pattern.slice(0,-1);return method.startsWith(prefix)}return pattern===method}function isMcpMiddlewareMethod(value){return MCP_MIDDLEWARE_METHODS.some(method=>method===value)}function composeMiddleware(entries,method,innerFn){let matching=entries.filter(entry=>matchesPattern(entry.pattern,method));return matching.length===0?_ctx=>innerFn():ctx=>{let index=-1,dispatch=i=>i<=index?Promise.reject(new Error("next() called multiple times")):(index=i,i===matching.length?innerFn():matching[i].handler(ctx,()=>dispatch(i+1)));return dispatch(0)}}function freezeMiddlewareContext(ctx){return Object.freeze({method:ctx.method,params:Object.freeze({...ctx.params}),...ctx.request!==void 0&&{request:ctx.request},...ctx.req!==void 0&&{req:ctx.req},...ctx.session!==void 0&&{session:Object.freeze({...ctx.session})},...ctx.auth!==void 0&&{auth:ctx.auth},state:new Map(ctx.state)})}async function runMcpOperation(middlewares,events,method,ctx,innerFn){dispatchMcpEvents(events,method,"before",ctx);let result=await composeMiddleware(middlewares,method,innerFn)(ctx);return assertValidMiddlewareResult(method,result),dispatchMcpEvents(events,method,"complete",ctx,result),result}function assertValidMiddlewareResult(method,result){if((method==="tools/call"||method==="resources/read"||method==="prompts/get")&&isInputRequiredResult(result))return;let validation=(()=>{switch(method){case"tools/call":return assertArrayProperty(method,result,"content"),CallToolResultSchema.safeParse(result);case"tools/list":return assertArrayResult(method,result),ListToolsResultSchema.safeParse({tools:result});case"resources/read":return assertArrayProperty(method,result,"contents"),ReadResourceResultSchema.safeParse(result);case"resources/list":return assertArrayResult(method,result),ListResourcesResultSchema.safeParse({resources:result});case"prompts/get":return assertArrayProperty(method,result,"messages"),GetPromptResultSchema.safeParse(result);case"prompts/list":return assertArrayResult(method,result),ListPromptsResultSchema.safeParse({prompts:result});default:throw new TypeError(`Unsupported MCP middleware method "${method}"`)}})();if(!validation.success)throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: ${validation.error.message}`)}function assertArrayResult(method,result){if(!Array.isArray(result))throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: expected an array`)}function assertArrayProperty(method,result,property){if(typeof result!="object"||result===null||!Array.isArray(result[property]))throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: expected a ${property} array`)}function dispatchMcpEvents(events,method,phase,ctx,result){let frozen=freezeMiddlewareContext(ctx);for(let entry of events)if(!(entry.phase!==phase||!matchesPattern(entry.pattern,method)))try{entry.handler(frozen,result)}catch(error3){console.error(`[mcp-use] MCP event listener for "${entry.pattern}" (${phase}) threw:`,error3)}}function parseMcpPattern(raw2){let pattern=raw2.startsWith("mcp:")?raw2.slice(4):raw2;return pattern.endsWith(":complete")?{pattern:pattern.slice(0,-9),phase:"complete"}:{pattern,phase:"before"}}function normalizeMcpMiddlewarePattern(raw2){return raw2.startsWith("mcp:")?raw2.slice(4):raw2}init_dist();init_fetch_app();function colorsEnabled(){return typeof process>"u"||process.env?.NO_COLOR!==void 0?!1:process.stdout?.isTTY===!0}function ansi(open,close){return text2=>colorsEnabled()?`\x1B[${open}m${text2}\x1B[${close}m`:text2}var bold=ansi(1,22),dim=ansi(2,22),red=ansi(31,39),green=ansi(32,39),yellow=ansi(33,39),blue=ansi(34,39),magenta=ansi(35,39),cyan=ansi(36,39),gray=ansi(90,39);function resolveLogLevel(configured){let raw2=typeof process>"u"?void 0:process.env?.MCP_USE_LOG_LEVEL?.toLowerCase();return raw2==="info"||raw2==="debug"||raw2==="trace"?raw2:configured??"info"}function formatClientInfo(info){if(!(info===void 0||typeof info.name!="string"))return typeof info.version=="string"&&info.version!==""?`${info.name}/${info.version}`:info.name}var detailFormatters={initialize:p=>({subject:formatClientInfo(p.clientInfo)}),ping:()=>({}),"server/discover":()=>({}),"completion/complete":p=>({subject:p.ref.type==="ref/prompt"?p.ref.name:p.ref.uri,input:p.argument}),"logging/setLevel":p=>({subject:p.level}),"prompts/get":p=>({subject:p.name,input:p.arguments}),"prompts/list":()=>({}),"resources/list":()=>({}),"resources/templates/list":()=>({}),"resources/read":p=>({subject:p.uri}),"resources/subscribe":p=>({subject:p.uri}),"resources/unsubscribe":p=>({subject:p.uri}),"subscriptions/listen":()=>({}),"tools/call":p=>({subject:p.name,input:p.arguments}),"tools/list":()=>({}),"sampling/createMessage":()=>({}),"elicitation/create":()=>({}),"roots/list":()=>({})};function isKnownMethod(method){return Object.prototype.hasOwnProperty.call(detailFormatters,method)}function formatDetail(message){if(!isKnownMethod(message.method))return{};try{let formatter=detailFormatters[message.method],detail=formatter(message.params);return typeof detail.subject=="string"||detail.subject===void 0?detail:{}}catch{return{}}}var INLINE_JSON_MAX_LENGTH=80;function inlineJson(value){let text2;try{text2=JSON.stringify(value)??String(value)}catch{text2=String(value)}return text2.length>INLINE_JSON_MAX_LENGTH?`${text2.slice(0,INLINE_JSON_MAX_LENGTH)}...`:text2}function formatClientIdentity(message){let meta2=message.params?._meta;if(meta2===void 0)return;let info=meta2[CLIENT_INFO_META_KEY];if(!(typeof info!="object"||info===null||typeof info.name!="string"))return formatClientInfo(info)}function formatMcpClient(message){let modern=formatClientIdentity(message);if(modern!==void 0)return modern;if(message.method==="initialize")try{return formatClientInfo(message.params.clientInfo)}catch{return}}function sanitize(text2){return text2.replace(/[\u0000-\u001F\u007F-\u009F]+/g," ")}function methodStyle(method){return method.startsWith("tools/")?cyan:method.startsWith("resources/")?green:method.startsWith("prompts/")?magenta:method==="initialize"||method==="ping"?gray:blue}function describeRequest(httpMethod,pathname,mcpPath,body){if(pathname!==mcpPath)return{method:httpMethod,client:void 0,mcpRequest:void 0,streaming:!1};let requests=Array.isArray(body)?body.filter(isJSONRPCRequest):isJSONRPCRequest(body)?[body]:[],mcpRequest=requests[0];return mcpRequest===void 0?{method:httpMethod,client:void 0,mcpRequest:void 0,streaming:!1}:{method:requests.length===1?sanitize(mcpRequest.method):`batch(${requests.map(request=>sanitize(request.method)).join(",")})`,client:formatMcpClient(mcpRequest)??"unknown",mcpRequest,streaming:mcpRequest.method==="subscriptions/listen"}}var REDACTED_HEADERS=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-api-key"]);function redactHeaders(headers){return Object.fromEntries(Object.entries(headers).map(([name,value])=>[name,REDACTED_HEADERS.has(name.toLowerCase())?"[REDACTED]":value]))}async function extractResponseOutcome(res,request){if(!res.body)return{errorMessage:null};let text2;try{let wasBuffered=isBufferedResponse(res,request),clone2=res.clone();wasBuffered&&trackBufferedResponse(request,res),text2=await clone2.text()}catch{return{errorMessage:null}}if(!text2)return{errorMessage:null};let isSse=(res.headers.get("content-type")??"").includes("text/event-stream"),payloads=[],tryParse=raw2=>{try{payloads.push(JSON.parse(raw2))}catch{}};if(isSse){for(let line of text2.split(/\r?\n/))if(line.startsWith("data:")){let data=line.slice(5).trim();data&&tryParse(data)}}else tryParse(text2);let result;for(let payload of payloads){if(payload===null||typeof payload!="object")continue;let message=payload;if(typeof message.error?.message=="string")return{errorMessage:message.error.message};if(message.result?.isError===!0){let textBlock=(Array.isArray(message.result.content)?message.result.content:[]).find(b=>b?.type==="text"&&typeof b.text=="string");return{errorMessage:textBlock?String(textBlock.text):"tool error"}}"result"in message&&(result=message.result)}return{errorMessage:null,result}}function compactToolResult(result){if(result===null||typeof result!="object")return result;let{structuredContent,content}=result;if(structuredContent!==void 0)return structuredContent;if(Array.isArray(content)){let[block]=content;if(content.length===1&&block?.type==="text")return block.text}return content}function formatForDump(value){function truncate(val){return typeof val=="string"&&val.length>100?`${val.slice(0,100)}...`:Array.isArray(val)?val.map(truncate):val!==null&&typeof val=="object"?Object.fromEntries(Object.entries(val).map(([k,v])=>[k,truncate(v)])):val}try{return JSON.stringify(truncate(value),null,2)}catch{return String(value)}}var DUMP_BODY_MAX_LENGTH=1e4;async function printTraceDump(response,requestHeaders,requestBody,readResponseBody){console.log(`
|
|
765
|
+
</html>`}var MANUFACT_INSPECTOR_ORIGIN,LOGO_SVG_PATHS,LINE_INTERSECTION_PATH,init_landing=__esm({"src/landing.ts"(){"use strict";MANUFACT_INSPECTOR_ORIGIN="https://inspector.manufact.com";LOGO_SVG_PATHS={path1:"M105.933 0C164.437 0.000115889 211.865 47.607 211.865 106.333C211.865 131.828 210.494 158.401 221.068 181.6L228.976 198.947C243.585 230.997 269.266 256.7 301.304 271.336L316.156 278.121C340.143 289.079 367.695 287.335 394.067 287.335C452.572 287.335 500 334.942 500 393.668C500 452.394 452.572 500.001 394.067 500.001C335.563 500.001 288.135 452.394 288.135 393.668C288.135 368.974 289.241 343.275 278.992 320.807L270.587 302.38C255.949 270.289 230.214 244.565 198.118 229.939L180.164 221.758C157.282 211.331 131.078 212.666 105.933 212.666C47.4278 212.666 4.92992e-05 165.059 0 106.333C0 47.607 47.4278 0 105.933 0Z",circle:{cx:100.426,cy:399.575,r:100.426},path2:"M500 100.426C500 155.889 455.037 200.851 399.574 200.851C344.11 200.851 299.148 155.889 299.148 100.426C299.148 44.962 344.11 0 399.574 0C455.037 0 500 44.962 500 100.426Z"},LINE_INTERSECTION_PATH="M10.5 4C10.5 7.31371 7.81371 10 4.5 10H0.5V11H4.5C7.81371 11 10.5 13.6863 10.5 17V21H11.5V17C11.5 13.6863 14.1863 11 17.5 11H21.5V10H17.5C14.1863 10 11.5 7.31371 11.5 4V0H10.5V4Z"}});var landing_handler_exports={};__export(landing_handler_exports,{createLandingPageResponse:()=>createLandingPageResponse});function createLandingPageResponse(request,basePath,config2,branding,tools,prompts,resources){let origin=resolveServerOrigin(request),url2=new URL(basePath,`${origin}/`).href,html2=generateLandingPage({...config2,url:url2,...branding.favicon!==void 0&&{iconUrl:new URL("/favicon.ico",`${origin}/`).href,...branding.faviconMimeType!==void 0&&{iconType:branding.faviconMimeType}},tools:Array.from(tools,entry=>entry.definition),prompts:Array.from(prompts,entry=>entry.definition),resources:Array.from(resources,entry=>entry.definition)});return new Response(request.method==="HEAD"?null:html2,{status:200,headers:{"cache-control":"no-store","content-type":"text/html; charset=utf-8","x-content-type-options":"nosniff"}})}var init_landing_handler=__esm({"src/landing-handler.ts"(){"use strict";init_landing();init_origin()}});var DEFAULT_DISPLAY_MODES=["inline","fullscreen","pip"],VALID_DISPLAY_MODES=new Set(["inline","fullscreen","pip"]);function normalizeViewConfig(config2){let autoResize=config2?.autoResize??!0,modes=config2?.displayModes===void 0?DEFAULT_DISPLAY_MODES:config2.displayModes;if(!Array.isArray(modes)||modes.length===0)throw new Error('viewConfig.displayModes must be a non-empty array that includes "inline"');let seen=new Set,normalizedModes=[];for(let mode of modes){if(typeof mode!="string"||!VALID_DISPLAY_MODES.has(mode))throw new Error(`viewConfig.displayModes contains invalid mode ${JSON.stringify(mode)}; expected "inline", "fullscreen", or "pip"`);if(seen.has(mode))throw new Error(`viewConfig.displayModes contains duplicate mode "${mode}"`);seen.add(mode),normalizedModes.push(mode)}if(!seen.has("inline"))throw new Error('viewConfig.displayModes must include "inline"');let preferred=config2?.preferredDisplayMode;if(preferred!==void 0&&preferred!=="inline"&&preferred!=="fullscreen")throw new Error('viewConfig.preferredDisplayMode must be "inline" or "fullscreen"');if(preferred!==void 0&&!seen.has(preferred))throw new Error("viewConfig.preferredDisplayMode must belong to displayModes");return{...preferred!==void 0&&{preferredDisplayMode:preferred},autoResize,displayModes:normalizedModes}}init_dist();import{createServer as createNodeHttpServer}from"node:http";var GET_MATCH_RESULT=Symbol();var bufferToFormData=(arrayBuffer,contentType)=>new Response(arrayBuffer,{headers:{"Content-Type":contentType.replace(/^[^;]+/,mediaType=>mediaType.toLowerCase())}}).formData();var MAX_NESTED_OBJECTS=1e4,isRawRequest=request=>"headers"in request,parseBody=async(request,options=Object.create(null))=>{let{all=!1,dot=!1}=options,mediaType=(isRawRequest(request)?request.headers:request.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return mediaType==="multipart/form-data"||mediaType==="application/x-www-form-urlencoded"?parseFormData(request,{all,dot}):{}};async function parseFormData(request,options){if(!isRawRequest(request)&&request.bodyCache.formData)return convertFormDataToBodyData(await request.bodyCache.formData,options);let headers=isRawRequest(request)?request.headers:request.raw.headers,arrayBuffer=await request.arrayBuffer(),formDataPromise=bufferToFormData(arrayBuffer,headers.get("Content-Type")||"");isRawRequest(request)||(request.bodyCache.formData=formDataPromise);let formData=await formDataPromise;return formData?convertFormDataToBodyData(formData,options):{}}function convertFormDataToBodyData(formData,options){let form=Object.create(null),nestingState={count:0};return formData.forEach((value,key)=>{options.all||key.endsWith("[]")?handleParsingAllValues(form,key,value):form[key]=value}),options.dot&&Object.entries(form).forEach(([key,value])=>{key.includes(".")&&(handleParsingNestedValues(form,key,value,nestingState),delete form[key])}),form}var handleParsingAllValues=(form,key,value)=>{form[key]!==void 0?Array.isArray(form[key])?form[key].push(value):form[key]=[form[key],value]:key.endsWith("[]")?form[key]=[value]:form[key]=value},handleParsingNestedValues=(form,key,value,state)=>{if(/(?:^|\.)__proto__\./.test(key))return;let nestedForm=form,keys=key.split(".",34);keys.length>33&&throwNestingLimitExceeded(),keys.forEach((key2,index)=>{index===keys.length-1?nestedForm[key2]=value:((!nestedForm[key2]||typeof nestedForm[key2]!="object"||Array.isArray(nestedForm[key2])||nestedForm[key2]instanceof File)&&(state.count++>=MAX_NESTED_OBJECTS&&throwNestingLimitExceeded(),nestedForm[key2]=Object.create(null)),nestedForm=nestedForm[key2])})},throwNestingLimitExceeded=()=>{throw new Error("Nesting limit exceeded")};var splitPath=path=>{let paths=path.split("/");return paths[0]===""&&paths.shift(),paths},splitRoutingPath=routePath=>{let{groups,path}=extractGroupsFromPath(routePath),paths=splitPath(path);return replaceGroupMarks(paths,groups)},extractGroupsFromPath=path=>{let groups=[];return path=path.replace(/\{[^}]+\}/g,(match2,index)=>{let mark=`@${index}`;return groups.push([mark,match2]),mark}),{groups,path}},replaceGroupMarks=(paths,groups)=>{for(let i=groups.length-1;i>=0;i--){let[mark]=groups[i];for(let j=paths.length-1;j>=0;j--)if(paths[j].includes(mark)){paths[j]=paths[j].replace(mark,groups[i][1]);break}}return paths},patternCache={},getPattern=(label,next)=>{if(label==="*")return"*";let match2=label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(match2){let cacheKey=`${label}#${next}`;return patternCache[cacheKey]||(match2[2]?patternCache[cacheKey]=next&&next[0]!==":"&&next[0]!=="*"?[cacheKey,match2[1],new RegExp(`^${match2[2]}(?=/${next})`)]:[label,match2[1],new RegExp(`^${match2[2]}$`)]:patternCache[cacheKey]=[label,match2[1],!0]),patternCache[cacheKey]}return null},tryDecode=(str,decoder)=>{try{return decoder(str)}catch{return str.replace(/(?:%[0-9A-Fa-f]{2})+/g,match2=>{try{return decoder(match2)}catch{return match2}})}},tryDecodeURI=str=>tryDecode(str,decodeURI),getPath=request=>{let url2=request.url,start=url2.indexOf("/",url2.indexOf(":")+4),i=start;for(;i<url2.length;i++){let charCode=url2.charCodeAt(i);if(charCode===37){let queryIndex=url2.indexOf("?",i),hashIndex=url2.indexOf("#",i),end=queryIndex===-1?hashIndex===-1?void 0:hashIndex:hashIndex===-1?queryIndex:Math.min(queryIndex,hashIndex),path=url2.slice(start,end);return tryDecodeURI(path.includes("%25")?path.replace(/%25/g,"%2525"):path)}else if(charCode===63||charCode===35)break}return url2.slice(start,i)};var getPathNoStrict=request=>{let result=getPath(request);return result.length>1&&result.at(-1)==="/"?result.slice(0,-1):result},mergePath=(base,sub,...rest)=>(rest.length&&(sub=mergePath(sub,...rest)),`${base?.[0]==="/"?"":"/"}${base}${sub==="/"?"":`${base?.at(-1)==="/"?"":"/"}${sub?.[0]==="/"?sub.slice(1):sub}`}`),checkOptionalParameter=path=>{if(path.charCodeAt(path.length-1)!==63||!path.includes(":"))return null;let segments=path.split("/"),results=[],basePath="";return segments.forEach(segment=>{if(segment!==""&&!/\:/.test(segment))basePath+="/"+segment;else if(/\:/.test(segment))if(segment.charCodeAt(segment.length-1)===63){results.length===0&&basePath===""?results.push("/"):results.push(basePath);let optionalSegment=segment.slice(0,-1);basePath+="/"+optionalSegment,results.push(basePath)}else basePath+="/"+segment}),results.filter((v,i,a)=>a.indexOf(v)===i)},tryDecodeURIComponent=str=>str.indexOf("%")!==-1?tryDecode(str,decodeURIComponent_):str,_decodeURI=value=>(value.indexOf("+")!==-1&&(value=value.replace(/\+/g," ")),tryDecodeURIComponent(value)),_getQueryParam=(url2,key,multiple)=>{let hashIndex=url2.indexOf("#",8);hashIndex!==-1&&(url2=url2.slice(0,hashIndex));let encoded;if(!multiple&&key&&key.indexOf("%")===-1&&key.indexOf("+")===-1){let keyIndex2=url2.indexOf("?",8);if(keyIndex2===-1)return;for(url2.startsWith(key,keyIndex2+1)||(keyIndex2=url2.indexOf(`&${key}`,keyIndex2+1));keyIndex2!==-1;){let trailingKeyCode=url2.charCodeAt(keyIndex2+key.length+1);if(trailingKeyCode===61){let valueIndex=keyIndex2+key.length+2,endIndex=url2.indexOf("&",valueIndex);return _decodeURI(url2.slice(valueIndex,endIndex===-1?void 0:endIndex))}else if(trailingKeyCode==38||isNaN(trailingKeyCode))return"";keyIndex2=url2.indexOf(`&${key}`,keyIndex2+1)}if(encoded=/[%+]/.test(url2),!encoded)return}let results=Object.create(null);encoded??=/[%+]/.test(url2);let keyIndex=url2.indexOf("?",8);for(;keyIndex!==-1;){let nextKeyIndex=url2.indexOf("&",keyIndex+1),valueIndex=url2.indexOf("=",keyIndex);valueIndex>nextKeyIndex&&nextKeyIndex!==-1&&(valueIndex=-1);let name=url2.slice(keyIndex+1,valueIndex===-1?nextKeyIndex===-1?void 0:nextKeyIndex:valueIndex);if(encoded&&(name=_decodeURI(name)),keyIndex=nextKeyIndex,name==="")continue;let value;valueIndex===-1?value="":(value=url2.slice(valueIndex+1,nextKeyIndex===-1?void 0:nextKeyIndex),encoded&&(value=_decodeURI(value))),multiple?(results[name]&&Array.isArray(results[name])||(results[name]=[]),results[name].push(value)):results[name]??=value}return key?results[key]:results},getQueryParam=_getQueryParam,getQueryParams=(url2,key)=>_getQueryParam(url2,key,!0),decodeURIComponent_=decodeURIComponent;var HonoRequest=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(request,path="/",matchResult=[[]]){this.raw=request,this.path=path,this.#matchResult=matchResult}param(key){return key?this.#getDecodedParam(key):this.#getAllDecodedParams()}#getDecodedParam(key){let paramKey=this.#matchResult[0][this.routeIndex]?.[1][key],param=this.#getParamValue(paramKey);return param&&tryDecodeURIComponent(param)}#getAllDecodedParams(){let decoded={},keys=Object.keys(this.#matchResult[0][this.routeIndex]?.[1]??{});for(let key of keys){let value=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);value!==void 0&&(decoded[key]=tryDecodeURIComponent(value))}return decoded}#getParamValue(paramKey){return this.#matchResult[1]?this.#matchResult[1][paramKey]:paramKey}query(key){return getQueryParam(this.url,key)}queries(key){return getQueryParams(this.url,key)}header(name){if(name)return this.raw.headers.get(name)??void 0;let headerData=Object.create(null);return this.raw.headers.forEach((value,key)=>{headerData[key]=value}),headerData}async parseBody(options){return parseBody(this,options)}#cachedBody=key=>{let{bodyCache,raw:raw2}=this,cachedBody=bodyCache[key];if(cachedBody)return cachedBody;for(let anyCachedKey in bodyCache)return bodyCache[anyCachedKey].then(body=>{anyCachedKey==="json"&&(body=JSON.stringify(body));let contentType=anyCachedKey==="formData"?void 0:raw2.headers.get("content-type");return new Response(body,{headers:contentType?{"Content-Type":contentType}:void 0})[key]()});return bodyCache[key]=raw2[key]()};json(){return this.#cachedBody("text").then(text2=>JSON.parse(text2))}text(){return this.#cachedBody("text")}arrayBuffer(){return this.#cachedBody("arrayBuffer")}bytes(){return this.#cachedBody("arrayBuffer").then(buffer=>new Uint8Array(buffer))}blob(){return this.#cachedBody("blob")}formData(){return this.#cachedBody("formData")}addValidatedData(target,data){(this.#validatedData??={})[target]=data}valid(target){return this.#validatedData?.[target]}get url(){return this.raw.url}get method(){return this.raw.method}get[GET_MATCH_RESULT](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,route]])=>route)}get routePath(){return this.#matchResult[0].map(([[,route]])=>route)[this.routeIndex].path}};var HtmlEscapedCallbackPhase={Stringify:1,BeforeStream:2,Stream:3},raw=(value,callbacks)=>{let escapedString=new String(value);return escapedString.isEscaped=!0,escapedString.callbacks=callbacks,escapedString};var resolveCallback=async(str,phase,preserveCallbacks,context,buffer)=>{typeof str=="object"&&!(str instanceof String)&&(str instanceof Promise||(str=str.toString()),str instanceof Promise&&(str=await str));let callbacks=str.callbacks;if(!callbacks?.length)return Promise.resolve(str);buffer?buffer[0]+=str:buffer=[str];let resStr=Promise.all(callbacks.map(c=>c({phase,buffer,context}))).then(res=>Promise.all(res.filter(Boolean).map(str2=>resolveCallback(str2,phase,!1,context,buffer))).then(()=>buffer[0]));return preserveCallbacks?raw(await resStr,callbacks):resStr};var TEXT_PLAIN="text/plain; charset=UTF-8",setDefaultContentType=(contentType,headers)=>({"Content-Type":contentType,...headers}),createResponseInstance=(body,init)=>new Response(body,init),Context=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(req,options){this.#rawRequest=req,options&&(this.#executionCtx=options.executionCtx,this.env=options.env,this.#notFoundHandler=options.notFoundHandler,this.#path=options.path,this.#matchResult=options.matchResult)}get req(){return this.#req??=new HonoRequest(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&"respondWith"in this.#executionCtx)return this.#executionCtx;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error("This context has no ExecutionContext")}get res(){return this.#res||=createResponseInstance(null,{headers:this.#preparedHeaders??=new Headers})}set res(_res){if(this.#res&&_res){_res=createResponseInstance(_res.body,_res);for(let[k,v]of this.#res.headers.entries())if(k!=="content-type")if(k==="set-cookie"){let cookies=this.#res.headers.getSetCookie();_res.headers.delete("set-cookie");for(let cookie of cookies)_res.headers.append("set-cookie",cookie)}else _res.headers.set(k,v)}this.#res=_res,this.finalized=!0}render=(...args)=>(this.#renderer??=content=>this.html(content),this.#renderer(...args));setLayout=layout=>this.#layout=layout;getLayout=()=>this.#layout;setRenderer=renderer=>{this.#renderer=renderer};header=(name,value,options)=>{this.finalized&&(this.#res=createResponseInstance(this.#res.body,this.#res));let headers=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;value===void 0?headers.delete(name):options?.append?headers.append(name,value):headers.set(name,value)};status=status=>{this.#status=status};set=(key,value)=>{this.#var??=new Map,this.#var.set(key,value)};get=key=>this.#var?this.#var.get(key):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(data,arg,headers){let responseHeaders=this.#res?new Headers(this.#res.headers):this.#preparedHeaders;if(typeof arg=="object"&&arg.headers){responseHeaders??=new Headers;for(let[key,value]of new Headers(arg.headers))key==="set-cookie"?responseHeaders.append(key,value):responseHeaders.set(key,value)}if(headers){if(!responseHeaders){let count=0;for(let k in headers)if(++count>1||typeof headers[k]!="string"){responseHeaders=new Headers;break}}if(responseHeaders)for(let k in headers){let v=headers[k];if(typeof v=="string")responseHeaders.set(k,v);else{responseHeaders.delete(k);for(let v2 of v)responseHeaders.append(k,v2)}}}let status=typeof arg=="number"?arg:arg?.status??this.#status;return createResponseInstance(data,{status,headers:responseHeaders??headers})}newResponse=(...args)=>this.#newResponse(...args);body=(data,arg,headers)=>this.#newResponse(data,arg,headers);text=(text2,arg,headers)=>!this.#preparedHeaders&&!this.#status&&!arg&&!headers&&!this.finalized?new Response(text2):this.#newResponse(text2,arg,setDefaultContentType(TEXT_PLAIN,headers));json=(object5,arg,headers)=>this.#newResponse(JSON.stringify(object5),arg,setDefaultContentType("application/json",headers));html=(html2,arg,headers)=>{let res=html3=>this.#newResponse(html3,arg,setDefaultContentType("text/html; charset=UTF-8",headers));return typeof html2=="object"?resolveCallback(html2,HtmlEscapedCallbackPhase.Stringify,!1,{}).then(res):res(html2)};redirect=(location,status)=>{let locationString=String(location);return this.header("Location",/[^\x00-\xFF]/.test(locationString)?encodeURI(locationString):locationString),this.newResponse(null,status??302)};notFound=()=>(this.#notFoundHandler??=()=>createResponseInstance(),this.#notFoundHandler(this))};var compose=(middleware,onError,onNotFound)=>(context,next)=>{let index=-1;return dispatch(0);async function dispatch(i){if(i<=index)throw new Error("next() called multiple times");index=i;let res,isError=!1,handler;if(middleware[i]?(handler=middleware[i][0][0],context.req.routeIndex=i):handler=i===middleware.length&&next||void 0,handler)try{res=await handler(context,()=>dispatch(i+1))}catch(err){if(err instanceof Error&&onError)context.error=err,res=await onError(err,context),isError=!0;else throw err}else context.finalized===!1&&onNotFound&&(res=await onNotFound(context));return res&&(context.finalized===!1||isError)&&(context.res=res),context}};var METHODS=["get","post","put","delete","options","patch","query"],MESSAGE_MATCHER_IS_ALREADY_BUILT="Can not add a route since the matcher is already built.",UnsupportedPathError=class extends Error{};var COMPOSED_HANDLER="__COMPOSED_HANDLER";var notFoundHandler=c=>c.text("404 Not Found",404),errorHandler=(err,c)=>{if("getResponse"in err){let res=err.getResponse();return c.newResponse(res.body,res)}return console.error(err),c.text("Internal Server Error",500)},Hono=class Hono2{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#path="/";routes=[];constructor(options={}){[...METHODS,"all"].forEach(method=>{this[method]=(args1,...args)=>{let methodName=method.toUpperCase();return typeof args1=="string"?this.#path=args1:this.#addRoute(methodName,this.#path,args1),args.forEach(handler=>{this.#addRoute(methodName,this.#path,handler)}),this}}),this.on=(method,path,...handlers)=>{for(let p of[path].flat()){this.#path=p;for(let m of[method].flat()){let methodName=m.toUpperCase();for(let handler of handlers)this.#addRoute(methodName,this.#path,handler)}}return this},this.use=(arg1,...handlers)=>(typeof arg1=="string"?this.#path=arg1:(this.#path="*",handlers.unshift(arg1)),handlers.forEach(handler=>{this.#addRoute("ALL",this.#path,handler)}),this);let{strict,...optionsWithoutStrict}=options;Object.assign(this,optionsWithoutStrict),this.getPath=strict??!0?options.getPath??getPath:getPathNoStrict}#clone(){let clone2=new Hono2({router:this.router,getPath:this.getPath});return clone2.errorHandler=this.errorHandler,clone2.#notFoundHandler=this.#notFoundHandler,clone2.routes=this.routes,clone2}#notFoundHandler=notFoundHandler;errorHandler=errorHandler;route(path,app){let subApp=this.basePath(path);return app.routes.map(r=>{let handler;app.errorHandler===errorHandler?handler=r.handler:(handler=async(c,next)=>(await compose([],app.errorHandler)(c,()=>r.handler(c,next))).res,handler[COMPOSED_HANDLER]=r.handler),subApp.#addRoute(r.method,r.path,handler,r.basePath)}),this}basePath(path){let subApp=this.#clone();return subApp._basePath=mergePath(this._basePath,path),subApp}onError=handler=>(this.errorHandler=handler,this);notFound=handler=>(this.#notFoundHandler=handler,this);mount(path,applicationHandler,options){let replaceRequest,optionHandler;options&&(typeof options=="function"?optionHandler=options:(optionHandler=options.optionHandler,options.replaceRequest===!1?replaceRequest=request=>request:replaceRequest=options.replaceRequest));let getOptions=optionHandler?c=>{let options2=optionHandler(c);return Array.isArray(options2)?options2:[options2]}:c=>{let executionContext;try{executionContext=c.executionCtx}catch{}return[c.env,executionContext]};replaceRequest||=(()=>{let mergedPath=mergePath(this._basePath,path),pathPrefixLength=mergedPath==="/"?0:mergedPath.length;return request=>{let url2=new URL(request.url);return url2.pathname=this.getPath(request).slice(pathPrefixLength)||"/",new Request(url2,request)}})();let handler=async(c,next)=>{let res=await applicationHandler(replaceRequest(c.req.raw),...getOptions(c));if(res)return res;await next()};return this.#addRoute("ALL",mergePath(path,"*"),handler),this}#addRoute(method,path,handler,baseRoutePath){path=mergePath(this._basePath,path);let r={basePath:baseRoutePath!==void 0?mergePath(this._basePath,baseRoutePath):this._basePath,path,method,handler};this.router.add(method,path,[handler,r]),this.routes.push(r)}#handleError(err,c){if(err instanceof Error)return this.errorHandler(err,c);throw err}#dispatch(request,executionCtx,env2,method){if(method==="HEAD")return(async()=>new Response(null,await this.#dispatch(request,executionCtx,env2,"GET")))();let path=this.getPath(request,{env:env2}),matchResult=this.router.match(method,path),c=new Context(request,{path,matchResult,env:env2,executionCtx,notFoundHandler:this.#notFoundHandler});if(matchResult[0].length===1){let res;try{res=matchResult[0][0][0][0](c,async()=>{c.res=await this.#notFoundHandler(c)})}catch(err){return this.#handleError(err,c)}return res instanceof Promise?res.then(resolved=>resolved||(c.finalized?c.res:this.#notFoundHandler(c))).catch(err=>this.#handleError(err,c)):res??this.#notFoundHandler(c)}let composed=compose(matchResult[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let context=await composed(c);if(!context.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return context.res}catch(err){return this.#handleError(err,c)}})()}fetch=(request,...rest)=>this.#dispatch(request,rest[1],rest[0],request.method);request=(input,requestInit,Env,executionCtx)=>input instanceof Request?this.fetch(requestInit?new Request(input,requestInit):input,Env,executionCtx):(input=input.toString(),this.fetch(new Request(/^https?:\/\//.test(input)?input:`http://localhost${mergePath("/",input)}`,requestInit),Env,executionCtx));fire=()=>{addEventListener("fetch",event=>{event.respondWith(this.#dispatch(event.request,event,void 0,event.request.method))})}};var createNullObject=()=>Object.create(null);var emptyParam=[];function match(method,path){let matchers=this.buildAllMatchers(),match2=((method2,path2)=>{let matcher=matchers[method2]||matchers.ALL,staticMatch=matcher[2][path2];if(staticMatch)return staticMatch;let match3=path2.match(matcher[0]);if(!match3)return[[],emptyParam];let index=match3.indexOf("",1);return[matcher[1][index],match3]});return this.match=match2,match2(method,path)}var LABEL_REG_EXP_STR="[^/]+";var TAIL_WILDCARD_REG_EXP_STR="(?:|/.*)",PATH_ERROR=Symbol(),regExpMetaChars=new Set(".\\+*[^]$()");function compareKey(a,b){return a.length===1?b.length===1?a<b?-1:1:-1:b.length===1?1:a===".*"||a==="(?:|/.*)"?b==="(?:|/.*)"?-1:1:b===".*"||b==="(?:|/.*)"?-1:a==="[^/]+"?1:b==="[^/]+"?-1:a.length===b.length?a<b?-1:1:b.length-a.length}var Node=class Node2{#index;#varIndex;#children=createNullObject();insert(tokens,index,paramMap,context,isStatic){let node=this;for(let i=0,len=tokens.length;i<len;i++){let token=tokens[i],pattern=token.length===1?token==="*"?i===len-1?["","",".*"]:["","",LABEL_REG_EXP_STR]:null:token==="/*"?["","",TAIL_WILDCARD_REG_EXP_STR]:token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),nextNode;if(pattern){let name=pattern[1],regexpStr=pattern[2]||"[^/]+";if(name&&pattern[2]&&(regexpStr===".*"||(regexpStr=regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(regexpStr))||regexpStr.length===1&®ExpMetaChars.has(regexpStr)))throw PATH_ERROR;if(nextNode=node.#children[regexpStr],!nextNode){if(regexpStr!==".*"&®expStr!=="(?:|/.*)"){for(let k in node.#children)if((regexpStr.length>1||k.length>1)&&k!==".*"&&k!=="(?:|/.*)")throw PATH_ERROR}nextNode=node.#children[regexpStr]=new Node2}name!==""&&(nextNode.#varIndex??=context.varIndex++,paramMap.push([name,nextNode.#varIndex]))}else if(nextNode=node.#children[token],!nextNode){for(let k in node.#children)if(k.length>1&&k!==".*"&&k!=="(?:|/.*)")throw PATH_ERROR;nextNode=node.#children[token]=new Node2}node=nextNode}if(node.#index!==void 0)throw PATH_ERROR;node.#index=isStatic?-1:index}buildRegExpStr(){let strList=Object.keys(this.#children).sort(compareKey).map(k=>{let c=this.#children[k],childStr=c.buildRegExpStr();return childStr===""?"":(typeof c.#varIndex=="number"?`(${k})@${c.#varIndex}`:regExpMetaChars.has(k)?`\\${k}`:k)+childStr}).filter(Boolean);return typeof this.#index=="number"&&this.#index!==-1&&strList.unshift(`#${this.#index}`),strList.length===0?"":strList.length===1?strList[0]:"(?:"+strList.join("|")+")"}};var Trie=class{#context={varIndex:0};#root=new Node;#index=0;paths=createNullObject();insert(path,isStatic){if(isStatic){this.#root.insert(path.split(""),0,[],this.#context,!0);return}let paramAssoc=[],groups=[],markedPath=path;for(let i=0;;){let replaced=!1;if(markedPath=markedPath.replace(/\{[^}]+\}/g,m=>{let mark=`@\\${i}`;return groups[i]=[mark,m],i++,replaced=!0,mark}),!replaced)break}let tokens=markedPath.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=groups.length-1;i>=0;i--){let[mark]=groups[i];for(let j=tokens.length-1;j>=0;j--)if(tokens[j].indexOf(mark)!==-1){tokens[j]=tokens[j].replace(mark,groups[i][1]);break}}this.#root.insert(tokens,this.#index,paramAssoc,this.#context,!1),this.paths[path]=[this.#index++,paramAssoc]}buildRegExp(){let regexp=this.#root.buildRegExpStr();if(regexp==="")return[/^$/,[],[]];let captureIndex=0,indexReplacementMap=[],paramReplacementMap=[];return regexp=regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g,(_,handlerIndex,paramIndex)=>handlerIndex!==void 0?(indexReplacementMap[++captureIndex]=Number(handlerIndex),"$()"):(paramIndex!==void 0&&(paramReplacementMap[Number(paramIndex)]=++captureIndex),"")),[new RegExp(`^${regexp}`),indexReplacementMap,paramReplacementMap]}};var wildcardRegExpCache=createNullObject();function buildWildcardRegExp(path){return wildcardRegExpCache[path]??=new RegExp(`^${path.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(match2,metaChar)=>metaChar?`\\${metaChar}`:match2==="/*"?TAIL_WILDCARD_REG_EXP_STR:match2==="*"?".*":`/:${LABEL_REG_EXP_STR}`)}$`)}function findMiddleware(middleware,path){for(let k of Object.keys(middleware).sort((a,b)=>b.length-a.length))if(buildWildcardRegExp(k).test(path))return[...middleware[k]]}var RegExpRouter=class{name="RegExpRouter";#middleware;#routes;#tries;constructor(){this.#middleware={ALL:createNullObject()},this.#routes={ALL:createNullObject()},this.#tries={ALL:new Trie}}#insertPath(method,path){try{this.#tries[method].insert(path,!/\*|\/:/.test(path))}catch(e){throw e===PATH_ERROR?new UnsupportedPathError(path):e}}add(method,path,handler){let middleware=this.#middleware,routes=this.#routes;if(!middleware)throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);if(!middleware[method]){this.#tries[method]=new Trie;for(let handlerMap of[middleware,routes]){handlerMap[method]=createNullObject();for(let p in handlerMap.ALL)handlerMap[method][p]=[...handlerMap.ALL[p]],this.#insertPath(method,p)}}path==="/*"&&(path="*");let methods=method==="ALL"?Object.keys(middleware):[method];if(/\*$/.test(path)){let re=buildWildcardRegExp(path);for(let m of methods)middleware[m][path]||(this.#insertPath(m,path),middleware[m][path]=findMiddleware(middleware[m],path)||findMiddleware(middleware.ALL,path)||[]);for(let handlerMap of[middleware,routes])for(let m of methods)for(let p in handlerMap[m])re.test(p)&&handlerMap[m][p].push([handler,path]);return}let paths=checkOptionalParameter(path)||[path];for(let path2 of paths)for(let m of methods)routes[m][path2]||(this.#insertPath(m,path2),routes[m][path2]=findMiddleware(middleware[m],path2)||findMiddleware(middleware.ALL,path2)||[]),routes[m][path2].push([handler,path2])}match=match;buildAllMatchers(){let matchers=createNullObject();for(let method of Object.keys(this.#routes))matchers[method]=this.#buildMatcher(method);return this.#middleware=this.#routes=this.#tries=void 0,wildcardRegExpCache=createNullObject(),matchers}#buildMatcher(method){let middleware=this.#middleware[method],routes=this.#routes[method],trie=this.#tries[method],staticMap=createNullObject(),handlerData=[],[regexp,indexReplacementMap,paramReplacementMap]=trie.buildRegExp();for(let r of[middleware,routes])for(let path in r){let handlers=r[path],pathData=trie.paths[path];if(!pathData){staticMap[path]=[handlers.map(([h])=>[h,createNullObject()]),emptyParam];continue}handlerData[pathData[0]]=handlers.map(([h,handlerPath])=>[h,trie.paths[handlerPath][1].reduceRight((map,[key],i)=>(map[key]=paramReplacementMap[pathData[1][i][1]],map),createNullObject())])}return[regexp,indexReplacementMap.map(i=>handlerData[i]),staticMap]}};var SmartRouter=class{name="SmartRouter";#routers=[];#routes=[];constructor(init){this.#routers=init.routers}add(method,path,handler){if(!this.#routes)throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);this.#routes.push([method,path,handler])}match(method,path){if(!this.#routes)throw new Error("Fatal error");let routers=this.#routers,routes=this.#routes,len=routers.length,i=0,res;for(;i<len;i++){let router=routers[i];try{for(let i2=0,len2=routes.length;i2<len2;i2++)router.add(...routes[i2]);res=router.match(method,path)}catch(e){if(e instanceof UnsupportedPathError)continue;throw e}this.match=router.match.bind(router),this.#routers=[router],this.#routes=void 0;break}if(i===len)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,res}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw new Error("No active router has been determined yet.");return this.#routers[0]}};var emptyParams=createNullObject(),order=0,Node3=class Node4{#methods=[];#children=createNullObject();#patterns=[];#pattern;#params=emptyParams;insert(method,path,handler){let curNode=this,parts=splitRoutingPath(path),possibleKeys=new Set,i=0;for(let p of parts){let nextP=parts[++i],pattern=getPattern(p,nextP)||(nextP===void 0&&p&&p.indexOf("*")===p.length-1?p:null),isParam=Array.isArray(pattern),key=isParam?pattern[0]:pattern||p,child=curNode.#children[key]||=new Node4;pattern&&!child.#pattern&&(child.#pattern=pattern,curNode.#patterns.push(child)),curNode=child,isParam&&possibleKeys.add(pattern[1])}curNode.#methods.push({[method]:{handler,possibleKeys:[...possibleKeys],score:++order}})}#pushHandlerSets(handlerSets,node,method,nodeParams,params){for(let i=0,len=node.#methods.length;i<len;i++){let m=node.#methods[i],handlerSet=m[method]||m.ALL;if(handlerSet){handlerSet.params=createNullObject(),handlerSets.push(handlerSet);for(let i2=0,len2=handlerSet.possibleKeys.length;i2<len2;i2++){let key=handlerSet.possibleKeys[i2];handlerSet.params[key]=params?.[key]&&!i2?params[key]:nodeParams[key]??params?.[key]}}}}search(method,path){let handlerSets=[];this.#params=emptyParams;let curNodes=[this],parts=splitPath(path),curNodesQueue=[],len=parts.length,partOffsets=null;for(let i=0;i<len;i++){let part=parts[i],isLast=i===len-1,tempNodes=[];for(let j=0,len2=curNodes.length;j<len2;j++){let node=curNodes[j],nextNode=node.#children[part];nextNode&&(nextNode.#params=node.#params,isLast?(nextNode.#children["*"]&&this.#pushHandlerSets(handlerSets,nextNode.#children["*"],method,node.#params),this.#pushHandlerSets(handlerSets,nextNode,method,node.#params)):tempNodes.push(nextNode));for(let child of node.#patterns){let pattern=child.#pattern,params=node.#params===emptyParams?{}:{...node.#params};if(typeof pattern=="string"){(pattern==="*"||part.startsWith(pattern.slice(0,-1)))&&(this.#pushHandlerSets(handlerSets,child,method,node.#params),pattern==="*"&&(child.#params=params,tempNodes.push(child)));continue}let[,name,matcher]=pattern;if(!(!part&&matcher===!0)){if(matcher!==!0){if(!partOffsets){partOffsets=[];let offset=path[0]==="/"?1:0;for(let p=0;p<len;p++)partOffsets[p]=offset,offset+=parts[p].length+1}let restPathString=path.slice(partOffsets[i]),m=matcher.exec(restPathString);if(m){params[name]=m[0],this.#pushHandlerSets(handlerSets,child,method,node.#params,params),m[0].length===restPathString.length&&child.#children["*"]&&this.#pushHandlerSets(handlerSets,child.#children["*"],method,node.#params,params);for(let _ in child.#children){child.#params=params;let componentCount=m[0].match(/\//g)?.length??0;(curNodesQueue[componentCount]||=[]).push(child);break}continue}}(matcher===!0||matcher.test(part))&&(params[name]=part,isLast?(this.#pushHandlerSets(handlerSets,child,method,params,node.#params),child.#children["*"]&&this.#pushHandlerSets(handlerSets,child.#children["*"],method,params,node.#params)):(child.#params=params,tempNodes.push(child)))}}}let shifted=curNodesQueue.shift();curNodes=shifted?tempNodes.concat(shifted):tempNodes}return handlerSets[1]&&handlerSets.sort((a,b)=>a.score-b.score),[handlerSets.map(({handler,params})=>[handler,params])]}};var TrieRouter=class{name="TrieRouter";#node=new Node3;add(method,path,handler){for(let result of checkOptionalParameter(path)||[path])this.#node.insert(method,result,handler)}match(method,path){return this.#node.search(method,path)}};var Hono3=class extends Hono{constructor(options={}){super(options),this.router=options.router??new SmartRouter({routers:[new RegExpRouter,new TrieRouter]})}};init_origin();init_public_route();var FAVICON_CACHE_CONTROL="public, max-age=31536000, immutable",FAVICON_REDIRECT_CACHE_CONTROL="public, max-age=300";function protocolOf(value){return/^([a-z][a-z\d+.-]*):/i.exec(value)?.[1]?.toLowerCase()}function publicAssetPath(basePath,source){return`${basePath==="/"?"":basePath}/_mcp-use/public/${source.split("/").map(segment=>encodeURIComponent(segment)).join("/")}`}function isLocalPublicSource(source){return protocolOf(source)===void 0}function selectFaviconFromIcons(icons){return icons[0]}function assertLocalPublicSource(source,field){if(source.startsWith("/")||source.includes("\\")||source.includes("?")||source.includes("#")||source.split("/").some(segment=>segment===""||segment===".."))throw new TypeError(`${field} must be an http(s) URL, image data URL, or safe path relative to public/`)}function parseDataImage(source,field){let comma=source.indexOf(",");if(comma<0)throw new TypeError(`${field} must be a valid image data URL`);let metadata=source.slice(5,comma),payload=source.slice(comma+1),parts=metadata.split(";"),mimeType=parts[0]?.toLowerCase()??"";if(!mimeType.startsWith("image/"))throw new TypeError(`${field} data URL must use an image MIME type`);try{if(parts.includes("base64")){let binary2=atob(payload);return{mimeType,bytes:Uint8Array.from(binary2,character=>character.charCodeAt(0))}}return{mimeType,bytes:new TextEncoder().encode(decodeURIComponent(payload))}}catch{throw new TypeError(`${field} must be a valid image data URL`)}}function assertBrandingSource(source,field){if(typeof source!="string"||source.length===0)throw new TypeError(`${field} must be a non-empty string`);let protocol=protocolOf(source);if(protocol===void 0)return assertLocalPublicSource(source,field),source;if(protocol==="data")return parseDataImage(source,field),source;if(protocol!=="http"&&protocol!=="https")throw new TypeError(`${field} must be an http(s) URL, image data URL, or safe path relative to public/`);try{new URL(source)}catch{throw new TypeError(`${field} must be a valid absolute http(s) URL`)}return source}function normalizeServerBranding(config2){let websiteUrl;if(config2.websiteUrl!==void 0){if(typeof config2.websiteUrl!="string"||config2.websiteUrl.length===0)throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL");let parsed;try{parsed=new URL(config2.websiteUrl)}catch{throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL")}if(parsed.protocol!=="http:"&&parsed.protocol!=="https:")throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL");websiteUrl=config2.websiteUrl}let icons;if(config2.icons!==void 0){if(!Array.isArray(config2.icons))throw new TypeError("icons must be an array of MCP Icon objects");icons=Object.freeze(config2.icons.map((value,index)=>{if(typeof value!="object"||value===null)throw new TypeError(`icons[${index}] must be an MCP Icon object`);let icon=value,src=assertBrandingSource(icon.src,`icons[${index}].src`),mimeType=icon.mimeType;if(mimeType!==void 0&&(typeof mimeType!="string"||!mimeType.toLowerCase().startsWith("image/")))throw new TypeError(`icons[${index}].mimeType must be an image MIME type when provided`);let sizes=icon.sizes;if(sizes!==void 0&&(!Array.isArray(sizes)||sizes.some(size=>typeof size!="string"||size.length===0)))throw new TypeError(`icons[${index}].sizes must be an array of non-empty strings when provided`);let normalizedSizes=sizes===void 0?void 0:sizes.map(size=>size),theme=icon.theme;if(theme!==void 0&&theme!=="light"&&theme!=="dark")throw new TypeError(`icons[${index}].theme must be "light" or "dark" when provided`);return Object.freeze({src,...mimeType!==void 0&&{mimeType},...normalizedSizes!==void 0&&{sizes:Object.freeze(normalizedSizes)},...theme!==void 0&&{theme}})}))}let explicitFavicon=config2.favicon===void 0?void 0:assertBrandingSource(config2.favicon,"favicon"),inferred=explicitFavicon===void 0?selectFaviconFromIcons(icons??[]):void 0,favicon=explicitFavicon??inferred?.src,faviconMimeType=inferred?.mimeType??icons?.find(icon=>icon.src===explicitFavicon)?.mimeType;return Object.freeze({...favicon!==void 0&&{favicon},...faviconMimeType!==void 0&&{faviconMimeType},...icons!==void 0&&{icons},...websiteUrl!==void 0&&{websiteUrl}})}function resolveImplementationIcons(icons,request,basePath){return icons.map(icon=>({...icon,src:request!==void 0&&isLocalPublicSource(icon.src)?`${resolveAssetsBase(request)}${publicAssetPath(basePath,icon.src)}`:icon.src,...icon.sizes!==void 0&&{sizes:[...icon.sizes]}}))}function hasLocalBrandingAsset(branding){return branding.favicon!==void 0&&isLocalPublicSource(branding.favicon)||branding.icons?.some(icon=>isLocalPublicSource(icon.src))===!0}function createFaviconHandler(branding,options){let source=branding.favicon;if(source!==void 0)return async request=>{if(request.method!=="GET"&&request.method!=="HEAD")return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});if(new URL(request.url).pathname!=="/favicon.ico")return new Response("Not Found",{status:404});let protocol=protocolOf(source);if(protocol==="http"||protocol==="https")return new Response(null,{status:307,headers:{Location:source,"Cache-Control":FAVICON_REDIRECT_CACHE_CONTROL}});if(protocol==="data"){let data=parseDataImage(source,"favicon");return new Response(request.method==="HEAD"?null:data.bytes.buffer,{status:200,headers:{"Content-Type":branding.faviconMimeType??data.mimeType,"Cache-Control":FAVICON_CACHE_CONTROL,"X-Content-Type-Options":"nosniff"}})}let{join}=await import("path"),publicRoot=options.dev?join(options.projectRoot,"public"):join(options.projectRoot,".mcp-use/build/views/public"),diskPath=await resolvePublicFilePath(publicRoot,source);if(diskPath===null)return new Response("Not Found",{status:404,headers:{"Cache-Control":"no-store"}});let response=await servePublicFile(diskPath,{...options.deferCors===!0&&{deferCors:!0},...request.method==="HEAD"&&{head:!0}});return response.headers.set("Cache-Control",FAVICON_CACHE_CONTROL),response.headers.set("X-Content-Type-Options","nosniff"),branding.faviconMimeType!==void 0&&response.headers.set("Content-Type",branding.faviconMimeType),response}}function isOAuthProviderLike(value){if(typeof value!="object"||value===null)return!1;let provider=value;return typeof provider.createTokenVerifier=="function"&&typeof provider.mapAuthInfo=="function"&&typeof provider.oauthMetadata=="object"&&provider.oauthMetadata!==null}function assertServerConfig(config2){if(config2.mixedAuth!==void 0&&typeof config2.mixedAuth!="boolean")throw new TypeError("mixedAuth must be a boolean");if(config2.mixedAuth===!0&&!isOAuthProviderLike(config2.oauth))throw new TypeError("mixedAuth requires an OAuth provider; set oauth on the server");if(config2.basePath!==void 0){if(typeof config2.basePath!="string")throw new TypeError("basePath must be an absolute URL pathname without empty segments, trailing slash, query, fragment, or whitespace");let{basePath}=config2;if(!basePath.startsWith("/")||basePath.includes("?")||basePath.includes("#")||/\s/.test(basePath)||basePath.includes("//")||basePath.length>1&&basePath.endsWith("/"))throw new TypeError("basePath must be an absolute URL pathname without empty segments, trailing slash, query, fragment, or whitespace")}if(config2.port!==void 0&&(typeof config2.port!="number"||!Number.isInteger(config2.port)||config2.port<0||config2.port>65535))throw new TypeError("port must be an integer between 0 and 65535");if(config2.skills!==void 0&&typeof config2.skills!="boolean"){if(typeof config2.skills!="object"||config2.skills===null||Array.isArray(config2.skills))throw new TypeError("skills must be a boolean or configuration object");let directory=config2.skills.directory;if(directory!==void 0&&typeof directory!="string")throw new TypeError("skills.directory must be a string when provided")}}var DEFAULT_LISTEN_HOST="127.0.0.1";function resolveListenHost(explicitHost,configuredHost,env2=process.env){if(explicitHost!==void 0)return explicitHost;let envHost=env2.HOST?.trim();return envHost!==void 0&&envHost!==""?envHost:configuredHost??DEFAULT_LISTEN_HOST}function resolveListenPort(explicitPort,configuredPort,env2=process.env){if(explicitPort!==void 0)return explicitPort;let envPort=parsePort(env2.PORT);return envPort!==void 0?envPort:configuredPort??3e3}function parsePort(value){if(value===void 0||value.trim()==="")return;let port=Number(value);return Number.isInteger(port)&&port>=0&&port<=65535?port:void 0}import{isBufferedResponse}from"#mcp-use-buffered-response";function toNodeHandler(handler,opts){return async(req,res,parsedBody)=>{typeof parsedBody=="function"&&(parsedBody=void 0);let finished=!1,abort=new AbortController;res.on("close",()=>{finished||abort.abort()}),res.destroyed===!0&&abort.abort();let request,response;try{request=await toWebRequest(req,parsedBody,{signal:abort.signal}),response=await handler.fetch(request,{...req.auth!==void 0&&{authInfo:req.auth},...parsedBody!==void 0&&{parsedBody}})}catch(error3){try{opts?.onerror?.(error3 instanceof Error?error3:new Error(String(error3)))}catch{}response=internalServerErrorResponse2(echoableRequestId2(parsedBody))}let headers={},setCookies=response.headers.getSetCookie?.();for(let[name,value]of response.headers){if(name==="set-cookie"&&setCookies?.length){headers[name]=setCookies;continue}headers[name]=value}if(res.writeHead(response.status,headers),response.body===null){finished=!0,res.end();return}if(isBufferedResponse(response,request)){try{let bytes=new Uint8Array(await response.arrayBuffer());finished=!0,res.end(bytes)}catch{finished=!0,res.end()}return}let drainResolve,releaseDrainWait=()=>{drainResolve?.(),drainResolve=void 0},waitForDrain=()=>new Promise(resolve=>{drainResolve=resolve});res.on("drain",releaseDrainWait);let closed=new Promise(resolve=>{abort.signal.addEventListener("abort",()=>resolve(),{once:!0})});try{for await(let chunk of response.body){if(abort.signal.aborted)break;let bytes=chunk instanceof Uint8Array?chunk:new Uint8Array(chunk);res.write(bytes)===!1&&await Promise.race([waitForDrain(),closed])}}catch{}finished=!0,res.end()}}async function toWebRequest(req,parsedBody,options){let method=(req.method??"GET").toUpperCase(),url2=`http://${singleHeaderValue(req.headers.host)??singleHeaderValue(req.headers[":authority"])??"localhost"}${req.url??"/"}`,headers=new Headers;for(let[name,value]of Object.entries(req.headers))if(!(value===void 0||name.startsWith(":")))if(Array.isArray(value))for(let item of value)headers.append(name,item);else headers.set(name,value);let body;if(method!=="GET"&&method!=="HEAD")if(parsedBody===void 0){let decoder=new TextDecoder,collected="";for await(let chunk of req)collected+=typeof chunk=="string"?chunk:decoder.decode(chunk,{stream:!0});collected+=decoder.decode(),collected.length>0&&(body=collected)}else{let serialized=JSON.stringify(parsedBody);headers.delete("content-encoding"),headers.delete("transfer-encoding"),serialized===void 0?headers.delete("content-length"):(body=serialized,headers.set("content-length",String(new TextEncoder().encode(serialized).byteLength)))}return new Request(url2,{method,headers,...options?.signal!==void 0&&{signal:options.signal},...body!==void 0&&{body}})}function singleHeaderValue(value){return Array.isArray(value)?value[0]:value}function echoableRequestId2(body){if(body===null||typeof body!="object"||Array.isArray(body))return null;let{method,id}=body;return typeof method!="string"?null:typeof id=="string"||typeof id=="number"?id:null}function internalServerErrorResponse2(id){return Response.json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id},{status:500})}init_dist();init_fetch_app();init_dist();var UI_EXTENSION_ID="io.modelcontextprotocol/ui",UI_MIME_TYPE="text/html;profile=mcp-app",UI_RESOURCE_URI_PREFIX="ui://views/";var UI_RESOURCE_URI_META_KEY="ui/resourceUri";function viewResourceUri(viewName){return`${UI_RESOURCE_URI_PREFIX}${viewName}.html`}var clientCapabilitiesByRequest=new WeakMap;function stashClientCapabilities(request,capabilities){clientCapabilitiesByRequest.set(request,capabilities)}function extractClientCapabilitiesFromBody(body){if(typeof body!="object"||body===null)return;let params=body.params;if(typeof params!="object"||params===null)return;let meta2=params._meta;if(typeof meta2!="object"||meta2===null)return;let capabilities=meta2[CLIENT_CAPABILITIES_META_KEY];if(!(typeof capabilities!="object"||capabilities===null))return capabilities}function supportsViews(capabilities){let extensions=capabilities?.extensions;if(extensions===void 0)return!1;let uiExtension=extensions[UI_EXTENSION_ID];if(typeof uiExtension!="object"||uiExtension===null)return!1;let mimeTypes=uiExtension.mimeTypes;return Array.isArray(mimeTypes)?mimeTypes.includes(UI_MIME_TYPE):!1}function requireOAuthAuthInfo(authInfo){if(authInfo===void 0||authInfo.extra===void 0||authInfo.expiresAt===void 0)throw new Error("OAuth callback did not receive mapped AuthInfo.extra")}function stringValue(value){return typeof value=="string"?value:void 0}function coordinateValue(value){return typeof value=="string"||typeof value=="number"&&Number.isFinite(value)?value:void 0}function normalizeUserContext(meta2){if(meta2===void 0)return;let locale=stringValue(meta2["openai/locale"])??stringValue(meta2["webplus/i18n"]),userAgent=stringValue(meta2["openai/userAgent"]),subject=stringValue(meta2["openai/subject"]),conversationId=stringValue(meta2["openai/session"]),organizationId=stringValue(meta2["openai/organization"]),rawLocation=meta2["openai/userLocation"],location;if(typeof rawLocation=="object"&&rawLocation!==null&&!Array.isArray(rawLocation)){let values=rawLocation,normalized={city:stringValue(values.city),region:stringValue(values.region),country:stringValue(values.country),timezone:stringValue(values.timezone),latitude:coordinateValue(values.latitude),longitude:coordinateValue(values.longitude)},entries=Object.entries(normalized).filter(entry=>entry[1]!==void 0);entries.length>0&&(location=Object.fromEntries(entries))}if(!(locale===void 0&&userAgent===void 0&&location===void 0&&subject===void 0&&conversationId===void 0&&organizationId===void 0))return{...locale!==void 0&&{locale},...userAgent!==void 0&&{userAgent},...location!==void 0&&{location},...subject!==void 0&&{subject},...conversationId!==void 0&&{conversationId},...organizationId!==void 0&&{organizationId}}}function requestEnvelope(ctx){return ctx.mcpReq.envelope}function requestClientInfo(ctx){return{...requestEnvelope(ctx)?.[CLIENT_INFO_META_KEY]??{}}}function toClientContext(ctx){let capabilities={...requestEnvelope(ctx)?.[CLIENT_CAPABILITIES_META_KEY]??{}},info=requestClientInfo(ctx),user=normalizeUserContext(ctx.mcpReq._meta);return{can(capability){return Object.hasOwn(capabilities,capability)},capabilities(){return{...capabilities}},extension(id){let settings=capabilities.extensions?.[id];return settings===void 0?void 0:{...settings}},info(){return{...info}},user(){return user===void 0?void 0:{...user,...user.location!==void 0&&{location:{...user.location}}}},supportsViews(){return supportsViews(capabilities)}}}function toRequestContext(ctx){let rawRequest=ctx.http?.req,http=rawRequest===void 0?void 0:getRequestBag(rawRequest).honoContext,request=http?.req??(rawRequest===void 0?void 0:new HonoRequest(rawRequest)),additions={signal:ctx.mcpReq.signal,...request!==void 0&&{request},...ctx.mcpReq.inputResponses!==void 0&&{inputResponses:ctx.mcpReq.inputResponses},client:toClientContext(ctx),requestState:()=>ctx.mcpReq.requestState(),async sendNotification(method,params){await ctx.mcpReq.notify({method,...params!==void 0&&{params}})},async reportProgress(progress,total,message){let progressToken=ctx.mcpReq._meta?.progressToken;return progressToken===void 0?!1:(await ctx.mcpReq.notify({method:"notifications/progress",params:{progressToken,progress,...total!==void 0&&{total},...message!==void 0&&{message}}}),!0)},async sendLog(level,data,logger){await ctx.mcpReq.notify({method:"notifications/message",params:{level,data,...logger!==void 0&&{logger}}})}};return http!==void 0?Object.assign(http,additions):{...additions,...request!==void 0&&{req:request}}}function toAuthenticatedRequestContext(ctx){let authInfo=ctx.http?.authInfo;return requireOAuthAuthInfo(authInfo),Object.assign(toRequestContext(ctx),{auth:{user:authInfo.extra.user,payload:authInfo.extra.payload,accessToken:authInfo.token,scopes:[...authInfo.scopes],permissions:[...authInfo.extra.permissions],...authInfo.clientId.length>0&&{clientId:authInfo.clientId},expiresAt:authInfo.expiresAt,...authInfo.resource!==void 0&&{resource:authInfo.resource}}})}init_dist();function isReadResourceResult(result){return"contents"in result&&Array.isArray(result.contents)}function isGetPromptResult(result){return"messages"in result&&Array.isArray(result.messages)}function toResourceResult(result,uri){if(isReadResourceResult(result))return result;let mime=result._meta&&typeof result._meta=="object"&&typeof result._meta.mimeType=="string"?result._meta.mimeType:void 0,contents=[];for(let block of result.content??[]){let mapped=contentBlockToResourceContents(block,uri,mime);mapped!==void 0&&contents.push(mapped)}return contents.length===0&&result.structuredContent!==void 0&&contents.push({uri,mimeType:"application/json",text:JSON.stringify(result.structuredContent)}),contents.length===0&&contents.push({uri,mimeType:"text/plain",text:""}),{contents}}function contentBlockToResourceContents(block,uri,mimeHint){if(block.type==="text")return{uri,mimeType:mimeHint??"text/plain",text:block.text};if(block.type==="image"||block.type==="audio")return{uri,mimeType:block.mimeType,blob:block.data};if(block.type==="resource")return{...block.resource}}function toPromptResult(result){if(isInputRequiredResult(result)||isGetPromptResult(result))return result;let messages=(result.content??[]).map(content=>({role:"user",content}));return messages.length===0&&result.structuredContent!==void 0&&messages.push({role:"user",content:{type:"text",text:JSON.stringify(result.structuredContent)}}),messages.length===0&&messages.push({role:"user",content:{type:"text",text:""}}),{messages}}init_fetch_app();import{inheritBufferedResponse}from"#mcp-use-buffered-response";var DEFAULT_METHODS=["GET","HEAD","POST","OPTIONS"],DEFAULT_ALLOWED_HEADERS=["Content-Type","Authorization","mcp-protocol-version","mcp-method","mcp-name"];function resolveAllowedOrigin(origin,requestOrigin){return origin===void 0?requestOrigin:typeof origin=="function"?origin(requestOrigin):origin==="*"?"*":Array.isArray(origin)?requestOrigin!==null&&origin.includes(requestOrigin)?requestOrigin:null:origin}function corsHeaders(options,request){if(request.headers.has("Access-Control-Allow-Origin"))return;let requestOrigin=request.headers.get("Origin"),allowedOrigin=resolveAllowedOrigin(options.origin,requestOrigin);if(allowedOrigin===null)return;let headers={"Access-Control-Allow-Origin":allowedOrigin,"Access-Control-Allow-Methods":options.methods.join(", "),"Access-Control-Allow-Headers":options.allowedHeaders.join(", ")};return options.credentials&&(headers["Access-Control-Allow-Credentials"]="true"),allowedOrigin!=="*"&&(headers.Vary="Origin"),headers}function mergeCorsHeaders(response,headers){if(response.headers.has("Access-Control-Allow-Origin"))return response;let merged=new Headers(response.headers);return new Headers(headers).forEach((value,key)=>{merged.set(key,value)}),inheritBufferedResponse(response,new Response(response.body,{status:response.status,statusText:response.statusText,headers:merged}))}function corsFetchMiddleware(options){if(!(options.enabled!==!1))return async(_request,next)=>next();let resolved={...options.origin!==void 0&&{origin:options.origin},methods:options.methods??DEFAULT_METHODS,allowedHeaders:options.allowedHeaders??DEFAULT_ALLOWED_HEADERS,credentials:options.credentials??!1};return async(request,next)=>{let headers=corsHeaders(resolved,request);if(headers===void 0)return next();if(request.method==="OPTIONS")return new Response(null,{status:204,headers});let response=await next();return mergeCorsHeaders(response,headers)}}function isGlobalCorsEnabled(cors){return cors!==void 0&&cors.enabled!==!1}init_auth_CUe6YdwF();init_dist();var MCP_MIDDLEWARE_METHODS=["tools/call","tools/list","resources/read","resources/list","prompts/get","prompts/list"];function withMcpMiddlewareParams(request,params){if(typeof request!="object"||request===null||Array.isArray(request))throw new TypeError("[mcp-use] MCP middleware received an invalid downstream request");return{...request,params}}function createMcpMiddlewareEntry(pattern,handler){let normalizedPattern=normalizeMcpMiddlewarePattern(pattern),invoke2=handler;if(normalizedPattern!=="*"&&!isMcpMiddlewareMethod(normalizedPattern))throw new TypeError(`Unsupported MCP middleware pattern "${pattern}". Use an exact MCP method or "mcp:*".`);return normalizedPattern==="*"?{pattern:normalizedPattern,handler:async(ctx,next)=>{let downstreamCalled=!1,downstreamResult;if(await invoke2(ctx,async()=>{downstreamResult=await next(),downstreamCalled=!0}),!downstreamCalled)throw new Error(`Wildcard MCP middleware "${normalizedPattern}" must call next()`);return downstreamResult}}:{pattern:normalizedPattern,handler:(ctx,next)=>invoke2(ctx,next)}}function createMcpEventListenerEntry(pattern,handler){let{pattern:normalizedPattern,phase}=parseMcpPattern(pattern),invoke2=handler;return{pattern:normalizedPattern,phase,handler:(ctx,result)=>invoke2(ctx,result)}}function matchesPattern(pattern,method){if(pattern==="*")return!0;if(pattern.endsWith("/*")){let prefix=pattern.slice(0,-1);return method.startsWith(prefix)}return pattern===method}function isMcpMiddlewareMethod(value){return MCP_MIDDLEWARE_METHODS.some(method=>method===value)}function composeMiddleware(entries,method,innerFn){let matching=entries.filter(entry=>matchesPattern(entry.pattern,method));return matching.length===0?_ctx=>innerFn():ctx=>{let index=-1,dispatch=i=>i<=index?Promise.reject(new Error("next() called multiple times")):(index=i,i===matching.length?innerFn():matching[i].handler(ctx,()=>dispatch(i+1)));return dispatch(0)}}function freezeMiddlewareContext(ctx){return Object.freeze({method:ctx.method,params:Object.freeze({...ctx.params}),...ctx.request!==void 0&&{request:ctx.request},...ctx.req!==void 0&&{req:ctx.req},...ctx.session!==void 0&&{session:Object.freeze({...ctx.session})},...ctx.auth!==void 0&&{auth:ctx.auth},state:new Map(ctx.state)})}async function runMcpOperation(middlewares,events,method,ctx,innerFn){dispatchMcpEvents(events,method,"before",ctx);let result=await composeMiddleware(middlewares,method,innerFn)(ctx);return assertValidMiddlewareResult(method,result),dispatchMcpEvents(events,method,"complete",ctx,result),result}function assertValidMiddlewareResult(method,result){if((method==="tools/call"||method==="resources/read"||method==="prompts/get")&&isInputRequiredResult(result))return;let validation=(()=>{switch(method){case"tools/call":return assertArrayProperty(method,result,"content"),CallToolResultSchema.safeParse(result);case"tools/list":return assertArrayResult(method,result),ListToolsResultSchema.safeParse({tools:result});case"resources/read":return assertArrayProperty(method,result,"contents"),ReadResourceResultSchema.safeParse(result);case"resources/list":return assertArrayResult(method,result),ListResourcesResultSchema.safeParse({resources:result});case"prompts/get":return assertArrayProperty(method,result,"messages"),GetPromptResultSchema.safeParse(result);case"prompts/list":return assertArrayResult(method,result),ListPromptsResultSchema.safeParse({prompts:result});default:throw new TypeError(`Unsupported MCP middleware method "${method}"`)}})();if(!validation.success)throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: ${validation.error.message}`)}function assertArrayResult(method,result){if(!Array.isArray(result))throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: expected an array`)}function assertArrayProperty(method,result,property){if(typeof result!="object"||result===null||!Array.isArray(result[property]))throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: expected a ${property} array`)}function dispatchMcpEvents(events,method,phase,ctx,result){let frozen=freezeMiddlewareContext(ctx);for(let entry of events)if(!(entry.phase!==phase||!matchesPattern(entry.pattern,method)))try{entry.handler(frozen,result)}catch(error3){console.error(`[mcp-use] MCP event listener for "${entry.pattern}" (${phase}) threw:`,error3)}}function parseMcpPattern(raw2){let pattern=raw2.startsWith("mcp:")?raw2.slice(4):raw2;return pattern.endsWith(":complete")?{pattern:pattern.slice(0,-9),phase:"complete"}:{pattern,phase:"before"}}function normalizeMcpMiddlewarePattern(raw2){return raw2.startsWith("mcp:")?raw2.slice(4):raw2}init_dist();init_fetch_app();import{isBufferedResponse as isBufferedResponse2,trackBufferedResponse}from"#mcp-use-buffered-response";function colorsEnabled(){return typeof process>"u"||process.env?.NO_COLOR!==void 0?!1:process.stdout?.isTTY===!0}function ansi(open,close){return text2=>colorsEnabled()?`\x1B[${open}m${text2}\x1B[${close}m`:text2}var bold=ansi(1,22),dim=ansi(2,22),red=ansi(31,39),green=ansi(32,39),yellow=ansi(33,39),blue=ansi(34,39),magenta=ansi(35,39),cyan=ansi(36,39),gray=ansi(90,39);function resolveLogLevel(configured){let raw2=typeof process>"u"?void 0:process.env?.MCP_USE_LOG_LEVEL?.toLowerCase();return raw2==="info"||raw2==="debug"||raw2==="trace"?raw2:configured??"info"}function formatClientInfo(info){if(!(info===void 0||typeof info.name!="string"))return typeof info.version=="string"&&info.version!==""?`${info.name}/${info.version}`:info.name}var detailFormatters={initialize:p=>({subject:formatClientInfo(p.clientInfo)}),ping:()=>({}),"server/discover":()=>({}),"completion/complete":p=>({subject:p.ref.type==="ref/prompt"?p.ref.name:p.ref.uri,input:p.argument}),"logging/setLevel":p=>({subject:p.level}),"prompts/get":p=>({subject:p.name,input:p.arguments}),"prompts/list":()=>({}),"resources/list":()=>({}),"resources/templates/list":()=>({}),"resources/read":p=>({subject:p.uri}),"resources/subscribe":p=>({subject:p.uri}),"resources/unsubscribe":p=>({subject:p.uri}),"subscriptions/listen":()=>({}),"tools/call":p=>({subject:p.name,input:p.arguments}),"tools/list":()=>({}),"sampling/createMessage":()=>({}),"elicitation/create":()=>({}),"roots/list":()=>({})};function isKnownMethod(method){return Object.prototype.hasOwnProperty.call(detailFormatters,method)}function formatDetail(message){if(!isKnownMethod(message.method))return{};try{let formatter=detailFormatters[message.method],detail=formatter(message.params);return typeof detail.subject=="string"||detail.subject===void 0?detail:{}}catch{return{}}}var INLINE_JSON_MAX_LENGTH=80;function inlineJson(value){let text2;try{text2=JSON.stringify(value)??String(value)}catch{text2=String(value)}return text2.length>INLINE_JSON_MAX_LENGTH?`${text2.slice(0,INLINE_JSON_MAX_LENGTH)}...`:text2}function formatClientIdentity(message){let meta2=message.params?._meta;if(meta2===void 0)return;let info=meta2[CLIENT_INFO_META_KEY];if(!(typeof info!="object"||info===null||typeof info.name!="string"))return formatClientInfo(info)}function formatMcpClient(message){let modern=formatClientIdentity(message);if(modern!==void 0)return modern;if(message.method==="initialize")try{return formatClientInfo(message.params.clientInfo)}catch{return}}function sanitize(text2){return text2.replace(/[\u0000-\u001F\u007F-\u009F]+/g," ")}function methodStyle(method){return method.startsWith("tools/")?cyan:method.startsWith("resources/")?green:method.startsWith("prompts/")?magenta:method==="initialize"||method==="ping"?gray:blue}function describeRequest(httpMethod,pathname,mcpPath,body){if(pathname!==mcpPath)return{method:httpMethod,client:void 0,mcpRequest:void 0,streaming:!1};let requests=Array.isArray(body)?body.filter(isJSONRPCRequest):isJSONRPCRequest(body)?[body]:[],mcpRequest=requests[0];return mcpRequest===void 0?{method:httpMethod,client:void 0,mcpRequest:void 0,streaming:!1}:{method:requests.length===1?sanitize(mcpRequest.method):`batch(${requests.map(request=>sanitize(request.method)).join(",")})`,client:formatMcpClient(mcpRequest)??"unknown",mcpRequest,streaming:mcpRequest.method==="subscriptions/listen"}}var REDACTED_HEADERS=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-api-key"]);function redactHeaders(headers){return Object.fromEntries(Object.entries(headers).map(([name,value])=>[name,REDACTED_HEADERS.has(name.toLowerCase())?"[REDACTED]":value]))}async function extractResponseOutcome(res,request){if(!res.body)return{errorMessage:null};let text2;try{let wasBuffered=isBufferedResponse2(res,request),clone2=res.clone();wasBuffered&&trackBufferedResponse(request,res),text2=await clone2.text()}catch{return{errorMessage:null}}if(!text2)return{errorMessage:null};let isSse=(res.headers.get("content-type")??"").includes("text/event-stream"),payloads=[],tryParse=raw2=>{try{payloads.push(JSON.parse(raw2))}catch{}};if(isSse){for(let line of text2.split(/\r?\n/))if(line.startsWith("data:")){let data=line.slice(5).trim();data&&tryParse(data)}}else tryParse(text2);let result;for(let payload of payloads){if(payload===null||typeof payload!="object")continue;let message=payload;if(typeof message.error?.message=="string")return{errorMessage:message.error.message};if(message.result?.isError===!0){let textBlock=(Array.isArray(message.result.content)?message.result.content:[]).find(b=>b?.type==="text"&&typeof b.text=="string");return{errorMessage:textBlock?String(textBlock.text):"tool error"}}"result"in message&&(result=message.result)}return{errorMessage:null,result}}function compactToolResult(result){if(result===null||typeof result!="object")return result;let{structuredContent,content}=result;if(structuredContent!==void 0)return structuredContent;if(Array.isArray(content)){let[block]=content;if(content.length===1&&block?.type==="text")return block.text}return content}function formatForDump(value){function truncate(val){return typeof val=="string"&&val.length>100?`${val.slice(0,100)}...`:Array.isArray(val)?val.map(truncate):val!==null&&typeof val=="object"?Object.fromEntries(Object.entries(val).map(([k,v])=>[k,truncate(v)])):val}try{return JSON.stringify(truncate(value),null,2)}catch{return String(value)}}var DUMP_BODY_MAX_LENGTH=1e4;async function printTraceDump(response,requestHeaders,requestBody,readResponseBody){console.log(`
|
|
766
766
|
${cyan("=".repeat(80))}`),console.log(bold(cyan("[TRACE] Request Details"))),console.log(cyan("-".repeat(80))),Object.keys(requestHeaders).length>0&&(console.log(yellow("Request Headers:")),console.log(formatForDump(redactHeaders(requestHeaders)))),requestBody!==void 0&&(console.log(yellow("Request Body:")),console.log(typeof requestBody=="string"?requestBody:formatForDump(requestBody)));let responseHeaders={};if(response.headers.forEach((value,key)=>{responseHeaders[key]=value}),Object.keys(responseHeaders).length>0&&(console.log(yellow("Response Headers:")),console.log(formatForDump(redactHeaders(responseHeaders)))),!readResponseBody)console.log(`${yellow("Response Body:")} (streaming \u2014 not dumped)`);else if(response.body===null)console.log(`${yellow("Response Body:")} (no body)`);else try{let text2=await response.clone().text();if(text2.length===0)console.log(`${yellow("Response Body:")} (empty)`);else{console.log(yellow("Response Body:"));try{console.log(formatForDump(JSON.parse(text2)))}catch{console.log(text2.length>DUMP_BODY_MAX_LENGTH?`${text2.slice(0,DUMP_BODY_MAX_LENGTH)}
|
|
767
767
|
... (truncated, ${text2.length-DUMP_BODY_MAX_LENGTH} more characters)`:text2)}}}catch{console.log(`${yellow("Response Body:")} (unable to read)`)}console.log(`${cyan("=".repeat(80))}
|
|
768
|
-
`)}function styleStatus(status){let text2=String(status);return status>=500?magenta(text2):status>=400?red(text2):status>=300?yellow(text2):green(text2)}function isNoisyRequest(httpMethod,pathname){return httpMethod!=="GET"&&httpMethod!=="HEAD"?!1:pathname.endsWith("/favicon.ico")}function formatRequestLogLine(line){let{description,detail}=line;return[...line.prefix===void 0?[]:[bold(line.prefix)],methodStyle(description.method)(description.method),...detail?.subject===void 0?[]:[bold(sanitize(detail.subject))],line.pathname,styleStatus(line.status),...description.client===void 0?[]:[dim(`client=${sanitize(description.client)}`)],dim(`${line.durationMs}ms`),...line.suffix].join(" ")}function requestLogger(options={}){return options.enabled===!1?(_request,next)=>next():async(request,next)=>{let level=resolveLogLevel(options.level),startedAt=Date.now(),httpMethod=request.method,pathname=new URL(request.url).pathname;if(isNoisyRequest(httpMethod,pathname))return next();let requestHeaders={};level==="trace"&&request.headers.forEach((value,key)=>{requestHeaders[key]=value});let requestBody;if(httpMethod!=="GET"&&httpMethod!=="HEAD"){let parsedBody=getRequestBag(request).parsedBody;if(parsedBody!==void 0)requestBody=parsedBody;else try{requestBody=await request.clone().json(),(request.headers.get("content-type")??"").includes("application/json")&&(getRequestBag(request).parsedBody=requestBody)}catch{}}let description=describeRequest(httpMethod,pathname,options.mcpPath,requestBody),logLine=(status,detail2,suffix2=[])=>{console.log(formatRequestLogLine({prefix:options.prefix,description,detail:detail2,pathname,status,durationMs:Date.now()-startedAt,suffix:suffix2}))},response;try{response=await next()}catch(error3){throw logLine(500,void 0,[red(`ERROR ${sanitize(error3 instanceof Error?error3.message:String(error3))}`)]),error3}let detail=description.mcpRequest===void 0?void 0:formatDetail(description.mcpRequest),suffix=[];if(description.mcpRequest!==void 0&&detail!==void 0){let echoPayloads=level!=="info";echoPayloads&&detail.input!==void 0&&suffix.push(inlineJson(detail.input));let outcome=description.streaming?{errorMessage:null}:await extractResponseOutcome(response,request);echoPayloads&&description.mcpRequest.method==="tools/call"&&outcome.errorMessage===null&&outcome.result!==void 0&&suffix.push(dim("->"),inlineJson(compactToolResult(outcome.result))),outcome.errorMessage!==null?suffix.push(red(`ERROR ${sanitize(outcome.errorMessage)}`)):response.status>=400&&suffix.push(red(`ERROR (HTTP ${response.status})`))}return logLine(response.status,detail,suffix),level==="trace"&&await printTraceDump(response,requestHeaders,requestBody,!description.streaming),response}}init_dist();init_fetch_app();function createMcpMount(factory,options={}){let{path="/mcp",handler:handlerOptions,authInfo:getAuthInfo}=options,legacyMode=handlerOptions?.legacy??"stateless",handler=createMcpHandler(factory,{legacy:"stateless",...handlerOptions});return{handler,fetch:async request=>{if(!matchesPath(request,path))return new Response("Not Found",{status:404});if(legacyMode==="stateless"){let method=request.method.toUpperCase();if(method==="GET"||method==="DELETE"||method==="HEAD")return new Response(null,{status:204})}let bag=getRequestBag(request),parsedBody=bag.parsedBody;if(parsedBody===void 0)try{parsedBody=await request.clone().json()}catch{}let capabilities=extractClientCapabilitiesFromBody(parsedBody);capabilities!==void 0&&stashClientCapabilities(request,capabilities);let authInfo=getAuthInfo?.(request)??bag.authInfo,response=await handler.fetch(request,{...parsedBody!==void 0&&{parsedBody},...authInfo!==void 0&&{authInfo}});return response.headers.get("content-type")?.toLowerCase().includes("application/json")?"Bun"in globalThis&&response.body!==null?new Response(await response.arrayBuffer(),{status:response.status,statusText:response.statusText,headers:response.headers}):trackBufferedResponse(request,response):response}}}init_dist();function createPrefixCompletion(values){let strings=values.map(String);return value=>{let prefix=String(value??"").toLowerCase();return strings.filter(candidate=>candidate.toLowerCase().startsWith(prefix))}}function completable2(schema2,complete){return typeof complete=="function"?completable(schema2,(value,context)=>complete(String(value??""),context)):completable(schema2,createPrefixCompletion(complete))}function normalizeCompletions(completions){let normalized=Object.create(null);for(let[variable,completer]of Object.entries(completions))completer!==void 0&&(normalized[variable]=Array.isArray(completer)?createPrefixCompletion(completer):completer);return normalized}init_dist();var HTTP_METHODS=["get","put","post","delete","options","head","patch","trace"];function registerOpenAPITools(server,options){let operations=collectOperations(options.spec,options),names=createToolNames(operations),baseUrl=operations.length>0?resolveBaseUrl(options):void 0;for(let[index,operation]of operations.entries()){let name=names[index];if(name===void 0||baseUrl===void 0)continue;let inputBindings=createInputBindings(operation);server.tool({name,description:createToolDescription(operation),inputSchema:createToolInputSchema(options.spec,operation,inputBindings)},async params=>callOpenAPIOperation(operation,params,options,inputBindings,baseUrl))}}function collectOperations(spec,options){let collected=[];for(let[path,pathItemOrRef]of Object.entries(spec.paths??{})){let pathItem=resolveRef(spec,pathItemOrRef);if(pathItem===void 0||isReferenceObject(pathItem))continue;let pathParameters=resolveParameters(spec,pathItem.parameters);for(let method of HTTP_METHODS){let operationOrRef=pathItem[method];if(operationOrRef===void 0)continue;let operation=resolveRef(spec,operationOrRef);if(operation===void 0||isReferenceObject(operation))continue;let operationParameters=resolveParameters(spec,operation.parameters),requestBody=operation.requestBody===void 0?void 0:resolveRef(spec,operation.requestBody),item={method,path,operation,parameters:mergeParameters(pathParameters,operationParameters),...requestBody!==void 0&&!isReferenceObject(requestBody)&&{requestBody}};isIncluded(item,options)&&collected.push(item)}}return collected}function resolveParameters(spec,parameters){let resolved=[];for(let parameter of parameters??[]){let value=resolveRef(spec,parameter);value!==void 0&&!isReferenceObject(value)&&resolved.push(value)}return resolved}function mergeParameters(pathParameters,operationParameters){let merged=new Map;for(let parameter of[...pathParameters,...operationParameters])merged.set(`${parameter.in}:${parameter.name}`,parameter);return[...merged.values()]}function isIncluded(operation,options){if(options.tags?.length){let tags=new Set(operation.operation.tags??[]);if(!options.tags.some(tag=>tags.has(tag)))return!1}return!(options.exclude??[]).some(rule=>matchesExcludeRule(operation,rule))}function matchesExcludeRule(operation,rule){if(rule.method&&rule.method.toLowerCase()!==operation.method||rule.operationId&&!matchesPattern2(rule.operationId,operation.operation.operationId??"")||rule.path&&!matchesPattern2(rule.path,operation.path))return!1;if(rule.tags?.length){let tags=new Set(operation.operation.tags??[]);if(!rule.tags.some(tag=>tags.has(tag)))return!1}return!0}function matchesPattern2(pattern,value){return typeof pattern=="string"?pattern===value:(pattern.lastIndex=0,pattern.test(value))}function createToolNames(operations){let seen=new Map;return operations.map(operation=>{let baseName=slugifyToolName(operation.operation.operationId??`${operation.method}_${operation.path.replace(/[{}]/g,"").replace(/\//g,"_")}`),count=seen.get(baseName)??0;if(seen.set(baseName,count+1),count===0)return baseName;let suffix=`_${count+1}`;return`${baseName.slice(0,64-suffix.length)}${suffix}`})}function createToolDescription(operation){return[operation.operation.summary,operation.operation.description,`HTTP: ${operation.method.toUpperCase()} ${operation.path}`].filter(part=>!!part).join(`
|
|
768
|
+
`)}function styleStatus(status){let text2=String(status);return status>=500?magenta(text2):status>=400?red(text2):status>=300?yellow(text2):green(text2)}function isNoisyRequest(httpMethod,pathname){return httpMethod!=="GET"&&httpMethod!=="HEAD"?!1:pathname.endsWith("/favicon.ico")}function formatRequestLogLine(line){let{description,detail}=line;return[...line.prefix===void 0?[]:[bold(line.prefix)],methodStyle(description.method)(description.method),...detail?.subject===void 0?[]:[bold(sanitize(detail.subject))],line.pathname,styleStatus(line.status),...description.client===void 0?[]:[dim(`client=${sanitize(description.client)}`)],dim(`${line.durationMs}ms`),...line.suffix].join(" ")}function requestLogger(options={}){return options.enabled===!1?(_request,next)=>next():async(request,next)=>{let level=resolveLogLevel(options.level),startedAt=Date.now(),httpMethod=request.method,pathname=new URL(request.url).pathname;if(isNoisyRequest(httpMethod,pathname))return next();let requestHeaders={};level==="trace"&&request.headers.forEach((value,key)=>{requestHeaders[key]=value});let requestBody;if(httpMethod!=="GET"&&httpMethod!=="HEAD"){let parsedBody=getRequestBag(request).parsedBody;if(parsedBody!==void 0)requestBody=parsedBody;else try{requestBody=await request.clone().json(),(request.headers.get("content-type")??"").includes("application/json")&&(getRequestBag(request).parsedBody=requestBody)}catch{}}let description=describeRequest(httpMethod,pathname,options.mcpPath,requestBody),logLine=(status,detail2,suffix2=[])=>{console.log(formatRequestLogLine({prefix:options.prefix,description,detail:detail2,pathname,status,durationMs:Date.now()-startedAt,suffix:suffix2}))},response;try{response=await next()}catch(error3){throw logLine(500,void 0,[red(`ERROR ${sanitize(error3 instanceof Error?error3.message:String(error3))}`)]),error3}let detail=description.mcpRequest===void 0?void 0:formatDetail(description.mcpRequest),suffix=[];if(description.mcpRequest!==void 0&&detail!==void 0){let echoPayloads=level!=="info";echoPayloads&&detail.input!==void 0&&suffix.push(inlineJson(detail.input));let outcome=description.streaming?{errorMessage:null}:await extractResponseOutcome(response,request);echoPayloads&&description.mcpRequest.method==="tools/call"&&outcome.errorMessage===null&&outcome.result!==void 0&&suffix.push(dim("->"),inlineJson(compactToolResult(outcome.result))),outcome.errorMessage!==null?suffix.push(red(`ERROR ${sanitize(outcome.errorMessage)}`)):response.status>=400&&suffix.push(red(`ERROR (HTTP ${response.status})`))}return logLine(response.status,detail,suffix),level==="trace"&&await printTraceDump(response,requestHeaders,requestBody,!description.streaming),response}}init_dist();init_fetch_app();import{trackBufferedResponse as trackBufferedResponse2}from"#mcp-use-buffered-response";function createMcpMount(factory,options={}){let{path="/mcp",handler:handlerOptions,authInfo:getAuthInfo}=options,legacyMode=handlerOptions?.legacy??"stateless",handler=createMcpHandler(factory,{legacy:"stateless",...handlerOptions});return{handler,fetch:async request=>{if(!matchesPath(request,path))return new Response("Not Found",{status:404});if(legacyMode==="stateless"){let method=request.method.toUpperCase();if(method==="GET"||method==="DELETE"||method==="HEAD")return new Response(null,{status:204})}let bag=getRequestBag(request),parsedBody=bag.parsedBody;if(parsedBody===void 0)try{parsedBody=await request.clone().json()}catch{}let capabilities=extractClientCapabilitiesFromBody(parsedBody);capabilities!==void 0&&stashClientCapabilities(request,capabilities);let authInfo=getAuthInfo?.(request)??bag.authInfo,response=await handler.fetch(request,{...parsedBody!==void 0&&{parsedBody},...authInfo!==void 0&&{authInfo}});return response.headers.get("content-type")?.toLowerCase().includes("application/json")?"Bun"in globalThis&&response.body!==null?new Response(await response.arrayBuffer(),{status:response.status,statusText:response.statusText,headers:response.headers}):trackBufferedResponse2(request,response):response}}}function object2(value,label){if(value===null||typeof value!="object"||Array.isArray(value))throw new TypeError(`${label} must be an object`);return value}function array2(value,label){if(!Array.isArray(value))throw new TypeError(`${label} must be an array`);return value}function nonBlank(value,label){if(typeof value!="string"||!value.trim())throw new TypeError(`${label} must be a non-blank string`)}function standard(json,validate){return{"~standard":{version:1,vendor:"mcp-use",jsonSchema:{input:()=>json,output:()=>json},async validate(value){try{return{value:await validate(value)}}catch(error3){return{issues:[{message:error3 instanceof Error?error3.message:String(error3)}]}}}}}}function prepareSettings(options){let readTool=options.readTool??"settings.read",updateTool=options.updateTool??"settings.update";if(nonBlank(readTool,"readTool"),nonBlank(updateTool,"updateTool"),readTool===updateTool)throw new TypeError("Settings read and update tools must have different names");object2(options.fields,"fields");let fields=Object.entries(options.fields).map(([name,field])=>[name,{...field}]);if(!fields.length)throw new TypeError("Settings require at least one field");let properties={};for(let[name,field]of fields){if(nonBlank(field.title,`Setting ${name} title`),field.description!==void 0&&typeof field.description!="string")throw new TypeError(`Setting ${name} description must be a string`);let outputProperty=field.schema["~standard"].jsonSchema.output({target:"draft-2020-12"}),property=field.schema["~standard"].jsonSchema.input({target:"draft-2020-12"});if(!["boolean","string","number","integer"].includes(String(property.type))||outputProperty.type!==property.type||["$ref","anyOf","oneOf","allOf"].some(key=>key in property)||property.enum!==void 0&&(property.type!=="string"||!Array.isArray(property.enum)||!property.enum.length||!property.enum.every(item=>typeof item=="string")))throw new TypeError(`Unsupported native setting ${name}: use boolean, string, string enum, number, or integer`);let wireProperty=structuredClone(property);delete wireProperty.default,Object.defineProperty(properties,name,{enumerable:!0,value:{...wireProperty,title:field.title,...field.description!==void 0&&{description:field.description}}})}let schema2={type:"object",properties,required:fields.map(([name])=>name),additionalProperties:!1},layout=options.layout===void 0?void 0:structuredClone(options.layout);if(layout!==void 0)for(let groupValue of array2(layout,"Settings layout")){let group=object2(groupValue,"Settings layout group");if(group.kind!=="group")throw new TypeError("Settings layout groups must have kind 'group'");nonBlank(group.title,"Settings layout group title");for(let itemValue of array2(group.items,"Settings layout group items")){let item=object2(itemValue,"Settings layout item");if(item.kind==="property"){if(nonBlank(item.property,"Settings layout property"),!Object.hasOwn(properties,item.property))throw new TypeError(`Settings layout references unknown setting: ${item.property}`)}else if(item.kind==="tool"){if(nonBlank(item.tool,"Settings layout action tool"),nonBlank(item.title,"Settings layout action title"),item.description!==void 0&&typeof item.description!="string")throw new TypeError("Settings layout action description must be a string")}else throw new TypeError("Settings layout items must have kind 'property' or 'tool'")}}let validateValues=async(value,partial2=!1)=>{let values=object2(value,partial2?"set":"values");for(let name of Object.keys(values))if(!Object.hasOwn(properties,name))throw new TypeError(`Unknown setting: ${name}`);if(partial2&&!Object.keys(values).length)throw new TypeError("Set at least one setting");let result={};for(let[name,field]of fields){if(!Object.hasOwn(values,name)){if(!partial2)throw new TypeError(`Missing effective setting: ${name}`);continue}let parsed=await field.schema["~standard"].validate(values[name]);if(parsed.issues!==void 0)throw new TypeError(`Invalid setting ${name}: ${parsed.issues.map(issue2=>issue2.message).join(", ")}`);if(parsed.value===void 0||!["string","boolean","number"].includes(typeof parsed.value)||typeof parsed.value=="number"&&!Number.isFinite(parsed.value))throw new TypeError(`Invalid primitive setting: ${name}`);if(!Object.is(parsed.value,values[name]))throw new TypeError(`Setting ${name} schema must not transform values`);Object.defineProperty(result,name,{enumerable:!0,value:parsed.value})}return result},emptySchema=standard({type:"object",additionalProperties:!1},value=>{if(Object.keys(object2(value,"arguments")).length)throw new TypeError("Settings read accepts empty arguments");return{}}),updateInput=standard({type:"object",properties:{set:{...schema2,required:[],minProperties:1}},required:["set"],additionalProperties:!1},async value=>{let input=object2(value,"arguments");if(Object.keys(input).some(key=>key!=="set"))throw new TypeError("Unknown settings update argument");return{set:await validateValues(input.set,!0)}}),readOutput=standard({type:"object",properties:{schema:{type:"object"},values:schema2,layout:{type:"array",items:{type:"object",properties:{kind:{const:"group"},title:{type:"string"},items:{type:"array",items:{type:"object"}}},required:["kind","title","items"]}}},required:["schema","values"]},async value=>{let output=object2(value,"settings result");return{...output,values:await validateValues(output.values)}}),updateOutput=standard({type:"object",properties:{values:schema2},required:["values"]},async value=>({values:await validateValues(object2(value,"settings result").values)}));return{capability:{readTool,updateTool},schema:schema2,layout,readDefinition:{name:readTool,inputSchema:emptySchema,outputSchema:readOutput,annotations:{readOnlyHint:!0}},updateDefinition:{name:updateTool,inputSchema:updateInput,outputSchema:updateOutput}}}init_dist();function createPrefixCompletion(values){let strings=values.map(String);return value=>{let prefix=String(value??"").toLowerCase();return strings.filter(candidate=>candidate.toLowerCase().startsWith(prefix))}}function completable2(schema2,complete){return typeof complete=="function"?completable(schema2,(value,context)=>complete(String(value??""),context)):completable(schema2,createPrefixCompletion(complete))}function normalizeCompletions(completions){let normalized=Object.create(null);for(let[variable,completer]of Object.entries(completions))completer!==void 0&&(normalized[variable]=Array.isArray(completer)?createPrefixCompletion(completer):completer);return normalized}init_dist();var HTTP_METHODS=["get","put","post","delete","options","head","patch","trace"];function registerOpenAPITools(server,options){let operations=collectOperations(options.spec,options),names=createToolNames(operations),baseUrl=operations.length>0?resolveBaseUrl(options):void 0;for(let[index,operation]of operations.entries()){let name=names[index];if(name===void 0||baseUrl===void 0)continue;let inputBindings=createInputBindings(operation);server.tool({name,description:createToolDescription(operation),inputSchema:createToolInputSchema(options.spec,operation,inputBindings)},async params=>callOpenAPIOperation(operation,params,options,inputBindings,baseUrl))}}function collectOperations(spec,options){let collected=[];for(let[path,pathItemOrRef]of Object.entries(spec.paths??{})){let pathItem=resolveRef(spec,pathItemOrRef);if(pathItem===void 0||isReferenceObject(pathItem))continue;let pathParameters=resolveParameters(spec,pathItem.parameters);for(let method of HTTP_METHODS){let operationOrRef=pathItem[method];if(operationOrRef===void 0)continue;let operation=resolveRef(spec,operationOrRef);if(operation===void 0||isReferenceObject(operation))continue;let operationParameters=resolveParameters(spec,operation.parameters),requestBody=operation.requestBody===void 0?void 0:resolveRef(spec,operation.requestBody),item={method,path,operation,parameters:mergeParameters(pathParameters,operationParameters),...requestBody!==void 0&&!isReferenceObject(requestBody)&&{requestBody}};isIncluded(item,options)&&collected.push(item)}}return collected}function resolveParameters(spec,parameters){let resolved=[];for(let parameter of parameters??[]){let value=resolveRef(spec,parameter);value!==void 0&&!isReferenceObject(value)&&resolved.push(value)}return resolved}function mergeParameters(pathParameters,operationParameters){let merged=new Map;for(let parameter of[...pathParameters,...operationParameters])merged.set(`${parameter.in}:${parameter.name}`,parameter);return[...merged.values()]}function isIncluded(operation,options){if(options.tags?.length){let tags=new Set(operation.operation.tags??[]);if(!options.tags.some(tag=>tags.has(tag)))return!1}return!(options.exclude??[]).some(rule=>matchesExcludeRule(operation,rule))}function matchesExcludeRule(operation,rule){if(rule.method&&rule.method.toLowerCase()!==operation.method||rule.operationId&&!matchesPattern2(rule.operationId,operation.operation.operationId??"")||rule.path&&!matchesPattern2(rule.path,operation.path))return!1;if(rule.tags?.length){let tags=new Set(operation.operation.tags??[]);if(!rule.tags.some(tag=>tags.has(tag)))return!1}return!0}function matchesPattern2(pattern,value){return typeof pattern=="string"?pattern===value:(pattern.lastIndex=0,pattern.test(value))}function createToolNames(operations){let seen=new Map;return operations.map(operation=>{let baseName=slugifyToolName(operation.operation.operationId??`${operation.method}_${operation.path.replace(/[{}]/g,"").replace(/\//g,"_")}`),count=seen.get(baseName)??0;if(seen.set(baseName,count+1),count===0)return baseName;let suffix=`_${count+1}`;return`${baseName.slice(0,64-suffix.length)}${suffix}`})}function createToolDescription(operation){return[operation.operation.summary,operation.operation.description,`HTTP: ${operation.method.toUpperCase()} ${operation.path}`].filter(part=>!!part).join(`
|
|
769
769
|
|
|
770
|
-
`)}function slugifyToolName(value){return value.trim().replace(/[^a-zA-Z0-9_-]+/g,"_").replace(/_+/g,"_").replace(/^_/,"").replace(/_$/,"").slice(0,64)||"openapi_tool"}function createToolInputSchema(spec,operation,inputBindings){let properties={},required2=[];for(let{parameter,inputName}of inputBindings.parameters){let parameterSchema=transformSchema(spec,parameter.schema??{});properties[inputName]={...parameterSchema,description:parameter.description??`${parameter.in} parameter`},(parameter.required||parameter.in==="path")&&required2.push(inputName)}let bodySchema=getJsonRequestBodySchema(operation.requestBody);bodySchema!==void 0&&inputBindings.bodyInputName!==void 0&&(properties[inputBindings.bodyInputName]=transformSchema(spec,bodySchema),operation.requestBody?.required&&required2.push(inputBindings.bodyInputName));let definitions=createSchemaDefinitions(spec),schema2={type:"object",properties,additionalProperties:!1,...required2.length>0&&{required:required2},...definitions!==void 0&&{$defs:definitions}};return fromJsonSchema2(schema2)}function createInputBindings(operation){let parameters=operation.parameters.filter(parameter=>parameter.in!=="cookie"),bodyInputName=getJsonRequestBodySchema(operation.requestBody)===void 0?void 0:"body",nameCounts=new Map;for(let parameter of parameters)nameCounts.set(parameter.name,(nameCounts.get(parameter.name)??0)+1);let usedNames=new Set(bodyInputName===void 0?[]:[bodyInputName]);return{parameters:parameters.map(parameter=>{let preferredName=(nameCounts.get(parameter.name)??0)>1||parameter.name===bodyInputName?`${parameter.name}_${parameter.in}`:parameter.name;return{parameter,inputName:claimInputName(preferredName,usedNames)}}),...bodyInputName!==void 0&&{bodyInputName}}}function claimInputName(preferredName,usedNames){let inputName=preferredName,suffix=2;for(;usedNames.has(inputName);)inputName=`${preferredName}_${suffix}`,suffix+=1;return usedNames.add(inputName),inputName}function createSchemaDefinitions(spec){let schemas=readRecord(spec.components?.schemas);if(schemas===void 0)return;let definitions={};for(let[name,schema2]of Object.entries(schemas))definitions[name]=transformSchemaNode(spec,schema2,new Set);return definitions}function transformSchema(spec,schema2){let transformed=transformSchemaNode(spec,schema2,new Set);return readRecord(transformed)??{}}function transformSchemaNode(spec,value,resolvingRefs){if(Array.isArray(value))return value.map(item=>transformSchemaNode(spec,item,resolvingRefs));let object4=readRecord(value);if(object4===void 0)return value;let ref=typeof object4.$ref=="string"?object4.$ref:void 0,siblings={};for(let[key,child]of Object.entries(object4))key!=="$ref"&&(key==="nullable"&&typeof child=="boolean"||(siblings[key]=transformSchemaNode(spec,child,resolvingRefs)));let transformed=siblings;if(ref!==void 0){let schemaRef=rewriteSchemaRef(spec,ref);if(schemaRef!==void 0)transformed={$ref:schemaRef,...siblings};else if(!resolvingRefs.has(ref)){let resolved=resolveRef(spec,{$ref:ref});if(resolved!==void 0){let nextRefs=new Set(resolvingRefs);nextRefs.add(ref),transformed={...readRecord(transformSchemaNode(spec,resolved,nextRefs))??{},...siblings}}}}return object4.nullable===!0?{anyOf:[transformed,{type:"null"}]}:transformed}function rewriteSchemaRef(spec,ref){let prefix="#/components/schemas/";if(ref.startsWith(prefix))return resolveRef(spec,{$ref:ref})===void 0?void 0:`#/$defs/${ref.slice(prefix.length)}`}function getJsonRequestBodySchema(requestBody){let content=requestBody?.content;if(content!==void 0)return content["application/json"]?.schema??content["application/*+json"]?.schema??Object.entries(content).find(([mediaType])=>mediaType.includes("+json"))?.[1].schema}async function callOpenAPIOperation(operation,params,options,inputBindings,baseUrl){let fetchImpl=options.fetch??globalThis.fetch,url2=buildUrl(operation,params,inputBindings.parameters,baseUrl),headers=buildHeaders(inputBindings.parameters,params,options),bodyInputName=inputBindings.bodyInputName,body=bodyInputName===void 0||params[bodyInputName]===void 0?void 0:JSON.stringify(params[bodyInputName]);body!==void 0&&!hasHeader(headers,"content-type")&&(headers["content-type"]="application/json");let response=await fetchImpl(url2,{method:operation.method.toUpperCase(),headers,...body!==void 0&&{body}}),contentType=response.headers.get("content-type")??"";if(!response.ok)return{content:[{type:"text",text:await response.text()}],isError:!0};if(contentType.includes("application/json")||contentType.includes("+json")){let text2=await response.text();try{let data=JSON.parse(text2);return{content:[{type:"text",text:JSON.stringify(data)}],structuredContent:data}}catch{return{content:[{type:"text",text:text2}]}}}return{content:[{type:"text",text:await response.text()}]}}function buildUrl(operation,params,parameterBindings,baseUrl){let interpolatedPath=operation.path.replace(/{([^}]+)}/g,(_match,name)=>{let binding=parameterBindings.find(({parameter})=>parameter.in==="path"&¶meter.name===name);return encodeURIComponent(String(binding===void 0?"":params[binding.inputName]??""))}),url2=new URL(interpolatedPath.replace(/^\/+/,""),ensureTrailingSlash(baseUrl));for(let{parameter,inputName}of parameterBindings){if(parameter.in!=="query")continue;let value=params[inputName];value==null||value===""||appendQueryParam(url2,parameter.name,value)}return url2.toString()}function buildHeaders(parameterBindings,params,options){let headers={...options.headers??{}};for(let{parameter,inputName}of parameterBindings){if(parameter.in!=="header")continue;let value=params[inputName];value==null||value===""||(headers[parameter.name]=String(value))}return options.auth?.type==="bearer"&&options.auth.token&&(headers.authorization=`Bearer ${options.auth.token}`),options.auth?.type==="header"&&options.auth.value&&(headers[options.auth.name]=options.auth.value),headers}function resolveBaseUrl(options){let baseUrl=options.baseUrl??options.spec.servers?.[0]?.url;if(baseUrl===void 0||baseUrl.trim()==="")throw new Error("MCPServer.fromOpenAPI requires options.baseUrl or spec.servers[0].url");return baseUrl}function appendQueryParam(url2,name,value){if(Array.isArray(value)){for(let item of value)item!=null&&item!==""&&url2.searchParams.append(name,String(item));return}url2.searchParams.set(name,String(value))}function ensureTrailingSlash(url2){return url2.endsWith("/")?url2:`${url2}/`}function hasHeader(headers,name){return Object.keys(headers).some(headerName=>headerName.toLowerCase()===name)}function isReferenceObject(value){let object4=readRecord(value);return object4!==void 0&&typeof object4.$ref=="string"}function resolveRef(spec,value){if(!isReferenceObject(value))return value;if(!value.$ref.startsWith("#/"))return;let segments=value.$ref.slice(2).split("/").map(segment=>segment.replace(/~1/g,"/").replace(/~0/g,"~")),current=spec;for(let segment of segments){let object4=readRecord(current);if(object4===void 0||!(segment in object4))return;current=object4[segment]}return current}function readRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)?value:void 0}init_dist();init_dist();init_fetch_app();function isRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function isLocalhost(url2){let hostname=url2.hostname.toLowerCase();return hostname==="localhost"||hostname.endsWith(".localhost")||hostname==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(hostname)}function parseAbsoluteUrl(value,name){let url2;try{url2=new URL(value)}catch{throw new Error(`${name} must be an absolute URL`)}if(url2.origin==="null"||url2.username!==""||url2.password!=="")throw new Error(`${name} must be an absolute URL without credentials`);return url2}function assertSecureHttpUrl(url2,name){if(url2.protocol!=="https:"&&!(url2.protocol==="http:"&&isLocalhost(url2)))throw new Error(`${name} must use HTTPS, or HTTP for localhost`)}init_dist();function invalidToken(message,cause){let error3=new OAuthError(OAuthErrorCode.InvalidToken,message);return cause!==void 0&&(error3.cause=cause),error3}function resolveConfiguredOAuthResource(options){let provider=options.provider,basePath=normalizeBasePath(options.basePath);if(provider.resource!==void 0)return validateOAuthResource(provider.resource,basePath);if(options.mcpUrl!==void 0)return validateOAuthResource(appendBasePath(requireAbsoluteOrigin(options.mcpUrl,"MCP_URL"),basePath),basePath)}function resolveLocalOAuthResource(listenOrigin,basePath){let listenOriginUrl=requireAbsoluteOrigin(listenOrigin,"listen origin");if(!isLocalhost(listenOriginUrl))throw new Error("OAuth listen origin must be localhost or a loopback address");return validateOAuthResource(appendBasePath(listenOriginUrl,normalizeBasePath(basePath)),basePath)}function validateOAuthResource(resource2,basePath){let normalizedBasePath=normalizeBasePath(basePath),url2=parseAbsoluteUrl(resource2,"OAuth resource");if(url2.search!==""||url2.hash!=="")throw new Error("OAuth resource must not include a query string or fragment");if(assertSecureHttpUrl(url2,"OAuth resource"),normalizePathname(url2.pathname)!==normalizedBasePath)throw new Error(`OAuth resource path must exactly match basePath (${normalizedBasePath})`);return url2.pathname=normalizedBasePath,url2}function wrapOAuthTokenVerifier(provider,expectedResource){let canonicalResource=normalizeResourceUrl(expectedResource),tokenVerifier=provider.createTokenVerifier(new URL(canonicalResource.href));if(tokenVerifier===null||typeof tokenVerifier!="object"||typeof tokenVerifier.verifyAccessToken!="function")throw new TypeError("OAuth provider createTokenVerifier must return an OAuthTokenVerifier");return{async verifyAccessToken(token){let authInfo=await tokenVerifier.verifyAccessToken(token);assertVerifiedAuthInfo(authInfo),assertResourceBinding(authInfo,canonicalResource);let mapped;try{mapped=provider.mapAuthInfo(authInfo)}catch(error3){throw invalidToken("Token identity mapping failed",error3)}return assertMappedExtra(mapped),{...authInfo,scopes:[...authInfo.scopes],extra:{...authInfo.extra,...mapped}}}}}function assertResourceBinding(authInfo,expectedResource){if(authInfo.resource===void 0)throw invalidToken("Token verifier did not return a validated protected resource");if(parseTokenResource(authInfo.resource).href!==normalizeResourceUrl(expectedResource).href)throw invalidToken("Token resource does not match the protected resource")}function parseTokenResource(value){if(!(value instanceof URL))throw invalidToken("Token resource must be an absolute HTTPS URL, or HTTP URL for localhost");let resource2=value;if(!/^https?:$/.test(resource2.protocol)||resource2.username!==""||resource2.password!==""||resource2.search!==""||resource2.hash!==""||resource2.protocol==="http:"&&!isLocalhost(resource2))throw invalidToken("Token resource must be an absolute HTTPS URL, or HTTP URL for localhost");return normalizeResourceUrl(resource2)}function normalizeResourceUrl(resource2){let normalized=new URL(resource2);return normalized.pathname=normalized.pathname==="/"?"/":normalized.pathname.replace(/\/+$/,""),normalized}function getOAuthProviderOptions(provider){return{oauthMetadata:provider.oauthMetadata,...provider.requiredScopes!==void 0&&{requiredScopes:[...provider.requiredScopes]},...provider.scopesSupported!==void 0&&{scopesSupported:[...provider.scopesSupported]},...provider.resourceName!==void 0&&{resourceName:provider.resourceName},...provider.serviceDocumentationUrl!==void 0&&{serviceDocumentationUrl:provider.serviceDocumentationUrl}}}function assertVerifiedAuthInfo(authInfo){if(authInfo===null||typeof authInfo!="object"||typeof authInfo.token!="string"||authInfo.token.length===0||typeof authInfo.clientId!="string"||!Array.isArray(authInfo.scopes)||!authInfo.scopes.every(scope=>typeof scope=="string")||typeof authInfo.expiresAt!="number"||!Number.isFinite(authInfo.expiresAt)||authInfo.expiresAt<=Date.now()/1e3)throw invalidToken("Token verifier returned invalid authentication information")}function assertMappedExtra(mapped){if(mapped===null||typeof mapped!="object"||!("user"in mapped)||mapped.user===void 0||!isRecord(mapped.payload)||!Array.isArray(mapped.permissions)||!mapped.permissions.every(permission=>typeof permission=="string"))throw invalidToken("Token identity mapping must return user, payload, and string permissions")}function requireAbsoluteOrigin(value,name){let url2=parseAbsoluteUrl(value,name);if(url2.pathname!=="/"||url2.search!==""||url2.hash!==""||url2.username!==""||url2.password!=="")throw new Error(`${name} must be an absolute origin without a path`);return url2}function appendBasePath(origin,basePath){let resource2=new URL(origin.origin);return resource2.pathname=basePath,resource2}function normalizeBasePath(basePath){if(!basePath.startsWith("/")||basePath.includes("?")||basePath.includes("#"))throw new Error("basePath must be an absolute URL pathname");return normalizePathname(basePath)}function normalizePathname(pathname){if(pathname==="/")return"/";let end=pathname.length;for(;end>0&&pathname.charCodeAt(end-1)===47;)end--;return pathname.slice(0,end)}function oauthMetadata(provider,resource2){let options=getOAuthProviderOptions(provider);return async(request,next)=>{let response=oauthMetadataResponse(request,{oauthMetadata:options.oauthMetadata,resourceServerUrl:resource2,...options.scopesSupported!==void 0&&{scopesSupported:[...options.scopesSupported]},...options.resourceName!==void 0&&{resourceName:options.resourceName},...options.serviceDocumentationUrl!==void 0&&{serviceDocumentationUrl:options.serviceDocumentationUrl}});return response!==void 0?response:next()}}function authInfoFromRequest(request){return getRequestBag(request).authInfo}init_dist();import{createRemoteJWKSet,jwtVerify,errors}from"jose";init_policy();function resolveToolInputSchema(definition){return definition.inputSchema??definition.schema}var EVENT="mcp_use_sdk_event",ENDPOINT="https://eu.i.posthog.com/i/v0/e/",TOKEN="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI",CONTENT=/(^|_)(arguments?|args|body|command|headers?|location|message|organization|path|query|response|secret|subject|token|uri|url|user_agent)(_|$)/i,RESERVED=new Set("feature action sdk_generation telemetry_schema_version sdk_package sdk_version server_id runtime_id identity_stability distinct_id validation_run_id is_validation".split(" ")),runtimeId;function getRuntimeId(){return runtimeId??=crypto.randomUUID(),runtimeId}var once=new Set,pending=new Set,identities=new Map;function hasControl(value){return[...value].some(character=>{let code=character.charCodeAt(0);return code<32||code===127})}function env(name){return typeof process>"u"?void 0:process.env?.[name]}function safeEnv(name){let value=env(name);return value!==void 0&&value.length>0&&value.length<=128&&!hasControl(value)?value:void 0}function canPersistTelemetryIdentity(){return typeof process>"u"||process.versions?.node===void 0?!1:!("Deno"in globalThis)}function disabled(){if(env("MCP_USE_ANONYMIZED_TELEMETRY")==="false")return!0;try{return globalThis.__MCP_USE_ANONYMIZED_TELEMETRY__===!1||typeof localStorage<"u"&&localStorage.getItem("MCP_USE_ANONYMIZED_TELEMETRY")==="false"}catch{return!1}}function isUsageDisabled(){return disabled()}function clean(properties){return Object.fromEntries(Object.entries(properties).filter(([key,value])=>key.length>128||hasControl(key)||key.startsWith("$")||RESERVED.has(key)||CONTENT.test(key)||value===void 0?!1:typeof value=="string"?value.length<=128&&!hasControl(value):typeof value=="boolean"||typeof value=="number"&&Number.isFinite(value)))}async function identity(serverRoot){let projectId=safeEnv("MCP_USE_TELEMETRY_PROJECT_ID");if(projectId!==void 0)return{id:projectId,stability:"project"};if(serverRoot===void 0||!canPersistTelemetryIdentity())return{id:getRuntimeId(),stability:"process"};let existing=identities.get(serverRoot);if(existing!==void 0)return existing;let resolving=(async()=>{try{let fs=await import("fs/promises"),directory=`${serverRoot}/.mcp-use`,file=`${directory}/usage.json`,read=async()=>{try{let value=JSON.parse(await fs.readFile(file,"utf8"));if(typeof value=="object"&&value!==null&&"schemaVersion"in value&&value.schemaVersion===1&&"serverId"in value&&typeof value.serverId=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value.serverId))return value.serverId}catch{}},stored=await read();if(stored!==void 0)return{id:stored,stability:"server"};await fs.mkdir(directory,{recursive:!0,mode:448});let created=crypto.randomUUID();try{return await fs.writeFile(file,`${JSON.stringify({schemaVersion:1,serverId:created})}
|
|
771
|
-
`,{flag:"wx",mode:384}),{id:created,stability:"server"}}catch{let raced=await read();if(raced!==void 0)return{id:raced,stability:"server"}}}catch{}return{id:getRuntimeId(),stability:"process"}})();return identities.set(serverRoot,resolving),resolving}function capture(feature,action,properties,options,resolveIdentity){let validationId=safeEnv("MCP_USE_TELEMETRY_VALIDATION_ID");if(disabled()||env("NODE_ENV")==="test"&&validationId===void 0||pending.size>=16)return;if(options.onceKey!==void 0){if(once.has(options.onceKey))return;once.add(options.onceKey)}let rate=Math.max(0,Math.min(1,options.sampleRate??1));if(validationId===void 0&&Math.random()>=rate)return;let request=(async()=>{try{let resolvedIdentity=await resolveIdentity(),body=JSON.stringify({api_key:TOKEN,event:EVENT,properties:{...clean(properties),feature,action,sdk_generation:"v2",telemetry_schema_version:2,sdk_package:"mcp-use",sdk_version:"2.
|
|
770
|
+
`)}function slugifyToolName(value){return value.trim().replace(/[^a-zA-Z0-9_-]+/g,"_").replace(/_+/g,"_").replace(/^_/,"").replace(/_$/,"").slice(0,64)||"openapi_tool"}function createToolInputSchema(spec,operation,inputBindings){let properties={},required2=[];for(let{parameter,inputName}of inputBindings.parameters){let parameterSchema=transformSchema(spec,parameter.schema??{});properties[inputName]={...parameterSchema,description:parameter.description??`${parameter.in} parameter`},(parameter.required||parameter.in==="path")&&required2.push(inputName)}let bodySchema=getJsonRequestBodySchema(operation.requestBody);bodySchema!==void 0&&inputBindings.bodyInputName!==void 0&&(properties[inputBindings.bodyInputName]=transformSchema(spec,bodySchema),operation.requestBody?.required&&required2.push(inputBindings.bodyInputName));let definitions=createSchemaDefinitions(spec),schema2={type:"object",properties,additionalProperties:!1,...required2.length>0&&{required:required2},...definitions!==void 0&&{$defs:definitions}};return fromJsonSchema2(schema2)}function createInputBindings(operation){let parameters=operation.parameters.filter(parameter=>parameter.in!=="cookie"),bodyInputName=getJsonRequestBodySchema(operation.requestBody)===void 0?void 0:"body",nameCounts=new Map;for(let parameter of parameters)nameCounts.set(parameter.name,(nameCounts.get(parameter.name)??0)+1);let usedNames=new Set(bodyInputName===void 0?[]:[bodyInputName]);return{parameters:parameters.map(parameter=>{let preferredName=(nameCounts.get(parameter.name)??0)>1||parameter.name===bodyInputName?`${parameter.name}_${parameter.in}`:parameter.name;return{parameter,inputName:claimInputName(preferredName,usedNames)}}),...bodyInputName!==void 0&&{bodyInputName}}}function claimInputName(preferredName,usedNames){let inputName=preferredName,suffix=2;for(;usedNames.has(inputName);)inputName=`${preferredName}_${suffix}`,suffix+=1;return usedNames.add(inputName),inputName}function createSchemaDefinitions(spec){let schemas=readRecord(spec.components?.schemas);if(schemas===void 0)return;let definitions={};for(let[name,schema2]of Object.entries(schemas))definitions[name]=transformSchemaNode(spec,schema2,new Set);return definitions}function transformSchema(spec,schema2){let transformed=transformSchemaNode(spec,schema2,new Set);return readRecord(transformed)??{}}function transformSchemaNode(spec,value,resolvingRefs){if(Array.isArray(value))return value.map(item=>transformSchemaNode(spec,item,resolvingRefs));let object5=readRecord(value);if(object5===void 0)return value;let ref=typeof object5.$ref=="string"?object5.$ref:void 0,siblings={};for(let[key,child]of Object.entries(object5))key!=="$ref"&&(key==="nullable"&&typeof child=="boolean"||(siblings[key]=transformSchemaNode(spec,child,resolvingRefs)));let transformed=siblings;if(ref!==void 0){let schemaRef=rewriteSchemaRef(spec,ref);if(schemaRef!==void 0)transformed={$ref:schemaRef,...siblings};else if(!resolvingRefs.has(ref)){let resolved=resolveRef(spec,{$ref:ref});if(resolved!==void 0){let nextRefs=new Set(resolvingRefs);nextRefs.add(ref),transformed={...readRecord(transformSchemaNode(spec,resolved,nextRefs))??{},...siblings}}}}return object5.nullable===!0?{anyOf:[transformed,{type:"null"}]}:transformed}function rewriteSchemaRef(spec,ref){let prefix="#/components/schemas/";if(ref.startsWith(prefix))return resolveRef(spec,{$ref:ref})===void 0?void 0:`#/$defs/${ref.slice(prefix.length)}`}function getJsonRequestBodySchema(requestBody){let content=requestBody?.content;if(content!==void 0)return content["application/json"]?.schema??content["application/*+json"]?.schema??Object.entries(content).find(([mediaType])=>mediaType.includes("+json"))?.[1].schema}async function callOpenAPIOperation(operation,params,options,inputBindings,baseUrl){let fetchImpl=options.fetch??globalThis.fetch,url2=buildUrl(operation,params,inputBindings.parameters,baseUrl),headers=buildHeaders(inputBindings.parameters,params,options),bodyInputName=inputBindings.bodyInputName,body=bodyInputName===void 0||params[bodyInputName]===void 0?void 0:JSON.stringify(params[bodyInputName]);body!==void 0&&!hasHeader(headers,"content-type")&&(headers["content-type"]="application/json");let response=await fetchImpl(url2,{method:operation.method.toUpperCase(),headers,...body!==void 0&&{body}}),contentType=response.headers.get("content-type")??"";if(!response.ok)return{content:[{type:"text",text:await response.text()}],isError:!0};if(contentType.includes("application/json")||contentType.includes("+json")){let text2=await response.text();try{let data=JSON.parse(text2);return{content:[{type:"text",text:JSON.stringify(data)}],structuredContent:data}}catch{return{content:[{type:"text",text:text2}]}}}return{content:[{type:"text",text:await response.text()}]}}function buildUrl(operation,params,parameterBindings,baseUrl){let interpolatedPath=operation.path.replace(/{([^}]+)}/g,(_match,name)=>{let binding=parameterBindings.find(({parameter})=>parameter.in==="path"&¶meter.name===name);return encodeURIComponent(String(binding===void 0?"":params[binding.inputName]??""))}),url2=new URL(interpolatedPath.replace(/^\/+/,""),ensureTrailingSlash(baseUrl));for(let{parameter,inputName}of parameterBindings){if(parameter.in!=="query")continue;let value=params[inputName];value==null||value===""||appendQueryParam(url2,parameter.name,value)}return url2.toString()}function buildHeaders(parameterBindings,params,options){let headers={...options.headers??{}};for(let{parameter,inputName}of parameterBindings){if(parameter.in!=="header")continue;let value=params[inputName];value==null||value===""||(headers[parameter.name]=String(value))}return options.auth?.type==="bearer"&&options.auth.token&&(headers.authorization=`Bearer ${options.auth.token}`),options.auth?.type==="header"&&options.auth.value&&(headers[options.auth.name]=options.auth.value),headers}function resolveBaseUrl(options){let baseUrl=options.baseUrl??options.spec.servers?.[0]?.url;if(baseUrl===void 0||baseUrl.trim()==="")throw new Error("MCPServer.fromOpenAPI requires options.baseUrl or spec.servers[0].url");return baseUrl}function appendQueryParam(url2,name,value){if(Array.isArray(value)){for(let item of value)item!=null&&item!==""&&url2.searchParams.append(name,String(item));return}url2.searchParams.set(name,String(value))}function ensureTrailingSlash(url2){return url2.endsWith("/")?url2:`${url2}/`}function hasHeader(headers,name){return Object.keys(headers).some(headerName=>headerName.toLowerCase()===name)}function isReferenceObject(value){let object5=readRecord(value);return object5!==void 0&&typeof object5.$ref=="string"}function resolveRef(spec,value){if(!isReferenceObject(value))return value;if(!value.$ref.startsWith("#/"))return;let segments=value.$ref.slice(2).split("/").map(segment=>segment.replace(/~1/g,"/").replace(/~0/g,"~")),current=spec;for(let segment of segments){let object5=readRecord(current);if(object5===void 0||!(segment in object5))return;current=object5[segment]}return current}function readRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)?value:void 0}init_dist();init_dist();init_fetch_app();function isRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function isLocalhost(url2){let hostname=url2.hostname.toLowerCase();return hostname==="localhost"||hostname.endsWith(".localhost")||hostname==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(hostname)}function parseAbsoluteUrl(value,name){let url2;try{url2=new URL(value)}catch{throw new Error(`${name} must be an absolute URL`)}if(url2.origin==="null"||url2.username!==""||url2.password!=="")throw new Error(`${name} must be an absolute URL without credentials`);return url2}function assertSecureHttpUrl(url2,name){if(url2.protocol!=="https:"&&!(url2.protocol==="http:"&&isLocalhost(url2)))throw new Error(`${name} must use HTTPS, or HTTP for localhost`)}init_dist();function invalidToken(message,cause){let error3=new OAuthError(OAuthErrorCode.InvalidToken,message);return cause!==void 0&&(error3.cause=cause),error3}function resolveConfiguredOAuthResource(options){let provider=options.provider,basePath=normalizeBasePath(options.basePath);if(provider.resource!==void 0)return validateOAuthResource(provider.resource,basePath);if(options.mcpUrl!==void 0)return validateOAuthResource(appendBasePath(requireAbsoluteOrigin(options.mcpUrl,"MCP_URL"),basePath),basePath)}function resolveLocalOAuthResource(listenOrigin,basePath){let listenOriginUrl=requireAbsoluteOrigin(listenOrigin,"listen origin");if(!isLocalhost(listenOriginUrl))throw new Error("OAuth listen origin must be localhost or a loopback address");return validateOAuthResource(appendBasePath(listenOriginUrl,normalizeBasePath(basePath)),basePath)}function validateOAuthResource(resource2,basePath){let normalizedBasePath=normalizeBasePath(basePath),url2=parseAbsoluteUrl(resource2,"OAuth resource");if(url2.search!==""||url2.hash!=="")throw new Error("OAuth resource must not include a query string or fragment");if(assertSecureHttpUrl(url2,"OAuth resource"),normalizePathname(url2.pathname)!==normalizedBasePath)throw new Error(`OAuth resource path must exactly match basePath (${normalizedBasePath})`);return url2.pathname=normalizedBasePath,url2}function wrapOAuthTokenVerifier(provider,expectedResource){let canonicalResource=normalizeResourceUrl(expectedResource),tokenVerifier=provider.createTokenVerifier(new URL(canonicalResource.href));if(tokenVerifier===null||typeof tokenVerifier!="object"||typeof tokenVerifier.verifyAccessToken!="function")throw new TypeError("OAuth provider createTokenVerifier must return an OAuthTokenVerifier");return{async verifyAccessToken(token){let authInfo=await tokenVerifier.verifyAccessToken(token);assertVerifiedAuthInfo(authInfo),assertResourceBinding(authInfo,canonicalResource);let mapped;try{mapped=provider.mapAuthInfo(authInfo)}catch(error3){throw invalidToken("Token identity mapping failed",error3)}return assertMappedExtra(mapped),{...authInfo,scopes:[...authInfo.scopes],extra:{...authInfo.extra,...mapped}}}}}function assertResourceBinding(authInfo,expectedResource){if(authInfo.resource===void 0)throw invalidToken("Token verifier did not return a validated protected resource");if(parseTokenResource(authInfo.resource).href!==normalizeResourceUrl(expectedResource).href)throw invalidToken("Token resource does not match the protected resource")}function parseTokenResource(value){if(!(value instanceof URL))throw invalidToken("Token resource must be an absolute HTTPS URL, or HTTP URL for localhost");let resource2=value;if(!/^https?:$/.test(resource2.protocol)||resource2.username!==""||resource2.password!==""||resource2.search!==""||resource2.hash!==""||resource2.protocol==="http:"&&!isLocalhost(resource2))throw invalidToken("Token resource must be an absolute HTTPS URL, or HTTP URL for localhost");return normalizeResourceUrl(resource2)}function normalizeResourceUrl(resource2){let normalized=new URL(resource2);return normalized.pathname=normalized.pathname==="/"?"/":normalized.pathname.replace(/\/+$/,""),normalized}function getOAuthProviderOptions(provider){return{oauthMetadata:provider.oauthMetadata,...provider.requiredScopes!==void 0&&{requiredScopes:[...provider.requiredScopes]},...provider.scopesSupported!==void 0&&{scopesSupported:[...provider.scopesSupported]},...provider.resourceName!==void 0&&{resourceName:provider.resourceName},...provider.serviceDocumentationUrl!==void 0&&{serviceDocumentationUrl:provider.serviceDocumentationUrl}}}function assertVerifiedAuthInfo(authInfo){if(authInfo===null||typeof authInfo!="object"||typeof authInfo.token!="string"||authInfo.token.length===0||typeof authInfo.clientId!="string"||!Array.isArray(authInfo.scopes)||!authInfo.scopes.every(scope=>typeof scope=="string")||typeof authInfo.expiresAt!="number"||!Number.isFinite(authInfo.expiresAt)||authInfo.expiresAt<=Date.now()/1e3)throw invalidToken("Token verifier returned invalid authentication information")}function assertMappedExtra(mapped){if(mapped===null||typeof mapped!="object"||!("user"in mapped)||mapped.user===void 0||!isRecord(mapped.payload)||!Array.isArray(mapped.permissions)||!mapped.permissions.every(permission=>typeof permission=="string"))throw invalidToken("Token identity mapping must return user, payload, and string permissions")}function requireAbsoluteOrigin(value,name){let url2=parseAbsoluteUrl(value,name);if(url2.pathname!=="/"||url2.search!==""||url2.hash!==""||url2.username!==""||url2.password!=="")throw new Error(`${name} must be an absolute origin without a path`);return url2}function appendBasePath(origin,basePath){let resource2=new URL(origin.origin);return resource2.pathname=basePath,resource2}function normalizeBasePath(basePath){if(!basePath.startsWith("/")||basePath.includes("?")||basePath.includes("#"))throw new Error("basePath must be an absolute URL pathname");return normalizePathname(basePath)}function normalizePathname(pathname){if(pathname==="/")return"/";let end=pathname.length;for(;end>0&&pathname.charCodeAt(end-1)===47;)end--;return pathname.slice(0,end)}function oauthMetadata(provider,resource2){let options=getOAuthProviderOptions(provider);return async(request,next)=>{let response=oauthMetadataResponse(request,{oauthMetadata:options.oauthMetadata,resourceServerUrl:resource2,...options.scopesSupported!==void 0&&{scopesSupported:[...options.scopesSupported]},...options.resourceName!==void 0&&{resourceName:options.resourceName},...options.serviceDocumentationUrl!==void 0&&{serviceDocumentationUrl:options.serviceDocumentationUrl}});return response!==void 0?response:next()}}function authInfoFromRequest(request){return getRequestBag(request).authInfo}init_dist();import{createRemoteJWKSet,jwtVerify,errors}from"jose";init_policy();function resolveToolInputSchema(definition){return definition.inputSchema??definition.schema}init_dist();var META_KEY="openai/ui";function record2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function validateEntrypointInput(definition){let entrypoints=definition.view?.entrypoints;if(!entrypoints?.length)return;let schema2=resolveToolInputSchema(definition),validate=schema2?fromJsonSchema2(schema2["~standard"].jsonSchema.input({target:"draft-2020-12"}))["~standard"].validate:void 0;for(let entrypoint of entrypoints){let payloads=entrypoint.type==="file"?entrypoint.extensions.map(extension=>({file:{name:`file${extension}`,resourceUri:"host-resource://opaque-handle"}})):[{}];if(entrypoint.type==="file"&&!validate)throw new TypeError(`Tool "${definition.name}" file entrypoint requires an inputSchema accepting { file: { name, resourceUri } }.`);for(let payload of payloads){let result=validate?.(payload);if(result&&("then"in result||result.issues))throw new TypeError(`Tool "${definition.name}" ${entrypoint.type} entrypoint launch arguments do not satisfy its inputSchema.`)}}}function buildEntrypointMeta(definition){let entrypoints=definition.view?.entrypoints;if(entrypoints===void 0)return definition._meta;let existing=definition._meta?.[META_KEY];return{...definition._meta,[META_KEY]:{...record2(existing)?existing:{},entrypoints:entrypoints.map(entry=>entry.type==="file"?{type:entry.type,extensions:[...entry.extensions]}:{type:entry.type})}}}var EVENT="mcp_use_sdk_event",ENDPOINT="https://eu.i.posthog.com/i/v0/e/",TOKEN="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI",CONTENT=/(^|_)(arguments?|args|body|command|headers?|location|message|organization|path|query|response|secret|subject|token|uri|url|user_agent)(_|$)/i,RESERVED=new Set("feature action sdk_generation telemetry_schema_version sdk_package sdk_version server_id runtime_id identity_stability distinct_id validation_run_id is_validation".split(" ")),runtimeId;function getRuntimeId(){return runtimeId??=crypto.randomUUID(),runtimeId}var once=new Set,pending=new Set,identities=new Map;function hasControl(value){return[...value].some(character=>{let code=character.charCodeAt(0);return code<32||code===127})}function env(name){return typeof process>"u"?void 0:process.env?.[name]}function safeEnv(name){let value=env(name);return value!==void 0&&value.length>0&&value.length<=128&&!hasControl(value)?value:void 0}function canPersistTelemetryIdentity(){return typeof process>"u"||process.versions?.node===void 0?!1:!("Deno"in globalThis)}function disabled(){if(env("MCP_USE_ANONYMIZED_TELEMETRY")==="false")return!0;try{return globalThis.__MCP_USE_ANONYMIZED_TELEMETRY__===!1||typeof localStorage<"u"&&localStorage.getItem("MCP_USE_ANONYMIZED_TELEMETRY")==="false"}catch{return!1}}function isUsageDisabled(){return disabled()}function clean(properties){return Object.fromEntries(Object.entries(properties).filter(([key,value])=>key.length>128||hasControl(key)||key.startsWith("$")||RESERVED.has(key)||CONTENT.test(key)||value===void 0?!1:typeof value=="string"?value.length<=128&&!hasControl(value):typeof value=="boolean"||typeof value=="number"&&Number.isFinite(value)))}async function identity(serverRoot){let projectId=safeEnv("MCP_USE_TELEMETRY_PROJECT_ID");if(projectId!==void 0)return{id:projectId,stability:"project"};if(serverRoot===void 0||!canPersistTelemetryIdentity())return{id:getRuntimeId(),stability:"process"};let existing=identities.get(serverRoot);if(existing!==void 0)return existing;let resolving=(async()=>{try{let fs=await import("fs/promises"),directory=`${serverRoot}/.mcp-use`,file=`${directory}/usage.json`,read=async()=>{try{let value=JSON.parse(await fs.readFile(file,"utf8"));if(typeof value=="object"&&value!==null&&"schemaVersion"in value&&value.schemaVersion===1&&"serverId"in value&&typeof value.serverId=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value.serverId))return value.serverId}catch{}},stored=await read();if(stored!==void 0)return{id:stored,stability:"server"};await fs.mkdir(directory,{recursive:!0,mode:448});let created=crypto.randomUUID();try{return await fs.writeFile(file,`${JSON.stringify({schemaVersion:1,serverId:created})}
|
|
771
|
+
`,{flag:"wx",mode:384}),{id:created,stability:"server"}}catch{let raced=await read();if(raced!==void 0)return{id:raced,stability:"server"}}}catch{}return{id:getRuntimeId(),stability:"process"}})();return identities.set(serverRoot,resolving),resolving}function capture(feature,action,properties,options,resolveIdentity){let validationId=safeEnv("MCP_USE_TELEMETRY_VALIDATION_ID");if(disabled()||env("NODE_ENV")==="test"&&validationId===void 0||pending.size>=16)return;if(options.onceKey!==void 0){if(once.has(options.onceKey))return;once.add(options.onceKey)}let rate=Math.max(0,Math.min(1,options.sampleRate??1));if(validationId===void 0&&Math.random()>=rate)return;let request=(async()=>{try{let resolvedIdentity=await resolveIdentity(),body=JSON.stringify({api_key:TOKEN,event:EVENT,properties:{...clean(properties),feature,action,sdk_generation:"v2",telemetry_schema_version:2,sdk_package:"mcp-use",sdk_version:"2.8.0-canary.0",server_id:resolvedIdentity.id,runtime_id:getRuntimeId(),identity_stability:resolvedIdentity.stability,distinct_id:resolvedIdentity.id,sample_rate:validationId===void 0?rate:1,$process_person_profile:!1,$geoip_disable:!0,...validationId!==void 0&&{is_validation:!0,validation_run_id:validationId}}});await fetch(ENDPOINT,{method:"POST",headers:{"content-type":"application/json"},keepalive:!0,body})}catch{return}})();pending.add(request),request.then(()=>pending.delete(request))}function recordUsage(feature,action,properties={},options={}){capture(feature,action,properties,options,()=>identity(options.serverRoot))}init_dist();function schema(validateValue){return{"~standard":{version:1,vendor:"mcp-use",validate(value){try{return{value:validateValue(value)}}catch(error3){return{issues:[{message:error3 instanceof Error?error3.message:String(error3)}]}}}}}}function object3(value){if(typeof value!="object"||value===null||Array.isArray(value))throw new TypeError("params must be an object");return value}var listParams=schema(value=>{let cursor=object3(value).cursor;if(cursor!==void 0&&typeof cursor!="string")throw new TypeError("cursor must be a string");return cursor===void 0?{}:{cursor}}),uriParams=schema(value=>{let params=object3(value);if(typeof params.uri!="string")throw new TypeError("uri must be a string");if(params.cursor!==void 0&&typeof params.cursor!="string")throw new TypeError("cursor must be a string");return{uri:params.uri,...typeof params.cursor=="string"&&{cursor:params.cursor}}}),anyResult=schema(value=>object3(value));function decodePathSegment(value){try{return decodeURIComponent(value)}catch{return value}}function registerSkillsRuntime(server,snapshot){let skills=new Map(snapshot.skills.map(skill=>[skill.uri,skill]));for(let resource2 of snapshot.resources)server.registerResource(resource2.uri,resource2.uri,{title:resource2.name,mimeType:resource2.mimeType},async()=>({contents:[{uri:resource2.uri,mimeType:resource2.mimeType,...resource2.text!==void 0?{text:resource2.text}:{blob:resource2.blob}}]}));server.server.setRequestHandler("skills/list",{params:listParams,result:anyResult},async()=>({skills:snapshot.skills})),server.server.setRequestHandler("skills/get",{params:uriParams,result:anyResult},async({uri})=>{let skill=skills.get(uri);if(skill===void 0)throw new ProtocolError(INVALID_PARAMS,`Unknown skill: ${uri}`);return{skill}}),server.server.setRequestHandler("resources/directory/read",{params:uriParams,result:anyResult},async({uri})=>{let normalized=uri.replace(/\/$/,""),knownDirectories=new Set(snapshot.directories.map(item=>item.uri)),prefix=`${normalized}/`,children=new Map;for(let resource2 of snapshot.resources){if(!resource2.uri.startsWith(prefix))continue;let remainder=resource2.uri.slice(prefix.length),[name]=remainder.split("/");if(name===void 0||name==="")continue;let childUri=`${normalized}/${name}`;children.set(childUri,{uri:childUri,name:decodePathSegment(name),mimeType:remainder.includes("/")?"inode/directory":resource2.mimeType})}for(let directory of snapshot.directories){if(!directory.uri.startsWith(prefix))continue;let remainder=directory.uri.slice(prefix.length);remainder===""||remainder.includes("/")||children.set(directory.uri,{uri:directory.uri,name:directory.name,mimeType:"inode/directory"})}if(!knownDirectories.has(normalized))throw new ProtocolError(INVALID_PARAMS,`Unknown skill directory: ${uri}`);return{resources:[...children.values()].sort((left,right)=>left.uri.localeCompare(right.uri))}})}var SKILLS_EXTENSION_ID="io.modelcontextprotocol/skills",registerSkills=Symbol.for("mcp-use.registerSkills");var registerViews=Symbol("mcp-use/registerViews");init_fetch_app();function resolveAssetUrl(assetPath,origin){if(!assetPath.startsWith("/"))throw new Error(`View manifest asset path must be origin-absolute (start with "/"); got ${JSON.stringify(assetPath)}`);return`${origin}${assetPath}`}function viewAssetsBasePath(basePath,viewName){return`${pathUnderBase(basePath,`_mcp-use/views/${viewName}`)}/`}function resolveExternalAssetUrl(assetPath,assetsBase,basePath,viewName){return assetPath.startsWith("http://")||assetPath.startsWith("https://")||assetPath.startsWith("data:")?assetPath:assetPath.startsWith("/")?resolveAssetUrl(assetPath,assetsBase):`${assetsBase}${viewAssetsBasePath(basePath,viewName)}${assetPath.replace(/^\/+/,"")}`}function resolvePublicBase(assetsBase,basePath){return`${assetsBase}${pathUnderBase(basePath,"_mcp-use/public")}/`}function escapeInlineScript(code){return code.replaceAll(/<\/script/gi,"<\\/script").replaceAll("<!--","\\x3C!--")}function escapeInlineStyle(css2){return css2.replaceAll(/<\/style/gi,"<\\/style")}function escapeHtml(value){return value.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">")}var VIEW_BOOTSTRAP_STYLE=`<style>
|
|
772
772
|
html,body,#root{background:transparent}
|
|
773
773
|
html,body{margin:0}
|
|
774
774
|
#root[data-mcp-use-loading]{display:flex;min-height:100vh;align-items:center;justify-content:center;flex-direction:column;gap:10px;color:rgba(127,127,127,.9)}
|
|
@@ -804,7 +804,7 @@ ${cssLinks}
|
|
|
804
804
|
${scriptTags}
|
|
805
805
|
<script type="module" src="${escapeHtml(entryUrl)}"></script>
|
|
806
806
|
</body>
|
|
807
|
-
</html>`}init_origin();init_fetch_app();var PUBLIC_BUILD_DIR=".mcp-use/build/views/public",PUBLIC_DEV_DIR="public",VIEW_ASSETS_BUILD_ROOT=".mcp-use/build/views",decodedAssets=new WeakMap;function serveEmbeddedAsset(assets,path,request,deferCors){let decoded;try{decoded=decodeURIComponent(path)}catch{return new Response("Not Found",{status:404})}if(decoded.includes("\\")||decoded.split("/").includes(".."))return new Response("Not Found",{status:404});let asset=Object.hasOwn(assets,decoded)?assets[decoded]:void 0;if(asset===void 0)return new Response("Not Found",{status:404});let body=null;return request.method!=="HEAD"&&(body=decodedAssets.get(asset)??null,body===null&&(body=Uint8Array.from(atob(asset.body),character=>character.charCodeAt(0)),decodedAssets.set(asset,body))),new Response(body,{headers:{"Content-Type":asset.contentType,"Cache-Control":"public, max-age=0, must-revalidate",...deferCors!==!0&&{"Access-Control-Allow-Origin":"*"}}})}function createViewAssetsHandler(basePath,views,options){if(views.size===0)return;let assetsPrefix=pathUnderBase(basePath,"_mcp-use/views"),projectRoot=options?.projectRoot??process.cwd();return async request=>{if(request.method!=="GET"&&request.method!=="HEAD")return new Response("Method Not Allowed",{status:405});if(!matchesPathPrefix(request,assetsPrefix))return new Response("Not Found",{status:404});let remainder=pathnameOf(request).slice(assetsPrefix.length+1),slash=remainder.indexOf("/");if(slash<=0||slash===remainder.length-1)return new Response("Not Found",{status:404});let viewName=remainder.slice(0,slash),subpath=remainder.slice(slash+1),entry=views.get(viewName);if(entry===void 0||entry.kind!=="external")return new Response("Not Found",{status:404});if(options?.assets!==void 0)return serveEmbeddedAsset(options.assets,remainder,request,options.deferCors);let[{join},{resolvePublicFilePath:resolvePublicFilePath2,servePublicFile:servePublicFile2}]=await Promise.all([import("path"),Promise.resolve().then(()=>(init_public_route(),public_route_exports))]),viewRoot=join(projectRoot,VIEW_ASSETS_BUILD_ROOT,viewName),diskPath=await resolvePublicFilePath2(viewRoot,subpath);return diskPath===null?new Response("Not Found",{status:404}):await servePublicFile2(diskPath,{...options?.deferCors===!0&&{deferCors:!0},...request.method==="HEAD"&&{head:!0}})}}function createViewPublicHandler(basePath,views,options){if(views.size===0&&options?.enabled!==!0)return;let publicPrefix=pathUnderBase(basePath,"_mcp-use/public"),subdir=options?.dev===!0?PUBLIC_DEV_DIR:PUBLIC_BUILD_DIR,projectRoot=options?.projectRoot??process.cwd();return async request=>{if(request.method!=="GET"&&request.method!=="HEAD")return new Response("Method Not Allowed",{status:405});if(!matchesPathPrefix(request,publicPrefix))return new Response("Not Found",{status:404});let encodedSubpath=pathnameOf(request).slice(publicPrefix.length+1),subpath;try{subpath=decodeURIComponent(encodedSubpath)}catch{return new Response("Not Found",{status:404})}if(subpath.length===0)return new Response("Not Found",{status:404});if(options?.assets!==void 0)return serveEmbeddedAsset(options.assets,`public/${encodedSubpath}`,request,options.deferCors);let[{join},{resolvePublicFilePath:resolvePublicFilePath2,servePublicFile:servePublicFile2}]=await Promise.all([import("path"),Promise.resolve().then(()=>(init_public_route(),public_route_exports))]),publicRoot=join(projectRoot,subdir),diskPath=await resolvePublicFilePath2(publicRoot,subpath);return diskPath===null?new Response("Not Found",{status:404}):await servePublicFile2(diskPath,{...options?.deferCors===!0&&{deferCors:!0},...request.method==="HEAD"&&{head:!0}})}}var CATEGORY_ENV={connectDomains:"CSP_CONNECT_DOMAINS",resourceDomains:"CSP_RESOURCE_DOMAINS",frameDomains:"CSP_FRAME_DOMAINS",baseUriDomains:"CSP_BASE_URI_DOMAINS"};function parseDomainList(raw2){return raw2===void 0||raw2.trim()===""?[]:raw2.split(",").map(s=>s.trim()).filter(s=>s.length>0)}function readEnvDomains(name){if(typeof process>"u")return;let raw2=process.env[name];if(!(raw2===void 0||raw2.trim()===""))return parseDomainList(raw2)}function readCspUrlsShortcut(){return readEnvDomains("CSP_URLS")??[]}function readEnvDomainsForCategory(category){let perCategory=readEnvDomains(CATEGORY_ENV[category]);return perCategory!==void 0?perCategory:readCspUrlsShortcut()}function mergeDomainLists(...segments){let seen=new Set,out=[];for(let segment of segments)for(let domain of segment)seen.has(domain)||(seen.add(domain),out.push(domain));return out}function toWebSocketOrigin(serverOrigin){return serverOrigin.startsWith("https://")?`wss://${serverOrigin.slice(8)}`:serverOrigin.startsWith("http://")?`ws://${serverOrigin.slice(7)}`:serverOrigin}function buildMergedResourceCsp(authorFacts,options){let author=authorFacts?.csp,mcpConnectAuto=[];options.serverOrigin!==""&&(mcpConnectAuto.push(options.serverOrigin),options.hmrWs===!0&&mcpConnectAuto.push(toWebSocketOrigin(options.serverOrigin)));let mcpResourceAuto=[],resourceOrigin=options.explicitAssetsBase?options.assetsOrigin:options.serverOrigin;resourceOrigin!==""&&mcpResourceAuto.push(resourceOrigin);let connectDomains=mergeDomainLists(author?.connectDomains??[],readEnvDomainsForCategory("connectDomains"),mcpConnectAuto),resourceDomains=mergeDomainLists(author?.resourceDomains??[],readEnvDomainsForCategory("resourceDomains"),mcpResourceAuto),frameDomains=mergeDomainLists(author?.frameDomains??[],readEnvDomainsForCategory("frameDomains")),baseUriDomains=mergeDomainLists(author?.baseUriDomains??[],readEnvDomainsForCategory("baseUriDomains")),scriptDirectives=mergeDomainLists(author?.scriptDirectives??[],options.hmrWs===!0?["'unsafe-eval'"]:[]);return{...author,connectDomains,resourceDomains,frameDomains,baseUriDomains,...scriptDirectives.length>0?{scriptDirectives}:{}}}init_origin();function buildToolUiMeta(viewName,visibility,existingMetadata){if(viewName===void 0&&visibility===void 0&&existingMetadata===void 0)return;let meta2={...existingMetadata},existingUi=existingMetadata?.["ui"],existingUiIsObject=typeof existingUi=="object"&&existingUi!==null&&!Array.isArray(existingUi),ui=existingUiIsObject?{...existingUi}:{};if(viewName!==void 0){let resourceUri=viewResourceUri(viewName);ui.resourceUri=resourceUri,meta2[UI_RESOURCE_URI_META_KEY]=resourceUri}else delete ui.resourceUri,delete meta2[UI_RESOURCE_URI_META_KEY];return visibility!==void 0?ui.visibility=[visibility]:delete ui.visibility,(viewName!==void 0||visibility!==void 0||existingUiIsObject)&&(meta2["ui"]=ui),meta2}function buildToolResultUiMeta(viewName){let resourceUri=viewResourceUri(viewName);return{ui:{resourceUri},[UI_RESOURCE_URI_META_KEY]:resourceUri}}function resolveCspOptions(options){let request=options?.request,serverOrigin=options?.serverOrigin??(request!==void 0?resolveServerOrigin(request):""),assetsBase=options?.assetsBase??(request!==void 0?resolveAssetsBase(request):serverOrigin);return{serverOrigin,assetsOrigin:originFromAssetsBase(assetsBase),explicitAssetsBase:hasExplicitAssetsBase(),...options?.hmrWs===!0?{hmrWs:!0}:{}}}function buildResourceUiMeta(authorFacts,options){let ui={csp:buildMergedResourceCsp(authorFacts,resolveCspOptions(options))};return authorFacts?.permissions!==void 0&&(ui.permissions=authorFacts.permissions),authorFacts?.domain!==void 0&&(ui.domain=authorFacts.domain),authorFacts?.prefersBorder!==void 0&&(ui.prefersBorder=authorFacts.prefersBorder),{ui}}function viewResourceConfig(_viewName,_entry,authorFacts,options){return{mimeType:UI_MIME_TYPE,...authorFacts?.description!==void 0&&{description:authorFacts.description},_meta:buildResourceUiMeta(authorFacts,options)}}var CLAUDE_RESOURCE_DOMAIN_SUFFIX=".claudemcpcontent.com",CLAUDE_RESOURCE_DOMAIN_HASH_LENGTH=32;function isClaudeClient(clientInfo){let name=clientInfo?.name;return typeof name=="string"&&name.toLowerCase().includes("claude")}async function computeClaudeResourceDomain(domain){if(domain.endsWith(CLAUDE_RESOURCE_DOMAIN_SUFFIX))return domain;let digest=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(domain));return`${Array.from(new Uint8Array(digest),byte=>byte.toString(16).padStart(2,"0")).join("").slice(0,CLAUDE_RESOURCE_DOMAIN_HASH_LENGTH)}${CLAUDE_RESOURCE_DOMAIN_SUFFIX}`}async function applyClaudeResourceDomain(meta2,clientInfo,userAgent){let effectiveClientInfo=typeof clientInfo?.name=="string"||typeof userAgent!="string"||userAgent.trim().length===0?clientInfo:{...clientInfo,name:userAgent.trim()};if(!isClaudeClient(effectiveClientInfo))return meta2;let ui=meta2["ui"];if(typeof ui!="object"||ui===null||Array.isArray(ui))return meta2;let domain=ui.domain;return typeof domain!="string"||domain.length===0?meta2:{...meta2,ui:{...ui,domain:await computeClaudeResourceDomain(domain)}}}function record2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)?value:void 0}function productId(value,fallback){if(typeof value!="string")return fallback;let normalized=value.trim();return normalized.length>0&&normalized.length<=64&&![...normalized].some(character=>{let code=character.charCodeAt(0);return code<32||code===127})?normalized:fallback}function clientUsageFromBody(body){if(!isJSONRPCRequest(body))return;let params=record2(body.params);if(body.method==="initialize"){let info2=record2(params?.clientInfo),capabilities2=record2(params?.capabilities)??{};return clientUsage(info2,capabilities2,params?.protocolVersion,"legacy")}let meta2=record2(params?._meta),info=record2(meta2?.[CLIENT_INFO_META_KEY]),capabilities=record2(meta2?.[CLIENT_CAPABILITIES_META_KEY]);if(!(info===void 0||capabilities===void 0))return clientUsage(info,capabilities,meta2?.[PROTOCOL_VERSION_META_KEY],"modern")}function clientUsage(info,capabilities,protocolVersion,era){let typedCapabilities=capabilities;return{client_name:productId(info?.name,"other"),client_version:productId(info?.version,"unknown"),protocol_era:era,protocol_version:productId(protocolVersion,"unknown"),connection_mode:era==="modern"?"stateless_request":"legacy_session",sampling_capability:Object.hasOwn(capabilities,"sampling"),elicitation_capability:Object.hasOwn(capabilities,"elicitation"),roots_capability:Object.hasOwn(capabilities,"roots"),extensions_capability:Object.hasOwn(capabilities,"extensions"),views_capability:supportsViews(typedCapabilities),capability_count:Object.keys(capabilities).length}}function registerFetchMiddleware(app,middleware){app.use("*",async(context,next)=>{let response=await middleware(context.req.raw,async()=>(await next(),context.res));return context.res=response,response})}var MCPServer=class _MCPServer{#config;#requestLogPrefix;#branding;#tools=new Map;#resources=new Map;#resourceTemplates=new Map;#prompts=new Map;#views=new Map;#skills;#skillsPrimed=!1;#skillsDiscovery;#viewBindings=new Map;#viewsPrimed=!1;#embeddedViewAssets;#viewsDevMode=!1;#viewsProjectRoot=process.cwd();#fetchHandler;#httpApp;#handler;#eventBus;#httpServer;#oauthResource;#oauthResourceResolved=!1;#oauthResourceConfigurationAbsent=!1;#instructionsOverride;#oauthProviderSetupRan=!1;#oauthProviderSetupFailure;#hostValidated=!1;#mcpMiddlewares=[];#mcpEventListeners=[];#usageScope;#openApiTools=new Set;#proxiedTools=new Set;#proxiedResources=new Set;#proxiedPrompts=new Set;#httpMiddlewareCount=0;#proxyServersConfigured=0;#proxyServersConnected=0;#proxyToolsDiscovered=0;#proxyResourcesDiscovered=0;#proxyPromptsDiscovered=0;#proxyOwners=[];#proxyOperations=new Set;#closed=!1;app;get;post;put;patch;delete;all;fetch;static fromOpenAPI(options){let server=new _MCPServer({name:options.name??options.spec.info.title,version:options.version??options.spec.info.version??"1.0.0"});registerOpenAPITools(server,options);for(let name of server.#tools.keys())server.#openApiTools.add(name);return server}constructor(config2){if(assertServerConfig(config2),this.#config=config2,this.#branding=normalizeServerBranding(config2),this.app=new Hono3,this.app.use("*",async(context,next)=>{getRequestBag(context.req.raw).honoContext=context,await next()}),this.get=this.app.get.bind(this.app),this.post=this.app.post.bind(this.app),this.put=this.app.put.bind(this.app),this.patch=this.app.patch.bind(this.app),this.delete=this.app.delete.bind(this.app),this.all=this.app.all.bind(this.app),this.fetch=async(request,env2,executionCtx)=>(await this.#ensureSkillsPrimed(),this.#ensureMounted("handler"),this.#httpApp.fetch(request,env2,executionCtx)),config2.oauth!==void 0){let mcpUrl=typeof process>"u"?void 0:process.env.MCP_URL,resource2=resolveConfiguredOAuthResource({provider:config2.oauth,basePath:this.#basePath(),...mcpUrl!==void 0&&{mcpUrl}});this.#oauthResource=resource2,this.#oauthResourceResolved=resource2!==void 0,this.#oauthResourceConfigurationAbsent=resource2===void 0}}get basePath(){return this.#basePath()}get host(){return this.#config.host}get port(){return this.#config.port}get branding(){return this.#branding}getHandler(){return this.fetch}tool(definition,callback){this.#assertNotStarted("tool",definition.name);let schemes=this.#resolveSecuritySchemes(definition);return this.#validateToolViewBinding(definition),this.#openApiTools.delete(definition.name),this.#proxiedTools.delete(definition.name),this.#tools.set(definition.name,{definition,callback,schemes}),Object.freeze({name:definition.name})}[registerViews](views,options){if(this.#viewsPrimed)throw new Error("Cannot prime views: the views registry is already primed on this server instance.");this.#assertNotStarted("views","manifest"),this.#viewsDevMode=options?.dev===!0,this.#embeddedViewAssets=options?.assets,options?.projectRoot!==void 0&&(this.#viewsProjectRoot=options.projectRoot);for(let[name,entry]of Object.entries(views))this.#views.set(name,entry);this.#viewsPrimed=!0}__primeViews(views,options){this[registerViews](views,options)}[registerSkills](snapshot){this.#assertNotStarted("skills","snapshot"),this.#skills=snapshot,this.#skillsPrimed=!0}__primeSkills(snapshot){this[registerSkills](snapshot)}__skillsConfig(){return this.#config.skills}async#discoverSkills(projectRoot,conventionalDirectory){let{discoverConfiguredSkills}=await import("#mcp-use-skills-loader"),snapshot=discoverConfiguredSkills(this.#config.skills,projectRoot,conventionalDirectory);return this[registerSkills](snapshot),snapshot}resource(definition,callback){this.#assertNotStarted("resource",definition.name);let previous=this.#resources.get(definition.name);return previous!==void 0&&this.#proxiedResources.delete(previous.definition.uri),this.#resources.set(definition.name,{definition,callback}),this}resourceTemplate(definition,callback){this.#assertNotStarted("resourceTemplate",definition.name);let complete=definition.complete===void 0?void 0:normalizeCompletions(definition.complete);return this.#resourceTemplates.set(definition.name,{definition,...complete!==void 0&&{complete},callback}),this}prompt(definition,callback){return this.#assertNotStarted("prompt",definition.name),this.#proxiedPrompts.delete(definition.name),this.#prompts.set(definition.name,{definition,callback}),this}async proxy(input){this.#assertOpen("proxy()");let operation=(async()=>{let{isProxyConnection:isProxyConnection2,mountProxyConnection:mountProxyConnection2,mountProxyServers:mountProxyServers2}=await Promise.resolve().then(()=>(init_mcp_proxy(),mcp_proxy_exports));if(isProxyConnection2(input)){this.#proxyServersConfigured+=1,await mountProxyConnection2(this.#proxyHost(),input);return}this.#proxyServersConfigured+=Object.keys(input).length,await mountProxyServers2(this.#proxyHost(),input)})();this.#proxyOperations.add(operation);try{await operation}finally{this.#proxyOperations.delete(operation)}}use(patternOrHandler,...handlers){if(typeof patternOrHandler=="string"&&patternOrHandler.startsWith("mcp:")){this.#assertNotStarted("middleware",patternOrHandler);let handler=handlers[0];return this.#mcpMiddlewares.push(createMcpMiddlewareEntry(patternOrHandler,handler)),this}return this.app.use.call(this.app,patternOrHandler,...handlers),this.#httpMiddlewareCount+=typeof patternOrHandler=="function"?1:handlers.length,this}on(pattern,handler){return this.#assertNotStarted("event listener",pattern),this.#mcpEventListeners.push(createMcpEventListenerEntry(pattern,handler)),this}__setEventBus(bus){this.#assertNotStarted("event bus","shared"),this.#eventBus=bus}__setRequestLogPrefix(prefix){this.#assertNotStarted("request log prefix","development"),this.#requestLogPrefix=prefix}__mount(){if(!this.#skillsPrimed)throw new Error("Cannot mount before skills discovery. CLI tooling must call __primeSkills first.");this.#ensureMounted("handler")}async notifyToolsChanged(){await this.#ensureSkillsPrimed(),await this.#ensureMounted("handler").handler.notify.toolsChanged()}async notifyPromptsChanged(){await this.#ensureSkillsPrimed(),await this.#ensureMounted("handler").handler.notify.promptsChanged()}async notifyResourcesChanged(){await this.#ensureSkillsPrimed(),await this.#ensureMounted("handler").handler.notify.resourcesChanged()}async notifyResourceUpdated(uri){await this.#ensureSkillsPrimed(),await this.#ensureMounted("handler").handler.notify.resourceUpdated(uri)}async listen(port=void 0,options={}){this.#assertOpen("listen()"),await this.#ensureSkillsPrimed();let host=resolveListenHost(options.host,this.#config.host),requestedPort=resolveListenPort(port,this.#config.port);return this.#assertListenOAuthConfiguration(host),new Promise((resolve,reject)=>{let resolveFetch,rejectFetch,fetchReady=new Promise((resolveFetchPromise,rejectFetchPromise)=>{resolveFetch=resolveFetchPromise,rejectFetch=rejectFetchPromise});fetchReady.catch(()=>{});let settled=!1,rejectAndClose=error3=>{settled||(settled=!0,reject(error3)),rejectFetch?.(error3),new Promise(closeResolve=>server.close(()=>closeResolve())).catch(()=>{}).finally(()=>{this.#httpServer===server&&(this.#httpServer=void 0)})},nodeHandler=toNodeHandler({fetch:async request=>(await fetchReady)(request)}),server=createNodeHttpServer((req,res)=>{nodeHandler(req,res)});server.once("error",rejectAndClose),server.listen(requestedPort,host,()=>{try{let address=server.address(),boundPort=typeof address=="object"&&address!==null?address.port:requestedPort,{fetch:fetch2}=this.#ensureMounted("listen",boundPort,host);resolveFetch?.(fetch2),settled||(settled=!0,resolve({port:boundPort,url:`http://localhost:${boundPort}${this.#basePath()}`}))}catch(error3){rejectAndClose(error3)}}),this.#httpServer=server})}async close(){this.#closed=!0,await Promise.allSettled([...this.#proxyOperations]);let errors2=[],proxyOwners=this.#proxyOwners.splice(0),ownerResults=await Promise.allSettled(proxyOwners.map(owner=>owner.close()));for(let result of ownerResults)result.status==="rejected"&&errors2.push(result.reason);try{await this.#handler?.close()}catch(error3){errors2.push(error3)}let httpServer=this.#httpServer;if(httpServer!==void 0)try{await new Promise((resolve,reject)=>{httpServer.close(err=>err?reject(err):resolve())}),this.#httpServer=void 0}catch(error3){errors2.push(error3)}if(errors2.length>0)throw new AggregateError(errors2,"Failed to close MCP server cleanly")}#assertOpen(operation){if(this.#closed)throw operation!==void 0?new Error(`Cannot call ${operation} after the server has closed.`):new Error("Cannot use the server after it has closed.")}#basePath(){return this.#config.basePath??"/mcp"}#resolveOAuthResource(mode,listenPort,listenHost){if(this.#config.oauth===void 0)return;if(this.#oauthResourceResolved)return this.#oauthResource;let host=listenHost??this.#config.host??"127.0.0.1",localListen=mode==="listen"&&listenPort!==void 0&&["127.0.0.1","localhost","::1"].includes(host);if(this.#oauthResourceConfigurationAbsent&&localListen)return this.#oauthResource=resolveLocalOAuthResource(`http://localhost:${listenPort}`,this.#basePath()),this.#oauthResourceResolved=!0,this.#oauthResource;throw new Error("OAuth requires an explicit resource or MCP_URL when using server.fetch or listening on a non-local host")}#assertListenOAuthConfiguration(host){if(this.#config.oauth!==void 0&&!["127.0.0.1","localhost","::1"].includes(host)&&!this.#oauthResourceResolved)throw new Error("OAuth listen() on a public or wildcard host requires an explicit provider resource or valid MCP_URL.")}#assertNotStarted(kind,name){if(this.#handler!==void 0)throw new Error(`Cannot register ${kind} "${name}" after the server has started: registrations are replayed per request from the registry, so register everything before listen()/server.fetch.`)}#trackConfigured(){recordUsage("server","configured",{tools_total:this.#tools.size,tools_local:this.#tools.size-this.#openApiTools.size-this.#proxiedTools.size,tools_openapi:this.#openApiTools.size,tools_proxied:this.#proxiedTools.size,resources:this.#resources.size,resource_templates:this.#resourceTemplates.size,prompts:this.#prompts.size,views:this.#views.size,proxy_servers_configured:this.#proxyServersConfigured,proxy_servers_connected:this.#proxyServersConnected,proxy_tools_discovered:this.#proxyToolsDiscovered,proxy_resources_discovered:this.#proxyResourcesDiscovered,proxy_prompts_discovered:this.#proxyPromptsDiscovered,proxy_tools_mounted:this.#proxiedTools.size,proxy_resources_mounted:this.#proxiedResources.size,proxy_prompts_mounted:this.#proxiedPrompts.size,http_middleware:this.#httpMiddlewareCount,mcp_middleware:this.#mcpMiddlewares.length,observers_before:this.#mcpEventListeners.filter(({phase})=>phase==="before").length,observers_complete:this.#mcpEventListeners.filter(({phase})=>phase==="complete").length,oauth_configured:this.#config.oauth!==void 0,cors_configured:this.#config.cors!==void 0,request_state_configured:this.#config.requestState!==void 0,legacy_policy:this.#config.legacy??"stateless"},{onceKey:`${this.#usageScopeId()}:server`,serverRoot:this.#viewsProjectRoot})}#trackClient(body){let client=clientUsageFromBody(body);client!==void 0&&recordUsage("client","observed",{...client},{onceKey:`${this.#usageScopeId()}:client:${JSON.stringify(client)}`,serverRoot:this.#viewsProjectRoot})}#usageScopeId(){return this.#usageScope??=crypto.randomUUID(),this.#usageScope}#runOAuthProviderSetup(resource2,basePath){let setup=this.#config.oauth?.setup;if(setup===void 0||this.#oauthProviderSetupRan)return;if(this.#oauthProviderSetupFailure!==void 0)throw this.#oauthProviderSetupFailure.error;let active=!0,assertActive=method=>{if(!active)throw new Error(`[mcp-use] OAuthProviderHost.${method}() called after the provider's setup hook returned; call it from setup().`)},host={resourceUrl:resource2,basePath,mixedAuth:this.#config.mixedAuth===!0,use:(pattern,handler)=>{assertActive("use"),this.use(pattern,handler)},tool:(definition,callback)=>{if(assertActive("tool"),this.#tools.has(definition.name))throw new Error(`[mcp-use] Tool "${definition.name}" is reserved by the OAuth provider; rename the application tool.`);return this.tool(definition,callback)},resource:(definition,callback)=>{if(assertActive("resource"),this.#resources.has(definition.name))throw new Error(`[mcp-use] Resource "${definition.name}" is reserved by the OAuth provider; rename the application resource.`);this.resource(definition,callback)},resourceTemplate:(definition,callback)=>{if(assertActive("resourceTemplate"),this.#resourceTemplates.has(definition.name))throw new Error(`[mcp-use] Resource template "${definition.name}" is reserved by the OAuth provider; rename the application resource template.`);this.resourceTemplate(definition,callback)},prompt:(definition,callback)=>{if(assertActive("prompt"),this.#prompts.has(definition.name))throw new Error(`[mcp-use] Prompt "${definition.name}" is reserved by the OAuth provider; rename the application prompt.`);this.prompt(definition,callback)},listTools:()=>(assertActive("listTools"),[...this.#tools.values()].map(({definition})=>definition)),instructions:transform2=>{assertActive("instructions"),this.#instructionsOverride=transform2(this.#instructionsOverride??this.#config.instructions)}};try{let returned=setup(host);if(typeof returned?.then=="function")throw Promise.resolve(returned).catch(()=>{}),new TypeError("[mcp-use] The OAuth provider's setup hook must be synchronous but returned a promise. Do async work before creating the provider.")}catch(error3){throw this.#oauthProviderSetupFailure={error:error3},error3}finally{active=!1}this.#oauthProviderSetupRan=!0}#proxyHost(){return{isStarted:()=>this.#handler!==void 0,hasTool:name=>this.#tools.has(name),hasResource:name=>this.#resources.has(name),hasPrompt:name=>this.#prompts.has(name),registerTool:(definition,callback)=>{this.#assertNotStarted("tool",definition.name),this.#proxiedTools.add(definition.name),this.#tools.set(definition.name,{definition,callback,schemes:this.#resolveSecuritySchemes(definition)})},registerResource:(definition,callback)=>{this.#assertNotStarted("resource",definition.name),this.#proxiedResources.add(definition.uri),this.#resources.set(definition.name,{definition,callback})},registerPrompt:(definition,callback)=>{this.#assertNotStarted("prompt",definition.name),this.#proxiedPrompts.add(definition.name),this.#prompts.set(definition.name,{definition,callback})},trackOwner:owner=>{this.#proxyOwners.push(owner)},trackNamespace:({tools,resources,prompts})=>{this.#proxyServersConnected+=1,this.#proxyToolsDiscovered+=tools,this.#proxyResourcesDiscovered+=resources,this.#proxyPromptsDiscovered+=prompts}}}async#ensureSkillsPrimed(){this.#skillsPrimed||(this.#skillsDiscovery??=this.#discoverSkills(typeof process>"u"?".":process.cwd(),"skills").then(()=>{}),await this.#skillsDiscovery)}#validationPolicy(mode,listenHost){let{allowedHosts,allowedOrigins}=this.#config,host=listenHost??this.#config.host??"127.0.0.1",localhostBind=["127.0.0.1","localhost","::1"].includes(host),hosts=allowedHosts!==void 0?[...new Set([...localhostAllowedHostnames(),...allowedHosts])]:mode==="listen"&&localhostBind?localhostAllowedHostnames():void 0,origins=allowedOrigins!==void 0?[...new Set([...localhostAllowedOrigins(),...allowedOrigins])]:void 0;return{hosts,origins}}#ensureMounted(mode,listenPort,listenHost){if(this.#assertOpen(),this.#fetchHandler===void 0||this.#handler===void 0){let{hosts,origins}=this.#validationPolicy(mode,listenHost),basePath=this.#basePath(),nestedBasePath=basePath==="/"?"":basePath,httpApp=new Hono3,middlewares=[requestLogger({...this.#config.logging,mcpPath:basePath,prefix:this.#requestLogPrefix}),jsonBodyMiddleware()],corsConfig=this.#config.cors;corsConfig!==void 0&&middlewares.unshift(corsFetchMiddleware(corsConfig));let deferViewCors=isGlobalCorsEnabled(corsConfig);hosts!==void 0&&middlewares.unshift(hostValidationMiddleware(hosts)),origins!==void 0&&middlewares.push(originValidationMiddleware(origins)),hosts===void 0&&mode==="listen"&&console.warn(`[mcp-use] listen() is serving on ${listenHost} without Host validation. Behind a platform edge that only routes your own domains this is expected; if this process is reachable directly, set allowedHosts to restrict it.`);let resource2=this.#resolveOAuthResource(mode,listenPort,listenHost);if(resource2!==void 0){let provider=this.#config.oauth;middlewares.push(oauthMetadata(provider,resource2))}for(let middleware of middlewares)registerFetchMiddleware(httpApp,middleware);resource2!==void 0&&this.#runOAuthProviderSetup(resource2,basePath),this.#validateViewBindingsAtMount();let{handler,fetch:mcpFetch}=createMcpMount(ctx=>this.#buildSdkServer(ctx),{path:basePath,...(this.#config.legacy!==void 0||this.#eventBus!==void 0)&&{handler:{...this.#config.legacy!==void 0&&{legacy:this.#config.legacy},...this.#eventBus!==void 0&&{bus:this.#eventBus}}},...resource2!==void 0&&{authInfo:request=>authInfoFromRequest(request)}});if(resource2!==void 0){let provider=this.#config.oauth,providerOptions=getOAuthProviderOptions(provider),mixedAuth=this.#config.mixedAuth===!0,gateOptions={verifier:wrapOAuthTokenVerifier(provider,resource2),resourceMetadataUrl:getOAuthProtectedResourceMetadataUrl(resource2),baselineScopes:providerOptions.requiredScopes??[],mixedAuth,toolSchemes:name=>this.#tools.get(name)?.schemes,openResourceUris:[...this.#viewBindings.keys()].map(viewResourceUri)},gate;httpApp.use("*",async(context,next)=>{if(new URL(context.req.url).pathname!==basePath){await next();return}if((this.#config.publicLandingPage===!0||mixedAuth)&&isHtmlNavigationRequest(context.req.raw)){await next();return}gate??=Promise.resolve().then(()=>(init_gate(),gate_exports)).then(({createOAuthGate:createOAuthGate2})=>createOAuthGate2(gateOptions));let response=await(await gate)(context.req.raw,async()=>(await next(),context.res));return context.res=response,response})}let mcpRouteHandler=request=>{let body=getRequestBag(request).parsedBody;return isJSONRPCRequest(body)&&(this.#trackConfigured(),this.#trackClient(body)),mcpFetch(request)},endpointHandler=async request=>isHtmlNavigationRequest(request)?(async()=>{let{createLandingPageResponse:createLandingPageResponse2}=await Promise.resolve().then(()=>(init_landing_handler(),landing_handler_exports));return createLandingPageResponse2(request,basePath,this.#config,this.#branding,this.#tools.values(),this.#prompts.values(),this.#resources.values())})():mcpRouteHandler(request),brandingDevMode=this.#viewsPrimed?this.#viewsDevMode:process.env.NODE_ENV!=="production",faviconHandler=createFaviconHandler(this.#branding,{dev:brandingDevMode,projectRoot:this.#viewsProjectRoot,deferCors:deferViewCors});faviconHandler!==void 0&&this.app.all("/favicon.ico",context=>faviconHandler(context.req.raw));let viewHandler=createViewPublicHandler(basePath,this.#views,{dev:this.#viewsPrimed?this.#viewsDevMode:brandingDevMode,projectRoot:this.#viewsProjectRoot,enabled:hasLocalBrandingAsset(this.#branding),deferCors:deferViewCors,...this.#embeddedViewAssets!==void 0&&{assets:this.#embeddedViewAssets}});if(viewHandler!==void 0&&this.app.on(["GET","HEAD"],`${nestedBasePath}/_mcp-use/public/*`,context=>viewHandler(context.req.raw)),!this.#viewsDevMode){let viewAssetsHandler=createViewAssetsHandler(basePath,this.#views,{projectRoot:this.#viewsProjectRoot,deferCors:deferViewCors,...this.#embeddedViewAssets!==void 0&&{assets:this.#embeddedViewAssets}});viewAssetsHandler!==void 0&&this.app.on(["GET","HEAD"],`${nestedBasePath}/_mcp-use/views/*`,context=>viewAssetsHandler(context.req.raw))}this.app.all(basePath,context=>endpointHandler(context.req.raw)),httpApp.route("/",this.app),this.#httpApp=httpApp,this.#fetchHandler=async request=>httpApp.fetch(request),this.#handler=handler,this.#hostValidated=hosts!==void 0}else if(mode==="listen"&&!this.#hostValidated&&this.#validationPolicy("listen",listenHost).hosts!==void 0)throw new Error("Cannot listen() on a localhost bind after server.fetch mounted the app without Host validation (server.fetch expects a platform edge in front). Call listen() first, or set allowedHosts.");return{fetch:this.#fetchHandler,handler:this.#handler}}#validateToolViewBinding(definition){let view=definition.view;if(view===void 0)return;if(definition.outputSchema===void 0)throw new Error(`Tool "${definition.name}" declares view "${view.name}" but has no outputSchema. View-bound tools require an outputSchema \u2014 the view reads structuredContent typed from it. Use outputSchema: z.object({}) for a view that takes no structured output.`);let existing=this.#viewBindings.get(view.name);if(existing!==void 0)throw new Error(`View "${view.name}" is already bound to tool "${existing.toolName}"; tool "${definition.name}" cannot bind the same view. Each view may be bound to one tool.`);this.#viewBindings.set(view.name,{toolName:definition.name,config:view})}#validateViewBindingsAtMount(){if(this.#viewBindings.size>0&&!this.#viewsPrimed){let first=[...this.#tools.values()].find(entry=>entry.definition.view!==void 0),viewName=first?.definition.view?.name??"unknown";throw new Error(`Tool "${first?.definition.name??"unknown"}" is bound to view "${viewName}" but no views were primed. Run \`mcp-use build\` and deploy the built entry, or in dev let the CLI prime views automatically.`)}for(let entry of this.#tools.values()){let viewName=entry.definition.view?.name;if(viewName!==void 0&&!this.#views.has(viewName))throw new Error(`Tool "${entry.definition.name}" is bound to view "${viewName}" which is not in the primed views registry. Run \`mcp-use build\` and deploy the built entry, or in dev let the CLI prime views automatically.`)}for(let viewName of this.#views.keys())this.#viewBindings.has(viewName)||console.warn(`[mcp-use] View "${viewName}" is registered but no tool binds it.`)}#buildSdkServer(ctx){let{name,version:version2,title,description}=this.#config,instructions=this.#instructionsOverride??this.#config.instructions,authInfo=ctx.authInfo,server=new McpServer({name,version:version2,...title!==void 0&&{title},...description!==void 0&&{description},...this.#branding.websiteUrl!==void 0&&{websiteUrl:this.#branding.websiteUrl},...this.#branding.icons!==void 0&&{icons:resolveImplementationIcons(this.#branding.icons,ctx.requestInfo,this.#basePath())}},{capabilities:{logging:{},tools:{listChanged:!0},prompts:{listChanged:!0},resources:{listChanged:!0,subscribe:!0},...this.#skills!==void 0&&{extensions:{[SKILLS_EXTENSION_ID]:{directoryRead:!0}}}},...instructions!==void 0&&{instructions},...authInfo!==void 0&&{authInfo},...this.#config.requestState!==void 0&&{requestState:this.#config.requestState}}),request=ctx.requestInfo,viewMetaOptions=request!==void 0?{request,hmrWs:this.#viewsDevMode}:{hmrWs:this.#viewsDevMode},basePath=this.#basePath();for(let entry of this.#tools.values())this.#registerTool(server,entry);for(let entry of this.#resources.values())this.#registerResource(server,entry);for(let entry of this.#resourceTemplates.values())this.#registerResourceTemplate(server,entry);for(let entry of this.#prompts.values())this.#registerPrompt(server,entry);for(let[viewName,viewEntry]of this.#views.entries())this.#registerViewResource(server,viewName,viewEntry,viewMetaOptions,basePath);return this.#skills!==void 0&®isterSkillsRuntime(server,this.#skills),this.#wrapListHandlers(server),server}#createMiddlewareContext(method,params,ctx){let requestContext=toRequestContext(ctx);return Object.assign(requestContext,{method,params,...ctx.sessionId!==void 0&&{session:{sessionId:ctx.sessionId}},...ctx.http?.authInfo!==void 0&&{auth:ctx.http.authInfo},state:new Map})}#runMcpHook(method,ctx,innerFn){let runOperation=method==="tools/call"&&this.#mcpMiddlewares.length===0&&this.#mcpEventListeners.length===0?innerFn:()=>runMcpOperation(this.#mcpMiddlewares,this.#mcpEventListeners,method,ctx,innerFn);if(isUsageDisabled())return runOperation();let startedAt=performance.now(),matchedMiddleware=this.#mcpMiddlewares.filter(entry=>matchesPattern(entry.pattern,method)).length,matchedObservers=phase=>this.#mcpEventListeners.filter(entry=>entry.phase===phase&&matchesPattern(entry.pattern,method)).length,request=ctx.request?.raw,client=request===void 0?void 0:clientUsageFromBody(getRequestBag(request).parsedBody),capture2=(outcome,completedPhase)=>{recordUsage("operation","completed",{method,outcome,duration_ms:Math.max(0,Math.round(performance.now()-startedAt)),primitive_origin:this.#primitiveOrigin(method,ctx.params),matched_middleware:matchedMiddleware,observers_before:matchedObservers("before"),observers_complete:completedPhase?matchedObservers("complete"):0,...client?.protocol_era==="modern"?client:{client_name:"unknown",protocol_era:"legacy"}},{sampleRate:outcome==="success"?.1:1,serverRoot:this.#viewsProjectRoot})};return runOperation().then(result=>{let outcome=isInputRequiredResult(result)?"input_required":method==="tools/call"&&typeof result=="object"&&result!==null&&"isError"in result&&result.isError===!0?"error":"success";return capture2(outcome,!0),result},error3=>{throw capture2("error",!1),error3})}#primitiveOrigin(method,params){if(method==="tools/call"){let name=String(params.name);return this.#proxiedTools.has(name)?"proxied":this.#openApiTools.has(name)?"openapi":"local"}return method==="resources/read"?this.#proxiedResources.has(String(params.uri))?"proxied":"local":method==="prompts/get"?this.#proxiedPrompts.has(String(params.name))?"proxied":"local":"mixed"}#wrapListHandlers(server){let handlers=server.server._requestHandlers;if(handlers===void 0)return;let wrapListMethod=(method,resultKey,transform2)=>{let original=handlers.get(method);if(original===void 0||original.__mcpListWrapped)return;let wrapped=async(request,extra)=>{let serverContext=extra,params=request.params??{},mwCtx=this.#createMiddlewareContext(method,params,serverContext),originalEnvelope,innerFn=async()=>{let downstreamRequest=withMcpMiddlewareParams(request,mwCtx.params),result=await original(downstreamRequest,extra);if(typeof result!="object"||result===null)throw new TypeError(`[mcp-use] ${method} handler returned a non-object result`);originalEnvelope=result;let items=originalEnvelope[resultKey];if(!Array.isArray(items))throw new TypeError(`[mcp-use] ${method} handler result is missing a ${resultKey} array`);return items},filtered=await this.#runMcpHook(method,mwCtx,innerFn);if(!Array.isArray(filtered))throw new TypeError(`[mcp-use] ${method} middleware must return a ${resultKey} array`);let emitted=transform2?.(filtered)??filtered;return{...originalEnvelope,[resultKey]:emitted}};wrapped.__mcpListWrapped=!0,handlers.set(method,wrapped)};wrapListMethod("tools/list","tools",tools=>tools.map(tool=>{let entry=this.#tools.get(tool.name),schemes=entry!==void 0&&this.#generatesSecuritySchemes(entry)?entry.schemes:void 0;return schemes===void 0?tool:{...tool,securitySchemes:schemes}})),wrapListMethod("resources/list","resources"),wrapListMethod("prompts/list","prompts")}#registerTool(server,entry){let{definition,callback,schemes}=entry,view=definition.view,uiMeta=buildToolUiMeta(view?.name,definition.visibility,definition._meta),toolMeta=this.#generatesSecuritySchemes(entry)?{...uiMeta,[SECURITY_SCHEMES_META_KEY]:schemes}:uiMeta,config2={...definition.title!==void 0&&{title:definition.title},...definition.description!==void 0&&{description:definition.description},...definition.annotations!==void 0&&{annotations:definition.annotations},...definition.outputSchema!==void 0&&{outputSchema:definition.outputSchema},...toolMeta!==void 0&&{_meta:toolMeta}},wireResultMeta=view!==void 0?buildToolResultUiMeta(view.name):void 0,inputSchema=resolveToolInputSchema(definition),invokeTool=async(args,ctx)=>{let mwCtx=this.#createMiddlewareContext("tools/call",{name:definition.name,arguments:args,...ctx.mcpReq._meta!==void 0&&{_meta:ctx.mcpReq._meta}},ctx),innerFn=async()=>{let effectiveArgs=mwCtx.params.arguments??{},result=await callback(effectiveArgs,this.#toToolRequestContext(ctx,schemes));return isInputRequiredResult(result)||wireResultMeta===void 0||result.isError===!0?result:{...result,_meta:{...result._meta,...wireResultMeta}}};return await this.#runMcpHook("tools/call",mwCtx,innerFn)};inputSchema!==void 0?server.registerTool(definition.name,{...config2,inputSchema},async(args,ctx)=>invokeTool(args,ctx)):server.registerTool(definition.name,config2,async ctx=>invokeTool({},ctx))}#registerViewResource(server,viewName,entry,metaOptions,basePath){let uri=viewResourceUri(viewName),authorFacts=this.#viewResourceFacts(this.#viewBindings.get(viewName)?.config),resourceConfig=viewResourceConfig(viewName,entry,authorFacts,metaOptions);server.registerResource(viewName,uri,resourceConfig,async(readUri,ctx)=>{let req=ctx.http?.req,readOptions=req!==void 0?{request:req,...metaOptions.hmrWs===!0?{hmrWs:!0}:{}}:metaOptions.hmrWs===!0?{hmrWs:!0}:{},assetsBase=req!==void 0?resolveAssetsBase(req):metaOptions.request!==void 0?resolveAssetsBase(metaOptions.request):"",html2=synthesizeViewDocument(entry,assetsBase,basePath,viewName),meta2=await applyClaudeResourceDomain(buildResourceUiMeta(authorFacts,readOptions),requestClientInfo(ctx),(req??metaOptions.request)?.headers.get("user-agent"));return{contents:[{uri:readUri.href,mimeType:resourceConfig.mimeType,text:html2,_meta:meta2}]}})}#registerResource(server,{definition,callback}){server.registerResource(definition.name,definition.uri,{...definition.title!==void 0&&{title:definition.title},...definition.description!==void 0&&{description:definition.description},...definition.mimeType!==void 0&&{mimeType:definition.mimeType},...definition.annotations!==void 0&&{annotations:definition.annotations},...definition._meta!==void 0&&{_meta:{...definition._meta}}},async(uri,ctx)=>{let mwCtx=this.#createMiddlewareContext("resources/read",{uri:uri.href,...ctx.mcpReq._meta!==void 0&&{_meta:ctx.mcpReq._meta}},ctx),innerFn=async()=>toResourceResult(await callback(uri,this.#toRequestContext(ctx)),uri.href);return await this.#runMcpHook("resources/read",mwCtx,innerFn)})}#registerResourceTemplate(server,{definition,callback,complete}){let template=new ResourceTemplate(definition.uriTemplate,{list:void 0,...complete!==void 0&&{complete}});server.registerResource(definition.name,template,{...definition.title!==void 0&&{title:definition.title},...definition.description!==void 0&&{description:definition.description},...definition.mimeType!==void 0&&{mimeType:definition.mimeType},...definition.annotations!==void 0&&{annotations:definition.annotations},...definition._meta!==void 0&&{_meta:{...definition._meta}}},async(uri,variables,ctx)=>{let mwCtx=this.#createMiddlewareContext("resources/read",{uri:uri.href,...ctx.mcpReq._meta!==void 0&&{_meta:ctx.mcpReq._meta}},ctx),innerFn=async()=>toResourceResult(await callback(uri,variables,this.#toRequestContext(ctx)),uri.href);return await this.#runMcpHook("resources/read",mwCtx,innerFn)})}#viewResourceFacts(viewConfig){if(viewConfig!==void 0)return{...viewConfig.description!==void 0&&{description:viewConfig.description},...viewConfig.csp!==void 0&&{csp:viewConfig.csp},...viewConfig.permissions!==void 0&&{permissions:viewConfig.permissions},...viewConfig.domain!==void 0&&{domain:viewConfig.domain},...viewConfig.prefersBorder!==void 0&&{prefersBorder:viewConfig.prefersBorder}}}#registerPrompt(server,{definition,callback}){let config2={...definition.title!==void 0&&{title:definition.title},...definition.description!==void 0&&{description:definition.description}},invokePrompt=async(args,ctx)=>{let mwCtx=this.#createMiddlewareContext("prompts/get",{name:definition.name,arguments:args,...ctx.mcpReq._meta!==void 0&&{_meta:ctx.mcpReq._meta}},ctx),innerFn=async()=>{let effectiveArgs=mwCtx.params.arguments??{};return toPromptResult(await callback(effectiveArgs,this.#toRequestContext(ctx)))};return await this.#runMcpHook("prompts/get",mwCtx,innerFn)};if(definition.schema!==void 0)server.registerPrompt(definition.name,{...config2,argsSchema:definition.schema},async(args,ctx)=>invokePrompt(args,ctx));else{let handler=async ctx=>invokePrompt({},ctx);server.registerPrompt(definition.name,config2,handler)}}#toRequestContext(ctx){return this.#config.oauth===void 0?toRequestContext(ctx):toAuthenticatedRequestContext(ctx)}#toToolRequestContext(ctx,schemes){return this.#config.oauth===void 0||!requiresSignIn(schemes)&&ctx.http?.authInfo===void 0?toRequestContext(ctx):toAuthenticatedRequestContext(ctx)}#securitySchemeOptions(){return{hasOAuth:this.#config.oauth!==void 0,mixedAuth:this.#config.mixedAuth===!0,baselineScopes:this.#config.oauth?.requiredScopes??[]}}#resolveSecuritySchemes(definition){let options=this.#securitySchemeOptions(),schemes=resolveSecuritySchemes(definition.name,definition.securitySchemes,options),warning=handWrittenSecuritySchemesWarning(definition.name,definition,options);return warning!==void 0&&console.warn(warning),schemes}#generatesSecuritySchemes(entry){let{definition}=entry;return definition.securitySchemes!==void 0?!0:this.#config.mixedAuth===!0&&definition._meta?.[SECURITY_SCHEMES_META_KEY]===void 0}};init_fetch_app();init_dist();function text(content){return{content:[{type:"text",text:content}],_meta:{mimeType:"text/plain"}}}function markdown(content){return{content:[{type:"text",text:content}],_meta:{mimeType:"text/markdown"}}}function html(content){return{content:[{type:"text",text:content}],_meta:{mimeType:"text/html"}}}function xml(content){return{content:[{type:"text",text:content}],_meta:{mimeType:"text/xml"}}}function css(content){return{content:[{type:"text",text:content}],_meta:{mimeType:"text/css"}}}function javascript(content){return{content:[{type:"text",text:content}],_meta:{mimeType:"text/javascript"}}}function image(data,mimeType="image/png"){return{content:[{type:"image",data,mimeType}],_meta:{mimeType,isImage:!0}}}function audio(data,mimeType="audio/wav"){return{content:[{type:"audio",data,mimeType}],_meta:{mimeType,isAudio:!0}}}function binary(base64Data,mimeType){return{content:[{type:"text",text:base64Data}],_meta:{mimeType,isBinary:!0}}}function resource(uri,mimeTypeOrContent,text2){if(typeof mimeTypeOrContent=="object"&&mimeTypeOrContent!==null&&"content"in mimeTypeOrContent){let contentResult=mimeTypeOrContent,extractedText,extractedMimeType;if(contentResult._meta&&typeof contentResult._meta=="object"){let meta2=contentResult._meta;typeof meta2.mimeType=="string"&&(extractedMimeType=meta2.mimeType)}let first=contentResult.content?.[0];return first?.type==="text"&&"text"in first&&(extractedText=first.text),{content:[{type:"resource",resource:{uri,...extractedMimeType!==void 0&&{mimeType:extractedMimeType},text:extractedText??""}}]}}let mimeType=mimeTypeOrContent;return{content:[{type:"resource",resource:{uri,...mimeType!==void 0&&mimeType!==""&&{mimeType},text:text2??""}}]}}function error2(message){return{isError:!0,content:[{type:"text",text:message}]}}function object3(data){return Array.isArray(data)?array2(data):{content:[{type:"text",text:JSON.stringify(data,null,2)}],structuredContent:data,_meta:{mimeType:"application/json"}}}function array2(data){return{content:[{type:"text",text:JSON.stringify(data,null,2)}],structuredContent:data}}function widget(config2){let props=config2.props??config2.data??{},{output,message,metadata}=config2,result={content:message?[{type:"text",text:message}]:Array.isArray(output?.content)&&output.content.length>0?output.content:[{type:"text",text:""}]};return metadata!==void 0&&Object.keys(metadata).length>0&&(result._meta=metadata),output?.structuredContent!==void 0?result.structuredContent=output.structuredContent:Object.keys(props).length>0&&(result.structuredContent=props),result}function mix(...results){let withStructured=results.filter(result=>result.structuredContent!==void 0),structuredContent=withStructured.length>0?withStructured.map(result=>result.structuredContent).reduce((acc,value)=>({...acc,...typeof value=="object"&&value!==null?value:{}}),{}):void 0,withMeta=results.filter(result=>result._meta!==void 0),_meta=withMeta.length>0?withMeta.map(result=>result._meta).reduce((acc,value)=>({...acc,...value!==void 0?value:{}}),{}):void 0;return{content:results.flatMap(result=>result.content),...structuredContent!==void 0&&Object.keys(structuredContent).length>0&&{structuredContent},..._meta!==void 0&&Object.keys(_meta).length>0&&{_meta}}}export{MCPServer,SKILLS_EXTENSION_ID,acceptedContent,array2 as array,audio,binary,completable2 as completable,composeFetch,composeMiddleware,createMcpEventListenerEntry,createMcpMiddlewareEntry,createMcpMount,createRequestStateCodec,css,error2 as error,getRequestBag,hostValidationMiddleware,html,image,inputRequired,inputResponse,isInputRequiredResult,javascript,jsonBodyMiddleware,markdown,matchesPath,matchesPathPrefix,matchesPattern,mix,object3 as object,originValidationMiddleware,pathnameOf,registerSkills,registerViews,requestLogger,resource,text,widget,xml};
|
|
807
|
+
</html>`}init_origin();init_fetch_app();var PUBLIC_BUILD_DIR=".mcp-use/build/views/public",PUBLIC_DEV_DIR="public",VIEW_ASSETS_BUILD_ROOT=".mcp-use/build/views",decodedAssets=new WeakMap;function serveEmbeddedAsset(assets,path,request,deferCors){let decoded;try{decoded=decodeURIComponent(path)}catch{return new Response("Not Found",{status:404})}if(decoded.includes("\\")||decoded.split("/").includes(".."))return new Response("Not Found",{status:404});let asset=Object.hasOwn(assets,decoded)?assets[decoded]:void 0;if(asset===void 0)return new Response("Not Found",{status:404});let body=null;return request.method!=="HEAD"&&(body=decodedAssets.get(asset)??null,body===null&&(body=Uint8Array.from(atob(asset.body),character=>character.charCodeAt(0)),decodedAssets.set(asset,body))),new Response(body,{headers:{"Content-Type":asset.contentType,"Cache-Control":"public, max-age=0, must-revalidate",...deferCors!==!0&&{"Access-Control-Allow-Origin":"*"}}})}function createViewAssetsHandler(basePath,views,options){if(views.size===0)return;let assetsPrefix=pathUnderBase(basePath,"_mcp-use/views"),projectRoot=options?.projectRoot??process.cwd();return async request=>{if(request.method!=="GET"&&request.method!=="HEAD")return new Response("Method Not Allowed",{status:405});if(!matchesPathPrefix(request,assetsPrefix))return new Response("Not Found",{status:404});let remainder=pathnameOf(request).slice(assetsPrefix.length+1),slash=remainder.indexOf("/");if(slash<=0||slash===remainder.length-1)return new Response("Not Found",{status:404});let viewName=remainder.slice(0,slash),subpath=remainder.slice(slash+1),entry=views.get(viewName);if(entry===void 0||entry.kind!=="external")return new Response("Not Found",{status:404});if(options?.assets!==void 0)return serveEmbeddedAsset(options.assets,remainder,request,options.deferCors);let[{join},{resolvePublicFilePath:resolvePublicFilePath2,servePublicFile:servePublicFile2}]=await Promise.all([import("path"),Promise.resolve().then(()=>(init_public_route(),public_route_exports))]),viewRoot=join(projectRoot,VIEW_ASSETS_BUILD_ROOT,viewName),diskPath=await resolvePublicFilePath2(viewRoot,subpath);return diskPath===null?new Response("Not Found",{status:404}):await servePublicFile2(diskPath,{...options?.deferCors===!0&&{deferCors:!0},...request.method==="HEAD"&&{head:!0}})}}function createViewPublicHandler(basePath,views,options){if(views.size===0&&options?.enabled!==!0)return;let publicPrefix=pathUnderBase(basePath,"_mcp-use/public"),subdir=options?.dev===!0?PUBLIC_DEV_DIR:PUBLIC_BUILD_DIR,projectRoot=options?.projectRoot??process.cwd();return async request=>{if(request.method!=="GET"&&request.method!=="HEAD")return new Response("Method Not Allowed",{status:405});if(!matchesPathPrefix(request,publicPrefix))return new Response("Not Found",{status:404});let encodedSubpath=pathnameOf(request).slice(publicPrefix.length+1),subpath;try{subpath=decodeURIComponent(encodedSubpath)}catch{return new Response("Not Found",{status:404})}if(subpath.length===0)return new Response("Not Found",{status:404});if(options?.assets!==void 0)return serveEmbeddedAsset(options.assets,`public/${encodedSubpath}`,request,options.deferCors);let[{join},{resolvePublicFilePath:resolvePublicFilePath2,servePublicFile:servePublicFile2}]=await Promise.all([import("path"),Promise.resolve().then(()=>(init_public_route(),public_route_exports))]),publicRoot=join(projectRoot,subdir),diskPath=await resolvePublicFilePath2(publicRoot,subpath);return diskPath===null?new Response("Not Found",{status:404}):await servePublicFile2(diskPath,{...options?.deferCors===!0&&{deferCors:!0},...request.method==="HEAD"&&{head:!0}})}}var CATEGORY_ENV={connectDomains:"CSP_CONNECT_DOMAINS",resourceDomains:"CSP_RESOURCE_DOMAINS",frameDomains:"CSP_FRAME_DOMAINS",baseUriDomains:"CSP_BASE_URI_DOMAINS"};function parseDomainList(raw2){return raw2===void 0||raw2.trim()===""?[]:raw2.split(",").map(s=>s.trim()).filter(s=>s.length>0)}function readEnvDomains(name){if(typeof process>"u")return;let raw2=process.env[name];if(!(raw2===void 0||raw2.trim()===""))return parseDomainList(raw2)}function readCspUrlsShortcut(){return readEnvDomains("CSP_URLS")??[]}function readEnvDomainsForCategory(category){let perCategory=readEnvDomains(CATEGORY_ENV[category]);return perCategory!==void 0?perCategory:readCspUrlsShortcut()}function mergeDomainLists(...segments){let seen=new Set,out=[];for(let segment of segments)for(let domain of segment)seen.has(domain)||(seen.add(domain),out.push(domain));return out}function toWebSocketOrigin(serverOrigin){return serverOrigin.startsWith("https://")?`wss://${serverOrigin.slice(8)}`:serverOrigin.startsWith("http://")?`ws://${serverOrigin.slice(7)}`:serverOrigin}function buildMergedResourceCsp(authorFacts,options){let author=authorFacts?.csp,mcpConnectAuto=[];options.serverOrigin!==""&&(mcpConnectAuto.push(options.serverOrigin),options.hmrWs===!0&&mcpConnectAuto.push(toWebSocketOrigin(options.serverOrigin)));let mcpResourceAuto=[],resourceOrigin=options.explicitAssetsBase?options.assetsOrigin:options.serverOrigin;resourceOrigin!==""&&mcpResourceAuto.push(resourceOrigin);let connectDomains=mergeDomainLists(author?.connectDomains??[],readEnvDomainsForCategory("connectDomains"),mcpConnectAuto),resourceDomains=mergeDomainLists(author?.resourceDomains??[],readEnvDomainsForCategory("resourceDomains"),mcpResourceAuto),frameDomains=mergeDomainLists(author?.frameDomains??[],readEnvDomainsForCategory("frameDomains")),baseUriDomains=mergeDomainLists(author?.baseUriDomains??[],readEnvDomainsForCategory("baseUriDomains")),scriptDirectives=mergeDomainLists(author?.scriptDirectives??[],options.hmrWs===!0?["'unsafe-eval'"]:[]);return{...author,connectDomains,resourceDomains,frameDomains,baseUriDomains,...scriptDirectives.length>0?{scriptDirectives}:{}}}init_origin();function buildToolUiMeta(viewName,visibility,existingMetadata){if(viewName===void 0&&visibility===void 0&&existingMetadata===void 0)return;let meta2={...existingMetadata},existingUi=existingMetadata?.["ui"],existingUiIsObject=typeof existingUi=="object"&&existingUi!==null&&!Array.isArray(existingUi),ui=existingUiIsObject?{...existingUi}:{};if(viewName!==void 0){let resourceUri=viewResourceUri(viewName);ui.resourceUri=resourceUri,meta2[UI_RESOURCE_URI_META_KEY]=resourceUri}else delete ui.resourceUri,delete meta2[UI_RESOURCE_URI_META_KEY];return visibility!==void 0?ui.visibility=[visibility]:delete ui.visibility,(viewName!==void 0||visibility!==void 0||existingUiIsObject)&&(meta2["ui"]=ui),meta2}function buildToolResultUiMeta(viewName){let resourceUri=viewResourceUri(viewName);return{ui:{resourceUri},[UI_RESOURCE_URI_META_KEY]:resourceUri}}function resolveCspOptions(options){let request=options?.request,serverOrigin=options?.serverOrigin??(request!==void 0?resolveServerOrigin(request):""),assetsBase=options?.assetsBase??(request!==void 0?resolveAssetsBase(request):serverOrigin);return{serverOrigin,assetsOrigin:originFromAssetsBase(assetsBase),explicitAssetsBase:hasExplicitAssetsBase(),...options?.hmrWs===!0?{hmrWs:!0}:{}}}function buildResourceUiMeta(authorFacts,options){let ui={csp:buildMergedResourceCsp(authorFacts,resolveCspOptions(options))};return authorFacts?.permissions!==void 0&&(ui.permissions=authorFacts.permissions),authorFacts?.domain!==void 0&&(ui.domain=authorFacts.domain),authorFacts?.prefersBorder!==void 0&&(ui.prefersBorder=authorFacts.prefersBorder),{ui,...authorFacts?.displayModes!==void 0&&{"openai/ui":{availableDisplayModes:authorFacts.displayModes.filter(mode=>mode==="inline"||mode==="fullscreen"),...authorFacts.preferredDisplayMode!==void 0&&{preferredDisplayMode:authorFacts.preferredDisplayMode}}}}}function viewResourceConfig(_viewName,_entry,authorFacts,options){return{mimeType:UI_MIME_TYPE,...authorFacts?.description!==void 0&&{description:authorFacts.description},_meta:buildResourceUiMeta(authorFacts,options)}}var CLAUDE_RESOURCE_DOMAIN_SUFFIX=".claudemcpcontent.com",CLAUDE_RESOURCE_DOMAIN_HASH_LENGTH=32;function isClaudeClient(clientInfo){let name=clientInfo?.name;return typeof name=="string"&&name.toLowerCase().includes("claude")}async function computeClaudeResourceDomain(domain){if(domain.endsWith(CLAUDE_RESOURCE_DOMAIN_SUFFIX))return domain;let digest=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(domain));return`${Array.from(new Uint8Array(digest),byte=>byte.toString(16).padStart(2,"0")).join("").slice(0,CLAUDE_RESOURCE_DOMAIN_HASH_LENGTH)}${CLAUDE_RESOURCE_DOMAIN_SUFFIX}`}async function applyClaudeResourceDomain(meta2,clientInfo,userAgent){let effectiveClientInfo=typeof clientInfo?.name=="string"||typeof userAgent!="string"||userAgent.trim().length===0?clientInfo:{...clientInfo,name:userAgent.trim()};if(!isClaudeClient(effectiveClientInfo))return meta2;let ui=meta2["ui"];if(typeof ui!="object"||ui===null||Array.isArray(ui))return meta2;let domain=ui.domain;return typeof domain!="string"||domain.length===0?meta2:{...meta2,ui:{...ui,domain:await computeClaudeResourceDomain(domain)}}}function record3(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)?value:void 0}function productId(value,fallback){if(typeof value!="string")return fallback;let normalized=value.trim();return normalized.length>0&&normalized.length<=64&&![...normalized].some(character=>{let code=character.charCodeAt(0);return code<32||code===127})?normalized:fallback}function clientUsageFromBody(body){if(!isJSONRPCRequest(body))return;let params=record3(body.params);if(body.method==="initialize"){let info2=record3(params?.clientInfo),capabilities2=record3(params?.capabilities)??{};return clientUsage(info2,capabilities2,params?.protocolVersion,"legacy")}let meta2=record3(params?._meta),info=record3(meta2?.[CLIENT_INFO_META_KEY]),capabilities=record3(meta2?.[CLIENT_CAPABILITIES_META_KEY]);if(!(info===void 0||capabilities===void 0))return clientUsage(info,capabilities,meta2?.[PROTOCOL_VERSION_META_KEY],"modern")}function clientUsage(info,capabilities,protocolVersion,era){let typedCapabilities=capabilities;return{client_name:productId(info?.name,"other"),client_version:productId(info?.version,"unknown"),protocol_era:era,protocol_version:productId(protocolVersion,"unknown"),connection_mode:era==="modern"?"stateless_request":"legacy_session",sampling_capability:Object.hasOwn(capabilities,"sampling"),elicitation_capability:Object.hasOwn(capabilities,"elicitation"),roots_capability:Object.hasOwn(capabilities,"roots"),extensions_capability:Object.hasOwn(capabilities,"extensions"),views_capability:supportsViews(typedCapabilities),capability_count:Object.keys(capabilities).length}}function registerFetchMiddleware(app,middleware){app.use("*",async(context,next)=>{let response=await middleware(context.req.raw,async()=>(await next(),context.res));return context.res=response,response})}var MCPServer=class _MCPServer{#config;#requestLogPrefix;#branding;#tools=new Map;#resources=new Map;#resourceTemplates=new Map;#prompts=new Map;#views=new Map;#settings;#skills;#skillsPrimed=!1;#skillsDiscovery;#viewBindings=new Map;#viewsPrimed=!1;#embeddedViewAssets;#viewsDevMode=!1;#viewsProjectRoot=process.cwd();#fetchHandler;#httpApp;#handler;#eventBus;#httpServer;#oauthResource;#oauthResourceResolved=!1;#oauthResourceConfigurationAbsent=!1;#instructionsOverride;#oauthProviderSetupRan=!1;#oauthProviderSetupFailure;#hostValidated=!1;#mcpMiddlewares=[];#mcpEventListeners=[];#usageScope;#openApiTools=new Set;#proxiedTools=new Set;#proxiedResources=new Set;#proxiedPrompts=new Set;#httpMiddlewareCount=0;#proxyServersConfigured=0;#proxyServersConnected=0;#proxyToolsDiscovered=0;#proxyResourcesDiscovered=0;#proxyPromptsDiscovered=0;#proxyOwners=[];#proxyOperations=new Set;#closed=!1;app;get;post;put;patch;delete;all;fetch;static fromOpenAPI(options){let server=new _MCPServer({name:options.name??options.spec.info.title,version:options.version??options.spec.info.version??"1.0.0"});registerOpenAPITools(server,options);for(let name of server.#tools.keys())server.#openApiTools.add(name);return server}constructor(config2){if(assertServerConfig(config2),this.#config=config2,this.#branding=normalizeServerBranding(config2),this.app=new Hono3,this.app.use("*",async(context,next)=>{getRequestBag(context.req.raw).honoContext=context,await next()}),this.get=this.app.get.bind(this.app),this.post=this.app.post.bind(this.app),this.put=this.app.put.bind(this.app),this.patch=this.app.patch.bind(this.app),this.delete=this.app.delete.bind(this.app),this.all=this.app.all.bind(this.app),this.fetch=async(request,env2,executionCtx)=>(await this.#ensureSkillsPrimed(),this.#ensureMounted("handler"),this.#httpApp.fetch(request,env2,executionCtx)),config2.oauth!==void 0){let mcpUrl=typeof process>"u"?void 0:process.env.MCP_URL,resource2=resolveConfiguredOAuthResource({provider:config2.oauth,basePath:this.#basePath(),...mcpUrl!==void 0&&{mcpUrl}});this.#oauthResource=resource2,this.#oauthResourceResolved=resource2!==void 0,this.#oauthResourceConfigurationAbsent=resource2===void 0}}get basePath(){return this.#basePath()}get host(){return this.#config.host}get port(){return this.#config.port}get branding(){return this.#branding}getHandler(){return this.fetch}tool(definition,callback){if(this.#assertNotStarted("tool",definition.name),this.#settings!==void 0&&[this.#settings.capability.readTool,this.#settings.capability.updateTool].includes(definition.name))throw new Error(`Tool "${definition.name}" is reserved for settings`);let schemes=this.#resolveSecuritySchemes(definition);return validateEntrypointInput(definition),this.#validateToolViewBinding(definition),this.#openApiTools.delete(definition.name),this.#proxiedTools.delete(definition.name),this.#tools.set(definition.name,{definition,callback,schemes}),Object.freeze({name:definition.name})}settings(options){if(this.#assertNotStarted("settings",options.readTool??"settings.read"),this.#settings!==void 0)throw new Error("Settings are already registered on this server");let prepared=prepareSettings(options);for(let name of[prepared.capability.readTool,prepared.capability.updateTool])if(this.#tools.has(name))throw new Error(`Settings tool "${name}" is already registered`);let read=options.read,update=options.update;this.tool(prepared.readDefinition,async(_args,ctx)=>({content:[],structuredContent:{schema:prepared.schema,...prepared.layout!==void 0&&{layout:prepared.layout},values:await read(ctx)}})),this.tool(prepared.updateDefinition,async({set},ctx)=>({content:[],structuredContent:{values:await update(set,ctx)}})),this.#settings=prepared}[registerViews](views,options){if(this.#viewsPrimed)throw new Error("Cannot prime views: the views registry is already primed on this server instance.");this.#assertNotStarted("views","manifest");for(let[name,entry]of Object.entries(views))try{normalizeViewConfig(entry.viewConfig)}catch(error3){throw new Error(`View "${name}" has an invalid viewConfig: ${error3 instanceof Error?error3.message:String(error3)}`,{cause:error3})}this.#viewsDevMode=options?.dev===!0,this.#embeddedViewAssets=options?.assets,options?.projectRoot!==void 0&&(this.#viewsProjectRoot=options.projectRoot);for(let[name,entry]of Object.entries(views))this.#views.set(name,entry);this.#viewsPrimed=!0}__primeViews(views,options){this[registerViews](views,options)}[registerSkills](snapshot){this.#assertNotStarted("skills","snapshot"),this.#skills=snapshot,this.#skillsPrimed=!0}__primeSkills(snapshot){this[registerSkills](snapshot)}__skillsConfig(){return this.#config.skills}async#discoverSkills(projectRoot,conventionalDirectory){let{discoverConfiguredSkills}=await import("#mcp-use-skills-loader"),snapshot=discoverConfiguredSkills(this.#config.skills,projectRoot,conventionalDirectory);return this[registerSkills](snapshot),snapshot}resource(definition,callback){this.#assertNotStarted("resource",definition.name);let previous=this.#resources.get(definition.name);return previous!==void 0&&this.#proxiedResources.delete(previous.definition.uri),this.#resources.set(definition.name,{definition,callback}),this}resourceTemplate(definition,callback){this.#assertNotStarted("resourceTemplate",definition.name);let complete=definition.complete===void 0?void 0:normalizeCompletions(definition.complete);return this.#resourceTemplates.set(definition.name,{definition,...complete!==void 0&&{complete},callback}),this}prompt(definition,callback){return this.#assertNotStarted("prompt",definition.name),this.#proxiedPrompts.delete(definition.name),this.#prompts.set(definition.name,{definition,callback}),this}async proxy(input){this.#assertOpen("proxy()");let operation=(async()=>{let{isProxyConnection:isProxyConnection2,mountProxyConnection:mountProxyConnection2,mountProxyServers:mountProxyServers2}=await Promise.resolve().then(()=>(init_mcp_proxy(),mcp_proxy_exports));if(isProxyConnection2(input)){this.#proxyServersConfigured+=1,await mountProxyConnection2(this.#proxyHost(),input);return}this.#proxyServersConfigured+=Object.keys(input).length,await mountProxyServers2(this.#proxyHost(),input)})();this.#proxyOperations.add(operation);try{await operation}finally{this.#proxyOperations.delete(operation)}}use(patternOrHandler,...handlers){if(typeof patternOrHandler=="string"&&patternOrHandler.startsWith("mcp:")){this.#assertNotStarted("middleware",patternOrHandler);let handler=handlers[0];return this.#mcpMiddlewares.push(createMcpMiddlewareEntry(patternOrHandler,handler)),this}return this.app.use.call(this.app,patternOrHandler,...handlers),this.#httpMiddlewareCount+=typeof patternOrHandler=="function"?1:handlers.length,this}on(pattern,handler){return this.#assertNotStarted("event listener",pattern),this.#mcpEventListeners.push(createMcpEventListenerEntry(pattern,handler)),this}__setEventBus(bus){this.#assertNotStarted("event bus","shared"),this.#eventBus=bus}__setRequestLogPrefix(prefix){this.#assertNotStarted("request log prefix","development"),this.#requestLogPrefix=prefix}__mount(){if(!this.#skillsPrimed)throw new Error("Cannot mount before skills discovery. CLI tooling must call __primeSkills first.");this.#ensureMounted("handler")}async notifyToolsChanged(){await this.#ensureSkillsPrimed(),await this.#ensureMounted("handler").handler.notify.toolsChanged()}async notifyPromptsChanged(){await this.#ensureSkillsPrimed(),await this.#ensureMounted("handler").handler.notify.promptsChanged()}async notifyResourcesChanged(){await this.#ensureSkillsPrimed(),await this.#ensureMounted("handler").handler.notify.resourcesChanged()}async notifyResourceUpdated(uri){await this.#ensureSkillsPrimed(),await this.#ensureMounted("handler").handler.notify.resourceUpdated(uri)}async listen(port=void 0,options={}){this.#assertOpen("listen()"),await this.#ensureSkillsPrimed();let host=resolveListenHost(options.host,this.#config.host),requestedPort=resolveListenPort(port,this.#config.port);return this.#assertListenOAuthConfiguration(host),new Promise((resolve,reject)=>{let resolveFetch,rejectFetch,fetchReady=new Promise((resolveFetchPromise,rejectFetchPromise)=>{resolveFetch=resolveFetchPromise,rejectFetch=rejectFetchPromise});fetchReady.catch(()=>{});let settled=!1,rejectAndClose=error3=>{settled||(settled=!0,reject(error3)),rejectFetch?.(error3),new Promise(closeResolve=>server.close(()=>closeResolve())).catch(()=>{}).finally(()=>{this.#httpServer===server&&(this.#httpServer=void 0)})},nodeHandler=toNodeHandler({fetch:async request=>(await fetchReady)(request)}),server=createNodeHttpServer((req,res)=>{nodeHandler(req,res)});server.once("error",rejectAndClose),server.listen(requestedPort,host,()=>{try{let address=server.address(),boundPort=typeof address=="object"&&address!==null?address.port:requestedPort,{fetch:fetch2}=this.#ensureMounted("listen",boundPort,host);resolveFetch?.(fetch2),settled||(settled=!0,resolve({port:boundPort,url:`http://localhost:${boundPort}${this.#basePath()}`}))}catch(error3){rejectAndClose(error3)}}),this.#httpServer=server})}async close(){this.#closed=!0,await Promise.allSettled([...this.#proxyOperations]);let errors2=[],proxyOwners=this.#proxyOwners.splice(0),ownerResults=await Promise.allSettled(proxyOwners.map(owner=>owner.close()));for(let result of ownerResults)result.status==="rejected"&&errors2.push(result.reason);try{await this.#handler?.close()}catch(error3){errors2.push(error3)}let httpServer=this.#httpServer;if(httpServer!==void 0)try{await new Promise((resolve,reject)=>{httpServer.close(err=>err?reject(err):resolve())}),this.#httpServer=void 0}catch(error3){errors2.push(error3)}if(errors2.length>0)throw new AggregateError(errors2,"Failed to close MCP server cleanly")}#assertOpen(operation){if(this.#closed)throw operation!==void 0?new Error(`Cannot call ${operation} after the server has closed.`):new Error("Cannot use the server after it has closed.")}#basePath(){return this.#config.basePath??"/mcp"}#resolveOAuthResource(mode,listenPort,listenHost){if(this.#config.oauth===void 0)return;if(this.#oauthResourceResolved)return this.#oauthResource;let host=listenHost??this.#config.host??"127.0.0.1",localListen=mode==="listen"&&listenPort!==void 0&&["127.0.0.1","localhost","::1"].includes(host);if(this.#oauthResourceConfigurationAbsent&&localListen)return this.#oauthResource=resolveLocalOAuthResource(`http://localhost:${listenPort}`,this.#basePath()),this.#oauthResourceResolved=!0,this.#oauthResource;throw new Error("OAuth requires an explicit resource or MCP_URL when using server.fetch or listening on a non-local host")}#assertListenOAuthConfiguration(host){if(this.#config.oauth!==void 0&&!["127.0.0.1","localhost","::1"].includes(host)&&!this.#oauthResourceResolved)throw new Error("OAuth listen() on a public or wildcard host requires an explicit provider resource or valid MCP_URL.")}#assertNotStarted(kind,name){if(this.#handler!==void 0)throw new Error(`Cannot register ${kind} "${name}" after the server has started: registrations are replayed per request from the registry, so register everything before listen()/server.fetch.`)}#trackConfigured(){recordUsage("server","configured",{tools_total:this.#tools.size,tools_local:this.#tools.size-this.#openApiTools.size-this.#proxiedTools.size,tools_openapi:this.#openApiTools.size,tools_proxied:this.#proxiedTools.size,resources:this.#resources.size,resource_templates:this.#resourceTemplates.size,prompts:this.#prompts.size,views:this.#views.size,proxy_servers_configured:this.#proxyServersConfigured,proxy_servers_connected:this.#proxyServersConnected,proxy_tools_discovered:this.#proxyToolsDiscovered,proxy_resources_discovered:this.#proxyResourcesDiscovered,proxy_prompts_discovered:this.#proxyPromptsDiscovered,proxy_tools_mounted:this.#proxiedTools.size,proxy_resources_mounted:this.#proxiedResources.size,proxy_prompts_mounted:this.#proxiedPrompts.size,http_middleware:this.#httpMiddlewareCount,mcp_middleware:this.#mcpMiddlewares.length,observers_before:this.#mcpEventListeners.filter(({phase})=>phase==="before").length,observers_complete:this.#mcpEventListeners.filter(({phase})=>phase==="complete").length,oauth_configured:this.#config.oauth!==void 0,cors_configured:this.#config.cors!==void 0,request_state_configured:this.#config.requestState!==void 0,legacy_policy:this.#config.legacy??"stateless"},{onceKey:`${this.#usageScopeId()}:server`,serverRoot:this.#viewsProjectRoot})}#trackClient(body){let client=clientUsageFromBody(body);client!==void 0&&recordUsage("client","observed",{...client},{onceKey:`${this.#usageScopeId()}:client:${JSON.stringify(client)}`,serverRoot:this.#viewsProjectRoot})}#usageScopeId(){return this.#usageScope??=crypto.randomUUID(),this.#usageScope}#runOAuthProviderSetup(resource2,basePath){let setup=this.#config.oauth?.setup;if(setup===void 0||this.#oauthProviderSetupRan)return;if(this.#oauthProviderSetupFailure!==void 0)throw this.#oauthProviderSetupFailure.error;let active=!0,assertActive=method=>{if(!active)throw new Error(`[mcp-use] OAuthProviderHost.${method}() called after the provider's setup hook returned; call it from setup().`)},host={resourceUrl:resource2,basePath,mixedAuth:this.#config.mixedAuth===!0,use:(pattern,handler)=>{assertActive("use"),this.use(pattern,handler)},tool:(definition,callback)=>{if(assertActive("tool"),this.#tools.has(definition.name))throw new Error(`[mcp-use] Tool "${definition.name}" is reserved by the OAuth provider; rename the application tool.`);return this.tool(definition,callback)},resource:(definition,callback)=>{if(assertActive("resource"),this.#resources.has(definition.name))throw new Error(`[mcp-use] Resource "${definition.name}" is reserved by the OAuth provider; rename the application resource.`);this.resource(definition,callback)},resourceTemplate:(definition,callback)=>{if(assertActive("resourceTemplate"),this.#resourceTemplates.has(definition.name))throw new Error(`[mcp-use] Resource template "${definition.name}" is reserved by the OAuth provider; rename the application resource template.`);this.resourceTemplate(definition,callback)},prompt:(definition,callback)=>{if(assertActive("prompt"),this.#prompts.has(definition.name))throw new Error(`[mcp-use] Prompt "${definition.name}" is reserved by the OAuth provider; rename the application prompt.`);this.prompt(definition,callback)},listTools:()=>(assertActive("listTools"),[...this.#tools.values()].map(({definition})=>definition)),instructions:transform2=>{assertActive("instructions"),this.#instructionsOverride=transform2(this.#instructionsOverride??this.#config.instructions)}};try{let returned=setup(host);if(typeof returned?.then=="function")throw Promise.resolve(returned).catch(()=>{}),new TypeError("[mcp-use] The OAuth provider's setup hook must be synchronous but returned a promise. Do async work before creating the provider.")}catch(error3){throw this.#oauthProviderSetupFailure={error:error3},error3}finally{active=!1}this.#oauthProviderSetupRan=!0}#proxyHost(){return{isStarted:()=>this.#handler!==void 0,hasTool:name=>this.#tools.has(name),hasResource:name=>this.#resources.has(name),hasPrompt:name=>this.#prompts.has(name),registerTool:(definition,callback)=>{this.#assertNotStarted("tool",definition.name),this.#proxiedTools.add(definition.name),this.#tools.set(definition.name,{definition,callback,schemes:this.#resolveSecuritySchemes(definition)})},registerResource:(definition,callback)=>{this.#assertNotStarted("resource",definition.name),this.#proxiedResources.add(definition.uri),this.#resources.set(definition.name,{definition,callback})},registerPrompt:(definition,callback)=>{this.#assertNotStarted("prompt",definition.name),this.#proxiedPrompts.add(definition.name),this.#prompts.set(definition.name,{definition,callback})},trackOwner:owner=>{this.#proxyOwners.push(owner)},trackNamespace:({tools,resources,prompts})=>{this.#proxyServersConnected+=1,this.#proxyToolsDiscovered+=tools,this.#proxyResourcesDiscovered+=resources,this.#proxyPromptsDiscovered+=prompts}}}async#ensureSkillsPrimed(){this.#skillsPrimed||(this.#skillsDiscovery??=this.#discoverSkills(typeof process>"u"?".":process.cwd(),"skills").then(()=>{}),await this.#skillsDiscovery)}#validationPolicy(mode,listenHost){let{allowedHosts,allowedOrigins}=this.#config,host=listenHost??this.#config.host??"127.0.0.1",localhostBind=["127.0.0.1","localhost","::1"].includes(host),hosts=allowedHosts!==void 0?[...new Set([...localhostAllowedHostnames(),...allowedHosts])]:mode==="listen"&&localhostBind?localhostAllowedHostnames():void 0,origins=allowedOrigins!==void 0?[...new Set([...localhostAllowedOrigins(),...allowedOrigins])]:void 0;return{hosts,origins}}#ensureMounted(mode,listenPort,listenHost){if(this.#assertOpen(),this.#fetchHandler===void 0||this.#handler===void 0){let{hosts,origins}=this.#validationPolicy(mode,listenHost),basePath=this.#basePath(),nestedBasePath=basePath==="/"?"":basePath,httpApp=new Hono3,middlewares=[requestLogger({...this.#config.logging,mcpPath:basePath,prefix:this.#requestLogPrefix}),jsonBodyMiddleware()],corsConfig=this.#config.cors;corsConfig!==void 0&&middlewares.unshift(corsFetchMiddleware(corsConfig));let deferViewCors=isGlobalCorsEnabled(corsConfig);hosts!==void 0&&middlewares.unshift(hostValidationMiddleware(hosts)),origins!==void 0&&middlewares.push(originValidationMiddleware(origins)),hosts===void 0&&mode==="listen"&&console.warn(`[mcp-use] listen() is serving on ${listenHost} without Host validation. Behind a platform edge that only routes your own domains this is expected; if this process is reachable directly, set allowedHosts to restrict it.`);let resource2=this.#resolveOAuthResource(mode,listenPort,listenHost);if(resource2!==void 0){let provider=this.#config.oauth;middlewares.push(oauthMetadata(provider,resource2))}for(let middleware of middlewares)registerFetchMiddleware(httpApp,middleware);resource2!==void 0&&this.#runOAuthProviderSetup(resource2,basePath);for(let group of this.#settings?.layout??[])for(let item of group.items)if(item.kind==="tool"&&!this.#tools.has(item.tool))throw new Error(`Settings action tool "${item.tool}" is not registered on this server`);this.#validateViewBindingsAtMount();let{handler,fetch:mcpFetch}=createMcpMount(ctx=>this.#buildSdkServer(ctx),{path:basePath,...(this.#config.legacy!==void 0||this.#eventBus!==void 0)&&{handler:{...this.#config.legacy!==void 0&&{legacy:this.#config.legacy},...this.#eventBus!==void 0&&{bus:this.#eventBus}}},...resource2!==void 0&&{authInfo:request=>authInfoFromRequest(request)}});if(resource2!==void 0){let provider=this.#config.oauth,providerOptions=getOAuthProviderOptions(provider),mixedAuth=this.#config.mixedAuth===!0,gateOptions={verifier:wrapOAuthTokenVerifier(provider,resource2),resourceMetadataUrl:getOAuthProtectedResourceMetadataUrl(resource2),baselineScopes:providerOptions.requiredScopes??[],mixedAuth,toolSchemes:name=>this.#tools.get(name)?.schemes,openResourceUris:[...this.#viewBindings.keys()].map(viewResourceUri)},gate;httpApp.use("*",async(context,next)=>{if(new URL(context.req.url).pathname!==basePath){await next();return}if((this.#config.publicLandingPage===!0||mixedAuth)&&isHtmlNavigationRequest(context.req.raw)){await next();return}gate??=Promise.resolve().then(()=>(init_gate(),gate_exports)).then(({createOAuthGate:createOAuthGate2})=>createOAuthGate2(gateOptions));let response=await(await gate)(context.req.raw,async()=>(await next(),context.res));return context.res=response,response})}let mcpRouteHandler=request=>{let body=getRequestBag(request).parsedBody;return isJSONRPCRequest(body)&&(this.#trackConfigured(),this.#trackClient(body)),mcpFetch(request)},endpointHandler=async request=>isHtmlNavigationRequest(request)?(async()=>{let{createLandingPageResponse:createLandingPageResponse2}=await Promise.resolve().then(()=>(init_landing_handler(),landing_handler_exports));return createLandingPageResponse2(request,basePath,this.#config,this.#branding,this.#tools.values(),this.#prompts.values(),this.#resources.values())})():mcpRouteHandler(request),brandingDevMode=this.#viewsPrimed?this.#viewsDevMode:process.env.NODE_ENV!=="production",faviconHandler=createFaviconHandler(this.#branding,{dev:brandingDevMode,projectRoot:this.#viewsProjectRoot,deferCors:deferViewCors});faviconHandler!==void 0&&this.app.all("/favicon.ico",context=>faviconHandler(context.req.raw));let viewHandler=createViewPublicHandler(basePath,this.#views,{dev:this.#viewsPrimed?this.#viewsDevMode:brandingDevMode,projectRoot:this.#viewsProjectRoot,enabled:hasLocalBrandingAsset(this.#branding)||[...this.#tools.values()].some(entry=>entry.definition.icons!==void 0&&hasLocalBrandingAsset({icons:entry.definition.icons})),deferCors:deferViewCors,...this.#embeddedViewAssets!==void 0&&{assets:this.#embeddedViewAssets}});if(viewHandler!==void 0&&this.app.on(["GET","HEAD"],`${nestedBasePath}/_mcp-use/public/*`,context=>viewHandler(context.req.raw)),!this.#viewsDevMode){let viewAssetsHandler=createViewAssetsHandler(basePath,this.#views,{projectRoot:this.#viewsProjectRoot,deferCors:deferViewCors,...this.#embeddedViewAssets!==void 0&&{assets:this.#embeddedViewAssets}});viewAssetsHandler!==void 0&&this.app.on(["GET","HEAD"],`${nestedBasePath}/_mcp-use/views/*`,context=>viewAssetsHandler(context.req.raw))}this.app.all(basePath,context=>endpointHandler(context.req.raw)),httpApp.route("/",this.app),this.#httpApp=httpApp,this.#fetchHandler=async request=>httpApp.fetch(request),this.#handler=handler,this.#hostValidated=hosts!==void 0}else if(mode==="listen"&&!this.#hostValidated&&this.#validationPolicy("listen",listenHost).hosts!==void 0)throw new Error("Cannot listen() on a localhost bind after server.fetch mounted the app without Host validation (server.fetch expects a platform edge in front). Call listen() first, or set allowedHosts.");return{fetch:this.#fetchHandler,handler:this.#handler}}#validateToolViewBinding(definition){let view=definition.view;if(view===void 0)return;if(definition.outputSchema===void 0)throw new Error(`Tool "${definition.name}" declares view "${view.name}" but has no outputSchema. View-bound tools require an outputSchema \u2014 the view reads structuredContent typed from it. Use outputSchema: z.object({}) for a view that takes no structured output.`);let existing=this.#viewBindings.get(view.name);if(existing!==void 0)throw new Error(`View "${view.name}" is already bound to tool "${existing.toolName}"; tool "${definition.name}" cannot bind the same view. Each view may be bound to one tool.`);this.#viewBindings.set(view.name,{toolName:definition.name,config:view})}#validateViewBindingsAtMount(){if(this.#viewBindings.size>0&&!this.#viewsPrimed){let first=[...this.#tools.values()].find(entry=>entry.definition.view!==void 0),viewName=first?.definition.view?.name??"unknown";throw new Error(`Tool "${first?.definition.name??"unknown"}" is bound to view "${viewName}" but no views were primed. Run \`mcp-use build\` and deploy the built entry, or in dev let the CLI prime views automatically.`)}for(let entry of this.#tools.values()){let viewName=entry.definition.view?.name;if(viewName!==void 0&&!this.#views.has(viewName))throw new Error(`Tool "${entry.definition.name}" is bound to view "${viewName}" which is not in the primed views registry. Run \`mcp-use build\` and deploy the built entry, or in dev let the CLI prime views automatically.`)}for(let viewName of this.#views.keys())this.#viewBindings.has(viewName)||console.warn(`[mcp-use] View "${viewName}" is registered but no tool binds it.`)}#buildSdkServer(ctx){let{name,version:version2,title,description}=this.#config,instructions=this.#instructionsOverride??this.#config.instructions,authInfo=ctx.authInfo,server=new McpServer({name,version:version2,...title!==void 0&&{title},...description!==void 0&&{description},...this.#branding.websiteUrl!==void 0&&{websiteUrl:this.#branding.websiteUrl},...this.#branding.icons!==void 0&&{icons:resolveImplementationIcons(this.#branding.icons,ctx.requestInfo,this.#basePath())}},{capabilities:{logging:{},tools:{listChanged:!0},prompts:{listChanged:!0},resources:{listChanged:!0,subscribe:!0},...(this.#skills!==void 0||this.#settings!==void 0)&&{extensions:{...this.#skills!==void 0&&{[SKILLS_EXTENSION_ID]:{directoryRead:!0}},...this.#settings!==void 0&&{"openai/settings":this.#settings.capability}}},...this.#settings!==void 0&&{experimental:{"openai/settings":this.#settings.capability}}},...instructions!==void 0&&{instructions},...authInfo!==void 0&&{authInfo},...this.#config.requestState!==void 0&&{requestState:this.#config.requestState}}),request=ctx.requestInfo,viewMetaOptions=request!==void 0?{request,hmrWs:this.#viewsDevMode}:{hmrWs:this.#viewsDevMode},basePath=this.#basePath();for(let entry of this.#tools.values())this.#registerTool(server,entry,request);for(let entry of this.#resources.values())this.#registerResource(server,entry);for(let entry of this.#resourceTemplates.values())this.#registerResourceTemplate(server,entry);for(let entry of this.#prompts.values())this.#registerPrompt(server,entry);for(let[viewName,viewEntry]of this.#views.entries())this.#registerViewResource(server,viewName,viewEntry,viewMetaOptions,basePath);return this.#skills!==void 0&®isterSkillsRuntime(server,this.#skills),this.#wrapListHandlers(server),server}#createMiddlewareContext(method,params,ctx){let requestContext=toRequestContext(ctx);return Object.assign(requestContext,{method,params,...ctx.sessionId!==void 0&&{session:{sessionId:ctx.sessionId}},...ctx.http?.authInfo!==void 0&&{auth:ctx.http.authInfo},state:new Map})}#runMcpHook(method,ctx,innerFn){let runOperation=method==="tools/call"&&this.#mcpMiddlewares.length===0&&this.#mcpEventListeners.length===0?innerFn:()=>runMcpOperation(this.#mcpMiddlewares,this.#mcpEventListeners,method,ctx,innerFn);if(isUsageDisabled())return runOperation();let startedAt=performance.now(),matchedMiddleware=this.#mcpMiddlewares.filter(entry=>matchesPattern(entry.pattern,method)).length,matchedObservers=phase=>this.#mcpEventListeners.filter(entry=>entry.phase===phase&&matchesPattern(entry.pattern,method)).length,request=ctx.request?.raw,client=request===void 0?void 0:clientUsageFromBody(getRequestBag(request).parsedBody),capture2=(outcome,completedPhase)=>{recordUsage("operation","completed",{method,outcome,duration_ms:Math.max(0,Math.round(performance.now()-startedAt)),primitive_origin:this.#primitiveOrigin(method,ctx.params),matched_middleware:matchedMiddleware,observers_before:matchedObservers("before"),observers_complete:completedPhase?matchedObservers("complete"):0,...client?.protocol_era==="modern"?client:{client_name:"unknown",protocol_era:"legacy"}},{sampleRate:outcome==="success"?.1:1,serverRoot:this.#viewsProjectRoot})};return runOperation().then(result=>{let outcome=isInputRequiredResult(result)?"input_required":method==="tools/call"&&typeof result=="object"&&result!==null&&"isError"in result&&result.isError===!0?"error":"success";return capture2(outcome,!0),result},error3=>{throw capture2("error",!1),error3})}#primitiveOrigin(method,params){if(method==="tools/call"){let name=String(params.name);return this.#proxiedTools.has(name)?"proxied":this.#openApiTools.has(name)?"openapi":"local"}return method==="resources/read"?this.#proxiedResources.has(String(params.uri))?"proxied":"local":method==="prompts/get"?this.#proxiedPrompts.has(String(params.name))?"proxied":"local":"mixed"}#wrapListHandlers(server){let handlers=server.server._requestHandlers;if(handlers===void 0)return;let wrapListMethod=(method,resultKey,transform2)=>{let original=handlers.get(method);if(original===void 0||original.__mcpListWrapped)return;let wrapped=async(request,extra)=>{let serverContext=extra,params=request.params??{},mwCtx=this.#createMiddlewareContext(method,params,serverContext),originalEnvelope,innerFn=async()=>{let downstreamRequest=withMcpMiddlewareParams(request,mwCtx.params),result=await original(downstreamRequest,extra);if(typeof result!="object"||result===null)throw new TypeError(`[mcp-use] ${method} handler returned a non-object result`);originalEnvelope=result;let items=originalEnvelope[resultKey];if(!Array.isArray(items))throw new TypeError(`[mcp-use] ${method} handler result is missing a ${resultKey} array`);return items},filtered=await this.#runMcpHook(method,mwCtx,innerFn);if(!Array.isArray(filtered))throw new TypeError(`[mcp-use] ${method} middleware must return a ${resultKey} array`);let emitted=transform2?.(filtered)??filtered;return{...originalEnvelope,[resultKey]:emitted}};wrapped.__mcpListWrapped=!0,handlers.set(method,wrapped)};wrapListMethod("tools/list","tools",tools=>tools.map(tool=>{let entry=this.#tools.get(tool.name),schemes=entry!==void 0&&this.#generatesSecuritySchemes(entry)?entry.schemes:void 0;return schemes===void 0?tool:{...tool,securitySchemes:schemes}})),wrapListMethod("resources/list","resources"),wrapListMethod("prompts/list","prompts")}#registerTool(server,entry,request){let{definition,callback,schemes}=entry,view=definition.view,uiMeta=buildToolUiMeta(view?.name,definition.visibility,buildEntrypointMeta(definition)),toolMeta=this.#generatesSecuritySchemes(entry)?{...uiMeta,[SECURITY_SCHEMES_META_KEY]:schemes}:uiMeta,config2={...definition.title!==void 0&&{title:definition.title},...definition.icons!==void 0&&{icons:resolveImplementationIcons(definition.icons,request,this.#basePath())},...definition.description!==void 0&&{description:definition.description},...definition.annotations!==void 0&&{annotations:definition.annotations},...definition.outputSchema!==void 0&&{outputSchema:definition.outputSchema},...toolMeta!==void 0&&{_meta:toolMeta}},wireResultMeta=view!==void 0?buildToolResultUiMeta(view.name):void 0,inputSchema=resolveToolInputSchema(definition),invokeTool=async(args,ctx)=>{let mwCtx=this.#createMiddlewareContext("tools/call",{name:definition.name,arguments:args,...ctx.mcpReq._meta!==void 0&&{_meta:ctx.mcpReq._meta}},ctx),innerFn=async()=>{let effectiveArgs=mwCtx.params.arguments??{},result=await callback(effectiveArgs,this.#toToolRequestContext(ctx,schemes));return isInputRequiredResult(result)||wireResultMeta===void 0||result.isError===!0?result:{...result,_meta:{...result._meta,...wireResultMeta}}};return await this.#runMcpHook("tools/call",mwCtx,innerFn)};inputSchema!==void 0?server.registerTool(definition.name,{...config2,inputSchema},async(args,ctx)=>invokeTool(args,ctx)):server.registerTool(definition.name,config2,async ctx=>invokeTool({},ctx))}#registerViewResource(server,viewName,entry,metaOptions,basePath){let uri=viewResourceUri(viewName),frontendConfig=normalizeViewConfig(entry.viewConfig),authorFacts={...this.#viewResourceFacts(this.#viewBindings.get(viewName)?.config),displayModes:frontendConfig.displayModes,...frontendConfig.preferredDisplayMode!==void 0&&{preferredDisplayMode:frontendConfig.preferredDisplayMode}},resourceConfig=viewResourceConfig(viewName,entry,authorFacts,metaOptions);server.registerResource(viewName,uri,resourceConfig,async(readUri,ctx)=>{let req=ctx.http?.req,readOptions=req!==void 0?{request:req,...metaOptions.hmrWs===!0?{hmrWs:!0}:{}}:metaOptions.hmrWs===!0?{hmrWs:!0}:{},assetsBase=req!==void 0?resolveAssetsBase(req):metaOptions.request!==void 0?resolveAssetsBase(metaOptions.request):"",html2=synthesizeViewDocument(entry,assetsBase,basePath,viewName),meta2=await applyClaudeResourceDomain(buildResourceUiMeta(authorFacts,readOptions),requestClientInfo(ctx),(req??metaOptions.request)?.headers.get("user-agent"));return{contents:[{uri:readUri.href,mimeType:resourceConfig.mimeType,text:html2,_meta:meta2}]}})}#registerResource(server,{definition,callback}){server.registerResource(definition.name,definition.uri,{...definition.title!==void 0&&{title:definition.title},...definition.description!==void 0&&{description:definition.description},...definition.mimeType!==void 0&&{mimeType:definition.mimeType},...definition.annotations!==void 0&&{annotations:definition.annotations},...definition._meta!==void 0&&{_meta:{...definition._meta}}},async(uri,ctx)=>{let mwCtx=this.#createMiddlewareContext("resources/read",{uri:uri.href,...ctx.mcpReq._meta!==void 0&&{_meta:ctx.mcpReq._meta}},ctx),innerFn=async()=>toResourceResult(await callback(uri,this.#toRequestContext(ctx)),uri.href);return await this.#runMcpHook("resources/read",mwCtx,innerFn)})}#registerResourceTemplate(server,{definition,callback,complete}){let template=new ResourceTemplate(definition.uriTemplate,{list:void 0,...complete!==void 0&&{complete}});server.registerResource(definition.name,template,{...definition.title!==void 0&&{title:definition.title},...definition.description!==void 0&&{description:definition.description},...definition.mimeType!==void 0&&{mimeType:definition.mimeType},...definition.annotations!==void 0&&{annotations:definition.annotations},...definition._meta!==void 0&&{_meta:{...definition._meta}}},async(uri,variables,ctx)=>{let mwCtx=this.#createMiddlewareContext("resources/read",{uri:uri.href,...ctx.mcpReq._meta!==void 0&&{_meta:ctx.mcpReq._meta}},ctx),innerFn=async()=>toResourceResult(await callback(uri,variables,this.#toRequestContext(ctx)),uri.href);return await this.#runMcpHook("resources/read",mwCtx,innerFn)})}#viewResourceFacts(viewConfig){if(viewConfig!==void 0)return{...viewConfig.description!==void 0&&{description:viewConfig.description},...viewConfig.csp!==void 0&&{csp:viewConfig.csp},...viewConfig.permissions!==void 0&&{permissions:viewConfig.permissions},...viewConfig.domain!==void 0&&{domain:viewConfig.domain},...viewConfig.prefersBorder!==void 0&&{prefersBorder:viewConfig.prefersBorder}}}#registerPrompt(server,{definition,callback}){let config2={...definition.title!==void 0&&{title:definition.title},...definition.description!==void 0&&{description:definition.description}},invokePrompt=async(args,ctx)=>{let mwCtx=this.#createMiddlewareContext("prompts/get",{name:definition.name,arguments:args,...ctx.mcpReq._meta!==void 0&&{_meta:ctx.mcpReq._meta}},ctx),innerFn=async()=>{let effectiveArgs=mwCtx.params.arguments??{};return toPromptResult(await callback(effectiveArgs,this.#toRequestContext(ctx)))};return await this.#runMcpHook("prompts/get",mwCtx,innerFn)};if(definition.schema!==void 0)server.registerPrompt(definition.name,{...config2,argsSchema:definition.schema},async(args,ctx)=>invokePrompt(args,ctx));else{let handler=async ctx=>invokePrompt({},ctx);server.registerPrompt(definition.name,config2,handler)}}#toRequestContext(ctx){return this.#config.oauth===void 0?toRequestContext(ctx):toAuthenticatedRequestContext(ctx)}#toToolRequestContext(ctx,schemes){return this.#config.oauth===void 0||!requiresSignIn(schemes)&&ctx.http?.authInfo===void 0?toRequestContext(ctx):toAuthenticatedRequestContext(ctx)}#securitySchemeOptions(){return{hasOAuth:this.#config.oauth!==void 0,mixedAuth:this.#config.mixedAuth===!0,baselineScopes:this.#config.oauth?.requiredScopes??[]}}#resolveSecuritySchemes(definition){let options=this.#securitySchemeOptions(),schemes=resolveSecuritySchemes(definition.name,definition.securitySchemes,options),warning=handWrittenSecuritySchemesWarning(definition.name,definition,options);return warning!==void 0&&console.warn(warning),schemes}#generatesSecuritySchemes(entry){let{definition}=entry;return definition.securitySchemes!==void 0?!0:this.#config.mixedAuth===!0&&definition._meta?.[SECURITY_SCHEMES_META_KEY]===void 0}};init_fetch_app();init_dist();function text(content){return{content:[{type:"text",text:content}],_meta:{mimeType:"text/plain"}}}function markdown(content){return{content:[{type:"text",text:content}],_meta:{mimeType:"text/markdown"}}}function html(content){return{content:[{type:"text",text:content}],_meta:{mimeType:"text/html"}}}function xml(content){return{content:[{type:"text",text:content}],_meta:{mimeType:"text/xml"}}}function css(content){return{content:[{type:"text",text:content}],_meta:{mimeType:"text/css"}}}function javascript(content){return{content:[{type:"text",text:content}],_meta:{mimeType:"text/javascript"}}}function image(data,mimeType="image/png"){return{content:[{type:"image",data,mimeType}],_meta:{mimeType,isImage:!0}}}function audio(data,mimeType="audio/wav"){return{content:[{type:"audio",data,mimeType}],_meta:{mimeType,isAudio:!0}}}function binary(base64Data,mimeType){return{content:[{type:"text",text:base64Data}],_meta:{mimeType,isBinary:!0}}}function resource(uri,mimeTypeOrContent,text2){if(typeof mimeTypeOrContent=="object"&&mimeTypeOrContent!==null&&"content"in mimeTypeOrContent){let contentResult=mimeTypeOrContent,extractedText,extractedMimeType;if(contentResult._meta&&typeof contentResult._meta=="object"){let meta2=contentResult._meta;typeof meta2.mimeType=="string"&&(extractedMimeType=meta2.mimeType)}let first=contentResult.content?.[0];return first?.type==="text"&&"text"in first&&(extractedText=first.text),{content:[{type:"resource",resource:{uri,...extractedMimeType!==void 0&&{mimeType:extractedMimeType},text:extractedText??""}}]}}let mimeType=mimeTypeOrContent;return{content:[{type:"resource",resource:{uri,...mimeType!==void 0&&mimeType!==""&&{mimeType},text:text2??""}}]}}function error2(message){return{isError:!0,content:[{type:"text",text:message}]}}function object4(data){return Array.isArray(data)?array3(data):{content:[{type:"text",text:JSON.stringify(data,null,2)}],structuredContent:data,_meta:{mimeType:"application/json"}}}function array3(data){return{content:[{type:"text",text:JSON.stringify(data,null,2)}],structuredContent:data}}function widget(config2){let props=config2.props??config2.data??{},{output,message,metadata}=config2,result={content:message?[{type:"text",text:message}]:Array.isArray(output?.content)&&output.content.length>0?output.content:[{type:"text",text:""}]};return metadata!==void 0&&Object.keys(metadata).length>0&&(result._meta=metadata),output?.structuredContent!==void 0?result.structuredContent=output.structuredContent:Object.keys(props).length>0&&(result.structuredContent=props),result}function mix(...results){let withStructured=results.filter(result=>result.structuredContent!==void 0),structuredContent=withStructured.length>0?withStructured.map(result=>result.structuredContent).reduce((acc,value)=>({...acc,...typeof value=="object"&&value!==null?value:{}}),{}):void 0,withMeta=results.filter(result=>result._meta!==void 0),_meta=withMeta.length>0?withMeta.map(result=>result._meta).reduce((acc,value)=>({...acc,...value!==void 0?value:{}}),{}):void 0;return{content:results.flatMap(result=>result.content),...structuredContent!==void 0&&Object.keys(structuredContent).length>0&&{structuredContent},..._meta!==void 0&&Object.keys(_meta).length>0&&{_meta}}}export{MCPServer,SKILLS_EXTENSION_ID,acceptedContent,array3 as array,audio,binary,completable2 as completable,composeFetch,composeMiddleware,createMcpEventListenerEntry,createMcpMiddlewareEntry,createMcpMount,createRequestStateCodec,css,error2 as error,getRequestBag,hostValidationMiddleware,html,image,inputRequired,inputResponse,isInputRequiredResult,javascript,jsonBodyMiddleware,markdown,matchesPath,matchesPathPrefix,matchesPattern,mix,object4 as object,originValidationMiddleware,pathnameOf,registerSkills,registerViews,requestLogger,resource,text,widget,xml};
|
|
808
808
|
/*! Bundled license information:
|
|
809
809
|
|
|
810
810
|
@modelcontextprotocol/server/dist/src-CX2iR2pK.mjs:
|